Skip to main content

@nudojs/service

The service package provides the main programmatic API for type inference. It combines parsing, directive extraction, and evaluation to produce analysis results suitable for tooling (LSP, CLI, IDE extensions).

analyzeFile​

analyzeFile(
filePath: string,
source: string,
activeCases?: Map<string, number>,
externalCallRecords?: CallRecord[],
loadModule?: LoadModule
): AnalysisResult

Runs type inference on a file. Uses filePath for module resolution and diagnostics. activeCases maps function name → case index for diagnostics (e.g. which case is “active” in the IDE).

externalCallRecords accepts call records harvested by collectCallRecords from usage-site files (tests, examples, upstream apps). Records that resolve to functions defined in this file are matched and injected as synthesized call@L cases — see the Call-Site Discovery guide.

Functions without @nudo:case directives are not skipped: whole-program inference synthesizes a call@L case for each observed call site, or an entry@L case with any parameters when no call site is found (marked entryOnly on the FunctionAnalysis). Unconstrained entry params are any; true unknown means inference failed.

Returns: AnalysisResult


analyzeFileAsync​

analyzeFileAsync(
filePath: string,
source: string,
activeCases?: Map<string, number>,
externalCallRecords?: CallRecord[],
loadModule?: LoadModule
): Promise<AnalysisResult>

Async entry to analyzeFile: preloads path-based env files (/// @nudo:env ./nudo-harvest-node.ts) via dynamic import — impossible synchronously in ESM — then runs the sync analysis, which picks the preloaded factories up from the env-loader cache. Use it from async tooling (CLI, LSP); the sync analyzeFile degrades when the analyzed file declares path envs.

Returns: Promise<AnalysisResult>


collectCallRecords​

collectCallRecords(filePath: string, source: string): CallRecord[]

Phase 1 of call-site discovery: evaluates a usage-site file's top-level code and records every call it makes, with the real argument and result types observed at each call site. Test-framework callbacks (it, test, describe) are invoked with unknown parameters so call sites inside test bodies are captured — the test framework itself never runs. The pass produces no diagnostics and never throws: usage-site files may depend on unmocked globals, so collection is best-effort.

Pass the returned records to analyzeFile/analyzeFileAsync as externalCallRecords to have them injected as call@L cases. See Call-Site Discovery — Programmatic API for the two-phase flow.

Returns: CallRecord[] (see CallRecord)


getTypeAtPosition​

getTypeAtPosition(
filePath: string,
source: string,
line: number,
column: number,
activeCases?: Map<string, number>
): Abs | null

Returns the Abs (the lossless shape × term × pred × conf value) at the given source position (1-based line, 0-based column). Uses the active case index per function when position is inside a function with cases.

Returns: Abs or null if no type at that position.


getTypeAtPositionAsync​

getTypeAtPositionAsync(
filePath: string,
source: string,
line: number,
column: number,
activeCases?: Map<string, number>
): Promise<Abs | null>

Async entry to getTypeAtPosition with path-env preloading (see analyzeFileAsync).

Returns: Promise<Abs | null>


getCompletionsAtPosition​

getCompletionsAtPosition(
filePath: string,
source: string,
line: number,
column: number
): CompletionItem[]

Returns completion items at the given position. Supports variable completions and property/method completions after obj..

Returns: Array of CompletionItem


getCasesForFile​

getCasesForFile(filePath: string, source: string): {
functionName: string;
cases: { name: string; index: number }[];
loc: SourceLocation;
}[]

Lists all functions with @nudo:case directives and their case names/indices. Used for IDE case switching.


isNudoTargetPath​

isNudoTargetPath(path: string): boolean

Extension gate shared by the CLI collector, watch mode, and the LSP isNudoFile check. Pure path rule (the file need not exist):

PathTarget?
.js / .mjs / .ts (case-insensitive)yes
.d.ts, .tsx, .jsx, .cjs, .mts, .cts, other extensionsno
*.nudo.{js,mjs,ts} sidecarsno (contract modules, not implementation)
*.nudo.draft.{js,mjs,ts}no (draft artifacts)

shouldAnalyzeFile​

shouldAnalyzeFile(
filePath: string,
source: string | undefined,
config?: AnalysisConfig,
): boolean

Whether an automatic path (LSP validate, watch, Vite plugin) should run analysis on this buffer/file. Named-path CLI commands (nudo check src/lib.js) ignore this gate and analyze the named file.

Gate order:

  1. isNudoTargetPath — non-targets never analyze
  2. nudo.analysis.exclude / include (default exclude: node_modules / dist / coverage)
  3. package.json#nudo.analysis.mode (shipped default "exports"; DEFAULT_ANALYSIS_MODE):
    • "directives" — only files with @nudo:* directives
    • "exports" (default) — directives or export-bearing (ESM/CJS) or a same-stem *.nudo.js sidecar
    • "all" — every target path that passes include/exclude

Source of truth for defaults: PUBLIC_API.md §7. Mode semantics: Coexistence.

Related: DEFAULT_ANALYSIS_MODE (re-exported constant, "exports"), filterDiagnosticsByLevel, diagnosticsLevelForFile, sourceHasNudoDirectives.


buildSemanticTokens​

buildSemanticTokens(
filePath: string,
source: string,
opts?: { loadModule?: LoadModule; autoBind?: boolean },
): number[]

Produces LSP-encoded semantic tokens (5-tuples: deltaLine/deltaStartChar/length/tokenType/tokenModifiers) from the analysis result — function bindings typed as function, other bindings as variable, parameters as parameter. Top-level named-export function bindings also carry a contract-tier modifier (contract / generated / derived) aligned with CodeLens ● contract via contractTierOf (A7). Non-export declarations keep declaration only. The LSP server's semanticTokens handler consumes this directly.

The matching legend and encoder are exported from the same module, and the LSP package re-exports them (TOKEN_TYPES/TOKEN_MODIFIERS) so the token-type indices can never drift from the extractor:

SEMANTIC_TOKEN_TYPES: readonly string[] // ["function", "variable", "parameter", "property",
// "type", "keyword", "string", "number", "comment",
// "decorator", "method"]
SEMANTIC_TOKEN_MODIFIERS: readonly string[] // ["declaration", "readonly", "deprecated", "unreachable",
// "contract", "generated", "derived"]

type SemanticToken = {
line: number; char: number; length: number;
typeIndex: number; modifierBitmask: number;
};

encodeSemanticTokens(tokens: SemanticToken[]): number[];
contractTierModifierBit(src: "handwritten" | "generated" | "implicit"): number;

encodeSemanticTokens delta-encodes { line, char, … } tokens into the flat number[] the LSP expects — buildSemanticTokens already returns encoded output, so you only need it when building tokens yourself.


buildModuleGraph​

buildModuleGraph(
files: string[],
cache?: ModuleGraphCache,
): {
imports: Map<string, Set<string>>; // file → files it imports
dependents: Map<string, Set<string>>; // file → files importing it
}

type ModuleGraphCache = Map<string, { mtimeMs: number; size: number; edges: string[] }>;

Statically extracts each file's relative import edges — the building block for incremental analysis. Extension resolution matches module resolution ('', .js, .ts, .mjs); bare npm specifiers are skipped. Both the CLI's watch mode and the LSP's dirty propagation build a graph over their known files this way.

Pass a cache to keep per-file edges across rebuilds (the LSP session exports one as moduleGraphCache): an entry is reused when the file's mtimeMs and size are unchanged — a stat-only hit with zero disk reads and zero parsing; a miss re-reads the file and backfills the entry.


computeDirtySet​

computeDirtySet(dependents: Map<string, Set<string>>, changedFile: string): string[]

Returns the changed file plus its transitive dependents (reverse-edge BFS over dependents). Safe in the presence of import cycles.


topoSortDirty​

topoSortDirty(imports: Map<string, Set<string>>, dirty: string[]): string[]

Orders a dirty set topologically with dependencies before dependents (only import edges internal to the dirty set count; cycles are tolerated — remaining files are appended in arbitrary order). Re-analyzing in this order ensures importers see their dependencies' updated types first.

A typical incremental-analysis loop:

const graph = buildModuleGraph(files);
const dirty = computeDirtySet(graph.dependents, changedFile);
for (const file of topoSortDirty(graph.imports, dirty)) {
// re-read and re-analyze `file`
}

absToTSType​

absToTSType(a: Abs): string

Serializes an Abs to TypeScript type syntax (e.g. number, string | number, { id: number; name: string }).


generateDts​

generateDts(result: AnalysisResult): string

Generates TypeScript declaration content (.d.ts) from an analysis result. Produces declare function signatures with real parameter names, inferred return types, and JSDoc comments.


generateFunctionDtsLines​

generateFunctionDtsLines(fn: FunctionAnalysis): string[]

Per-function slice of generateDts — JSDoc plus one export declare function line. The CLI's nudo export --format dts shares this exact function with generateDts, so both paths emit byte-identical declarations. Functions without cases emit nothing (or a rest-args (...args: unknown[]) line when only combined is known); noDeclaration functions (CJS exports.X = fn) emit nothing and stay in check/test JSON output only.


absToSchemaSource​

absToSchemaSource(a: Abs, opts?: { dialect?: SchemaDialect }): string
projectAbsToSchema(a: Abs, opts?: { dialect?: SchemaDialect }): {
source: string;
dialect: SchemaDialect;
dropped: string[];
}
absToSchemaNode(a: Abs): { node: SchemaNode; dropped: string[] }

Abs → dialect schema source (one-way, lossy). Intermediate SchemaNode carries refinements from Abs preds (numeric bounds, int, string length) plus dropped notes for unprojectable preds. Default dialect is zod.

Example:

absToSchemaSource(numVar("x", gt(v("x"), lit(0))))
// → "z.number().gt(0)"

absToStandardSchema / absToStandardSchemaModule​

absToStandardSchema(a: Abs, opts?: { name?: string }): { source: string; dropped: string[] }
absToStandardSchemaModule(
exports: Record<string, Abs>,
opts?: { banner?: string },
): { source: string; dropped: string[] }
validateSchemaNode(node: SchemaNode, value: unknown): StandardSchemaResult

Abs → Standard Schema v1 runtime module source (~standard, vendor: "nudo"). Zero third-party validator dependency. validate walks the same SchemaNode refinements as schema dialect projection (bounds / int / string length). This is an ecosystem runtime path — not a replacement for nudo check.

validateSchemaNode is the testable semantic core; generated modules inline the same check.


generateGuardFunctionFromAbs​

generateGuardFunctionFromAbs(name: string, abs: Abs): string

Generates a zero-dependency runtime type guard function as a string. The generated function uses typeof, Array.isArray, and property checks for validation.

Example:

generateGuardFunctionFromAbs("isUser", obj({ name: str() }))
// → "function isUser(data) { ... }"

Case Emission​

The case-emitter functions freeze synthesized call@L cases into source text. The CLI's nudo test --freeze[=update] is a thin orchestration over them — see the CLI guide for the workflows and merge policy.

serializeCaseArg​

serializeCaseArg(a: Abs): string | null

Serializes a single Abs into expression text that the directive grammar (parseCaseArgExpr) can read back. Returns null for shapes directives cannot express: function, promise (eff), and brand values, bigint literals, non-finite / scientific-notation numbers, and strings/object keys containing structural characters or control characters.

Example:

serializeCaseArg(num()) // → "number()"
serializeCaseArg(strLit("a")) // → '"a"'

buildCaseDirective​

buildCaseDirective(name: string, argsAbs: Abs[]): string | null

Assembles one single-line directive * @nudo:case "name" (a, b) (leading *, no trailing newline) ready to be spliced into a JSDoc block. Returns null when any argument fails serialization or the name contains a quote or newline.

Example:

buildCaseDirective("call@L2", [str()])
// → ' * @nudo:case "call@L2" (string())'

stripGeneratedCaseDirectives​

stripGeneratedCaseDirectives(source: string): { source: string; removed: string[] }

Removes every generated @nudo:case directive line (name starting with the reserved call@ prefix); a JSDoc block left with no other directives or text is removed together with its /** and */ lines. Non-case directives and plain comments are never touched. removed lists the deleted case names in order. This is the first half of update mode — note that hand-written cases named call@… are stripped too, since the prefix is reserved.

insertGeneratedCaseDirectives​

insertGeneratedCaseDirectives(source: string, analysis: AnalysisResult): EmitResult

Freezes the analysis's synthesized cases (source === "callsite") into source: directives are inserted directly above each function declaration — into an existing JSDoc block after its /** line, or into a newly created block. Functions with hand-written cases or existing call@ directives are skipped (see EmitResult), as are entry-only functions; cases that fail serialization are reported per function. Returns the rewritten source alongside the written/skipped report.

unifiedDiff​

unifiedDiff(a: string, b: string, path: string): string

Line-level unified diff (--- a/path header, @@ hunks, 3 context lines) with no third-party dependency; returns "" when the texts are identical. Used by --dry-run to preview emission.

EmitResult​

type EmitSkipReason =
| "hand-written" // function has non-call@ case directives
| "already-generated" // function already has call@ directives (add mode leaves them)
| "entry-only" // no call sites found — nothing worth freezing
| "no-serializable-cases" // no case could be expressed as directive text
| "no-declaration" // CJS binding/assignment function, no stable declaration
| "skipped"; // function skipped by the analyzer itself

type EmitResult = {
source: string; // rewritten source (identical to input when nothing changed)
changed: boolean; // whether any function was written
written: Array<{ fn: string; cases: string[] }>;
skipped: Array<{ fn: string; reason: EmitSkipReason; detail?: string }>;
};

Minimal add / update flows:

import { analyzeFileAsync, insertGeneratedCaseDirectives, stripGeneratedCaseDirectives } from "@nudojs/service";

// add: insert the synthesized cases into the source as-is
const result = await analyzeFileAsync(filePath, source, undefined, records);
const emitted = insertGeneratedCaseDirectives(source, result);

// update: strip old generated directives first, re-analyze, then insert
const stripped = stripGeneratedCaseDirectives(source);
const reanalyzed = await analyzeFileAsync(filePath, stripped.source, undefined, records);
const synced = insertGeneratedCaseDirectives(stripped.source, reanalyzed);

Result Types​

AnalysisResult​

type AnalysisResult = {
functions: FunctionAnalysis[];
diagnostics: Diagnostic[];
bindings: Map<string, BindingInfo>;
nodeAbsMap: Map<Node, Abs>;
caseHints: CaseHint[];
/** functions imported from other modules, synthesized from
cross-file call sites observed while analyzing this file */
externalFunctions?: FunctionAnalysis[];
}

FunctionAnalysis​

type FunctionAnalysis = {
name: string;
loc: SourceLocation;
paramNames: string[]; // actual parameter names from AST
cases: CaseResult[];
combinedAbs?: Abs; // join of case-result Abs; source of the d.ts return type
entryOnly?: boolean; // synthesized entry@L case, no call sites found
skipped?: boolean;
/** CJS-style binding/assignment functions (exports.X = fn) have no
declaration-stable name; .d.ts generation skips them while
check/test JSON output still reports them */
noDeclaration?: boolean;
/** absolute path of the module this function is imported from
(externalFunctions only) */
fromModule?: string;
}

CaseResult​

type CaseResult = {
name: string;
argAbs: Abs[]; // lossless argument Abs
abs: Abs; // lossless result Abs
throwsAbs: Abs; // lossless thrown Abs (never when no throw)
throwLoc?: SourceLocation;
source?: "directive" | "callsite"; // "callsite" = synthesized from an observed call site;
// hand-written cases and entry@ fallbacks leave it unset
expected?: Abs; // `@nudo:case "name" (…) => expected` — presence marks a test assertion
aggregatedFrom?: number; // additional call sites folded into a symbolic case
intension?: { // intensional summary (algebra generalize)
display?: string; term?: string; pred?: string; conf?: string;
abs?: string; // lossless Abs, single line (formatAbs)
absMultiline?: string;
};
}

CallRecord​

One observed call at a usage site, harvested by collectCallRecords:

type CallRecord = {
fnName: string; // callee name observed at the call site
argAbs: Abs[]; // lossless argument Abs as observed
resultAbs: Abs; // observed result Abs (never when the call threw)
throwsAbs: Abs; // observed thrown Abs (never when no throw)
callLoc?: { line: number; column: number }; // call position; line becomes the call@L case name
targetModule?: string; // module the callee was bound from
targetExport?: string; // export name the callee was bound as
targetAliases?: string[]; // later re-export names (barrels, CJS forwarding shims)
fnModule?: string; // module whose evaluation created the function value (definition site)
}

The targetModule/targetExport/fnModule fields drive the attribution gate: a record only matches files its module actually points at, so same-named helpers in test files cannot smear their records across unrelated files. See Call-Site Discovery — Safety Design.

CaseInfo​

type CaseInfo = {
functionName: string;
caseName: string;
caseIndex: number;
}

Addresses a single case of a single function by name and index.

CaseHint​

type CaseHint = {
line: number;
label: string;
ok: boolean;
}

Inline hint (line, label, pass/fail) rendered by IDE integrations next to directives.

Diagnostic​

type Diagnostic = {
range: SourceLocation;
severity: DiagnosticSeverity; // "error" | "warning" | "info"
message: string;
tags?: DiagnosticTag[]; // e.g. ["unnecessary"]
code?: string; // e.g. "nudo:unknown-recv", "nudo:mock-invalid", "nudo-unreachable"
suggestions?: string[];
data?: unknown; // additional context for code actions
/** provenance of the receiver value (callsite argument that flowed into the error) */
origin?: { line: number; column: number };
}

DiagnosticSeverity is "error" | "warning" | "info"; DiagnosticTag is currently "unnecessary".

SourceLocation​

type SourceLocation = {
start: { line: number; column: number };
end: { line: number; column: number };
}

BindingInfo​

type BindingInfo = {
abs: Abs;
loc?: SourceLocation;
}

Type (and optional location) of a top-level binding, keyed by name in AnalysisResult.bindings.

CompletionItem​

type CompletionItem = {
label: string;
kind: "property" | "method" | "variable";
detail?: string;
}

SymbolInfo / ReferenceInfo / SymbolTable​

type SymbolInfo = {
name: string;
kind: "function" | "variable" | "class" | "parameter";
loc: SourceLocation;
uri?: string;
}

type ReferenceInfo = {
name: string;
loc: SourceLocation;
uri?: string;
}

type SymbolTable = {
definitions: Map<string, SymbolInfo>;
references: ReferenceInfo[];
}

Definitions and references for go-to-definition / find-references tooling; the LSP package builds tables of this shape over its open documents.

Export inventory​

Generated by node scripts/gen-api-docs.mjs from package export surfaces (PUBLIC_API.md / src/index.ts) — do not edit this block (or regenerate via pnpm run docs:gen). Summaries quote the source JSDoc first sentence as-is — CJK text means the symbol's doc is not yet English, and — means no JSDoc at all. Each row's name carries a stable anchor #slug (the lowercased symbol name).

Includes the @nudojs/service (src/index.ts) face and public emit faces re-exported from @nudojs/service/emit.

NameKindSummarySignature
AbsGraphOptionstype—AbsGraphOptions = { loadModule?: AbsLoadModule; seedVars?: Record<string, Abs>; seedFns?: Record<string, { params: string[]; body: Node; ...
AbsMockSeedstype—AbsMockSeeds = { seedVars: Record<string, Abs>; seedFns: Record<string, { params: string[]; body: Node; async?: boolean; fingerprint?: st...
AbsModuleCacheEntrytype会话级依赖模块缓存条目:自身 stat 指纹 + 子树内容指纹 + 导出 + 子树装载 issue。AbsModuleCacheEntry = { mtimeMs: number; size: number; contentHash: string; depFingerprints: AbsModuleDepFingerprint[]; exports: AbsModul...
AbsModuleDepFingerprinttype单条本地依赖的内容指纹:解析后稳定路径 + 求值时源码的 hashSource (与 loadModuleDepsFingerprint 同一 hash 口径,DESIGN-002 不另起第二套)。AbsModuleDepFingerprint = { path: string; hash: string; via?: { spec: string; fromFile: string }; }
AbsModuleGraphResulttype—AbsModuleGraphResult = { modules: Record<string, AbsModuleExports>; byPath: Map<string, AbsModuleExports>; issues: AbsModuleLoadIssue[]; }
AbsModuleLoadIssuetype模块装载问题分类(求值引擎是唯一上报源;analyzer 映射诊断用)AbsModuleLoadIssue = { kind: | "cycle" | "depth" | "missing" | "missing-export" | "exports-unresolved" | "unreadable" | "json-invalid"; l...
absToSchemaNodefnAbs → SchemaNode + dropped(优先 core absToConstraint;失败则 shape 尽力)absToSchemaNode( a: Abs, opts?: { scope?: SchemaProjectionScope }, )
absToSchemaSourcefn—absToSchemaSource( a: Abs, opts?: { dialect?: SchemaDialect; scope?: SchemaProjectionScope }, ): string
absToStandardSchemaFunctionfnAbs → Standard Schema v1 函数级模块源码(入参面 + 返回面)。absToStandardSchemaFunction( spec: StandardSchemaFunctionSpec, opts?: { banner?: string; scope?: SchemaProjectionScope }, ): StandardSchemaModuleProjection
absToTSTypefnAbs → TS 类型串。有损:pred / 非 lit term 落到 shape 基类型。absToTSType(a: Abs, typeVars?: Map<string, string>): string
absToZodSchemaModulefnAbs 导出表 → 可 import 的 zod JS 模块源码。absToZodSchemaModule( exports: Record<string, Abs>, opts?: { banner?: string; scope?: SchemaProjectionScope }, ): ZodModuleProjection
AlsoSynthesizeCasestype--both-paths(nudo test):对带 @nudo:case 的函数同轮也走合成路径 (call@/entry@),directive case 与合成 case 同轮同报(教学对比面)。AlsoSynthesizeCases = boolean | readonly string[]
ambientSourcesOfSidecarfnlib.nudo.{js,mjs,ts} → candidate ambient sources next to itambientSourcesOfSidecar(sidecarPath: string): string[]
ANALYSIS_ABIconst带包版本:升级 @nudojs/* 后旧 CheckJson 不得继续命中。const ANALYSIS_ABI
analysisConfigfn归一化 nudo.analysis。默认 mode=exports(A1:无指令但有 export/侧车的文件 进 IDE 分析;all / directives 需显式配置)。analysisConfig(config: NudoConfig | null | undefined): AnalysisConfig
AnalysisConfigtype—AnalysisConfig = { include: string[]; exclude: string[]; mode: AnalysisMode; diagnostics: DiagnosticsLevel; callSiteBudget: number; evalM...
analysisFileCacheKeyfn—analysisFileCacheKey( filePath: string, source: string, activeCases?: Map<string, number>, externalCallRecords?: CallRecord[], analysisCfg?: { mode: string; evalMissingSlot: string; callSiteBudget: number; diagnostics: string; maxForks?: number; }, loadModule?: AnalyzeLoadModule, projectEnvNames?: string[], autoBind?: boolean, caseMode: DirectiveCaseMode = "all", alsoSynthesizeCases?: AlsoSynthesizeCases, )
AnalysisModetype—AnalysisMode = "directives" | "exports" | "all"
AnalysisResulttype—AnalysisResult = { functions: FunctionAnalysis[]; diagnostics: Diagnostic[]; bindings: Map<string, BindingInfo>; nodeAbsMap: Map<Node, Ab...
AnalysisSessiontype—AnalysisSession = { evictForDependents(files: string[]): void; clear(): void; reset(): void; analyze( filePath: string, source: string, a...
analyzeExportsFromSourcefn分析单文件导出 + 内涵签名(source 由 host 提供)analyzeExportsFromSource( filePath: string, source: string, ): ModuleExports
analyzeFilefn整文件分析。同 (path, source, cases, external) 命中 memo → O(1)。analyzeFile( filePath: string, source: string, activeCases?: Map<string, number>, externalCallRecords?: CallRecord[], loadModule?: AnalyzeLoadModule, caseMode: DirectiveCaseMode = "all", alsoSynthesizeCases?: AlsoSynthesizeCases, ): AnalysisResult
analyzeFileAsyncfnAsync entry to analyzeFile: preloads path-based env files (/// @nudo:env ./nudo-harvest-node.ts) via dynamic import — impossible synchronously in ESM — then runs the sync analysis, which picks the preloaded factories up from the env-loader cache.analyzeFileAsync( filePath: string, source: string, activeCases?: Map<string, number>, externalCallRecords?: CallRecord[], loadModule?: AnalyzeLoadModule, caseMode: DirectiveCaseMode = "all", alsoSynthesizeCases?: AlsoSynthesizeCases, ): Promise<AnalysisResult>
analyzeFileAsyncWithEvalFailuresfn{@link analyzeFileAsync} 的观测面版本(1145):env 预载 + 同步分析 + 按文件的引擎内部回落观测。analyzeFileAsyncWithEvalFailures( filePath: string, source: string, activeCases?: Map<string, number>, externalCallRecords?: CallRecord[], loadModule?: AnalyzeLoadModule, caseMode: DirectiveCaseMode = "all", alsoSynthesizeCases?: AlsoSynthesizeCases, ): Promise<{ analysis: AnalysisResult; evalFailures: FileEvalFailure[] }>
analyzeFileWithEvalFailuresfn分析一个文件 + 观测该文件的引擎内部回落(1145 观测面)。analyzeFileWithEvalFailures( filePath: string, source: string, activeCases?: Map<string, number>, externalCallRecords?: CallRecord[], loadModule?: AnalyzeLoadModule, caseMode: DirectiveCaseMode = "all", alsoSynthesizeCases?: AlsoSynthesizeCases, )
applyBForkBudgetFromConfigfn把 fork 预算写进 core(core 保持无 IO)。applyBForkBudgetFromConfig( config: NudoConfig | null | undefined, env: NodeJS.ProcessEnv = process.env, ): number
applyMockModuleDirectivesfnOverlay @nudo:mock-module directives onto a modules map.applyMockModuleDirectives( base: Record<string, AbsModuleExports>, fileDirectives: FileDirective[], opts: { fromFile: string; loadModule?: LoadModule }, ): MockModuleApplyResult
applyMockModuleDirectivesFromSourcefnSource string → apply mock-module (CLI / one-shot hosts).applyMockModuleDirectivesFromSource( source: string, base: Record<string, AbsModuleExports>, opts: { fromFile: string; loadModule?: LoadModule }, ): MockModuleApplyResult
applySessionCacheConfigfn接线 package.json#nudo.sessionCache(进程内 LRU 上限)并立刻 trim。applySessionCacheConfig(config: NudoConfig | null | undefined): SessionCacheLimits
applyTextEditsfn把 edits 应用到源码(按 start 从后往前)applyTextEdits(source: string, edits: TextEdit[]): string
BindingInfotype—BindingInfo = { abs: Abs; loc?: SourceLocation; }
blankGeneratedCaseDirectivesfn供分析使用的源码视图:把生成态 call@ case 指令抹成空注释行(行数 不变)。BUG-076:混合块(手写 case + 生成见证)不参与剥离,但分析若仍把 旧见证当 directive case 读到,就不再合成当前调用点证据 ⇒ 陈旧见证永远 不刷新。写盘基源仍用 stripGeneratedCaseDirectives 的结果(手写块原样)。blankGeneratedCaseDirectives(source: string): string
BodyReadFieldtype—BodyReadField = { field: string; type: string; via: string; fields?: BodyReadField[]; }
BodyReadTypestype—BodyReadTypes = Map<string, Map<string, BodyReadField[]>>
buildCaseDirectivefn组装单行 * @nudo:case "name" (a, b) 指令文本(无尾换行)。buildCaseDirective(name: string, argsAbs: Abs[]): string | null
buildEvalInjectionfn—buildEvalInjection( filePath: string, source: string, allEnvNames: string[], dirDiags: DirectiveDiag[], parseAst: (filePath: string, source: string) => ReturnType<typeof parse>, )
buildModuleGraphfnStatically extract each file's relative import edges (extension resolution identical to CLI resolveModule: ''/'.js'/'.ts'/'.mjs'; bare npm specifiers skipped).buildModuleGraph( files: string[], cache?: ModuleGraphCache, )
buildTestReportfn汇总一份 case 报告的断言结果(+ 逐函数展示行)。buildTestReport( file: string, result: AnalysisResult, opts: TestReportOptions = {}, ): TestReport
CallRecordtype——
CallsiteRecordstype采集结果:记录 + 路径错误(两者必须分开呈现)。CallsiteRecords = { records: CallRecord[]; errors: Array<{ path: string; message: string }>; }
caseExpectedSatisfiedfn实际值是否满足期望(结构面 leqAbs + 对象槽字面量严格面 + 值面谓词)。caseExpectedSatisfied(actual: Abs, expected: Abs): boolean
CaseHinttype—CaseHint = { line: number; label: string; ok: boolean; }
CaseJsontype—CaseJson = { version: 1; file: string; summary: { functions: number; externalFunctions: number; cases: number; diagnostics: number; }; fu...
CaseJsonCasetype—CaseJsonCase = { name: string; args: string[]; result: string; throws: string | null; source: string | null; aggregatedFrom?: number; arg...
CaseJsonFunctiontype—CaseJsonFunction = { name: string; loc: SourceLocation; entryOnly: boolean; noDeclaration?: boolean; cases: CaseJsonCase[]; combined?: st...
CaseResulttype—CaseResult = { name: string; argAbs: Abs[]; abs: Abs; throwsAbs: Abs; throwLoc?: SourceLocation; source?: "directive" | "callsite"; expec...
CaseTestOutcometype—CaseTestOutcome = { fn: string; caseName: string; ok: boolean; unchecked: boolean; uncheckedReason?: "no-expectation" | "inference-failed...
checkCacheKeyfncheck 报告键:abi + 相对路径 + 源码 sha + autoBind + 侧车 sha + @nudo:import / 传递契约依赖内容 sha(依赖变更必须 miss)。checkCacheKey( filePath: string, source: string, opts: { autoBind: boolean; projectDir?: string; sidecarContent?: string | null; depContents?: Array<{ path: string; content: string | null }>; projectEnvNames?: string[]; analysisCfg?: { mode?: string; evalMissingSlot?: string; callSiteBudget?: number; entryThrows?: string; ignoreThrows?: string; maxForks?: number; }; }, ): string
checkConfigfnpackage.json#nudo 键 → 执法选项checkConfig(config: NudoConfig | null | undefined): CheckConfig
CheckConfigtype—CheckConfig = { entryThrows: "error" | "warning" | "off"; ignoreThrows: string[]; }
CheckSupplementOptionstype补充诊断通道的采集选项。CheckSupplementOptions = { modules?: Record<string, unknown>; loadModule?: LoadModule; }
clearAbsModuleCachefn—clearAbsModuleCache(): void
clearAnalysisFileCachefn—clearAnalysisFileCache(): void
clearAnalysisSessionCachesfn清空全部会话级分析缓存(service + core)。clearAnalysisSessionCaches(): void
clearEnvPathDepsfn—clearEnvPathDeps(): void
clearEvalCachefn—clearEvalCache(): void
clearFnAnalysisCachefn—clearFnAnalysisCache(): void
clearPathEnvCachesfnHost cache-clear hooks (CLI watch / vite / tests) must drop path-env modules tooclearPathEnvCaches(): void
collectAbsBindingsFromGraphfn收集顶层绑定名 → Abs(含相对 import / 裸包 harvest 注入)。collectAbsBindingsFromGraph( source: string, filePath: string, opts: AbsGraphOptions = {}, ): Map<string, Abs>
collectCallRecordsfn调用点发现(阶段一):在"使用现场"文件(测试 / 上层应用)中求值 顶层代码,收集它对(外部模块导出的)函数的调用记录。每条记录带 真实的实参类型与结果类型——后续 analyzeFile 将其注入合成 case, 使被使用方从 entry-only(参数全 unknown)升级为真实调用形态。collectCallRecords(filePath: string, source: string): CallSiteRecord[]
collectCallsiteRecordsfn采集使用点记录(--from 等价通道)。collectCallsiteRecords(sites: string[]): CallsiteRecords
collectCheckSupplementIssuesfn采集三条补充诊断通道(指令文法 / mock 装载 / env 未解析)→ CheckIssue[]。collectCheckSupplementIssues( filePath: string, source: string, opts: CheckSupplementOptions = {}, ): CheckIssue[]
collectDependencySpecsconst——
collectEnvGlobalsfn—collectEnvGlobals(envNames: string[]): Record<string, Abs>
collectEnvModulesfnBug 282:env 模块是 CJS 互操作模块——Node 的 node:fs 的默认导出就是 模块对象本身(具名导出挂在它上面)⇒ ESM 默认导入 (import fs from "node:fs")必须绑到命名空间。collectEnvModules(envNames: string[]): Record<string, AbsModuleExports>
collectEnvNamesfn—collectEnvNames(filePath: string, source: string, includeProject: boolean): string[]
collectEvalDiagnosticsfn静态收集 求值引擎诊断。collectEvalDiagnostics( source: string, extraKnown?: Iterable<string>, filename?: string, ): EvalDiagnostics
collectEvalReplacementsfn收集 @nudo:replace + @nudo:as → transpile 注入表。collectEvalReplacements( source: string, opts?: { diags?: DirectiveDiag[] }, ): EvalReplacements
collectLoadDepContentsfn—collectLoadDepContents( filePath: string, source: string, loadModule: (spec: string, fromFile: string) => string | undefined, )
collectMissingExportIssuesfnnamed import / re-export 缺名 → missing-export issue。collectMissingExportIssues( source: string, modules: Record<string, AbsModuleExports>, fromFile: string, ): AbsModuleLoadIssue[]
collectParamBodyReadTypesfn收集每个函数形参成员读取 + 用法推断类型。collectParamBodyReadTypes(source: string): BodyReadTypes
collectParamContractsfn收集每个函数形参的契约证据(quickfix 侧车发射面): 数组方法接收者读 → array(元素契约)(元素 shape 由回调元素位 成员读合成);纯成员读 → shape(…);参数本体标量用法 → 叶子 DSL (number() 等)。无证据参数不进表(契约留 any 位)。collectParamContracts(source: string): ParamContracts
collectSkipReturnsfn每个带 @nudo:skip 的顶层函数 → 声明的返回 Abs;null = 未声明返回类型。collectSkipReturns(source: string): Map<string, Abs | null>
collectStaticImportsfn从入口文件沿静态相对 import/require 收集(仅类型事实,不是运行时加载器)。collectStaticImports( entryFile: string, maxDepth = 8, ): Map<string, ModuleExports>
compileAnyMatcherfnCompile a pattern list into a matcher that is true when any pattern matches.compileAnyMatcher(patterns: string[] | string): Matcher
compilePatternfn单模式编译:无通配符(* / ?)→ 字面量子串匹配;有 → 锚定正则。compilePattern(pattern: string): Matcher
CompletionItemtype—CompletionItem = { label: string; kind: "property" | "method" | "variable" | "function"; detail?: string; }
ComposedEvalModulestype模块图组装的共享产物:analyzer 与 tryRunEval 走同一序列 (evalAbsModuleGraph → collectEnvModules → mergeHarvestUnderEnv → applyMockModule*),单一事实源,不再各自漂移。ComposedEvalModules = { modules: Record<string, AbsModuleExports>; issues: AbsModuleLoadIssue[]; mockErrors: string[]; mockModuleErrors: ...
composeEvalModulesfn模块图组装单一入口:相对/harvest 模块图 → @nudo:env modules 并入 (手写 env wins,B8)→ @nudo:mock-module 覆盖。composeEvalModules( source: string, filePath: string, opts: { envNames?: string[]; seedVars?: Record<string, Abs>; seedFns?: AbsGraphOptions["seedFns"]; loadModule?: LoadModule; fileDirectives?: FileDirective[]; } = {}, ): ComposedEvalModules
computeDirtySetfnchanged plus its transitive dependents (reverse-edge BFS); cycle-safe via visited.computeDirtySet(dependents: Map<string, Set<string>>, changedFile: string): string[]
configIgnoreThrowsfnpackage.json#nudo.check.ignoreThrows 的原始值 → 与 CLI 同口径的列表 (679:配置面复用本解析器,不再走各面自己的严格 string[] 过滤—— 裸字符串 "TypeError" 曾被静默丢成空表 ⇒ 门禁假红)。configIgnoreThrows( config: { check?: unknown } | null | undefined, ): string[]
ConstraintSourceExprtype—ConstraintSourceExpr = { expr: string; importFrom?: string; importName?: string; }
contractCacheKeyfneffectiveContract 表键(L1 Phase B,design-persistent-cache)。contractCacheKey( filePath: string, source: string, opts: { autoBind: boolean; projectDir?: string; sidecarSource?: string | undefined; depContents?: Array<{ path: string; content: string | null }>; projectEnvNames?: string[]; }, ): string
contractConfigfn归一化 nudo.contract 配置段。contractConfig(config: NudoConfig | null | undefined): ContractConfig
ContractConfigtype—ContractConfig = { autoBind: boolean; emit: string[]; }
ContractDraftEntrytype—ContractDraftEntry = { fn: string; identity?: string; params: Array<{ name: string; constraint?: NudoConstraint; display: string; project...
ContractDraftOptstype—ContractDraftOpts = { fnNames?: string[]; records?: CallRecord[]; loadModule?: LoadModule; autoBind?: boolean; bodyAccesses?: boolean; so...
ContractDraftResulttype—ContractDraftResult = { file: string; entries: ContractDraftEntry[]; draftSource: string; sidecarPath: string; }
contractDslOffn契约证据 → constraint-builder DSL 文本(array(shape({ … })) 等)contractDslOf(ev: ParamContractEvidence): string
contractSurfacefn单文件 contract 表面:analyzer 推断结果给出函数清单与 implicit 展示, effectiveContract 给出契约命中(手写 > 生成段)。contractSurface( filePath: string, opts: ContractSurfaceOpts = {}, ): Promise<ContractSurfaceEntry[]>
ContractSurfaceEntrytype—ContractSurfaceEntry = { fn: string; identity?: string; kind: "export" | "local"; source: "handwritten" | "generated" | "implicit"; param...
ContractSurfaceOptstype—ContractSurfaceOpts = { autoBind?: boolean; loadModule?: LoadModule; records?: CallRecord[]; source?: string; diagnostics?: ContractFaceD...
currentBForkBudgetLimitfn当前生效 fork 上限(调试/测试;与 core getEvalForkBudgetLimit 同源)currentBForkBudgetLimit(): number
DEFAULT_ANALYSIS_MODEconst", ]; /** A1 产品默认:exports — 普通带导出的 .js 进 IDE;directives/all 需显式const DEFAULT_ANALYSIS_MODE
DEFAULT_SESSION_CACHE_LIMITSconst保守默认:多项目共存时不悄悄吃内存(大仓请显式调高)const DEFAULT_SESSION_CACHE_LIMITS
defaultAbsLoadModulefn相对说明符 → 源码(与 defaultLoadModule 同一扩展名/入口候选表)defaultAbsLoadModule(spec: string, fromFile: string): string | undefined
defaultLoadModulefn默认 loadModule:相对/绝对说明符 → 源码。defaultLoadModule( spec: string, fromFile: string, mode?: ModuleLoadMode, ): string | undefined
DepContenttype—DepContent = { path: string; content: string | null }
DerivedExporttype—DerivedExport = { file: string; fn: string; paramNames: string[]; params: DerivedParam[]; returns?: { constraint: NudoConstraint; dsl: st...
DerivedParamtype—DerivedParam = { name: string; constraint: NudoConstraint; dsl: string; prelude: string[]; imports: Array<{ name: string; from: string }>...
deriveFromRootfn入口:对 filePath 做 root 驱动下行推导。deriveFromRoot( filePath: string, opts: RootDeriveOpts = {}, ): RootDeriveResult
detectEntryVariantsFromPackageJsonfnDetect browser/node dual faces in a parsed package.json.detectEntryVariantsFromPackageJson(pkg: unknown): EntryVariantFaces | null
Diagnostictype—Diagnostic = { range: SourceLocation; severity: DiagnosticSeverity; message: string; tags?: DiagnosticTag[]; code?: string; suggestions?:...
DiagnosticSeveritytype—DiagnosticSeverity = "error" | "warning" | "info"
DiagnosticsLeveltype—DiagnosticsLevel = "off" | "errors" | "default" | "verbose"
diagnosticsLevelForFilefn—diagnosticsLevelForFile(filePath: string): DiagnosticsLevel
DiagnosticTagtype—DiagnosticTag = "unnecessary"
DirectiveCaseModetype@nudo:case 求值档: - none(默认):不跑 case;有 case 的函数也走 entry@ 出签名(check / IDE) - all:逐 case 真跑(nudo test / CaseJson / freeze) - selected:只跑 activeCases 选中的那条(LSP selectCase)DirectiveCaseMode = "none" | "all" | "selected"
directiveDiagIssuesfnD1: 指令文法诊断(nudo:directive-syntax)→ CheckIssue(warning,不挡 exit)。directiveDiagIssues( diags: Array<{ code: string; message: string; at?: { line: number; column: number }; }>, ): CheckIssue[]
DiskCachefn—DiskCache { private readonly root: string | undefined; private readonly ns: string; private readonly keyMat: Buffer | undefined; enabled ...
DiskCacheOptionstype—DiskCacheOptions = { root?: string | undefined; namespace: string; signKey?: string; }
diskCacheRootfn磁盘缓存根(B3):config.cache / NUDO_CACHE_DIR / 默认关。diskCacheRoot( config: NudoConfig | null | undefined, projectDir: string | undefined, ): string | undefined
DiskCacheSignErrorfnnudo.cache.sign 配置错误(sign: true 但 NUDO_CACHE_KEY 缺席/空, 或 sign 取值形状非法)。签名是安全旋钮 ⇒ 拒绝运行(CLI 面显式报错 退出),不静默降级到未签名缓存。DiskCacheSignError extends Error { constructor(message: string) { super(message); this.name = "DiskCacheSignError"; } }
diskCacheSignStatefn—diskCacheSignState( config: NudoConfig | null | undefined, env: NodeJS.ProcessEnv = process.env, ): DiskCacheSignState
DiskCacheSignStatetype磁盘缓存条目签名状态(B3 信任面): - { kind: "off" }:未开签名(默认)——旧未签名行为原样 - { kind: "on", key }:签名开 + NUDO_CACHE_KEY 就绪(key = 原始密钥串, HMAC 密钥材料派生见 disk-cache.ts) - { kind: "error", message }:配置错误——sign: true 但密钥缺席/空。DiskCacheSignState = | { kind: "off" } | { kind: "on"; key: string } | { kind: "error"; message: string }
domainEvidenceCasesfn产物面(dts / zod / standard / guard)的域证据 case。domainEvidenceCases(cases: readonly CaseResult[]): CaseResult[]
draftContractfn为单文件顶层导出生成 contract 草稿(不写盘)。draftContract( filePath: string, opts: ContractDraftOpts = {}, ): Promise<ContractDraftResult>
DraftEvidencetypeDraftEvidence body = 仅来自函数体对形参的成员读取(草稿建议,非义务)。DraftEvidence = "callsite" | "directive" | "symbolic" | "body" | "none"
DtsClassSurfacetype类声明面(成员面 + 导出形态)DtsClassSurface extends DtsClassMemberSurface { exportName?: string; exportNames?: string[]; isDefault: boolean; }
DtsContractFacetype契约面证据(export CLI 从 effectiveContract 取——与 check 签名面同数据源: sidecar(*.nudo.js)∪ inline @nudo:contract)。DtsContractFace { params: Array<{ name: string; abs: Abs; optional?: boolean; display?: string }>; return?: Abs; returnDisplay?: string; }
DtsFunctionProjectiontypeprojectFunctionDts 的返回面:声明行 + 主签名参数位(unknown = 无证据)DtsFunctionProjection { lines: string[]; params: Array<{ name: string; type: string }>; exportName?: string; classMember?: { className: s...
DtsModuleExtrastype模块面合成的分析面补充证据(函数入口之外的事实:模块级绑定 Abs)。DtsModuleExtras { values?: ReadonlyMap<string, Abs>; }
DtsModuleProjectiontype模块面 dts 投影结果DtsModuleProjection { lines: string[]; params: Array<{ name: string; type: string }>; }
dtsModuleSurfacefn模块导出面扫描(源文件 → 导出名表 + 类面 + 再导出语句)。dtsModuleSurface(source: string): DtsModuleSurface
DtsModuleSurfacetype模块导出面(源文件的导出面:导出名 → 本地绑定 + 类面 + 再导出 + 导入面)DtsModuleSurface { exportBindings: Map<string, string>; reexports: string[]; classes: Map<string, DtsClassSurface>; imports?: Map<string,...
DtsValueSurfacetype模块级值声明面(BUG-190):export const/let/var 与 TS enum。DtsValueSurface { kind: "const" | "let" | "var" | "enum"; enumMembers?: Array<{ name: string; init?: string }>; constEnum?: boolean; type...
emitContractfn单文件 emit:分析 → 逐目标投影/自检 → 组装侧车内容 →(非 dryRun)写盘。emitContract( filePath: string, opts: EmitContractOpts, ): Promise<EmitContractResult>
EmitContractOptstype—EmitContractOpts = { fnNames?: string[]; mode: "add" | "update"; all?: boolean; dryRun?: boolean; records?: CallRecord[]; source?: string...
EmitContractResulttype—EmitContractResult = { written: string[]; skipped: Array<{ fn: string; reason: EmitContractSkipReason }>; changed: boolean; diff?: string...
EmitContractSkipReasontype—EmitContractSkipReason = | "name-clash" | "not-projectable" | "not-an-export" | "no-change" | "emit-denied" | "multi-declarator" | "expor...
emitDerivedFromRootfn—emitDerivedFromRoot( rootFile: string, opts: { fnNames?: string[]; mode: "add" | "update"; dryRun?: boolean; loadModule?: LoadModule; autoBind?: boolean; refreshExistingOnly?: boolean; baseContent?: (sidecarPath: string) => string | undefined; skipWrite?: string[]; directSections?: Set<string>; directCreatedSections?: Set<string>; }, ): EmitDerivedResult
EmitDerivedResulttype—EmitDerivedResult = { sidecars: Array<{ file: string; sidecarPath: string; fn: string; written: boolean; writtenNames?: string[]; changed...
EmitResulttype—EmitResult = { source: string; changed: boolean; written: Array<{ fn: string; cases: string[] }>; skipped: Array<{ fn: string; reason: Em...
EmitSkipReasontype—EmitSkipReason = | "hand-written" | "already-generated" | "entry-only" | "no-serializable-cases" | "no-declaration" | "contract-violation...
ENTRY_CONTRACT_NOTEconstentry@ 回退 case × 有效契约的注解行:解释「check 全绿但 test 打 (any) => any throws」的表面矛盾——entry@ 用的是无约束入口 face, 契约作用于 check/export 面;要看到受约束的 case 就加 @nudo:case 或提供调用点。throws 显示保留(那是无约束 face 的诚实结果)。const ENTRY_CONTRACT_NOTE
EntryVariantFaceGrouptypeOne browser/node face pair, scoped to a subpath or field source.EntryVariantFaceGroup = { key: string; browser: string[]; node: string[]; }
EntryVariantFacestype—EntryVariantFaces = { kind: "exports-conditions" | "browser-field"; groups: Map<string, EntryVariantFaceGroup>; }
entryVariantForFilefnDual-entry info for an analyzed file: the owning package must declare a dual group (browser + node faces resolving to different files in the same subpath / field source) and this file must be one of that group's entry targets on exactly one face.entryVariantForFile(filePath: string): EntryVariantInfo | null
EntryVariantInfotype—EntryVariantInfo = { pkgPath: string; pkgDir: string; pkgName?: string; kind: "exports-conditions" | "browser-field"; browserPaths: strin...
EntryVariantIssuetypeHost-facing info issue (CLI check / JSON) for one analyzed entry variant.EntryVariantIssue = { severity: "info"; code: typeof DIAG.dualEntry; message: string; suggestion: string; line: number; column: number; }
entryVariantIssueForFilefn—entryVariantIssueForFile(filePath: string): EntryVariantIssue | null
ENV_UNRESOLVED_CODEconstpath env 加载失败告警码(live 瞬态:每轮 preloadPathEnvs 现场收集)。const ENV_UNRESOLVED_CODE
EnvHarvestConflicttypeConflict when handwritten env overwrote a harvest module/export (B8).EnvHarvestConflict = { module: string; exports: string[]; defaultOverwritten: boolean; }
envPathDependentsfn依赖该 env 模板的源文件列表envPathDependents(envPath: string): string[]
envUnresolvedIssuesfnpath env 未解析 → CheckIssue(warning)。envUnresolvedIssues( filePath: string, source: string, baseDir = dirname(filePath), ): CheckIssue[]
evalAbsModuleGraphfn递归求值相对依赖 + 裸包 harvest,产出入口可用的 modules 表。evalAbsModuleGraph( entrySource: string, entryFile: string, opts: AbsGraphOptions = {}, ): AbsModuleGraphResult
EvalBuiltinUnknowntype—EvalBuiltinUnknown = { name: string; range: EvalLoc }
EvalDiagnosticstype—EvalDiagnostics = { unreachable: EvalUnreachable[]; builtinUnknown: EvalBuiltinUnknown[]; capabilityDenied: EvalBuiltinUnknown[]; deniedM...
EvalRunResulttype—EvalRunResult = { exports: Record<string, unknown>; modules: Record<string, AbsModuleExports>; memberDiags?: EvalMemberDiag[]; moduleIssu...
EvalUnreachabletype—EvalUnreachable = { range: EvalLoc }
evictAbsModuleCacheFilesfn键身份统一 stablePathKey(FIX-RESIDUAL-4):跨盘符形态删除/命中一致evictAbsModuleCacheFiles(paths: string[]): void
evictAnalysisCachesForFilesfn依赖内容变更后:按入口文件定向逐出 service 层缓存。evictAnalysisCachesForFiles(files: string[]): void
evictAnalysisFileCacheForFilesfn依赖变更后:按入口文件逐出(查找与写入同走 stablePathKey)evictAnalysisFileCacheForFiles(files: string[]): number
evictEvalCacheForFilesfn依赖文件变更后:逐出以这些文件为入口的 evaluator 缓存(键走 stablePathKey;两种 mode 槽一并清)evictEvalCacheForFiles(files: string[]): number
evictFnAnalysisCacheForFilesfnDependency content changed: drop every per-fn entry for these entry files.evictFnAnalysisCacheForFiles(files: string[]): number
evictProjectConfigMemofn清空 findProjectConfig 目录链 memo(项目配置 watch 通道 / 测试隔离)。evictProjectConfigMemo(): void
extractNudoImportSpecsfn从源码提取 @nudo:import / @nudo:import * as 的 specifierextractNudoImportSpecs(source: string): string[]
FileEvalFailuretype——
filterDiagnosticsByLevelfn按 analysis.diagnostics 档过滤 evaluator/check 显示路径诊断。filterDiagnosticsByLevel<T extends { severity: string; code?: string }>( diags: T[], level: DiagnosticsLevel, ): T[]
findOwningPackagefnNearest package.json walking up from the file's directory.findOwningPackage( fromFile: string, )
findProjectConfigfn—findProjectConfig( startDir: string, )
formatContractSurfaceLinefn单条 contract 打印行(CLI runContract 与 LSP agent 面共用)formatContractSurfaceLine(e: ContractSurfaceEntry): string
formatDerivedSectionfn组装生成段(组合式 + import + prelude)。formatDerivedSection( row: DerivedExport, opts: { rootSidecarDir: string; targetSidecarDir: string; takenNames?: Iterable<string>; }, )
formatDraftModulefn草稿模块文本(人读 + 可复制到 *.nudo.js / *.nudo.ts)formatDraftModule( filePath: string, entries: ContractDraftEntry[], sidecarPath?: string, throwsHints?: readonly string[], ): string
formatDraftSummaryfn—formatDraftSummary( sourceRel: string, draftRel: string, result: ContractDraftResult, write?: WriteDraftResult, ): string[]
formatEmitSummaryfnemit 摘要行(CLI runContractEmit 与 LSP agent 面共用;路径由调用方按 展示口径传入——CLI 传 cwd 相对、agent 传绝对路径)。formatEmitSummary( sourcePath: string, sidecarRel: string, result: EmitContractResult, ): string[]
formatExpectedfn期望值的可读文本(带谓词):number (> 0) / { n: number (> 0) }。formatExpected(expected: Abs): string
formatPathErrorTextfn路径错误的非 JSON 面文案(CLI 的 usage error 面同口径): 一行原因 + 一行 fix: 提示。formatPathErrorText(errors: PathError[]): string
formatTestReportfn—formatTestReport(r: TestReport): string
FunctionAnalysistype—FunctionAnalysis = { name: string; loc: SourceLocation; paramNames: string[]; formals?: FormalParam[]; declaredReturnType?: string; thisR...
generateDtsfn—generateDts(result: AnalysisResult): string
generateFunctionDtsLinesfn—generateFunctionDtsLines( fn: FunctionAnalysis, contract?: DtsContractFace, ): string[]
generateGuardFunctionFromAbsfn守卫源码:export function <name>(value: unknown): boolean { … }。generateGuardFunctionFromAbs(name: string, abs: Abs, used?: Set<string>): string
getAbsModuleCacheSizefn测试/诊断:当前条目数(≤ ABS_MODULE_CACHE_MAX)getAbsModuleCacheSize(): number
getAnalysisFileCacheSizefn—getAnalysisFileCacheSize(): number
getAnalysisSessionfn进程内默认 AnalysisSession(LSP server / CLI watch / agent tools 共用)getAnalysisSession(): AnalysisSession
getEnvHarvestConflictCollectorfnRead-only peek for tests / nested restore.getEnvHarvestConflictCollector()
getEnvPathDepsSizefn测试/诊断:反向依赖驻留规模getEnvPathDepsSize(): number
getEvalCacheSizefn测试/诊断:当前 evaluator run 缓存条目数(≤ getSessionCacheLimits().maxEvalRuns)getEvalCacheSize(): number
getFnAnalysisCacheSizefn测试/诊断:当前条目数(≤ getSessionCacheLimits().maxFns)getFnAnalysisCacheSize(): number
getPathEnvCacheSizesfn测试/诊断:path-env 驻留规模(均 ≤ 对应上限)getPathEnvCacheSizes()
getPathEnvDepContentsfn已成功预载的 path env 文件(供 check 磁盘缓存指纹纳入 sha)。getPathEnvDepContents(baseDir?: string): Array<{ path: string; content: string | null }>
getPathEnvLoadErrorsfnpath env 加载失败诊断(check/test 打印 nudo:env-unresolved warning 用)。getPathEnvLoadErrors(baseDir?: string): Array<{ path: string; error: string; baseDir: string }>
getSessionCacheLimitsfn—getSessionCacheLimits( env: NodeJS.ProcessEnv = process.env, ): SessionCacheLimits
inferenceFailedfnBug 950 第三态:引擎未能推断实测值(⇒ 无法判定,不是「不匹配」)。inferenceFailed(actual: Abs): boolean
injectBindingsfn—injectBindings( source: string, bindings: TypeBinding[], )
InsertCaseOptionstype固化写回的宿主接线(BUG-055 / BUG-119)——全部可选: 缺省时行为与改前逐字一致(只认源码内指令契约、add 模式的整函数跳过)。InsertCaseOptions = { filePath?: string; loadModule?: (spec: string, fromFile: string) => string | undefined; autoBind?: boolean; project...
insertGeneratedCaseDirectivesfn把 analysis 中的合成 case(source === "callsite")固化为源码指令: 1.insertGeneratedCaseDirectives( source: string, analysis: AnalysisResult, opts: InsertCaseOptions = {}, ): EmitResult
isEnvTemplatePathfnwatch 门禁:env 模板变更必须可被接收(即便扩展名不进 isNudoTargetPath)isEnvTemplatePath(path: string): boolean
isNudoTargetPathfnnudo 推断目标文件判定(纯扩展名规则,路径无需存在)。isNudoTargetPath(path: string): boolean
isProjectConfigPathfn—isProjectConfigPath(path: string): boolean
isRuntimeGlobalCtorNamefnbrand 名能否用 z.instanceof(<name>) 表达(须是运行时全局构造器名)。isRuntimeGlobalCtorName(name: string): boolean
isSidecarPathfnFormal sidecar contracts only — drafts never ambient-bind and need not reanalyzeisSidecarPath(path: string): boolean
isWatchRelevantPathfnWatch accept gate: analysis targets + sidecar/config/env-template invalidatorsisWatchRelevantPath(path: string): boolean
LoadModuletype—LoadModule = (spec: string, fromFile: string) => string | undefined
locFromNodefn—locFromNode(node: Node): SourceLocation
Matchertype极简 glob → RegExp 编译器(自 vite-plugin 内联实现抽取,语义不变)。Matcher = (id: string) => boolean
matchesEmitAllowlistfn极简 glob(** / * / ?):相对 projectDir 匹配源文件绝对路径 (不是侧车路径;侧车随源文件同目录写出)。无白名单 → true。matchesEmitAllowlist( absPath: string, projectDir: string | undefined, patterns: string[], ): boolean
matchSidecarFnDeclfn定位侧车里目标契约的声明起点:export const <name> = fn( / <name> = fn(。matchSidecarFnDecl( sidecarSource: string, exportName: string, )
materializeActionfnkind → WorkspaceEdit 物化。返回 undefined = 该 action 只读(info)或缺证据。materializeAction(input: MaterializeInput): QuickfixPlan | undefined
MaterializeInputtype—MaterializeInput = { code: string; fn?: string; file: string; source: string; sidecarText?: string; sidecarPath: string; action: CheckAct...
mergeCheckIssuesfn追加 issues 并同步 summary/ok(有新 error 则 ok=false)。mergeCheckIssues<T extends Summarized>(report: T, issues: CheckIssue[]): T
MergeHarvestOptionstype—MergeHarvestOptions = { onConflict?: (c: EnvHarvestConflict) => void; }
mergeHarvestUnderEnvfnHandwritten @nudojs/env wins over harvest / graph modules on overlapping module keys and overlapping export names (docs/versioning.md B8 + website harvester API).mergeHarvestUnderEnv( harvestModules: Record<string, AbsModuleExports>, envModules: Record<string, AbsModuleExports>, opts?: MergeHarvestOptions, ): Record<string, AbsModuleExports>
mockDirectivesToAbsSeedsfn从函数上的 @nudo:mock 指令收集 Abs seedmockDirectivesToAbsSeeds( functions: Array<{ directives: FunctionWithDirectives["directives"]; name?: string }>, opts?: { fromFile?: string; loadModule?: LoadModule; }, ): AbsMockSeeds
MockFromErrortype@nudo:mock name from "path" 解析失败(缺文件/缺绑定/求值失败)。MockFromError = { name: string; fromPath: string; message: string; code?: string; }
mockFromErrorIssuesfnmock 装载失败 → CheckIssue。mockFromErrorIssues(mockFromErrors: MockFromError[]): CheckIssue[]
MockModuleApplyResulttype—MockModuleApplyResult = { modules: Record<string, AbsModuleExports>; errors: FromMockError[]; applied: boolean; }
mockSeedsForSourcefn便捷入口:源码 → @nudo:mock 的 eval 注入 Abs 绑定(checkSource 注入管线用)mockSeedsForSource( source: string, opts?: { fromFile?: string; loadModule?: LoadModule }, ): Record<string, Abs>
mockSeedsToAbsMocksfn求值引擎注入用:seedVars + seedFns 统一为 Abs 函数绑定。mockSeedsToAbsMocks(seeds: AbsMockSeeds): Record<string, Abs>
ModuleExportstype—ModuleExports = { path: string; named: Map<string, string>; defaultExport?: string; source: string; poly: Map<string, PolyFn>; }
ModuleGraphCachetypemtime 边缓存:key 为文件路径,edges 为已抽取的相对 import 边(与 buildModuleGraph 返回语义一致)。ModuleGraphCache = Map<string, { mtimeMs: number; size: number; edges: string[] }>
ModuleReadErrorfn路径 stat 或文件读失败(EACCES / EMFILE / ESTALE / EIO …)。ModuleReadError extends Error { readonly code: string; readonly path: string; constructor(path: string, cause: unknown) { const code = (c...
normalizeRealPathfn—normalizeRealPath(p: string): string
normPosixPathfnposix 化(\ → /)——等值比较前先统一分隔符normPosixPath(p: string): string
noteEnvPathDepsfn源码里的 path-based load specs 解析为绝对路径后登记反向边noteEnvPathDeps(sourcePath: string, source: string): void
NudoCacheConfigtypenudo.cache 的对象形态(CI 级信任面): - dir:根目录(true/省略 → .nudo/cache;字符串 → 自定义根;false → 关闭) - sign:条目 HMAC 签名(默认 false)。开启时必须提供 env NUDO_CACHE_KEY(非空),否则拒绝运行(显式配置错误,不静默降级)—— 伪造的结构合法 CheckJson 会造成假绿(persistent-cache.md 的 L1 关闭理由), 签名把「结构合法」升级为「本密钥签发」。NudoCacheConfig = { dir?: boolean | string; sign?: boolean; }
NudoConfigtype—NudoConfig = { env?: string[]; mocks?: Record<string, string>; contract?: { autoBind?: boolean; emit?: string[] | string; }; analysis?: {...
openDiskCachefn单源 DiskCache 构造:根目录(diskCacheRoot)+ 签名状态 (diskCacheSignState)一并解析。配置错误时 throw DiskCacheSignError (消费面:CLI check/contract/health 在 action 层预检给分面错误形态; 本函数是库面/漏检路径的 fail-closed 兜底)。openDiskCache(opts: { config: NudoConfig | null | undefined; projectDir: string | undefined; namespace: string; env?: NodeJS.ProcessEnv; }): DiskCache
ParamContractEvidencetype参数契约证据(quickfix 侧车发射面): - array:参数被当数组方法接收者调用(items.reduce(…));element 为 回调元素位合成的元素契约(无证据 → array(any())) - shape:参数被成员读取(既有 body-read 字段面) - scalar:参数本体直接用法(1 + tax → number())——多参函数只收窄 一个参数仍消不掉 L2(残余 may-throw 来自其余未约束位) 优先级:array > shape > scalar(数组方法读是最强形态证据)。ParamContractEvidence = | { kind: "array"; element?: ParamContractEvidence } | { kind: "shape"; fields: BodyReadField[] } | { kind: "scal...
ParamContractstypefnName → paramName → 契约证据(参数按声明序插入)ParamContracts = Map<string, Map<string, ParamContractEvidence>>
parseIgnoreThrowsfn--ignore-throws / package.json#nudo.check.ignoreThrows 解析的 单一实现(CLI / LSP / vite-plugin 三面共享)。parseIgnoreThrows(raw?: unknown): string[] | undefined
pathEnvPreloadFingerprintfn预载状态指纹(已驻留的 path env 文件:路径 + mtimeMs)。pathEnvPreloadFingerprint(): string
PathErrortype路径错误(--json 信封的 pathErrors 面;非 JSON 面走 usage error)。PathError = { path: string; code: PathErrorCode; message: string; suggestion: string; }
PathErrorCodetype路径错误码(与 CLI 的 PathError 码集一致)。PathErrorCode = | typeof DIAG.pathNotFound | typeof DIAG.pathEmptyDir | typeof DIAG.pathNotTarget | typeof DIAG.pathMissingCallsite | typ...
pathNotFoundErrorfn路径不存在(CLI 同口径文案)。pathNotFoundError(path: string): PathError
projectConfigMemoStatsfn诊断/测试:memo 条目数 + 实际读盘(readFileSync+JSON.parse)次数projectConfigMemoStats()
projectFunctionDtsfn为单个函数生成 .d.ts 投影(JSDoc + 单一 widen 主签名)。projectFunctionDts( fn: FunctionAnalysis, contract?: DtsContractFace, surface?: DtsModuleSurface, ): DtsFunctionProjection
projectModuleDtsfn—projectModuleDts( surface: DtsModuleSurface | undefined, entries: ReadonlyArray<{ fn: FunctionAnalysis; projection: DtsFunctionProjection; contract?: DtsContractFace; }>, extras?: DtsModuleExtras, ): DtsModuleProjection
QuickfixPlantype—QuickfixPlan = { titleKind: QuickfixTitleKind; title: string; edits: TextEdit[]; sidecar?: { path: string; newText: string }; openPath?: ...
QuickfixTitleKindtype—QuickfixTitleKind = "fix" | "silence" | "review" | "adjust" | "scaffold"
ReferenceInfotype—ReferenceInfo = { name: string; loc: SourceLocation; uri?: string; }
relativizePathfn稳定逻辑根相对化(磁盘缓存路径维):树内相对 root,树外取 node_modules/<pkg> 段、monorepo root 或 pnpm store 内容哈希; 绝对路径明文绝不进 key。relativizePath(p: string, root?: string): string
resetAllAnalysisCachesfn比 clearAnalysisSessionCaches 更彻底:再丢 AST LRU(测试 / 进程复用场景)resetAllAnalysisCaches(): void
resetSessionCacheLimitStatefn测试:清空显式 / package.json 层(env 每次调用现读,无需重置)resetSessionCacheLimitState(): void
resolveModulefn—resolveModule(source: string, fromDir: string)
resolveRelativeSpecfn相对说明符 → 相对 from 文件的规范化 posix 路径;非相对说明符 → undefinedresolveRelativeSpec(from: string, spec: string): string | undefined
RootDeriveOptstype—RootDeriveOpts = { loadModule?: LoadModule; autoBind?: boolean; fnNames?: string[]; refreshExistingOnly?: boolean; }
RootDeriveResulttype—RootDeriveResult = { roots: string[]; derived: DerivedExport[]; hasRoot: boolean; graphError?: string; }
safeLoadModulefnloadModule 容错包装:读失败当 miss,避免 I/O 错误炸穿指纹/图遍历。safeLoadModule( loadModule: (spec: string, fromFile: string) => string | undefined, spec: string, fromFile: string, ): string | undefined
SchemaDialecttype—SchemaDialect = "zod"
SchemaNodetype—SchemaNode = | { k: "lit"; value: import("@nudojs/core").LiteralValue } | { k: "prim"; type: "number" | "string" | "boolean" | "bigint" |...
SchemaProjectiontype—SchemaProjection = { source: string; dialect: SchemaDialect; dropped: string[]; }
SchemaProjectionScopetype模块面作用域(BUG-051):shadowedGlobals = 本模块里被用户绑定(类 / 导入 / 顶层声明)遮蔽掉的全局构造器名。SchemaProjectionScope = { shadowedGlobals?: ReadonlySet<string>; }
SchemaRefinementtype—SchemaRefinement = | { kind: "numBound"; op: "gt" | "ge" | "lt" | "le"; n: number } | { kind: "int" } | { kind: "strMin"; n: number } | {...
serializeCaseArgfn单个 Abs → parseCaseArgExpr 可解析回去的表达式文本;不可表达返回 nullserializeCaseArg(a: Abs): string | null
serializeCaseJsonfn—serializeCaseJson( result: AnalysisResult, file: string, ): CaseJson
SessionCacheLimitstype会话级内存 LRU 上限(进程内,非磁盘 cache)。SessionCacheLimits = { maxFiles: number; maxFns: number; maxEvalRuns: number; }
setAnalysisSessionfn测试:替换默认 session(返回旧值以便恢复)setAnalysisSession(session: AnalysisSession | undefined): AnalysisSession | undefined
setEnvHarvestConflictCollectorfnInstall conflict collector; returns the previous one so nested/concurrent analyzeFile callers can save/restore (scoped fallback: inside runWithCollectorScope each analysis gets its own slot, no cross-talk).setEnvHarvestConflictCollector( collector: ((c: EnvHarvestConflict) => void) | null, )
setSessionCacheFromProjectfnpackage.json#nudo.sessionCache 层(findProjectConfig / 宿主接线)setSessionCacheFromProject(partial: PartialLimits | null | undefined): void
setSessionCacheLimitsfn显式覆盖(宿主 / 测试)。传 null 清除显式层setSessionCacheLimits(partial: PartialLimits | null): SessionCacheLimits
sha256Hexfn—sha256Hex(data: string | Buffer): string
shapeDslFromFieldsfnshape({ type: string(), loc: shape({ start: … }) }) 文本。shapeDslFromFields(fields: BodyReadField[]): string
shouldAnalyzeFilefn是否应对该文件跑分析(自动路径,如 LSP validate)。shouldAnalyzeFile( filePath: string, source: string | undefined, config?: AnalysisConfig, ): boolean
sidecarDraftPathfnlib.js|ts → lib.nudo.draft.js|ts(不进 ambient sidecar 表)sidecarDraftPath(filePath: string): string
sourceHasNudoDirectivesfn—hasNudoDirectives(source: string): boolean
SourceLocationtype—SourceLocation = { start: { line: number; column: number }; end: { line: number; column: number }; }
stablePathKeyconst——
stablePathKeyGraphconst——
StandardSchemaFunctionSpectype标准面函数级装配描述(入参面 + 返回面)。StandardSchemaFunctionSpec = { fn: string; inputs?: ReadonlyArray<{ name: string; abs: Abs; optional?: boolean }>; formals?: ReadonlyArra...
StandardSchemaInputEntrytype标准面入参条目:整参(param)或解构形参的字段(field)。StandardSchemaInputEntry = | { kind: "param"; name: string; abs: Abs; optional?: boolean } | { kind: "field"; name: string; abs: Abs; opt...
StandardSchemaIssuetype—StandardSchemaIssue = { message: string; path?: ReadonlyArray<PropertyKey>; }
StandardSchemaModuleProjectiontype—StandardSchemaModuleProjection = { source: string; dropped: string[]; }
StandardSchemaResulttype—StandardSchemaResult = | { value: unknown; issues?: undefined } | { issues: ReadonlyArray<StandardSchemaIssue>; value?: undefined }
stripGeneratedCaseDirectivesfn从源码剥离所有本模块生成的 @nudo:case 指令(名字以 call@ 开头,整行删除)。stripGeneratedCaseDirectives(source: string)
Summarizedtypecheck 报告的最小可并入形状(CheckReport / CheckJson 都满足)。Summarized = { issues: CheckIssue[]; ok: boolean; summary: { errors: number; warnings: number; infos: number; functions: number }; }
SYMBOLIC_BUDGET_NOTEconstcall@symbolic(预算聚合见证)× actionable 提示(精度悬崖 UX):报告里出现 call@symbolic = 该函数的调用点数超过了 callSiteBudget(默认 3, package.json#nudo.analysis.callSiteBudget,1–64),超预算的调用点被折进 一条宽化聚合见证(#widened,可解释降级)。两条恢复路径,与 check 面 nudo:recursion-truncated 的建议句式同构(「事实 — 动作 A or 动作 B」): - 抬预算:package.json#nudo.analysis.callSiteBudget(1–64); - 固化精确见证:@nudo:case(limitations §3.2.2 同款口径——递归函数的 精确见证用指令固化,不要依赖 call@:预算只保住前 N 个调用点)。const SYMBOLIC_BUDGET_NOTE
SymbolInfotype—SymbolInfo = { name: string; kind: "function" | "variable" | "class" | "parameter"; loc: SourceLocation; uri?: string; }
SymbolTabletype—SymbolTable = { definitions: Map<string, SymbolInfo>; references: ReferenceInfo[]; }
targetPathErrorfn「分析目标」闸门(与 CLI resolveTargetsCollect 的文件分支同口径): 侧车契约模块(*.nudo.js / *.nudo.draft.*)、类型声明(.d.ts)、 JSX(.jsx / .tsx)不是分析目标——把它们送进分析器会得到 「0 个函数 ⇒ 0 error ⇒ 判绿」的假绿(或把契约 DSL 构造器当成真实 调用点报成 case)。targetPathError(path: string): PathError | undefined
TestReporttype—TestReport = { file: string; passed: number; failed: number; unchecked: number; outcomes: CaseTestOutcome[]; caseLines: string[]; }
TestReportOptionstype—TestReportOptions = { entryContractNotes?: ReadonlySet<string>; }
TextEdittype—TextEdit = { startLine: number; startCol: number; endLine: number; endCol: number; newText: string; }
topoSortDirtyfnTopological order with dependencies before dependents (only imports edges internal to dirty; cycles tolerated — remaining files appended in arbitrary order).topoSortDirty(imports: Map<string, Set<string>>, dirty: string[]): string[]
trimAnalysisFileCachefn立刻压到当前 maxFiles(调低上限时收内存)trimAnalysisFileCache(): void
trimEvalCachefn立刻压到当前 maxEvalRuns(调低上限时收内存)trimEvalCache(): void
trimFnAnalysisCachefn立刻压到当前 maxFns(调低上限时收内存)trimFnAnalysisCache(): void
tryEvalCallfn求值引擎求值具名导出(仅成功结果)tryEvalCall( source: string, filePath: string, fnName: string, args: Abs[], opts: { envNames?: string[]; mocks?: Record<string, Abs>; phi?: Phi; loadModule?: LoadModule; depKey?: string | null; keepNeverThrows?: boolean; } = {}, ): Abs | undefined
tryEvalCallFullfn求值引擎求值具名导出(结果 + throws);opts.collectCalls 时附带调用点记录。tryEvalCallFull( source: string, filePath: string, fnName: string, args: Abs[], opts: { collectCalls?: boolean; collectMemberDiags?: boolean; envNames?: string[]; mocks?: Record<string, Abs>; phi?: Phi; thisArg?: Abs; loadModule?: LoadModule; depKey?: string | null; } = {}, )
tryRunEvalfn模块图 + runTranspiled(默认 analyze 模式)tryRunEval( source: string, filePath: string, opts: { maxLoopIters?: number; mode?: "exec" | "analyze"; envNames?: string[]; mocks?: Record<string, Abs>; lenientGlobals?: boolean; loadModule?: LoadModule; depKey?: string | null; composed?: ComposedEvalModules; fresh?: boolean; } = {}, ): EvalRunResult | undefined
TypeBindingtype—TypeBinding = { name: string; type: string }
typeExprToDirectivefnagent 面类型表达式 → @nudo:as 文法(认不出的表达式落到 unknown)typeExprToDirective(expr: string): string
unifiedDifffn—unifiedDiff(a: string, b: string, path: string): string
writeContractDraftfn写入 *.nudo.draft.js(覆盖草稿文件本身;不碰正式 *.nudo.js)。writeContractDraft( filePath: string, draftSource: string, opts: { dryRun?: boolean; projectDir?: string; entries?: ReadonlyArray<Pick<ContractDraftEntry, "dsl" | "skipped">>; draftable?: boolean; } = {}, ): WriteDraftResult
WriteDraftResulttype—WriteDraftResult = { draftPath: string; written: boolean; changed: boolean; draftable: boolean; draftSource: string; skipped?: "hand-edit...
writeFileAtomicfntmp + rename 原子写(同目录 temp ⇒ 崩溃/磁盘满时目标要么旧要么新,不会 半截)。随机后缀用 randomBytes(不是 Math.random/Date.now):防可 预测 tmp 路径被预置符号链接劫持。writeFileAtomic(path: string, data: string): void
ZodModuleProjectiontype—ZodModuleProjection = { source: string; dialect: SchemaDialect; dropped: string[]; }