awesome-emulator-cli 0.4.0 → 0.5.1

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
@@ -4,7 +4,7 @@
4
4
  <img src="./assets/social-preview-v2.png" alt="Awesome Emulator CLI — Local emulator testing for AWS SDKs" width="100%">
5
5
  </p>
6
6
 
7
- Awesome Emulator CLI is a Docker wrapper for AWS Emulator: it starts a local container and supplies connection settings to your test command. The CLI is distributed with Node.js, but the project under test can use any AWS SDK language and does not need to be a Node.js project.
7
+ A Node.js CLI that manages AWS Emulator in Docker and passes its connection settings to your test command. Your tests can use any AWS SDK language; they do not need to run in Node.js.
8
8
 
9
9
  This is an independent project and is not affiliated with or endorsed by Amazon Web Services.
10
10
 
@@ -14,93 +14,50 @@ This is an independent project and is not affiliated with or endorsed by Amazon
14
14
  - Docker Engine or Docker Desktop
15
15
  - x86_64/amd64 or ARM64/aarch64
16
16
 
17
- Node.js is required to run the CLI. Your application and test project can use any language.
17
+ On first use, Docker downloads the selected AWS Emulator RPM and signature, verifies the signature, and builds an image. The image is reused on later runs. To prepare it before tests start, run `npx awesome-emulator prepare`; use `--version` or `AWS_EMULATOR_VERSION` to select a release.
18
18
 
19
- On first start, Docker downloads the selected AWS Emulator RPM and its signature, verifies the signature, and builds a local image. Later starts reuse the image for that version and architecture.
20
-
21
- Prepare the image ahead of the first test run with:
22
-
23
- ```sh
24
- npx awesome-emulator prepare
25
- ```
26
-
27
- This builds or reuses the same versioned image as `start` and `run`, without starting a container or creating emulator state files. It can be run during CI setup or alongside other independent setup work so image construction does not delay the first test command. Pass `--version` or set `AWS_EMULATOR_VERSION` when you want to prepare a specific release.
28
-
29
- ## Run a test command
19
+ ## Run tests
30
20
 
31
21
  ```sh
32
22
  npm install --save-dev awesome-emulator-cli
33
23
  npx awesome-emulator run -- npm test
34
24
  ```
35
25
 
36
- `run` starts the emulator, supplies the connection settings to the child process, then stops the container. Use `--version` to select a release and `--port 0` to choose a free local port. Run `npx awesome-emulator --help` for all options.
37
-
38
- Set the child's default AWS region with `--region`:
26
+ `run` starts the emulator, supplies its endpoint and TLS settings to the child process, then stops the container. Set the child's default region with `--region`:
39
27
 
40
28
  ```sh
41
29
  npx awesome-emulator run --region ap-northeast-1 -- npm test
42
30
  ```
43
31
 
44
- By default, both `AWS_REGION` and `AWS_DEFAULT_REGION` are `us-east-1`. `--region` sets both for the child command without changing the emulator endpoint. An SDK client configured with its own region continues to use that explicit region.
32
+ Both `AWS_REGION` and `AWS_DEFAULT_REGION` default to `us-east-1`. An explicit region on an SDK client still takes precedence.
45
33
 
46
- ### Run non-Node projects
34
+ The CLI removes inherited AWS credentials, profiles, and service endpoints from the child environment. Credentials or endpoints explicitly set in project or build configuration still need to target the emulator. Commands run without a shell by default; on Windows, `.cmd` and `.bat` commands need `--shell`, which should only be used with trusted arguments.
47
35
 
48
- You can run an existing project command even when the project has no `package.json`. Use `npm exec` to download the CLI for the run:
36
+ The CLI can run commands from projects without a `package.json` too. For example, run Python tests with:
49
37
 
50
38
  ```sh
51
39
  npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run -- python -m pytest
52
40
  ```
53
41
 
54
- The same pattern works with other SDK projects:
55
-
56
- ```sh
57
- # AWS CLI v2, Boto3, and AWS SDK for Go v2 use AWS_CA_BUNDLE automatically.
58
- npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run -- aws sts get-caller-identity
59
- npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run -- python -m pytest
60
- npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run -- go test ./...
61
-
62
- # AWS SDK for JavaScript v3 uses NODE_EXTRA_CA_CERTS, which the CLI sets by default.
63
- npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run -- npm test
64
-
65
- # Java, Rust, and .NET need an additional TLS setting.
66
- npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run --sdk java-v2 -- ./mvnw -B -o test
67
- npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run --sdk rust -- cargo test --offline
68
- npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run --sdk dotnet -- dotnet test --no-restore
69
- ```
70
-
71
- Resolve Java, Rust, and .NET dependencies before the wrapped command when they are not already cached. For example, run `./mvnw -B dependency:go-offline`, `cargo fetch`, or `dotnet restore` before starting the emulator.
72
-
73
- The repository runs an integration smoke check for AWS CLI v2, Boto3, AWS SDK for JavaScript v3, Java 2.x, Go v2, Rust, and .NET. It verifies that each client reaches the emulator's STS endpoint with TLS enabled and receives the emulator account ID.
42
+ The same pattern works with AWS CLI, Go, Java, Rust, and .NET projects. Use `--sdk` when a command needs SDK-specific TLS settings; see the [SDK configuration guide](./docs/sdk-configuration.md).
74
43
 
75
- The common child environment sets `AWS_ENDPOINT_URL`, the emulator credentials and config files, `AWS_CA_BUNDLE`, and the region. The CLI removes inherited credential variables, profile selectors, and service-specific endpoint variables so those host environment settings cannot redirect or authenticate the test. `AWS_DISABLE_HOST_PREFIX_INJECTION` is enabled for SDKs that otherwise rewrite the local host. The wrapper manages inherited environment and JVM option variables; project code or build configuration that explicitly sets credentials or endpoints must be configured for the emulator.
44
+ ## Reuse the emulator across commands
76
45
 
77
- Use `--sdk` only when a process needs SDK-specific TLS configuration. It can be repeated when one command runs more than one SDK:
78
-
79
- | SDK | TLS configuration |
80
- | --- | --- |
81
- | AWS CLI v2, Boto3, AWS SDK for Go v2 | `AWS_CA_BUNDLE` |
82
- | AWS SDK for JavaScript v3 | `NODE_EXTRA_CA_CERTS` |
83
- | AWS SDK for Java 2.x | `--sdk java-v2` adds the emulator `truststore.p12` to `JAVA_TOOL_OPTIONS` |
84
- | AWS SDK for Rust | `--sdk rust` sets `SSL_CERT_FILE` to `ca.pem` |
85
- | AWS SDK for .NET | `--sdk dotnet` sets `SSL_CERT_FILE` to `ca.pem` |
86
-
87
- Java's `JAVA_TOOL_OPTIONS` applies to every JVM started by the child command, including Maven or Gradle and test workers. Resolve Java build dependencies before invoking `awesome-emulator run`, or use a truststore that contains both the emulator certificate and the certificates for other HTTPS hosts. The emulator truststore contains only the emulator certificate, so HTTPS calls to Maven Central, AWS, or other hosts can fail while it is active. The CLI appends to existing `JAVA_TOOL_OPTIONS`; if `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS`, or `_JAVA_OPTIONS` already sets `javax.net.ssl.trustStore`, it preserves that truststore. If only `javax.net.ssl.trustStoreType=PKCS12` is set, the CLI adds the emulator truststore path and preserves the type. An incompatible truststore type requires a custom truststore path. A preserved truststore must also trust the emulator. `MAVEN_OPTS` and `GRADLE_OPTS` remain in their own variables; if either sets a separate truststore, make sure the Java test JVM trusts the emulator too.
88
-
89
- The AWS SDK for Java gives JVM system properties precedence over environment variables. When `--sdk java-v2` is selected, the CLI checks inherited `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS`, `_JAVA_OPTIONS`, `JAVA_OPTS`, `MAVEN_OPTS`, `GRADLE_OPTS`, `ANT_OPTS`, and `SBT_OPTS` values and rejects AWS credential, profile, or endpoint properties and `@argument-file` references so inherited JVM options cannot bypass the emulator settings.
90
-
91
- `AWS_CA_BUNDLE` and `SSL_CERT_FILE` replace the default CA bundle for SDKs that read them. If the same process must contact other HTTPS services, create a combined bundle with the emulator CA and the roots it needs. `NODE_EXTRA_CA_CERTS` is additive to Node.js's default trust roots.
92
-
93
- Child commands run without a shell by default, so each argument is passed as data. On Windows, `.cmd` and `.bat` launchers such as `npm`, and shell built-ins such as `echo` and `dir`, require an explicit shell opt-in:
46
+ Use a named session when setup and tests run as separate commands or CI steps:
94
47
 
95
48
  ```sh
96
- npx awesome-emulator run --shell -- npm test
49
+ npx awesome-emulator up --session ci-tests --init -- node scripts/seed-emulator.js
50
+ npx awesome-emulator exec --session ci-tests -- npm test
51
+ npx awesome-emulator down --session ci-tests
97
52
  ```
98
53
 
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.
54
+ `--init` runs once after the emulator is healthy. If it fails, `up` stops the container and exits with an error. Initializer output goes to stderr so `up`'s JSON output stays machine-readable. Use `down` in an always-run CI cleanup step to stop the session after failures.
55
+
56
+ Session metadata is stored under `~/.aws/emulator/sessions/` (Windows: `%USERPROFILE%\.aws\emulator\sessions\`) and contains connection details, not credential values.
100
57
 
101
58
  ## Use from Node.js
102
59
 
103
- Use the API when your test harness needs to control the emulator lifecycle directly:
60
+ Use the API when a test harness needs to control the emulator directly:
104
61
 
105
62
  ```js
106
63
  import { startEmulator } from "awesome-emulator-cli";
@@ -113,24 +70,18 @@ try {
113
70
  }
114
71
  ```
115
72
 
116
- Pass an `AbortSignal` as `signal` to cancel image building or startup. `NODE_EXTRA_CA_CERTS` is read when Node.js starts. For an already-running Node.js process, configure the AWS SDK's HTTPS handler with `emulator.caFile`; use `awesome-emulator run` when you want the wrapper to start a child process with TLS settings already applied.
73
+ Pass an `AbortSignal` as `signal` to cancel image building or startup. For an already-running Node.js process, configure the AWS SDK's HTTPS handler with `emulator.caFile`; `NODE_EXTRA_CA_CERTS` is only read when Node.js starts.
117
74
 
118
75
  ## Local files and telemetry
119
76
 
120
- The emulator writes its config, credentials, and CA certificate under `~/.aws/emulator/<port>/` (Windows: `%USERPROFILE%\.aws\emulator\<port>\`). The emulator keeps resources in memory; a clean stop removes the per-port files and resources.
121
-
122
- Telemetry is on by default. AWS says it collects aggregate usage and error data, not requests, responses, code, credentials, or personal data. Turn it off for a run with:
77
+ The emulator stores its config, credentials, and CA certificate under `~/.aws/emulator/<port>/` (Windows: `%USERPROFILE%\.aws\emulator\<port>\`). Resources stay in memory and are removed when the container stops.
123
78
 
124
- ```sh
125
- npx awesome-emulator run --telemetry off -- npm test
126
- ```
127
-
128
- Read the [AWS Emulator telemetry details](https://docs.aws.amazon.com/emulator/latest/userguide/telemetry.html) before choosing whether to leave telemetry on.
79
+ Telemetry is on by default. Turn it off for a run with `--telemetry off`. See [AWS Emulator telemetry details](https://docs.aws.amazon.com/emulator/latest/userguide/telemetry.html) for what it collects.
129
80
 
130
81
  AWS Emulator is for building and testing. Do not use it for production workloads or security testing. See the [official limitations](https://docs.aws.amazon.com/emulator/latest/userguide/) and [security guidance](https://docs.aws.amazon.com/emulator/latest/userguide/security.html).
131
82
 
132
- See [CONTRIBUTING.md](./CONTRIBUTING.md) to contribute and [SECURITY.md](./SECURITY.md) to report a vulnerability.
133
-
134
83
  ## License
135
84
 
136
85
  MIT. See [LICENSE](./LICENSE). This license covers the wrapper; downloaded AWS Emulator binaries retain their own license and notices.
86
+
87
+ See [CONTRIBUTING.md](./CONTRIBUTING.md) to contribute and [SECURITY.md](./SECURITY.md) to report a vulnerability.
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.1",
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",