@aws-blocks/core 0.1.3 → 0.1.7

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.
Files changed (66) hide show
  1. package/dist/cdk/index.d.ts +1 -1
  2. package/dist/cdk/index.d.ts.map +1 -1
  3. package/dist/cdk/index.js +1 -1
  4. package/dist/client/index.d.ts +1 -1
  5. package/dist/client/index.d.ts.map +1 -1
  6. package/dist/client/index.js +1 -1
  7. package/dist/constants.d.ts +12 -0
  8. package/dist/constants.d.ts.map +1 -1
  9. package/dist/constants.js +12 -0
  10. package/dist/errors.d.ts +28 -0
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/errors.js +27 -1
  13. package/dist/errors.test.d.ts +2 -0
  14. package/dist/errors.test.d.ts.map +1 -0
  15. package/dist/errors.test.js +47 -0
  16. package/dist/hosting.d.ts +22 -1
  17. package/dist/hosting.d.ts.map +1 -1
  18. package/dist/index.cdk.d.ts +1 -1
  19. package/dist/index.cdk.d.ts.map +1 -1
  20. package/dist/index.cdk.js +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +1 -1
  24. package/dist/scripts/dev-server-config.test.d.ts +2 -0
  25. package/dist/scripts/dev-server-config.test.d.ts.map +1 -0
  26. package/dist/scripts/dev-server-config.test.js +37 -0
  27. package/dist/scripts/dev-server-supervisor.test.d.ts +2 -0
  28. package/dist/scripts/dev-server-supervisor.test.d.ts.map +1 -0
  29. package/dist/scripts/dev-server-supervisor.test.js +551 -0
  30. package/dist/scripts/dev-server.d.ts +92 -0
  31. package/dist/scripts/dev-server.d.ts.map +1 -1
  32. package/dist/scripts/dev-server.js +317 -34
  33. package/dist/scripts/index.d.ts +1 -0
  34. package/dist/scripts/index.d.ts.map +1 -1
  35. package/dist/scripts/index.js +1 -0
  36. package/dist/scripts/process-tree.d.ts +126 -0
  37. package/dist/scripts/process-tree.d.ts.map +1 -0
  38. package/dist/scripts/process-tree.js +198 -0
  39. package/dist/scripts/sandbox.d.ts.map +1 -1
  40. package/dist/scripts/sandbox.js +41 -3
  41. package/dist/scripts/stack-id.d.ts +12 -0
  42. package/dist/scripts/stack-id.d.ts.map +1 -0
  43. package/dist/scripts/stack-id.js +54 -0
  44. package/dist/scripts/stack-id.test.d.ts +2 -0
  45. package/dist/scripts/stack-id.test.d.ts.map +1 -0
  46. package/dist/scripts/stack-id.test.js +54 -0
  47. package/dist/version.d.ts +1 -1
  48. package/dist/version.js +1 -1
  49. package/package.json +1 -1
  50. package/src/cdk/index.ts +1 -1
  51. package/src/client/index.ts +1 -1
  52. package/src/constants.ts +13 -0
  53. package/src/errors.test.ts +55 -0
  54. package/src/errors.ts +32 -1
  55. package/src/hosting.ts +22 -1
  56. package/src/index.cdk.ts +1 -1
  57. package/src/index.ts +1 -1
  58. package/src/scripts/dev-server-config.test.ts +43 -0
  59. package/src/scripts/dev-server-supervisor.test.ts +621 -0
  60. package/src/scripts/dev-server.ts +364 -33
  61. package/src/scripts/index.ts +1 -0
  62. package/src/scripts/process-tree.ts +245 -0
  63. package/src/scripts/sandbox.ts +40 -3
  64. package/src/scripts/stack-id.test.ts +63 -0
  65. package/src/scripts/stack-id.ts +61 -0
  66. package/src/version.ts +1 -1
@@ -0,0 +1,245 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { spawnSync } from 'node:child_process';
5
+
6
+ // Shared process-tree teardown primitives used by every dev-tooling entrypoint
7
+ // (the dev server and the sandbox). Both spawn a long-running command with
8
+ // `shell: true`, so the real process (Vite, or the `tsx watch` dev server) is a
9
+ // grandchild of the shell. Reaping it requires killing the whole tree, not just
10
+ // the shell parent — see the per-function docs. Keeping this in one module means
11
+ // the dev server, the sandbox, and the `process.on('exit')` safety net all reap
12
+ // identically instead of hand-rolling divergent copies.
13
+
14
+ /** Minimal child-process surface needed to terminate a frontend dev server. */
15
+ export interface KillableProcess {
16
+ pid?: number;
17
+ kill(signal?: NodeJS.Signals | number): boolean;
18
+ }
19
+
20
+ /** Subset of {@link import('node:child_process').SpawnSyncReturns} that {@link windowsTreeKill} inspects. */
21
+ interface TreeKillResult {
22
+ status: number | null;
23
+ error?: Error;
24
+ }
25
+
26
+ /**
27
+ * Force-kill an entire process tree on Windows via `taskkill /T /F /PID <pid>`.
28
+ *
29
+ * Windows has no POSIX process groups, so a bare `child.kill()` only signals the
30
+ * spawned shell and orphans the real dev server (the Vite grandchild), which
31
+ * keeps holding `:3100` — the very wedge the POSIX process-group kill fixes.
32
+ * `taskkill /T` walks the live child tree by PID and terminates every
33
+ * descendant; `/F` is required because Windows cannot deliver a graceful
34
+ * shutdown to a non-console subtree anyway (Node maps SIGTERM/SIGKILL to
35
+ * `TerminateProcess`).
36
+ *
37
+ * Returns `true` only when `taskkill` ran AND reported the tree handled — exit
38
+ * `0` (reaped the tree) or `128` (`"process not found"`, i.e. already gone).
39
+ * Returns `false` when the command could not be spawned at all (e.g. not on
40
+ * `PATH`) OR when it ran but returned any other status (e.g. `1` = access
41
+ * denied): such a run did NOT reap the tree, so the caller must fall back to a
42
+ * direct `child.kill` rather than treat the leak as handled. (`child.kill`
43
+ * cannot reap the orphaned grandchild either, but the fallback is cheap and
44
+ * strictly correct — we never silently swallow a failed tree-kill.) Never
45
+ * throws.
46
+ */
47
+ export function windowsTreeKill(
48
+ pid: number,
49
+ runner: (command: string, args: readonly string[]) => TreeKillResult = (command, args) =>
50
+ spawnSync(command, args as string[], { stdio: 'ignore', windowsHide: true }),
51
+ ): boolean {
52
+ try {
53
+ const { status, error } = runner('taskkill', ['/T', '/F', '/PID', String(pid)]);
54
+ // Couldn't even spawn taskkill (e.g. not on PATH) → not handled; fall back.
55
+ if (error) return false;
56
+ // taskkill ran: only exit 0 (reaped the tree) or 128 ("process not found",
57
+ // already gone) mean the tree is handled. Any other non-null status (e.g.
58
+ // 1 = access denied) means taskkill ran but did NOT reap the tree, so report
59
+ // not-handled and let the caller fall back to a direct child.kill.
60
+ return status === 0 || status === 128;
61
+ } catch {
62
+ return false;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Terminate a process spawned with `shell: true`, including its descendants, on
68
+ * every platform.
69
+ *
70
+ * Under a shell the real dev server (e.g. Vite) is a **grandchild**: the direct
71
+ * child is the shell, so signalling only the shell (`child.kill`) orphans the
72
+ * grandchild, which keeps holding its port (`:3100`) and wedges the next
73
+ * restart.
74
+ *
75
+ * - **POSIX**: the process is spawned `detached` (its own process group,
76
+ * pgid === child.pid), so we signal the whole group with
77
+ * `process.kill(-pid, signal)` and every descendant dies, freeing the port.
78
+ * - **Windows**: there are no process groups, so we reap the tree with
79
+ * `taskkill /T /F /PID <pid>` (see {@link windowsTreeKill}), which walks the
80
+ * child tree by PID. A bare `child.kill` would leave the Vite grandchild
81
+ * bound to `:3100`, reproducing the POSIX wedge.
82
+ *
83
+ * Best-effort and never throws: a missing/invalid pid, an already-dead group
84
+ * (ESRCH), a failed group signal, or an unavailable `taskkill` all degrade to a
85
+ * direct `child.kill`.
86
+ */
87
+ export function killFrontendTree(
88
+ child: KillableProcess,
89
+ signal: NodeJS.Signals = 'SIGTERM',
90
+ platform: NodeJS.Platform = process.platform,
91
+ killFn: (pid: number, signal: NodeJS.Signals) => void = (p, s) => process.kill(p, s),
92
+ winTreeKill: (pid: number) => boolean = windowsTreeKill,
93
+ ): void {
94
+ const { pid } = child;
95
+ // pid > 1 guards against signalling the whole current group (-0) or init (-1).
96
+ if (pid && pid > 1) {
97
+ if (platform !== 'win32') {
98
+ try {
99
+ killFn(-pid, signal);
100
+ return;
101
+ } catch {
102
+ // Group already gone or signal failed — fall through to a direct kill.
103
+ }
104
+ } else if (winTreeKill(pid)) {
105
+ // taskkill walked the PID tree and reaped the Vite grandchild.
106
+ return;
107
+ }
108
+ }
109
+ try {
110
+ child.kill(signal);
111
+ } catch {
112
+ // Process already exited; nothing to do.
113
+ }
114
+ }
115
+
116
+ /** Child surface {@link terminateProcessTree} needs: a tree to kill plus exit state to await. */
117
+ export interface AwaitableChild extends KillableProcess {
118
+ exitCode: number | null;
119
+ signalCode: NodeJS.Signals | null;
120
+ once(event: 'exit', listener: () => void): unknown;
121
+ }
122
+
123
+ const defaultSleep = (ms: number): Promise<void> =>
124
+ new Promise((res) => {
125
+ setTimeout(res, ms).unref?.();
126
+ });
127
+
128
+ /**
129
+ * Grace (ms) we wait for the child's `exit` event *after* SIGKILL before giving
130
+ * up and reporting its last-known exit state. Deliberately shorter than — and
131
+ * intentionally decoupled from — the injectable SIGTERM `graceMs`: SIGKILL
132
+ * cannot be caught, blocked, or handled, so the child is already being
133
+ * force-terminated; we only need a brief beat to observe the `exit` event, not a
134
+ * full, tunable shutdown window. Fixed (not a parameter) because no caller needs
135
+ * to tune it — the injected `sleep` is the test seam.
136
+ */
137
+ export const KILL_GRACE_MS = 500;
138
+
139
+ /**
140
+ * Probe whether a detached process *group* still has at least one live member,
141
+ * **without signalling it**. Used to scope the post-exit group SIGKILL in
142
+ * {@link terminateProcessTree} to the only window where the `-pid` group signal
143
+ * is PID-reuse-safe.
144
+ *
145
+ * The hazard: {@link killFrontendTree}'s POSIX reap is `process.kill(-pid, …)`,
146
+ * which targets the process group whose gid is `pid`. That is safe only while a
147
+ * group member is still alive — a survivor keeps the kernel from recycling
148
+ * `pid` as a brand-new (unrelated) group leader. Once the whole group has
149
+ * drained, `pid` is eligible for reuse and a blind `-pid` kill could land on an
150
+ * unrelated group. So before a *post-exit* reap we probe here and skip when the
151
+ * group has already drained (there is then nothing of ours left to reap).
152
+ *
153
+ * - **POSIX**: `kill(-pid, 0)` sends no signal — it only checks the group
154
+ * exists and is signallable. Success or `EPERM` (exists but owned by another
155
+ * user) ⇒ alive. `ESRCH` (or anything else) ⇒ treat as drained.
156
+ * - **Windows**: there are no process groups and the reap path
157
+ * (`taskkill /T /F /PID`) walks the live PID tree, so there is no `-pid`
158
+ * recycle hazard — always allow the reap (`true`).
159
+ *
160
+ * Never throws. `platform`/`kill` are injected for tests.
161
+ */
162
+ export function isProcessGroupAlive(
163
+ pid: number,
164
+ platform: NodeJS.Platform = process.platform,
165
+ kill: (pid: number, signal: number) => void = (p, s) => process.kill(p, s),
166
+ ): boolean {
167
+ if (platform === 'win32') return true;
168
+ try {
169
+ kill(-pid, 0);
170
+ return true;
171
+ } catch (e) {
172
+ return (e as NodeJS.ErrnoException).code === 'EPERM';
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Terminate a child process *tree* and wait — bounded — for the child to exit,
178
+ * escalating SIGTERM → SIGKILL. Reuses {@link killFrontendTree} so every
179
+ * entrypoint reaps the same way (POSIX process-group kill / Windows `taskkill`)
180
+ * instead of hand-rolling its own group kill.
181
+ *
182
+ * Post-exit policy: if the child has *already* exited, a detached grandchild may
183
+ * still be orphaned (still holding a port), so we issue one best-effort group
184
+ * SIGKILL to reap it — but ONLY when the group still has a live member
185
+ * ({@link isProcessGroupAlive}). When the whole group has already drained (the
186
+ * common healthy shutdown — Vite was already gone), `pid` is eligible for
187
+ * recycling and a blind `-pid` signal could hit an unrelated, newly created
188
+ * group; since there is also nothing of ours left to reap, we skip the kill.
189
+ * See the dev server's "POST-EXIT GROUP-KILL POLICY" for the full rationale and
190
+ * the accepted residual (the synchronous probe→kill window). Otherwise we
191
+ * SIGTERM the tree, wait up to `graceMs` for a clean exit, then SIGKILL the tree
192
+ * and wait a short grace.
193
+ *
194
+ * Return value — IMPORTANT: the boolean reflects only the **direct child's**
195
+ * exit state (its `exitCode`/`signalCode`), NOT whole-group teardown or port
196
+ * release. On POSIX the SIGKILL is delivered to the whole group (`-pid`), but a
197
+ * surviving *detached grandchild* can outlive the awaited child and keep holding
198
+ * a port even after this resolves `true`. So `true` means only "the child we
199
+ * awaited has exited (or was already gone)" and `false` means "it was still
200
+ * alive when the budget elapsed" — neither guarantees the port is free. Callers
201
+ * that need a freed port MUST follow this with a bounded port-free wait (see
202
+ * `waitForPortFree` in dev-server.ts, which the dev-server child's own SIGTERM
203
+ * handler runs). Dependencies are injected for tests.
204
+ */
205
+ export async function terminateProcessTree(
206
+ child: AwaitableChild,
207
+ graceMs = 2000,
208
+ killTree: (c: KillableProcess, signal: NodeJS.Signals) => void = killFrontendTree,
209
+ sleep: (ms: number) => Promise<void> = defaultSleep,
210
+ isGroupAlive: (pid: number) => boolean = isProcessGroupAlive,
211
+ ): Promise<boolean> {
212
+ if (child.exitCode !== null || child.signalCode !== null) {
213
+ // ── POST-EXIT GROUP-KILL (scoped) ──────────────────────────────────────
214
+ // The direct child has already exited, but a detached *grandchild* (e.g. an
215
+ // orphaned Vite) may still be alive in its process group, still holding a
216
+ // port — reap it with one best-effort group SIGKILL.
217
+ //
218
+ // SCOPING: only reap when the group still has a live member. killFrontendTree's
219
+ // `-pid` group signal is PID-reuse-safe ONLY while a member keeps `pid`
220
+ // reserved as the group id; once the whole group has drained `pid` can be
221
+ // recycled and a blind `process.kill(-pid)` could hit an unrelated group. So
222
+ // we probe first (isProcessGroupAlive; POSIX signal 0) and skip when already
223
+ // drained — there is then nothing of ours to reap. The residual synchronous
224
+ // probe→kill window is the accepted trade-off documented in dev-server.ts
225
+ // "POST-EXIT GROUP-KILL POLICY", cross-referenced here so the risk is
226
+ // discoverable at this shared primitive.
227
+ const { pid } = child;
228
+ if (pid && pid > 1 && isGroupAlive(pid)) {
229
+ killTree(child, 'SIGKILL');
230
+ }
231
+ return true;
232
+ }
233
+ const exited = new Promise<void>((res) => child.once('exit', () => res()));
234
+ killTree(child, 'SIGTERM');
235
+ const exitedCleanly = await Promise.race([
236
+ exited.then(() => true),
237
+ sleep(graceMs).then(() => false),
238
+ ]);
239
+ if (exitedCleanly) return true;
240
+ killTree(child, 'SIGKILL');
241
+ // Shorter, fixed grace after SIGKILL (vs. the injectable SIGTERM graceMs):
242
+ // SIGKILL is uncatchable, so we only need a brief beat to observe `exit`.
243
+ await Promise.race([exited, sleep(KILL_GRACE_MS)]);
244
+ return child.exitCode !== null || child.signalCode !== null;
245
+ }
@@ -11,6 +11,7 @@ import { trackCommand } from '../telemetry/trackCommand.js';
11
11
  import { buildAndSendEvent } from '../telemetry/client.js';
12
12
  import { getCdkTelemetryEnv } from './cdk-telemetry-env.js';
13
13
  import { runSync, spawnCommand } from './run-command.js';
14
+ import { terminateProcessTree } from './process-tree.js';
14
15
 
15
16
  /**
16
17
  * Import the backend definition to populate the Scope BB registry.
@@ -147,6 +148,12 @@ export async function startSandbox(options: SandboxOptions) {
147
148
  `--app`, `npm exec tsx -- -C cdk ${backendPath}`
148
149
  ], {
149
150
  stdio: ["ignore", "pipe", "pipe"],
151
+ // Own process group on POSIX so cleanup can reap the whole `cdk watch` tree
152
+ // (npx → cdk → node) via terminateProcessTree, not just the npx shell — a
153
+ // bare kill() would orphan the real cdk-watch node process, the same
154
+ // shell-only-kill leak this PR eliminates for the dev server. Windows has no
155
+ // groups; terminateProcessTree reaps the tree via taskkill.
156
+ detached: process.platform !== 'win32',
150
157
  env: { ...process.env, NODE_OPTIONS: "--conditions=cdk", ...getCdkTelemetryEnv('sandbox') },
151
158
  });
152
159
 
@@ -166,6 +173,12 @@ export async function startSandbox(options: SandboxOptions) {
166
173
  const devServer = spawnCommand(cmd, args, {
167
174
  stdio: "inherit",
168
175
  shell: true,
176
+ // Own process group on POSIX so cleanup can signal the whole dev-server
177
+ // tree (shell → tsx → node). The node dev server then runs its own SIGTERM
178
+ // handler — the ~2s terminateFrontend drain that reaps the *detached* Vite
179
+ // great-grandchild — which a bare `devServer.kill()` (the shell only) never
180
+ // triggers. Windows has no groups; terminateProcessTree reaps via taskkill.
181
+ detached: process.platform !== 'win32',
169
182
  env: {
170
183
  ...process.env,
171
184
  NODE_OPTIONS: '',
@@ -173,12 +186,36 @@ export async function startSandbox(options: SandboxOptions) {
173
186
  },
174
187
  });
175
188
 
176
- const cleanup = () => {
189
+ let cleaningUp = false;
190
+ const cleanup = async () => {
191
+ if (cleaningUp) return; // idempotent — a second signal must not re-enter
192
+ cleaningUp = true;
177
193
  console.log("\n\n🛑 Stopping local processes...");
178
194
  console.log(" (AWS resources are still running)");
179
195
  console.log("\n To destroy AWS resources, run: npm run sandbox:destroy\n");
180
- cdkWatch.kill();
181
- devServer.kill();
196
+ // Reap BOTH child trees the way the dev server reaps Vite — a process-group
197
+ // SIGTERM→SIGKILL via the shared terminateProcessTree — instead of a bare
198
+ // kill() that signals only the npx/shell parent and orphans the real
199
+ // grandchild (cdk-watch's node, or the dev server's detached Vite). Run them
200
+ // concurrently so the cdk-watch teardown doesn't serialize on top of the dev
201
+ // server's longer drain.
202
+ //
203
+ // Only the dev-server child owns the `:3100` port-free wait: its own SIGTERM
204
+ // handler runs terminateFrontend (a ~2s drain that reaps the detached Vite
205
+ // great-grandchild AND polls until the port frees), so we give it the longer
206
+ // 6s budget (> that ~2s drain) — a hung dev server still escalates to a tree
207
+ // SIGKILL and we exit regardless, so shutdown can never wedge. cdk watch
208
+ // holds no local port, so a bounded tree-kill is all it needs.
209
+ //
210
+ // That a group SIGTERM (terminateProcessTree → killFrontendTree's
211
+ // `process.kill(-pid, 'SIGTERM')`) actually reaches the *nested* node dev
212
+ // server and runs its own SIGTERM handler — the load-bearing assumption of
213
+ // the 6s budget above — is verified by the "group SIGTERM reaches a nested
214
+ // node child" integration test in dev-server-supervisor.test.ts.
215
+ await Promise.all([
216
+ terminateProcessTree(cdkWatch, 2000),
217
+ terminateProcessTree(devServer, 6000),
218
+ ]);
182
219
  process.exit(0);
183
220
  };
184
221
 
@@ -0,0 +1,63 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { describe, it, afterEach } from 'node:test';
5
+ import assert from 'node:assert';
6
+ import { mkdirSync, writeFileSync, rmSync, readFileSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { tmpdir } from 'node:os';
9
+
10
+ import { getStackId, getSandboxId } from './stack-id.js';
11
+
12
+ describe('getStackId', () => {
13
+ let tmpDir: string;
14
+
15
+ afterEach(() => {
16
+ if (tmpDir) rmSync(tmpDir, { recursive: true, force: true });
17
+ });
18
+
19
+ it('reads stackId from .blocks/config.json', () => {
20
+ tmpDir = join(tmpdir(), `stack-id-test-${Date.now()}`);
21
+ mkdirSync(join(tmpDir, '.blocks'), { recursive: true });
22
+ writeFileSync(join(tmpDir, '.blocks', 'config.json'), JSON.stringify({ stackId: 'test-abc123' }));
23
+ assert.strictEqual(getStackId(tmpDir), 'test-abc123');
24
+ });
25
+
26
+ it('throws actionable error when config is missing', () => {
27
+ tmpDir = join(tmpdir(), `stack-id-test-missing-${Date.now()}`);
28
+ mkdirSync(tmpDir, { recursive: true });
29
+ assert.throws(() => getStackId(tmpDir), /\.blocks\/config\.json not found/);
30
+ });
31
+
32
+ it('throws actionable error when stackId key is missing', () => {
33
+ tmpDir = join(tmpdir(), `stack-id-test-nokey-${Date.now()}`);
34
+ mkdirSync(join(tmpDir, '.blocks'), { recursive: true });
35
+ writeFileSync(join(tmpDir, '.blocks', 'config.json'), JSON.stringify({ other: 'value' }));
36
+ assert.throws(() => getStackId(tmpDir), /\.blocks\/config\.json not found/);
37
+ });
38
+ });
39
+
40
+ describe('getSandboxId', () => {
41
+ let tmpDir: string;
42
+
43
+ afterEach(() => {
44
+ if (tmpDir) rmSync(tmpDir, { recursive: true, force: true });
45
+ });
46
+
47
+ it('generates and persists a sandbox id', () => {
48
+ tmpDir = join(tmpdir(), `sandbox-id-test-${Date.now()}`);
49
+ mkdirSync(tmpDir, { recursive: true });
50
+ const id = getSandboxId(tmpDir);
51
+ assert.match(id, /^[a-z0-9]+-[a-f0-9]{6}$/);
52
+ // Verify persisted
53
+ const stored = readFileSync(join(tmpDir, '.blocks-sandbox', 'sandbox-id.txt'), 'utf-8').trim();
54
+ assert.strictEqual(stored, id);
55
+ });
56
+
57
+ it('returns existing id on subsequent calls', () => {
58
+ tmpDir = join(tmpdir(), `sandbox-id-test-idem-${Date.now()}`);
59
+ mkdirSync(join(tmpDir, '.blocks-sandbox'), { recursive: true });
60
+ writeFileSync(join(tmpDir, '.blocks-sandbox', 'sandbox-id.txt'), 'alice-abc123');
61
+ assert.strictEqual(getSandboxId(tmpDir), 'alice-abc123');
62
+ });
63
+ });
@@ -0,0 +1,61 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
5
+ import { join, dirname } from 'node:path';
6
+ import { execSync } from 'node:child_process';
7
+ import { randomBytes } from 'node:crypto';
8
+
9
+ interface BlocksConfig {
10
+ stackId?: string;
11
+ [key: string]: unknown;
12
+ }
13
+
14
+ function randomSuffix(length: number): string {
15
+ return randomBytes(length).toString('hex').slice(0, length);
16
+ }
17
+
18
+ /**
19
+ * Get the stackId from `.blocks/config.json` in the project root.
20
+ * This is the stable project identifier used as the base for CloudFormation stack names.
21
+ */
22
+ export function getStackId(projectRoot?: string): string {
23
+ const root = projectRoot || process.cwd();
24
+ const configPath = join(root, '.blocks', 'config.json');
25
+ try {
26
+ const config: BlocksConfig = JSON.parse(readFileSync(configPath, 'utf-8'));
27
+ if (!config.stackId) throw new Error('missing key');
28
+ return config.stackId;
29
+ } catch {
30
+ throw new Error(
31
+ `.blocks/config.json not found or missing stackId — it is created by create-blocks-app and should be committed. ` +
32
+ `To fix manually, create ${configPath} with: { "stackId": "<your-app-name>" }`
33
+ );
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Get or create a per-machine sandbox identifier.
39
+ * Stored in `.blocks-sandbox/sandbox-id.txt` (gitignored).
40
+ * Format: `<username(8)>-<random(6)>` — identifies the developer's sandbox.
41
+ */
42
+ export function getSandboxId(projectRoot?: string): string {
43
+ const root = projectRoot || process.cwd();
44
+ const filePath = join(root, '.blocks-sandbox', 'sandbox-id.txt');
45
+ if (existsSync(filePath)) return readFileSync(filePath, 'utf-8').trim();
46
+ const dir = dirname(filePath);
47
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
48
+ const username = getUsername().toLowerCase().replace(/[^a-z0-9]/g, '').slice(0, 8) || 'dev';
49
+ const random = randomSuffix(6);
50
+ const id = `${username}-${random}`;
51
+ writeFileSync(filePath, id);
52
+ return id;
53
+ }
54
+
55
+ function getUsername(): string {
56
+ try {
57
+ return execSync('git config user.name', { encoding: 'utf-8' }).trim();
58
+ } catch {
59
+ return process.env.USER || process.env.USERNAME || 'user';
60
+ }
61
+ }
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  // Auto-generated by scripts/generate-version.mjs — do not edit manually
2
- export const CORE_VERSION = '0.1.3';
2
+ export const CORE_VERSION = '0.1.7';