Merge branch 'feat/dylib-resolution' into feat/dyld-shared-cache

Carry #952's Apple ownership into the cache work: the cache reader and
fixture move to src/artifacts/apple/, the cache facts, platforms and
resolution schema to src/domain/apple/, the cache service to
src/application/apple/, and the lane to scripts/verify/apple/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kaoru0822
2026-10-07 13:32:48 +00:00
co-authored by Claude Opus 5.5
90 changed files with 1354 additions and 289 deletions
@@ -1,43 +0,0 @@
import { describe, expect, it } from "vitest";
import { collectInterfaceBuilderResourceKeys } from "./AppleAssetCatalogAnalysis.js";
describe("Apple asset catalog application workflow", () => {
it("joins only explicit resource-key fields with archive provenance", () => {
expect(
collectInterfaceBuilderResourceKeys([
{
id: "ib:Main.nib:object:2",
kind: "resource",
name: "Decorative image",
attributes: {
imageName: "Toolbar",
title: "not-an-asset-key",
image: 42,
},
evidence: [
{
artifact_path: "Contents/Resources/Main.nib",
artifact_sha256: "d".repeat(64),
},
],
},
{
id: "ib:Main.nib:object:3",
kind: "control",
name: "Toolbar",
attributes: { title: "not-an-asset-key" },
evidence: [],
},
]),
).toEqual([
{
sourceNodeId: "ib:Main.nib:object:2",
sourcePath: "Contents/Resources/Main.nib",
sourceArchiveSha256: "d".repeat(64),
field: "imageName",
key: "Toolbar",
},
]);
});
});
@@ -1,267 +0,0 @@
import { createHash } from "node:crypto";
import { lstat } from "node:fs/promises";
import { DirectoryArtifactReader } from "../artifacts/DirectoryArtifactReader.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
import {
appleAssetCatalogInputSchema,
parseAppleAssetCatalogRecords,
projectAppleAssetCatalogPage,
} from "../domain/appleAssetCatalog.js";
import { execFileOutput } from "../process/ExecFileOutput.js";
const ASSETUTIL = "/usr/bin/assetutil";
const MAX_CATALOG_BYTES = 64 * 1024 * 1024;
const MAX_TOTAL_METADATA_BYTES = 64 * 1024 * 1024;
const RESOURCE_KEY_FIELDS = new Set([
"image",
"imageName",
"image_name",
"resourceName",
"resource_name",
"assetName",
"asset_name",
"UIImageName",
"NSImageName",
]);
/** Inspect compiled asset catalog metadata without extracting rendition bytes. */
export const analyzeAppleAssetCatalogs = async (input: {
readonly bundlePath: string;
readonly targetSha256: string;
readonly page?: unknown;
readonly signal?: AbortSignal;
readonly runAssetUtil?: (
path: string,
signal?: AbortSignal,
) => Promise<string>;
}) => {
if (process.platform !== "darwin" && input.runAssetUtil === undefined)
throw new ArtifactReaderFailure(
"unavailable",
"Apple asset catalog inspection requires macOS assetutil",
);
const page = appleAssetCatalogInputSchema.parse(input.page ?? {});
const reader = new DirectoryArtifactReader(input.bundlePath);
const catalogs: {
path: string;
sha256: string;
records: ReturnType<typeof parseAppleAssetCatalogRecords>;
}[] = [];
let totalMetadataBytes = 0;
try {
for await (const entry of reader.entries(input.signal)) {
if (entry.kind !== "file" || !entry.path.endsWith("Assets.car")) continue;
const inspected = await inspectAssetCatalogEntry({
reader,
entry,
runAssetUtil: input.runAssetUtil ?? runAssetUtil,
...(input.signal === undefined ? {} : { signal: input.signal }),
});
totalMetadataBytes += inspected.metadataBytes;
if (totalMetadataBytes > MAX_TOTAL_METADATA_BYTES)
throw new ArtifactReaderFailure(
"limit",
`Combined asset catalog metadata exceeds ${MAX_TOTAL_METADATA_BYTES} bytes`,
);
catalogs.push(inspected.catalog);
}
} finally {
await reader.close();
}
if (catalogs.length === 0)
throw new ArtifactReaderFailure(
"unavailable",
"No compiled Assets.car catalogs were found in the app bundle",
);
const interfaceBuilder = await analyzeInterfaceBuilderBundle({
bundlePath: input.bundlePath,
targetSha256: input.targetSha256,
...(input.signal === undefined ? {} : { signal: input.signal }),
});
const resourceReferences = collectInterfaceBuilderResourceKeys(
interfaceBuilder.graph.nodes,
);
const result = projectAppleAssetCatalogPage({
targetSha256: input.targetSha256,
catalogs,
offset: page.offset,
limit: page.limit,
resourceReferences,
});
return {
...result,
limitations: [
...result.limitations,
"Exact resource-key joins use only recognized image or asset key fields on decoded Interface Builder resource objects; other archive resource references are not inferred.",
...(interfaceBuilder.graph.truncated
? [
"Interface Builder resource-key joins may be incomplete because the decoded UI graph was truncated.",
]
: []),
],
};
};
const inspectAssetCatalogEntry = async (input: {
readonly reader: DirectoryArtifactReader;
readonly entry: import("../artifacts/ArtifactReader.js").ArtifactEntry;
readonly runAssetUtil: (
path: string,
signal?: AbortSignal,
) => Promise<string>;
readonly signal?: AbortSignal;
}) => {
const { entry, reader, signal } = input;
const sha256 = await digestBounded(reader, entry, signal);
const before = await lstat(entry.adapterKey);
if (
entry.sourceIdentity === undefined ||
before.dev !== entry.sourceIdentity.device ||
before.ino !== entry.sourceIdentity.inode
)
throw new ArtifactReaderFailure(
"integrity",
`Asset catalog changed before inspection: ${entry.path}`,
);
const output = await input.runAssetUtil(entry.adapterKey, signal);
const after = await lstat(entry.adapterKey);
if (
before.dev !== after.dev ||
before.ino !== after.ino ||
before.size !== after.size ||
(await digestBounded(reader, entry, signal)) !== sha256
)
throw new ArtifactReaderFailure(
"integrity",
`Asset catalog changed during inspection: ${entry.path}`,
);
let parsed: unknown;
try {
parsed = JSON.parse(output);
} catch (cause: unknown) {
throw new ArtifactReaderFailure(
"format",
`assetutil returned invalid JSON for ${entry.path}`,
{ cause },
);
}
try {
return {
catalog: {
path: entry.path,
sha256,
records: parseAppleAssetCatalogRecords(parsed),
},
metadataBytes: Buffer.byteLength(output, "utf8"),
};
} catch (cause: unknown) {
throw new ArtifactReaderFailure(
"format",
`assetutil returned an unsupported record for ${entry.path}`,
{ cause },
);
}
};
/** Return only explicit image or asset fields from decoded resource objects. */
export const collectInterfaceBuilderResourceKeys = (
nodes: readonly {
readonly id: string;
readonly kind: string;
readonly name?: string;
readonly attributes: Readonly<Record<string, unknown>>;
readonly evidence: readonly {
readonly artifact_path: string | null;
readonly artifact_sha256: string | null;
}[];
}[],
) =>
nodes.flatMap((node) => {
const source = node.evidence.find(
(item) => item.artifact_path !== null && item.artifact_sha256 !== null,
);
const sourcePath = source?.artifact_path;
const sourceArchiveSha256 = source?.artifact_sha256;
if (sourcePath == null || sourceArchiveSha256 == null) return [];
return Object.entries(node.attributes).flatMap(([field, value]) =>
RESOURCE_KEY_FIELDS.has(field) &&
typeof value === "string" &&
value.length > 0
? [
{
sourceNodeId: node.id,
sourcePath,
sourceArchiveSha256,
field,
key: value,
},
]
: [],
);
});
const runAssetUtil = async (
path: string,
signal?: AbortSignal,
): Promise<string> => {
try {
return (
await execFileOutput(ASSETUTIL, ["--info", path], {
timeout: 60_000,
maxBuffer: MAX_CATALOG_BYTES,
...(signal === undefined ? {} : { signal }),
})
).stdout;
} catch (cause: unknown) {
if (signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Asset catalog inspection cancelled",
);
const code =
typeof cause === "object" && cause !== null && "code" in cause
? cause.code
: undefined;
throw new ArtifactReaderFailure(
code === "ENOENT"
? "unavailable"
: code === "ETIMEDOUT" || code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"
? "limit"
: "io",
`assetutil failed${code === undefined ? "" : ` (${String(code)})`}`,
{ cause },
);
}
};
const digestBounded = async (
reader: DirectoryArtifactReader,
entry: import("../artifacts/ArtifactReader.js").ArtifactEntry,
signal?: AbortSignal,
): Promise<string> => {
if (entry.declaredSize === null || entry.declaredSize > MAX_CATALOG_BYTES)
throw new ArtifactReaderFailure(
"limit",
`Asset catalog exceeds ${MAX_CATALOG_BYTES} bytes: ${entry.path}`,
);
const stream = await reader.open(entry, signal);
const hash = createHash("sha256");
let length = 0;
for await (const chunk of stream) {
if (signal?.aborted === true)
throw new ArtifactReaderFailure(
"cancelled",
"Asset catalog inspection cancelled",
);
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
length += bytes.length;
if (length > MAX_CATALOG_BYTES)
throw new ArtifactReaderFailure(
"limit",
`Asset catalog exceeds byte limit: ${entry.path}`,
);
hash.update(bytes);
}
return hash.digest("hex");
};
-413
View File
@@ -1,413 +0,0 @@
import { createHash } from "node:crypto";
import { parseBinary } from "plist";
import { DirectoryArtifactReader } from "../artifacts/DirectoryArtifactReader.js";
import { projectPlistValue } from "../domain/plistValue.js";
import {
omittedPrototypeKeysLimitation,
parseXmlPropertyList,
} from "../domain/propertyListKeys.js";
import {
decodeNibArchive,
type NibArchiveDocument,
} from "../artifacts/NibArchive.js";
import type { ArtifactEntry } from "../artifacts/ArtifactReader.js";
import {
buildInterfaceBuilderAnalysis,
interfaceBuilderLimitsSchema,
type InterfaceBuilderDocumentInput,
} from "../domain/interfaceBuilderGraph.js";
import {
mergeNibHierarchies,
projectNibViewHierarchy,
type NibHierarchyNode,
} from "./NibViewHierarchy.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
const MAX_DOCUMENT_BYTES = 64 * 1024 * 1024;
/** Decode compiled Interface Builder archives from a local app bundle. */
export const analyzeInterfaceBuilderBundle = async (input: {
readonly bundlePath: string;
readonly targetSha256: string;
readonly limits?: unknown;
readonly signal?: AbortSignal;
}) => {
const limits = interfaceBuilderLimitsSchema.parse(input.limits ?? {});
const reader = new DirectoryArtifactReader(input.bundlePath);
const documents: InterfaceBuilderDocumentInput[] = [];
const invalid: string[] = [];
const incompleteHierarchies = new Map<string, number>();
const prototypeKeyOmissions = new Map<string, number>();
let omitted = 0;
let attempted = 0;
try {
for await (const entry of reader.entries(input.signal)) {
if (entry.kind !== "file" || !isInterfaceBuilderArchive(entry.path))
continue;
if (attempted >= limits.max_documents) {
omitted += 1;
continue;
}
attempted += 1;
try {
const bytes = await readEntry(reader, entry, input.signal);
const nib =
bytes.subarray(0, 10).toString("ascii") === "NIBArchive"
? projectNibArchive(decodeNibArchive(bytes))
: null;
const { value: raw, omittedPrototypeKeys } =
nib === null
? decodePlist(bytes)
: { value: nib.raw, omittedPrototypeKeys: 0 };
if (nib !== null && nib.omitted > 0)
incompleteHierarchies.set(entry.path, nib.omitted);
if (omittedPrototypeKeys > 0)
prototypeKeyOmissions.set(entry.path, omittedPrototypeKeys);
const documentHash = createHash("sha256").update(bytes).digest("hex");
documents.push({
relativePath: entry.path,
archiveSha256: documentHash,
documentKind: entry.path.includes(".storyboardc/")
? "storyboard_scene"
: "nib",
raw,
});
} catch (cause: unknown) {
if (input.signal?.aborted === true) throw cause;
invalid.push(
`${entry.path}: ${cause instanceof Error ? cause.message : "archive decode failed"}`,
);
}
}
} finally {
await reader.close();
}
const result = buildInterfaceBuilderAnalysis({
targetSha256: input.targetSha256,
toolVersion: "rea-interface-builder/1",
documents,
limits,
});
return finalizeHierarchyCoverage(result, {
incompleteHierarchies,
prototypeKeyOmissions,
invalid,
attempted,
omitted,
});
};
const finalizeHierarchyCoverage = (
result: ReturnType<typeof buildInterfaceBuilderAnalysis>,
counts: {
incompleteHierarchies: ReadonlyMap<string, number>;
prototypeKeyOmissions: ReadonlyMap<string, number>;
invalid: readonly string[];
attempted: number;
omitted: number;
},
) => {
const { incompleteHierarchies, prototypeKeyOmissions, invalid } = counts;
const archiveDecodePartial =
invalid.length > 0 || prototypeKeyOmissions.size > 0;
return {
...result,
documents: result.documents.map((document) => ({
...document,
hierarchy_complete:
document.hierarchy_complete &&
!incompleteHierarchies.has(document.relative_path),
})),
graph: {
...result.graph,
coverage: [
...result.graph.coverage.map((facet) => {
const omitted = incompleteHierarchies.get(
facet.facet.replace(/^hierarchy:/u, ""),
);
return facet.facet.startsWith("hierarchy:") && omitted !== undefined
? {
...facet,
status: "partial" as const,
reason: "serialized_view_hierarchy_incomplete",
omitted: facet.omitted + omitted,
}
: facet;
}),
{
facet: "archive_decode",
status: archiveDecodePartial
? ("partial" as const)
: ("complete" as const),
reason:
invalid.length > 0
? "one_or_more_archives_invalid"
: prototypeKeyOmissions.size > 0
? "dictionary_entries_omitted"
: null,
examined: counts.attempted,
omitted: counts.omitted,
},
],
truncated:
result.graph.truncated ||
counts.omitted > 0 ||
archiveDecodePartial ||
incompleteHierarchies.size > 0,
},
limitations: [
...result.limitations,
"Compiled Interface Builder archives are private serialized object graphs. The decoder reports only recognized keyed-archive objects and connections; unrecognized object classes and fields remain unknown.",
...(incompleteHierarchies.size === 0
? []
: [
"Some serialized hierarchy links could not be projected within the bounded hierarchy; their parentage remains unknown.",
]),
...(invalid.length === 0
? []
: [
`Some Interface Builder archives could not be decoded: ${invalid.slice(0, 16).join("; ")}`,
]),
...[...prototypeKeyOmissions].map(
([path, count]) => `${path}: ${omittedPrototypeKeysLimitation(count)}`,
),
],
};
};
/** Project decoded NIB records into the same bounded graph input as ibtool. */
const projectNibArchive = (archive: NibArchiveDocument) => {
const byId = new Map(archive.objects.map((object) => [object.id, object]));
const dereference = (value: JsonValue | undefined): JsonValue | undefined => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return value;
const ref = value.$nib_object_ref;
if (typeof ref !== "number") return value;
const target = byId.get(ref);
if (target === undefined) return undefined;
if (target.class_name.replace(/\0+$/u, "") === "NSString") {
const data = target.values["NS.bytes"];
if (typeof data === "object" && data !== null && !Array.isArray(data)) {
const encoded = data.$nib_data_base64;
if (typeof encoded === "string")
return Buffer.from(encoded, "base64").toString("utf8");
}
}
return { objectID: String(ref) };
};
const referencedString = (value: JsonValue | undefined): string | null => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return null;
const ref = value.$nib_object_ref;
if (typeof ref !== "number") return null;
const target = byId.get(ref);
const data = target?.values["NS.bytes"];
if (target?.class_name.replace(/\0+$/u, "") !== "NSString") return null;
if (typeof data !== "object" || data === null || Array.isArray(data))
return null;
const encoded = data.$nib_data_base64;
return typeof encoded === "string"
? Buffer.from(encoded, "base64").toString("utf8")
: null;
};
const runtimeClass = (objectId: number): string | null => {
const object = byId.get(objectId);
if (object === undefined) return null;
const storedClass = object.class_name.replace(/\0+$/u, "");
if (storedClass === "NSClassSwapper")
return referencedString(object.values.NSClassName) ?? storedClass;
return storedClass === "UIClassSwapper"
? (referencedString(object.values.UIClassName) ?? storedClass)
: storedClass;
};
const objects = Object.fromEntries(
archive.objects
.filter((object) => {
const name = runtimeClass(object.id) ?? "";
return !/^(?:NSObject|NSIBObjectData|NSString|NSMutableString|NSNumber|NSArray|NSMutableArray|NSSet|NSMutableSet|NSDictionary|NSMutableDictionary|NSApplication|NSNib.*Connector|UIRuntime\w*Connection)$/u.test(
name,
);
})
.map((object) => {
const className =
runtimeClass(object.id) ?? object.class_name.replace(/\0+$/u, "");
const strings = Object.entries(object.values).flatMap(
([key, value]) => {
const resolved = dereference(value);
return typeof resolved === "string" ? [[key, resolved]] : [];
},
);
const name =
strings.find(([key]) =>
/(?:title|label|identifier|accessibility|name|contents)/iu.test(
key ?? "",
),
)?.[1] ?? className;
return [
String(object.id),
{
customClass: className,
label: name,
objectID: String(object.id),
nibValues: Object.fromEntries(
Object.entries(object.values).map(([key, value]) => [
key,
dereference(value) ?? null,
]),
),
},
];
}),
);
const connections: Record<string, JsonValue[]> = {};
const hierarchy: NibHierarchyNode[] = [];
const reference = (value: JsonValue | undefined): number | null => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return null;
return typeof value.$nib_object_ref === "number"
? value.$nib_object_ref
: null;
};
for (const object of archive.objects) {
const className = object.class_name.replace(/\0+$/u, "");
// AppKit connectors use NS-prefixed keys; UIKit's runtime outlet and
// event connections use UI-prefixed keys with the same roles.
const uiKit = /^UIRuntime\w*Connection$/u.test(className);
if (!uiKit && !className.includes("Connector")) continue;
const values = object.values;
const source = reference(uiKit ? values.UISource : values.NSSource);
if (source === null) continue;
const destination = reference(
uiKit ? values.UIDestination : values.NSDestination,
);
const label = referencedString(uiKit ? values.UILabel : values.NSLabel);
const type = className.includes("Outlet")
? "outlet"
: className.includes("Control") || className.includes("Event")
? "action"
: className;
const eventMask = values.UIEventMask;
// The source is the outlet owner or the sending control; the destination
// is the outlet value or the action target, and a nil target is the
// first responder.
(connections[String(source)] ??= []).push({
type,
"destination-id": destination === null ? null : String(destination),
label,
source_id: String(source),
archive_object_id: String(object.id),
...(typeof eventMask === "number" ? { ui_event_mask: eventMask } : {}),
});
}
let hierarchyOmitted = 0;
const hierarchyFor = (
objectId: number,
seen: Set<number>,
depth: number,
): NibHierarchyNode | null => {
if (depth > 32 || seen.has(objectId)) {
hierarchyOmitted += 1;
return null;
}
const object = byId.get(objectId);
if (object === undefined) {
hierarchyOmitted += 1;
return null;
}
const nextSeen = new Set(seen).add(objectId);
const children: NibHierarchyNode[] = [];
for (const [key, value] of Object.entries(object.values)) {
if (!/(?:subviews|contentview|childviewcontrollers|view)$/iu.test(key))
continue;
const direct = reference(value);
if (direct === null) continue;
const target = byId.get(direct);
if (target === undefined) {
hierarchyOmitted += 1;
continue;
}
if (/array|set/iu.test(target.class_name)) {
for (const candidate of Object.values(target.values)) {
const child = reference(candidate);
const nested =
child === null ? null : hierarchyFor(child, nextSeen, depth + 1);
if (nested !== null) children.push(nested);
}
} else {
const nested = hierarchyFor(direct, nextSeen, depth + 1);
if (nested !== null) children.push(nested);
}
}
return { objectID: String(objectId), children };
};
const ibData = archive.objects.find(
({ class_name }) => class_name.replace(/\0+$/u, "") === "NSIBObjectData",
);
const rootId = reference(ibData?.values.NSRoot);
const hierarchyRoots = rootId === null ? [] : [rootId];
for (const hierarchyRoot of hierarchyRoots) {
const root = hierarchyFor(hierarchyRoot, new Set(), 0);
if (root !== null) hierarchy.push(root);
}
const viewHierarchy = projectNibViewHierarchy(
archive.objects,
new Set(Object.keys(objects).map(Number)),
);
const merged = mergeNibHierarchies(hierarchy, viewHierarchy.hierarchy ?? []);
return {
omitted: viewHierarchy.omitted + hierarchyOmitted + merged.omitted,
raw: jsonValueSchema.parse({
"com.apple.ibtool.document.objects": objects,
"com.apple.ibtool.document.connections": connections,
"com.apple.ibtool.document.hierarchy": merged.hierarchy,
"com.apple.ibtool.document.classes": Object.fromEntries(
archive.classes.map((name) => [name.replace(/\0+$/u, ""), {}]),
),
}),
};
};
const isInterfaceBuilderArchive = (path: string): boolean => {
const lower = path.toLowerCase();
return lower.endsWith(".nib") || lower.endsWith("/objects.nib");
};
const readEntry = async (
reader: DirectoryArtifactReader,
entry: ArtifactEntry,
signal?: AbortSignal,
): Promise<Buffer> => {
if (entry.declaredSize !== null && entry.declaredSize > MAX_DOCUMENT_BYTES)
throw new RangeError(
"archive exceeds the 64 MiB per-document decode limit",
);
const stream = await reader.open(entry, signal);
const chunks: Buffer[] = [];
let length = 0;
for await (const chunk of stream) {
const bytes = Buffer.isBuffer(chunk)
? chunk
: Buffer.from(chunk as Uint8Array);
length += bytes.length;
if (length > MAX_DOCUMENT_BYTES) {
stream.destroy();
throw new RangeError(
"archive exceeded the 64 MiB per-document decode limit",
);
}
chunks.push(bytes);
}
return Buffer.concat(chunks, length);
};
/** Project decoded plist data and dates while retaining omitted-key coverage. */
const decodePlist = (
bytes: Buffer,
): { readonly value: JsonValue; readonly omittedPrototypeKeys: number } => {
const { value, omittedPrototypeKeys } =
bytes.subarray(0, 8).toString("ascii") === "bplist00"
? { value: parseBinary(bytes), omittedPrototypeKeys: 0 }
: parseXmlPropertyList(bytes.toString("utf8"));
return { value: projectPlistValue(value).value, omittedPrototypeKeys };
};
+1 -1
View File
@@ -3,7 +3,7 @@ import { z } from "zod";
import type { AnalysisOperationPort } from "./AnalysisProvider.js";
import type { EnhancedResult } from "./EnhancedToolTypes.js";
import type { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
import { interfaceBuilderAnalysisSchema } from "../domain/interfaceBuilderGraph.js";
import { interfaceBuilderAnalysisSchema } from "../domain/apple/interfaceBuilderGraph.js";
import {
nativeInvestigationGraphSchema,
nativeInvestigationTraceSchema,
-189
View File
@@ -1,189 +0,0 @@
import { describe, expect, it } from "vitest";
import {
mergeNibHierarchies,
projectNibViewHierarchy,
} from "./NibViewHierarchy.js";
const object = (id: number, parent?: number) => ({
id,
class_name: "NSView",
values:
parent === undefined ? {} : { NSSuperview: { $nib_object_ref: parent } },
});
describe("serialized NIB view hierarchy bounds", () => {
it("leaves archives without superview links to the legacy projection", () => {
expect(projectNibViewHierarchy([object(0)], new Set([0]))).toEqual({
hierarchy: null,
omitted: 0,
});
});
it("uses the serialized parent direction and retains all sibling links", () => {
expect(
projectNibViewHierarchy(
[object(0), object(1, 0), object(2, 0)],
new Set([0, 1, 2]),
),
).toEqual({
hierarchy: [
{
objectID: "0",
children: [
{ objectID: "1", children: [] },
{ objectID: "2", children: [] },
],
},
],
omitted: 0,
});
});
it("reports missing parents without inventing parentage", () => {
expect(projectNibViewHierarchy([object(0, 99)], new Set([0]))).toEqual({
hierarchy: [],
omitted: 1,
});
});
it("reports a missing encoded window content view as incomplete", () => {
expect(
projectNibViewHierarchy(
[
{
id: 0,
class_name: "NSWindowTemplate",
values: { NSWindowView: { $nib_object_ref: 99 } },
},
],
new Set([0]),
),
).toEqual({ hierarchy: [{ objectID: "0", children: [] }], omitted: 1 });
});
it("marks unsupported serialized parent values as incomplete", () => {
expect(
projectNibViewHierarchy(
[{ id: 0, class_name: "NSView", values: { NSSuperview: "unknown" } }],
new Set([0]),
),
).toEqual({ hierarchy: null, omitted: 1 });
});
it("reports cyclic and self-referential parentage as incomplete", () => {
expect(
projectNibViewHierarchy(
[object(0, 1), object(1, 0), object(2, 2)],
new Set([0, 1, 2]),
),
).toEqual({
hierarchy: [],
omitted: 3,
});
});
it("does not project children whose parent was not retained", () => {
expect(
projectNibViewHierarchy([object(0), object(1, 0)], new Set([1])),
).toEqual({
hierarchy: [],
omitted: 1,
});
});
it("reports nodes beyond the depth bound instead of claiming complete coverage", () => {
const objects = Array.from({ length: 132 }, (_, id) =>
object(id, id === 0 ? undefined : id - 1),
);
expect(
projectNibViewHierarchy(objects, new Set(objects.map(({ id }) => id)))
.omitted,
).toBe(3);
});
it("reports nodes beyond the record bound", () => {
const objects = Array.from({ length: 20_002 }, (_, id) =>
object(id, id === 0 ? undefined : 0),
);
expect(
projectNibViewHierarchy(objects, new Set(objects.map(({ id }) => id)))
.omitted,
).toBe(2);
});
});
describe("legacy NIB hierarchy preservation", () => {
it("keeps encoded window parents while merging shared views only once", () => {
const legacy = [
{
objectID: "window",
children: [
{ objectID: "view", children: [{ objectID: "first", children: [] }] },
],
},
];
const recovered = [
{
objectID: "view",
children: [
{ objectID: "first", children: [] },
{ objectID: "second", children: [] },
],
},
];
expect(mergeNibHierarchies(legacy, recovered).hierarchy).toEqual([
{
objectID: "window",
children: [
{
objectID: "view",
children: [
{ objectID: "first", children: [] },
{ objectID: "second", children: [] },
],
},
],
},
]);
});
it("moves an existing root under its encoded parent without duplicate visits", () => {
expect(
mergeNibHierarchies(
[{ objectID: "child", children: [] }],
[
{
objectID: "parent",
children: [{ objectID: "child", children: [] }],
},
],
),
).toEqual({
hierarchy: [
{ objectID: "parent", children: [{ objectID: "child", children: [] }] },
],
omitted: 0,
});
});
it("reports conflicting encoded parents rather than dropping a link silently", () => {
const legacy = [
{ objectID: "first", children: [{ objectID: "child", children: [] }] },
];
const recovered = [
{ objectID: "second", children: [{ objectID: "child", children: [] }] },
];
expect(mergeNibHierarchies(legacy, recovered).omitted).toBe(1);
});
it("does not introduce a cycle when moving an existing root", () => {
const legacy = [
{ objectID: "child", children: [{ objectID: "parent", children: [] }] },
];
const recovered = [
{ objectID: "parent", children: [{ objectID: "child", children: [] }] },
];
expect(mergeNibHierarchies(legacy, recovered)).toEqual({
hierarchy: legacy,
omitted: 1,
});
});
});
-176
View File
@@ -1,176 +0,0 @@
import type { NibArchiveDocument } from "../artifacts/NibArchive.js";
import type { JsonValue } from "../domain/jsonValue.js";
export type NibHierarchyNode = {
objectID: string;
children: NibHierarchyNode[];
};
/** Project encoded view parents; archive owners are not inferred view parents. */
export const projectNibViewHierarchy = (
objects: NibArchiveDocument["objects"],
retainedIds: ReadonlySet<number>,
) => {
const { parents, involved, invalid } = collectNibParents(
objects,
retainedIds,
);
if (parents.size === 0) return { hierarchy: null, omitted: invalid };
const children = new Map<number, number[]>();
for (const [child, parent] of parents) {
if (!retainedIds.has(parent) || !retainedIds.has(child)) continue;
const siblings = children.get(parent) ?? [];
siblings.push(child);
children.set(parent, siblings);
}
const roots: NibHierarchyNode[] = [];
const pending: { id: number; depth: number; output: NibHierarchyNode[] }[] =
[];
for (const id of involved)
if (!parents.has(id)) pending.push({ id, depth: 0, output: roots });
const visited = new Set<number>();
while (pending.length > 0) {
const item = pending.pop();
if (item === undefined) break;
if (visited.has(item.id) || item.depth > 128 || visited.size >= 20_000)
continue;
visited.add(item.id);
const node: NibHierarchyNode = { objectID: String(item.id), children: [] };
item.output.push(node);
for (const child of [...(children.get(item.id) ?? [])].reverse())
pending.push({ id: child, depth: item.depth + 1, output: node.children });
}
return {
hierarchy: roots,
omitted: involved.size - visited.size + invalid,
};
};
/** Add encoded parent links once; conflicting legacy parents remain unknown. */
export const mergeNibHierarchies = (
legacy: NibHierarchyNode[],
recovered: NibHierarchyNode[],
) => {
const existing = new Map<string, NibHierarchyNode>();
const owners = new Map<string, NibHierarchyNode[]>();
const parents = new Map<string, string>();
const pending = legacy.map((node) => ({
node,
output: legacy,
parent: null as string | null,
}));
while (pending.length > 0) {
const entry = pending.pop();
if (entry === undefined || existing.has(entry.node.objectID)) continue;
existing.set(entry.node.objectID, entry.node);
owners.set(entry.node.objectID, entry.output);
if (entry.parent !== null) parents.set(entry.node.objectID, entry.parent);
pending.push(
...entry.node.children.map((node) => ({
node,
output: entry.node.children,
parent: entry.node.objectID,
})),
);
}
let omitted = 0;
const additions = recovered.map((node) => ({
node,
output: legacy,
parent: null as string | null,
}));
while (additions.length > 0) {
const entry = additions.pop();
if (entry === undefined) break;
let target = existing.get(entry.node.objectID);
if (target === undefined) {
target = { objectID: entry.node.objectID, children: [] };
existing.set(target.objectID, target);
entry.output.push(target);
owners.set(target.objectID, entry.output);
if (entry.parent !== null) parents.set(target.objectID, entry.parent);
} else if (
entry.parent !== null &&
owners.get(target.objectID) !== entry.output
) {
const owner = owners.get(target.objectID);
if (
owner !== legacy ||
wouldCycle(target.objectID, entry.parent, parents)
) {
omitted += 1;
} else {
owner.splice(owner.indexOf(target), 1);
entry.output.push(target);
owners.set(target.objectID, entry.output);
parents.set(target.objectID, entry.parent);
}
}
for (const node of [...entry.node.children].reverse())
additions.push({
node,
output: target.children,
parent: target.objectID,
});
}
return { hierarchy: legacy, omitted };
};
const wouldCycle = (
child: string,
parent: string,
parents: ReadonlyMap<string, string>,
): boolean => {
const seen = new Set<string>();
let current: string | undefined = parent;
while (current !== undefined && !seen.has(current)) {
if (current === child) return true;
seen.add(current);
current = parents.get(current);
}
return false;
};
const reference = (value: JsonValue | undefined): number | null => {
if (typeof value !== "object" || value === null || Array.isArray(value))
return null;
return typeof value.$nib_object_ref === "number"
? value.$nib_object_ref
: null;
};
const collectNibParents = (
objects: NibArchiveDocument["objects"],
retainedIds: ReadonlySet<number>,
) => {
const parents = new Map<number, number>();
const involved = new Set<number>();
let invalid = 0;
for (const object of objects) {
if (!retainedIds.has(object.id)) continue;
const child = reference(object.values.NSWindowView);
if (
object.class_name.replace(/\0+$/u, "") === "NSWindowTemplate" &&
invalidReference(object.values.NSWindowView)
)
invalid += 1;
if (
object.class_name.replace(/\0+$/u, "") === "NSWindowTemplate" &&
child !== null
) {
parents.set(child, object.id);
involved.add(object.id);
involved.add(child);
}
const parent = reference(object.values.NSSuperview);
if (invalidReference(object.values.NSSuperview)) invalid += 1;
if (parent === null) continue;
parents.set(object.id, parent);
involved.add(object.id);
if (retainedIds.has(parent)) involved.add(parent);
}
return { parents, involved, invalid };
};
const invalidReference = (value: JsonValue | undefined): boolean =>
value !== undefined && value !== null && reference(value) === null;
@@ -1,12 +1,12 @@
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { Evidence } from "../domain/evidence.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Evidence } from "../../domain/evidence.js";
import {
appleApplicationProjectionInputSchema,
projectAppleApplication,
} from "../domain/appleApplication.js";
import type { Result } from "../domain/result.js";
import { APPLE_APPLICATION_PROVIDER } from "./InvestigationProviders.js";
import { projectInventoryEvidence } from "./InventoryProjectionEvidence.js";
} from "../../domain/apple/appleApplication.js";
import type { Result } from "../../domain/result.js";
import { APPLE_APPLICATION_PROVIDER } from "../InvestigationProviders.js";
import { projectInventoryEvidence } from "../InventoryProjectionEvidence.js";
const OPERATION = "project_apple_application_graph" as const;
@@ -2,22 +2,22 @@ import { createHash } from "node:crypto";
import { open } from "node:fs/promises";
import { resolve } from "node:path";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import { DyldSharedCache } from "../artifacts/DyldSharedCacheReader.js";
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { ArtifactOperationError } from "../domain/artifactOperationError.js";
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
import { DyldSharedCache } from "../../artifacts/apple/DyldSharedCacheReader.js";
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import { ArtifactOperationError } from "../../domain/artifactOperationError.js";
import {
DYLD_SHARED_CACHE_LIMITATIONS,
dyldSharedCacheResultSchema,
inspectDyldSharedCacheInputSchema,
type DyldSharedCacheResult,
type InspectedCacheImage,
} from "../domain/dyldSharedCache.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import { APPLE_APPLICATION_PROVIDER } from "./InvestigationProviders.js";
} from "../../domain/apple/dyldSharedCache.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
import { err, ok, type Result } from "../../domain/result.js";
import { APPLE_APPLICATION_PROVIDER } from "../InvestigationProviders.js";
const OPERATION = "inspect_dyld_shared_cache" as const;
const HASH_CHUNK_BYTES = 1024 * 1024;