awesome-emulator-cli 0.1.0 → 0.1.2

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
@@ -21,6 +21,14 @@ npx awesome-emulator run -- npm test
21
21
 
22
22
  `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.
23
23
 
24
+ 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:
25
+
26
+ ```sh
27
+ npx awesome-emulator run --shell -- npm test
28
+ ```
29
+
30
+ 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.
31
+
24
32
  ## Use from Node.js
25
33
 
26
34
  Use the API when your test harness needs to control the emulator lifecycle directly:
package/dist/cli.js CHANGED
@@ -1,15 +1,17 @@
1
1
  #!/usr/bin/env node
2
2
  import { runWithEmulator, startEmulator } from "./index.js";
3
+ import { FORWARDED_SIGNALS, getSignalExitCode } from "./signals.js";
3
4
  function usage() {
4
5
  console.log(`Usage:
5
6
  awesome-emulator start [options]
6
- awesome-emulator run [options] -- <command> [args...]
7
+ awesome-emulator run [options] [--shell] -- <command> [args...]
7
8
 
8
9
  Options:
9
10
  -v, --version <version> AWS Emulator version (default: 1.0.522)
10
11
  -p, --port <port> Host port; 0 chooses an available port (default: 9297)
11
12
  -t, --telemetry <on|off> Telemetry setting (default: on)
12
13
  --memory <limit> Container memory limit (default: 2g)
14
+ --shell (run only) Enable .cmd/.bat and built-ins; trusted values only
13
15
  -h, --help Show this help`);
14
16
  }
15
17
  function parse(argv) {
@@ -31,6 +33,12 @@ function parse(argv) {
31
33
  }
32
34
  if (token === "-h" || token === "--help")
33
35
  return { help: true };
36
+ if (token === "--shell") {
37
+ if (command !== "run")
38
+ throw new Error("--shell can only be used with the run command.");
39
+ options.shell = true;
40
+ continue;
41
+ }
34
42
  const optionNames = {
35
43
  "-v": "version", "--version": "version",
36
44
  "-p": "port", "--port": "port",
@@ -54,13 +62,7 @@ function waitForAbort(signal) {
54
62
  return new Promise((resolve) => signal.addEventListener("abort", () => resolve(), { once: true }));
55
63
  }
56
64
  function signalExitCode(signal) {
57
- if (signal.reason === "SIGINT")
58
- return 130;
59
- if (signal.reason === "SIGTERM")
60
- return 143;
61
- if (signal.reason === "SIGHUP")
62
- return 129;
63
- return 1;
65
+ return getSignalExitCode(signal.reason);
64
66
  }
65
67
  function formatError(error) {
66
68
  if (error instanceof AggregateError) {
@@ -82,7 +84,13 @@ async function main(signal) {
82
84
  return runWithEmulator(program, args, { ...parsed.options, signal });
83
85
  }
84
86
  if (parsed.command === "start") {
85
- const emulator = await startEmulator({ ...parsed.options, signal });
87
+ const emulator = await startEmulator({
88
+ version: parsed.options.version,
89
+ port: parsed.options.port,
90
+ telemetry: parsed.options.telemetry,
91
+ memory: parsed.options.memory,
92
+ signal,
93
+ });
86
94
  try {
87
95
  if (!signal.aborted) {
88
96
  console.log(JSON.stringify({
@@ -106,7 +114,7 @@ async function main(signal) {
106
114
  }
107
115
  const controller = new AbortController();
108
116
  const signalHandlers = new Map();
109
- for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
117
+ for (const signal of FORWARDED_SIGNALS) {
110
118
  const handler = () => controller.abort(signal);
111
119
  signalHandlers.set(signal, handler);
112
120
  process.once(signal, handler);
@@ -0,0 +1,20 @@
1
+ export type EmulatorEnvironment = {
2
+ AWS_ENDPOINT_URL: string;
3
+ AWS_SHARED_CREDENTIALS_FILE: string;
4
+ AWS_CONFIG_FILE: string;
5
+ AWS_CA_BUNDLE: string;
6
+ AWS_EC2_METADATA_DISABLED: "true";
7
+ AWS_REGION: string;
8
+ AWS_DEFAULT_REGION: string;
9
+ NODE_EXTRA_CA_CERTS: string;
10
+ };
11
+ export type EmulatorConnectionSettings = {
12
+ endpointUrl: string;
13
+ healthCheckUrl: string;
14
+ configFile: string;
15
+ credentialsFile: string;
16
+ caFile: string;
17
+ environment: EmulatorEnvironment;
18
+ };
19
+ export declare function createEmulatorConnectionSettings(port: number, stateDirectory: string): EmulatorConnectionSettings;
20
+ export declare function createChildEnvironment(parentEnvironment: NodeJS.ProcessEnv, emulatorEnvironment: EmulatorEnvironment): NodeJS.ProcessEnv;
@@ -0,0 +1,47 @@
1
+ import path from "node:path";
2
+ const AWS_CREDENTIAL_ENVIRONMENT_KEYS = [
3
+ "AWS_ACCESS_KEY_ID",
4
+ "AWS_SECRET_ACCESS_KEY",
5
+ "AWS_SESSION_TOKEN",
6
+ "AWS_PROFILE",
7
+ "AWS_DEFAULT_PROFILE",
8
+ "AWS_ROLE_ARN",
9
+ "AWS_WEB_IDENTITY_TOKEN_FILE",
10
+ "AWS_CONTAINER_CREDENTIALS_FULL_URI",
11
+ "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",
12
+ "AWS_CONTAINER_AUTHORIZATION_TOKEN",
13
+ "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE",
14
+ "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS",
15
+ ];
16
+ export function createEmulatorConnectionSettings(port, stateDirectory) {
17
+ const endpointUrl = `https://127.0.0.1:${port}`;
18
+ const portDirectory = path.join(stateDirectory, String(port));
19
+ const environment = {
20
+ AWS_ENDPOINT_URL: endpointUrl,
21
+ AWS_SHARED_CREDENTIALS_FILE: path.join(portDirectory, "emulator_credentials"),
22
+ AWS_CONFIG_FILE: path.join(portDirectory, "config"),
23
+ AWS_CA_BUNDLE: path.join(portDirectory, "ca.pem"),
24
+ AWS_EC2_METADATA_DISABLED: "true",
25
+ AWS_REGION: "us-east-1",
26
+ AWS_DEFAULT_REGION: "us-east-1",
27
+ NODE_EXTRA_CA_CERTS: path.join(portDirectory, "ca.pem"),
28
+ };
29
+ return {
30
+ endpointUrl,
31
+ healthCheckUrl: `${endpointUrl}/__admin/health`,
32
+ configFile: environment.AWS_CONFIG_FILE,
33
+ credentialsFile: environment.AWS_SHARED_CREDENTIALS_FILE,
34
+ caFile: environment.AWS_CA_BUNDLE,
35
+ environment,
36
+ };
37
+ }
38
+ export function createChildEnvironment(parentEnvironment, emulatorEnvironment) {
39
+ const childEnvironment = { ...parentEnvironment, ...emulatorEnvironment };
40
+ for (const key of AWS_CREDENTIAL_ENVIRONMENT_KEYS)
41
+ delete childEnvironment[key];
42
+ for (const key of Object.keys(childEnvironment)) {
43
+ if (key.startsWith("AWS_ENDPOINT_URL_"))
44
+ delete childEnvironment[key];
45
+ }
46
+ return childEnvironment;
47
+ }
@@ -0,0 +1,8 @@
1
+ export type EmulatorArchitecture = {
2
+ docker: "amd64" | "arm64";
3
+ rpm: "x86_64" | "aarch64";
4
+ };
5
+ export declare function getArchitecture(): EmulatorArchitecture;
6
+ export declare function createEmulatorDockerfile(): string;
7
+ export declare function createEmulatorImageTag(version: string, architecture: EmulatorArchitecture, dockerfile: string): string;
8
+ export declare function ensureEmulatorImage(version: string, architecture: EmulatorArchitecture, signal?: AbortSignal): Promise<string>;
@@ -0,0 +1,88 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { docker, throwIfAborted } from "./docker.js";
6
+ const PACKAGE_ROOT = "https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS";
7
+ const PACKAGE_SIGNING_KEY = "https://downloads.aws.com/keys/gpg/current.asc";
8
+ const PACKAGE_SIGNING_FINGERPRINT = "98BCF336A3BE53B734E967C52E5BF49BD940F624";
9
+ const CONTAINER_PORT = 9297;
10
+ export function getArchitecture() {
11
+ if (process.arch === "x64")
12
+ return { docker: "amd64", rpm: "x86_64" };
13
+ if (process.arch === "arm64")
14
+ return { docker: "arm64", rpm: "aarch64" };
15
+ throw new Error(`AWS Emulator is not available for this architecture: ${process.arch}.`);
16
+ }
17
+ export function createEmulatorDockerfile() {
18
+ return `FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal
19
+ ARG AWS_EMULATOR_VERSION
20
+ ARG AWS_EMULATOR_RPM_ARCH
21
+ RUN set -eu; \\
22
+ export GNUPGHOME=/tmp/aws-emulator-gnupg; \\
23
+ mkdir -m 0700 "$GNUPGHOME"; \\
24
+ dnf swap -y gnupg2-minimal gnupg2-full; \\
25
+ curl -fsSLo /tmp/aws-emulator.rpm ${PACKAGE_ROOT}/aws-emulator-\${AWS_EMULATOR_VERSION}-1-\${AWS_EMULATOR_RPM_ARCH}.rpm; \\
26
+ curl -fsSLo /tmp/aws-emulator.rpm.sig ${PACKAGE_ROOT}/aws-emulator-\${AWS_EMULATOR_VERSION}-1-\${AWS_EMULATOR_RPM_ARCH}.rpm.sig; \\
27
+ curl -fsSLo /tmp/aws-publishing.asc ${PACKAGE_SIGNING_KEY}; \\
28
+ gpg --batch --import /tmp/aws-publishing.asc; \\
29
+ fingerprint="$(gpg --batch --with-colons --fingerprint "${PACKAGE_SIGNING_FINGERPRINT}" | awk -F: '$1 == "fpr" { print $10; exit }')"; \\
30
+ test "$fingerprint" = "${PACKAGE_SIGNING_FINGERPRINT}"; \\
31
+ gpg --batch --export "$fingerprint" > /tmp/aws-publishing.gpg; \\
32
+ gpgv --keyring /tmp/aws-publishing.gpg /tmp/aws-emulator.rpm.sig /tmp/aws-emulator.rpm; \\
33
+ dnf remove -y gnupg2-smime; \\
34
+ dnf swap -y gnupg2-full gnupg2-minimal; \\
35
+ rpm -i /tmp/aws-emulator.rpm; \\
36
+ mkdir -p /home/emulator/.aws/emulator; \\
37
+ chown -R 1000:1000 /home/emulator; \\
38
+ rm -rf "$GNUPGHOME" /tmp/aws-emulator.rpm /tmp/aws-emulator.rpm.sig /tmp/aws-publishing.asc /tmp/aws-publishing.gpg; \\
39
+ dnf clean all
40
+ USER 1000:1000
41
+ ENV HOME=/home/emulator
42
+ EXPOSE ${CONTAINER_PORT}
43
+ ENTRYPOINT ["aws-emulator", "-b", "0.0.0.0"]
44
+ `;
45
+ }
46
+ export function createEmulatorImageTag(version, architecture, dockerfile) {
47
+ const buildDefinitionHash = createHash("sha256")
48
+ .update(JSON.stringify({
49
+ dockerfile,
50
+ version,
51
+ dockerArchitecture: architecture.docker,
52
+ rpmArchitecture: architecture.rpm,
53
+ }))
54
+ .digest("hex");
55
+ return `awesome-emulator-cli:${version}-${architecture.docker}-${buildDefinitionHash}`;
56
+ }
57
+ export async function ensureEmulatorImage(version, architecture, signal) {
58
+ throwIfAborted(signal);
59
+ const dockerfile = createEmulatorDockerfile();
60
+ const image = createEmulatorImageTag(version, architecture, dockerfile);
61
+ try {
62
+ await docker(["image", "inspect", image], { capture: true, signal });
63
+ throwIfAborted(signal);
64
+ return image;
65
+ }
66
+ catch {
67
+ throwIfAborted(signal);
68
+ // Build the official Linux package into a local image on first use.
69
+ }
70
+ const context = await mkdtemp(path.join(os.tmpdir(), "awesome-emulator-cli-"));
71
+ try {
72
+ throwIfAborted(signal);
73
+ await writeFile(path.join(context, "Dockerfile"), dockerfile, "utf8");
74
+ await docker([
75
+ "build",
76
+ "--platform", `linux/${architecture.docker}`,
77
+ "--build-arg", `AWS_EMULATOR_VERSION=${version}`,
78
+ "--build-arg", `AWS_EMULATOR_RPM_ARCH=${architecture.rpm}`,
79
+ "--tag", image,
80
+ context,
81
+ ], { signal });
82
+ throwIfAborted(signal);
83
+ return image;
84
+ }
85
+ finally {
86
+ await rm(context, { recursive: true, force: true });
87
+ }
88
+ }
@@ -0,0 +1,24 @@
1
+ export type StartEmulatorOptions = {
2
+ version?: string;
3
+ port?: number | string;
4
+ telemetry?: string;
5
+ memory?: string;
6
+ startupTimeoutMs?: number;
7
+ signal?: AbortSignal;
8
+ };
9
+ export type RunWithEmulatorOptions = StartEmulatorOptions & {
10
+ /**
11
+ * Run the child command through a shell. Shell metacharacters in command or
12
+ * arguments are interpreted, so only enable this for trusted values.
13
+ * Defaults to false.
14
+ */
15
+ shell?: boolean;
16
+ };
17
+ export type ResolvedEmulatorOptions = {
18
+ version: string;
19
+ requestedPort: number;
20
+ telemetry: "on" | "off";
21
+ memory: string;
22
+ startupTimeoutMs: number;
23
+ };
24
+ export declare function resolveEmulatorOptions(options: StartEmulatorOptions, environment?: NodeJS.ProcessEnv): ResolvedEmulatorOptions;
@@ -0,0 +1,48 @@
1
+ const DEFAULT_VERSION = "1.0.522";
2
+ const DEFAULT_PORT = 9297;
3
+ const DEFAULT_MEMORY = "2g";
4
+ function normalizeVersion(value, environment) {
5
+ const version = value ?? environment.AWS_EMULATOR_VERSION ?? DEFAULT_VERSION;
6
+ if (!/^\d+\.\d+\.\d+$/.test(String(version))) {
7
+ throw new Error(`Invalid AWS Emulator version: ${version}. Use a version such as 1.0.522.`);
8
+ }
9
+ return String(version);
10
+ }
11
+ function normalizePort(value, environment) {
12
+ const port = Number(value ?? environment.AWS_EMULATOR_PORT ?? DEFAULT_PORT);
13
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
14
+ throw new Error(`Invalid port: ${value}. Use a number from 0 to 65535.`);
15
+ }
16
+ return port;
17
+ }
18
+ function normalizeTelemetry(value, environment) {
19
+ const telemetry = String(value ?? environment.EMULATOR_TELEMETRY ?? "on").toLowerCase();
20
+ if (["on", "true", "1"].includes(telemetry))
21
+ return "on";
22
+ if (["off", "false", "0"].includes(telemetry))
23
+ return "off";
24
+ throw new Error(`Invalid telemetry setting: ${value}. Use on or off.`);
25
+ }
26
+ function normalizeMemory(value) {
27
+ const memory = String(value ?? DEFAULT_MEMORY);
28
+ if (!/^\d+(?:\.\d+)?[kmgt]$/i.test(memory) || Number.parseFloat(memory) <= 0) {
29
+ throw new Error(`Invalid memory limit: ${value}. Use a Docker memory value such as 2g.`);
30
+ }
31
+ return memory;
32
+ }
33
+ function normalizeStartupTimeout(value) {
34
+ const timeout = Number(value ?? 120_000);
35
+ if (!Number.isInteger(timeout) || timeout < 1000) {
36
+ throw new Error("startupTimeoutMs must be an integer of at least 1000.");
37
+ }
38
+ return timeout;
39
+ }
40
+ export function resolveEmulatorOptions(options, environment = process.env) {
41
+ return {
42
+ version: normalizeVersion(options.version, environment),
43
+ requestedPort: normalizePort(options.port, environment),
44
+ telemetry: normalizeTelemetry(options.telemetry, environment),
45
+ memory: normalizeMemory(options.memory),
46
+ startupTimeoutMs: normalizeStartupTimeout(options.startupTimeoutMs),
47
+ };
48
+ }
package/dist/index.d.ts CHANGED
@@ -1,11 +1,7 @@
1
- export type StartEmulatorOptions = {
2
- version?: string;
3
- port?: number | string;
4
- telemetry?: string;
5
- memory?: string;
6
- startupTimeoutMs?: number;
7
- signal?: AbortSignal;
8
- };
1
+ import { type EmulatorEnvironment } from "./emulator-environment.js";
2
+ import { type RunWithEmulatorOptions, type StartEmulatorOptions } from "./emulator-options.js";
3
+ export type { RunWithEmulatorOptions, StartEmulatorOptions } from "./emulator-options.js";
4
+ export type { EmulatorEnvironment } from "./emulator-environment.js";
9
5
  export type EmulatorSession = {
10
6
  version: string;
11
7
  port: number;
@@ -18,16 +14,6 @@ export type EmulatorSession = {
18
14
  containerId: string;
19
15
  stop: () => Promise<void>;
20
16
  };
21
- export type EmulatorEnvironment = {
22
- AWS_ENDPOINT_URL: string;
23
- AWS_SHARED_CREDENTIALS_FILE: string;
24
- AWS_CONFIG_FILE: string;
25
- AWS_CA_BUNDLE: string;
26
- AWS_EC2_METADATA_DISABLED: "true";
27
- AWS_REGION: string;
28
- AWS_DEFAULT_REGION: string;
29
- NODE_EXTRA_CA_CERTS: string;
30
- };
31
17
  /**
32
18
  * Start AWS Emulator in a local Docker container.
33
19
  *
@@ -38,4 +24,4 @@ export declare function startEmulator(options?: StartEmulatorOptions): Promise<E
38
24
  /**
39
25
  * Run a child process with AWS Emulator settings and stop the emulator afterward.
40
26
  */
41
- export declare function runWithEmulator(command: string, args?: string[], options?: StartEmulatorOptions): Promise<number>;
27
+ export declare function runWithEmulator(command: string, args?: string[], options?: RunWithEmulatorOptions): Promise<number>;
package/dist/index.js CHANGED
@@ -1,116 +1,15 @@
1
1
  import { randomBytes } from "node:crypto";
2
- import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { mkdir, readFile } from "node:fs/promises";
3
3
  import https from "node:https";
4
4
  import net from "node:net";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
7
  import { createRetryableStop, startContainer, stopContainer, withEmulator } from "./container-lifecycle.js";
8
8
  import { docker, throwIfAborted } from "./docker.js";
9
+ import { createChildEnvironment, createEmulatorConnectionSettings } from "./emulator-environment.js";
10
+ import { ensureEmulatorImage, getArchitecture } from "./emulator-image.js";
11
+ import { resolveEmulatorOptions } from "./emulator-options.js";
9
12
  import { runCommand } from "./process.js";
10
- const DEFAULT_VERSION = "1.0.522";
11
- const DEFAULT_PORT = 9297;
12
- const DEFAULT_MEMORY = "2g";
13
- const PACKAGE_ROOT = "https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS";
14
- const PACKAGE_SIGNING_KEY = "https://downloads.aws.com/keys/gpg/current.asc";
15
- const PACKAGE_SIGNING_FINGERPRINT = "98BCF336A3BE53B734E967C52E5BF49BD940F624";
16
- const CONTAINER_PORT = 9297;
17
- function normalizeVersion(value) {
18
- const version = value ?? process.env.AWS_EMULATOR_VERSION ?? DEFAULT_VERSION;
19
- if (!/^\d+\.\d+\.\d+$/.test(String(version))) {
20
- throw new Error(`Invalid AWS Emulator version: ${version}. Use a version such as 1.0.522.`);
21
- }
22
- return String(version);
23
- }
24
- function normalizePort(value) {
25
- const port = Number(value ?? process.env.AWS_EMULATOR_PORT ?? DEFAULT_PORT);
26
- if (!Number.isInteger(port) || port < 0 || port > 65535) {
27
- throw new Error(`Invalid port: ${value}. Use a number from 0 to 65535.`);
28
- }
29
- return port;
30
- }
31
- function normalizeTelemetry(value) {
32
- const telemetry = String(value ?? process.env.EMULATOR_TELEMETRY ?? "on").toLowerCase();
33
- if (["on", "true", "1"].includes(telemetry))
34
- return "on";
35
- if (["off", "false", "0"].includes(telemetry))
36
- return "off";
37
- throw new Error(`Invalid telemetry setting: ${value}. Use on or off.`);
38
- }
39
- function normalizeMemory(value) {
40
- const memory = String(value ?? DEFAULT_MEMORY);
41
- if (!/^\d+(?:\.\d+)?[kmgt]$/i.test(memory) || Number.parseFloat(memory) <= 0) {
42
- throw new Error(`Invalid memory limit: ${value}. Use a Docker memory value such as 2g.`);
43
- }
44
- return memory;
45
- }
46
- function normalizeStartupTimeout(value) {
47
- const timeout = Number(value ?? 120_000);
48
- if (!Number.isInteger(timeout) || timeout < 1000) {
49
- throw new Error("startupTimeoutMs must be an integer of at least 1000.");
50
- }
51
- return timeout;
52
- }
53
- function getArchitecture() {
54
- if (process.arch === "x64")
55
- return { docker: "amd64", rpm: "x86_64" };
56
- if (process.arch === "arm64")
57
- return { docker: "arm64", rpm: "aarch64" };
58
- throw new Error(`AWS Emulator is not available for this architecture: ${process.arch}.`);
59
- }
60
- async function ensureImage(version, architecture, signal) {
61
- throwIfAborted(signal);
62
- const image = `awesome-emulator-cli:${version}-${architecture.docker}`;
63
- try {
64
- await docker(["image", "inspect", image], { capture: true, signal });
65
- throwIfAborted(signal);
66
- return image;
67
- }
68
- catch {
69
- throwIfAborted(signal);
70
- // Build the official Linux package into a local image on first use.
71
- }
72
- const context = await mkdtemp(path.join(os.tmpdir(), "awesome-emulator-cli-"));
73
- const dockerfile = `FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal
74
- ARG AWS_EMULATOR_VERSION
75
- ARG AWS_EMULATOR_RPM_ARCH
76
- RUN set -eu; \\
77
- export GNUPGHOME=/tmp/aws-emulator-gnupg; \\
78
- mkdir -m 0700 "$GNUPGHOME"; \\
79
- curl -fsSLo /tmp/aws-emulator.rpm ${PACKAGE_ROOT}/aws-emulator-\${AWS_EMULATOR_VERSION}-1-\${AWS_EMULATOR_RPM_ARCH}.rpm; \\
80
- curl -fsSLo /tmp/aws-emulator.rpm.sig ${PACKAGE_ROOT}/aws-emulator-\${AWS_EMULATOR_VERSION}-1-\${AWS_EMULATOR_RPM_ARCH}.rpm.sig; \\
81
- curl -fsSLo /tmp/aws-publishing.asc ${PACKAGE_SIGNING_KEY}; \\
82
- gpg --batch --import /tmp/aws-publishing.asc; \\
83
- fingerprint="$(gpg --batch --with-colons --fingerprint ssm-publishing@amazon.com | awk -F: '$1 == "fpr" { print $10; exit }')"; \\
84
- test "$fingerprint" = "${PACKAGE_SIGNING_FINGERPRINT}"; \\
85
- gpg --batch --verify /tmp/aws-emulator.rpm.sig /tmp/aws-emulator.rpm; \\
86
- rpm -i /tmp/aws-emulator.rpm; \\
87
- mkdir -p /home/emulator/.aws/emulator; \\
88
- chown -R 1000:1000 /home/emulator; \\
89
- rm -rf "$GNUPGHOME" /tmp/aws-emulator.rpm /tmp/aws-emulator.rpm.sig /tmp/aws-publishing.asc; \\
90
- dnf clean all
91
- USER 1000:1000
92
- ENV HOME=/home/emulator
93
- EXPOSE ${CONTAINER_PORT}
94
- ENTRYPOINT ["aws-emulator", "-b", "0.0.0.0"]
95
- `;
96
- try {
97
- throwIfAborted(signal);
98
- await writeFile(path.join(context, "Dockerfile"), dockerfile, "utf8");
99
- await docker([
100
- "build",
101
- "--platform", `linux/${architecture.docker}`,
102
- "--build-arg", `AWS_EMULATOR_VERSION=${version}`,
103
- "--build-arg", `AWS_EMULATOR_RPM_ARCH=${architecture.rpm}`,
104
- "--tag", image,
105
- context,
106
- ], { signal });
107
- throwIfAborted(signal);
108
- return image;
109
- }
110
- finally {
111
- await rm(context, { recursive: true, force: true });
112
- }
113
- }
114
13
  async function getAvailablePort() {
115
14
  const server = net.createServer();
116
15
  await new Promise((resolve, reject) => {
@@ -144,6 +43,27 @@ function requestHealth(port, ca, signal) {
144
43
  });
145
44
  }
146
45
  const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
46
+ function createContainerRunArguments({ architecture, containerName, image, memory, port, stateDirectory, telemetry, }) {
47
+ const hostUser = process.platform === "linux"
48
+ && typeof process.getuid === "function"
49
+ && typeof process.getgid === "function"
50
+ ? ["--user", `${process.getuid()}:${process.getgid()}`]
51
+ : [];
52
+ return [
53
+ "run", "--detach",
54
+ "--platform", `linux/${architecture.docker}`,
55
+ ...hostUser,
56
+ "--memory", memory,
57
+ "--memory-swap", memory,
58
+ "--publish", `127.0.0.1:${port}:${port}`,
59
+ "--mount", `type=bind,source=${stateDirectory},target=/home/emulator/.aws/emulator`,
60
+ "--env", "HOME=/home/emulator",
61
+ "--name", containerName,
62
+ image,
63
+ "-p", String(port),
64
+ "-t", telemetry,
65
+ ];
66
+ }
147
67
  async function waitUntilHealthy(containerId, port, stateDirectory, timeoutMs, signal) {
148
68
  const deadline = Date.now() + timeoutMs;
149
69
  const caFile = path.join(stateDirectory, String(port), "ca.pem");
@@ -184,38 +104,25 @@ async function waitUntilHealthy(containerId, port, stateDirectory, timeoutMs, si
184
104
  */
185
105
  export async function startEmulator(options = {}) {
186
106
  throwIfAborted(options.signal);
187
- const version = normalizeVersion(options.version);
188
- const requestedPort = normalizePort(options.port);
107
+ const { version, requestedPort, telemetry, memory, startupTimeoutMs } = resolveEmulatorOptions(options);
189
108
  const port = requestedPort === 0 ? await getAvailablePort() : requestedPort;
190
109
  throwIfAborted(options.signal);
191
- const telemetry = normalizeTelemetry(options.telemetry);
192
- const memory = normalizeMemory(options.memory);
193
- const startupTimeoutMs = normalizeStartupTimeout(options.startupTimeoutMs);
194
110
  const architecture = getArchitecture();
195
111
  const stateDirectory = path.join(os.homedir(), ".aws", "emulator");
196
112
  await mkdir(stateDirectory, { recursive: true, mode: 0o700 });
197
- const image = await ensureImage(version, architecture, options.signal);
113
+ const image = await ensureEmulatorImage(version, architecture, options.signal);
198
114
  throwIfAborted(options.signal);
199
115
  const containerName = `awesome-emulator-cli-${process.pid}-${randomBytes(4).toString("hex")}`;
200
- const hostUser = process.platform === "linux"
201
- && typeof process.getuid === "function"
202
- && typeof process.getgid === "function"
203
- ? ["--user", `${process.getuid()}:${process.getgid()}`]
204
- : [];
205
- const runningContainerId = await startContainer(containerName, [
206
- "run", "--detach",
207
- "--platform", `linux/${architecture.docker}`,
208
- ...hostUser,
209
- "--memory", memory,
210
- "--memory-swap", memory,
211
- "--publish", `127.0.0.1:${port}:${port}`,
212
- "--mount", `type=bind,source=${stateDirectory},target=/home/emulator/.aws/emulator`,
213
- "--env", "HOME=/home/emulator",
214
- "--name", containerName,
116
+ const runArguments = createContainerRunArguments({
117
+ architecture,
118
+ containerName,
215
119
  image,
216
- "-p", String(port),
217
- "-t", telemetry,
218
- ], options.signal, (id, signal) => waitUntilHealthy(id, port, stateDirectory, startupTimeoutMs, signal));
120
+ memory,
121
+ port,
122
+ stateDirectory,
123
+ telemetry,
124
+ });
125
+ const runningContainerId = await startContainer(containerName, runArguments, options.signal, (id, signal) => waitUntilHealthy(id, port, stateDirectory, startupTimeoutMs, signal));
219
126
  const stop = createRetryableStop(() => stopContainer(runningContainerId));
220
127
  try {
221
128
  throwIfAborted(options.signal);
@@ -229,27 +136,11 @@ export async function startEmulator(options = {}) {
229
136
  }
230
137
  throw startupError;
231
138
  }
232
- const endpointUrl = `https://127.0.0.1:${port}`;
233
- const portDirectory = path.join(stateDirectory, String(port));
234
- const environment = {
235
- AWS_ENDPOINT_URL: endpointUrl,
236
- AWS_SHARED_CREDENTIALS_FILE: path.join(portDirectory, "emulator_credentials"),
237
- AWS_CONFIG_FILE: path.join(portDirectory, "config"),
238
- AWS_CA_BUNDLE: path.join(portDirectory, "ca.pem"),
239
- AWS_EC2_METADATA_DISABLED: "true",
240
- AWS_REGION: "us-east-1",
241
- AWS_DEFAULT_REGION: "us-east-1",
242
- NODE_EXTRA_CA_CERTS: path.join(portDirectory, "ca.pem"),
243
- };
139
+ const connectionSettings = createEmulatorConnectionSettings(port, stateDirectory);
244
140
  return {
245
141
  version,
246
142
  port,
247
- endpointUrl,
248
- healthCheckUrl: `${endpointUrl}/__admin/health`,
249
- configFile: environment.AWS_CONFIG_FILE,
250
- credentialsFile: environment.AWS_SHARED_CREDENTIALS_FILE,
251
- caFile: environment.AWS_CA_BUNDLE,
252
- environment,
143
+ ...connectionSettings,
253
144
  containerId: runningContainerId,
254
145
  stop,
255
146
  };
@@ -260,28 +151,9 @@ export async function startEmulator(options = {}) {
260
151
  export async function runWithEmulator(command, args = [], options = {}) {
261
152
  if (!command)
262
153
  throw new Error("A command is required.");
263
- return withEmulator(() => startEmulator(options), async (emulator) => {
264
- const childEnvironment = { ...process.env, ...emulator.environment };
265
- for (const key of [
266
- "AWS_ACCESS_KEY_ID",
267
- "AWS_SECRET_ACCESS_KEY",
268
- "AWS_SESSION_TOKEN",
269
- "AWS_PROFILE",
270
- "AWS_DEFAULT_PROFILE",
271
- "AWS_ROLE_ARN",
272
- "AWS_WEB_IDENTITY_TOKEN_FILE",
273
- "AWS_CONTAINER_CREDENTIALS_FULL_URI",
274
- "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",
275
- "AWS_CONTAINER_AUTHORIZATION_TOKEN",
276
- "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE",
277
- "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS",
278
- ]) {
279
- delete childEnvironment[key];
280
- }
281
- for (const key of Object.keys(childEnvironment)) {
282
- if (key.startsWith("AWS_ENDPOINT_URL_"))
283
- delete childEnvironment[key];
284
- }
285
- return runCommand(command, args, childEnvironment, options.signal);
154
+ const { shell = false, ...emulatorOptions } = options;
155
+ return withEmulator(() => startEmulator(emulatorOptions), async (emulator) => {
156
+ const childEnvironment = createChildEnvironment(process.env, emulator.environment);
157
+ return runCommand(command, args, childEnvironment, emulatorOptions.signal, shell);
286
158
  });
287
159
  }
package/dist/process.d.ts CHANGED
@@ -1 +1 @@
1
- export declare function runCommand(command: string, args: string[], env: NodeJS.ProcessEnv, signal?: AbortSignal): Promise<number>;
1
+ export declare function runCommand(command: string, args: string[], env: NodeJS.ProcessEnv, signal?: AbortSignal, shell?: boolean): Promise<number>;
package/dist/process.js CHANGED
@@ -1,15 +1,11 @@
1
1
  import { spawn } from "node:child_process";
2
- const signalExitCodes = {
3
- SIGHUP: 129,
4
- SIGINT: 130,
5
- SIGTERM: 143,
6
- };
7
- export function runCommand(command, args, env, signal) {
2
+ import { FORWARDED_SIGNALS, getSignalExitCode, isForwardedSignal } from "./signals.js";
3
+ export function runCommand(command, args, env, signal, shell = false) {
8
4
  return new Promise((resolve, reject) => {
9
5
  const child = spawn(command, args, {
10
6
  env,
11
7
  stdio: "inherit",
12
- shell: process.platform === "win32",
8
+ shell,
13
9
  windowsHide: false,
14
10
  });
15
11
  let receivedSignal;
@@ -28,7 +24,7 @@ export function runCommand(command, args, env, signal) {
28
24
  receivedSignal = signal;
29
25
  child.kill(signal);
30
26
  };
31
- for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
27
+ for (const signal of FORWARDED_SIGNALS) {
32
28
  const handler = () => forwardSignal(signal);
33
29
  handlers.set(signal, handler);
34
30
  process.once(signal, handler);
@@ -36,7 +32,7 @@ export function runCommand(command, args, env, signal) {
36
32
  if (signal) {
37
33
  abortHandler = () => {
38
34
  const reason = signal.reason;
39
- const abortSignal = reason === "SIGINT" || reason === "SIGTERM" || reason === "SIGHUP" ? reason : "SIGTERM";
35
+ const abortSignal = isForwardedSignal(reason) ? reason : "SIGTERM";
40
36
  forwardSignal(abortSignal);
41
37
  };
42
38
  if (signal.aborted)
@@ -57,7 +53,7 @@ export function runCommand(command, args, env, signal) {
57
53
  settled = true;
58
54
  cleanup();
59
55
  if (receivedSignal) {
60
- resolve(signalExitCodes[receivedSignal] ?? 1);
56
+ resolve(getSignalExitCode(receivedSignal));
61
57
  }
62
58
  else if (signal) {
63
59
  resolve(1);
@@ -0,0 +1,4 @@
1
+ export declare const FORWARDED_SIGNALS: readonly ["SIGINT", "SIGTERM", "SIGHUP"];
2
+ export type ForwardedSignal = (typeof FORWARDED_SIGNALS)[number];
3
+ export declare function isForwardedSignal(value: unknown): value is ForwardedSignal;
4
+ export declare function getSignalExitCode(value: unknown): number;
@@ -0,0 +1,12 @@
1
+ export const FORWARDED_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
2
+ const SIGNAL_EXIT_CODES = {
3
+ SIGHUP: 129,
4
+ SIGINT: 130,
5
+ SIGTERM: 143,
6
+ };
7
+ export function isForwardedSignal(value) {
8
+ return typeof value === "string" && Object.hasOwn(SIGNAL_EXIT_CODES, value);
9
+ }
10
+ export function getSignalExitCode(value) {
11
+ return isForwardedSignal(value) ? SIGNAL_EXIT_CODES[value] : 1;
12
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "awesome-emulator-cli",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Awesome Emulator CLI for use with AWS Emulator in local tests from npm scripts or Node.js. It runs the upstream Linux package in Docker.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -51,7 +51,7 @@
51
51
  "access": "public"
52
52
  },
53
53
  "devDependencies": {
54
- "@types/node": "^20.19.43",
55
- "typescript": "^5.9.3"
54
+ "@types/node": "^26.6.6",
55
+ "typescript": "^7.0.2"
56
56
  }
57
57
  }