@tapflowio/ios-agent 0.27.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,12 @@
1
+ @tapflowio/ios-agent — Third-Party Notices
2
+
3
+ This package is licensed under the MIT License (see LICENSE).
4
+
5
+ It includes logic derived from baguette
6
+ (https://github.com/tddworks/baguette),
7
+ licensed under the Apache License, Version 2.0 (see LICENSE-APACHE-2.0).
8
+
9
+ It includes a list of launchd labels selected from simslim
10
+ (https://github.com/MobAI-App/simslim),
11
+ licensed under the MIT License. Copyright (c) 2026 Interlap.
12
+ The full notice is in dist/leanLabels.js.
@@ -1,11 +1,39 @@
1
1
  import type { ChromeData, ChromeButton, ChromeRect } from '@tapflowio/protocol';
2
+ /** Runs a tool and resolves its stdout. Killing on timeout ends the swift interpreter too: the `swift`
3
+ * driver execs into `swift-frontend` under the same pid (measured). */
4
+ export type ChromeRunner = (cmd: string, args: string[], timeoutMs: number, signal: AbortSignal) => Promise<Buffer>;
2
5
  type ScreenSize = {
3
6
  width: number;
4
7
  height: number;
5
8
  };
6
9
  export declare function screenSizeFromDeviceType(profile: unknown, capabilities: unknown): ScreenSize | null;
10
+ export interface DeviceChromeLoaderOptions {
11
+ run?: ChromeRunner;
12
+ chromeMapPath?: string;
13
+ chromeDir?: string;
14
+ profilesDir?: string;
15
+ /** Where rendered PNGs are cached, and the render scripts written. */
16
+ cacheDir?: string;
17
+ loadBudgetMs?: number;
18
+ }
7
19
  export declare class DeviceChromeLoader {
8
- load(typeIdentifier: string): ChromeData | null;
20
+ private readonly run;
21
+ private readonly chromeMapPath;
22
+ private readonly chromeDir;
23
+ private readonly profilesDir;
24
+ private readonly cacheDir;
25
+ private readonly loadBudgetMs;
26
+ /** One load per device type at a time, and its result for the life of the process. A failure is not kept:
27
+ * the dashboard mounts no viewer at all without chrome, so remembering a `null` from one slow first boot
28
+ * would leave that model blank until the agent restarted. Xcode updated under a running agent keeps the old
29
+ * chrome until restart — this bypasses the disk cache's mtime check. */
30
+ private readonly loads;
31
+ private deviceTypes;
32
+ constructor(options?: DeviceChromeLoaderOptions);
33
+ load(typeIdentifier: string): Promise<ChromeData | null>;
34
+ /** Once per process when it succeeds: it used to run twice on every boot. */
35
+ private listDeviceTypes;
36
+ private loadUncached;
9
37
  }
10
38
  export type { ChromeData, ChromeButton, ChromeRect };
11
39
  //# sourceMappingURL=DeviceChromeLoader.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"DeviceChromeLoader.d.ts","sourceRoot":"","sources":["../src/DeviceChromeLoader.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAiiB/E,KAAK,UAAU,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAA;AAmBnD,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,OAAO,GAAG,UAAU,GAAG,IAAI,CAiBnG;AAqFD,qBAAa,kBAAkB;IAC7B,IAAI,CAAC,cAAc,EAAE,MAAM,GAAG,UAAU,GAAG,IAAI;CAqMhD;AAED,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,EAAE,CAAA"}
1
+ {"version":3,"file":"DeviceChromeLoader.d.ts","sourceRoot":"","sources":["../src/DeviceChromeLoader.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAA;AAgB/E;wEACwE;AACxE,MAAM,MAAM,YAAY,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,MAAM,CAAC,CAAA;AAkjBnH,KAAK,UAAU,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAA;AAmBnD,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,OAAO,GAAG,UAAU,GAAG,IAAI,CAiBnG;AAgFD,MAAM,WAAW,yBAAyB;IACxC,GAAG,CAAC,EAAE,YAAY,CAAA;IAClB,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,sEAAsE;IACtE,QAAQ,CAAC,EAAE,MAAM,CAAA;IACjB,YAAY,CAAC,EAAE,MAAM,CAAA;CACtB;AAED,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAc;IAClC,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAQ;IACtC,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAQ;IAClC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAQ;IACpC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAQ;IACjC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAQ;IACrC;;;6EAGyE;IACzE,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAgD;IACtE,OAAO,CAAC,WAAW,CAAgC;gBAEvC,OAAO,GAAE,yBAA8B;IASnD,IAAI,CAAC,cAAc,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC;IAgBxD,6EAA6E;YAC/D,eAAe;YAQf,YAAY;CAyM3B;AAED,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,EAAE,CAAA"}
@@ -1,25 +1,53 @@
1
1
  // Button layout logic (computeButtonLayout) is derived from baguette (Apache-2.0):
2
2
  // https://github.com/tddworks/baguette
3
- import { execFileSync } from 'child_process';
4
- import { existsSync, readFileSync, writeFileSync, statSync } from 'fs';
3
+ import { execFile } from 'child_process';
4
+ import { existsSync, readFileSync, statSync } from 'fs';
5
+ import { rename, rm, writeFile } from 'fs/promises';
5
6
  import { join } from 'path';
6
7
  import { tmpdir } from 'os';
7
8
  const CHROME_MAP_PATH = '/Library/Developer/DeviceKit/chrome_map.plist';
8
9
  const CHROME_DIR = '/Library/Developer/DeviceKit/Chrome';
9
10
  const PROFILES_DIR = '/Library/Developer/CoreSimulator/Profiles/DeviceTypes';
10
- // ---------------------------------------------------------------------------
11
- // Utilities
12
- // ---------------------------------------------------------------------------
13
- function readPlistAsJson(filePath) {
14
- const json = execFileSync('plutil', ['-convert', 'json', '-o', '-', filePath]);
11
+ const defaultRunner = (cmd, args, timeoutMs, signal) => new Promise((resolve, reject) => {
12
+ execFile(cmd, args, { timeout: timeoutMs, killSignal: 'SIGKILL', signal, encoding: 'buffer', maxBuffer: 16 * 1024 * 1024 }, (err, stdout) => (err ? reject(err) : resolve(stdout)));
13
+ });
14
+ /** Per call: plutil, sips and simctl answer in milliseconds; a swift render compiles first. */
15
+ const TOOL_TIMEOUT_MS = 10_000;
16
+ const SWIFT_TIMEOUT_MS = 45_000;
17
+ /** For a whole load. A cold cache runs a frame render plus one per button state, so per-call bounds alone
18
+ * could add up to minutes against a boot the relay clients give 180s in total. */
19
+ const LOAD_BUDGET_MS = 60_000;
20
+ let renderSeq = 0;
21
+ async function readPlistAsJson(ctx, filePath) {
22
+ const json = await ctx.run('plutil', ['-convert', 'json', '-o', '-', filePath], TOOL_TIMEOUT_MS, ctx.signal);
15
23
  return JSON.parse(json.toString());
16
24
  }
17
- function getSipsSize(filePath) {
18
- const out = execFileSync('sips', ['-g', 'pixelWidth', '-g', 'pixelHeight', filePath]).toString();
25
+ async function getSipsSize(ctx, filePath) {
26
+ const out = (await ctx.run('sips', ['-g', 'pixelWidth', '-g', 'pixelHeight', filePath], TOOL_TIMEOUT_MS, ctx.signal)).toString();
19
27
  const w = out.match(/pixelWidth:\s*([\d.]+)/);
20
28
  const h = out.match(/pixelHeight:\s*([\d.]+)/);
21
29
  return { width: Math.round(parseFloat(w[1])), height: Math.round(parseFloat(h[1])) };
22
30
  }
31
+ /**
32
+ * Runs a generated swift script that writes one PNG. Both the script and the image get a name of their own:
33
+ * the frame scripts carry per-device geometry in their text, so a shared script path let two concurrent
34
+ * loads render one device with the other's numbers and cache it; and the image is renamed into place, so a
35
+ * render killed half-way, or read by another load mid-write, never leaves a truncated PNG behind as cache.
36
+ */
37
+ async function renderSwift(ctx, script, inputs, outPath) {
38
+ const tag = `${process.pid}-${++renderSeq}`;
39
+ const scriptPath = join(ctx.cacheDir, `tapflow-render-${tag}.swift`);
40
+ const tmpOut = `${outPath}.${tag}.tmp`;
41
+ try {
42
+ await writeFile(scriptPath, script);
43
+ await ctx.run('swift', [scriptPath, ...inputs, tmpOut], SWIFT_TIMEOUT_MS, ctx.signal);
44
+ await rename(tmpOut, outPath);
45
+ }
46
+ finally {
47
+ await rm(scriptPath, { force: true });
48
+ await rm(tmpOut, { force: true });
49
+ }
50
+ }
23
51
  // Mirrors baguette's LiveChromes.computeMargins + buttonTopLeft.
24
52
  // compositeW/H = device body dimensions in 1× PDF pts (before button margin expansion).
25
53
  // For composite PDF: pdfSize.width / pdfSize.height.
@@ -27,7 +55,7 @@ function getSipsSize(filePath) {
27
55
  // leftWidth/rightWidth: bezel sizes; top/bottom-anchor x offsets are measured from
28
56
  // the screen edge (after bezel), so we add leftWidth for leading and subtract
29
57
  // rightWidth for trailing to convert to canvas coordinates.
30
- function computeButtonLayout(inputs, resourcesDir, compositeW, compositeH, scale = 2, leftWidth = 0, rightWidth = 0) {
58
+ async function computeButtonLayout(ctx, inputs, resourcesDir, compositeW, compositeH, scale = 2, leftWidth = 0, rightWidth = 0) {
31
59
  const margins = { left: 0, top: 0, right: 0, bottom: 0 };
32
60
  const infos = [];
33
61
  for (const inp of inputs) {
@@ -37,11 +65,13 @@ function computeButtonLayout(inputs, resourcesDir, compositeW, compositeH, scale
37
65
  if (!existsSync(pdfPath))
38
66
  continue;
39
67
  try {
40
- const size = getSipsSize(pdfPath);
68
+ const size = await getSipsSize(ctx, pdfPath);
41
69
  const roll = inp.offsets.rollover ?? inp.offsets.normal;
42
70
  infos.push({ input: inp, w: size.width, h: size.height, roll });
43
71
  }
44
- catch { /* skip unmeasurable assets */ }
72
+ catch {
73
+ ctx.incomplete = true; /* skip unmeasurable assets */
74
+ }
45
75
  }
46
76
  // Pass 1 — margins (baguette's computeMargins, rollover offset)
47
77
  for (const { input: inp, w, h, roll } of infos) {
@@ -115,7 +145,7 @@ function computeButtonLayout(inputs, resourcesDir, compositeW, compositeH, scale
115
145
  const downPath = join(resourcesDir, `${inp.imageDown}.pdf`);
116
146
  if (existsSync(downPath)) {
117
147
  try {
118
- const downSize = getSipsSize(downPath);
148
+ const downSize = await getSipsSize(ctx, downPath);
119
149
  pressed = {
120
150
  pdfPath: downPath,
121
151
  topLeftX: btnTopLeftX,
@@ -124,7 +154,9 @@ function computeButtonLayout(inputs, resourcesDir, compositeW, compositeH, scale
124
154
  pdfH: downSize.height,
125
155
  };
126
156
  }
127
- catch { /* skip unmeasurable pressed asset */ }
157
+ catch {
158
+ ctx.incomplete = true; /* skip unmeasurable pressed asset */
159
+ }
128
160
  }
129
161
  }
130
162
  pressedData.push(pressed);
@@ -186,7 +218,7 @@ function computeButtonLayout(inputs, resourcesDir, compositeW, compositeH, scale
186
218
  // ---------------------------------------------------------------------------
187
219
  // Single PDF → PNG at 2× (used for pressed-state button images)
188
220
  // ---------------------------------------------------------------------------
189
- function renderPdfToPng(pdfPath, outPath) {
221
+ function renderPdfToPng(ctx, pdfPath, outPath) {
190
222
  const SCRIPT = `
191
223
  import Foundation
192
224
  import CoreGraphics
@@ -217,15 +249,13 @@ let dest = CGImageDestinationCreateWithURL(URL(fileURLWithPath: dst) as CFURL, "
217
249
  CGImageDestinationAddImage(dest, img, nil)
218
250
  CGImageDestinationFinalize(dest)
219
251
  `;
220
- const scriptPath = join(tmpdir(), 'tapflow-pdf-to-png.swift');
221
- writeFileSync(scriptPath, SCRIPT);
222
- execFileSync('swift', [scriptPath, pdfPath, outPath]);
252
+ return renderSwift(ctx, SCRIPT, [pdfPath], outPath);
223
253
  }
224
254
  // ---------------------------------------------------------------------------
225
255
  // Frame PNG rendering — composite PDF path
226
256
  // Renders composite PDF + physical button PDFs into one PNG at 2×.
227
257
  // ---------------------------------------------------------------------------
228
- function renderFramePng(compositePdf, outPath, margins, buttons) {
258
+ function renderFramePng(ctx, compositePdf, outPath, margins, buttons) {
229
259
  const behind = buttons.filter(b => !b.onTop);
230
260
  const onTop = buttons.filter(b => b.onTop);
231
261
  function btnLiteral(b) {
@@ -297,16 +327,14 @@ let dest = CGImageDestinationCreateWithURL(URL(fileURLWithPath: dst) as CFURL, "
297
327
  CGImageDestinationAddImage(dest, img, nil)
298
328
  CGImageDestinationFinalize(dest)
299
329
  `;
300
- const scriptPath = join(tmpdir(), 'tapflow-frame-png.swift');
301
- writeFileSync(scriptPath, SCRIPT);
302
- execFileSync('swift', [scriptPath, compositePdf, outPath]);
330
+ return renderSwift(ctx, SCRIPT, [compositePdf], outPath);
303
331
  }
304
332
  // ---------------------------------------------------------------------------
305
333
  // Frame PNG rendering — nine-slice path
306
334
  // Rasterizes 8 PDF slices to bitmaps, composes them around the screen hole,
307
335
  // then draws physical button PDFs. Matches baguette's compose9Slice approach.
308
336
  // ---------------------------------------------------------------------------
309
- function renderNineSlicePng(slicePaths, outPath, leftWidth, rightWidth, topHeight, bottomHeight, cornerW, cornerH, screenW, screenH, margins, buttons) {
337
+ function renderNineSlicePng(ctx, slicePaths, outPath, leftWidth, rightWidth, topHeight, bottomHeight, cornerW, cornerH, screenW, screenH, margins, buttons) {
310
338
  const behind = buttons.filter(b => !b.onTop);
311
339
  const onTop = buttons.filter(b => b.onTop);
312
340
  function btnLiteral(b) {
@@ -437,22 +465,7 @@ let dest = CGImageDestinationCreateWithURL(URL(fileURLWithPath: dst) as CFURL,
437
465
  CGImageDestinationAddImage(dest, outImg, nil)
438
466
  CGImageDestinationFinalize(dest)
439
467
  `;
440
- const scriptPath = join(tmpdir(), 'tapflow-frame-nineslice.swift');
441
- writeFileSync(scriptPath, SCRIPT);
442
- execFileSync('swift', [scriptPath, outPath]);
443
- }
444
- // ---------------------------------------------------------------------------
445
- // Model identifier and profile lookups
446
- // ---------------------------------------------------------------------------
447
- function modelIdentifierForType(typeIdentifier) {
448
- try {
449
- const out = execFileSync('xcrun', ['simctl', 'list', 'devicetypes', '-j']);
450
- const types = JSON.parse(out.toString())['devicetypes'];
451
- return types.find(t => t.identifier === typeIdentifier)?.modelIdentifier ?? null;
452
- }
453
- catch {
454
- return null;
455
- }
468
+ return renderSwift(ctx, SCRIPT, [], outPath);
456
469
  }
457
470
  // Physical px ÷ scale → logical points. A missing or non-positive value is no answer rather than a
458
471
  // wrong one.
@@ -496,19 +509,16 @@ export function screenSizeFromDeviceType(profile, capabilities) {
496
509
  }
497
510
  return null;
498
511
  }
499
- function loadProfileScreenSize(typeIdentifier) {
512
+ async function loadProfileScreenSize(ctx, profilesDir, name) {
500
513
  try {
501
- const out = execFileSync('xcrun', ['simctl', 'list', 'devicetypes', '-j']);
502
- const types = JSON.parse(out.toString())['devicetypes'];
503
- const name = types.find(t => t.identifier === typeIdentifier)?.name;
504
514
  if (!name)
505
515
  return null;
506
- const resourcesDir = join(PROFILES_DIR, `${name}.simdevicetype`, 'Contents', 'Resources');
516
+ const resourcesDir = join(profilesDir, `${name}.simdevicetype`, 'Contents', 'Resources');
507
517
  const plistPath = join(resourcesDir, 'profile.plist');
508
518
  if (!existsSync(plistPath))
509
519
  return null;
510
520
  const capabilitiesPath = join(resourcesDir, 'capabilities.plist');
511
- return screenSizeFromDeviceType(readPlistAsJson(plistPath), existsSync(capabilitiesPath) ? readPlistAsJson(capabilitiesPath) : null);
521
+ return screenSizeFromDeviceType(await readPlistAsJson(ctx, plistPath), existsSync(capabilitiesPath) ? await readPlistAsJson(ctx, capabilitiesPath) : null);
512
522
  }
513
523
  catch {
514
524
  return null;
@@ -517,35 +527,37 @@ function loadProfileScreenSize(typeIdentifier) {
517
527
  // ---------------------------------------------------------------------------
518
528
  // Button PNG attachment — renders each button's normal PDF separately for CSS overlay
519
529
  // ---------------------------------------------------------------------------
520
- function attachButtonPngs(buttons, drawData, chromeName) {
530
+ async function attachButtonPngs(ctx, buttons, drawData, chromeName) {
521
531
  for (let i = 0; i < buttons.length; i++) {
522
532
  if (i >= drawData.length)
523
533
  continue;
524
534
  const pdfPath = drawData[i].pdfPath;
525
535
  const cacheKey = `tapflow-btn-normal-${chromeName}-${i}.png`;
526
- const outPath = join(tmpdir(), cacheKey);
536
+ const outPath = join(ctx.cacheDir, cacheKey);
527
537
  try {
528
538
  if (!existsSync(outPath) || statSync(pdfPath).mtimeMs > statSync(outPath).mtimeMs) {
529
- renderPdfToPng(pdfPath, outPath);
539
+ await renderPdfToPng(ctx, pdfPath, outPath);
530
540
  }
531
541
  buttons[i].buttonPng = readFileSync(outPath).toString('base64');
532
542
  }
533
- catch { /* skip if rendering fails */ }
543
+ catch {
544
+ ctx.incomplete = true; /* skip if rendering fails */
545
+ }
534
546
  }
535
547
  }
536
548
  // ---------------------------------------------------------------------------
537
549
  // Pressed PNG attachment — renders imageDown PDFs and attaches to buttons[]
538
550
  // ---------------------------------------------------------------------------
539
- function attachPressedPngs(buttons, pressedData, chromeName, scale) {
551
+ async function attachPressedPngs(ctx, buttons, pressedData, chromeName, scale) {
540
552
  for (let i = 0; i < buttons.length; i++) {
541
553
  const pd = pressedData[i];
542
554
  if (!pd)
543
555
  continue;
544
556
  const cacheKey = `tapflow-btn-pressed-${chromeName}-${i}.png`;
545
- const outPath = join(tmpdir(), cacheKey);
557
+ const outPath = join(ctx.cacheDir, cacheKey);
546
558
  try {
547
559
  if (!existsSync(outPath) || statSync(pd.pdfPath).mtimeMs > statSync(outPath).mtimeMs) {
548
- renderPdfToPng(pd.pdfPath, outPath);
560
+ await renderPdfToPng(ctx, pd.pdfPath, outPath);
549
561
  }
550
562
  buttons[i].pressedPng = readFileSync(outPath).toString('base64');
551
563
  buttons[i].pressedRect = {
@@ -555,24 +567,71 @@ function attachPressedPngs(buttons, pressedData, chromeName, scale) {
555
567
  height: Math.round(pd.pdfH * scale),
556
568
  };
557
569
  }
558
- catch { /* skip if rendering fails */ }
570
+ catch {
571
+ ctx.incomplete = true; /* skip if rendering fails */
572
+ }
559
573
  }
560
574
  }
561
- // ---------------------------------------------------------------------------
562
- // DeviceChromeLoader
563
- // ---------------------------------------------------------------------------
564
575
  export class DeviceChromeLoader {
576
+ run;
577
+ chromeMapPath;
578
+ chromeDir;
579
+ profilesDir;
580
+ cacheDir;
581
+ loadBudgetMs;
582
+ /** One load per device type at a time, and its result for the life of the process. A failure is not kept:
583
+ * the dashboard mounts no viewer at all without chrome, so remembering a `null` from one slow first boot
584
+ * would leave that model blank until the agent restarted. Xcode updated under a running agent keeps the old
585
+ * chrome until restart — this bypasses the disk cache's mtime check. */
586
+ loads = new Map();
587
+ deviceTypes = null;
588
+ constructor(options = {}) {
589
+ this.run = options.run ?? defaultRunner;
590
+ this.chromeMapPath = options.chromeMapPath ?? CHROME_MAP_PATH;
591
+ this.chromeDir = options.chromeDir ?? CHROME_DIR;
592
+ this.profilesDir = options.profilesDir ?? PROFILES_DIR;
593
+ this.cacheDir = options.cacheDir ?? tmpdir();
594
+ this.loadBudgetMs = options.loadBudgetMs ?? LOAD_BUDGET_MS;
595
+ }
565
596
  load(typeIdentifier) {
597
+ const pending = this.loads.get(typeIdentifier);
598
+ if (pending)
599
+ return pending;
600
+ const budget = new AbortController();
601
+ const timer = setTimeout(() => budget.abort(), this.loadBudgetMs);
602
+ timer.unref?.();
603
+ const ctx = { run: this.run, signal: budget.signal, cacheDir: this.cacheDir, incomplete: false };
604
+ const loading = this.loadUncached(typeIdentifier, ctx).catch(() => null).finally(() => clearTimeout(timer));
605
+ this.loads.set(typeIdentifier, loading);
606
+ // A load that skipped a button still gives this boot a device, but is not kept: the budget usually runs
607
+ // out in the button renders, and remembering that result would hide those buttons until a restart. What
608
+ // did render is on disk, so the next boot picks up where this one stopped.
609
+ void loading.then((chrome) => { if (!chrome || ctx.incomplete)
610
+ this.loads.delete(typeIdentifier); });
611
+ return loading;
612
+ }
613
+ /** Once per process when it succeeds: it used to run twice on every boot. */
614
+ async listDeviceTypes(ctx) {
615
+ if (this.deviceTypes)
616
+ return this.deviceTypes;
617
+ const out = await ctx.run('xcrun', ['simctl', 'list', 'devicetypes', '-j'], TOOL_TIMEOUT_MS, ctx.signal);
618
+ const types = JSON.parse(out.toString())['devicetypes'];
619
+ this.deviceTypes = types;
620
+ return types;
621
+ }
622
+ async loadUncached(typeIdentifier, ctx) {
566
623
  try {
567
- const modelId = modelIdentifierForType(typeIdentifier);
624
+ const types = await this.listDeviceTypes(ctx);
625
+ const typeInfo = types.find(t => t.identifier === typeIdentifier);
626
+ const modelId = typeInfo?.modelIdentifier;
568
627
  if (!modelId)
569
628
  return null;
570
- const chromeMap = readPlistAsJson(CHROME_MAP_PATH);
629
+ const chromeMap = await readPlistAsJson(ctx, this.chromeMapPath);
571
630
  const entry = chromeMap[modelId];
572
631
  if (!entry)
573
632
  return null;
574
633
  const chromeName = entry.ChromeIdentifier.split('.').pop();
575
- const resourcesDir = join(CHROME_DIR, `${chromeName}.devicechrome`, 'Contents', 'Resources');
634
+ const resourcesDir = join(this.chromeDir, `${chromeName}.devicechrome`, 'Contents', 'Resources');
576
635
  const chromeJsonPath = join(resourcesDir, 'chrome.json');
577
636
  if (!existsSync(chromeJsonPath))
578
637
  return null;
@@ -592,21 +651,23 @@ export class DeviceChromeLoader {
592
651
  // -----------------------------------------------------------------------
593
652
  const compositePdf = join(resourcesDir, 'PhoneComposite.pdf');
594
653
  if (existsSync(compositePdf)) {
595
- const pdfSize = getSipsSize(compositePdf);
654
+ const pdfSize = await getSipsSize(ctx, compositePdf);
596
655
  const screenW = pdfSize.width - leftWidth - rightWidth;
597
656
  const screenH = pdfSize.height - topHeight - bottomHeight;
598
657
  const bezelInset = Math.max(leftWidth, topHeight);
599
658
  const screenCornerRadius1x = Math.max(0, outerRadius - bezelInset);
600
- const { margins: btnM, drawData, buttons, pressedData } = computeButtonLayout(rawInputs, resourcesDir, pdfSize.width, pdfSize.height, scale, leftWidth, rightWidth);
659
+ const { margins: btnM, drawData, buttons, pressedData } = await computeButtonLayout(ctx, rawInputs, resourcesDir, pdfSize.width, pdfSize.height, scale, leftWidth, rightWidth);
601
660
  const expandedW = pdfSize.width + btnM.left + btnM.right;
602
661
  const expandedH = pdfSize.height + btnM.top + btnM.bottom;
603
- // v3: buttons excluded from framePng — rendered separately as CSS-animated overlays
604
- const framePath = join(tmpdir(), `tapflow-frame-v3-${chromeName}.png`);
662
+ // v3: buttons excluded from framePng — rendered separately as CSS-animated overlays.
663
+ // The canvas size is in the key, as for nine-slice: a button that could not be measured shrinks the
664
+ // margins, and a frame rendered that way must not be served to a later load that measured them all.
665
+ const framePath = join(this.cacheDir, `tapflow-frame-v3-${chromeName}-c${Math.round(expandedW)}x${Math.round(expandedH)}.png`);
605
666
  if (!existsSync(framePath) || statSync(compositePdf).mtimeMs > statSync(framePath).mtimeMs) {
606
- renderFramePng(compositePdf, framePath, btnM, []);
667
+ await renderFramePng(ctx, compositePdf, framePath, btnM, []);
607
668
  }
608
- attachButtonPngs(buttons, drawData, chromeName);
609
- attachPressedPngs(buttons, pressedData, chromeName, scale);
669
+ await attachButtonPngs(ctx, buttons, drawData, chromeName);
670
+ await attachPressedPngs(ctx, buttons, pressedData, chromeName, scale);
610
671
  const screenRect = {
611
672
  x: Math.round((leftWidth + btnM.left) * scale),
612
673
  y: Math.round((topHeight + btnM.top) * scale),
@@ -659,11 +720,11 @@ export class DeviceChromeLoader {
659
720
  // Corner PDF dimensions define the actual bezel insets used in composition.
660
721
  // The sizing.leftWidth/rightWidth in chrome.json is the VISIBLE bezel width
661
722
  // (interior of the corner), not the full corner PDF dimensions.
662
- const cornerSize = getSipsSize(slicePaths.topLeft);
723
+ const cornerSize = await getSipsSize(ctx, slicePaths.topLeft);
663
724
  const cornerW = cornerSize.width;
664
725
  const cornerH = cornerSize.height; // should equal topHeight from sizing
665
726
  // Get logical screen dimensions from the device type's plists
666
- const screenSize = loadProfileScreenSize(typeIdentifier);
727
+ const screenSize = await loadProfileScreenSize(ctx, this.profilesDir, typeInfo?.name);
667
728
  if (!screenSize)
668
729
  return null;
669
730
  const screenW = screenSize.width;
@@ -673,18 +734,18 @@ export class DeviceChromeLoader {
673
734
  const compositeH = topHeight + screenH + bottomHeight;
674
735
  const bezelInset = Math.max(leftWidth, topHeight);
675
736
  const screenCornerRadius1x = Math.max(0, outerRadius - bezelInset);
676
- const { margins: btnM, drawData, buttons, pressedData } = computeButtonLayout(rawInputs, resourcesDir, compositeW, compositeH, scale, leftWidth, rightWidth);
737
+ const { margins: btnM, drawData, buttons, pressedData } = await computeButtonLayout(ctx, rawInputs, resourcesDir, compositeW, compositeH, scale, leftWidth, rightWidth);
677
738
  const expandedW = compositeW + btnM.left + btnM.right;
678
739
  const expandedH = compositeH + btnM.top + btnM.bottom;
679
740
  // nb = no-buttons: buttons excluded from framePng, rendered separately as CSS-animated overlays
680
- const framePath = join(tmpdir(), `tapflow-frame-nineslice-nb-${chromeName}-${screenW}x${screenH}-c${Math.round(expandedW)}x${Math.round(expandedH)}.png`);
741
+ const framePath = join(this.cacheDir, `tapflow-frame-nineslice-nb-${chromeName}-${screenW}x${screenH}-c${Math.round(expandedW)}x${Math.round(expandedH)}.png`);
681
742
  const needsRender = !existsSync(framePath)
682
743
  || statSync(slicePaths.topLeft).mtimeMs > statSync(framePath).mtimeMs;
683
744
  if (needsRender) {
684
- renderNineSlicePng(slicePaths, framePath, leftWidth, rightWidth, topHeight, bottomHeight, cornerW, cornerH, screenW, screenH, btnM, []);
745
+ await renderNineSlicePng(ctx, slicePaths, framePath, leftWidth, rightWidth, topHeight, bottomHeight, cornerW, cornerH, screenW, screenH, btnM, []);
685
746
  }
686
- attachButtonPngs(buttons, drawData, chromeName);
687
- attachPressedPngs(buttons, pressedData, chromeName, scale);
747
+ await attachButtonPngs(ctx, buttons, drawData, chromeName);
748
+ await attachPressedPngs(ctx, buttons, pressedData, chromeName, scale);
688
749
  // Screen hole: starts at sizing insets within the device body
689
750
  const screenRect = {
690
751
  x: Math.round((btnM.left + leftWidth) * scale),