awesome-emulator-cli 0.4.0 → 0.5.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.
package/README.md CHANGED
@@ -98,6 +98,31 @@ npx awesome-emulator run --shell -- npm test
98
98
 
99
99
  Use `--shell` only with trusted command and argument values. Shell metacharacters are interpreted in this mode. Node.js API callers can opt in with `runWithEmulator(command, args, { shell: true })` under the same restriction.
100
100
 
101
+ ## Reuse an emulator across commands
102
+
103
+ Use a named session when setup and tests run in separate commands or CI steps. The session metadata is stored under `~/.aws/emulator/sessions/` with restrictive file permissions on Unix systems; it contains container and connection details, not credential values. `exec` supplies the same emulator environment as `run` and can be called repeatedly:
104
+
105
+ ```sh
106
+ npx awesome-emulator up --session ci-tests --port 0
107
+ npx awesome-emulator exec --session ci-tests -- npm run seed
108
+ npx awesome-emulator exec --session ci-tests -- npm test
109
+ npx awesome-emulator down --session ci-tests
110
+ ```
111
+
112
+ In CI, put the final `down` command in an always-run cleanup step so the container is removed even when a test step fails. Each CI job should use its own session name. `up` prints the connection settings as JSON; it does not print the container ID or credential values.
113
+
114
+ Persistent sessions use `ps` on Unix or Windows PowerShell on Windows to distinguish an active startup from an abandoned session record.
115
+
116
+ Run a one-time seed or setup command after the emulator becomes healthy with `--init`. The initializer receives the same emulator environment as `exec`; a non-zero exit makes `up` fail and stops the session. Initializer stdout is sent to stderr so the JSON printed by `up` remains machine-readable:
117
+
118
+ ```sh
119
+ npx awesome-emulator up --session ci-tests --init -- node scripts/seed-emulator.js
120
+ npx awesome-emulator exec --session ci-tests -- npm test
121
+ npx awesome-emulator down --session ci-tests
122
+ ```
123
+
124
+ Initializer arguments are passed directly without a shell by default. Use `--shell` before `--` only when you need shell behavior and trust all command values.
125
+
101
126
  ## Use from Node.js
102
127
 
103
128
  Use the API when your test harness needs to control the emulator lifecycle directly:
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { prepareEmulatorImage, runWithEmulator, startEmulator, } from "./index.js";
2
+ import { prepareEmulatorImage, downEmulatorSession, execEmulatorSession, runWithEmulator, startEmulator, upEmulatorSession, } from "./index.js";
3
3
  import { DEFAULT_VERSION } from "./emulator-options.js";
4
4
  import { FORWARDED_SIGNALS, getSignalExitCode } from "./signals.js";
5
5
  import { DEFAULT_AWS_REGION, SUPPORTED_EMULATOR_SDKS } from "./emulator-environment.js";
@@ -8,16 +8,21 @@ function usage() {
8
8
  awesome-emulator prepare [--version <version>]
9
9
  awesome-emulator start [options]
10
10
  awesome-emulator run [options] [--region <region>] [--sdk <family>]... [--shell] -- <command> [args...]
11
+ awesome-emulator up --session <name> [options] [--init [child options] -- <command> [args...]]
12
+ awesome-emulator exec --session <name> [--region <region>] [--sdk <family>]... [--shell] -- <command> [args...]
13
+ awesome-emulator down --session <name>
11
14
 
12
15
  Options:
13
16
  -v, --version <version> AWS Emulator version (default: ${DEFAULT_VERSION})
14
- -p, --port <port> (start/run) Host port; 0 chooses an available port (default: 9297)
15
- -t, --telemetry <on|off> (start/run) Telemetry setting (default: on)
16
- --memory <limit> (start/run) Container memory limit (default: 2g)
17
- --region <region> (run only) Default region for the child command (default: ${DEFAULT_AWS_REGION})
18
- --sdk <family> (run only) Add SDK-specific TLS settings; repeatable
17
+ -p, --port <port> (start/run/up) Host port; 0 chooses an available port (default: 9297)
18
+ -t, --telemetry <on|off> (start/run/up) Telemetry setting (default: on)
19
+ --memory <limit> (start/run/up) Container memory limit (default: 2g)
20
+ --region <region> (run/exec/up --init) Default region for the child command (default: ${DEFAULT_AWS_REGION})
21
+ --session <name> (up/exec/down) Persistent emulator session name
22
+ --sdk <family> (run/exec/up --init) Add SDK-specific TLS settings; repeatable
19
23
  (${SUPPORTED_EMULATOR_SDKS.join(", ")})
20
- --shell (run only) Enable .cmd/.bat and built-ins; trusted values only
24
+ --shell (run/exec/up --init) Enable .cmd/.bat and built-ins; trusted values only
25
+ --init (up only) Run a command after the emulator becomes healthy
21
26
  -h, --help Show this help`);
22
27
  }
23
28
  function parse(argv) {
@@ -27,6 +32,7 @@ function parse(argv) {
27
32
  const options = {};
28
33
  const commandArgs = [];
29
34
  let separator = false;
35
+ let initRequested = false;
30
36
  for (let index = 1; index < argv.length; index += 1) {
31
37
  const token = argv[index];
32
38
  if (separator) {
@@ -34,20 +40,31 @@ function parse(argv) {
34
40
  continue;
35
41
  }
36
42
  if (token === "--") {
43
+ if (command === "up" && !initRequested)
44
+ throw new Error("The up command accepts child arguments only after --init --.");
37
45
  separator = true;
38
46
  continue;
39
47
  }
40
48
  if (token === "-h" || token === "--help")
41
49
  return { help: true };
50
+ if (token === "--init") {
51
+ if (command !== "up")
52
+ throw new Error("--init can only be used with the up command.");
53
+ if (initRequested)
54
+ throw new Error("--init can only be specified once.");
55
+ initRequested = true;
56
+ options.init = true;
57
+ continue;
58
+ }
42
59
  if (token === "--shell") {
43
- if (command !== "run")
44
- throw new Error("--shell can only be used with the run command.");
60
+ if (command !== "run" && command !== "exec" && command !== "up")
61
+ throw new Error("--shell can only be used with the run or exec command, or with up --init.");
45
62
  options.shell = true;
46
63
  continue;
47
64
  }
48
65
  if (token === "--sdk") {
49
- if (command !== "run")
50
- throw new Error("--sdk can only be used with the run command.");
66
+ if (command !== "run" && command !== "exec" && command !== "up")
67
+ throw new Error("--sdk can only be used with the run or exec command, or with up --init.");
51
68
  const value = argv[index + 1];
52
69
  if (!value || value.startsWith("--"))
53
70
  throw new Error("Missing value for --sdk");
@@ -65,22 +82,40 @@ function parse(argv) {
65
82
  "-t": "telemetry", "--telemetry": "telemetry",
66
83
  "--memory": "memory",
67
84
  "--region": "region",
85
+ "--session": "session",
68
86
  };
69
87
  const key = optionNames[token];
70
88
  if (!key)
71
89
  throw new Error(`Unknown option: ${token}`);
72
- if (key === "region" && command !== "run") {
73
- throw new Error("--region can only be used with the run command.");
90
+ if (key === "region" && command !== "run" && command !== "exec" && command !== "up") {
91
+ throw new Error("--region can only be used with the run or exec command, or with up --init.");
92
+ }
93
+ if (key === "session" && command !== "up" && command !== "exec" && command !== "down") {
94
+ throw new Error("--session can only be used with the up, exec, or down command.");
74
95
  }
75
96
  if (command === "prepare" && key !== "version") {
76
97
  throw new Error(`${token} can only be used with the start or run command.`);
77
98
  }
99
+ if ((command === "exec" || command === "down") && key !== "region" && key !== "session") {
100
+ throw new Error(`${token} cannot be used with the ${command} command.`);
101
+ }
78
102
  const value = argv[index + 1];
79
103
  if (!value || value.startsWith("--"))
80
104
  throw new Error(`Missing value for ${token}`);
81
105
  options[key] = value;
82
106
  index += 1;
83
107
  }
108
+ if ((command === "up" || command === "exec" || command === "down") && !options.session) {
109
+ throw new Error(`--session is required with the ${command} command.`);
110
+ }
111
+ if (command === "up") {
112
+ if (initRequested && (!separator || commandArgs.length === 0)) {
113
+ throw new Error("Usage: awesome-emulator up --session <name> [options] --init -- <command> [args...]");
114
+ }
115
+ if (!initRequested && (separator || options.region || options.sdks || options.shell)) {
116
+ throw new Error("Child command options and arguments for up require --init.");
117
+ }
118
+ }
84
119
  return { help: false, command, options, commandArgs };
85
120
  }
86
121
  function waitForAbort(signal) {
@@ -110,6 +145,43 @@ async function main(signal) {
110
145
  throw new Error("Usage: awesome-emulator run [options] -- <command> [args...]");
111
146
  return runWithEmulator(program, args, { ...parsed.options, signal });
112
147
  }
148
+ if (parsed.command === "up") {
149
+ const [initCommand, ...initArgs] = parsed.commandArgs;
150
+ const session = await upEmulatorSession(parsed.options.session, {
151
+ version: parsed.options.version,
152
+ port: parsed.options.port,
153
+ telemetry: parsed.options.telemetry,
154
+ memory: parsed.options.memory,
155
+ signal,
156
+ init: parsed.options.init ? {
157
+ command: initCommand,
158
+ args: initArgs,
159
+ region: parsed.options.region,
160
+ sdks: parsed.options.sdks,
161
+ shell: parsed.options.shell,
162
+ } : undefined,
163
+ });
164
+ console.log(JSON.stringify(session, null, 2));
165
+ return 0;
166
+ }
167
+ if (parsed.command === "exec") {
168
+ const [program, ...args] = parsed.commandArgs;
169
+ if (!program)
170
+ throw new Error("Usage: awesome-emulator exec --session <name> -- <command> [args...]");
171
+ return execEmulatorSession(parsed.options.session, program, args, {
172
+ region: parsed.options.region,
173
+ sdks: parsed.options.sdks,
174
+ shell: parsed.options.shell,
175
+ signal,
176
+ });
177
+ }
178
+ if (parsed.command === "down") {
179
+ if (parsed.commandArgs.length > 0)
180
+ throw new Error("The down command does not accept child command arguments.");
181
+ await downEmulatorSession(parsed.options.session);
182
+ console.log(`Emulator session "${parsed.options.session}" stopped.`);
183
+ return 0;
184
+ }
113
185
  if (parsed.command === "prepare") {
114
186
  const image = await prepareEmulatorImage({ version: parsed.options.version, signal });
115
187
  console.log(`AWS Emulator image is ready: ${image}`);
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type EmulatorEnvironment } from "./emulator-environment.js";
1
+ import { type EmulatorEnvironment, type EmulatorSdk } from "./emulator-environment.js";
2
2
  import { type PrepareEmulatorOptions, type RunWithEmulatorOptions, type StartEmulatorOptions } from "./emulator-options.js";
3
3
  export type { PrepareEmulatorOptions, RunWithEmulatorOptions, StartEmulatorOptions } from "./emulator-options.js";
4
4
  export type { EmulatorEnvironment, EmulatorSdk } from "./emulator-environment.js";
@@ -14,15 +14,26 @@ export type EmulatorSession = {
14
14
  containerId: string;
15
15
  stop: () => Promise<void>;
16
16
  };
17
+ export type PersistentEmulatorSession = Omit<EmulatorSession, "containerId" | "stop"> & {
18
+ name: string;
19
+ };
20
+ export type EmulatorSessionExecOptions = Pick<RunWithEmulatorOptions, "shell" | "sdks" | "region" | "signal">;
21
+ export type EmulatorSessionInitCommand = {
22
+ command: string;
23
+ args?: string[];
24
+ shell?: boolean;
25
+ sdks?: EmulatorSdk[];
26
+ region?: string;
27
+ };
28
+ export type UpEmulatorSessionOptions = StartEmulatorOptions & {
29
+ init?: EmulatorSessionInitCommand;
30
+ };
17
31
  /** Build or reuse the selected AWS Emulator Docker image without starting a container. */
18
32
  export declare function prepareEmulatorImage(options?: PrepareEmulatorOptions): Promise<string>;
19
- /**
20
- * Start AWS Emulator in a local Docker container.
21
- *
22
- * The returned object includes SDK environment variables and an idempotent
23
- * stop() function. Port 0 asks the wrapper to choose an available local port.
24
- */
25
33
  export declare function startEmulator(options?: StartEmulatorOptions): Promise<EmulatorSession>;
34
+ export declare function upEmulatorSession(name: string, options?: UpEmulatorSessionOptions): Promise<PersistentEmulatorSession>;
35
+ export declare function execEmulatorSession(name: string, command: string, args?: string[], options?: EmulatorSessionExecOptions): Promise<number>;
36
+ export declare function downEmulatorSession(name: string): Promise<void>;
26
37
  /**
27
38
  * Run a child process with AWS Emulator settings and stop the emulator afterward.
28
39
  */
package/dist/index.js CHANGED
@@ -8,8 +8,14 @@ import { createRetryableStop, startContainer, stopContainer, withEmulator } from
8
8
  import { docker, throwIfAborted } from "./docker.js";
9
9
  import { createChildEnvironment, createEmulatorConnectionSettings, normalizeEmulatorSdks, resolveAwsRegion, } from "./emulator-environment.js";
10
10
  import { ensureEmulatorImage, getArchitecture } from "./emulator-image.js";
11
+ import { isSessionOwnerRunning, readSession, removeSession, reserveSession, validateSessionName, writeRunningSession } from "./session-store.js";
11
12
  import { resolveEmulatorOptions, resolveEmulatorVersion, } from "./emulator-options.js";
12
13
  import { runCommand } from "./process.js";
14
+ const MANAGED_CONTAINER_LABEL = "io.github.c19yamamoto.awesome-emulator-cli.managed";
15
+ const SESSION_CONTAINER_LABEL = "io.github.c19yamamoto.awesome-emulator-cli.session";
16
+ function emulatorStateDirectory() {
17
+ return path.join(os.homedir(), ".aws", "emulator");
18
+ }
13
19
  /** Build or reuse the selected AWS Emulator Docker image without starting a container. */
14
20
  export async function prepareEmulatorImage(options = {}) {
15
21
  throwIfAborted(options.signal);
@@ -49,16 +55,18 @@ function requestHealth(port, ca, signal) {
49
55
  });
50
56
  }
51
57
  const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
52
- function createContainerRunArguments({ architecture, containerName, image, memory, port, stateDirectory, telemetry, }) {
58
+ function createContainerRunArguments({ architecture, containerName, image, labels, memory, port, stateDirectory, telemetry, }) {
53
59
  const hostUser = process.platform === "linux"
54
60
  && typeof process.getuid === "function"
55
61
  && typeof process.getgid === "function"
56
62
  ? ["--user", `${process.getuid()}:${process.getgid()}`]
57
63
  : [];
64
+ const dockerLabels = Object.entries(labels).flatMap(([key, value]) => ["--label", `${key}=${value}`]);
58
65
  return [
59
66
  "run", "--detach",
60
67
  "--platform", `linux/${architecture.docker}`,
61
68
  ...hostUser,
69
+ ...dockerLabels,
62
70
  "--memory", memory,
63
71
  "--memory-swap", memory,
64
72
  "--publish", `127.0.0.1:${port}:${port}`,
@@ -108,21 +116,21 @@ async function waitUntilHealthy(containerId, port, stateDirectory, timeoutMs, si
108
116
  * The returned object includes SDK environment variables and an idempotent
109
117
  * stop() function. Port 0 asks the wrapper to choose an available local port.
110
118
  */
111
- export async function startEmulator(options = {}) {
119
+ async function startEmulatorWithIdentity(options, containerName, labels) {
112
120
  throwIfAborted(options.signal);
113
121
  const { version, requestedPort, telemetry, memory, startupTimeoutMs } = resolveEmulatorOptions(options);
114
122
  const port = requestedPort === 0 ? await getAvailablePort() : requestedPort;
115
123
  throwIfAborted(options.signal);
116
124
  const architecture = getArchitecture();
117
- const stateDirectory = path.join(os.homedir(), ".aws", "emulator");
125
+ const stateDirectory = emulatorStateDirectory();
118
126
  await mkdir(stateDirectory, { recursive: true, mode: 0o700 });
119
127
  const image = await ensureEmulatorImage(version, architecture, options.signal);
120
128
  throwIfAborted(options.signal);
121
- const containerName = `awesome-emulator-cli-${process.pid}-${randomBytes(4).toString("hex")}`;
122
129
  const runArguments = createContainerRunArguments({
123
130
  architecture,
124
131
  containerName,
125
132
  image,
133
+ labels,
126
134
  memory,
127
135
  port,
128
136
  stateDirectory,
@@ -151,6 +159,135 @@ export async function startEmulator(options = {}) {
151
159
  stop,
152
160
  };
153
161
  }
162
+ export async function startEmulator(options = {}) {
163
+ const containerName = `awesome-emulator-cli-${process.pid}-${randomBytes(4).toString("hex")}`;
164
+ return startEmulatorWithIdentity(options, containerName, { [MANAGED_CONTAINER_LABEL]: "true" });
165
+ }
166
+ export async function upEmulatorSession(name, options = {}) {
167
+ validateSessionName(name);
168
+ const { init, ...emulatorOptions } = options;
169
+ const initOptions = init
170
+ ? { sdks: normalizeEmulatorSdks(init.sdks), region: resolveAwsRegion(init.region) }
171
+ : undefined;
172
+ if (init && !init.command)
173
+ throw new Error("An initialization command is required.");
174
+ const stateDirectory = emulatorStateDirectory();
175
+ const containerName = `awesome-emulator-cli-session-${randomBytes(4).toString("hex")}-${name}`;
176
+ await reserveSession(stateDirectory, name, containerName);
177
+ let emulator;
178
+ try {
179
+ emulator = await startEmulatorWithIdentity(emulatorOptions, containerName, {
180
+ [MANAGED_CONTAINER_LABEL]: "true",
181
+ [SESSION_CONTAINER_LABEL]: name,
182
+ });
183
+ if (init && initOptions) {
184
+ const childEnvironment = createChildEnvironment(process.env, emulator.environment, initOptions);
185
+ const exitCode = await runCommand(init.command, init.args ?? [], childEnvironment, options.signal, init.shell ?? false, "stderr");
186
+ if (exitCode !== 0) {
187
+ throwIfAborted(options.signal);
188
+ throw new Error(`Emulator session "${name}" initialization command failed with exit code ${exitCode}.`);
189
+ }
190
+ }
191
+ const record = {
192
+ schemaVersion: 1,
193
+ name,
194
+ state: "running",
195
+ containerName,
196
+ containerId: emulator.containerId,
197
+ version: emulator.version,
198
+ port: emulator.port,
199
+ };
200
+ await writeRunningSession(stateDirectory, record);
201
+ throwIfAborted(options.signal);
202
+ const { containerId: _containerId, stop: _stop, ...publicSession } = emulator;
203
+ return { name, ...publicSession };
204
+ }
205
+ catch (error) {
206
+ const cleanupErrors = [];
207
+ if (emulator) {
208
+ try {
209
+ await emulator.stop();
210
+ }
211
+ catch (cleanupError) {
212
+ cleanupErrors.push(cleanupError);
213
+ }
214
+ }
215
+ if (!(error instanceof AggregateError) && cleanupErrors.length === 0) {
216
+ try {
217
+ await removeSession(stateDirectory, name);
218
+ }
219
+ catch (cleanupError) {
220
+ cleanupErrors.push(cleanupError);
221
+ }
222
+ }
223
+ if (cleanupErrors.length > 0) {
224
+ throw new AggregateError([error, ...cleanupErrors], `Failed to start emulator session "${name}" and clean up its state.`);
225
+ }
226
+ throw error;
227
+ }
228
+ }
229
+ async function inspectSessionContainer(name, containerName) {
230
+ let details;
231
+ try {
232
+ details = await docker([
233
+ "inspect",
234
+ "--format",
235
+ `{{.Id}}|{{.State.Running}}|{{index .Config.Labels "${MANAGED_CONTAINER_LABEL}"}}|{{index .Config.Labels "${SESSION_CONTAINER_LABEL}"}}`,
236
+ containerName,
237
+ ], { capture: true });
238
+ }
239
+ catch (error) {
240
+ if (error instanceof Error && /no such (?:container|object)/i.test(error.message))
241
+ return undefined;
242
+ throw error;
243
+ }
244
+ const [containerId, running, managed, sessionName] = details.split("|");
245
+ if (managed !== "true" || sessionName !== name) {
246
+ throw new Error(`Docker container "${containerName}" is not owned by emulator session "${name}".`);
247
+ }
248
+ if (!containerId || !/^[a-f0-9]{12,64}$/i.test(containerId)) {
249
+ throw new Error(`Docker returned invalid session details for "${name}".`);
250
+ }
251
+ return { containerId, running: running === "true" };
252
+ }
253
+ export async function execEmulatorSession(name, command, args = [], options = {}) {
254
+ if (!command)
255
+ throw new Error("A command is required.");
256
+ validateSessionName(name);
257
+ const { signal, shell = false, sdks: requestedSdks = [], region } = options;
258
+ const childRegion = resolveAwsRegion(region);
259
+ const sdks = normalizeEmulatorSdks(requestedSdks);
260
+ const stateDirectory = emulatorStateDirectory();
261
+ const session = await readSession(stateDirectory, name);
262
+ if (session.state !== "running") {
263
+ throw new Error(`Emulator session "${name}" is still starting. Wait for "awesome-emulator up" to finish before running commands.`);
264
+ }
265
+ const container = await inspectSessionContainer(name, session.containerName);
266
+ if (!container) {
267
+ throw new Error(`Emulator session "${name}" is stale. Run "awesome-emulator down --session ${name}" to remove it.`);
268
+ }
269
+ if (container.containerId !== session.containerId) {
270
+ throw new Error(`Emulator session "${name}" no longer matches its Docker container. Run "awesome-emulator down --session ${name}" to remove it.`);
271
+ }
272
+ if (!container.running) {
273
+ throw new Error(`Emulator session "${name}" is not running. Run "awesome-emulator down --session ${name}" to remove it.`);
274
+ }
275
+ const emulator = createEmulatorConnectionSettings(session.port, stateDirectory);
276
+ const childEnvironment = createChildEnvironment(process.env, emulator.environment, { sdks, region: childRegion });
277
+ return runCommand(command, args, childEnvironment, signal, shell);
278
+ }
279
+ export async function downEmulatorSession(name) {
280
+ validateSessionName(name);
281
+ const stateDirectory = emulatorStateDirectory();
282
+ const session = await readSession(stateDirectory, name);
283
+ if (session.state === "starting" && isSessionOwnerRunning(session)) {
284
+ throw new Error(`Emulator session "${name}" is still starting. Retry after "awesome-emulator up" finishes.`);
285
+ }
286
+ const container = await inspectSessionContainer(name, session.containerName);
287
+ if (container)
288
+ await stopContainer(container.containerId);
289
+ await removeSession(stateDirectory, name);
290
+ }
154
291
  /**
155
292
  * Run a child process with AWS Emulator settings and stop the emulator afterward.
156
293
  */
package/dist/process.d.ts CHANGED
@@ -1 +1 @@
1
- export declare function runCommand(command: string, args: string[], env: NodeJS.ProcessEnv, signal?: AbortSignal, shell?: boolean): Promise<number>;
1
+ export declare function runCommand(command: string, args: string[], env: NodeJS.ProcessEnv, signal?: AbortSignal, shell?: boolean, stdout?: "inherit" | "stderr"): Promise<number>;
package/dist/process.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { spawn } from "node:child_process";
2
2
  import { FORWARDED_SIGNALS, getSignalExitCode, isForwardedSignal } from "./signals.js";
3
- export function runCommand(command, args, env, signal, shell = false) {
3
+ export function runCommand(command, args, env, signal, shell = false, stdout = "inherit") {
4
4
  return new Promise((resolve, reject) => {
5
5
  const child = spawn(command, args, {
6
6
  env,
7
- stdio: "inherit",
7
+ stdio: stdout === "stderr" ? ["inherit", 2, "inherit"] : "inherit",
8
8
  shell,
9
9
  windowsHide: false,
10
10
  });
@@ -0,0 +1,24 @@
1
+ export type StartingSessionRecord = {
2
+ schemaVersion: 1;
3
+ name: string;
4
+ state: "starting";
5
+ containerName: string;
6
+ ownerPid: number;
7
+ ownerStartMarker: string;
8
+ };
9
+ export type RunningSessionRecord = {
10
+ schemaVersion: 1;
11
+ name: string;
12
+ state: "running";
13
+ containerName: string;
14
+ containerId: string;
15
+ version: string;
16
+ port: number;
17
+ };
18
+ export type SessionRecord = StartingSessionRecord | RunningSessionRecord;
19
+ export declare function validateSessionName(name: string): string;
20
+ export declare function isSessionOwnerRunning(record: StartingSessionRecord): boolean;
21
+ export declare function reserveSession(stateDirectory: string, name: string, containerName: string): Promise<string>;
22
+ export declare function writeRunningSession(stateDirectory: string, record: RunningSessionRecord): Promise<void>;
23
+ export declare function readSession(stateDirectory: string, name: string): Promise<SessionRecord>;
24
+ export declare function removeSession(stateDirectory: string, name: string): Promise<void>;
@@ -0,0 +1,152 @@
1
+ import { chmod, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
2
+ import { spawnSync } from "node:child_process";
3
+ import { randomBytes } from "node:crypto";
4
+ import path from "node:path";
5
+ const SESSION_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
6
+ export function validateSessionName(name) {
7
+ if (!SESSION_NAME_PATTERN.test(name)) {
8
+ throw new Error("Invalid session name. Use 1-63 lowercase letters, numbers, or hyphens; start and end with a letter or number.");
9
+ }
10
+ return name;
11
+ }
12
+ function getProcessStartMarker(pid) {
13
+ if (!Number.isSafeInteger(pid) || pid <= 0)
14
+ return undefined;
15
+ const isWindows = process.platform === "win32";
16
+ const command = isWindows ? "powershell.exe" : "ps";
17
+ const args = isWindows
18
+ ? ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", `$process = [System.Diagnostics.Process]::GetProcessById(${pid}); $process.StartTime.ToUniversalTime().ToString('o')`]
19
+ : ["-o", "lstart=", "-p", String(pid)];
20
+ const result = spawnSync(command, args, {
21
+ encoding: "utf8",
22
+ env: { ...process.env, LC_ALL: "C", TZ: "UTC" },
23
+ timeout: isWindows ? 15_000 : 2_000,
24
+ windowsHide: true,
25
+ });
26
+ if (result.error || result.status !== 0)
27
+ return undefined;
28
+ return result.stdout.trim() || undefined;
29
+ }
30
+ function isProcessRunning(pid) {
31
+ try {
32
+ process.kill(pid, 0);
33
+ return true;
34
+ }
35
+ catch (error) {
36
+ if (error instanceof Error && "code" in error && error.code === "EPERM")
37
+ return true;
38
+ if (error instanceof Error && "code" in error && error.code === "ESRCH")
39
+ return false;
40
+ throw error;
41
+ }
42
+ }
43
+ export function isSessionOwnerRunning(record) {
44
+ const currentStartMarker = getProcessStartMarker(record.ownerPid);
45
+ if (currentStartMarker)
46
+ return record.ownerStartMarker === currentStartMarker;
47
+ if (isProcessRunning(record.ownerPid)) {
48
+ throw new Error(`Could not verify the owner process for emulator session "${record.name}". Ensure ${process.platform === "win32" ? "Windows PowerShell" : "ps"} is available, then retry.`);
49
+ }
50
+ return false;
51
+ }
52
+ function sessionPath(stateDirectory, name) {
53
+ return path.join(stateDirectory, "sessions", `${validateSessionName(name)}.json`);
54
+ }
55
+ export async function reserveSession(stateDirectory, name, containerName) {
56
+ const filename = sessionPath(stateDirectory, name);
57
+ const ownerStartMarker = getProcessStartMarker(process.pid);
58
+ if (!ownerStartMarker) {
59
+ throw new Error(`Could not identify the startup process. Ensure ${process.platform === "win32" ? "Windows PowerShell" : "ps"} is available to manage persistent sessions.`);
60
+ }
61
+ const directory = path.dirname(filename);
62
+ await mkdir(directory, { recursive: true, mode: 0o700 });
63
+ if (process.platform !== "win32")
64
+ await chmod(directory, 0o700);
65
+ const record = {
66
+ schemaVersion: 1,
67
+ name,
68
+ state: "starting",
69
+ containerName,
70
+ ownerPid: process.pid,
71
+ ownerStartMarker,
72
+ };
73
+ try {
74
+ await writeFile(filename, `${JSON.stringify(record)}\n`, { flag: "wx", mode: 0o600 });
75
+ }
76
+ catch (error) {
77
+ if (error instanceof Error && "code" in error && error.code === "EEXIST") {
78
+ throw new Error(`Emulator session "${name}" already exists. Stop it with "awesome-emulator down --session ${name}" before reusing the name.`);
79
+ }
80
+ throw error;
81
+ }
82
+ return filename;
83
+ }
84
+ export async function writeRunningSession(stateDirectory, record) {
85
+ validateSessionName(record.name);
86
+ const filename = sessionPath(stateDirectory, record.name);
87
+ const temporaryFilename = `${filename}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
88
+ try {
89
+ await writeFile(temporaryFilename, `${JSON.stringify(record)}\n`, { flag: "wx", mode: 0o600 });
90
+ await rename(temporaryFilename, filename);
91
+ }
92
+ finally {
93
+ await unlink(temporaryFilename).catch(() => { });
94
+ }
95
+ }
96
+ export async function readSession(stateDirectory, name) {
97
+ const filename = sessionPath(stateDirectory, name);
98
+ let contents;
99
+ try {
100
+ contents = await readFile(filename, "utf8");
101
+ }
102
+ catch (error) {
103
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
104
+ throw new Error(`Emulator session "${name}" was not found. Start it with "awesome-emulator up --session ${name}".`);
105
+ }
106
+ throw error;
107
+ }
108
+ let record;
109
+ try {
110
+ record = JSON.parse(contents);
111
+ }
112
+ catch {
113
+ throw new Error(`Emulator session "${name}" has invalid metadata. Remove its session file before continuing.`);
114
+ }
115
+ if (!isSessionRecord(record, name)) {
116
+ throw new Error(`Emulator session "${name}" has invalid metadata. Remove its session file before continuing.`);
117
+ }
118
+ return record;
119
+ }
120
+ export async function removeSession(stateDirectory, name) {
121
+ try {
122
+ await unlink(sessionPath(stateDirectory, name));
123
+ }
124
+ catch (error) {
125
+ if (error instanceof Error && "code" in error && error.code === "ENOENT")
126
+ return;
127
+ throw error;
128
+ }
129
+ }
130
+ function isSessionRecord(value, expectedName) {
131
+ if (typeof value !== "object" || value === null)
132
+ return false;
133
+ const record = value;
134
+ if (record.schemaVersion !== 1 || record.name !== expectedName || typeof record.containerName !== "string")
135
+ return false;
136
+ if (!record.containerName.startsWith("awesome-emulator-cli-session-") || !record.containerName.endsWith(`-${record.name}`))
137
+ return false;
138
+ if (record.state === "starting") {
139
+ return Number.isSafeInteger(record.ownerPid)
140
+ && Number(record.ownerPid) > 0
141
+ && typeof record.ownerStartMarker === "string"
142
+ && record.ownerStartMarker.length > 0;
143
+ }
144
+ if (record.state !== "running")
145
+ return false;
146
+ return typeof record.containerId === "string"
147
+ && /^[a-f0-9]{12,64}$/i.test(record.containerId)
148
+ && typeof record.version === "string"
149
+ && Number.isInteger(record.port)
150
+ && Number(record.port) > 0
151
+ && Number(record.port) <= 65535;
152
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "awesome-emulator-cli",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Run tests for AWS SDKs in any language; the CLI manages the local emulator in Docker.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",