Open History to see the last commit
1import { existsSync, rmSync } from 'node:fs'
2import { spawn } from 'node:child_process'
3import { dirname, resolve } from 'node:path'
4import { fileURLToPath } from 'node:url'
5
6type RuntimeResultRow = {
7 status: `passed` | `failed`
8 payload: {
9 passed?: number
10 failed?: number
11 skipped?: number
12 total?: number
13 failures?: Array<{
14 name?: string
15 error?: string
16 }>
17 error?: string
18 step?: string
19 runId?: string
20 }
21}
22
23const packageDirectory = dirname(fileURLToPath(import.meta.url))
24const appDirectory = resolve(packageDirectory, `app`)
25const appId = `com.tanstack.db.capacitorsqlitee2e`
26const runtimeRunId = Date.now().toString(36)
27const resultsDatabaseName = `tanstack_db_capacitor_e2e_results_${runtimeRunId}`
28
29function runCommand(
30 command: string,
31 args: Array<string>,
32 options: {
33 cwd?: string
34 env?: NodeJS.ProcessEnv
35 } = {},
36): Promise<void> {
37 return new Promise((resolvePromise, rejectPromise) => {
38 const child = spawn(command, args, {
39 cwd: options.cwd ?? packageDirectory,
40 env: {
41 ...process.env,
42 ...options.env,
43 },
44 stdio: `inherit`,
45 })
46
47 child.on(`exit`, (code) => {
48 if (code === 0) {
49 resolvePromise()
50 return
51 }
52
53 rejectPromise(
54 new Error(
55 `${command} ${args.join(` `)} exited with code ${String(code)}`,
56 ),
57 )
58 })
59 child.on(`error`, rejectPromise)
60 })
61}
62
63async function resolveSimulatorId(): Promise<string> {
64 const requestedId = process.env.TANSTACK_DB_CAPACITOR_IOS_SIMULATOR_ID?.trim()
65 if (requestedId) {
66 return requestedId
67 }
68
69 const devices = await new Promise<string>((resolvePromise, rejectPromise) => {
70 let output = ``
71 const child = spawn(
72 `xcrun`,
73 [`simctl`, `list`, `devices`, `available`, `-j`],
74 {
75 cwd: packageDirectory,
76 stdio: [`ignore`, `pipe`, `inherit`],
77 },
78 )
79
80 child.stdout.on(`data`, (chunk) => {
81 output += String(chunk)
82 })
83 child.on(`exit`, (code) => {
84 if (code === 0) {
85 resolvePromise(output)
86 return
87 }
88
89 rejectPromise(new Error(`Unable to list iOS simulators`))
90 })
91 child.on(`error`, rejectPromise)
92 })
93
94 const parsed = JSON.parse(devices) as {
95 devices: Record<
96 string,
97 Array<{
98 udid: string
99 name: string
100 state: string
101 isAvailable: boolean
102 }>
103 >
104 }
105
106 const availableIPhones = Object.entries(parsed.devices)
107 .filter(([runtime]) => runtime.includes(`iOS`))
108 .flatMap(([, runtimeDevices]) => runtimeDevices)
109 .filter((device) => device.isAvailable && device.name.includes(`iPhone`))
110
111 const bootedDevice = availableIPhones.find(
112 (device) => device.state === `Booted`,
113 )
114 if (bootedDevice) {
115 return bootedDevice.udid
116 }
117
118 const preferredDevice =
119 availableIPhones.find((device) => device.name === `iPhone 16 Pro`) ??
120 availableIPhones[0]
121
122 if (!preferredDevice) {
123 throw new Error(`No available iOS simulator found`)
124 }
125
126 return preferredDevice.udid
127}
128
129async function ensureNativeProject(): Promise<void> {
130 const iosProjectDirectory = resolve(appDirectory, `ios`)
131 const iosXcodeProjectPath = resolve(
132 iosProjectDirectory,
133 `App`,
134 `App.xcodeproj`,
135 )
136 const iosPodfilePath = resolve(iosProjectDirectory, `App`, `Podfile`)
137
138 if (existsSync(iosXcodeProjectPath) && !existsSync(iosPodfilePath)) {
139 rmSync(iosProjectDirectory, {
140 recursive: true,
141 force: true,
142 })
143 }
144
145 if (!existsSync(iosXcodeProjectPath)) {
146 await runCommand(`pnpm`, [`run`, `native:add:ios`], {
147 cwd: appDirectory,
148 })
149 }
150
151 await runCommand(`pnpm`, [`build`], {
152 cwd: appDirectory,
153 env: {
154 VITE_TANSTACK_DB_CAPACITOR_E2E_RUN_ID: runtimeRunId,
155 },
156 })
157 await runCommand(`pnpm`, [`exec`, `cap`, `sync`, `ios`], {
158 cwd: appDirectory,
159 })
160}
161
162async function resolveAppDataContainer(): Promise<string> {
163 return new Promise((resolvePromise, rejectPromise) => {
164 let output = ``
165 const child = spawn(
166 `xcrun`,
167 [`simctl`, `get_app_container`, `booted`, appId, `data`],
168 {
169 cwd: appDirectory,
170 stdio: [`ignore`, `pipe`, `inherit`],
171 },
172 )
173
174 child.stdout.on(`data`, (chunk) => {
175 output += String(chunk)
176 })
177 child.on(`exit`, (code) => {
178 if (code === 0) {
179 resolvePromise(output.trim())
180 return
181 }
182
183 rejectPromise(new Error(`Unable to resolve simulator app data container`))
184 })
185 child.on(`error`, rejectPromise)
186 })
187}
188
189async function readSqlScalar(
190 databasePath: string,
191 sql: string,
192): Promise<string | null> {
193 return new Promise((resolvePromise, rejectPromise) => {
194 let output = ``
195 const child = spawn(`sqlite3`, [databasePath, sql], {
196 cwd: appDirectory,
197 stdio: [`ignore`, `pipe`, `ignore`],
198 })
199
200 child.stdout.on(`data`, (chunk) => {
201 output += String(chunk)
202 })
203 child.on(`exit`, (code) => {
204 if (code === 0) {
205 const trimmed = output.trim()
206 resolvePromise(trimmed.length > 0 ? trimmed : null)
207 return
208 }
209
210 rejectPromise(new Error(`sqlite3 query failed`))
211 })
212 child.on(`error`, rejectPromise)
213 })
214}
215
216async function waitForResult(): Promise<RuntimeResultRow> {
217 const simulatorId = await resolveSimulatorId()
218 await ensureNativeProject()
219 await runCommand(`open`, [
220 `-a`,
221 `Simulator`,
222 `--args`,
223 `-CurrentDeviceUDID`,
224 simulatorId,
225 ])
226 await runCommand(`xcrun`, [`simctl`, `boot`, simulatorId]).catch(() =>
227 Promise.resolve(),
228 )
229 await runCommand(`xcrun`, [`simctl`, `bootstatus`, simulatorId, `-b`])
230 await runCommand(`xcrun`, [`simctl`, `terminate`, simulatorId, appId]).catch(
231 () => Promise.resolve(),
232 )
233 await runCommand(
234 `pnpm`,
235 [`exec`, `cap`, `run`, `ios`, `--target`, simulatorId, `--no-sync`],
236 {
237 cwd: appDirectory,
238 },
239 )
240
241 const appDataContainer = await resolveAppDataContainer()
242 const databasePath = resolve(
243 appDataContainer,
244 `Documents`,
245 `${resultsDatabaseName}SQLite.db`,
246 )
247 const deadline = Date.now() + 600_000
248
249 while (Date.now() < deadline) {
250 if (existsSync(databasePath)) {
251 const status = await readSqlScalar(
252 databasePath,
253 `SELECT status FROM test_run_results ORDER BY id DESC LIMIT 1;`,
254 )
255 const payloadJson = await readSqlScalar(
256 databasePath,
257 `SELECT payload_json FROM test_run_results ORDER BY id DESC LIMIT 1;`,
258 )
259
260 if (status && payloadJson) {
261 return {
262 status: status as RuntimeResultRow[`status`],
263 payload: JSON.parse(payloadJson) as RuntimeResultRow[`payload`],
264 }
265 }
266 }
267
268 await new Promise((resolvePromise) => setTimeout(resolvePromise, 1000))
269 }
270
271 throw new Error(`Timed out waiting for native iOS e2e result`)
272}
273
274const result = await waitForResult()
275
276if (result.status !== `passed`) {
277 const firstFailure = result.payload.failures?.[0]
278 throw new Error(
279 result.payload.error ??
280 (firstFailure
281 ? `${firstFailure.name ?? `Unnamed failure`}: ${firstFailure.error ?? `No error message`}`
282 : `Native iOS e2e suite failed`),
283 )
284}
285
286console.log(
287 JSON.stringify(
288 {
289 runId: runtimeRunId,
290 status: result.status,
291 passed: result.payload.passed ?? 0,
292 failed: result.payload.failed ?? 0,
293 skipped: result.payload.skipped ?? 0,
294 total: result.payload.total ?? 0,
295 },
296 null,
297 2,
298 ),
299)