diff --git a/packages/platform-apple/package.json b/packages/platform-apple/package.json
index e0d4df834e..4455944f9e 100644
--- a/packages/platform-apple/package.json
+++ b/packages/platform-apple/package.json
@@ -59,6 +59,10 @@
"types": "./src/physical-device-facade.ts",
"default": "./src/physical-device-facade.ts"
},
+ "./plist": {
+ "types": "./src/plist-facade.ts",
+ "default": "./src/plist-facade.ts"
+ },
"./snapshot-source": {
"types": "./src/snapshot-source-facade.ts",
"default": "./src/snapshot-source-facade.ts"
@@ -93,7 +97,6 @@
}
},
"devDependencies": {
- "@agent-device/test-kit": "workspace:*",
- "plist": "5.0.0"
+ "@agent-device/test-kit": "workspace:*"
}
}
diff --git a/packages/platform-apple/src/core/__tests__/fixtures/info-binary.plist b/packages/platform-apple/src/core/__tests__/fixtures/info-binary.plist
new file mode 100644
index 0000000000..d5783f794d
Binary files /dev/null and b/packages/platform-apple/src/core/__tests__/fixtures/info-binary.plist differ
diff --git a/packages/platform-apple/src/core/__tests__/fixtures/info-xml.plist b/packages/platform-apple/src/core/__tests__/fixtures/info-xml.plist
new file mode 100644
index 0000000000..b00503b6c0
--- /dev/null
+++ b/packages/platform-apple/src/core/__tests__/fixtures/info-xml.plist
@@ -0,0 +1,79 @@
+
+
+
+
+ BuildMachineOSBuild
+ 24G90
+ CFBundleDevelopmentRegion
+ en
+ CFBundleDisplayName
+ Example & App
+ CFBundleExecutable
+ ExampleApp
+ CFBundleIdentifier
+ com.example.app
+ CFBundleInfoDictionaryVersion
+ 6.0
+ CFBundleName
+ ExampleApp
+ CFBundlePackageType
+ APPL
+ CFBundleShortVersionString
+ 1.4.2
+ CFBundleURLTypes
+
+
+ CFBundleTypeRole
+ Editor
+ CFBundleURLName
+ com.example.app.expo
+ CFBundleURLSchemes
+
+ exp+example
+ example
+
+
+
+ CFBundleURLSchemes
+
+ fb1234567890
+
+
+
+ CFBundleVersion
+ 142
+ LSApplicationQueriesSchemes
+
+ tel
+ mailto
+
+ LSRequiresIPhoneOS
+
+ MinimumOSVersion
+ 15.1
+ NSCameraUsageDescription
+ Example uses the camera to scan barcodes.
+ NSMicrophoneUsageDescription
+
+ UIDeviceFamily
+
+ 1
+ 2
+
+ UIDesignRequiresCompatibility
+
+ UILaunchStoryboardName
+ BootScreen
+ UIPrerenderedIcon
+
+ UIRequiredDeviceCapabilities
+
+ armv7
+
+ UISupportedInterfaceOrientations
+
+ UIInterfaceOrientationPortrait
+ UIInterfaceOrientationLandscapeLeft
+
+
+
diff --git a/packages/platform-apple/src/core/__tests__/fixtures/ints-binary.plist b/packages/platform-apple/src/core/__tests__/fixtures/ints-binary.plist
new file mode 100644
index 0000000000..8d117ca655
Binary files /dev/null and b/packages/platform-apple/src/core/__tests__/fixtures/ints-binary.plist differ
diff --git a/packages/platform-apple/src/core/__tests__/fixtures/ints-xml.plist b/packages/platform-apple/src/core/__tests__/fixtures/ints-xml.plist
new file mode 100644
index 0000000000..ab8b018125
--- /dev/null
+++ b/packages/platform-apple/src/core/__tests__/fixtures/ints-xml.plist
@@ -0,0 +1,22 @@
+
+
+
+
+ Neg
+ -12
+ Neg32
+ -2147483648
+ SafeMax
+ 9007199254740991
+ U16Max
+ 65535
+ U32Max
+ 4294967295
+ U8High
+ 128
+ U8Max
+ 255
+ Zero
+ 0
+
+
diff --git a/packages/platform-apple/src/core/__tests__/fixtures/kinds-binary.plist b/packages/platform-apple/src/core/__tests__/fixtures/kinds-binary.plist
new file mode 100644
index 0000000000..273576a3ae
Binary files /dev/null and b/packages/platform-apple/src/core/__tests__/fixtures/kinds-binary.plist differ
diff --git a/packages/platform-apple/src/core/__tests__/fixtures/kinds-xml.plist b/packages/platform-apple/src/core/__tests__/fixtures/kinds-xml.plist
new file mode 100644
index 0000000000..6c7b4399fb
--- /dev/null
+++ b/packages/platform-apple/src/core/__tests__/fixtures/kinds-xml.plist
@@ -0,0 +1,49 @@
+
+
+
+
+ String
+ plain
+ EmptyString
+
+ UnicodeString
+ Zürich — 東京
+ Integer
+ -12
+ BigInteger
+ 9007199254740991
+ Real
+ 2.5
+ True
+
+ False
+
+ Null
+
+ Date
+ 2026-11-22T09:15:30Z
+ Data
+
+ iVBORw0KGgo=
+
+ Array
+
+ one
+ 2
+
+ EmptyArray
+
+ Nested
+
+ Inner
+
+ Flag
+
+
+ Number
+ 7
+
+ EmptyDict
+
+
+
diff --git a/packages/platform-apple/src/core/__tests__/fixtures/padded-binary.plist b/packages/platform-apple/src/core/__tests__/fixtures/padded-binary.plist
new file mode 100644
index 0000000000..cd9f7d56fc
Binary files /dev/null and b/packages/platform-apple/src/core/__tests__/fixtures/padded-binary.plist differ
diff --git a/packages/platform-apple/src/core/__tests__/fixtures/padded-xml.plist b/packages/platform-apple/src/core/__tests__/fixtures/padded-xml.plist
new file mode 100644
index 0000000000..da819bc0af
--- /dev/null
+++ b/packages/platform-apple/src/core/__tests__/fixtures/padded-xml.plist
@@ -0,0 +1,25 @@
+
+
+
+
+ PaddedKey
+ PaddedValue
+ Blank
+
+ Tabbed
+ x
+ CdataSplit
+ foobaz
+ CdataSpaced
+
+
+
+ Entities
+ &
+ Multiline
+ line1
+ line2
+ URL
+ https://example.com/a?b=1&c=2
+
+
diff --git a/packages/platform-apple/src/core/__tests__/ios-simulator-accessibility.test.ts b/packages/platform-apple/src/core/__tests__/ios-simulator-accessibility.test.ts
index 3d1f1ccce2..df3af5a36b 100644
--- a/packages/platform-apple/src/core/__tests__/ios-simulator-accessibility.test.ts
+++ b/packages/platform-apple/src/core/__tests__/ios-simulator-accessibility.test.ts
@@ -2,7 +2,6 @@ import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { beforeEach, test, vi } from 'vitest';
-import { build, type PlistValue } from 'plist';
import { mkdtempForTest } from '../../__tests__/tmp-dir.ts';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { IOS_TEST_SIMULATOR } from './apple-core-stub-helpers.ts';
@@ -24,21 +23,33 @@ beforeEach(async () => {
vi.mocked(runXcrun).mockClear();
});
-function writePreferences(contents: string | Record): void {
+/** Builds an XML preferences document from entries whose values are already plist XML. */
+function plistEntries(entries: Record): string {
+ const body = Object.entries(entries)
+ .map(([key, value]) => `${key}${value}`)
+ .join('');
+ return `\n${body}`;
+}
+
+/** Writes the simulator preferences file from entries whose values are already plist XML. */
+function writePreferences(entries: Record): void;
+/** Writes the simulator preferences file verbatim: damaged bytes, or bytes copied from a fixture. */
+function writePreferences(contents: string): void;
+function writePreferences(contents: Record | string): void {
const dir = path.join(setPath, device.id, 'data/Library/Preferences');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(
path.join(dir, 'com.apple.Accessibility.plist'),
- typeof contents === 'string' ? contents : build(contents),
+ typeof contents === 'string' ? contents : plistEntries(contents),
);
}
const wrote = () => vi.mocked(runXcrun).mock.calls.some(([args]) => args.includes('defaults'));
for (const [label, preferences] of [
- ['the key is on', { ApplicationAccessibilityEnabled: true }],
- ['the key is 1', { ApplicationAccessibilityEnabled: 1 }],
- ['the key is absent', { ReduceMotionEnabled: false }],
+ ['the key is on', { ApplicationAccessibilityEnabled: '' }],
+ ['the key is 1', { ApplicationAccessibilityEnabled: '1' }],
+ ['the key is absent', { ReduceMotionEnabled: '' }],
] as const) {
test(`skips the guest write when ${label} on this host`, async () => {
writePreferences(preferences);
@@ -48,8 +59,11 @@ for (const [label, preferences] of [
}
for (const [label, write] of [
- ['the key is off', () => writePreferences({ ApplicationAccessibilityEnabled: false })],
- ['the key is 0', () => writePreferences({ ApplicationAccessibilityEnabled: 0 })],
+ ['the key is off', () => writePreferences({ ApplicationAccessibilityEnabled: '' })],
+ [
+ 'the key is 0',
+ () => writePreferences({ ApplicationAccessibilityEnabled: '0' }),
+ ],
['the file is malformed', () => writePreferences('bplist00 truncated')],
['the file is missing', () => {}],
] as const) {
@@ -61,9 +75,9 @@ for (const [label, write] of [
}
test('reads again on every launch, so a later teardown is seen', async () => {
- writePreferences({ ApplicationAccessibilityEnabled: true });
+ writePreferences({ ApplicationAccessibilityEnabled: '' });
await prepareIosSimulatorAccessibility(device);
- writePreferences({ ApplicationAccessibilityEnabled: false });
+ writePreferences({ ApplicationAccessibilityEnabled: '' });
await prepareIosSimulatorAccessibility(device);
assert.equal(
vi.mocked(runXcrun).mock.calls.filter(([args]) => args.includes('defaults')).length,
@@ -88,7 +102,7 @@ for (const [value, expectWrite] of [
}
test('a scoped (remote) tool provider writes even when this host has an on key', async () => {
- writePreferences({ ApplicationAccessibilityEnabled: true });
+ writePreferences({ ApplicationAccessibilityEnabled: '' });
await withAppleToolProvider({} as Parameters[0], () =>
prepareIosSimulatorAccessibility(device),
);
diff --git a/packages/platform-apple/src/core/__tests__/plist-value.test.ts b/packages/platform-apple/src/core/__tests__/plist-value.test.ts
new file mode 100644
index 0000000000..9c913838ab
--- /dev/null
+++ b/packages/platform-apple/src/core/__tests__/plist-value.test.ts
@@ -0,0 +1,359 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { test } from 'vitest';
+import {
+ APPLE_PLIST_PARSE_REASONS,
+ ApplePlistParseError,
+ parseApplePlist,
+} from '../plist-value.ts';
+
+const FIXTURES = fileURLToPath(new URL('./fixtures/', import.meta.url));
+const bytesOf = (name: string): Uint8Array =>
+ new Uint8Array(fs.readFileSync(path.join(FIXTURES, name)));
+const xmlDocument = (body: string): Uint8Array =>
+ new TextEncoder().encode(
+ `\n${body}`,
+ );
+
+/** Reads a `bplist00` document this test crafts by hand instead of one a tool wrote. */
+const binaryDocument = (base64: string): Uint8Array =>
+ new Uint8Array(Buffer.from(base64, 'base64'));
+
+/** Asserts a refusal carries the reason its table declares. */
+const refusedWith =
+ (expected: string) =>
+ (error: unknown): boolean =>
+ error instanceof ApplePlistParseError && error.reason === expected;
+
+const asDate = (value: unknown): Date => value as Date;
+const asBytes = (value: unknown): Uint8Array => value as Uint8Array;
+
+/** The keys the two readers have callers for: app metadata, and a simulator's preference file. */
+for (const [label, name] of [
+ ['An XML Info.plist', 'info-xml.plist'],
+ ['A binary Info.plist', 'info-binary.plist'],
+] as const) {
+ test(`${label} answers the bundle keys app resolution reads`, () => {
+ const plist = parseApplePlist(bytesOf(name))!;
+ assert.equal(plist.CFBundleIdentifier, 'com.example.app');
+ assert.equal(plist.CFBundleExecutable, 'ExampleApp');
+ assert.equal(plist.CFBundleName, 'ExampleApp');
+ assert.equal(plist.CFBundleDisplayName, 'Example & App');
+ assert.equal(plist.CFBundleShortVersionString, '1.4.2');
+ assert.equal(plist.CFBundleVersion, '142');
+ assert.equal(plist.UILaunchStoryboardName, 'BootScreen');
+ assert.equal(plist.LSRequiresIPhoneOS, true);
+ assert.deepEqual(plist.UIDeviceFamily, [1, 2]);
+ assert.deepEqual(plist.LSApplicationQueriesSchemes, ['tel', 'mailto']);
+ assert.deepEqual(plist.UISupportedInterfaceOrientations, [
+ 'UIInterfaceOrientationPortrait',
+ 'UIInterfaceOrientationLandscapeLeft',
+ ]);
+ });
+
+ test(`${label} answers the nested URL schemes deep-link resolution reads`, () => {
+ const plist = parseApplePlist(bytesOf(name))!;
+ assert.deepEqual(plist.CFBundleURLTypes, [
+ {
+ CFBundleTypeRole: 'Editor',
+ CFBundleURLName: 'com.example.app.expo',
+ CFBundleURLSchemes: ['exp+example', 'example'],
+ },
+ { CFBundleURLSchemes: ['fb1234567890'] },
+ ]);
+ });
+}
+
+for (const [label, name] of [
+ ['XML', 'kinds-xml.plist'],
+ ['binary', 'kinds-binary.plist'],
+] as const) {
+ test(`a ${label} document reads each value kind as its own JS type`, () => {
+ const plist = parseApplePlist(bytesOf(name))!;
+ assert.equal(plist.String, 'plain');
+ assert.equal(plist.EmptyString, '');
+ assert.equal(plist.UnicodeString, 'Zürich — 東京');
+ assert.equal(plist.Integer, -12);
+ assert.equal(plist.BigInteger, 9007199254740991);
+ assert.equal(plist.Real, 2.5);
+ assert.equal(plist.True, true);
+ assert.equal(plist.False, false);
+ assert.equal(asDate(plist.Date).getTime(), Date.UTC(2026, 10, 22, 9, 15, 30));
+ assert.deepEqual(
+ asBytes(plist.Data),
+ new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ );
+ assert.deepEqual(plist.Array, ['one', 2]);
+ assert.deepEqual(plist.EmptyArray, []);
+ assert.deepEqual(plist.Nested, { Inner: { Flag: true }, Number: 7 });
+ assert.deepEqual(plist.EmptyDict, {});
+ });
+}
+
+test('an XML document reads a null value the binary format cannot store', () => {
+ assert.equal(parseApplePlist(bytesOf('kinds-xml.plist'))!.Null, null);
+});
+
+test('the binary preferences fixtures a simulator writes read as the accessibility state they hold', () => {
+ assert.equal(
+ parseApplePlist(bytesOf('accessibility-true.plist'))!.ApplicationAccessibilityEnabled,
+ true,
+ );
+ assert.equal(
+ parseApplePlist(bytesOf('accessibility-false.plist'))!.ApplicationAccessibilityEnabled,
+ false,
+ );
+});
+
+/**
+ * The spacing both Apple parsers keep: `plutil -convert json` and `plistlib.loads` answer each of these
+ * values, and `plutil -convert binary1` wrote the binary fixture from the XML one.
+ */
+const paddedValues = {
+ ' PaddedKey ': ' PaddedValue ',
+ Blank: ' ',
+ Tabbed: '\tx\t',
+ CdataSplit: 'foo bar baz',
+ CdataSpaced: '\n spaced \n',
+ Entities: ' & ',
+ Multiline: 'line1\n\tline2',
+ URL: 'https://example.com/a?b=1&c=2',
+};
+
+for (const [label, name] of [
+ ['XML', 'padded-xml.plist'],
+ ['binary', 'padded-binary.plist'],
+] as const) {
+ test(`a ${label} document keeps the whitespace its strings and keys are written with`, () => {
+ assert.deepEqual(parseApplePlist(bytesOf(name)), paddedValues);
+ });
+}
+
+test('both stored forms answer one padded document with the same values', () => {
+ assert.deepEqual(
+ parseApplePlist(bytesOf('padded-binary.plist')),
+ parseApplePlist(bytesOf('padded-xml.plist')),
+ );
+});
+
+/**
+ * A writer that de-duplicates names one object several times instead of repeating it, so this document
+ * holds one ASCII string, object 3, and its array names it in all three slots. Each slot answers the
+ * value `plutil -convert json` answers, and decoding one object per index keeps a document's cost
+ * proportional to its bytes rather than to how often it repeats a reference.
+ */
+test('a binary document whose objects share one referenced object reads that object each time', () => {
+ assert.deepEqual(
+ parseApplePlist(
+ binaryDocument(
+ 'YnBsaXN0MDDRAQJRQaMDAwNSaGkICw0RAAAAAAAAAQEAAAAAAAAABAAAAAAAAAAAAAAAAAAAABQ=',
+ ),
+ ),
+ { A: ['hi', 'hi', 'hi'] },
+ );
+});
+
+test('an XML dictionary keeps its keys as own properties, including one named __proto__', () => {
+ const plist = parseApplePlist(
+ xmlDocument('__proto__polluted'),
+ )!;
+ assert.deepEqual(Object.getOwnPropertyDescriptor(plist, '__proto__')?.value, { polluted: true });
+ assert.equal(Object.getPrototypeOf(plist), Object.prototype);
+ assert.equal(Object.getPrototypeOf({}), Object.prototype);
+});
+
+test('a binary dictionary keeps a key it stores as a separate object', () => {
+ // bplist00: a one-entry dictionary whose key is the ASCII string "Key" and whose value is `true`.
+ const plist = parseApplePlist(
+ binaryDocument('YnBsaXN0MDDRAQJTS2V5CQgLDwAAAAAAAAEBAAAAAAAAAAMAAAAAAAAAAAAAAAAAAAAQ'),
+ )!;
+ assert.deepEqual(plist, { Key: true });
+});
+
+/**
+ * Widths one real encoder chose for each value: `plutil -convert binary1` and Python's `plistlib` both
+ * write a negative across eight bytes and keep 1-, 2- and 4-byte integers unsigned, which is how Apple's
+ * own reader decodes them. Read as signed, `U8High` would come back −128 and `U32Max` −1.
+ */
+test('a binary integer keeps the sign its byte width carries', () => {
+ assert.deepEqual(parseApplePlist(bytesOf('ints-binary.plist')), {
+ Neg: -12,
+ Neg32: -2147483648,
+ SafeMax: 9007199254740991,
+ U8High: 128,
+ U8Max: 255,
+ U16Max: 65535,
+ U32Max: 4294967295,
+ Zero: 0,
+ });
+});
+
+test('the XML and binary integer fixtures agree value for value', () => {
+ assert.deepEqual(parseApplePlist(bytesOf('ints-xml.plist')), {
+ Neg: -12,
+ Neg32: -2147483648,
+ SafeMax: 9007199254740991,
+ U8High: 128,
+ U8Max: 255,
+ U16Max: 65535,
+ U32Max: 4294967295,
+ Zero: 0,
+ });
+});
+
+/** Builds `depth` dictionaries, each holding one entry keyed `k`, the innermost holding `true`. */
+function nestedDictXml(depth: number): Uint8Array {
+ return new TextEncoder().encode(
+ '\n' +
+ 'k'.repeat(depth) +
+ '' +
+ ''.repeat(depth) +
+ '',
+ );
+}
+
+/**
+ * Builds a `bplist00` of the same shape as `nestedDictXml`: object 2·i is a one-entry dictionary keyed by
+ * object 2·i+1 holding object 2·i+2, and the last object is `true`. Every offset and reference is valid,
+ * so only the depth tells this document from one a real writer produced.
+ */
+function nestedDictBinary(depth: number): Uint8Array {
+ const ref = (value: number, size: number) =>
+ [...Array(size).keys()].reverse().map((shift) => Math.floor(value / 256 ** shift) % 256);
+ const objectCount = 2 * depth + 1;
+ const refSize = objectCount < 256 ? 1 : objectCount < 65536 ? 2 : 4;
+ const payloadAt = (index: number): number[] => {
+ if (index % 2 === 1) return [0x51, 0x6b]; // ASCII string "k"
+ if (index === objectCount - 1) return [0x09]; // true
+ return [0xd1, ...ref(index + 1, refSize), ...ref(index + 2, refSize)];
+ };
+ const payloads: number[][] = [];
+ for (let index = 0; index < objectCount; index += 1) payloads.push(payloadAt(index));
+ const bodyBytes = payloads.reduce((total, payload) => total + payload.length, 0);
+ const span = 8 + bodyBytes + objectCount * refSize + 32;
+ const offsetSize = span < 256 ? 1 : span < 65536 ? 2 : 4;
+ const bytes = [...new TextEncoder().encode('bplist00')];
+ let cursor = 8;
+ const offsets: number[] = [];
+ for (const payload of payloads) {
+ offsets.push(cursor);
+ bytes.push(...payload);
+ cursor += payload.length;
+ }
+ for (const offset of offsets) bytes.push(...ref(offset, offsetSize));
+ bytes.push(0, 0, 0, 0, 0, 0, offsetSize, refSize);
+ bytes.push(...ref(objectCount, 8), ...ref(0, 8), ...ref(cursor, 8));
+ return new Uint8Array(bytes);
+}
+
+/** Reads a document, reporting its value, or the reason or error name that refused it. */
+function outcomeOf(bytes: Uint8Array): string {
+ try {
+ return JSON.stringify(parseApplePlist(bytes))!;
+ } catch (error) {
+ return error instanceof ApplePlistParseError
+ ? error.reason
+ : `untyped:${(error as Error).name}`;
+ }
+}
+
+const malformed = APPLE_PLIST_PARSE_REASONS.malformed.reason;
+
+/**
+ * Nesting is bounded the same way in both stored forms: a document a real writer could have produced is
+ * read, and a deeper one is refused as malformed rather than running the binary reader out of stack.
+ */
+for (const [depth, expected] of [
+ [200, 'value'],
+ [300, malformed],
+ [5_000, malformed],
+] as const) {
+ test(`values nested ${depth} levels deep answer as a ${expected === 'value' ? 'value' : 'refusal'} in both forms`, () => {
+ const xml = outcomeOf(nestedDictXml(depth));
+ const binary = outcomeOf(nestedDictBinary(depth));
+ assert.equal(binary, xml);
+ if (expected === 'value') assert.match(xml, /"k":true/);
+ else assert.equal(xml, malformed);
+ });
+}
+
+const malformedCases = [
+ [
+ 'a binary object reference naming an index past the object count',
+ binaryDocument('YnBsaXN0MDChAlFBCAoAAAAAAAABAQAAAAAAAAACAAAAAAAAAAAAAAAAAAAADA=='),
+ ],
+ ['an XML document whose tag is left open', new TextEncoder().encode('A')],
+ [
+ 'an XML entry that does not start with a ',
+ xmlDocument('Aa1'),
+ ],
+ ['an XML that is not base64', xmlDocument('Anot base64!!')],
+ ['an XML with no number in it', xmlDocument('Aabc')],
+ [
+ 'an XML whose text is a number followed by other text',
+ xmlDocument('A12abc'),
+ ],
+ [
+ 'an XML beyond the largest integer a JS number holds exactly',
+ xmlDocument('A9007199254740993'),
+ ],
+ [
+ 'an XML whose text is a number followed by a unit suffix',
+ xmlDocument('A3.5f'),
+ ],
+ ['an XML holding two decimal points', xmlDocument('A1.5.5')],
+ [
+ 'a document shorter than a binary header and trailer',
+ new TextEncoder().encode('bplist00 truncated'),
+ ],
+ [
+ 'a binary document whose top object index is past its object count',
+ binaryDocument('YnBsaXN0MDAJCAAAAAAAAAEBAAAAAAAAAAEAAAAAAAAABAAAAAAAAAAJ'),
+ ],
+ [
+ 'a binary document whose object contains itself',
+ binaryDocument('YnBsaXN0MDDRAAAIAAAAAAAAAQEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAs='),
+ ],
+ [
+ 'a binary string whose length runs past the document',
+ binaryDocument('YnBsaXN0MDBfEchBCAAAAAAAAAEBAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAM'),
+ ],
+ ['a text document that is not a plist at all', new TextEncoder().encode('{ key = value; }')],
+] as const;
+
+for (const [label, bytes] of malformedCases) {
+ test(`${label} is refused as malformed`, () => {
+ assert.throws(
+ () => parseApplePlist(bytes),
+ refusedWith(APPLE_PLIST_PARSE_REASONS.malformed.reason),
+ );
+ });
+}
+
+const unsupportedCases = [
+ ['an XML tag this reader does not model', xmlDocument('A')],
+ [
+ 'a binary object kind this reader does not model',
+ binaryDocument('YnBsaXN0MDBwCAAAAAAAAAEBAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAJ'),
+ ],
+] as const;
+
+for (const [label, bytes] of unsupportedCases) {
+ test(`${label} is refused as an unsupported type`, () => {
+ assert.throws(
+ () => parseApplePlist(bytes),
+ refusedWith(APPLE_PLIST_PARSE_REASONS.unsupportedType.reason),
+ );
+ });
+}
+
+for (const [label, document] of [
+ ['an array', 'a'],
+ ['a scalar', 'scalar'],
+] as const) {
+ test(`a plist whose root value is ${label} is read as no metadata`, () => {
+ assert.equal(parseApplePlist(new TextEncoder().encode(document)), null);
+ });
+}
diff --git a/packages/platform-apple/src/core/ios-simulator-accessibility.ts b/packages/platform-apple/src/core/ios-simulator-accessibility.ts
index ee2e9f1c8a..3ef42c367e 100644
--- a/packages/platform-apple/src/core/ios-simulator-accessibility.ts
+++ b/packages/platform-apple/src/core/ios-simulator-accessibility.ts
@@ -3,7 +3,7 @@ import { isHandheldAppleSimulator, type DeviceInfo } from '@agent-device/kernel/
import { normalizeError } from '@agent-device/kernel/errors';
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
import { hostHomeDirectory, readHostBinaryFile } from '@agent-device/host-kit/host-file';
-import { parseApplePlist } from './plist.ts';
+import { parseApplePlist } from './plist-value.ts';
import { buildSimctlArgsForDevice, simulatorAddressFor } from './simctl.ts';
import { hasScopedAppleToolProvider, runXcrun } from './tool-provider.ts';
@@ -67,7 +67,7 @@ async function readHostAppAccessibility(
udid,
'data/Library/Preferences/com.apple.Accessibility.plist',
);
- const parsed = await parseApplePlist(await readHostBinaryFile(preferences));
+ const parsed = parseApplePlist(await readHostBinaryFile(preferences));
if (!parsed) return 'unknown';
const value = parsed.ApplicationAccessibilityEnabled;
if (value === undefined || value === true || value === 1) return 'enabled';
diff --git a/packages/platform-apple/src/core/plist-value.ts b/packages/platform-apple/src/core/plist-value.ts
new file mode 100644
index 0000000000..8869d79633
--- /dev/null
+++ b/packages/platform-apple/src/core/plist-value.ts
@@ -0,0 +1,547 @@
+import { parseXmlDocumentSync, type XmlNode } from '@agent-device/xml';
+import type { ReasonTable } from '@agent-device/kernel/errors';
+
+/**
+ * Reads one Apple property list — XML text or `bplist00` binary — into plain JS values, with no
+ * third-party plist parser. A downloaded app's `Info.plist` and a simulator's preference file are the
+ * documents read here.
+ *
+ * Each stored form maps to the JS value its name states: a dictionary becomes an own-property object,
+ * an array an array, `` and a binary ASCII or UTF-16 string a string, `` and ``
+ * a number, ``/`` and the binary singletons a boolean, `` and the binary null a
+ * `null`, `` and a binary date a `Date`, `` and binary data a `Uint8Array`, and a binary
+ * unique id `{ UID: number }`. A key equal to `__proto__` becomes an own property like any other, so a
+ * document cannot repoint an object's prototype.
+ *
+ * A document this reader cannot model is refused with `ApplePlistParseError` rather than answered with
+ * a partial value. `malformed` means the bytes or tags are damaged, refer to themselves, or exceed the
+ * budgets below; `unsupported type` means the document is well formed but names a value kind or a
+ * dictionary key type this reader does not model.
+ *
+ * A writer that de-duplicates repeats one reference instead of repeating the object it names. Such an
+ * object is decoded once, so the positions that reference it answer the same object.
+ */
+
+/** A value an Apple property list holds. */
+export type ApplePlistValue =
+ | null
+ | boolean
+ | number
+ | string
+ | Date
+ | Uint8Array
+ | ApplePlistValue[]
+ | ApplePlistRecord;
+
+/** One Apple property list dictionary. */
+export type ApplePlistRecord = { readonly [key: string]: ApplePlistValue };
+
+/** Why an Apple property list document cannot become a JS value. */
+export const APPLE_PLIST_PARSE_REASONS = {
+ // The document is damaged, refers to itself, or is larger than a reader's budget.
+ malformed: { reason: 'apple_plist_malformed' },
+ // The document is well formed but names a value kind or key type this reader does not model.
+ unsupportedType: { reason: 'apple_plist_unsupported_type' },
+} as const satisfies ReasonTable<'apple plist'>;
+
+/** Why an Apple property list cannot become a JS value. */
+export type ApplePlistParseReason =
+ (typeof APPLE_PLIST_PARSE_REASONS)[keyof typeof APPLE_PLIST_PARSE_REASONS]['reason'];
+
+/** An Apple property list that cannot become a JS value. */
+export class ApplePlistParseError extends Error {
+ readonly reason: ApplePlistParseReason;
+
+ constructor(reason: ApplePlistParseReason, message: string) {
+ super(message);
+ this.name = 'ApplePlistParseError';
+ this.reason = reason;
+ }
+}
+
+const BINARY_MAGIC = 'bplist00';
+const BINARY_TRAILER_BYTES = 32;
+/** The values, including every nested entry, one binary document may hold at most. */
+const MAX_BINARY_VALUES = 100_000;
+/**
+ * How deeply binary objects may nest before the reader refuses the document. The XML walker applies a
+ * bound of the same size to its elements, and both stop far below the depth that would exhaust the JS
+ * stack. Real plists nest a handful of levels.
+ */
+const MAX_BINARY_NESTING_DEPTH = 256;
+const MAX_NUMBER_BYTES = 8;
+/**
+ * The text one XML `` holds: an optional sign, then decimal digits, or `0x` and hex digits —
+ * the grammar `plutil` accepts. Nothing else is read as a number.
+ */
+const XML_INTEGER_TEXT = /^[+-]?(?:0[xX][0-9a-fA-F]+|[0-9]+)$/;
+/** The text one XML `` holds: a decimal literal with at least one digit, no hex and no suffix. */
+const XML_REAL_TEXT = /^[+-]?(?:[0-9]*\.[0-9]+|[0-9]+\.[0-9]*|[0-9]+)(?:[eE][+-]?[0-9]+)?$/;
+/** Seconds between the Apple reference date, 2001-01-01, and the JS one. */
+const APPLE_EPOCH_SECONDS = 978_307_200;
+const MAX_DATE_MS = 8.64e15;
+/** Code units decoded per step, so `String.fromCharCode` never receives a huge argument list. */
+const STRING_CHUNK_UNITS = 1_024;
+const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
+
+/**
+ * Reads the dictionary an Apple property list holds, from XML text or `bplist00` bytes.
+ *
+ * Returns `null` when the document names no dictionary: a value that is an array or a scalar. Throws
+ * `ApplePlistParseError` for a document this reader cannot model, including a text document that is not
+ * XML at all, such as a legacy OpenStep plist.
+ *
+ * The refusals go past what a permissive reader answers, so a caller sees one typed error instead of a
+ * value it cannot represent: an XML `` or `` whose text is not exactly a number, or names
+ * an integer beyond `Number.MAX_SAFE_INTEGER`; an XML `` such as `nan`; an XML `` no `Date`
+ * holds; a `` holding more than one value; a binary dictionary key that is not a string; a binary
+ * integer wider than eight bytes; and a binary object kind this reader does not model.
+ */
+export function parseApplePlist(bytes: Uint8Array): Record | null {
+ return asRecord(
+ startsWithBinaryMagic(bytes)
+ ? readBinaryPlistValue(bytes)
+ : readXmlPlistValue(new TextDecoder().decode(bytes)),
+ ) as Record | null;
+}
+
+function startsWithBinaryMagic(bytes: Uint8Array): boolean {
+ if (bytes.byteLength < BINARY_MAGIC.length) return false;
+ for (let index = 0; index < BINARY_MAGIC.length; index += 1) {
+ if (bytes[index] !== BINARY_MAGIC.charCodeAt(index)) return false;
+ }
+ return true;
+}
+
+function asRecord(value: unknown): ApplePlistRecord | null {
+ if (value === null || typeof value !== 'object' || value instanceof Uint8Array) return null;
+ return Array.isArray(value) || value instanceof Date ? null : (value as ApplePlistRecord);
+}
+
+/** Reads the value an XML property list names below its `` element. */
+function readXmlPlistValue(plist: string): ApplePlistValue {
+ const nodes = readXmlDocument(plist);
+ const root = nodes.find((node) => node.name === 'plist');
+ if (!root) throw malformed('no element was found');
+ if (root.children.length > 1) throw malformed(' holds more than one value');
+ const valueNode = root.children[0];
+ return valueNode ? readXmlPlistNode(valueNode) : null;
+}
+
+/**
+ * Parses plist XML, reporting a document the XML walker rejects as the same malformed plist a broken
+ * binary document gets, so callers catch one error type from one module.
+ *
+ * Text is not trimmed. Apple reads ` v ` as a padded string and a `` the way it
+ * is written, so a plist read here answers the same text the `plutil` and `plistlib` parsers do.
+ */
+function readXmlDocument(plist: string): XmlNode[] {
+ try {
+ return parseXmlDocumentSync(plist, { trimText: false });
+ } catch (error) {
+ const detail = error instanceof Error ? error.message : 'the XML document was rejected';
+ throw malformed(detail.replace(/\.$/, ''));
+ }
+}
+
+function readXmlPlistNode(node: XmlNode): ApplePlistValue {
+ switch (node.name) {
+ case 'dict':
+ return readXmlPlistDict(node);
+ case 'array':
+ return node.children.map(readXmlPlistNode);
+ case 'string':
+ return node.text ?? '';
+ case 'integer':
+ return readXmlInteger(node);
+ case 'real':
+ return readXmlReal(node);
+ case 'true':
+ return true;
+ case 'false':
+ return false;
+ case 'null':
+ return null;
+ case 'date':
+ return requireXmlDate(node);
+ case 'data':
+ return readBase64(node.text ?? '');
+ default:
+ throw unsupported(`plist tag <${node.name}>`);
+ }
+}
+
+/**
+ * Reads a `` as alternating `` and value children. A `` with no value after it holds an
+ * empty string, the way Apple's own readers treat a trailing key.
+ */
+function readXmlPlistDict(node: XmlNode): ApplePlistRecord {
+ const entries: [string, ApplePlistValue][] = [];
+ for (let index = 0; index < node.children.length; index += 2) {
+ const keyNode = node.children[index]!;
+ if (keyNode.name !== 'key') throw malformed(`a entry starts with <${keyNode.name}>`);
+ const valueNode = node.children[index + 1];
+ entries.push([keyNode.text ?? '', valueNode ? readXmlPlistNode(valueNode) : '']);
+ }
+ return Object.fromEntries(entries);
+}
+
+/**
+ * Reads an XML ``. Its text must be the whole number, so a prefix such as `12abc` is refused
+ * rather than read as 12, and a value beyond `MAX_SAFE_INTEGER` is refused like the binary reader
+ * refuses it, so both forms answer one number the same way.
+ */
+function readXmlInteger(node: XmlNode): number {
+ const text = node.text ?? '';
+ if (!XML_INTEGER_TEXT.test(text)) throw malformed(`text "${text}" as `);
+ const digits = text.replace(/^[+-]/, '');
+ // BigInt parses hex and decimal digits without a leading sign, which the text grammar already checked.
+ const magnitude = BigInt(digits);
+ if (magnitude > BigInt(Number.MAX_SAFE_INTEGER)) {
+ throw malformed(`integer ${text} beyond an exact JS number`);
+ }
+ return text.startsWith('-') ? -Number(magnitude) : Number(magnitude);
+}
+
+/** Reads an XML ``, whose text must be the whole decimal literal, with no suffix or spaces. */
+function readXmlReal(node: XmlNode): number {
+ const text = node.text ?? '';
+ if (!XML_REAL_TEXT.test(text)) throw malformed(`text "${text}" as `);
+ return requireXmlNumber(node, Number.parseFloat(text));
+}
+
+function requireXmlNumber(node: XmlNode, value: number): number {
+ if (!Number.isFinite(value)) throw malformed(`text "${node.text ?? ''}" as <${node.name}>`);
+ return value;
+}
+
+function requireXmlDate(node: XmlNode): Date {
+ const date = new Date(node.text ?? '');
+ if (Number.isNaN(date.getTime())) throw malformed(`text "${node.text ?? ''}" as `);
+ return date;
+}
+
+/** Reads an XML `` element, whose base64 text Apple wraps across lines. */
+function readBase64(text: string): Uint8Array {
+ const compact = text.replaceAll(/\s+/g, '');
+ if (!BASE64.test(compact)) throw malformed('text inside is not base64');
+ return Uint8Array.from(atob(compact), (char) => char.charCodeAt(0));
+}
+
+/** Byte positions inside the trailer that name the document's own geometry. */
+const TRAILER_OFFSET_INT_SIZE = 6;
+const TRAILER_OBJECT_REF_SIZE = 7;
+const TRAILER_OBJECT_COUNT = 8;
+const TRAILER_TOP_OBJECT = 16;
+const TRAILER_OFFSET_TABLE = 24;
+
+/** The marker nibble Apple assigns each binary object kind. */
+const KIND_SINGLETON = 0x0;
+const KIND_INT = 0x1;
+const KIND_REAL = 0x2;
+const KIND_DATE = 0x3;
+const KIND_DATA = 0x4;
+const KIND_ASCII = 0x5;
+const KIND_UTF16 = 0x6;
+const KIND_UID = 0x8;
+const KIND_ARRAY = 0xa;
+const KIND_DICT = 0xd;
+/** A low nibble of this value means the real length follows as an `` object. */
+const EXTENDED_LENGTH_NIBBLE = 0x0f;
+
+/**
+ * Reads one `bplist00` document through its header and trailer. Every offset, length and object
+ * reference is checked against the document before it is read, an object cannot appear inside itself,
+ * and the document as a whole gets `MAX_BINARY_VALUES` values.
+ */
+class BinaryPlistReader {
+ private readonly bytes: Uint8Array;
+ private readonly view: DataView;
+ private readonly offsetIntSize: number;
+ private readonly objectRefSize: number;
+ private readonly objectCount: number;
+ private readonly topObject: number;
+ private readonly offsetTableOffset: number;
+ private readonly openObjects = new Set();
+ private readonly decoded = new Map();
+ private valueBudget = MAX_BINARY_VALUES;
+
+ private constructor(bytes: Uint8Array) {
+ this.bytes = bytes;
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const trailer = bytes.byteLength - BINARY_TRAILER_BYTES;
+ this.offsetIntSize = this.readTrailerSize(trailer + TRAILER_OFFSET_INT_SIZE, 'offset size');
+ this.objectRefSize = this.readTrailerSize(
+ trailer + TRAILER_OBJECT_REF_SIZE,
+ 'object reference size',
+ );
+ this.objectCount = this.readNumberAt(trailer + TRAILER_OBJECT_COUNT, 'object count');
+ this.topObject = this.readNumberAt(trailer + TRAILER_TOP_OBJECT, 'top object');
+ this.offsetTableOffset = this.readNumberAt(trailer + TRAILER_OFFSET_TABLE, 'offset table');
+ this.require(this.objectCount <= bytes.byteLength, 'object count');
+ this.require(this.topObject < this.objectCount, 'top object');
+ this.require(
+ this.offsetTableOffset + this.objectCount * this.offsetIntSize <= bytes.byteLength,
+ 'offset table',
+ );
+ }
+
+ static open(bytes: Uint8Array): BinaryPlistReader {
+ if (bytes.byteLength < BINARY_MAGIC.length + BINARY_TRAILER_BYTES) {
+ throw malformed('it is shorter than a header and a trailer');
+ }
+ return new BinaryPlistReader(bytes);
+ }
+
+ /** Reads the document's top-level object. */
+ readTopValue(): ApplePlistValue {
+ return this.readObjectByIndex(this.topObject);
+ }
+
+ /**
+ * Reads one object by index. `openObjects` holds the indices on the path from the top object down, so
+ * its size is the current nesting depth: it both refuses an object that contains itself and refuses a
+ * chain too deep to walk before it exhausts the JS stack. `decoded` holds one value per index, so an
+ * object many other objects reference is decoded once, which keeps a document's cost proportional to
+ * the document rather than to how often it repeats a reference.
+ */
+ private readObjectByIndex(index: number): ApplePlistValue {
+ this.require(index < this.objectCount, 'object reference past the object count');
+ if (this.valueBudget <= 0) throw malformed('it holds too many values');
+ this.valueBudget -= 1;
+ const decoded = this.decoded.get(index);
+ if (decoded !== undefined) return decoded;
+ if (this.openObjects.has(index)) throw malformed('an object contains itself');
+ if (this.openObjects.size >= MAX_BINARY_NESTING_DEPTH) {
+ throw malformed(`an object nested deeper than ${MAX_BINARY_NESTING_DEPTH} levels`);
+ }
+ this.openObjects.add(index);
+ try {
+ const value = this.readObjectAt(this.offsetOfObject(index));
+ this.decoded.set(index, value);
+ return value;
+ } finally {
+ this.openObjects.delete(index);
+ }
+ }
+
+ private readObjectAt(offset: number): ApplePlistValue {
+ const marker = this.readUint8(offset);
+ const kind = marker >> 4;
+ const nibble = marker & 0x0f;
+ switch (kind) {
+ case KIND_SINGLETON:
+ return readSingleton(marker);
+ case KIND_INT:
+ return this.readIntAt(offset, nibble);
+ case KIND_REAL:
+ return this.readRealAt(offset, nibble);
+ case KIND_DATE:
+ return this.readDateAt(offset, nibble);
+ case KIND_DATA:
+ return this.readDataAt(offset, nibble);
+ case KIND_ASCII:
+ return this.readTextAt(offset, nibble, 1);
+ case KIND_UTF16:
+ return this.readTextAt(offset, nibble, 2);
+ case KIND_UID:
+ return { UID: this.readUnsignedAt(offset + 1, nibble + 1, 'unique id') };
+ case KIND_ARRAY:
+ return this.readArrayAt(offset, nibble);
+ case KIND_DICT:
+ return this.readDictAt(offset, nibble);
+ default:
+ throw unsupported(`binary plist object type 0x${kind.toString(16)}`);
+ }
+ }
+
+ private readIntAt(offset: number, nibble: number): number {
+ const byteCount = 1 << nibble;
+ if (byteCount > MAX_NUMBER_BYTES) throw malformed(`integer of ${byteCount} bytes`);
+ this.requireRange(offset + 1, byteCount);
+ if (byteCount < MAX_NUMBER_BYTES) return this.readUnsigned(offset + 1, byteCount);
+ const value = this.view.getBigInt64(offset + 1);
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {
+ throw malformed('integer beyond an exact JS number');
+ }
+ return Number(value);
+ }
+
+ private readRealAt(offset: number, nibble: number): number {
+ const byteCount = 1 << nibble;
+ this.requireRange(offset + 1, byteCount);
+ if (byteCount === 4) return this.view.getFloat32(offset + 1);
+ if (byteCount === 8) return this.view.getFloat64(offset + 1);
+ throw malformed(`real of ${byteCount} bytes`);
+ }
+
+ private readDateAt(offset: number, nibble: number): Date {
+ if (nibble !== 3) throw malformed('date of a size other than 8 bytes');
+ this.requireRange(offset + 1, MAX_NUMBER_BYTES);
+ const timestamp = (APPLE_EPOCH_SECONDS + this.view.getFloat64(offset + 1)) * 1000;
+ if (!Number.isFinite(timestamp) || Math.abs(timestamp) > MAX_DATE_MS) {
+ throw malformed('date beyond the range a Date holds');
+ }
+ return new Date(timestamp);
+ }
+
+ private readDataAt(offset: number, nibble: number): Uint8Array {
+ const { length, payload } = this.readLengthAt(offset, nibble);
+ this.requireRange(payload, length);
+ return this.bytes.subarray(payload, payload + length).slice();
+ }
+
+ /**
+ * Reads an ASCII (`unit` 1) or UTF-16BE (`unit` 2) string, whose length counts code units. An ASCII
+ * byte becomes the code point of the same value; Apple writes non-ASCII text as UTF-16.
+ */
+ private readTextAt(offset: number, nibble: number, unit: number): string {
+ const { length, payload } = this.readLengthAt(offset, nibble);
+ this.requireRange(payload, length * unit);
+ const chunks: string[] = [];
+ for (let done = 0; done < length; done += STRING_CHUNK_UNITS) {
+ const units = Math.min(STRING_CHUNK_UNITS, length - done);
+ const codes = new Array(units);
+ for (let unitIndex = 0; unitIndex < units; unitIndex += 1) {
+ const at = payload + (done + unitIndex) * unit;
+ codes[unitIndex] = unit === 1 ? this.view.getUint8(at) : this.view.getUint16(at);
+ }
+ chunks.push(String.fromCharCode(...codes));
+ }
+ return chunks.join('');
+ }
+
+ private readArrayAt(offset: number, nibble: number): ApplePlistValue[] {
+ const { length, payload } = this.readLengthAt(offset, nibble);
+ this.requireRange(payload, length * this.objectRefSize);
+ const values: ApplePlistValue[] = [];
+ for (let index = 0; index < length; index += 1) {
+ values.push(
+ this.readObjectByIndex(this.readObjectRefAt(payload + index * this.objectRefSize)),
+ );
+ }
+ return values;
+ }
+
+ /** Reads every key before any value, so one failed key refuses the whole dictionary. */
+ private readDictAt(offset: number, nibble: number): ApplePlistRecord {
+ const { length, payload } = this.readLengthAt(offset, nibble);
+ this.requireRange(payload, 2 * length * this.objectRefSize);
+ const keys: string[] = [];
+ for (let index = 0; index < length; index += 1) {
+ const key = this.readObjectByIndex(
+ this.readObjectRefAt(payload + index * this.objectRefSize),
+ );
+ if (typeof key !== 'string') {
+ throw unsupported('binary plist dictionary key that is not a string');
+ }
+ keys.push(key);
+ }
+ const entries: [string, ApplePlistValue][] = [];
+ for (let index = 0; index < length; index += 1) {
+ const value = this.readObjectByIndex(
+ this.readObjectRefAt(payload + (length + index) * this.objectRefSize),
+ );
+ entries.push([keys[index]!, value]);
+ }
+ return Object.fromEntries(entries);
+ }
+
+ /** The declared length of a string, data, array or dictionary, and where its payload starts. */
+ private readLengthAt(offset: number, nibble: number): { length: number; payload: number } {
+ if (nibble !== EXTENDED_LENGTH_NIBBLE) return { length: nibble, payload: offset + 1 };
+ const lengthMarker = this.readUint8(offset + 1);
+ if (lengthMarker >> 4 !== KIND_INT) throw malformed('object length that is not an integer');
+ const size = 1 << (lengthMarker & 0x0f);
+ const length = this.readUnsignedAt(offset + 2, size, 'object length');
+ return { length, payload: offset + 2 + size };
+ }
+
+ private readObjectRefAt(offset: number): number {
+ return this.readUnsignedAt(offset, this.objectRefSize, 'object reference');
+ }
+
+ private offsetOfObject(index: number): number {
+ const entry = this.offsetTableOffset + index * this.offsetIntSize;
+ this.requireRange(entry, this.offsetIntSize);
+ const offset = this.readUnsigned(entry, this.offsetIntSize);
+ this.requireRange(offset, 1);
+ return offset;
+ }
+
+ private readTrailerSize(offset: number, what: string): number {
+ const size = this.readUint8(offset);
+ if (size < 1 || size > MAX_NUMBER_BYTES) throw malformed(`${what} of ${size} bytes`);
+ return size;
+ }
+
+ /** The trailer's own fields, which Apple stores unsigned across eight bytes. */
+ private readNumberAt(offset: number, what: string): number {
+ return this.readUnsignedAt(offset, MAX_NUMBER_BYTES, what);
+ }
+
+ private readUnsignedAt(offset: number, size: number, what: string): number {
+ if (size < 1 || size > MAX_NUMBER_BYTES) throw malformed(`${what} of ${size} bytes`);
+ this.requireRange(offset, size);
+ return this.readUnsigned(offset, size);
+ }
+
+ private readUint8(offset: number): number {
+ this.requireRange(offset, 1);
+ return this.view.getUint8(offset);
+ }
+
+ /** Reads `size` big-endian bytes as one unsigned number, the width Apple writes at most. */
+ private readUnsigned(offset: number, size: number): number {
+ let value = 0;
+ for (let index = 0; index < size; index += 1) {
+ value = value * 256 + this.view.getUint8(offset + index);
+ }
+ return value;
+ }
+
+ private requireRange(offset: number, length: number): void {
+ this.require(
+ Number.isSafeInteger(offset) &&
+ offset >= 0 &&
+ Number.isSafeInteger(length) &&
+ length >= 0 &&
+ offset + length <= this.bytes.byteLength,
+ 'bytes past the end of the document',
+ );
+ }
+
+ private require(holds: boolean, detail: string): void {
+ if (!holds) throw malformed(detail);
+ }
+}
+
+function readBinaryPlistValue(bytes: Uint8Array): ApplePlistValue {
+ if (textPrefix(bytes) !== BINARY_MAGIC) throw malformed(`it does not start with ${BINARY_MAGIC}`);
+ return BinaryPlistReader.open(bytes).readTopValue();
+}
+
+function textPrefix(bytes: Uint8Array): string {
+ return String.fromCharCode(...bytes.subarray(0, BINARY_MAGIC.length));
+}
+
+function readSingleton(marker: number): boolean | null {
+ if (marker === 0x00) return null;
+ if (marker === 0x08) return false;
+ if (marker === 0x09) return true;
+ throw malformed(`singleton marker 0x${marker.toString(16)}`);
+}
+
+function malformed(detail: string): ApplePlistParseError {
+ return new ApplePlistParseError(
+ APPLE_PLIST_PARSE_REASONS.malformed.reason,
+ `Malformed Apple plist: ${detail}.`,
+ );
+}
+
+function unsupported(detail: string): ApplePlistParseError {
+ return new ApplePlistParseError(
+ APPLE_PLIST_PARSE_REASONS.unsupportedType.reason,
+ `Unsupported Apple plist: ${detail}.`,
+ );
+}
diff --git a/packages/platform-apple/src/core/plist.ts b/packages/platform-apple/src/core/plist.ts
index 14a69520db..97c40e0cb2 100644
--- a/packages/platform-apple/src/core/plist.ts
+++ b/packages/platform-apple/src/core/plist.ts
@@ -62,13 +62,3 @@ function readXmlPlistString(plist: string, key: string): string | undefined {
});
return result;
}
-
-/** Parses downloaded app metadata on hosts without Apple's plist tools. */
-export async function parseApplePlist(bytes: Uint8Array): Promise | null> {
- const { parse } = await import('plist');
- const binary = new TextDecoder().decode(bytes.subarray(0, 8)) === 'bplist00';
- const value = parse(binary ? bytes : new TextDecoder().decode(bytes));
- return value !== null && typeof value === 'object' && !Array.isArray(value)
- ? (value as Record)
- : null;
-}
diff --git a/packages/platform-apple/src/plist-facade.ts b/packages/platform-apple/src/plist-facade.ts
new file mode 100644
index 0000000000..50e2552125
--- /dev/null
+++ b/packages/platform-apple/src/plist-facade.ts
@@ -0,0 +1 @@
+export { parseApplePlist } from './core/plist-value.ts';
diff --git a/packages/platform-apple/src/tool-provider-facade.ts b/packages/platform-apple/src/tool-provider-facade.ts
index 2885987906..93f4b168af 100644
--- a/packages/platform-apple/src/tool-provider-facade.ts
+++ b/packages/platform-apple/src/tool-provider-facade.ts
@@ -8,10 +8,6 @@ export {
withAppleToolProvider,
} from './core/tool-provider.ts';
-export async function parseApplePlist(bytes: Uint8Array): Promise | null> {
- const plist = await import('./core/plist.ts');
- return await plist.parseApplePlist(bytes);
-}
export type {
AppleMacOsHostProvider,
ApplePlistProvider,
diff --git a/packages/provider-limrun/src/ios-app-logs.test.ts b/packages/provider-limrun/src/ios-app-logs.test.ts
index f2481904a0..e76810459a 100644
--- a/packages/provider-limrun/src/ios-app-logs.test.ts
+++ b/packages/provider-limrun/src/ios-app-logs.test.ts
@@ -19,7 +19,7 @@ test('scrubs retained, live console, and buffered unified app logs', async () =>
streamSyslog: () => systemStream,
},
} as unknown as Parameters[0],
- async () => async () => ({}),
+ async () => () => ({}),
);
const signal = new AbortController().signal;
const app = 'com.example.app';
diff --git a/packages/provider-limrun/src/ios-files.test.ts b/packages/provider-limrun/src/ios-files.test.ts
index 803862fba2..f3c4aae8fc 100644
--- a/packages/provider-limrun/src/ios-files.test.ts
+++ b/packages/provider-limrun/src/ios-files.test.ts
@@ -18,7 +18,7 @@ test('invalid file list and staging JSON preserve status without a decoder cause
{ apiUrl: 'https://instance.invalid/api', token } as Parameters<
typeof createLimrunSimulatorFiles
>[0],
- async () => ({}),
+ () => ({}),
new AbortController().signal,
);
const file = path.join(await mkdtempForTest('limrun-files-'), 'data.txt');
diff --git a/packages/provider-limrun/src/ios-files.ts b/packages/provider-limrun/src/ios-files.ts
index 6601f06ff8..43adbdb57f 100644
--- a/packages/provider-limrun/src/ios-files.ts
+++ b/packages/provider-limrun/src/ios-files.ts
@@ -222,7 +222,7 @@ export async function readLimrunAppInfo(
timeoutMs,
signal,
});
- return await parsePlist(await fs.readFile(destinationPath, { signal }));
+ return parsePlist(await fs.readFile(destinationPath, { signal }));
} catch (error) {
if (error instanceof AppError && error.details?.statusCode === 404) return null;
throw error;
diff --git a/packages/xml/src/index.test.ts b/packages/xml/src/index.test.ts
index 98f458eb0d..abf2bb37af 100644
--- a/packages/xml/src/index.test.ts
+++ b/packages/xml/src/index.test.ts
@@ -68,6 +68,43 @@ test('parseXmlDocumentSync skips UTF-8 byte order marks', () => {
assert.equal(nodes[0]?.name, 'root');
});
+test('parseXmlDocumentSync with trimText false keeps the spacing a value is written with', () => {
+ const nodes = parseXmlDocumentSync(
+ [
+ '',
+ ' ',
+ ' Name ',
+ ' Padded ',
+ ' ',
+ '',
+ '',
+ ].join('\n'),
+ { trimText: false },
+ );
+
+ const values = nodes[0]!.children;
+ assert.equal(values[0]?.text, ' Name ');
+ assert.equal(values[1]?.text, ' Padded ');
+ assert.equal(values[2]?.text, ' ');
+ assert.equal(values[3]?.text, null);
+});
+
+test('parseXmlDocumentSync with trimText false joins each text segment as written', () => {
+ const nodes = parseXmlDocumentSync('foobaz', {
+ trimText: false,
+ });
+
+ assert.equal(nodes[0]?.text, 'foo bar baz');
+});
+
+test('parseXmlDocumentSync with trimText false keeps text a CDATA section alone holds', () => {
+ const nodes = parseXmlDocumentSync(['', '', ''].join('\n'), {
+ trimText: false,
+ });
+
+ assert.equal(nodes[0]?.text, '\n spaced \n');
+});
+
test('parseXmlDocumentSync rejects mismatched closing tags', () => {
assert.throws(() => parseXmlDocumentSync(''), /Expected <\/child>/);
});
diff --git a/packages/xml/src/internal/parser.ts b/packages/xml/src/internal/parser.ts
index 147d19d13d..20b47cc052 100644
--- a/packages/xml/src/internal/parser.ts
+++ b/packages/xml/src/internal/parser.ts
@@ -22,7 +22,7 @@ export function parseXmlDocumentSync(xml: string, options: XmlParseOptions = {})
`XML document exceeds maximum supported size of ${maxDocumentChars} characters.`,
);
}
- return new LimitedXmlParser(xml).parse();
+ return new LimitedXmlParser(xml, options.trimText ?? true).parse();
}
class LimitedXmlParser {
@@ -30,9 +30,11 @@ class LimitedXmlParser {
private readonly stack: XmlNode[] = [];
private index = 0;
private readonly xml: string;
+ private readonly trimText: boolean;
- constructor(xml: string) {
+ constructor(xml: string, trimText: boolean) {
this.xml = xml;
+ this.trimText = trimText;
}
parse(): XmlNode[] {
@@ -168,14 +170,15 @@ class LimitedXmlParser {
}
private appendText(text: string, decodeEntities: boolean): void {
- const trimmed = text.trim();
- if (!trimmed) return;
+ // Without `trimText`, spacing that is all a node holds is kept: Apple reads the text of
+ // ` ` as three spaces, and spacing between two tags is dropped by
+ // `readText`, which never hands an all-spacing segment to a node that holds a value.
+ const kept = this.trimText ? text.trim() : text;
+ if (!kept) return;
const node = this.stack.at(-1);
if (!node) return;
- // Preserve fast-xml-parser's trimValues behavior for each text segment we keep.
- node.text = `${node.text ?? ''}${
- decodeEntities ? decodeXmlCharacterReferences(trimmed) : trimmed
- }`;
+ // With `trimText`, this keeps fast-xml-parser's trimValues behavior for each kept segment.
+ node.text = `${node.text ?? ''}${decodeEntities ? decodeXmlCharacterReferences(kept) : kept}`;
}
private addNode(node: XmlNode): void {
diff --git a/packages/xml/src/internal/types.ts b/packages/xml/src/internal/types.ts
index 0bedf71aad..c3a854c564 100644
--- a/packages/xml/src/internal/types.ts
+++ b/packages/xml/src/internal/types.ts
@@ -7,4 +7,10 @@ export type XmlNode = {
export type XmlParseOptions = {
maxDocumentChars?: number;
+ /**
+ * When false, the text of a node keeps the spacing it is written with. Only whole segments of text
+ * between tags that hold nothing but spacing are dropped, so the spacing inside a value survives.
+ * Defaults to true, which trims each segment, the way `fast-xml-parser` does with `trimValues`.
+ */
+ trimText?: boolean;
};
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index de8f924c40..7f5538cc63 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -801,9 +801,6 @@ importers:
'@agent-device/test-kit':
specifier: workspace:*
version: link:../test-kit
- plist:
- specifier: 5.0.0
- version: 5.0.0
packages/platform-harmonyos:
devDependencies:
@@ -3502,10 +3499,6 @@ packages:
'@workflow/serde@4.1.0':
resolution: {integrity: sha512-pav4F2BoirECWR7Nf1TKt+2eETcBj7jj4cBefQ8VXQCA6NPkaKeLfj/zMgi+3zYV5ZIBT4GuUiphsj0/b9hPQQ==}
- '@xmldom/xmldom@0.9.12':
- resolution: {integrity: sha512-5AXjrcMClTryPe9LgZrygpB1lj7s0S9E0+W+AHaVKAVyHanafK86iPSvG5xHVSp/jC+VH1UXu0TAEmY279xH7A==}
- engines: {node: '>=14.6'}
-
'@yuku-codegen/binding-android-arm64@0.8.7':
resolution: {integrity: sha512-C/0zV5IhgVdYhGJTwrY0v8dknxlhiKwtVJkMUaexu9/QvRmzlV4vfU3hZlUSgqc2BxQHntL1mCVbDq8j0FRFDw==}
cpu: [arm64]
@@ -5151,10 +5144,6 @@ packages:
engines: {node: '>=20'}
hasBin: true
- plist@5.0.0:
- resolution: {integrity: sha512-20N+g1DvMm/DFRbsvER7tT4wDryq0WunK7VMkDaiJcKNapAnUMkTsAnacFYf8n420F4Hf6/hefgmJRkMb1M0fg==}
- engines: {node: '>=18'}
-
pngjs@7.0.0:
resolution: {integrity: sha512-LKWqWJRhstyYo9pGvgor/ivk2w94eSjE3RGVuzLGlr3NmD8bf7RcYGze1mNdEHRP6TRP6rMuDHk5t44hnTRyow==}
engines: {node: '>=14.19.0'}
@@ -6035,10 +6024,6 @@ packages:
utf-8-validate:
optional: true
- xmlbuilder@15.1.1:
- resolution: {integrity: sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==}
- engines: {node: '>=8.0'}
-
xxhash-wasm@1.1.0:
resolution: {integrity: sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA==}
@@ -7953,8 +7938,6 @@ snapshots:
'@workflow/serde@4.1.0': {}
- '@xmldom/xmldom@0.9.12': {}
-
'@yuku-codegen/binding-android-arm64@0.8.7':
optional: true
@@ -9762,11 +9745,6 @@ snapshots:
playwright-core@1.64.1: {}
- plist@5.0.0:
- dependencies:
- '@xmldom/xmldom': 0.9.12
- xmlbuilder: 15.1.1
-
pngjs@7.0.0: {}
postcss-nested@7.0.2(postcss@8.5.23):
@@ -10664,8 +10642,6 @@ snapshots:
ws@8.21.3: {}
- xmlbuilder@15.1.1: {}
-
xxhash-wasm@1.1.0: {}
y18n@5.0.8: {}
diff --git a/scripts/__tests__/eager-closure-budgets.ts b/scripts/__tests__/eager-closure-budgets.ts
index b8e9f0341a..e39ae67a50 100644
--- a/scripts/__tests__/eager-closure-budgets.ts
+++ b/scripts/__tests__/eager-closure-budgets.ts
@@ -208,6 +208,7 @@ const APPLE_DOMAIN_MECHANICS_ENTRY_FILES: ReadonlySet = new Set([
'packages/platform-apple/src/install-artifact-facade.ts',
'packages/platform-apple/src/perf-facade.ts',
'packages/platform-apple/src/physical-device-facade.ts',
+ 'packages/platform-apple/src/plist-facade.ts',
'packages/platform-apple/src/runner-operations-facade.ts',
'packages/platform-apple/src/runner-owner-facade.ts',
'packages/platform-apple/src/simctl-facade.ts',
diff --git a/scripts/layering/package-boundaries.test.ts b/scripts/layering/package-boundaries.test.ts
index bf99294d06..9000b54cbe 100644
--- a/scripts/layering/package-boundaries.test.ts
+++ b/scripts/layering/package-boundaries.test.ts
@@ -647,6 +647,7 @@ test('the real tree parses, declares, and passes R11', () => {
'@agent-device/platform-apple/macos-leaf',
'@agent-device/platform-apple/perf',
'@agent-device/platform-apple/physical-device',
+ '@agent-device/platform-apple/plist',
'@agent-device/platform-apple/runner-owner',
'@agent-device/platform-apple/runner/operations',
'@agent-device/platform-apple/session-observation',
diff --git a/scripts/layering/platform-package-policy.fixtures.ts b/scripts/layering/platform-package-policy.fixtures.ts
index 1d076e4a07..780e6e0a69 100644
--- a/scripts/layering/platform-package-policy.fixtures.ts
+++ b/scripts/layering/platform-package-policy.fixtures.ts
@@ -77,6 +77,7 @@ function familyDeclarations(): PlatformPackageDeclaration[] {
'@agent-device/platform-apple/macos-leaf',
'@agent-device/platform-apple/perf',
'@agent-device/platform-apple/physical-device',
+ '@agent-device/platform-apple/plist',
'@agent-device/platform-apple/runner/operations',
'@agent-device/platform-apple/runner-owner',
'@agent-device/platform-apple/session-observation',
diff --git a/scripts/layering/platform-package-policy.test.ts b/scripts/layering/platform-package-policy.test.ts
index 2acf8289f4..3d0033af95 100644
--- a/scripts/layering/platform-package-policy.test.ts
+++ b/scripts/layering/platform-package-policy.test.ts
@@ -286,6 +286,7 @@ test('the Apple domain facades preserve synchronous helpers without widening the
'@agent-device/platform-apple/install-artifact',
'@agent-device/platform-apple/perf',
'@agent-device/platform-apple/physical-device',
+ '@agent-device/platform-apple/plist',
'@agent-device/platform-apple/runner-owner',
'@agent-device/platform-apple/simctl',
'@agent-device/platform-apple/snapshot-source',
@@ -294,7 +295,6 @@ test('the Apple domain facades preserve synchronous helpers without widening the
]) {
sources.set('src/platform-runtime-domain-facade.ts', `import '${specifier}';`);
assert.deepEqual(checkPlatformPackagePolicy(sources, declarations(), policyOptions()), []);
- sources.delete('src/platform-runtime-domain-facade.ts');
}
const widened = declarations();
diff --git a/scripts/layering/platform-package-policy.ts b/scripts/layering/platform-package-policy.ts
index dd190870ab..b9b1398642 100644
--- a/scripts/layering/platform-package-policy.ts
+++ b/scripts/layering/platform-package-policy.ts
@@ -108,6 +108,7 @@ const MECHANICS_FACET_SUBPATHS: Readonly {
- const [runner, tools, { buildSimctlArgsForDevice }, { createAppleApplicationTools }] =
- await Promise.all([
- import('@agent-device/platform-apple/runner/operations'),
- import('@agent-device/platform-apple/tool-provider'),
- import('@agent-device/platform-apple/simctl'),
- import('./platform-runtime-apple-application-tools.ts'),
- ]);
+ const [
+ runner,
+ tools,
+ { buildSimctlArgsForDevice },
+ { createAppleApplicationTools },
+ { parseApplePlist },
+ ] = await Promise.all([
+ import('@agent-device/platform-apple/runner/operations'),
+ import('@agent-device/platform-apple/tool-provider'),
+ import('@agent-device/platform-apple/simctl'),
+ import('./platform-runtime-apple-application-tools.ts'),
+ import('@agent-device/platform-apple/plist'),
+ ]);
const { resolveOpenTarget, applyRuntimeHints, clearRuntimeHints } = createAppleApplicationTools(
host.env,
);
@@ -148,7 +154,7 @@ async function createProviderAppleHost(
hasScopedProvider: tools.hasScopedAppleToolProvider,
runXcrun: tools.runXcrun,
simctlArgsForDevice: buildSimctlArgsForDevice,
- parsePlist: tools.parseApplePlist,
+ parsePlist: parseApplePlist,
}),
readBundleAppName: async (appPath) =>
await runOnHost(async () => {
diff --git a/src/sdk/plugin-device-host.ts b/src/sdk/plugin-device-host.ts
index f7d295cade..49cef40263 100644
--- a/src/sdk/plugin-device-host.ts
+++ b/src/sdk/plugin-device-host.ts
@@ -22,6 +22,7 @@ type AndroidAdbInvocation = import('@agent-device/platform-android/mechanics').A
type AndroidAdbExecutor = Parameters[0];
type AndroidPerfOperations = Awaited>;
type AppleRunnerOperations = typeof import('@agent-device/platform-apple/runner/operations');
+type ApplePlistModule = typeof import('@agent-device/platform-apple/plist');
type AppleToolProviderModule = typeof import('@agent-device/platform-apple/tool-provider');
type HostRetry = typeof import('@agent-device/host-kit/retry');
@@ -114,7 +115,7 @@ export type ProviderAppleHost = Readonly<{
hasScopedProvider: AppleToolProviderModule['hasScopedAppleToolProvider'];
runXcrun: AppleToolProviderModule['runXcrun'];
simctlArgsForDevice: typeof import('@agent-device/platform-apple/simctl').buildSimctlArgsForDevice;
- parsePlist: AppleToolProviderModule['parseApplePlist'];
+ parsePlist: ApplePlistModule['parseApplePlist'];
}>;
readBundleAppName(appPath: string): Promise;
}>;
diff --git a/tsdown.config.ts b/tsdown.config.ts
index f6d1acb178..310aa1d567 100644
--- a/tsdown.config.ts
+++ b/tsdown.config.ts
@@ -62,7 +62,6 @@ export default defineConfig({
deps: {
alwaysBundle: [/^@agent-device\//],
onlyBundle: [
- '@xmldom/xmldom',
'b4a',
'events-universal',
'fast-fifo',
@@ -71,14 +70,12 @@ export default defineConfig({
'ip-address',
'jpeg-js',
'pend',
- 'plist',
'pngjs',
'smart-buffer',
'socks',
'streamx',
'tar-stream',
'text-decoder',
- 'xmlbuilder',
'yaml',
'yauzl',
],
diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md
index e0aad7780f..7d289f84a5 100644
--- a/website/docs/docs/error-reasons.md
+++ b/website/docs/docs/error-reasons.md
@@ -149,6 +149,13 @@ These reasons can come from more than one command.
| --- | --- |
| `app-list-unreadable` | `simctl` produced no list of the simulator's installed apps, so the app could not be resolved. |
+### Apple plist
+
+| Reason | Meaning |
+| --- | --- |
+| `apple_plist_malformed` | The document is damaged, refers to itself, or is larger than a reader's budget. |
+| `apple_plist_unsupported_type` | The document is well formed but names a value kind or key type this reader does not model. |
+
### Apple runner
| Reason | Meaning |