runcloud 0.2.211 → 0.2.213

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.
@@ -952,9 +952,92 @@ async function createSimulatorSession(platform, opts) {
952
952
  autoDelete: opts.rm,
953
953
  codec: requestedCodec(opts.codec),
954
954
  ...(opts.devHost ? { devHost: opts.devHost } : {}),
955
+ ...(opts.restoreState ? { restoreState: opts.restoreState } : {}),
955
956
  ...(platform === 'ios' ? runCloudIosOptions(opts) : {}),
956
957
  });
957
958
  }
959
+ const STATE_WAIT_DEADLINE_MS = 10 * 60_000;
960
+ const STATE_LONG_POLL_MS = 60_000;
961
+ const STATE_POLL_INTERVAL_MS = 500;
962
+ function printCreatedSession(session, opts) {
963
+ const restore = session.stateRestore;
964
+ if (opts.json || !restore || typeof restore !== 'object') {
965
+ print(session, opts);
966
+ return;
967
+ }
968
+ print({ ...session, stateRestore: `${restore.status}${restore.code ? ` (${restore.code})` : ''}` }, opts);
969
+ if (restore.status !== 'restored') {
970
+ console.error(`warning: saved state ${restore.stateId ?? ''} was not restored; the session started from a clean device`);
971
+ }
972
+ }
973
+ function sleep(ms) {
974
+ return new Promise((resolveSleep) => setTimeout(resolveSleep, ms));
975
+ }
976
+ async function getSimulatorState(stateId, wait) {
977
+ const id = stateId.trim();
978
+ if (!id)
979
+ throw new InvalidArgumentError('state id is required');
980
+ const path = `/run-cloud/states/${encodeURIComponent(id)}`;
981
+ if (!wait)
982
+ return await client().get(path);
983
+ const deadline = Date.now() + STATE_WAIT_DEADLINE_MS;
984
+ for (;;) {
985
+ const state = await client().get(`${path}?waitMs=${STATE_LONG_POLL_MS}`);
986
+ if (state.status !== 'pending')
987
+ return state;
988
+ if (Date.now() >= deadline) {
989
+ throw new ApiError(0, `Saved state ${id} is still pending after ${STATE_WAIT_DEADLINE_MS / 60_000} minutes; check it later with runcloud states get ${id}`, path, {
990
+ code: 'state_wait_timeout',
991
+ retryable: true,
992
+ details: { stateId: id },
993
+ });
994
+ }
995
+ await sleep(STATE_POLL_INTERVAL_MS);
996
+ }
997
+ }
998
+ async function releaseSimulatorSessionSavingState(platform, sessionId, wait) {
999
+ const path = `/run-cloud/${platform}/${encodeURIComponent(sessionId)}?saveState=1`;
1000
+ const session = await client().delete(path);
1001
+ const saved = session.savedState;
1002
+ const failure = (message, code, stateId) => new ApiError(0, message, path, {
1003
+ code,
1004
+ retryable: false,
1005
+ sessionId,
1006
+ platform,
1007
+ action: 'delete',
1008
+ details: { ...(stateId ? { stateId } : {}), session },
1009
+ });
1010
+ if (!saved || typeof saved !== 'object') {
1011
+ throw failure('The session was released, but the API did not start a state save', 'state_save_unacknowledged');
1012
+ }
1013
+ if (saved.status !== 'pending' || typeof saved.stateId !== 'string' || !saved.stateId) {
1014
+ const code = typeof saved.code === 'string' ? saved.code : 'state_save_failed';
1015
+ throw failure(`The session was released, but its state was not saved (${code})`, code);
1016
+ }
1017
+ const stateId = saved.stateId;
1018
+ if (!wait)
1019
+ return { stateId, ...session };
1020
+ let state;
1021
+ try {
1022
+ state = await getSimulatorState(stateId, true);
1023
+ }
1024
+ catch (error) {
1025
+ const code = error instanceof ApiError && error.code ? error.code : 'state_wait_failed';
1026
+ throw new ApiError(0, `The session was released and state ${stateId} is saving, but waiting for it failed (${code}); check it with runcloud states get ${stateId}`, path, {
1027
+ code,
1028
+ retryable: true,
1029
+ sessionId,
1030
+ platform,
1031
+ action: 'delete',
1032
+ details: { stateId, session },
1033
+ });
1034
+ }
1035
+ if (state.status !== 'ready') {
1036
+ const code = typeof state.code === 'string' ? state.code : 'state_save_failed';
1037
+ throw failure(`The session was released, but saving state ${stateId} failed (${code})`, code, stateId);
1038
+ }
1039
+ return { stateId, ...session, state };
1040
+ }
958
1041
  async function openSimulatorSessionUrl(platform, sessionId, url) {
959
1042
  const path = `/run-cloud/${platform}/${encodeURIComponent(sessionId)}/open-url`;
960
1043
  try {
@@ -1164,8 +1247,9 @@ function registerSimulatorCommands(program, platform) {
1164
1247
  }
1165
1248
  }, opts));
1166
1249
  createCommand
1250
+ .option('--restore-state <state-id>', 'start from a saved state (see delete --save-state); falls back to a clean device')
1167
1251
  .action((opts) => action(async () => {
1168
- print(await createSimulatorSession(platform, opts), opts);
1252
+ printCreatedSession(await createSimulatorSession(platform, opts), opts);
1169
1253
  }, opts));
1170
1254
  simulator
1171
1255
  .command('list')
@@ -1188,9 +1272,15 @@ function registerSimulatorCommands(program, platform) {
1188
1272
  .command('delete')
1189
1273
  .description(`Release ${article} ${label} session`)
1190
1274
  .argument('<id>')
1275
+ .option('--save-state', 'save the apps and their data as the session ends, and print the stateId', false)
1276
+ .option('--wait', 'with --save-state: wait until the saved state is ready or failed', false)
1191
1277
  .option('--json', 'output JSON', false)
1192
1278
  .action((id, opts) => action(async () => {
1193
- print(await client().delete(`/run-cloud/${platform}/${encodeURIComponent(id)}`), opts);
1279
+ if (opts.wait && !opts.saveState)
1280
+ throw new InvalidArgumentError('--wait needs --save-state');
1281
+ print(opts.saveState
1282
+ ? await releaseSimulatorSessionSavingState(platform, id, opts.wait === true)
1283
+ : await client().delete(`/run-cloud/${platform}/${encodeURIComponent(id)}`), opts);
1194
1284
  }, opts));
1195
1285
  simulator
1196
1286
  .command('open-url')
@@ -1759,6 +1849,31 @@ export function registerRunCloud(program) {
1759
1849
  .action((id, opts) => action(async () => {
1760
1850
  print(await client().delete(`/run-cloud/assets/${encodeURIComponent(id)}`), opts);
1761
1851
  }));
1852
+ const states = program
1853
+ .command('states')
1854
+ .alias('state')
1855
+ .description('Inspect and delete saved simulator and emulator states');
1856
+ states
1857
+ .command('get')
1858
+ .description('Show a saved state')
1859
+ .argument('<state-id>')
1860
+ .option('--wait', 'wait until the state is ready or failed', false)
1861
+ .option('--json', 'output JSON', false)
1862
+ .action((stateId, opts) => action(async () => {
1863
+ print(await getSimulatorState(stateId, opts.wait === true), opts);
1864
+ }, opts));
1865
+ states
1866
+ .command('delete')
1867
+ .description('Delete a saved state and every stored copy')
1868
+ .argument('<state-id>')
1869
+ .option('--json', 'output JSON', false)
1870
+ .action((stateId, opts) => action(async () => {
1871
+ const id = stateId.trim();
1872
+ if (!id)
1873
+ throw new InvalidArgumentError('state id is required');
1874
+ await client().delete(`/run-cloud/states/${encodeURIComponent(id)}`);
1875
+ print({ ok: true, stateId: id, deleted: true }, opts);
1876
+ }, opts));
1762
1877
  const capability = program
1763
1878
  .command('capability')
1764
1879
  .alias('capabilities')
@@ -1,5 +1,5 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
- import { cp, copyFile, lstat, mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises';
2
+ import { cp, copyFile, lstat, mkdir, mkdtemp, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
3
3
  import { existsSync } from 'node:fs';
4
4
  import { tmpdir } from 'node:os';
5
5
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
@@ -150,11 +150,40 @@ function remoteAdditionalPath(value) {
150
150
  }
151
151
  return { home, path };
152
152
  }
153
+ async function checkSourceLink(root, realRoot, link, relativePath) {
154
+ const target = await realpath(link).catch(() => null);
155
+ if (!target)
156
+ throw new Error(`Xcode source symbolic link cannot be resolved: ${relativePath}`);
157
+ if (target !== realRoot && !target.startsWith(`${realRoot}${sep}`)) {
158
+ throw new Error(`Xcode source symbolic link points outside the source directory: ${relativePath}`);
159
+ }
160
+ if (!(await stat(target)).isDirectory())
161
+ return;
162
+ for (let parent = dirname(link);; parent = dirname(parent)) {
163
+ const realParent = await realpath(parent);
164
+ if (realParent === target || realParent.startsWith(`${target}${sep}`)) {
165
+ throw new Error(`Xcode source symbolic link loops back to a directory that contains it: ${relativePath}`);
166
+ }
167
+ if (parent === root)
168
+ return;
169
+ }
170
+ }
171
+ async function realSourcePaths(realRoot, source, isDirectory) {
172
+ const target = await realpath(source).catch(() => null);
173
+ if (!target?.startsWith(`${realRoot}${sep}`))
174
+ return [];
175
+ const parts = relative(realRoot, target).split(sep);
176
+ return parts.map((_, index) => {
177
+ const path = parts.slice(0, index + 1).join('/');
178
+ return index < parts.length - 1 || isDirectory ? `${path}/` : path;
179
+ });
180
+ }
153
181
  export async function packSource(sourcePath, flags) {
154
182
  const root = resolve(sourcePath);
155
183
  const rootStat = await stat(root).catch(() => null);
156
184
  if (!rootStat?.isDirectory())
157
185
  throw new Error(`Xcode source path is not a directory: ${sourcePath}`);
186
+ const realRoot = await realpath(root);
158
187
  const temporary = await mkdtemp(join(tmpdir(), 'runcloud-xcode-'));
159
188
  const workspace = join(temporary, 'workspace');
160
189
  const archivePath = join(temporary, 'source.tar.gz');
@@ -165,21 +194,34 @@ export async function packSource(sourcePath, flags) {
165
194
  gitignore.add(gitignoreText);
166
195
  const ignored = compilePatterns(flags.ignore, '--ignore');
167
196
  const included = compilePatterns(flags.include, '--include');
197
+ const excluded = (candidate) => defaultExcluded(candidate) || gitignore.ignores(candidate) || matches(ignored, candidate);
198
+ const linkedDirectories = [];
168
199
  await cp(root, workspace, {
169
200
  recursive: true,
170
- dereference: false,
201
+ dereference: true,
171
202
  preserveTimestamps: true,
172
203
  filter: async (source) => {
173
204
  if (source === root)
174
205
  return true;
175
206
  const info = await lstat(source);
176
207
  const relativePath = relative(root, source).split(sep).join('/');
177
- const candidate = info.isDirectory() ? `${relativePath}/` : relativePath;
208
+ const isDirectory = info.isSymbolicLink()
209
+ ? Boolean((await stat(source).catch(() => null))?.isDirectory())
210
+ : info.isDirectory();
211
+ const candidate = isDirectory ? `${relativePath}/` : relativePath;
178
212
  const forced = relativePath.endsWith('.xcconfig') || matches(included, candidate);
179
- if (!forced && (defaultExcluded(candidate) || gitignore.ignores(candidate) || matches(ignored, candidate)))
180
- return false;
181
- if (info.isSymbolicLink())
182
- throw new Error(`Xcode source archives do not follow symbolic links: ${relativePath}`);
213
+ const linked = info.isSymbolicLink() || linkedDirectories.some((directory) => source.startsWith(`${directory}${sep}`));
214
+ if (!forced) {
215
+ if (excluded(candidate))
216
+ return false;
217
+ if (linked && (await realSourcePaths(realRoot, source, isDirectory)).some(excluded))
218
+ return false;
219
+ }
220
+ if (info.isSymbolicLink()) {
221
+ await checkSourceLink(root, realRoot, source, relativePath);
222
+ if (isDirectory)
223
+ linkedDirectories.push(source);
224
+ }
183
225
  return true;
184
226
  },
185
227
  });
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = '0.2.211';
1
+ export const CLI_VERSION = '0.2.213';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "runcloud",
3
- "version": "0.2.211",
3
+ "version": "0.2.213",
4
4
  "description": "Create and control run.cloud remote mobile simulators and cloud sandboxes",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
Binary file
@@ -40,7 +40,7 @@ runcloud ios get "$SESSION_ID" --json
40
40
  ```
41
41
 
42
42
  Replace `ios` with `android` for an Android artifact. The shared lifecycle is
43
- `create`, `list`, `get`, `open-url`, `location set|clear`, `settings`, `logs`, and `delete`. Use `--json` whenever
43
+ `create`, `list`, `get`, `open-url`, `location set|clear`, `settings`, `logs`, and `delete` (with `--save-state`). Use `--json` whenever
44
44
  another program consumes output, and inspect `runcloud ios|android --help` for
45
45
  create and log options.
46
46
 
@@ -48,6 +48,30 @@ iOS needs an Apple Silicon simulator-compatible `.app`, `.zip`, `.tar.gz`, or
48
48
  `.ipa`; a device-signed App Store IPA is not a substitute. Android needs an
49
49
  emulator-compatible APK.
50
50
 
51
+ ## Save and Restore State (Stay Signed In)
52
+
53
+ Sign in once, save the device state as you release it, and start later sessions
54
+ from that state:
55
+
56
+ ```bash
57
+ STATE_ID=$(runcloud ios delete "$SESSION_ID" --save-state --wait --json | jq -r '.stateId')
58
+ runcloud ios create --restore-state "$STATE_ID" --json | jq '.stateRestore'
59
+ runcloud states get "$STATE_ID" --json
60
+ runcloud states delete "$STATE_ID"
61
+ ```
62
+
63
+ - Works on `ios` and `android`; a state restores only onto its own platform.
64
+ - iOS saves apps, app data, app groups and the keychain; Android saves apps and
65
+ package data. Permission grants, location and appearance are not saved.
66
+ - A state is kept 30 days (a restore does not extend it) and is capped at
67
+ 1 GiB compressed.
68
+ - Only the principal (user or API key) that saved a state can read, restore, or
69
+ delete it. Save with the same key that later restores.
70
+ - A create always returns a session. Check `stateRestore.status`: anything but
71
+ `restored` means a clean device; read `code` instead of retrying blindly.
72
+ - SDK: `delete(id, { saveState: true })`, `create({ restoreState })`,
73
+ `cloud.states.get(stateId, { waitMs })`, and `cloud.states.delete(stateId)`.
74
+
51
75
  ## Control a Session
52
76
 
53
77
  Both platform groups expose acknowledged controls:
Binary file