From 9960695bc85f4020295518755acfcf8e5f166c4d Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 12 Jul 2026 03:25:10 +0800 Subject: [PATCH] Add domain layer: errors, result, hopper values, symbol analysis --- src/domain/errors.ts | 73 ++++++++++++++++++++ src/domain/hopperValues.ts | 128 +++++++++++++++++++++++++++++++++++ src/domain/result.ts | 10 +++ src/domain/symbolAnalysis.ts | 108 +++++++++++++++++++++++++++++ 4 files changed, 319 insertions(+) create mode 100644 src/domain/errors.ts create mode 100644 src/domain/hopperValues.ts create mode 100644 src/domain/result.ts create mode 100644 src/domain/symbolAnalysis.ts diff --git a/src/domain/errors.ts b/src/domain/errors.ts new file mode 100644 index 000000000..e65f61c09 --- /dev/null +++ b/src/domain/errors.ts @@ -0,0 +1,73 @@ +/** Base class for expected Hopper integration failures. */ +export abstract class HopperError extends Error { + abstract readonly _tag: string; +} + +/** Hopper did not respond within the configured operation deadline. */ +export class HopperTimeoutError extends HopperError { + readonly _tag = "HopperTimeoutError"; + + constructor(readonly timeoutMs: number) { + super(`Hopper did not respond within ${String(timeoutMs)}ms`); + } +} + +/** The caller cancelled a Hopper operation before it completed. */ +export class HopperCancelledError extends HopperError { + readonly _tag = "HopperCancelledError"; + + constructor() { + super("Hopper operation was cancelled"); + } +} + +/** Hopper returned bytes or JSON that do not satisfy the NDJSON RPC contract. */ +export class HopperProtocolError extends HopperError { + readonly _tag = "HopperProtocolError"; +} + +/** Hopper's JSON-RPC endpoint returned an expected remote error response. */ +export class HopperRemoteError extends HopperError { + readonly _tag = "HopperRemoteError"; + + constructor( + readonly code: number, + readonly safeMessage: string, + ) { + super(`Hopper request failed (${String(code)}): ${safeMessage}`); + } +} + +/** The owned Hopper bridge stopped before its client was closed. */ +export class HopperProcessError extends HopperError { + readonly _tag = "HopperProcessError"; + + constructor(readonly exitCode: number | null) { + super(`Hopper bridge stopped unexpectedly with code ${String(exitCode)}`); + } +} + +/** Hopper did not make the repository bridge available after launch. */ +export class HopperUnavailableError extends HopperError { + readonly _tag = "HopperUnavailableError"; + + constructor() { + super( + "Hopper did not start the analysis bridge. Check the target and loader architecture options, then retry.", + ); + } +} + +/** Hopper or the repository bridge could not be started. */ +export class HopperStartError extends HopperError { + readonly _tag = "HopperStartError"; + + constructor(options?: ErrorOptions) { + super("Hopper application bridge could not be started", options); + } +} + +/** Runtime configuration could not be parsed safely. */ +export class ConfigurationError extends HopperError { + readonly _tag = "ConfigurationError"; +} diff --git a/src/domain/hopperValues.ts b/src/domain/hopperValues.ts new file mode 100644 index 000000000..adc28b017 --- /dev/null +++ b/src/domain/hopperValues.ts @@ -0,0 +1,128 @@ +import { z } from "zod"; + +import type { JsonValue } from "../hopper/protocol.js"; +import { HopperProtocolError } from "./errors.js"; +import { err, ok, type Result } from "./result.js"; + +export interface AddressedName { + readonly address: string; + readonly name: string; +} + +export interface SegmentSummary { + readonly name: string; + readonly start: string; + readonly end: string; +} + +const procedureMapSchema = z.record(z.string(), z.string()); +const addressedNamesSchema = z.array( + z.object({ address: z.string(), name: z.string() }), +); +const addressedNameMapSchema = z.record(z.string(), z.string()); +const segmentSchema = z.object({ + name: z.string().default(""), + start: z.string().default(""), + end: z.string().default(""), +}); + +/** Parse Hopper's direct or wrapped procedure map into stable entries. */ +export const parseProcedures = ( + value: JsonValue, +): Result => { + const parsed = procedureMapSchema.safeParse( + unwrapProperty(value, "procedures"), + ); + return parsed.success + ? ok( + Object.entries(parsed.data).map(([address, name]) => ({ + address, + name, + })), + ) + : invalid("procedure map", parsed.error); +}; + +/** Parse Hopper's direct or wrapped list of address/name records. */ +export const parseNames = ( + value: JsonValue, +): Result => { + const unwrapped = unwrapProperty(value, "names"); + const records = addressedNamesSchema.safeParse(unwrapped); + if (records.success) return ok(records.data); + const map = addressedNameMapSchema.safeParse(unwrapped); + return map.success + ? ok(Object.entries(map.data).map(([address, name]) => ({ address, name }))) + : invalid("name list", map.error); +}; + +/** Parse callee/caller strings from direct or wrapped Hopper results. */ +export const parseRelatedAddresses = ( + value: JsonValue, + relation: "callees" | "callers", +): Result => { + const parsed = z.array(z.string()).safeParse(unwrapProperty(value, relation)); + return parsed.success + ? ok(parsed.data) + : invalid(`${relation} list`, parsed.error); +}; + +/** Parse direct or wrapped Hopper segment records. */ +export const parseSegments = ( + value: JsonValue, +): Result => { + const parsed = z + .array(segmentSchema) + .safeParse(unwrapProperty(value, "segments")); + return parsed.success + ? ok(parsed.data) + : invalid("segment list", parsed.error); +}; + +/** Parse direct or wrapped Hopper document names. */ +export const parseDocuments = ( + value: JsonValue, +): Result => { + const parsed = z + .array(z.string()) + .safeParse(unwrapProperty(value, "documents")); + return parsed.success + ? ok(parsed.data) + : invalid("document list", parsed.error); +}; + +/** Parse a direct or wrapped list when only its cardinality is required. */ +export const parseListCount = ( + value: JsonValue, + property: string, +): Result => { + const unwrapped = unwrapProperty(value, property); + const list = z.array(z.unknown()).safeParse(unwrapped); + if (list.success) return ok(list.data.length); + const map = z.record(z.string(), z.unknown()).safeParse(unwrapped); + return map.success + ? ok(Object.keys(map.data).length) + : invalid(`${property} list`, map.error); +}; + +const unwrapProperty = (value: JsonValue, property: string): JsonValue => { + if ( + typeof value === "object" && + value !== null && + !Array.isArray(value) && + property in value + ) { + return value[property] ?? null; + } + return value; +}; + +const invalid = ( + expected: string, + cause: z.ZodError, +): Result => + err( + new HopperProtocolError(`Hopper returned an invalid ${expected}`, { + cause, + }), + ); diff --git a/src/domain/result.ts b/src/domain/result.ts new file mode 100644 index 000000000..cf7cb0789 --- /dev/null +++ b/src/domain/result.ts @@ -0,0 +1,10 @@ +/** A typed channel for expected success or failure. */ +export type Result = + | { readonly ok: true; readonly value: T } + | { readonly ok: false; readonly error: E }; + +/** Construct a successful result. */ +export const ok = (value: T): Result => ({ ok: true, value }); + +/** Construct a failed result. */ +export const err = (error: E): Result => ({ ok: false, error }); diff --git a/src/domain/symbolAnalysis.ts b/src/domain/symbolAnalysis.ts new file mode 100644 index 000000000..c47aebb0b --- /dev/null +++ b/src/domain/symbolAnalysis.ts @@ -0,0 +1,108 @@ +import type { JsonValue } from "../hopper/protocol.js"; +import type { AddressedName } from "./hopperValues.js"; + +const MAX_SCANNED_SYMBOLS = 5_000; +const MAX_RETURNED_SYMBOLS = 100; + +/** Select Swift class symbols using the legacy `_TtC` convention. */ +export const discoverSwiftClasses = ( + procedures: readonly AddressedName[], + pattern: string, +): JsonValue => { + const classes = procedures + .slice(0, MAX_SCANNED_SYMBOLS) + .filter(({ name }) => name.includes("_TtC")) + .filter(({ name }) => pattern.length === 0 || name.includes(pattern)); + return { + count: classes.length, + classes: classes.slice(0, MAX_RETURNED_SYMBOLS).map(toJsonEntry), + }; +}; + +/** Select and deduplicate Objective-C class labels. */ +export const discoverObjcClasses = ( + names: readonly AddressedName[], + pattern: string, +): JsonValue => { + const classes = uniqueByName( + names + .filter( + ({ name }) => + ["OBJC_CLASS", "OBJC_$_CLASS"].some((marker) => + name.includes(marker), + ) || name.startsWith("_OBJC_"), + ) + .filter(({ name }) => pattern.length === 0 || name.includes(pattern)), + ); + return { + count: classes.length, + classes: classes.slice(0, MAX_RETURNED_SYMBOLS).map(toJsonEntry), + }; +}; + +/** Select and deduplicate Objective-C and Swift protocol labels. */ +export const discoverObjcProtocols = ( + names: readonly AddressedName[], +): JsonValue => { + const protocols = uniqueByName( + names.filter( + ({ name }) => name.includes("OBJC_PROTOCOL") || name.includes("_TtP"), + ), + ); + return { + count: protocols.length, + protocols: protocols.slice(0, MAX_RETURNED_SYMBOLS).map(toJsonEntry), + }; +}; + +const SWIFT_CATEGORIES = [ + ["classes", "_TtC"], + ["structs", "_TtV"], + ["enums", "_TtO"], + ["protocols", "_TtP"], + ["extensions", "_TtE"], +] as const; + +/** Categorize deduplicated Swift mangled symbols. */ +export const categorizeSwiftTypes = ( + procedures: readonly AddressedName[], +): JsonValue => { + const groups: Record = Object.fromEntries( + [...SWIFT_CATEGORIES.map(([category]) => category), "other"].map( + (category) => [category, []], + ), + ); + const seen = new Set(); + + for (const entry of procedures.slice(0, MAX_SCANNED_SYMBOLS)) { + if (!entry.name.includes("_Tt") || seen.has(entry.name)) continue; + seen.add(entry.name); + const category = + SWIFT_CATEGORIES.find(([, prefix]) => + entry.name.startsWith(prefix), + )?.[0] ?? "other"; + groups[category]?.push(entry); + } + + const categories = Object.fromEntries( + Object.entries(groups).map(([category, items]) => [ + category, + { count: items.length, items: items.slice(0, 50).map(toJsonEntry) }, + ]), + ); + return { total: seen.size, categories }; +}; + +const uniqueByName = (entries: readonly AddressedName[]): AddressedName[] => { + const seen = new Set(); + return entries.filter(({ name }) => { + if (seen.has(name)) return false; + seen.add(name); + return true; + }); +}; + +const toJsonEntry = ({ address, name }: AddressedName): JsonValue => ({ + address, + name, +});