mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 11:29:54 +00:00
* fix(cli): one trusted PATH rule for the engine and CLI; say why a project copy was skipped The Windows PATH rules (quoted entries, the %SystemRoot% folders) now live in the parsers' trustedPathDirs, so engine helper lookups and the CLI's PATH rewrite apply the same rule. When sam, aws, gcloud, docker, git or npx is not found but a copy sits in a project folder the rule skipped, the message names that copy by its path relative to the project and says why it was not used. cloudrun now reports a missing gcloud or docker as not found instead of "exited with null". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * test(cli): join a simulated Windows PATH with the Windows separator The shared trusted-folder rule now splits PATH on ';' whenever the platform is win32, as Windows does. Two tests that pretend to be Windows on Linux built PATH with ':', so the rule saw one folder instead of two. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(cli): name skipped copies above the working folder; pin Windows PATH to the shared rule The not-found hint now names any copy the trusted PATH rule skipped, relative to the working folder, including ../node_modules/.bin when an npm or pnpm script runs from a subfolder. A Windows test pins that quoted PATH entries still go through the shared rule, so the project root's and ancestors' node_modules/.bin stay skipped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * chore(cli): trim projectCopyHint comments to the package's comment share Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
247 lines
8.9 KiB
TypeScript
247 lines
8.9 KiB
TypeScript
/**
|
|
* Thin wrappers around the AWS SAM CLI used by `hyperframes lambda deploy`
|
|
* and `hyperframes lambda destroy`.
|
|
*
|
|
* We shell out instead of programmatically driving the CloudFormation API
|
|
* because:
|
|
* 1. SAM handles the rollback-on-failure semantics correctly, including
|
|
* stuck-rollback recovery. Re-implementing that in TypeScript would
|
|
* duplicate a non-trivial chunk of the SAM CLI.
|
|
* 2. The SAM template at `examples/aws-lambda/template.yaml` already
|
|
* describes the topology; adopters who customize the template
|
|
* shouldn't have to maintain it twice.
|
|
* 3. SAM's `--resolve-s3` auto-creates an artifact bucket for the
|
|
* handler ZIP upload, which we'd otherwise have to re-implement.
|
|
*
|
|
* CDK adopters use `HyperframesRenderStack` directly from their own
|
|
* CDK app — this CLI path is for users who don't want to write a CDK
|
|
* project.
|
|
*/
|
|
|
|
import { execFileSync, spawnSync } from "node:child_process";
|
|
import { existsSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { CliUsageError } from "../../utils/commandResult.js";
|
|
import { projectCopyHint } from "../../utils/projectCopyHint.js";
|
|
|
|
/** Throws with a clear hint when the SAM CLI is not on PATH. */
|
|
function assertSamAvailable(): void {
|
|
try {
|
|
execFileSync("sam", ["--version"], { stdio: "ignore" });
|
|
} catch {
|
|
throw new Error(
|
|
"`sam` CLI not found on PATH. Install AWS SAM CLI from https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html and retry." +
|
|
projectCopyHint("sam"),
|
|
);
|
|
}
|
|
}
|
|
|
|
/** Throws with a clear hint when the `aws` CLI is not on PATH. */
|
|
function assertAwsCliAvailable(): void {
|
|
try {
|
|
execFileSync("aws", ["--version"], { stdio: "ignore" });
|
|
} catch {
|
|
throw new Error(
|
|
"`aws` CLI not found on PATH. Install from https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html and configure credentials before retrying." +
|
|
projectCopyHint("aws"),
|
|
);
|
|
}
|
|
}
|
|
|
|
export interface DeployOptions {
|
|
/** Directory holding the `template.yaml` to deploy; SAM runs from here. */
|
|
samDir: string;
|
|
/** CloudFormation stack name. */
|
|
stackName: string;
|
|
region: string;
|
|
awsProfile?: string;
|
|
reservedConcurrency?: number;
|
|
/** Lambda memory in MB. Forwarded as the `LambdaMemoryMb` parameter override. */
|
|
lambdaMemoryMb?: number;
|
|
chromeSource?: "sparticuz" | "chrome-headless-shell";
|
|
/** ECR image for the arm64 video function; omitted, chunks render on the x86 function. */
|
|
videoImageUri?: string;
|
|
/** Pass-through stdio. Defaults to "inherit" so SAM's progress lines stream live. */
|
|
stdio?: "inherit" | "pipe";
|
|
}
|
|
|
|
/**
|
|
* Resolve the checkout's SAM template. Its `CodeUri` is relative to the monorepo; outside a
|
|
* checkout deploy uses the adapter's packaged template instead (see prebuiltHandler.ts).
|
|
*/
|
|
export function locateSamTemplate(repoRoot: string): string {
|
|
const candidate = join(repoRoot, "examples", "aws-lambda", "template.yaml");
|
|
if (!existsSync(candidate)) {
|
|
throw new Error(
|
|
`[lambda] SAM template not found at ${candidate}. ` +
|
|
"`hyperframes lambda deploy` needs a HyperFrames repo checkout: run it from one, " +
|
|
"or set HYPERFRAMES_REPO_ROOT to point at one.",
|
|
);
|
|
}
|
|
return candidate;
|
|
}
|
|
|
|
/** `--concurrency`: a positive integer, or `none` (-1, the template's "unreserved"). */
|
|
export function parseReservedConcurrency(raw: unknown): number | undefined {
|
|
if (raw === undefined || raw === null || raw === "") return undefined;
|
|
if (raw === "none") return -1;
|
|
const n = Number(raw);
|
|
if (!Number.isInteger(n) || n < 1) {
|
|
throw new CliUsageError(
|
|
`[lambda] --concurrency must be a positive integer or "none"; got ${String(raw)}`,
|
|
);
|
|
}
|
|
return n;
|
|
}
|
|
|
|
/** Run `sam deploy` non-interactively. Returns when SAM exits 0; throws on non-zero. */
|
|
export function samDeploy(opts: DeployOptions): void {
|
|
assertSamAvailable();
|
|
const paramOverrides = [
|
|
`ChromeSource=${opts.chromeSource ?? "sparticuz"}`,
|
|
// Always sent: omitted, SAM's UsePreviousValue would keep a video function the user dropped.
|
|
`VideoImageUri=${opts.videoImageUri ?? '""'}`,
|
|
];
|
|
// Omitted, SAM sends UsePreviousValue: a redeploy keeps the stack's reservation, a new stack gets -1.
|
|
if (opts.reservedConcurrency !== undefined) {
|
|
paramOverrides.push(`ReservedConcurrency=${opts.reservedConcurrency}`);
|
|
}
|
|
if (opts.lambdaMemoryMb !== undefined) {
|
|
paramOverrides.push(`LambdaMemoryMb=${opts.lambdaMemoryMb}`);
|
|
}
|
|
const args = [
|
|
"deploy",
|
|
"--stack-name",
|
|
opts.stackName,
|
|
"--region",
|
|
opts.region,
|
|
"--resolve-s3",
|
|
"--capabilities",
|
|
"CAPABILITY_IAM",
|
|
"--no-confirm-changeset",
|
|
"--no-fail-on-empty-changeset",
|
|
"--parameter-overrides",
|
|
...paramOverrides,
|
|
];
|
|
if (opts.awsProfile) {
|
|
args.push("--profile", opts.awsProfile);
|
|
}
|
|
const result = spawnSync("sam", args, { cwd: opts.samDir, stdio: opts.stdio ?? "inherit" });
|
|
if (result.status !== 0) {
|
|
throw new Error(
|
|
`[lambda] sam deploy exited with code ${result.status ?? "unknown"}\n` +
|
|
`If a prior attempt left a stack in ROLLBACK_COMPLETE, CloudFormation can't reuse it. ` +
|
|
`Delete it before retrying:\n` +
|
|
` aws cloudformation delete-stack --stack-name aws-sam-cli-managed-default --region ${opts.region}\n` +
|
|
` aws cloudformation delete-stack --stack-name ${opts.stackName} --region ${opts.region}\n` +
|
|
`(the first is SAM's managed artifacts stack from --resolve-s3; the second is the render stack).`,
|
|
);
|
|
}
|
|
}
|
|
|
|
/** Run `sam delete` non-interactively. */
|
|
export function samDelete(opts: {
|
|
samDir: string;
|
|
stackName: string;
|
|
region: string;
|
|
awsProfile?: string;
|
|
stdio?: "inherit" | "pipe";
|
|
}): void {
|
|
assertSamAvailable();
|
|
const args = ["delete", "--stack-name", opts.stackName, "--region", opts.region, "--no-prompts"];
|
|
if (opts.awsProfile) {
|
|
args.push("--profile", opts.awsProfile);
|
|
}
|
|
const result = spawnSync("sam", args, { cwd: opts.samDir, stdio: opts.stdio ?? "inherit" });
|
|
if (result.status !== 0) {
|
|
throw new Error(`[lambda] sam delete exited with code ${result.status ?? "unknown"}`);
|
|
}
|
|
}
|
|
|
|
export interface StackOutputBag {
|
|
bucketName: string;
|
|
functionName: string;
|
|
stateMachineArn: string;
|
|
reservedConcurrency?: number;
|
|
/** Present when the stack has the arm64 video function. */
|
|
videoFunctionName?: string;
|
|
}
|
|
|
|
/**
|
|
* Query CloudFormation for the stack outputs the SAM template exports.
|
|
* Used after `samDeploy` to populate the local state file.
|
|
*/
|
|
export function fetchStackOutputs(opts: {
|
|
stackName: string;
|
|
region: string;
|
|
awsProfile?: string;
|
|
}): StackOutputBag {
|
|
assertAwsCliAvailable();
|
|
const args = [
|
|
"cloudformation",
|
|
"describe-stacks",
|
|
"--stack-name",
|
|
opts.stackName,
|
|
"--region",
|
|
opts.region,
|
|
"--query",
|
|
"Stacks[0]",
|
|
"--output",
|
|
"json",
|
|
];
|
|
if (opts.awsProfile) {
|
|
args.unshift("--profile", opts.awsProfile);
|
|
}
|
|
const out = execFileSync("aws", args, { encoding: "utf-8" });
|
|
const stack = JSON.parse(out) as {
|
|
Outputs?: { OutputKey: string; OutputValue: string }[];
|
|
Parameters?: { ParameterKey: string; ParameterValue: string }[];
|
|
};
|
|
const byKey = new Map((stack.Outputs ?? []).map((o) => [o.OutputKey, o.OutputValue]));
|
|
const reserved = Number(
|
|
stack.Parameters?.find((p) => p.ParameterKey === "ReservedConcurrency")?.ParameterValue,
|
|
);
|
|
const bucketName = byKey.get("RenderBucketName");
|
|
const functionName = byKey.get("RenderFunctionArn");
|
|
const stateMachineArn = byKey.get("RenderStateMachineArn");
|
|
if (!bucketName || !functionName || !stateMachineArn) {
|
|
throw new Error(
|
|
`[lambda] stack ${opts.stackName} is missing one of RenderBucketName/RenderFunctionArn/RenderStateMachineArn. Got keys: ${[...byKey.keys()].join(", ")}`,
|
|
);
|
|
}
|
|
return {
|
|
bucketName,
|
|
// RenderFunctionArn is the full ARN; the Lambda function name is the
|
|
// last colon-segment, which downstream `getRenderProgress` calls use
|
|
// for cost math + CloudWatch lookups.
|
|
functionName: functionName.split(":").pop() ?? functionName,
|
|
stateMachineArn,
|
|
reservedConcurrency: reserved > 0 ? reserved : undefined,
|
|
videoFunctionName: byKey.get("VideoFunctionArn")?.split(":").pop(),
|
|
};
|
|
}
|
|
|
|
/** Delete an ECR repository and its images; one that is already gone counts as deleted. */
|
|
export function deleteEcrRepository(opts: {
|
|
repositoryName: string;
|
|
region: string;
|
|
awsProfile?: string;
|
|
}): void {
|
|
assertAwsCliAvailable();
|
|
const args = [
|
|
"ecr",
|
|
"delete-repository",
|
|
"--repository-name",
|
|
opts.repositoryName,
|
|
"--force",
|
|
"--region",
|
|
opts.region,
|
|
];
|
|
if (opts.awsProfile) args.push("--profile", opts.awsProfile);
|
|
const result = spawnSync("aws", args, { encoding: "utf-8" });
|
|
if (result.status === 0 || result.stderr?.includes("RepositoryNotFoundException")) return;
|
|
throw new Error(
|
|
`[lambda] aws ecr delete-repository ${opts.repositoryName} exited with code ${result.status ?? "unknown"}: ${result.stderr ?? ""}`,
|
|
);
|
|
}
|