// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { createHash } from 'node:crypto'; import { closeSync, openSync, readdirSync, readSync, writeFileSync } from 'node:fs'; import { dirname, join, posix } from 'node:path'; import { fileURLToPath } from 'node:url'; import { Construct } from 'constructs'; import { Annotations, CfnResource, CustomResource, Duration, Lazy, Names, RemovalPolicy, Stack, Token, } from 'aws-cdk-lib'; import * as iam from 'aws-cdk-lib/aws-iam'; import { CfnOriginAccessControl } from 'aws-cdk-lib/aws-cloudfront'; import { HttpOrigin, type HttpOriginProps } from 'aws-cdk-lib/aws-cloudfront-origins'; import { Code, Function as LambdaFunction } from 'aws-cdk-lib/aws-lambda'; import { LogGroup, RetentionDays } from 'aws-cdk-lib/aws-logs'; import { BlockPublicAccess, Bucket, BucketEncryption } from 'aws-cdk-lib/aws-s3'; import { Asset } from 'aws-cdk-lib/aws-s3-assets'; import { AwsCustomResource, AwsCustomResourcePolicy, PhysicalResourceId, Provider } from 'aws-cdk-lib/custom-resources'; import { HostingError } from '../hosting_error.js'; import type { ComputeResource } from '../manifest/types.js'; import { DEFAULT_NODE_RUNTIME } from './node_runtime.js'; const __dirname = dirname(fileURLToPath(import.meta.url)); // Pre-bundled at build time (scripts/bundle-handlers.mjs) with // `@aws-sdk/client-lambda-web` inlined — that client is not in the Lambda // runtime baseline. Dotless basename: see kv_keys.ts. const POLICY_HANDLER_BUNDLE = join(__dirname, 'web_function_policy_handler_bundle.mjs'); // ---- Constants ---- /** * Regions where Lambda Web Functions are available (launch set, Oct 2026). * Synth fails fast outside this set instead of surfacing a CloudFormation * "unrecognized resource type" error minutes into a deploy. */ export const WEB_FUNCTION_SUPPORTED_REGIONS: ReadonlySet = new Set([ 'us-east-1', 'us-east-2', 'us-west-2', 'ap-northeast-1', 'eu-west-1', ]); /** The only Web Function runtime at launch. */ const WEB_FUNCTION_RUNTIME = 'nodejs24.x'; /** Web Function request timeout bounds (seconds). */ const MIN_TIMEOUT_SECONDS = 3; const MAX_TIMEOUT_SECONDS = 900; const DEFAULT_TIMEOUT_SECONDS = 30; /** Bounds for `maxConcurrencyPerEnvironment` (revision setting). */ const MAX_CONCURRENCY_PER_ENVIRONMENT = 128; /** * Response headers a Web Function adds that name internal resources * (`lambda-web-logstream`: log stream + revision id). Hosting removes them * at the edge via its response headers policy. */ export const WEB_FUNCTION_INTERNAL_HEADERS: readonly string[] = ['lambda-web-logstream']; /** Logical-id prefix of the content-hashed revision resource. */ const REVISION_LOGICAL_ID_PREFIX = 'WebFunctionRevision'; /** Endpoint name. Create-only, so it must never change for a deployed app. */ const ENDPOINT_NAME = 'default'; /** * Entry shim written into the bundle root. The Web Function runtime loads * `AWS_LAMBDA_NODEJS_ENTRYPOINT` and waits for a server on the host:port in * `AWS_LAMBDA_HTTP_ENDPOINT`. Framework servers read their listen address from * their own env vars (`HOST`/`PORT` for Astro + SvelteKit, `NITRO_HOST`/ * `NITRO_PORT` for Nitro, `HOSTNAME`/`PORT` for a Next.js standalone server), * so the shim maps the Lambda-provided address onto all of them, then imports * the framework's own server entry unchanged. */ export const WEB_FUNCTION_ENTRY_SHIM = '__aws_blocks_web_entry.mjs'; /** @internal Render the entry shim that boots `serverEntry` (bundle-relative). */ export const renderEntryShim = (serverEntry: string): string => `// Generated by @aws-cdk-blocks/hosting — Lambda Web Functions entry shim. Do not edit. import { dirname, join } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; const endpoint = process.env.AWS_LAMBDA_HTTP_ENDPOINT; if (endpoint) { const sep = endpoint.lastIndexOf(':'); const host = endpoint.slice(0, sep); const port = endpoint.slice(sep + 1); for (const key of ['HOST', 'HOSTNAME', 'NITRO_HOST']) process.env[key] = host; for (const key of ['PORT', 'NITRO_PORT']) process.env[key] = port; } const entry = join(dirname(fileURLToPath(import.meta.url)), ${JSON.stringify(serverEntry)}); // Servers launched by the Lambda Web Adapter ran from their own directory // (run.sh \`cd\`s there); keep the same working directory. process.chdir(dirname(entry)); await import(pathToFileURL(entry).href); `; // ---- Public types ---- /** * Tuning for Lambda Web Function compute (`compute.type: 'web-function'`). */ export type WebFunctionOptions = { /** * Upper bound on concurrent requests a single execution environment serves. * Lambda manages a dynamic limit below this. Range 1–128. Default: Lambda's * default (64). */ maxConcurrencyPerEnvironment?: number; /** * Cap on execution environments for the endpoint (per Region). Range * 2–10,000. Default: unset (bounded only by the account vCPU quota). */ maxEnvironments?: number; /** * Request-rate cap for the endpoint in requests per second (per Region). * 0 blocks all traffic; otherwise 100–1,000 in steps of 100 or 2,000–10,000 * in steps of 1,000. Default: unset (bounded only by the account quota). */ rateLimit?: number; }; /** * Props for the WebFunctionConstruct. */ export type WebFunctionConstructProps = WebFunctionOptions & { /** Logical name of this compute resource (e.g. `default`). */ name: string; /** The compute resource definition from the deploy manifest (`http-server`). */ computeResource: ComputeResource; /** Per-request timeout. Default: from manifest or 30 seconds. Range 3–900. */ timeout?: Duration; /** CloudWatch log retention. Default: ONE_MONTH. */ logRetention?: RetentionDays; /** Skip the supported-region check (e.g. a Region added after this release). */ skipRegionValidation?: boolean; /** Additional environment variables (merged over the manifest's). */ environment?: Record; }; // ---- Construct ---- /** * SSR compute on **AWS Lambda Web Functions** — the framework's own Node.js HTTP * server runs directly on Lambda (no Lambda Web Adapter, no API Gateway). Each * execution environment serves many concurrent requests and is billed for * active CPU, which suits I/O-bound SSR. * * Provisions: * - a versioned code bucket + the bundle zip (Web Functions only take code * from a versioned S3 object that `lambda.amazonaws.com` can read), * - the `AWS::Lambda::WebFunction`, an immutable `WebFunctionRevision` per * deploy, and a `HomeRegion` `WebFunctionEndpoint` with `IamAuth`, * - a CloudFront origin access control (`lambda`, `always-amz-auth`) so only * the distribution can invoke the endpoint — see {@link createOrigin} and * {@link allowCloudFrontInvoke}. * * Declared with raw `CfnResource`s so it works on every `aws-cdk-lib` in the * supported peer range (the generated L1s only exist from 2.273.0). */ export class WebFunctionConstruct extends Construct implements iam.IGrantable { /** Execution role the server runs as. */ readonly role: iam.Role; readonly grantPrincipal: iam.IPrincipal; /** Physical Web Function name. */ readonly functionName: string; /** Web Function ARN (`arn:…:web-function/`). */ readonly functionArn: string; /** Endpoint ARN — the resource CloudFront is granted to invoke. */ readonly endpointArn: string; /** Endpoint domain name (`..lambda-web..on.aws`). */ readonly endpointDomainName: string; /** Origin access control CloudFront signs origin requests with. */ readonly originAccessControl: CfnOriginAccessControl; /** The underlying CloudFormation resources (escape hatch). */ readonly cfnWebFunction: CfnResource; readonly cfnRevision: CfnResource; readonly cfnEndpoint: CfnResource; private readonly environment: Record; private readonly logRetention: RetentionDays; private policyResource?: CustomResource; constructor(scope: Construct, id: string, props: WebFunctionConstructProps) { super(scope, id); const { computeResource } = props; const stack = Stack.of(this); validateRegion(stack.region, props.skipRegionValidation); const timeoutSeconds = resolveTimeout(props.timeout, computeResource.timeout); validateOptions(props); if (computeResource.type !== 'http-server') { throw new HostingError('WebFunctionUnsupportedComputeError', { message: `compute.type 'web-function' needs an HTTP-server build, but compute resource ` + `'${props.name}' is '${computeResource.type}'.`, resolution: 'Web Functions run the framework server directly. Use a framework/preset that emits a ' + 'Node.js HTTP server: Astro (@astrojs/node standalone), SvelteKit (adapter-node), ' + "Nuxt/Nitro with `nitro: { preset: 'node-server' }`, or Next.js with OpenNext's `node` " + "wrapper. The built-in adapters build these automatically when run inside " + "withComputeTarget('web-function', …) (core Hosting does this). Otherwise remove " + "`compute.type` (defaults to 'lambda').", }); } if (computeResource.runtime && computeResource.runtime !== WEB_FUNCTION_RUNTIME) { Annotations.of(this).addWarningV2( '@aws-cdk-blocks/hosting:WebFunctionRuntime', `Compute resource '${props.name}' declares runtime '${computeResource.runtime}', but Lambda Web ` + `Functions only support '${WEB_FUNCTION_RUNTIME}'. Deploying on ${WEB_FUNCTION_RUNTIME}.`, ); } // Lambda doesn't check that the server starts when it activates a revision, // so a bundle that crashes on boot deploys green. The likeliest cause is a // native module built for x64 (Web Functions run on Arm64) — e.g. a // HostingConstruct user whose adapter run didn't target Web Functions. const x64Modules = findX64NativeModules(computeResource.bundle); if (x64Modules.length > 0) { Annotations.of(this).addWarningV2( '@aws-cdk-blocks/hosting:WebFunctionX64NativeModule', `Compute resource '${props.name}' ships x86-64 native modules, but Lambda Web Functions run on Arm64 — ` + `the server may fail to start: ${x64Modules.join(', ')}. Rebuild them for linux-arm64 ` + "(wrap the adapter run in withComputeTarget('web-function', …) from @aws-cdk-blocks/hosting/adapters).", ); } // ---- Entry shim ---- const serverEntry = resolveServerEntry(props.name, computeResource); writeFileSync(join(computeResource.bundle, WEB_FUNCTION_ENTRY_SHIM), renderEntryShim(serverEntry), 'utf-8'); this.functionName = Names.uniqueResourceName(this, { maxLength: 64, separator: '-' }); // ---- Execution role ---- this.role = new iam.Role(this, 'FunctionRole', { assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'), managedPolicies: [iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSLambdaBasicExecutionRole')], }); this.grantPrincipal = this.role; // ---- Log groups ---- // Lambda writes in-Region logs to `.local` and centralizes them into // `` in the home Region. Pre-create both so the retention applies // (the service would otherwise create them with infinite retention). The // home group's name is CloudFormation-generated, NOT the default // `/aws/lambda/web/`: draining environments can still write after a // stack delete, which recreates a fixed-name group and makes the next // create of the same stack fail on the name collision. const retention = props.logRetention ?? RetentionDays.ONE_MONTH; this.logRetention = retention; const logGroup = new LogGroup(this, 'LogGroup', { retention, removalPolicy: RemovalPolicy.DESTROY }); const localLogGroup = new LogGroup(this, 'LocalLogGroup', { logGroupName: `${logGroup.logGroupName}.local`, retention, removalPolicy: RemovalPolicy.DESTROY, }); // ---- Code ---- // Every deploy copies the bundle zip onto ONE stable key and the revision // pins the object version that copy returns. Overwriting a key leaves // existing revisions untouched (they pin a version), and the superseded // zip becomes a non-current version that the lifecycle rule below expires. // A key per deploy, by contrast, keeps every old zip current forever, and // deleting/pruning it risks failing the revision still serving traffic. const codeBucket = new Bucket(this, 'CodeBucket', { versioned: true, encryption: BucketEncryption.S3_MANAGED, blockPublicAccess: BlockPublicAccess.BLOCK_ALL, enforceSSL: true, removalPolicy: RemovalPolicy.DESTROY, autoDeleteObjects: true, // Only superseded zips are non-current. CloudFormation deletes their // revisions in the same deploy, so 30 days only bounds the bucket size. lifecycleRules: [{ noncurrentVersionExpiration: Duration.days(30) }], }); const codeKey = `web-function/${this.functionName}/code.zip`; const revisionArnPattern = stack.formatArn({ service: 'lambda', resource: 'web-function', resourceName: `${this.functionName}/revision/*`, }); const bucketPolicy = codeBucket.addToResourcePolicy( new iam.PolicyStatement({ sid: 'AllowLambdaWebFunctionCodeAccess', principals: [new iam.ServicePrincipal('lambda.amazonaws.com')], actions: ['s3:GetObject', 's3:GetObjectVersion'], resources: [codeBucket.arnForObjects(codeKey)], conditions: { ArnLike: { 'aws:SourceArn': revisionArnPattern } }, }), ); const codeAsset = new Asset(this, 'CodeAsset', { path: computeResource.bundle }); const codeUpload = new AwsCustomResource(this, 'CodeUpload', { // onCreate defaults to onUpdate. The call re-runs whenever its parameters // change, i.e. whenever the bundle (asset key) changes. onUpdate: { service: 'S3', action: 'copyObject', parameters: { Bucket: codeBucket.bucketName, Key: codeKey, CopySource: `${codeAsset.s3BucketName}/${codeAsset.s3ObjectKey}`, }, // Stable id: an update must never look like a replacement (Express // Mode sandbox deploys run with rollback disabled, which rejects it). physicalResourceId: PhysicalResourceId.of('web-function-code'), outputPaths: ['VersionId'], }, policy: AwsCustomResourcePolicy.fromStatements([ new iam.PolicyStatement({ actions: ['s3:GetObject', 's3:GetObjectVersion'], resources: [codeAsset.bucket.arnForObjects(codeAsset.s3ObjectKey)], }), new iam.PolicyStatement({ actions: ['s3:PutObject'], resources: [codeBucket.arnForObjects(codeKey)] }), ]), installLatestAwsSdk: false, timeout: Duration.minutes(5), }); const codeVersionId = codeUpload.getResponseField('VersionId'); // ---- Web Function, revision, endpoint ---- this.cfnWebFunction = new CfnResource(this, 'WebFunction', { type: 'AWS::Lambda::WebFunction', properties: { FunctionName: this.functionName }, }); this.functionArn = this.cfnWebFunction.getAtt('FunctionArn').toString(); this.environment = { ...computeResource.environment, ...props.environment }; this.environment.AWS_LAMBDA_NODEJS_ENTRYPOINT = WEB_FUNCTION_ENTRY_SHIM; const revisionProperties = { FunctionName: this.functionName, BuildConfig: { CodeConfig: { S3Object: { Bucket: codeBucket.bucketName, Key: codeKey, VersionId: codeVersionId } }, RuntimeConfig: { Runtime: WEB_FUNCTION_RUNTIME }, }, ServiceConfig: { ExecutionRoleArn: this.role.roleArn, TimeoutSeconds: timeoutSeconds, MaxConcurrencyPerEnvironment: props.maxConcurrencyPerEnvironment, // Lazy: env vars are added after construction (secrets, CDK Blocks // config, ISR wiring). Every revision property is create-only, so a // changed env var produces a new revision — the same as a new deploy. EnvironmentVariables: Lazy.any({ produce: () => ({ ...this.environment }) }), TelemetryConfig: { LoggingConfig: { LogGroup: logGroup.logGroupName } }, }, }; this.cfnRevision = new CfnResource(this, 'Revision', { type: 'AWS::Lambda::WebFunctionRevision', properties: revisionProperties, }); this.cfnRevision.addDependency(this.cfnWebFunction); // Lambda reads the object when the revision is created: the zip, the // bucket policy, and the role (incl. its default policy) must exist first. // Depending on the log groups also orders a stack delete: the revision // (and its environments) go before the groups they write to. this.cfnRevision.node.addDependency(codeUpload, this.role, logGroup, localLogGroup); // Every revision property is create-only, so an in-place change would be a // REPLACEMENT update, which CloudFormation rejects on stacks deployed with // rollback disabled (Express Mode sandbox deploys). Like `lambda.Version`, // derive the logical id from the revision's content instead: a change adds // a new revision, the endpoint is re-pointed (an in-place update), and the // old revision is deleted during cleanup. this.cfnRevision.overrideLogicalId( Lazy.uncachedString({ produce: () => { const hash = createHash('sha256') .update(JSON.stringify(stack.resolve(revisionProperties))) .update(codeAsset.assetHash) .digest('hex') .slice(0, 16); return `${REVISION_LOGICAL_ID_PREFIX}${hash}`; }, }), ); if (bucketPolicy.policyDependable) this.cfnRevision.node.addDependency(bucketPolicy.policyDependable); this.cfnEndpoint = new CfnResource(this, 'Endpoint', { type: 'AWS::Lambda::WebFunctionEndpoint', properties: { FunctionName: this.functionName, EndpointName: ENDPOINT_NAME, EndpointType: 'HomeRegion', // IamAuth + CloudFront OAC: only the distribution (granted via the // resource policy) can invoke the endpoint. An ApplicationManaged // endpoint would stay publicly reachable at its own domain. AuthType: 'IamAuth', RevisionWeights: [{ RevisionId: this.cfnRevision.getAtt('RevisionId'), Weight: 100 }], ScalingConfig: props.maxEnvironments !== undefined ? { MaxEnvironments: props.maxEnvironments } : undefined, ThrottleConfig: props.rateLimit !== undefined ? { RateLimit: props.rateLimit } : undefined, }, }); this.cfnEndpoint.addDependency(this.cfnWebFunction); this.endpointArn = this.cfnEndpoint.getAtt('EndpointArn').toString(); this.endpointDomainName = this.cfnEndpoint.getAtt('DomainName').toString(); this.originAccessControl = new CfnOriginAccessControl(this, 'OriginAccessControl', { originAccessControlConfig: { name: Names.uniqueResourceName(this, { maxLength: 64, separator: '-' }), originAccessControlOriginType: 'lambda', // The only signing behavior CloudFront accepts for Web Function // origins. It signs with `X-Amz-*` headers and leaves the viewer's // `Authorization` header intact for the app's own auth. signingBehavior: 'always-amz-auth', signingProtocol: 'sigv4', }, }); } /** Add an environment variable to the server (applies to the deployed revision). */ addEnvironment(key: string, value: string): this { if (value === '') { // Web Function env values must be non-empty; Lambda rejects the revision. Annotations.of(this).addWarningV2( '@aws-cdk-blocks/hosting:WebFunctionEmptyEnv', `Environment variable '${key}' is empty and was not set — Lambda Web Functions reject empty values.`, ); return this; } this.environment[key] = value; return this; } /** Add a statement to the execution role's policy. */ addToRolePolicy(statement: iam.PolicyStatement): void { this.role.addToPrincipalPolicy(statement); } /** A CloudFront origin for the endpoint, signed with this function's OAC. */ createOrigin(props: HttpOriginProps = {}): HttpOrigin { return new HttpOrigin(this.endpointDomainName, { ...props, originAccessControlId: this.originAccessControl.attrId }); } /** * Grant one CloudFront distribution `lambda:InvokeWebFunctionEndpoint` on the * endpoint, via the Web Function's resource-based policy. Call once — the * function has a single policy document and this resource owns it. */ allowCloudFrontInvoke(distributionId: string): void { if (this.policyResource) { throw new HostingError('WebFunctionPolicyAlreadySetError', { message: 'allowCloudFrontInvoke() was already called for this Web Function.', resolution: 'A Web Function has a single resource policy; grant one distribution per function.', }); } const stack = Stack.of(this); const distributionArn = stack.formatArn({ service: 'cloudfront', region: '', resource: 'distribution', resourceName: distributionId, }); const policy = { Version: '2012-10-17', Statement: [ { Sid: 'AllowCloudFrontOAC', Effect: 'Allow', Principal: { Service: 'cloudfront.amazonaws.com' }, Action: 'lambda:InvokeWebFunctionEndpoint', Resource: this.endpointArn, Condition: { StringEquals: { 'aws:SourceArn': distributionArn } }, }, ], }; // Explicit log group for the handler + provider framework: the Lambda // default (`/aws/lambda/`, created on first invoke) has infinite // retention and outlives the stack. const policyLogGroup = new LogGroup(this, 'PolicyLogGroup', { retention: this.logRetention, removalPolicy: RemovalPolicy.DESTROY, }); const handler = new LambdaFunction(this, 'PolicyFn', { code: Code.fromAsset(dirname(POLICY_HANDLER_BUNDLE), { exclude: ['*', '!web_function_policy_handler_bundle.mjs'], }), handler: 'web_function_policy_handler_bundle.handler', runtime: DEFAULT_NODE_RUNTIME, timeout: Duration.minutes(2), logGroup: policyLogGroup, }); handler.addToRolePolicy( new iam.PolicyStatement({ actions: ['lambda:PutResourcePolicy', 'lambda:DeleteResourcePolicy'], resources: [this.functionArn], }), ); const provider = new Provider(this, 'PolicyProvider', { onEventHandler: handler, logGroup: policyLogGroup }); this.policyResource = new CustomResource(this, 'ResourcePolicy', { serviceToken: provider.serviceToken, properties: { FunctionArn: this.functionArn, Policy: stack.toJsonString(policy) }, }); // The policy names the endpoint ARN; put it once the endpoint exists. this.policyResource.node.addDependency(this.cfnEndpoint); } } // ---- Validation helpers ---- /** ELF `e_machine` value for x86-64. */ const ELF_MACHINE_X86_64 = 0x3e; /** * @internal Bundle-relative paths (at most `limit`) of `.node` native modules * compiled for x86-64 — read from each file's ELF header (`e_machine` at byte * 18). Non-ELF files (e.g. darwin builds) are ignored. */ const findX64NativeModules = (bundle: string, limit = 5): string[] => { const found: string[] = []; let entries: string[]; try { entries = readdirSync(bundle, { recursive: true, encoding: 'utf-8' }); } catch { return found; } const header = Buffer.alloc(20); for (const rel of entries) { if (!rel.endsWith('.node')) continue; let fd: number | undefined; try { fd = openSync(join(bundle, rel), 'r'); const read = readSync(fd, header, 0, header.length, 0); const isElf = read === header.length && header.readUInt32BE(0) === 0x7f454c46; if (isElf && header.readUInt16LE(18) === ELF_MACHINE_X86_64) found.push(rel); } catch { // unreadable entry (directory named *.node, broken symlink) — skip } finally { if (fd !== undefined) closeSync(fd); } if (found.length >= limit) break; } return found; }; const validateRegion = (region: string, skip: boolean | undefined): void => { if (skip || Token.isUnresolved(region) || WEB_FUNCTION_SUPPORTED_REGIONS.has(region)) return; throw new HostingError('WebFunctionUnsupportedRegionError', { message: `Lambda Web Functions are not available in region '${region}'.`, resolution: `Deploy to one of: ${[...WEB_FUNCTION_SUPPORTED_REGIONS].join(', ')} — or remove ` + "`compute.type: 'web-function'` to use Lambda compute (available in every Region). " + 'Set `skipRegionValidation: true` if Web Functions have since launched in your Region.', }); }; const resolveTimeout = (timeout: Duration | undefined, manifestSeconds: number | undefined): number => { const seconds = timeout?.toSeconds() ?? manifestSeconds ?? DEFAULT_TIMEOUT_SECONDS; if (!Number.isInteger(seconds) || seconds < MIN_TIMEOUT_SECONDS || seconds > MAX_TIMEOUT_SECONDS) { throw new HostingError('InvalidTimeoutError', { message: `compute.timeout for a Web Function must be ${MIN_TIMEOUT_SECONDS}–${MAX_TIMEOUT_SECONDS} whole seconds; received ${seconds}.`, resolution: `Set compute.timeout between ${MIN_TIMEOUT_SECONDS} and ${MAX_TIMEOUT_SECONDS} seconds.`, }); } return seconds; }; const isValidRateLimit = (n: number): boolean => n === 0 || (n >= 100 && n <= 1000 && n % 100 === 0) || (n >= 2000 && n <= 10000 && n % 1000 === 0); const validateOptions = (opts: WebFunctionOptions): void => { const { maxConcurrencyPerEnvironment: mc, maxEnvironments: me, rateLimit: rl } = opts; if (mc !== undefined && (!Number.isInteger(mc) || mc < 1 || mc > MAX_CONCURRENCY_PER_ENVIRONMENT)) { throw new HostingError('InvalidWebFunctionOptionError', { message: `compute.webFunction.maxConcurrencyPerEnvironment must be an integer 1–${MAX_CONCURRENCY_PER_ENVIRONMENT}; received ${mc}.`, resolution: 'Omit it to use the Lambda default (64).', }); } if (me !== undefined && (!Number.isInteger(me) || me < 2 || me > 10000)) { throw new HostingError('InvalidWebFunctionOptionError', { message: `compute.webFunction.maxEnvironments must be an integer 2–10000; received ${me}.`, resolution: 'Omit it to scale up to the account vCPU quota.', }); } if (rl !== undefined && !isValidRateLimit(rl)) { throw new HostingError('InvalidWebFunctionOptionError', { message: `compute.webFunction.rateLimit ${rl} is not a supported value.`, resolution: 'Use 0 (block all), 100–1000 in steps of 100, or 2000–10000 in steps of 1000.', }); } }; /** * The bundle-relative Node module that starts the server. Adapters set * `serverEntry`; otherwise fall back to a JS `entrypoint` (Nitro `index.mjs`, * OpenNext `server.js`). A shell `entrypoint` (`run.sh`) is a Lambda Web Adapter * wrapper and can't be imported. */ const resolveServerEntry = (name: string, resource: ComputeResource): string => { const candidate = resource.serverEntry ?? resource.entrypoint; if (candidate && /\.(m|c)?js$/.test(candidate)) return `./${posix.normalize(candidate)}`; throw new HostingError('WebFunctionServerEntryError', { message: `Compute resource '${name}' has no Node.js server entry (entrypoint: '${resource.entrypoint ?? 'unset'}').`, resolution: "Set `serverEntry` on the compute resource to the bundle-relative server module (e.g. 'server/entry.mjs').", }); };