Support per-subclass static wrappers; drop runtime map
Introduce per-subclass static-method wrapper support: detect wrapper-pattern methods in the AST, resolve concrete types via a TypeChecker, render per-subclass overrides, and append them into transformed output. Adds static-wrapper detector, subclass-override codegen, a typecheck file pipeline, a lazy ts.Program cache, and the subclass-wrapper resolver. Integrates the pipeline into the Vite plugin (including program cache invalidation on HMR) and threads extra root type names into registry selection so generated overrides get required codecs. Remove the runtime-map fallback feature and related types/logic (runtime-map module, dynamic runtime generation, and public API surface), simplifying runtime stubs and protobuf.d.ts. Update README and analyzer to document and support the new flow; add tests and fixtures for subclass-wrapper behavior.
This commit is contained in:
1 parent
5924346823
commit
3726913c1f
17 files changed
+1342
-601
No files matched your search
+88
-26
@@ -160,6 +160,86 @@ const bytes = encodeWrapped<string>({ value: 'hi' });
|
||||
Chained forwarders also work (`A` forwards to `B` which is imported from
|
||||
another module, etc.).
|
||||
|
||||
## Static method wrappers (per-subclass overrides)
|
||||
|
||||
Sometimes you want an abstract base class to hold the encode / decode
|
||||
pipeline once, with each subclass supplying only the request-/response-
|
||||
shaped helpers:
|
||||
|
||||
```ts
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
|
||||
abstract class PacketTransformer {
|
||||
static encode<R, T extends { serialize: (ctx: unknown, p: never) => R }>(
|
||||
this: T,
|
||||
ctx: unknown,
|
||||
params: T['serialize'] extends (ctx: unknown, p: infer P) => R ? P : never,
|
||||
): Uint8Array {
|
||||
return protobuf_encode<R>((this as any).serialize(ctx, params));
|
||||
}
|
||||
|
||||
static decode<B, Res, T extends { deserialize: (ctx: unknown, body: B) => Res }>(
|
||||
this: T,
|
||||
ctx: unknown,
|
||||
bytes: Uint8Array,
|
||||
): Res {
|
||||
return (this as any).deserialize(ctx, protobuf_decode<B>(bytes));
|
||||
}
|
||||
}
|
||||
|
||||
class DemoTransformer extends PacketTransformer {
|
||||
static serialize(_ctx: unknown, p: DemoReq): DemoReqPb { /* … */ }
|
||||
static deserialize(_ctx: unknown, b: DemoResPb): DemoRes { /* … */ }
|
||||
}
|
||||
|
||||
// Just call the inherited methods naturally:
|
||||
const bytes = DemoTransformer.encode(undefined, { /* … */ });
|
||||
const result = DemoTransformer.decode(undefined, bytes);
|
||||
```
|
||||
|
||||
`protobuf_encode<R>` / `protobuf_decode<B>` inside the abstract body can't
|
||||
be replaced statically — `R` and `B` are erased at runtime. Proton handles
|
||||
this by:
|
||||
|
||||
1. Detecting any class whose static method (a) takes type parameters, (b)
|
||||
calls `protobuf_encode<R>` / `protobuf_decode<R>` where `R` is one of
|
||||
those parameters, and (c) constrains `this: T extends { … }` with the
|
||||
parameter appearing inside the constraint.
|
||||
2. Using TypeScript's TypeChecker — built lazily from your project's
|
||||
`tsconfig.json` — to walk the `extends` chain for every subclass in the
|
||||
file (cross-file edges and path aliases included) and resolve the
|
||||
wrapper's type parameter against the subclass's sibling method
|
||||
signature (`serialize`'s return type for `R`, `deserialize`'s body
|
||||
parameter for `B`, in this example).
|
||||
3. Appending a per-subclass override after the class declaration:
|
||||
|
||||
```js
|
||||
DemoTransformer.encode = function (ctx, params) {
|
||||
return protobuf_encode_DemoReqPb(this.serialize(ctx, params));
|
||||
};
|
||||
```
|
||||
|
||||
The original call sites stay unmodified — runtime dispatch finds the
|
||||
override naturally because static properties live on the constructor
|
||||
function. The abstract base body is left intact too; nothing ever calls
|
||||
it.
|
||||
|
||||
Naming is structural, not configured:
|
||||
|
||||
- The wrapper method can be named anything (`encode`, `enc`, `request`, …)
|
||||
— proton only looks at the body and constraint shape.
|
||||
- The sibling method's name is read out of the `this: T extends { … }`
|
||||
constraint, so `serialize`/`deserialize`, `build`/`parse`, or any other
|
||||
pair works.
|
||||
- Multi-level inheritance (`Leaf → MidBase → AbstractBase`) is followed
|
||||
end-to-end by the TypeChecker.
|
||||
|
||||
If the sibling method lacks an explicit return / parameter annotation the
|
||||
checker's inferred type is used as a fallback. The override is only
|
||||
emitted when every codec call in the wrapper body resolves successfully —
|
||||
partial resolution would produce dead identifier references at runtime,
|
||||
so the all-or-nothing rule is intentional.
|
||||
|
||||
## proto3 default-value semantics
|
||||
|
||||
**Important behavioural detail.** Proton follows the proto3 wire format spec:
|
||||
@@ -201,29 +281,6 @@ Currently unsupported:
|
||||
|
||||
…all of these will throw with a clear message instead of producing bad bytes.
|
||||
|
||||
## Optional: runtime-map fallback
|
||||
|
||||
If a call site can't be statically resolved (e.g. dynamic loading after build),
|
||||
the plugin can emit a JSON map that the runtime can consume to generate codecs
|
||||
on the fly. Off by default.
|
||||
|
||||
```ts
|
||||
import protobufVitePlugin from '@snowluma/proton/vite';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [protobufVitePlugin({
|
||||
runtimeMap: { enabled: true, fileName: 'snowluma-proton.runtime-map.json' },
|
||||
})],
|
||||
});
|
||||
```
|
||||
|
||||
```ts
|
||||
import runtimeMap from './snowluma-proton.runtime-map.json';
|
||||
import { protobuf_enableRuntimeMapFallback } from '@snowluma/proton';
|
||||
|
||||
protobuf_enableRuntimeMapFallback(runtimeMap);
|
||||
```
|
||||
|
||||
## Edge cases fixed on top of upstream
|
||||
|
||||
Each has a regression test in `test/__tests__/analyzer.test.ts`:
|
||||
@@ -259,15 +316,20 @@ src/
|
||||
monomorphizer.ts generic instantiation → concrete ProtobufMessage
|
||||
import-resolver.ts cross-file definition + wrapper resolution
|
||||
callsite.ts matches protobuf_encode/decode invocations
|
||||
static-wrapper.ts static-method wrapper detection (AST)
|
||||
utils.ts name resolution + synthetic-SF tracking
|
||||
dependency-graph.ts topo sort + reachability
|
||||
types.ts shared schema types
|
||||
codegen/ inlined wire-format emitters
|
||||
subclass-override.ts per-subclass override codegen
|
||||
typecheck/ TypeChecker-backed pipeline (per-subclass overrides)
|
||||
program-cache.ts lazy ts.Program, keyed by tsconfig
|
||||
subclass-wrapper.ts extends-chain walking + type-param resolution
|
||||
file-pipeline.ts per-file glue used by the plugin's transform()
|
||||
transform/ Vite plugin string edits
|
||||
index.ts plugin entry (./vite)
|
||||
runtime.ts runtime stubs + map fallback (.)
|
||||
runtime-map.ts serialized map format
|
||||
runtime.ts runtime stubs (.)
|
||||
|
||||
protobuf.d.ts public types (pb<>, pb_repeated<>, primitive aliases)
|
||||
test/ vitest suite (analyzer + cross-file + plugin)
|
||||
test/ vitest suite (analyzer + cross-file + plugin + subclass-wrapper)
|
||||
```
|
||||
Vendored
-36
@@ -23,39 +23,3 @@ export type bytes = Uint8Array;
|
||||
// ── Encode / decode (replaced at compile-time by the vite plugin) ────
|
||||
export function protobuf_encode<T>(params: T): Uint8Array;
|
||||
export function protobuf_decode<T>(data: Uint8Array): T;
|
||||
|
||||
// ── Optional runtime map fallback (disabled by default) ───────────────
|
||||
export interface ProtobufRuntimeField {
|
||||
name: string;
|
||||
fieldNumber: number;
|
||||
typeName: string;
|
||||
wireType: 0 | 1 | 2 | 5;
|
||||
isMessage: boolean;
|
||||
isOptional: boolean;
|
||||
isRepeated: boolean;
|
||||
}
|
||||
|
||||
export interface ProtobufRuntimeMessage {
|
||||
name: string;
|
||||
fields: ProtobufRuntimeField[];
|
||||
}
|
||||
|
||||
export interface ProtobufRuntimeCallSite {
|
||||
file: string;
|
||||
line: number;
|
||||
column: number;
|
||||
fnName: 'protobuf_encode' | 'protobuf_decode';
|
||||
typeName: string;
|
||||
}
|
||||
|
||||
export interface ProtobufRuntimeMap {
|
||||
version: 1;
|
||||
messages: ProtobufRuntimeMessage[];
|
||||
callSites: ProtobufRuntimeCallSite[];
|
||||
}
|
||||
|
||||
/** Enables map-based runtime dynamic code generation fallback. */
|
||||
export function protobuf_enableRuntimeMapFallback(map: ProtobufRuntimeMap): void;
|
||||
|
||||
/** Disables map-based runtime fallback and clears generated function cache. */
|
||||
export function protobuf_disableRuntimeMapFallback(): void;
|
||||
@@ -1,20 +1,20 @@
|
||||
import ts from 'typescript';
|
||||
import { WireType, PRIMITIVE_TYPE_MAP, type ProtobufMessage, type MessageRegistry, type GenericProtobufTemplate } from './types.js';
|
||||
import { collectInterface, collectGenericInterface, collectConcreteFieldGenericTypeArgs } from './collector.js';
|
||||
import { monomorphizeTypeNode } from './monomorphizer.js';
|
||||
import {
|
||||
createImportedTypeNameResolver,
|
||||
typeNodeToMangledName,
|
||||
registerSyntheticTypeSourceFile,
|
||||
resolveSourceFileForTypeNode,
|
||||
} from './utils.js';
|
||||
import type { ImportedDefinitions, WrapperBinding } from './import-resolver.js';
|
||||
import {
|
||||
collectProtobufImportBindings,
|
||||
matchProtobufCallSite,
|
||||
type CanonicalProtobufFn,
|
||||
} from './callsite.js';
|
||||
import { collectConcreteFieldGenericTypeArgs, collectGenericInterface, collectInterface } from './collector.js';
|
||||
import { buildDependencyRegistry } from './dependency-graph.js';
|
||||
import type { ImportedDefinitions, WrapperBinding } from './import-resolver.js';
|
||||
import { monomorphizeTypeNode } from './monomorphizer.js';
|
||||
import { PRIMITIVE_TYPE_MAP, WireType, type GenericProtobufTemplate, type MessageRegistry, type ProtobufMessage } from './types.js';
|
||||
import {
|
||||
createImportedTypeNameResolver,
|
||||
registerSyntheticTypeSourceFile,
|
||||
resolveSourceFileForTypeNode,
|
||||
typeNodeToMangledName,
|
||||
} from './utils.js';
|
||||
|
||||
export { typeNodeToMangledName } from './utils.js';
|
||||
|
||||
@@ -260,11 +260,17 @@ export function analyzeSource(code: string, filePath: string, imported?: Importe
|
||||
/**
|
||||
* Build a minimal message registry by collecting only call-site root types and
|
||||
* their transitive message dependencies.
|
||||
*
|
||||
* `extraRootNames` lets callers seed the root set with type names that
|
||||
* weren't discovered through `protobuf_encode/decode` call sites — used by
|
||||
* the subclass-wrapper pipeline to drag in codecs whose only consumer is a
|
||||
* per-subclass override generated outside this analyzer.
|
||||
*/
|
||||
export function selectUsedRegistry(
|
||||
registry: MessageRegistry,
|
||||
callSites: CallSiteRecord[],
|
||||
sourceFile: ts.SourceFile,
|
||||
extraRootNames?: Iterable<string>,
|
||||
): UsedRegistryResult {
|
||||
const roots = new Set<string>();
|
||||
const resolved: ResolvedCallSiteRecord[] = [];
|
||||
@@ -276,6 +282,12 @@ export function selectUsedRegistry(
|
||||
resolved.push({ ...cs, typeName });
|
||||
}
|
||||
|
||||
if (extraRootNames) {
|
||||
for (const name of extraRootNames) {
|
||||
if (registry.has(name)) roots.add(name);
|
||||
}
|
||||
}
|
||||
|
||||
if (roots.size === 0) {
|
||||
return { registry: new Map(), roots, callSites: resolved };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
import ts from 'typescript';
|
||||
import { collectProtobufImportBindings, matchProtobufCallSite, type CanonicalProtobufFn, type ProtobufImportBindings } from './callsite.js';
|
||||
|
||||
/**
|
||||
* Static-method wrapper detection.
|
||||
*
|
||||
* A "wrapper" here is the abstract half of the pattern that motivates the
|
||||
* whole feature:
|
||||
*
|
||||
* ```ts
|
||||
* abstract class PacketTransformer {
|
||||
* static encode<R, T extends { serialize: (...) => R }>(this: T, ...) {
|
||||
* return protobuf_encode<R>(this.serialize(...));
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* The method itself can never run at the user's call site because `R` is
|
||||
* erased at runtime. Proton's job is to walk every subclass of such a base,
|
||||
* resolve `R` per subclass via TypeChecker, and emit a per-subclass override
|
||||
* with a concrete codec inlined.
|
||||
*
|
||||
* This module only handles the AST-side detection — what the method looks
|
||||
* like and which type parameter it pipes into protobuf_encode/decode. The
|
||||
* subclass resolution + codegen lives in `typecheck/subclass-wrapper.ts`
|
||||
* because both steps need a TypeChecker.
|
||||
*
|
||||
* The detector is intentionally name-agnostic: it doesn't care that the
|
||||
* method is called `encode`, that the sibling is `serialize`, or that the
|
||||
* base is `PacketTransformer`. It only looks at the structural pattern,
|
||||
* which keeps it usable for user-defined variants (decode side, RPC chains,
|
||||
* etc.) without further configuration.
|
||||
*/
|
||||
|
||||
/** A single `protobuf_encode<X>(...)` / `protobuf_decode<X>(...)` call inside
|
||||
* the wrapper's body where `X` is one of the wrapper's own type parameters.
|
||||
* The override generator uses the position info to splice in a concrete
|
||||
* codec identifier in place of the generic form. */
|
||||
export interface WrapperCodecCall {
|
||||
fnName: CanonicalProtobufFn;
|
||||
/** Name of the wrapper's type parameter used as the type argument. Always
|
||||
* one of `WrapperMethodInfo.typeParamNames`. */
|
||||
typeParamName: string;
|
||||
/** Offset of the call's expression start (e.g. `protobuf_encode`) in the
|
||||
* *original* source file. */
|
||||
exprStart: number;
|
||||
/** Offset directly after the closing `>` of the type-argument list. */
|
||||
typeArgsEnd: number;
|
||||
}
|
||||
|
||||
export interface WrapperMethodInfo {
|
||||
/** Method name as written on the abstract class — used to look up
|
||||
* override targets on subclasses. */
|
||||
methodName: string;
|
||||
/** All type parameters declared by this method (`<R, T, ...>`). */
|
||||
typeParamNames: string[];
|
||||
/** Constraint sub-AST attached to the `this: T` parameter, if any.
|
||||
* The subclass resolver uses this to figure out which sibling method's
|
||||
* signature defines each codec-relevant type parameter. */
|
||||
thisConstraint: ts.TypeNode | null;
|
||||
/** Original method declaration node — kept so the override generator can
|
||||
* copy its parameter list and body verbatim before substituting codecs. */
|
||||
declaration: ts.MethodDeclaration;
|
||||
/** Every protobuf_encode/decode call inside the body whose type-arg is
|
||||
* one of the wrapper's type parameters. There can legitimately be
|
||||
* several (encode + decode sharing a body, sequential pipeline, etc.). */
|
||||
codecCalls: WrapperCodecCall[];
|
||||
}
|
||||
|
||||
export interface ClassWrapperInfo {
|
||||
/** The abstract class declaration carrying the wrapper methods. */
|
||||
classDecl: ts.ClassDeclaration;
|
||||
/** Map keyed by method name for O(1) lookup during override generation. */
|
||||
methods: Map<string, WrapperMethodInfo>;
|
||||
}
|
||||
|
||||
/** Find every static-method wrapper on a single class. Returns null if the
|
||||
* class has no qualifying methods (the common case — only the abstract
|
||||
* base of a transformer hierarchy will return non-null). */
|
||||
export function detectClassWrappers(
|
||||
cls: ts.ClassDeclaration,
|
||||
sf: ts.SourceFile,
|
||||
bindings?: ProtobufImportBindings,
|
||||
): ClassWrapperInfo | null {
|
||||
const importBindings = bindings ?? collectProtobufImportBindings(sf);
|
||||
const methods = new Map<string, WrapperMethodInfo>();
|
||||
|
||||
for (const member of cls.members) {
|
||||
if (!ts.isMethodDeclaration(member)) continue;
|
||||
if (!isStaticMethod(member)) continue;
|
||||
if (!member.typeParameters?.length) continue;
|
||||
if (!member.body) continue;
|
||||
const methodName = getMethodName(member);
|
||||
if (!methodName) continue;
|
||||
|
||||
const typeParamNames = member.typeParameters.map(tp => tp.name.text);
|
||||
const typeParamSet = new Set(typeParamNames);
|
||||
const codecCalls = collectCodecCallsInBody(member.body, sf, importBindings, typeParamSet);
|
||||
if (codecCalls.length === 0) continue;
|
||||
|
||||
methods.set(methodName, {
|
||||
methodName,
|
||||
typeParamNames,
|
||||
thisConstraint: extractThisConstraint(member),
|
||||
declaration: member,
|
||||
codecCalls,
|
||||
});
|
||||
}
|
||||
|
||||
if (methods.size === 0) return null;
|
||||
return { classDecl: cls, methods };
|
||||
}
|
||||
|
||||
/** Locate every wrapper-bearing class in a single source file. Driven from
|
||||
* the analyzer once per file; the subclass resolver consumes the result. */
|
||||
export function detectClassWrappersInFile(
|
||||
sf: ts.SourceFile,
|
||||
bindings?: ProtobufImportBindings,
|
||||
): Map<string, ClassWrapperInfo> {
|
||||
const importBindings = bindings ?? collectProtobufImportBindings(sf);
|
||||
const out = new Map<string, ClassWrapperInfo>();
|
||||
for (const stmt of sf.statements) {
|
||||
if (!ts.isClassDeclaration(stmt) || !stmt.name) continue;
|
||||
const info = detectClassWrappers(stmt, sf, importBindings);
|
||||
if (info) out.set(stmt.name.text, info);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function isStaticMethod(m: ts.MethodDeclaration): boolean {
|
||||
const mods = ts.getModifiers(m);
|
||||
return mods?.some(mod => mod.kind === ts.SyntaxKind.StaticKeyword) ?? false;
|
||||
}
|
||||
|
||||
function getMethodName(m: ts.MethodDeclaration): string | null {
|
||||
if (ts.isIdentifier(m.name)) return m.name.text;
|
||||
if (ts.isStringLiteral(m.name)) return m.name.text;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Walk method body, collecting every protobuf_encode/decode call whose
|
||||
* type-arg is a bare reference to one of the method's type parameters. */
|
||||
function collectCodecCallsInBody(
|
||||
body: ts.Block,
|
||||
sf: ts.SourceFile,
|
||||
importBindings: ProtobufImportBindings,
|
||||
typeParamSet: Set<string>,
|
||||
): WrapperCodecCall[] {
|
||||
const out: WrapperCodecCall[] = [];
|
||||
|
||||
function visit(node: ts.Node): void {
|
||||
if (ts.isCallExpression(node)) {
|
||||
const cs = matchProtobufCallSite(node, sf, importBindings, { allowLegacyUnboundCanonical: true });
|
||||
if (cs) {
|
||||
const ta = cs.firstTypeArg;
|
||||
// Only track calls whose type-arg is a simple type-param identifier.
|
||||
// `protobuf_encode<Wrapper<T>>` etc. is rare in wrapper bodies; if it
|
||||
// shows up we'd need a more elaborate substitution scheme so we leave
|
||||
// it for now (the AST analyzer's existing path handles concrete
|
||||
// forms separately).
|
||||
if (ts.isTypeReferenceNode(ta) && ts.isIdentifier(ta.typeName) && !ta.typeArguments?.length) {
|
||||
const name = ta.typeName.text;
|
||||
if (typeParamSet.has(name)) {
|
||||
out.push({
|
||||
fnName: cs.fnName,
|
||||
typeParamName: name,
|
||||
exprStart: cs.exprStart,
|
||||
typeArgsEnd: cs.typeArgsEnd,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ts.forEachChild(node, visit);
|
||||
}
|
||||
|
||||
visit(body);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Pluck the `T` constraint from a `this: T` parameter, returning the
|
||||
* constraint TypeNode (e.g. the `{ serialize: ... }` literal). Returns
|
||||
* null for any shape that doesn't match — the subclass resolver treats
|
||||
* that as "no per-subclass override possible". */
|
||||
function extractThisConstraint(method: ts.MethodDeclaration): ts.TypeNode | null {
|
||||
const thisParam = method.parameters.find(p =>
|
||||
ts.isIdentifier(p.name) && p.name.text === 'this',
|
||||
);
|
||||
if (!thisParam?.type) return null;
|
||||
if (!ts.isTypeReferenceNode(thisParam.type) || !ts.isIdentifier(thisParam.type.typeName)) return null;
|
||||
const thisTypeParamName = thisParam.type.typeName.text;
|
||||
|
||||
const thisTypeParam = method.typeParameters?.find(tp => tp.name.text === thisTypeParamName);
|
||||
return thisTypeParam?.constraint ?? null;
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import ts from 'typescript';
|
||||
import type { ResolvedSubclassWrapper } from '../typecheck/subclass-wrapper.js';
|
||||
|
||||
/**
|
||||
* Per-subclass override code generation.
|
||||
*
|
||||
* The abstract base class's static method body is copied verbatim, with
|
||||
* every `protobuf_encode<R>` / `protobuf_decode<B>` occurrence rewritten to
|
||||
* the concrete `protobuf_encode_${typeName}` / `protobuf_decode_${typeName}`
|
||||
* identifier. The result is assigned onto the subclass:
|
||||
*
|
||||
* ```ts
|
||||
* Sub.encode = function (ctx, params) { … rewritten body … };
|
||||
* ```
|
||||
*
|
||||
* Output language:
|
||||
* The generated text is appended into the subclass's own (already-TS)
|
||||
* transform result. Anything TS-only inside the body (`as never`, return-
|
||||
* type annotations on local vars, etc.) survives intact and is dropped
|
||||
* downstream by the same TS-to-JS step that already handles the rest of
|
||||
* the user file. We avoid running our own transpilation step here both
|
||||
* because it adds latency and because re-transpiling once Vite is about
|
||||
* to do it again would generate duplicate work for every transform.
|
||||
*/
|
||||
|
||||
export interface SubclassOverrideRenderResult {
|
||||
/** The generated override source text, ready to append after the subclass
|
||||
* declaration. Trailing newline included. */
|
||||
code: string;
|
||||
}
|
||||
|
||||
export function renderSubclassOverride(resolved: ResolvedSubclassWrapper): SubclassOverrideRenderResult | null {
|
||||
const { subclass, wrapper, resolvedCodecCalls } = resolved;
|
||||
if (!subclass.name) return null;
|
||||
if (!wrapper.declaration.body) return null;
|
||||
if (resolvedCodecCalls.length === 0) return null;
|
||||
|
||||
const wrapperSf = wrapper.declaration.getSourceFile();
|
||||
const body = wrapper.declaration.body;
|
||||
const bodyStart = body.getStart(wrapperSf);
|
||||
const bodyEnd = body.getEnd();
|
||||
const bodyText = wrapperSf.text.slice(bodyStart, bodyEnd);
|
||||
|
||||
// Apply edits in reverse position order so earlier offsets stay valid.
|
||||
const edits = resolvedCodecCalls
|
||||
.map(c => ({
|
||||
start: c.exprStart - bodyStart,
|
||||
end: c.typeArgsEnd - bodyStart,
|
||||
replacement: `${c.fnName}_${c.resolvedTypeName}`,
|
||||
}))
|
||||
.filter(e => e.start >= 0 && e.end <= bodyText.length)
|
||||
.sort((a, b) => b.start - a.start);
|
||||
|
||||
let body2 = bodyText;
|
||||
for (const e of edits) {
|
||||
body2 = body2.slice(0, e.start) + e.replacement + body2.slice(e.end);
|
||||
}
|
||||
|
||||
const paramList = renderParameterList(wrapper.declaration, wrapperSf);
|
||||
const subclassName = subclass.name.text;
|
||||
const methodName = wrapper.methodName;
|
||||
|
||||
return {
|
||||
code: `${subclassName}.${methodName} = function (${paramList}) ${body2};\n`,
|
||||
};
|
||||
}
|
||||
|
||||
/** Build the parameter list for the override function. Skips the implicit
|
||||
* `this` parameter (TypeScript-only; not real at runtime) and strips type
|
||||
* annotations — the override is plain JS-flavoured TS at this point and
|
||||
* carrying the original annotations would force the analyzer to also
|
||||
* rewrite any type-references inside them, which is needless work for code
|
||||
* that gets transpiled to JS in the very next pipeline step. */
|
||||
function renderParameterList(method: ts.MethodDeclaration, sf: ts.SourceFile): string {
|
||||
const out: string[] = [];
|
||||
for (const param of method.parameters) {
|
||||
if (ts.isIdentifier(param.name) && param.name.text === 'this') continue;
|
||||
|
||||
const namePart = renderBindingName(param.name, sf);
|
||||
const optional = param.questionToken ? '?' : '';
|
||||
const initializer = param.initializer
|
||||
? ` = ${param.initializer.getText(sf)}`
|
||||
: '';
|
||||
const rest = param.dotDotDotToken ? '...' : '';
|
||||
|
||||
out.push(`${rest}${namePart}${optional}${initializer}`);
|
||||
}
|
||||
return out.join(', ');
|
||||
}
|
||||
|
||||
/** Stringify a parameter binding name, preserving destructuring patterns.
|
||||
* We deliberately use `getText()` rather than re-emitting via the printer
|
||||
* because the printer would also try to re-quote literals and re-format
|
||||
* trivia, producing diffs against the user's original formatting that
|
||||
* serve no purpose. */
|
||||
function renderBindingName(name: ts.BindingName, sf: ts.SourceFile): string {
|
||||
return name.getText(sf);
|
||||
}
|
||||
@@ -1,30 +1,15 @@
|
||||
import type { Plugin } from 'vite';
|
||||
import { analyze, analyzeSource, selectUsedRegistry, typeNodeToMangledName } from './ast/analyzer.js';
|
||||
import { resolveImports, type ParsedFileEntry } from './ast/import-resolver.js';
|
||||
import { generateCode } from './codegen/generator.js';
|
||||
import { applyReplacements, replaceCallSites } from './transform/replacer.js';
|
||||
import type { MessageRegistry } from './ast/types.js';
|
||||
import { resolveImports, type ParsedFileEntry } from './ast/import-resolver.js';
|
||||
import { createRuntimeMap, type RuntimeMapCallSite } from './runtime-map.js';
|
||||
import { runSubclassWrapperPipeline } from './typecheck/file-pipeline.js';
|
||||
import { invalidateProgramCache } from './typecheck/program-cache.js';
|
||||
|
||||
export interface ProtobufRuntimeMapPluginOptions {
|
||||
enabled?: boolean;
|
||||
fileName?: string;
|
||||
}
|
||||
export type ProtobufVitePluginOptions = Record<string, never>;
|
||||
|
||||
export interface ProtobufVitePluginOptions {
|
||||
runtimeMap?: ProtobufRuntimeMapPluginOptions;
|
||||
}
|
||||
|
||||
interface RuntimeMapFileEntry {
|
||||
messages: MessageRegistry;
|
||||
callSites: RuntimeMapCallSite[];
|
||||
}
|
||||
|
||||
export default function protobufVitePlugin(options: ProtobufVitePluginOptions = {}): Plugin {
|
||||
export default function protobufVitePlugin(_options: ProtobufVitePluginOptions = {}): Plugin {
|
||||
const fileCache = new Map<string, ParsedFileEntry>();
|
||||
const runtimeMapByFile = new Map<string, RuntimeMapFileEntry>();
|
||||
const runtimeMapEnabled = options.runtimeMap?.enabled === true;
|
||||
const runtimeMapFileName = options.runtimeMap?.fileName ?? 'snowluma-proton.runtime-map.json';
|
||||
|
||||
return {
|
||||
name: 'vite-plugin-protobuf',
|
||||
@@ -36,78 +21,56 @@ export default function protobufVitePlugin(options: ProtobufVitePluginOptions =
|
||||
|
||||
const imported = resolveImports(code, cleanId, fileCache);
|
||||
const { registry, callSites, sourceFile } = analyze(code, cleanId, imported);
|
||||
if (registry.size === 0 && callSites.length === 0) return null;
|
||||
// Subclass-wrapper pipeline lives outside the AST analyzer because it
|
||||
// needs a TypeChecker. It returns extra root type names that must
|
||||
// participate in `selectUsedRegistry` so the codecs they reference
|
||||
// actually get generated, plus the per-subclass override text we
|
||||
// append after the user code.
|
||||
const subclassWrappers = runSubclassWrapperPipeline(cleanId);
|
||||
|
||||
const used = selectUsedRegistry(registry, callSites, sourceFile);
|
||||
if (used.registry.size === 0) {
|
||||
runtimeMapByFile.delete(cleanId);
|
||||
if (
|
||||
registry.size === 0 &&
|
||||
callSites.length === 0 &&
|
||||
subclassWrappers.resolvedWrappers.length === 0
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (runtimeMapEnabled) {
|
||||
runtimeMapByFile.set(cleanId, {
|
||||
messages: used.registry,
|
||||
callSites: used.callSites.map(cs => ({
|
||||
file: cleanId,
|
||||
line: cs.line,
|
||||
column: cs.column,
|
||||
fnName: cs.fnName as RuntimeMapCallSite['fnName'],
|
||||
typeName: cs.typeName,
|
||||
})),
|
||||
});
|
||||
}
|
||||
const used = selectUsedRegistry(
|
||||
registry,
|
||||
callSites,
|
||||
sourceFile,
|
||||
subclassWrappers.extraRootTypeNames,
|
||||
);
|
||||
if (used.registry.size === 0) return null;
|
||||
|
||||
const generatedCode = generateCode(used.registry);
|
||||
const { transformedCode, hasReplacements } = applyReplacements(code, sourceFile, callSites, used.registry);
|
||||
if (!hasReplacements && generatedCode === '') return null;
|
||||
const overrideCode = subclassWrappers.overrideCode;
|
||||
if (!hasReplacements && generatedCode === '' && overrideCode === '') return null;
|
||||
|
||||
return { code: generatedCode + '\n' + transformedCode, map: null };
|
||||
return {
|
||||
code: generatedCode + '\n' + transformedCode + (overrideCode ? '\n' + overrideCode : ''),
|
||||
map: null,
|
||||
};
|
||||
},
|
||||
|
||||
handleHotUpdate({ file }) {
|
||||
if (file.endsWith('.ts')) {
|
||||
fileCache.delete(file);
|
||||
runtimeMapByFile.delete(file);
|
||||
invalidateProgramCache(file);
|
||||
}
|
||||
},
|
||||
|
||||
generateBundle() {
|
||||
if (!runtimeMapEnabled) return;
|
||||
|
||||
const mergedMessages: MessageRegistry = new Map();
|
||||
const mergedCallSites: RuntimeMapCallSite[] = [];
|
||||
|
||||
for (const entry of runtimeMapByFile.values()) {
|
||||
for (const [name, msg] of entry.messages) mergedMessages.set(name, msg);
|
||||
mergedCallSites.push(...entry.callSites);
|
||||
}
|
||||
|
||||
if (mergedMessages.size === 0 || mergedCallSites.length === 0) return;
|
||||
|
||||
const runtimeMap = createRuntimeMap({
|
||||
messages: mergedMessages,
|
||||
callSites: mergedCallSites,
|
||||
});
|
||||
|
||||
this.emitFile({
|
||||
type: 'asset',
|
||||
fileName: runtimeMapFileName,
|
||||
source: JSON.stringify(runtimeMap, null, 2),
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export {
|
||||
analyze,
|
||||
analyzeSource,
|
||||
applyReplacements,
|
||||
generateCode,
|
||||
replaceCallSites,
|
||||
applyReplacements,
|
||||
typeNodeToMangledName,
|
||||
resolveImports,
|
||||
selectUsedRegistry,
|
||||
createRuntimeMap,
|
||||
typeNodeToMangledName,
|
||||
};
|
||||
|
||||
export type { ProtobufRuntimeMap, RuntimeMapCallSite } from './runtime-map.js';
|
||||
@@ -1,71 +0,0 @@
|
||||
import type { MessageRegistry, ProtobufField, ProtobufMessage } from './ast/types.js';
|
||||
|
||||
export type RuntimeMapFnName = 'protobuf_encode' | 'protobuf_decode';
|
||||
|
||||
export interface RuntimeMapCallSite {
|
||||
file: string;
|
||||
line: number;
|
||||
column: number;
|
||||
fnName: RuntimeMapFnName;
|
||||
typeName: string;
|
||||
}
|
||||
|
||||
export interface ProtobufRuntimeMap {
|
||||
version: 1;
|
||||
messages: ProtobufMessage[];
|
||||
callSites: RuntimeMapCallSite[];
|
||||
}
|
||||
|
||||
function cloneField(field: ProtobufField): ProtobufField {
|
||||
return {
|
||||
name: field.name,
|
||||
fieldNumber: field.fieldNumber,
|
||||
typeName: field.typeName,
|
||||
wireType: field.wireType,
|
||||
isMessage: field.isMessage,
|
||||
isOptional: field.isOptional,
|
||||
isRepeated: field.isRepeated,
|
||||
};
|
||||
}
|
||||
|
||||
function cloneMessage(msg: ProtobufMessage): ProtobufMessage {
|
||||
return {
|
||||
name: msg.name,
|
||||
fields: msg.fields.map(cloneField),
|
||||
};
|
||||
}
|
||||
|
||||
export function registryToRuntimeMapMessages(registry: MessageRegistry): ProtobufMessage[] {
|
||||
return [...registry.values()].map(cloneMessage);
|
||||
}
|
||||
|
||||
export function runtimeMapToRegistry(map: ProtobufRuntimeMap): MessageRegistry {
|
||||
const registry: MessageRegistry = new Map();
|
||||
for (const msg of map.messages) {
|
||||
registry.set(msg.name, cloneMessage(msg));
|
||||
}
|
||||
return registry;
|
||||
}
|
||||
|
||||
export function normalizeRuntimeMapPath(filePath: string): string {
|
||||
const noQuery = filePath.replace(/[?#].*$/, '');
|
||||
return noQuery.replace(/\\/g, '/').replace(/^file:\/\//, '');
|
||||
}
|
||||
|
||||
export function createRuntimeMap(map: { messages: MessageRegistry; callSites: RuntimeMapCallSite[] }): ProtobufRuntimeMap {
|
||||
const dedupedCallSites = new Map<string, RuntimeMapCallSite>();
|
||||
for (const cs of map.callSites) {
|
||||
const normalized = {
|
||||
...cs,
|
||||
file: normalizeRuntimeMapPath(cs.file),
|
||||
};
|
||||
const key = `${normalized.file}:${normalized.line}:${normalized.column}:${normalized.fnName}:${normalized.typeName}`;
|
||||
dedupedCallSites.set(key, normalized);
|
||||
}
|
||||
|
||||
return {
|
||||
version: 1,
|
||||
messages: registryToRuntimeMapMessages(map.messages),
|
||||
callSites: [...dedupedCallSites.values()],
|
||||
};
|
||||
}
|
||||
@@ -1,61 +1,15 @@
|
||||
import { buildDependencyRegistry } from './ast/dependency-graph.js';
|
||||
import type { MessageRegistry } from './ast/types.js';
|
||||
import { generateCode } from './codegen/generator.js';
|
||||
import {
|
||||
normalizeRuntimeMapPath,
|
||||
runtimeMapToRegistry,
|
||||
type ProtobufRuntimeMap,
|
||||
type RuntimeMapCallSite,
|
||||
type RuntimeMapFnName,
|
||||
} from './runtime-map.js';
|
||||
|
||||
type DynamicEncode = (params: unknown) => Uint8Array;
|
||||
type DynamicDecode = (data: Uint8Array) => unknown;
|
||||
|
||||
interface DynamicTypeFns {
|
||||
encode?: DynamicEncode;
|
||||
decode?: DynamicDecode;
|
||||
}
|
||||
|
||||
interface StackFrame {
|
||||
file: string;
|
||||
line: number;
|
||||
column: number;
|
||||
}
|
||||
|
||||
const DYNAMIC_MISS = Symbol('snowluma-proton-dynamic-miss');
|
||||
|
||||
let runtimeMapFallback: ProtobufRuntimeMap | null = null;
|
||||
let runtimeMapRegistry: MessageRegistry | null = null;
|
||||
let runtimeMapCallSites: RuntimeMapCallSite[] = [];
|
||||
const dynamicTypeCache = new Map<string, DynamicTypeFns>();
|
||||
|
||||
/**
|
||||
* Enable dynamic runtime fallback from a pre-collected map file.
|
||||
* This is disabled by default.
|
||||
* Runtime stubs.
|
||||
*
|
||||
* `protobuf_encode<T>()` / `protobuf_decode<T>()` are placeholders that
|
||||
* exist only so the user's source type-checks and bundlers don't strip
|
||||
* the import. Every real call site is rewritten by the proton Vite
|
||||
* plugin (`@snowluma/proton/vite`) into a fully-inlined, type-specific
|
||||
* codec call. If the plugin isn't installed, hitting these stubs at
|
||||
* runtime is a bug — we throw loudly rather than silently producing
|
||||
* wrong bytes.
|
||||
*/
|
||||
export function protobuf_enableRuntimeMapFallback(map: ProtobufRuntimeMap): void {
|
||||
runtimeMapFallback = map;
|
||||
runtimeMapRegistry = runtimeMapToRegistry(map);
|
||||
runtimeMapCallSites = map.callSites.map(cs => ({
|
||||
...cs,
|
||||
file: normalizeRuntimeMapPath(cs.file),
|
||||
}));
|
||||
dynamicTypeCache.clear();
|
||||
}
|
||||
|
||||
/** Disable dynamic runtime fallback and clear all generated function caches. */
|
||||
export function protobuf_disableRuntimeMapFallback(): void {
|
||||
runtimeMapFallback = null;
|
||||
runtimeMapRegistry = null;
|
||||
runtimeMapCallSites = [];
|
||||
dynamicTypeCache.clear();
|
||||
}
|
||||
|
||||
export function protobuf_encode<T>(_params: T): Uint8Array {
|
||||
const dynamic = tryDynamicInvoke('protobuf_encode', _params);
|
||||
if (dynamic !== DYNAMIC_MISS) return dynamic as Uint8Array;
|
||||
|
||||
throw new Error(
|
||||
'protobuf_encode<T>() was not transformed by the @snowluma/proton Vite plugin. ' +
|
||||
'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.',
|
||||
@@ -63,152 +17,8 @@ export function protobuf_encode<T>(_params: T): Uint8Array {
|
||||
}
|
||||
|
||||
export function protobuf_decode<T>(_data: Uint8Array): T {
|
||||
const dynamic = tryDynamicInvoke('protobuf_decode', _data);
|
||||
if (dynamic !== DYNAMIC_MISS) return dynamic as T;
|
||||
|
||||
throw new Error(
|
||||
'protobuf_decode<T>() was not transformed by the @snowluma/proton Vite plugin. ' +
|
||||
'Make sure protobufVitePlugin() is added to your vite.config.ts plugins array.',
|
||||
);
|
||||
}
|
||||
|
||||
function tryDynamicInvoke(fnName: RuntimeMapFnName, payload: unknown): unknown {
|
||||
if (!runtimeMapFallback || runtimeMapFallback.version !== 1 || !runtimeMapRegistry) {
|
||||
return DYNAMIC_MISS;
|
||||
}
|
||||
|
||||
const caller = getFirstUserFrame();
|
||||
if (!caller) return DYNAMIC_MISS;
|
||||
|
||||
const callSite = resolveCallSite(fnName, caller);
|
||||
if (!callSite) return DYNAMIC_MISS;
|
||||
|
||||
const typeFns = ensureTypeFunctions(callSite.typeName);
|
||||
if (!typeFns) return DYNAMIC_MISS;
|
||||
|
||||
const fn = fnName === 'protobuf_encode' ? typeFns.encode : typeFns.decode;
|
||||
if (typeof fn !== 'function') return DYNAMIC_MISS;
|
||||
|
||||
return fn(payload as never);
|
||||
}
|
||||
|
||||
function ensureTypeFunctions(typeName: string): DynamicTypeFns | null {
|
||||
const cached = dynamicTypeCache.get(typeName);
|
||||
if (cached) return cached;
|
||||
if (!runtimeMapRegistry || !runtimeMapRegistry.has(typeName)) return null;
|
||||
|
||||
const subset = buildDependencyRegistry(runtimeMapRegistry, [typeName]);
|
||||
if (subset.size === 0) return null;
|
||||
|
||||
const generated = generateCode(subset);
|
||||
if (!generated) return null;
|
||||
|
||||
const factory = new Function(
|
||||
`${generated}\nreturn {\n` +
|
||||
` encode: typeof protobuf_encode_${typeName} === 'function' ? protobuf_encode_${typeName} : undefined,\n` +
|
||||
` decode: typeof protobuf_decode_${typeName} === 'function' ? protobuf_decode_${typeName} : undefined,\n` +
|
||||
`};`,
|
||||
) as () => DynamicTypeFns;
|
||||
|
||||
const compiled = factory();
|
||||
dynamicTypeCache.set(typeName, compiled);
|
||||
return compiled;
|
||||
}
|
||||
|
||||
function resolveCallSite(fnName: RuntimeMapFnName, caller: StackFrame): RuntimeMapCallSite | null {
|
||||
const callerFile = normalizeRuntimeMapPath(caller.file);
|
||||
|
||||
const candidates = runtimeMapCallSites.filter(cs =>
|
||||
cs.fnName === fnName &&
|
||||
cs.line === caller.line &&
|
||||
pathsLikelySame(callerFile, cs.file),
|
||||
);
|
||||
|
||||
if (candidates.length === 0) return null;
|
||||
if (candidates.length === 1) return candidates[0];
|
||||
|
||||
let best = candidates[0];
|
||||
let bestDistance = Math.abs(best.column - caller.column);
|
||||
for (let i = 1; i < candidates.length; i++) {
|
||||
const dist = Math.abs(candidates[i].column - caller.column);
|
||||
if (dist < bestDistance) {
|
||||
best = candidates[i];
|
||||
bestDistance = dist;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function getFirstUserFrame(): StackFrame | null {
|
||||
const err = new Error();
|
||||
if (!err.stack) return null;
|
||||
|
||||
const lines = err.stack.split('\n').slice(1);
|
||||
for (const raw of lines) {
|
||||
const frame = parseStackLine(raw);
|
||||
if (!frame) continue;
|
||||
|
||||
const file = normalizeRuntimeMapPath(frame.file);
|
||||
if (isRuntimeInternalFile(file)) continue;
|
||||
|
||||
return {
|
||||
file,
|
||||
line: frame.line,
|
||||
column: frame.column,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseStackLine(line: string): StackFrame | null {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed) return null;
|
||||
|
||||
let location = trimmed;
|
||||
const atPrefix = 'at ';
|
||||
if (location.startsWith(atPrefix)) {
|
||||
location = location.slice(atPrefix.length).trim();
|
||||
}
|
||||
|
||||
const openParen = location.lastIndexOf('(');
|
||||
if (openParen >= 0 && location.endsWith(')')) {
|
||||
location = location.slice(openParen + 1, -1);
|
||||
}
|
||||
|
||||
const lastColon = location.lastIndexOf(':');
|
||||
if (lastColon < 0) return null;
|
||||
const secondLastColon = location.lastIndexOf(':', lastColon - 1);
|
||||
if (secondLastColon < 0) return null;
|
||||
|
||||
const file = location.slice(0, secondLastColon);
|
||||
const linePart = location.slice(secondLastColon + 1, lastColon);
|
||||
const colPart = location.slice(lastColon + 1);
|
||||
|
||||
const parsedLine = Number(linePart);
|
||||
const parsedCol = Number(colPart);
|
||||
if (!Number.isFinite(parsedLine) || !Number.isFinite(parsedCol)) return null;
|
||||
|
||||
return {
|
||||
file,
|
||||
line: parsedLine,
|
||||
column: parsedCol,
|
||||
};
|
||||
}
|
||||
|
||||
function isRuntimeInternalFile(file: string): boolean {
|
||||
return file.endsWith('/runtime.ts') || file.endsWith('/runtime.js') || file.includes('/dist/runtime.js');
|
||||
}
|
||||
|
||||
function pathsLikelySame(a: string, b: string): boolean {
|
||||
if (a === b) return true;
|
||||
const aBase = basename(a);
|
||||
const bBase = basename(b);
|
||||
return aBase !== '' && aBase === bBase;
|
||||
}
|
||||
|
||||
function basename(file: string): string {
|
||||
const normalized = normalizeRuntimeMapPath(file);
|
||||
const idx = normalized.lastIndexOf('/');
|
||||
return idx >= 0 ? normalized.slice(idx + 1) : normalized;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import ts from 'typescript';
|
||||
import { getProgramForFile } from './program-cache.js';
|
||||
import { resolveSubclassWrappers, WrapperLookupCache, type ResolvedSubclassWrapper } from './subclass-wrapper.js';
|
||||
import { renderSubclassOverride } from '../codegen/subclass-override.js';
|
||||
|
||||
/**
|
||||
* Plugin-facing entry point for the subclass-wrapper feature.
|
||||
*
|
||||
* Pulls the file's TypeChecker (lazily — returns null and short-circuits
|
||||
* if no tsconfig is reachable), walks every class declaration in the
|
||||
* file's program-side SourceFile, runs the subclass resolver against each,
|
||||
* and returns both the resolved wrappers and the extra root type names
|
||||
* that the analyzer pipeline needs to drag into the codec registry.
|
||||
*
|
||||
* The function is intentionally side-effect free: caching of the Program
|
||||
* lives in `program-cache.ts`, and the override text is materialised by
|
||||
* `renderSubclassOverride`. Each call gets a fresh `WrapperLookupCache`
|
||||
* because the underlying detect call is memoised per ClassDeclaration —
|
||||
* the cache only matters across the iterations of a single file's
|
||||
* subclasses (which is exactly what we do here).
|
||||
*/
|
||||
export interface SubclassWrapperPipelineResult {
|
||||
/** All resolved subclass overrides reachable from this file. Empty when
|
||||
* TypeChecker is unavailable, when no class in the file extends a
|
||||
* wrapper-bearing base, or when resolution fails for every candidate. */
|
||||
resolvedWrappers: ResolvedSubclassWrapper[];
|
||||
/** Mangled type names that must be present in the codec registry for the
|
||||
* generated overrides to compile against. Handed to `selectUsedRegistry`
|
||||
* as extra roots. */
|
||||
extraRootTypeNames: string[];
|
||||
/** Rendered override source text, in declaration order. Empty string
|
||||
* when there's nothing to emit. */
|
||||
overrideCode: string;
|
||||
}
|
||||
|
||||
export function runSubclassWrapperPipeline(filePath: string): SubclassWrapperPipelineResult {
|
||||
const empty: SubclassWrapperPipelineResult = {
|
||||
resolvedWrappers: [],
|
||||
extraRootTypeNames: [],
|
||||
overrideCode: '',
|
||||
};
|
||||
|
||||
const programCtx = getProgramForFile(filePath);
|
||||
if (!programCtx) return empty;
|
||||
|
||||
const sf = programCtx.program.getSourceFile(filePath);
|
||||
if (!sf) return empty;
|
||||
|
||||
const cache = new WrapperLookupCache();
|
||||
const allResolved: ResolvedSubclassWrapper[] = [];
|
||||
const extraRoots = new Set<string>();
|
||||
|
||||
for (const stmt of sf.statements) {
|
||||
if (!ts.isClassDeclaration(stmt) || !stmt.name) continue;
|
||||
const resolved = resolveSubclassWrappers(stmt, sf, programCtx.checker, cache);
|
||||
for (const r of resolved) {
|
||||
allResolved.push(r);
|
||||
for (const c of r.resolvedCodecCalls) extraRoots.add(c.resolvedTypeName);
|
||||
}
|
||||
}
|
||||
|
||||
if (allResolved.length === 0) return empty;
|
||||
|
||||
const overrideParts: string[] = [];
|
||||
for (const r of allResolved) {
|
||||
const rendered = renderSubclassOverride(r);
|
||||
if (rendered) overrideParts.push(rendered.code);
|
||||
}
|
||||
|
||||
return {
|
||||
resolvedWrappers: allResolved,
|
||||
extraRootTypeNames: [...extraRoots],
|
||||
overrideCode: overrideParts.join(''),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import ts from 'typescript';
|
||||
import { existsSync } from 'fs';
|
||||
import { dirname, resolve } from 'path';
|
||||
|
||||
/**
|
||||
* Lazy ts.Program cache, keyed by tsconfig path.
|
||||
*
|
||||
* Proton's transform hook runs per-file but the wrapper-pattern feature
|
||||
* needs project-wide type information (extends chains across files,
|
||||
* inferred types on sibling methods, tsconfig path aliases). Building a
|
||||
* fresh Program per call would be cost-prohibitive, so we create one per
|
||||
* tsconfig and reuse it; HMR drops the cache for the affected program so
|
||||
* the next transform rebuilds it.
|
||||
*
|
||||
* Failure modes are deliberately swallowed (returning null): the rest of
|
||||
* the analyzer pipeline must keep working AST-only when no tsconfig is
|
||||
* reachable (typical for the in-repo test fixtures that synthesize file
|
||||
* names with no on-disk presence).
|
||||
*/
|
||||
|
||||
export interface ProgramContext {
|
||||
/** Absolute path to the tsconfig this program was built from. */
|
||||
tsconfigPath: string;
|
||||
program: ts.Program;
|
||||
checker: ts.TypeChecker;
|
||||
}
|
||||
|
||||
interface CacheEntry extends ProgramContext {
|
||||
/** Set of absolute source file paths reachable from this program. */
|
||||
fileSet: Set<string>;
|
||||
}
|
||||
|
||||
const programCache = new Map<string, CacheEntry>();
|
||||
|
||||
/** Cap upward walk; keeps the lookup loop bounded if we end up at a
|
||||
* monorepo root with no tsconfig (rare in this repo, but possible if a
|
||||
* caller hands us a path outside the workspace). */
|
||||
const TSCONFIG_WALK_MAX_DEPTH = 24;
|
||||
|
||||
function findTsconfigUpwards(startDir: string): string | null {
|
||||
let dir = resolve(startDir);
|
||||
for (let i = 0; i < TSCONFIG_WALK_MAX_DEPTH; i++) {
|
||||
const candidate = resolve(dir, 'tsconfig.json');
|
||||
if (existsSync(candidate)) return candidate;
|
||||
const parent = resolve(dir, '..');
|
||||
if (parent === dir) return null;
|
||||
dir = parent;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildProgram(tsconfigPath: string): CacheEntry | null {
|
||||
const configFile = ts.readConfigFile(tsconfigPath, ts.sys.readFile);
|
||||
if (configFile.error) return null;
|
||||
|
||||
const parsedConfig = ts.parseJsonConfigFileContent(
|
||||
configFile.config,
|
||||
ts.sys,
|
||||
dirname(tsconfigPath),
|
||||
);
|
||||
if (parsedConfig.fileNames.length === 0) return null;
|
||||
|
||||
// `noEmit: true` + `skipLibCheck: true` are the two things that pay back
|
||||
// hardest here: we never actually emit (proton does its own codegen) and
|
||||
// the lib check is the single biggest cost factor.
|
||||
const options: ts.CompilerOptions = {
|
||||
...parsedConfig.options,
|
||||
noEmit: true,
|
||||
skipLibCheck: parsedConfig.options.skipLibCheck ?? true,
|
||||
};
|
||||
|
||||
const program = ts.createProgram({
|
||||
rootNames: parsedConfig.fileNames,
|
||||
options,
|
||||
});
|
||||
|
||||
const checker = program.getTypeChecker();
|
||||
const fileSet = new Set<string>();
|
||||
for (const sf of program.getSourceFiles()) {
|
||||
if (!sf.isDeclarationFile) fileSet.add(normalizePath(sf.fileName));
|
||||
}
|
||||
|
||||
return { tsconfigPath, program, checker, fileSet };
|
||||
}
|
||||
|
||||
/** Locate (or build) the program that contains `filePath`. Returns null if
|
||||
* no tsconfig is reachable, or if the file isn't part of any program — in
|
||||
* which case the caller MUST fall back to the AST-only pipeline. */
|
||||
export function getProgramForFile(filePath: string): ProgramContext | null {
|
||||
const tsconfigPath = findTsconfigUpwards(dirname(filePath));
|
||||
if (!tsconfigPath) return null;
|
||||
|
||||
let entry = programCache.get(tsconfigPath);
|
||||
if (!entry) {
|
||||
const built = buildProgram(tsconfigPath);
|
||||
if (!built) return null;
|
||||
entry = built;
|
||||
programCache.set(tsconfigPath, entry);
|
||||
}
|
||||
|
||||
if (!entry.fileSet.has(normalizePath(filePath))) {
|
||||
// File isn't included in this tsconfig (e.g. excluded fixture). The
|
||||
// checker would still answer, but using a Program that doesn't actually
|
||||
// contain the file leads to subtly wrong symbol lookups.
|
||||
return null;
|
||||
}
|
||||
|
||||
return { tsconfigPath: entry.tsconfigPath, program: entry.program, checker: entry.checker };
|
||||
}
|
||||
|
||||
/** Drop the cached program containing `filePath`, or all programs if no
|
||||
* argument is given. Called from the plugin's `handleHotUpdate` hook. */
|
||||
export function invalidateProgramCache(filePath?: string): void {
|
||||
if (!filePath) {
|
||||
programCache.clear();
|
||||
return;
|
||||
}
|
||||
const normalized = normalizePath(filePath);
|
||||
for (const [tsconfigPath, entry] of programCache) {
|
||||
if (entry.fileSet.has(normalized)) {
|
||||
programCache.delete(tsconfigPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function normalizePath(p: string): string {
|
||||
return resolve(p).replace(/\\/g, '/');
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
import ts from 'typescript';
|
||||
import type { ClassWrapperInfo, WrapperCodecCall, WrapperMethodInfo } from '../ast/static-wrapper.js';
|
||||
import { detectClassWrappers } from '../ast/static-wrapper.js';
|
||||
import {
|
||||
createImportedTypeNameResolver,
|
||||
resolveSourceFileForTypeNode,
|
||||
typeNodeToMangledName,
|
||||
} from '../ast/utils.js';
|
||||
|
||||
/**
|
||||
* Subclass-side resolution of inherited wrapper methods.
|
||||
*
|
||||
* Given a subclass that extends an abstract wrapper-bearing base, this
|
||||
* module figures out, for every wrapper method and every codec call inside
|
||||
* its body, what concrete type the wrapper's type-parameter resolves to on
|
||||
* THIS subclass. The answer is then handed to the override generator,
|
||||
* which produces the per-subclass `Sub.method = function(...)` stub.
|
||||
*
|
||||
* Why TypeChecker:
|
||||
* - The base class is virtually always in a different file (and possibly
|
||||
* a different package). Walking the extends chain by AST alone would
|
||||
* re-implement TypeScript's symbol resolution, including module-path
|
||||
* aliases from tsconfig — which is exactly what TypeChecker already
|
||||
* does correctly.
|
||||
* - Subclass-side type extraction sometimes targets methods without
|
||||
* explicit return-type / parameter annotations; TypeChecker fills in
|
||||
* the gap by inferring from the body.
|
||||
* - Multi-level inheritance chains (Sub → MidBase → AbstractBase) work
|
||||
* transparently because TypeChecker resolves each extends edge.
|
||||
*/
|
||||
|
||||
/** Where, in the wrapper's `this: T extends { … }` constraint, the
|
||||
* codec-relevant type parameter is positioned on a member's signature. */
|
||||
export type ResolutionPosition =
|
||||
| { kind: 'returnType' }
|
||||
| { kind: 'paramType'; index: number };
|
||||
|
||||
export interface ResolvedCodecCall extends WrapperCodecCall {
|
||||
/** Mangled name of the resolved concrete type — same shape used by the
|
||||
* rest of the analyzer (`UserMsg`, `Wrapper__string`, …). The override
|
||||
* generator pastes `protobuf_encode_${typeName}` / `protobuf_decode_…`
|
||||
* into the cloned wrapper body in place of the generic form. */
|
||||
resolvedTypeName: string;
|
||||
/** Synthetic TypeNode for the resolved type, suitable for handing to the
|
||||
* monomorphizer. Lives in its own SourceFile via the existing synthetic-
|
||||
* SF registry so subsequent `getText()` / import-resolution calls land
|
||||
* in the right module. */
|
||||
resolvedTypeNode: ts.TypeNode;
|
||||
}
|
||||
|
||||
export interface ResolvedSubclassWrapper {
|
||||
/** The subclass declaration in the file being transformed. */
|
||||
subclass: ts.ClassDeclaration;
|
||||
/** The wrapper-bearing ancestor (one of `subclass`'s direct or transitive
|
||||
* bases). Used so codegen can copy the abstract method body. */
|
||||
wrapperOwner: ts.ClassDeclaration;
|
||||
wrapper: WrapperMethodInfo;
|
||||
/** Each codec call inside the wrapper body, with type parameters
|
||||
* resolved against this specific subclass. */
|
||||
resolvedCodecCalls: ResolvedCodecCall[];
|
||||
}
|
||||
|
||||
/** Walk a subclass's extends chain (via the checker) and return every
|
||||
* wrapper inherited by it, paired with the per-codec-call type resolution.
|
||||
* An empty array means the subclass either doesn't extend anything proton
|
||||
* cares about, or proton couldn't resolve at least one type. */
|
||||
export function resolveSubclassWrappers(
|
||||
subclass: ts.ClassDeclaration,
|
||||
subclassSf: ts.SourceFile,
|
||||
checker: ts.TypeChecker,
|
||||
wrapperCache: WrapperLookupCache,
|
||||
): ResolvedSubclassWrapper[] {
|
||||
const results: ResolvedSubclassWrapper[] = [];
|
||||
const wrappers = collectInheritedWrappers(subclass, checker, wrapperCache);
|
||||
|
||||
for (const { wrapperOwner, wrapper } of wrappers) {
|
||||
const resolvedCodecCalls = resolveWrapperCodecCalls(
|
||||
subclass,
|
||||
subclassSf,
|
||||
wrapperOwner,
|
||||
wrapper,
|
||||
checker,
|
||||
);
|
||||
if (resolvedCodecCalls === null) continue;
|
||||
results.push({ subclass, wrapperOwner, wrapper, resolvedCodecCalls });
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
interface InheritedWrapper {
|
||||
wrapperOwner: ts.ClassDeclaration;
|
||||
wrapper: WrapperMethodInfo;
|
||||
}
|
||||
|
||||
function collectInheritedWrappers(
|
||||
cls: ts.ClassDeclaration,
|
||||
checker: ts.TypeChecker,
|
||||
wrapperCache: WrapperLookupCache,
|
||||
): InheritedWrapper[] {
|
||||
const result: InheritedWrapper[] = [];
|
||||
// Skip `cls` itself: we only override methods inherited from ancestors,
|
||||
// never methods declared directly on the subclass (those are not a
|
||||
// wrapper-pattern subclass at all — they're presumably the abstract base
|
||||
// of yet another hierarchy).
|
||||
let first = true;
|
||||
for (const ancestor of walkExtendsChain(cls, checker)) {
|
||||
if (first) { first = false; continue; }
|
||||
const info = wrapperCache.getOrDetect(ancestor);
|
||||
if (!info) continue;
|
||||
for (const wrapper of info.methods.values()) {
|
||||
result.push({ wrapperOwner: ancestor, wrapper });
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Resolve every codec call inside a wrapper body for one specific
|
||||
* subclass. Returns null if any single codec call fails to resolve — the
|
||||
* override is all-or-nothing because partially-generated code would
|
||||
* reference undefined codec identifiers at runtime. */
|
||||
function resolveWrapperCodecCalls(
|
||||
subclass: ts.ClassDeclaration,
|
||||
subclassSf: ts.SourceFile,
|
||||
wrapperOwner: ts.ClassDeclaration,
|
||||
wrapper: WrapperMethodInfo,
|
||||
checker: ts.TypeChecker,
|
||||
): ResolvedCodecCall[] | null {
|
||||
if (!wrapper.thisConstraint) return null;
|
||||
|
||||
const resolved: ResolvedCodecCall[] = [];
|
||||
for (const codecCall of wrapper.codecCalls) {
|
||||
const position = findTypeParamInConstraint(wrapper.thisConstraint, codecCall.typeParamName);
|
||||
if (!position) return null;
|
||||
|
||||
const typeNode = extractSubclassMemberTypeNode(
|
||||
subclass,
|
||||
subclassSf,
|
||||
position.memberName,
|
||||
position.position,
|
||||
checker,
|
||||
);
|
||||
if (!typeNode) return null;
|
||||
|
||||
const typeName = computeMangledName(typeNode, subclassSf);
|
||||
if (!typeName) return null;
|
||||
|
||||
resolved.push({
|
||||
...codecCall,
|
||||
resolvedTypeName: typeName,
|
||||
resolvedTypeNode: typeNode,
|
||||
});
|
||||
// Suppress unused-variable warning while wrapperOwner is reserved for
|
||||
// future cross-file diagnostics on chain-resolution failure.
|
||||
void wrapperOwner;
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
|
||||
/** Inspect a `{ memberName: (params) => returnType }` literal and locate
|
||||
* the property whose signature references `typeParamName`. Returns the
|
||||
* member name plus where on its signature the type appears. */
|
||||
interface ConstraintHit {
|
||||
memberName: string;
|
||||
position: ResolutionPosition;
|
||||
}
|
||||
|
||||
function findTypeParamInConstraint(constraint: ts.TypeNode, typeParamName: string): ConstraintHit | null {
|
||||
if (!ts.isTypeLiteralNode(constraint)) return null;
|
||||
|
||||
for (const member of constraint.members) {
|
||||
if (!ts.isPropertySignature(member) || !member.type) continue;
|
||||
const memberName = getPropertyNameText(member.name);
|
||||
if (!memberName) continue;
|
||||
const fnType = member.type;
|
||||
if (!ts.isFunctionTypeNode(fnType)) continue;
|
||||
|
||||
if (fnType.type && isBareTypeRef(fnType.type, typeParamName)) {
|
||||
return { memberName, position: { kind: 'returnType' } };
|
||||
}
|
||||
for (let i = 0; i < fnType.parameters.length; i++) {
|
||||
const p = fnType.parameters[i];
|
||||
if (p.type && isBareTypeRef(p.type, typeParamName)) {
|
||||
return { memberName, position: { kind: 'paramType', index: i } };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isBareTypeRef(node: ts.TypeNode, name: string): boolean {
|
||||
if (!ts.isTypeReferenceNode(node)) return false;
|
||||
if (!ts.isIdentifier(node.typeName)) return false;
|
||||
return node.typeName.text === name;
|
||||
}
|
||||
|
||||
function getPropertyNameText(name: ts.PropertyName): string | null {
|
||||
if (ts.isIdentifier(name)) return name.text;
|
||||
if (ts.isStringLiteral(name)) return name.text;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Pull a type out of a subclass member's signature at the requested
|
||||
* position. Prefers the explicit annotation when present; falls back to
|
||||
* the TypeChecker's inferred type otherwise. */
|
||||
function extractSubclassMemberTypeNode(
|
||||
subclass: ts.ClassDeclaration,
|
||||
subclassSf: ts.SourceFile,
|
||||
memberName: string,
|
||||
position: ResolutionPosition,
|
||||
checker: ts.TypeChecker,
|
||||
): ts.TypeNode | null {
|
||||
for (const member of subclass.members) {
|
||||
if (!ts.isMethodDeclaration(member)) continue;
|
||||
const mods = ts.getModifiers(member);
|
||||
if (!mods?.some(m => m.kind === ts.SyntaxKind.StaticKeyword)) continue;
|
||||
if (!ts.isIdentifier(member.name) || member.name.text !== memberName) continue;
|
||||
|
||||
if (position.kind === 'returnType') {
|
||||
if (member.type) return member.type;
|
||||
const sig = checker.getSignatureFromDeclaration(member);
|
||||
if (!sig) return null;
|
||||
const ret = checker.getReturnTypeOfSignature(sig);
|
||||
return typeToTypeNode(ret, member, checker);
|
||||
}
|
||||
|
||||
const param = member.parameters[position.index];
|
||||
if (!param) return null;
|
||||
if (param.type) return param.type;
|
||||
const type = checker.getTypeAtLocation(param);
|
||||
return typeToTypeNode(type, member, checker);
|
||||
}
|
||||
|
||||
// Suppress unused-variable warning while subclassSf is reserved for
|
||||
// future diagnostics that print source positions.
|
||||
void subclassSf;
|
||||
return null;
|
||||
}
|
||||
|
||||
function typeToTypeNode(type: ts.Type, enclosing: ts.Node, checker: ts.TypeChecker): ts.TypeNode | null {
|
||||
return checker.typeToTypeNode(
|
||||
type,
|
||||
enclosing,
|
||||
ts.NodeBuilderFlags.NoTruncation | ts.NodeBuilderFlags.UseFullyQualifiedType,
|
||||
) ?? null;
|
||||
}
|
||||
|
||||
/** Walk the extends chain in source order, yielding the class declaration
|
||||
* for each level. Uses the checker so cross-file edges and tsconfig path
|
||||
* aliases resolve correctly. */
|
||||
function* walkExtendsChain(
|
||||
cls: ts.ClassDeclaration,
|
||||
checker: ts.TypeChecker,
|
||||
): IterableIterator<ts.ClassDeclaration> {
|
||||
let current: ts.ClassDeclaration | null = cls;
|
||||
const seen = new Set<ts.ClassDeclaration>();
|
||||
|
||||
while (current && !seen.has(current)) {
|
||||
seen.add(current);
|
||||
yield current;
|
||||
|
||||
const ext = current.heritageClauses?.find(h => h.token === ts.SyntaxKind.ExtendsKeyword);
|
||||
const heritageExpr = ext?.types[0]?.expression;
|
||||
if (!heritageExpr) break;
|
||||
|
||||
const symbol = checker.getSymbolAtLocation(heritageExpr);
|
||||
if (!symbol) break;
|
||||
|
||||
// When the parent is imported, `getSymbolAtLocation` lands on the
|
||||
// import-alias symbol; the class declaration lives on the aliased
|
||||
// target symbol. Resolve through the alias before reading
|
||||
// declarations — otherwise cross-file inheritance never finds the
|
||||
// base class.
|
||||
const targetSymbol = (symbol.flags & ts.SymbolFlags.Alias)
|
||||
? checker.getAliasedSymbol(symbol)
|
||||
: symbol;
|
||||
|
||||
const decls = targetSymbol.getDeclarations();
|
||||
if (!decls) break;
|
||||
const parentDecl = decls.find((d): d is ts.ClassDeclaration => ts.isClassDeclaration(d));
|
||||
if (!parentDecl) break;
|
||||
current = parentDecl;
|
||||
}
|
||||
}
|
||||
|
||||
/** Map a resolved TypeNode to the mangled name proton's generator expects.
|
||||
* Routes through `typeNodeToMangledName` so primitives, generics, and
|
||||
* synthetic-SF-registered nodes all share the same shape used elsewhere
|
||||
* in the analyzer. */
|
||||
function computeMangledName(node: ts.TypeNode, fallbackSf: ts.SourceFile): string | null {
|
||||
// If the node was produced by TypeChecker (synthetic), the synthetic-SF
|
||||
// registry already has the right context; for explicit annotations the
|
||||
// node is part of the subclass's own SourceFile, which is what we hand
|
||||
// in as the fallback.
|
||||
const effectiveSf = resolveSourceFileForTypeNode(node, fallbackSf);
|
||||
const resolver = createImportedTypeNameResolver(effectiveSf);
|
||||
try {
|
||||
return typeNodeToMangledName(node, effectiveSf, resolver);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-program cache of wrapper detection results. The same abstract base
|
||||
* gets re-discovered for every subclass it has, so memoizing on the class
|
||||
* declaration node keeps the cost flat as the number of subclasses grows.
|
||||
*/
|
||||
export class WrapperLookupCache {
|
||||
private readonly map = new WeakMap<ts.ClassDeclaration, ClassWrapperInfo | null>();
|
||||
|
||||
getOrDetect(cls: ts.ClassDeclaration): ClassWrapperInfo | null {
|
||||
if (this.map.has(cls)) return this.map.get(cls)!;
|
||||
const sf = cls.getSourceFile();
|
||||
const info = detectClassWrappers(cls, sf);
|
||||
this.map.set(cls, info);
|
||||
return info;
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import protobufVitePlugin from '../../src/index';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { analyze, analyzeSource, selectUsedRegistry } from '../../src/ast/analyzer';
|
||||
import { generateCode } from '../../src/codegen/generator';
|
||||
import { replaceCallSites } from '../../src/transform/replacer';
|
||||
import { loadFixture, execAndGet } from '../helpers';
|
||||
import { execAndGet, loadFixture } from '../helpers';
|
||||
|
||||
describe('plugin integration', () => {
|
||||
it('full transform pipeline', () => {
|
||||
@@ -215,93 +214,4 @@ const buf = protobuf_encode<UsedMsg>({ inner: { id: 1 } });
|
||||
expect(gen).not.toContain('protobuf_encode_UnusedMsg');
|
||||
});
|
||||
|
||||
it('emits runtime map asset when runtimeMap is enabled', () => {
|
||||
const code = `
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
|
||||
interface Msg { id: pb<1, uint_32>; }
|
||||
const buf = protobuf_encode<Msg>({ id: 1 });
|
||||
`;
|
||||
|
||||
const plugin = protobufVitePlugin({
|
||||
runtimeMap: {
|
||||
enabled: true,
|
||||
fileName: 'pb.runtime-map.json',
|
||||
},
|
||||
});
|
||||
|
||||
const transformHook = plugin.transform!;
|
||||
const transform = typeof transformHook === 'function' ? transformHook : transformHook.handler;
|
||||
const transformResult = transform.call({} as any, code, 'entry.ts');
|
||||
expect(transformResult).toBeTruthy();
|
||||
|
||||
const emitted: any[] = [];
|
||||
const generateHook = plugin.generateBundle!;
|
||||
const generateBundle = typeof generateHook === 'function' ? generateHook : generateHook.handler;
|
||||
const testContext: any = {
|
||||
emitFile(asset: any) {
|
||||
emitted.push(asset);
|
||||
return 'asset-id';
|
||||
},
|
||||
};
|
||||
|
||||
generateBundle.call(
|
||||
testContext,
|
||||
{} as any,
|
||||
{} as any,
|
||||
false,
|
||||
);
|
||||
|
||||
expect(emitted).toHaveLength(1);
|
||||
expect(emitted[0].type).toBe('asset');
|
||||
expect(emitted[0].fileName).toBe('pb.runtime-map.json');
|
||||
|
||||
const payload = JSON.parse(emitted[0].source);
|
||||
expect(payload.version).toBe(1);
|
||||
expect(payload.callSites).toHaveLength(1);
|
||||
expect(payload.callSites[0].fnName).toBe('protobuf_encode');
|
||||
expect(payload.callSites[0].typeName).toBe('Msg');
|
||||
});
|
||||
|
||||
it('emits canonical runtime map entries for imported type aliases', () => {
|
||||
const code = `
|
||||
import { protobuf_encode, protobuf_decode } from '@snowluma/proton';
|
||||
import type { UserMsg as AliasMsg } from './types';
|
||||
|
||||
const buf = protobuf_encode<AliasMsg>({ id: 1, name: 'a' });
|
||||
const decoded = protobuf_decode<AliasMsg>(buf);
|
||||
`;
|
||||
|
||||
const plugin = protobufVitePlugin({
|
||||
runtimeMap: {
|
||||
enabled: true,
|
||||
fileName: 'pb.runtime-map.json',
|
||||
},
|
||||
});
|
||||
|
||||
const transformHook = plugin.transform!;
|
||||
const transform = typeof transformHook === 'function' ? transformHook : transformHook.handler;
|
||||
const transformResult = transform.call({} as any, code, 'test/fixtures/cross-file/aliased-consumer.ts');
|
||||
expect(transformResult).toBeTruthy();
|
||||
|
||||
const emitted: any[] = [];
|
||||
const generateHook = plugin.generateBundle!;
|
||||
const generateBundle = typeof generateHook === 'function' ? generateHook : generateHook.handler;
|
||||
const testContext: any = {
|
||||
emitFile(asset: any) {
|
||||
emitted.push(asset);
|
||||
return 'asset-id';
|
||||
},
|
||||
};
|
||||
|
||||
generateBundle.call(testContext, {} as any, {} as any, false);
|
||||
|
||||
expect(emitted).toHaveLength(1);
|
||||
const payload = JSON.parse(emitted[0].source);
|
||||
expect(payload.messages.some((msg: { name: string }) => msg.name === 'UserMsg')).toBe(true);
|
||||
expect(payload.messages.some((msg: { name: string }) => msg.name === 'AliasMsg')).toBe(false);
|
||||
expect(payload.callSites).toHaveLength(2);
|
||||
expect(payload.callSites[0].typeName).toBe('UserMsg');
|
||||
expect(payload.callSites[1].typeName).toBe('UserMsg');
|
||||
});
|
||||
});
|
||||
@@ -1,98 +0,0 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { analyzeSource } from '../../src/ast/analyzer';
|
||||
import { createRuntimeMap } from '../../src/runtime-map';
|
||||
import {
|
||||
protobuf_decode,
|
||||
protobuf_disableRuntimeMapFallback,
|
||||
protobuf_enableRuntimeMapFallback,
|
||||
protobuf_encode,
|
||||
} from '../../src/runtime';
|
||||
|
||||
function captureFrameFromThrow(fn: () => unknown, sourceFile: string): { line: number; column: number } {
|
||||
try {
|
||||
fn();
|
||||
} catch (err) {
|
||||
const stack = err instanceof Error ? err.stack ?? '' : '';
|
||||
for (const raw of stack.split('\n')) {
|
||||
const line = raw.trim();
|
||||
if (!line.includes(sourceFile)) continue;
|
||||
|
||||
const location = line.endsWith(')') && line.includes('(')
|
||||
? line.slice(line.lastIndexOf('(') + 1, -1)
|
||||
: line.replace(/^at\s+/, '');
|
||||
|
||||
const lastColon = location.lastIndexOf(':');
|
||||
const secondLastColon = location.lastIndexOf(':', lastColon - 1);
|
||||
if (lastColon < 0 || secondLastColon < 0) continue;
|
||||
|
||||
const parsedLine = Number(location.slice(secondLastColon + 1, lastColon));
|
||||
const parsedColumn = Number(location.slice(lastColon + 1));
|
||||
if (Number.isFinite(parsedLine) && Number.isFinite(parsedColumn)) {
|
||||
return { line: parsedLine, column: parsedColumn };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Unable to capture stack frame for ${sourceFile}`);
|
||||
}
|
||||
|
||||
function invokeEncode(): Uint8Array {
|
||||
return new Function(
|
||||
'protobuf_encode',
|
||||
`\n//# sourceURL=runtime-map-encode.js\nreturn protobuf_encode({ value: 7 });`,
|
||||
)(protobuf_encode) as Uint8Array;
|
||||
}
|
||||
|
||||
function invokeDecode(data: Uint8Array): any {
|
||||
return new Function(
|
||||
'protobuf_decode',
|
||||
'data',
|
||||
`\n//# sourceURL=runtime-map-decode.js\nreturn protobuf_decode(data);`,
|
||||
)(protobuf_decode, data);
|
||||
}
|
||||
|
||||
describe('runtime map fallback', () => {
|
||||
afterEach(() => {
|
||||
protobuf_disableRuntimeMapFallback();
|
||||
});
|
||||
|
||||
it('dynamically generates encode/decode from runtime map when enabled', () => {
|
||||
const schema = `
|
||||
interface SimpleMsg {
|
||||
value: pb<1, uint_32>;
|
||||
}
|
||||
`;
|
||||
const registry = analyzeSource(schema, 'schema.ts');
|
||||
|
||||
const encodeFrame = captureFrameFromThrow(invokeEncode, 'runtime-map-encode.js');
|
||||
const decodeFrame = captureFrameFromThrow(() => invokeDecode(new Uint8Array([0x08, 0x07])), 'runtime-map-decode.js');
|
||||
|
||||
const runtimeMap = createRuntimeMap({
|
||||
messages: registry,
|
||||
callSites: [
|
||||
{
|
||||
file: 'runtime-map-encode.js',
|
||||
line: encodeFrame.line,
|
||||
column: encodeFrame.column,
|
||||
fnName: 'protobuf_encode',
|
||||
typeName: 'SimpleMsg',
|
||||
},
|
||||
{
|
||||
file: 'runtime-map-decode.js',
|
||||
line: decodeFrame.line,
|
||||
column: decodeFrame.column,
|
||||
fnName: 'protobuf_decode',
|
||||
typeName: 'SimpleMsg',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
protobuf_enableRuntimeMapFallback(runtimeMap);
|
||||
|
||||
const encoded = invokeEncode();
|
||||
expect([...encoded]).toEqual([0x08, 0x07]);
|
||||
|
||||
const decoded = invokeDecode(encoded);
|
||||
expect(decoded.value).toBe(7);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,243 @@
|
||||
import { readFileSync } from 'fs';
|
||||
import { dirname, resolve } from 'path';
|
||||
import ts from 'typescript';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { detectClassWrappersInFile } from '../../src/ast/static-wrapper';
|
||||
import { renderSubclassOverride } from '../../src/codegen/subclass-override';
|
||||
import protobufVitePlugin from '../../src/index';
|
||||
import { runSubclassWrapperPipeline } from '../../src/typecheck/file-pipeline';
|
||||
import { getProgramForFile, invalidateProgramCache } from '../../src/typecheck/program-cache';
|
||||
import { WrapperLookupCache, resolveSubclassWrappers } from '../../src/typecheck/subclass-wrapper';
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const fixturePath = resolve(here, 'wrapper-fixtures', 'packet-transformer.ts');
|
||||
|
||||
function loadFixture(): string {
|
||||
return readFileSync(fixturePath, 'utf-8');
|
||||
}
|
||||
|
||||
describe('static-wrapper detection (AST)', () => {
|
||||
it('detects encode + decode wrappers on the abstract base', () => {
|
||||
const code = loadFixture();
|
||||
const sf = ts.createSourceFile(fixturePath, code, ts.ScriptTarget.Latest, true);
|
||||
const wrappers = detectClassWrappersInFile(sf);
|
||||
|
||||
expect(wrappers.has('PacketTransformer')).toBe(true);
|
||||
const base = wrappers.get('PacketTransformer')!;
|
||||
expect(base.methods.has('encode')).toBe(true);
|
||||
expect(base.methods.has('decode')).toBe(true);
|
||||
|
||||
const encode = base.methods.get('encode')!;
|
||||
expect(encode.typeParamNames).toContain('R');
|
||||
expect(encode.typeParamNames).toContain('T');
|
||||
expect(encode.codecCalls).toHaveLength(1);
|
||||
expect(encode.codecCalls[0]).toMatchObject({
|
||||
fnName: 'protobuf_encode',
|
||||
typeParamName: 'R',
|
||||
});
|
||||
|
||||
const decode = base.methods.get('decode')!;
|
||||
expect(decode.codecCalls).toHaveLength(1);
|
||||
expect(decode.codecCalls[0]).toMatchObject({
|
||||
fnName: 'protobuf_decode',
|
||||
typeParamName: 'B',
|
||||
});
|
||||
});
|
||||
|
||||
it('returns no wrappers for a class without protobuf type-param usage', () => {
|
||||
const code = `
|
||||
class NotAWrapper {
|
||||
static helper<X>(value: X): X { return value; }
|
||||
}
|
||||
`;
|
||||
const sf = ts.createSourceFile('not-a-wrapper.ts', code, ts.ScriptTarget.Latest, true);
|
||||
const wrappers = detectClassWrappersInFile(sf);
|
||||
expect(wrappers.size).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('subclass wrapper resolution (TypeChecker)', () => {
|
||||
it('resolves R for DemoTransformer.encode through the serialize return type', () => {
|
||||
invalidateProgramCache();
|
||||
const programCtx = getProgramForFile(fixturePath);
|
||||
if (!programCtx) {
|
||||
throw new Error('TypeChecker program unavailable for fixture');
|
||||
}
|
||||
const sf = programCtx.program.getSourceFile(fixturePath)!;
|
||||
expect(sf).toBeDefined();
|
||||
|
||||
const subclass = sf.statements.find(
|
||||
(s): s is ts.ClassDeclaration => ts.isClassDeclaration(s) && s.name?.text === 'DemoTransformer',
|
||||
)!;
|
||||
|
||||
const cache = new WrapperLookupCache();
|
||||
const resolved = resolveSubclassWrappers(subclass, sf, programCtx.checker, cache);
|
||||
expect(resolved).toHaveLength(2);
|
||||
|
||||
const encode = resolved.find(r => r.wrapper.methodName === 'encode')!;
|
||||
expect(encode.resolvedCodecCalls).toHaveLength(1);
|
||||
expect(encode.resolvedCodecCalls[0]).toMatchObject({
|
||||
fnName: 'protobuf_encode',
|
||||
resolvedTypeName: 'DemoRequestPb',
|
||||
});
|
||||
|
||||
const decode = resolved.find(r => r.wrapper.methodName === 'decode')!;
|
||||
expect(decode.resolvedCodecCalls).toHaveLength(1);
|
||||
expect(decode.resolvedCodecCalls[0]).toMatchObject({
|
||||
fnName: 'protobuf_decode',
|
||||
resolvedTypeName: 'DemoResponsePb',
|
||||
});
|
||||
});
|
||||
|
||||
it('renders the per-subclass override as JS-flavoured TS', () => {
|
||||
invalidateProgramCache();
|
||||
const programCtx = getProgramForFile(fixturePath)!;
|
||||
const sf = programCtx.program.getSourceFile(fixturePath)!;
|
||||
const subclass = sf.statements.find(
|
||||
(s): s is ts.ClassDeclaration => ts.isClassDeclaration(s) && s.name?.text === 'DemoTransformer',
|
||||
)!;
|
||||
|
||||
const cache = new WrapperLookupCache();
|
||||
const resolved = resolveSubclassWrappers(subclass, sf, programCtx.checker, cache);
|
||||
const encode = resolved.find(r => r.wrapper.methodName === 'encode')!;
|
||||
const rendered = renderSubclassOverride(encode);
|
||||
expect(rendered).not.toBeNull();
|
||||
expect(rendered!.code).toContain('DemoTransformer.encode = function');
|
||||
expect(rendered!.code).toContain('protobuf_encode_DemoRequestPb');
|
||||
expect(rendered!.code).not.toContain('protobuf_encode<R>');
|
||||
});
|
||||
});
|
||||
|
||||
describe('file-pipeline (end-to-end)', () => {
|
||||
it('produces extra root names + override code for the demo subclass', () => {
|
||||
invalidateProgramCache();
|
||||
const result = runSubclassWrapperPipeline(fixturePath);
|
||||
|
||||
expect(result.extraRootTypeNames).toEqual(
|
||||
expect.arrayContaining(['DemoRequestPb', 'DemoResponsePb']),
|
||||
);
|
||||
expect(result.overrideCode).toContain('DemoTransformer.encode = function');
|
||||
expect(result.overrideCode).toContain('DemoTransformer.decode = function');
|
||||
expect(result.overrideCode).toContain('protobuf_encode_DemoRequestPb');
|
||||
expect(result.overrideCode).toContain('protobuf_decode_DemoResponsePb');
|
||||
});
|
||||
|
||||
it('returns an empty result when no class in the file extends a wrapper', () => {
|
||||
invalidateProgramCache();
|
||||
// Re-use an existing test file that has no transformer classes.
|
||||
const otherFile = resolve(here, 'plugin.test.ts');
|
||||
const result = runSubclassWrapperPipeline(otherFile);
|
||||
expect(result.resolvedWrappers).toHaveLength(0);
|
||||
expect(result.extraRootTypeNames).toHaveLength(0);
|
||||
expect(result.overrideCode).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('cross-file inheritance', () => {
|
||||
const subclassFile = resolve(here, 'wrapper-fixtures', 'subclass-transformer.ts');
|
||||
|
||||
it('walks the extends edge into a separate module and resolves wrappers', () => {
|
||||
invalidateProgramCache();
|
||||
const result = runSubclassWrapperPipeline(subclassFile);
|
||||
expect(result.extraRootTypeNames).toEqual(
|
||||
expect.arrayContaining(['FooRequestPb', 'FooResponsePb']),
|
||||
);
|
||||
expect(result.overrideCode).toContain('FooTransformer.enc = function');
|
||||
expect(result.overrideCode).toContain('FooTransformer.dec = function');
|
||||
expect(result.overrideCode).toContain('protobuf_encode_FooRequestPb');
|
||||
expect(result.overrideCode).toContain('protobuf_decode_FooResponsePb');
|
||||
});
|
||||
|
||||
it('does not generate overrides on the abstract base file itself', () => {
|
||||
invalidateProgramCache();
|
||||
const baseFile = resolve(here, 'wrapper-fixtures', 'base-transformer.ts');
|
||||
const result = runSubclassWrapperPipeline(baseFile);
|
||||
// No subclasses defined in the base file → no overrides emitted there.
|
||||
expect(result.resolvedWrappers).toHaveLength(0);
|
||||
expect(result.overrideCode).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('plugin transform integration', () => {
|
||||
function runPluginOnFixture(): string {
|
||||
invalidateProgramCache();
|
||||
const plugin = protobufVitePlugin();
|
||||
const code = loadFixture();
|
||||
const transformHook = plugin.transform!;
|
||||
const transformFn = typeof transformHook === 'function' ? transformHook : transformHook.handler;
|
||||
const result = transformFn.call({} as never, code, fixturePath);
|
||||
return (result as { code: string }).code;
|
||||
}
|
||||
|
||||
it('appends concrete codecs + per-subclass overrides to the fixture output', () => {
|
||||
const out = runPluginOnFixture();
|
||||
|
||||
// Concrete codecs got generated for the types extracted from
|
||||
// serialize/deserialize annotations.
|
||||
expect(out).toContain('protobuf_encode_DemoRequestPb');
|
||||
expect(out).toContain('protobuf_decode_DemoResponsePb');
|
||||
|
||||
// Per-subclass overrides replace the inherited abstract bodies.
|
||||
expect(out).toContain('DemoTransformer.encode = function');
|
||||
expect(out).toContain('DemoTransformer.decode = function');
|
||||
|
||||
// The original abstract body's `protobuf_encode<R>` form is left alone
|
||||
// (the analyzer skips type-param call-sites). It only appears once —
|
||||
// in the abstract method body — not in the generated override.
|
||||
const overrideMatches = out.match(/protobuf_encode<R>/g);
|
||||
expect(overrideMatches?.length).toBe(1);
|
||||
});
|
||||
|
||||
/** Transpile the plugin output to plain ES2022, then strip the module
|
||||
* syntax so `new Function()` can eval it. We use the ESNext module
|
||||
* setting (rather than None / CJS, which would leak `exports`
|
||||
* references the eval context doesn't have) and just delete the
|
||||
* resulting `import` / `export` lines — exports are unused at this
|
||||
* layer because we reach the class through its identifier, not through
|
||||
* a module namespace. */
|
||||
function toPlainJs(tsOut: string): string {
|
||||
const jsOut = ts.transpileModule(tsOut, {
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },
|
||||
}).outputText;
|
||||
return jsOut
|
||||
.replace(/^\s*import [^;]+;\s*$/gm, '')
|
||||
.replace(/^\s*export\s+\{[^}]*\};?\s*$/gm, '')
|
||||
.replace(/^export\s+(default\s+)?/gm, '$1')
|
||||
.replace(/^export\s+/gm, '');
|
||||
}
|
||||
|
||||
it('end-to-end: override actually invokes the concrete codec at runtime', () => {
|
||||
const stripped = toPlainJs(runPluginOnFixture());
|
||||
|
||||
const harness = `
|
||||
${stripped}
|
||||
const bytes = DemoTransformer.encode(undefined, { param: 42 });
|
||||
const decoded = protobuf_decode_DemoRequestPb(bytes);
|
||||
globalThis.__r = { bytesLength: bytes.length, decoded };
|
||||
`;
|
||||
new Function(harness)();
|
||||
const r = (globalThis as unknown as { __r: { bytesLength: number; decoded: { param: number; id: number } } }).__r;
|
||||
delete (globalThis as unknown as { __r?: unknown }).__r;
|
||||
|
||||
expect(r.bytesLength).toBeGreaterThan(0);
|
||||
expect(r.decoded).toEqual({ param: 42, id: 123 });
|
||||
});
|
||||
|
||||
it('end-to-end: decode override forwards the bytes through deserialize', () => {
|
||||
const stripped = toPlainJs(runPluginOnFixture());
|
||||
|
||||
const harness = `
|
||||
${stripped}
|
||||
// Build a response payload using the concrete encoder, then feed it
|
||||
// through the subclass's generated decode override.
|
||||
const responseBytes = protobuf_encode_DemoResponsePb({ result: 7, id: 99 });
|
||||
globalThis.__r = DemoTransformer.decode(undefined, responseBytes);
|
||||
`;
|
||||
new Function(harness)();
|
||||
const r = (globalThis as unknown as { __r: { result: number } }).__r;
|
||||
delete (globalThis as unknown as { __r?: unknown }).__r;
|
||||
|
||||
expect(r.result).toBe(7);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
// Cross-file fixture: the abstract base lives in this module and is
|
||||
// imported + extended by `subclass-transformer.ts`. Exercises the
|
||||
// TypeChecker's ability to walk an extends chain across file boundaries.
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
|
||||
export abstract class CrossFileBase {
|
||||
static enc<R, T extends { build: (ctx: unknown, p: never) => R }>(
|
||||
this: T,
|
||||
ctx: unknown,
|
||||
params: T['build'] extends (ctx: unknown, p: infer P) => R ? P : never,
|
||||
): Uint8Array {
|
||||
const payload = (this as unknown as { build: (c: unknown, p: never) => R }).build(ctx, params as never);
|
||||
return protobuf_encode<R>(payload);
|
||||
}
|
||||
|
||||
static dec<B, Res, T extends { parse: (ctx: unknown, body: B) => Res }>(
|
||||
this: T,
|
||||
ctx: unknown,
|
||||
bytes: Uint8Array,
|
||||
): Res {
|
||||
const decoded = protobuf_decode<B>(bytes);
|
||||
return (this as unknown as { parse: (c: unknown, b: B) => Res }).parse(ctx, decoded);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// Fixture for the subclass-wrapper TypeChecker pipeline tests.
|
||||
// Mirrors the user's PacketTransformer pattern verbatim so the resolver +
|
||||
// override generator can be exercised end-to-end.
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { int_32, pb } from '@snowluma/proton';
|
||||
|
||||
export interface StaticPacketTransformer<RPCParams, RPCResult, Params, Result> {
|
||||
readonly command: string;
|
||||
serialize(ctx: unknown, params: Params): RPCParams;
|
||||
deserialize(ctx: unknown, body: RPCResult): Result;
|
||||
}
|
||||
|
||||
export abstract class PacketTransformer {
|
||||
static encode<
|
||||
R,
|
||||
T extends { serialize: (ctx: unknown, params: never) => R }
|
||||
>(
|
||||
this: T,
|
||||
ctx: unknown,
|
||||
params: T['serialize'] extends (ctx: unknown, p: infer P) => R ? P : never,
|
||||
) {
|
||||
const rpcData = this.serialize(ctx, params as never);
|
||||
return protobuf_encode<R>(rpcData);
|
||||
}
|
||||
|
||||
static decode<
|
||||
B,
|
||||
Res,
|
||||
T extends { deserialize: (ctx: unknown, body: B) => Res }
|
||||
>(
|
||||
this: T,
|
||||
ctx: unknown,
|
||||
bytes: Uint8Array,
|
||||
): Res {
|
||||
const oIdbPackage = protobuf_decode<B>(bytes);
|
||||
return this.deserialize(ctx, oIdbPackage);
|
||||
}
|
||||
}
|
||||
|
||||
interface rsq {
|
||||
param: number;
|
||||
}
|
||||
interface rsq_pb {
|
||||
param: pb<3, int_32>;
|
||||
id: pb<1, int_32>;
|
||||
}
|
||||
interface rps {
|
||||
result: number;
|
||||
}
|
||||
interface rps_pb {
|
||||
result: pb<1, int_32>;
|
||||
id: pb<2, int_32>;
|
||||
}
|
||||
|
||||
export class DemoTransformer extends PacketTransformer {
|
||||
static readonly command = 'trpc.qq_new_tech.OidbSvcTrpcTcp.0x112e_1';
|
||||
|
||||
static serialize(_ctx: unknown, params: rsq): rsq_pb {
|
||||
return {
|
||||
param: params.param,
|
||||
id: 123,
|
||||
};
|
||||
}
|
||||
|
||||
static deserialize(_ctx: unknown, body: rps_pb): rps {
|
||||
console.log('Deserializing response with id:', body.id);
|
||||
return {
|
||||
result: body.result || 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
DemoTransformer.encode(undefined, { param: 42 });
|
||||
@@ -0,0 +1,34 @@
|
||||
// Cross-file fixture: imports the abstract base from `base-transformer.ts`
|
||||
// and supplies the concrete sibling methods. The plugin's pipeline must
|
||||
// resolve the extends edge across the file boundary via the TypeChecker
|
||||
// and still emit per-subclass overrides here.
|
||||
import type { int_32, pb } from '@snowluma/proton';
|
||||
import { CrossFileBase } from './base-transformer';
|
||||
|
||||
export interface FooRequestPb {
|
||||
value: pb<1, int_32>;
|
||||
}
|
||||
|
||||
export interface FooResponsePb {
|
||||
ok: pb<1, int_32>;
|
||||
}
|
||||
|
||||
export interface FooRequest {
|
||||
value: number;
|
||||
}
|
||||
|
||||
export interface FooResponse {
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
export class FooTransformer extends CrossFileBase {
|
||||
static readonly command = 'foo.cmd';
|
||||
|
||||
static build(_ctx: unknown, params: FooRequest): FooRequestPb {
|
||||
return { value: params.value };
|
||||
}
|
||||
|
||||
static parse(_ctx: unknown, body: FooResponsePb): FooResponse {
|
||||
return { ok: (body.ok ?? 0) > 0 };
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user