@guren/plugin-lambda 0.1.0

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 ADDED
@@ -0,0 +1,66 @@
1
+ # @guren/plugin-lambda
2
+
3
+ Deploy a [Guren](https://guren.dev/) application to AWS Lambda on the Node.js runtime.
4
+
5
+ ```bash
6
+ bunx guren plugin @guren/plugin-lambda
7
+ bun add @guren/plugin-lambda
8
+ ```
9
+
10
+ Installing registers a `lambda:build` command and scaffolds `src/lambda.ts` — the module whose exports become your Lambda handlers.
11
+
12
+ ## Build and deploy
13
+
14
+ ```bash
15
+ bunx guren lambda:build
16
+ ```
17
+
18
+ `lambda:build` runs your app's `build` script, then assembles a `.lambda/` directory:
19
+
20
+ | Path | Contents |
21
+ |------|----------|
22
+ | `function/` | Self-contained ESM bundle (`handler.js`) plus the SSR bundle and Drizzle migrations — deploy this as the function code (handlers: `handler.http`, `handler.queue`, ...) |
23
+ | `assets/` | `public/` staged for S3, with built assets mirrored under both `/assets/` and `/public/assets/` |
24
+ | `env.json` | Environment the function expects (`NODE_ENV`, Inertia asset entries) — the same values are baked into the bundle as defaults |
25
+
26
+ It is generated output — add `.lambda` to `.gitignore` (the installer does this) and rebuild before every deploy. Pass `--zip` to also produce `function.zip` for direct uploads; CDK's `Code.fromAsset('.lambda/function')` archives the directory on its own.
27
+
28
+ ## API
29
+
30
+ - **`buildLambdaOutput(options)`** — the function behind `lambda:build`; import it for custom build scripts.
31
+ - **`lambdaPlugin()`** — the service provider factory, registered automatically by `guren plugin`.
32
+
33
+ The runtime adapters live in the framework itself — `createLambdaHandler`, `createSqsHandler`, `createScheduleHandler`, and `createConsoleHandler` from `@guren/core/lambda`.
34
+
35
+ ## Infrastructure (CDK)
36
+
37
+ The `@guren/plugin-lambda/cdk` subpath ships a construct that provisions the whole topology (`aws-cdk-lib` is an optional peer dependency):
38
+
39
+ ```typescript
40
+ import { GurenLambdaApp } from '@guren/plugin-lambda/cdk'
41
+
42
+ new GurenLambdaApp(stack, 'App', {
43
+ functionDir: '../.lambda/function',
44
+ assets: { dir: '../.lambda/assets' }, // S3 + CloudFront
45
+ queue: {}, // SQS + worker + DLQ
46
+ console: true, // aws lambda invoke, dispatching src/console.ts's kernel
47
+ dataApi: { // DATABASE_* env + rds-data/secret grants
48
+ database: 'appdb',
49
+ resourceArn: process.env.DATABASE_RESOURCE_ARN!,
50
+ secretArn: process.env.DATABASE_SECRET_ARN!,
51
+ },
52
+ environment: { APP_KEY: process.env.APP_KEY! },
53
+ })
54
+ ```
55
+
56
+ HTTP API, queue worker with partial batch failures, EventBridge scheduling, and asset routing (`/assets/*`, `/public/*`) come wired with the handler names `lambda:build` emits. Every sub-resource is exposed as a property for further customization.
57
+
58
+ ## Things Lambda changes
59
+
60
+ - **Bundle time is production.** `bun build` inlines `process.env.NODE_ENV` when bundling; the build pins it to `"production"` so runtime configuration cannot accidentally ship a development bundle.
61
+ - **The filesystem is read-only** except `/tmp`. Sessions and cache need a store that survives invocations — `DatabaseSessionStore`, or Redis via `@guren/core/redis`.
62
+ - **Passwords hash with Node's scrypt.** The default hasher detects the runtime and uses `NodeHasher` off Bun; hashes are not interchangeable with Bun's `ScryptHasher`.
63
+ - **Static assets belong on S3 + CloudFront**, not in the function. Point real asset URLs at the function's environment (`GUREN_INERTIA_ENTRY`, `GUREN_INERTIA_STYLES`) to override the baked same-origin defaults.
64
+ - **The database wants the RDS Data API.** `createAwsDataApiDatabase` from `@guren/core` connects to Aurora Serverless v2 over HTTP — no pool, no RDS Proxy, no VPC. Classic RDS works too with `createPostgresDatabase` plus RDS Proxy (`clientOptions: { prepare: false, max: 1 }`).
65
+
66
+ See the [Serverless Deployment Guide](https://guren.dev/docs/guides/serverless) for the full setup, including SQS, EventBridge, and CDK.
@@ -0,0 +1,84 @@
1
+ import { Duration } from 'aws-cdk-lib';
2
+ import * as apigwv2 from 'aws-cdk-lib/aws-apigatewayv2';
3
+ import * as cloudfront from 'aws-cdk-lib/aws-cloudfront';
4
+ import * as lambda from 'aws-cdk-lib/aws-lambda';
5
+ import * as s3 from 'aws-cdk-lib/aws-s3';
6
+ import * as sqs from 'aws-cdk-lib/aws-sqs';
7
+ import { Construct } from 'constructs';
8
+
9
+ interface GurenLambdaQueueProps {
10
+ /** SQS messages delivered per invocation. Defaults to 10. */
11
+ batchSize?: number;
12
+ /** Retries before a message lands in the dead-letter queue. Defaults to 3. */
13
+ maxReceiveCount?: number;
14
+ /** Worker timeout. Also drives the queue's visibility timeout. Defaults to 60 seconds. */
15
+ timeout?: Duration;
16
+ }
17
+ interface GurenLambdaScheduleProps {
18
+ /** How often the scheduler handler runs. Defaults to every minute. */
19
+ rate?: Duration;
20
+ }
21
+ interface GurenLambdaAssetsProps {
22
+ /** The staged assets directory produced by `guren lambda:build` (`.lambda/assets`). */
23
+ dir: string;
24
+ }
25
+ interface GurenLambdaDataApiProps {
26
+ /** Aurora cluster ARN — exposed as DATABASE_RESOURCE_ARN. */
27
+ resourceArn: string;
28
+ /** Secrets Manager secret ARN — exposed as DATABASE_SECRET_ARN. */
29
+ secretArn: string;
30
+ /** Database name — exposed as DATABASE_NAME. */
31
+ database?: string;
32
+ }
33
+ interface GurenLambdaAppProps {
34
+ /** The function directory produced by `guren lambda:build` (`.lambda/function`). */
35
+ functionDir: string;
36
+ /** Environment variables shared by every function (DATABASE_*, APP_KEY, ...). */
37
+ environment?: Record<string, string>;
38
+ /** Defaults to Node.js 22 — the runtime `lambda:build` bundles for. */
39
+ runtime?: lambda.Runtime;
40
+ /** Memory for every function. Defaults to 512 MB. */
41
+ memorySize?: number;
42
+ /** HTTP function timeout. Defaults to 30 seconds. */
43
+ timeout?: Duration;
44
+ /** Provision SQS + a queue worker wired to the `queue` export. */
45
+ queue?: GurenLambdaQueueProps;
46
+ /** Provision an EventBridge rule wired to the `schedule` export. */
47
+ schedule?: GurenLambdaScheduleProps;
48
+ /** Provision a console function wired to the `console` export (invoke with `{"command": "db:migrate"}`). */
49
+ console?: boolean;
50
+ /** Serve `.lambda/assets` from S3 behind CloudFront, with the app as the default origin. */
51
+ assets?: GurenLambdaAssetsProps;
52
+ /** Wire every function to Aurora via the RDS Data API: environment plus the rds-data and secret-read grants. */
53
+ dataApi?: GurenLambdaDataApiProps;
54
+ }
55
+ /**
56
+ * The full serverless topology for a Guren app in one construct: an HTTP API
57
+ * in front of the `http` handler, and opt-in SQS/EventBridge/console wiring
58
+ * plus CloudFront + S3 for static assets. Handler names follow the module
59
+ * `guren lambda:build` emits (`handler.http`, `handler.queue`, ...).
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * new GurenLambdaApp(this, 'App', {
64
+ * functionDir: '../.lambda/function',
65
+ * assets: { dir: '../.lambda/assets' },
66
+ * queue: {},
67
+ * environment: { DATABASE_NAME: 'appdb', DATABASE_RESOURCE_ARN: '...', DATABASE_SECRET_ARN: '...' },
68
+ * })
69
+ * ```
70
+ */
71
+ declare class GurenLambdaApp extends Construct {
72
+ readonly httpFunction: lambda.Function;
73
+ readonly httpApi: apigwv2.HttpApi;
74
+ readonly queue?: sqs.Queue;
75
+ readonly deadLetterQueue?: sqs.Queue;
76
+ readonly queueFunction?: lambda.Function;
77
+ readonly scheduleFunction?: lambda.Function;
78
+ readonly consoleFunction?: lambda.Function;
79
+ readonly assetsBucket?: s3.Bucket;
80
+ readonly distribution?: cloudfront.Distribution;
81
+ constructor(scope: Construct, id: string, props: GurenLambdaAppProps);
82
+ }
83
+
84
+ export { GurenLambdaApp, type GurenLambdaAppProps, type GurenLambdaAssetsProps, type GurenLambdaDataApiProps, type GurenLambdaQueueProps, type GurenLambdaScheduleProps };
@@ -0,0 +1,198 @@
1
+ import {
2
+ lambdaHandlerId
3
+ } from "../chunk-K64F77DP.js";
4
+
5
+ // src/cdk/index.ts
6
+ import { existsSync, readdirSync, readFileSync } from "fs";
7
+ import { resolve } from "path";
8
+ import { CfnOutput, Duration } from "aws-cdk-lib";
9
+ import * as apigwv2 from "aws-cdk-lib/aws-apigatewayv2";
10
+ import { HttpLambdaIntegration } from "aws-cdk-lib/aws-apigatewayv2-integrations";
11
+ import * as cloudfront from "aws-cdk-lib/aws-cloudfront";
12
+ import * as origins from "aws-cdk-lib/aws-cloudfront-origins";
13
+ import * as events from "aws-cdk-lib/aws-events";
14
+ import * as targets from "aws-cdk-lib/aws-events-targets";
15
+ import * as iam from "aws-cdk-lib/aws-iam";
16
+ import * as lambda from "aws-cdk-lib/aws-lambda";
17
+ import { SqsEventSource } from "aws-cdk-lib/aws-lambda-event-sources";
18
+ import * as s3 from "aws-cdk-lib/aws-s3";
19
+ import * as s3deploy from "aws-cdk-lib/aws-s3-deployment";
20
+ import * as sqs from "aws-cdk-lib/aws-sqs";
21
+ import { Construct } from "constructs";
22
+ var GurenLambdaApp = class extends Construct {
23
+ httpFunction;
24
+ httpApi;
25
+ queue;
26
+ deadLetterQueue;
27
+ queueFunction;
28
+ scheduleFunction;
29
+ consoleFunction;
30
+ assetsBucket;
31
+ distribution;
32
+ constructor(scope, id, props) {
33
+ super(scope, id);
34
+ const code = lambda.Code.fromAsset(props.functionDir);
35
+ const runtime = props.runtime ?? lambda.Runtime.NODEJS_22_X;
36
+ const memorySize = props.memorySize ?? 512;
37
+ const environment = {
38
+ NODE_ENV: "production",
39
+ ...dataApiEnvironment(props.dataApi),
40
+ // `guren lambda:build` writes the environment the bundle expects (asset
41
+ // and SSR locations) next to the function directory; explicit props win.
42
+ ...readBuildEnvironment(props.functionDir),
43
+ ...props.environment
44
+ };
45
+ const functionDefaults = { code, runtime, memorySize, environment };
46
+ this.httpFunction = new lambda.Function(this, "Http", {
47
+ ...functionDefaults,
48
+ handler: lambdaHandlerId("http"),
49
+ timeout: props.timeout ?? Duration.seconds(30)
50
+ });
51
+ this.httpApi = new apigwv2.HttpApi(this, "Api", {
52
+ defaultIntegration: new HttpLambdaIntegration("HttpIntegration", this.httpFunction)
53
+ });
54
+ if (props.queue) {
55
+ const workerTimeout = props.queue.timeout ?? Duration.seconds(60);
56
+ this.deadLetterQueue = new sqs.Queue(this, "JobDeadLetterQueue");
57
+ this.queue = new sqs.Queue(this, "JobQueue", {
58
+ // AWS guidance for Lambda event sources: at least 6x the function
59
+ // timeout, so a message never becomes visible again mid-processing
60
+ // (batching windows and retries extend the in-flight period).
61
+ visibilityTimeout: Duration.seconds(workerTimeout.toSeconds() * 6),
62
+ deadLetterQueue: {
63
+ queue: this.deadLetterQueue,
64
+ maxReceiveCount: props.queue.maxReceiveCount ?? 3
65
+ }
66
+ });
67
+ this.queueFunction = new lambda.Function(this, "QueueWorker", {
68
+ ...functionDefaults,
69
+ handler: lambdaHandlerId("queue"),
70
+ timeout: workerTimeout
71
+ });
72
+ this.queueFunction.addEventSource(
73
+ new SqsEventSource(this.queue, {
74
+ batchSize: props.queue.batchSize ?? 10,
75
+ // createSqsHandler() returns per-message failures; without this the
76
+ // whole batch would be retried when one job fails.
77
+ reportBatchItemFailures: true
78
+ })
79
+ );
80
+ }
81
+ if (props.schedule) {
82
+ this.scheduleFunction = new lambda.Function(this, "Scheduler", {
83
+ ...functionDefaults,
84
+ handler: lambdaHandlerId("schedule"),
85
+ timeout: Duration.seconds(60)
86
+ });
87
+ new events.Rule(this, "ScheduleRule", {
88
+ schedule: events.Schedule.rate(props.schedule.rate ?? Duration.minutes(1)),
89
+ targets: [new targets.LambdaFunction(this.scheduleFunction)]
90
+ });
91
+ }
92
+ if (props.console) {
93
+ this.consoleFunction = new lambda.Function(this, "Console", {
94
+ ...functionDefaults,
95
+ handler: lambdaHandlerId("console"),
96
+ timeout: Duration.minutes(5)
97
+ });
98
+ }
99
+ const functions = [this.httpFunction, this.queueFunction, this.scheduleFunction, this.consoleFunction].filter((fn) => fn !== void 0);
100
+ if (this.queue) {
101
+ for (const fn of functions) {
102
+ fn.addEnvironment("SQS_QUEUE_URL", this.queue.queueUrl);
103
+ this.queue.grantSendMessages(fn);
104
+ }
105
+ }
106
+ if (props.dataApi) {
107
+ for (const fn of functions) {
108
+ fn.addToRolePolicy(new iam.PolicyStatement({
109
+ actions: [
110
+ "rds-data:ExecuteStatement",
111
+ "rds-data:BatchExecuteStatement",
112
+ "rds-data:BeginTransaction",
113
+ "rds-data:CommitTransaction",
114
+ "rds-data:RollbackTransaction"
115
+ ],
116
+ resources: [props.dataApi.resourceArn]
117
+ }));
118
+ fn.addToRolePolicy(new iam.PolicyStatement({
119
+ actions: ["secretsmanager:GetSecretValue"],
120
+ resources: [props.dataApi.secretArn]
121
+ }));
122
+ }
123
+ }
124
+ if (props.assets) {
125
+ this.assetsBucket = new s3.Bucket(this, "Assets", {
126
+ blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
127
+ enforceSSL: true
128
+ });
129
+ const apiDomain = `${this.httpApi.apiId}.execute-api.${this.httpApi.stack.region}.${this.httpApi.stack.urlSuffix}`;
130
+ const assetOrigin = origins.S3BucketOrigin.withOriginAccessControl(this.assetsBucket);
131
+ const assetBehavior = {
132
+ origin: assetOrigin,
133
+ viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
134
+ cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED
135
+ };
136
+ const additionalBehaviors = {
137
+ "/assets/*": assetBehavior,
138
+ "/public/*": assetBehavior
139
+ };
140
+ if (existsSync(props.assets.dir)) {
141
+ for (const entry of readdirSync(props.assets.dir, { withFileTypes: true })) {
142
+ if (entry.name === "assets" || entry.name === "public") {
143
+ continue;
144
+ }
145
+ additionalBehaviors[entry.isDirectory() ? `/${entry.name}/*` : `/${entry.name}`] = assetBehavior;
146
+ }
147
+ }
148
+ this.distribution = new cloudfront.Distribution(this, "Distribution", {
149
+ defaultBehavior: {
150
+ origin: new origins.HttpOrigin(apiDomain),
151
+ viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
152
+ allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL,
153
+ // Every page render is dynamic; assets carry the cacheable content.
154
+ cachePolicy: cloudfront.CachePolicy.CACHING_DISABLED,
155
+ // Forward cookies/query/headers, but not Host — API Gateway routes
156
+ // by its own hostname.
157
+ originRequestPolicy: cloudfront.OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER
158
+ },
159
+ additionalBehaviors
160
+ });
161
+ new s3deploy.BucketDeployment(this, "AssetsDeployment", {
162
+ sources: [s3deploy.Source.asset(props.assets.dir)],
163
+ destinationBucket: this.assetsBucket,
164
+ // Invalidate on deploy: the /public/assets mirror and root-level
165
+ // files are not content-hashed, and CACHING_OPTIMIZED holds them
166
+ // for up to 24h otherwise.
167
+ distribution: this.distribution,
168
+ distributionPaths: ["/*"]
169
+ });
170
+ new CfnOutput(this, "DistributionUrl", { value: `https://${this.distribution.distributionDomainName}` });
171
+ }
172
+ new CfnOutput(this, "ApiUrl", { value: this.httpApi.apiEndpoint });
173
+ }
174
+ };
175
+ function dataApiEnvironment(dataApi) {
176
+ if (!dataApi) {
177
+ return {};
178
+ }
179
+ return {
180
+ DATABASE_RESOURCE_ARN: dataApi.resourceArn,
181
+ DATABASE_SECRET_ARN: dataApi.secretArn,
182
+ ...dataApi.database ? { DATABASE_NAME: dataApi.database } : {}
183
+ };
184
+ }
185
+ function readBuildEnvironment(functionDir) {
186
+ const envPath = resolve(functionDir, "../env.json");
187
+ if (!existsSync(envPath)) {
188
+ return {};
189
+ }
190
+ try {
191
+ return JSON.parse(readFileSync(envPath, "utf8"));
192
+ } catch {
193
+ return {};
194
+ }
195
+ }
196
+ export {
197
+ GurenLambdaApp
198
+ };
@@ -0,0 +1,244 @@
1
+ import {
2
+ LAMBDA_HANDLER_EXPORTS,
3
+ LAMBDA_HANDLER_MODULE
4
+ } from "./chunk-K64F77DP.js";
5
+
6
+ // src/build.ts
7
+ import { cpSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
8
+ import { resolve } from "path";
9
+ import {
10
+ DEV_ONLY_MODULES,
11
+ importSpecifier,
12
+ MCP_SDK_SUBPATH_PREFIX,
13
+ renderDevOnlyStub,
14
+ assertOutputDirOutsideRoot,
15
+ resetOutputDir,
16
+ resolveClientAssetEnv,
17
+ resolvePathLike,
18
+ resolveSsrEntryFile,
19
+ ssrRuntimePaths,
20
+ stageStaticAssets
21
+ } from "@guren/core/internal/deploy-build";
22
+ var MCP_UNAVAILABLE = "The MCP endpoint is unavailable on AWS Lambda \u2014 it generates files on disk.";
23
+ var UNAVAILABLE_ON_LAMBDA = {
24
+ sqlite: "bun:sqlite is unavailable on AWS Lambda \u2014 use createAwsDataApiDatabase() or createPostgresDatabase().",
25
+ vite: "The Vite dev server is unavailable on AWS Lambda \u2014 serve assets from S3/CloudFront.",
26
+ mcp: MCP_UNAVAILABLE
27
+ };
28
+ var DEV_ONLY_STUBS = Object.fromEntries(
29
+ DEV_ONLY_MODULES.map((module) => [
30
+ module.specifier,
31
+ renderDevOnlyStub(module, UNAVAILABLE_ON_LAMBDA[module.kind])
32
+ ])
33
+ );
34
+ var unlistedMcpStub = `throw new Error(${JSON.stringify(MCP_UNAVAILABLE)})
35
+ `;
36
+ function escapeRegExp(value) {
37
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
38
+ }
39
+ var STUB_FILTER = new RegExp(
40
+ `^(?:${[
41
+ ...DEV_ONLY_MODULES.map((module) => escapeRegExp(module.specifier)),
42
+ `${escapeRegExp(MCP_SDK_SUBPATH_PREFIX)}.+`
43
+ ].join("|")})$`
44
+ );
45
+ async function buildLambdaOutput(options = {}) {
46
+ const root = resolvePathLike(options.rootDir ?? process.cwd());
47
+ const out = resolvePathLike(options.outputDir ?? resolve(root, ".lambda"));
48
+ const entrypoint = resolvePathLike(options.entrypoint ?? resolve(root, "src/lambda.ts"));
49
+ const publicDir = resolvePathLike(options.publicDir ?? resolve(root, "public"));
50
+ const ssrDir = resolvePathLike(options.ssrDir ?? resolve(root, ".guren/ssr"));
51
+ const migrationsDir = resolvePathLike(options.migrationsDir ?? resolve(root, "db/migrations"));
52
+ const clientEntryKey = options.clientEntryKey ?? "resources/js/app.tsx";
53
+ const ssrEntryKey = options.ssrEntryKey ?? "resources/js/ssr.tsx";
54
+ assertOutputDirOutsideRoot(out, root, "Lambda build");
55
+ if (!options.skipAppBuild) {
56
+ runAppBuild(root);
57
+ }
58
+ if (!existsSync(entrypoint)) {
59
+ throw new Error(
60
+ `Lambda build: entrypoint not found at ${entrypoint}. Run \`bunx guren plugin @guren/plugin-lambda\` to scaffold src/lambda.ts, or pass "entrypoint".`
61
+ );
62
+ }
63
+ const ssrFile = resolveSsrEntry(ssrDir, ssrEntryKey);
64
+ const assetEnv = resolveClientAssetEnv(publicDir, clientEntryKey, "Lambda build");
65
+ resetOutputDir(out, root, "Lambda build");
66
+ const funcDir = resolve(out, "function");
67
+ mkdirSync(funcDir, { recursive: true });
68
+ stageStaticAssets(publicDir, resolve(out, "assets"));
69
+ const env = buildLambdaEnvironment(assetEnv, ssrFile, ssrDir);
70
+ const wrapperPath = resolve(out, `${LAMBDA_HANDLER_MODULE}.ts`);
71
+ writeFileSync(wrapperPath, renderHandlerModule({ out, entrypoint, env }));
72
+ await bundleHandler(wrapperPath, funcDir);
73
+ writeFileSync(resolve(funcDir, "package.json"), `${JSON.stringify({ type: "module" }, null, 2)}
74
+ `);
75
+ if (ssrFile) {
76
+ cpSync(ssrDir, resolve(funcDir, ".guren/ssr"), { recursive: true });
77
+ }
78
+ if (existsSync(migrationsDir)) {
79
+ cpSync(migrationsDir, resolve(funcDir, "db/migrations"), { recursive: true });
80
+ }
81
+ writeFileSync(resolve(out, "env.json"), `${JSON.stringify({ NODE_ENV: "production", ...env }, null, 2)}
82
+ `);
83
+ if (options.zip) {
84
+ zipFunction(out, funcDir);
85
+ }
86
+ }
87
+ function buildLambdaEnvironment(assetEnv, ssrFile, ssrDir) {
88
+ const env = {};
89
+ if (assetEnv.entry) {
90
+ env.GUREN_INERTIA_ENTRY = assetEnv.entry;
91
+ }
92
+ if (assetEnv.styles) {
93
+ env.GUREN_INERTIA_STYLES = assetEnv.styles;
94
+ }
95
+ if (ssrFile) {
96
+ const ssrPaths = ssrRuntimePaths(ssrDir, ssrFile, "./.guren/ssr");
97
+ env.GUREN_INERTIA_SSR_ENTRY = ssrPaths.entry;
98
+ if (ssrPaths.manifest) {
99
+ env.GUREN_INERTIA_SSR_MANIFEST = ssrPaths.manifest;
100
+ }
101
+ }
102
+ return env;
103
+ }
104
+ function renderHandlerModule(input) {
105
+ const lines = [
106
+ "// Generated by `guren lambda:build`. Do not edit \u2014 regenerate instead.",
107
+ ""
108
+ ];
109
+ const envEntries = Object.entries(input.env);
110
+ if (envEntries.length > 0) {
111
+ lines.push(
112
+ "// Baked as defaults so a deploy needs no function configuration; real",
113
+ "// environment variables (e.g. absolute CloudFront URLs) still win.",
114
+ ...envEntries.map(([key, value]) => `process.env.${key} ??= ${JSON.stringify(value)}`),
115
+ ""
116
+ );
117
+ }
118
+ lines.push(
119
+ "// Imported dynamically so the assignments above run before the app module",
120
+ "// graph evaluates \u2014 static imports are hoisted past them.",
121
+ `const module = await import(${JSON.stringify(importSpecifier(input.out, input.entrypoint, "Lambda build"))})`,
122
+ ""
123
+ );
124
+ for (const name of LAMBDA_HANDLER_EXPORTS) {
125
+ if (name === "console") {
126
+ lines.push("const consoleHandler = module.console", "export { consoleHandler as console }");
127
+ } else {
128
+ lines.push(`export const ${name} = module.${name}`);
129
+ }
130
+ }
131
+ lines.push("");
132
+ return lines.join("\n");
133
+ }
134
+ async function bundleHandler(handlerEntry, funcDir) {
135
+ const result = await Bun.build({
136
+ entrypoints: [handlerEntry],
137
+ outdir: funcDir,
138
+ target: "node",
139
+ // `identifiers: false`: class names are runtime identity here.
140
+ // `registerJob()`/`getJob()` key the job registry on `JobClass.name`, and
141
+ // that name is serialized into every queued message (SqsDriver,
142
+ // RedisDriver), a notification's persisted `type`, and `HttpException.name`
143
+ // — mangling silently breaks all of them.
144
+ //
145
+ // Not `keepNames`/`--keep-names`: as of Bun 1.3.14 both are accepted and
146
+ // silently leave class names mangled, so they cannot replace this.
147
+ minify: { whitespace: true, syntax: true, identifiers: false },
148
+ define: {
149
+ // `bun build` inlines `process.env.NODE_ENV` at bundle time (defaulting
150
+ // to "development"), so pin it to "production" for the deployed function.
151
+ "process.env.NODE_ENV": '"production"',
152
+ // Every module in the bundle shares one `import.meta.url` — the real
153
+ // runtime value of the single output file, `file:///var/task/handler.js`.
154
+ // That breaks the framework's `new URL('../db/migrations', import.meta.url)`
155
+ // convention (config/database.ts, config/app.ts's migration check): those
156
+ // files live one directory below the app root, so the same expression
157
+ // must resolve from one level under /var/task to reach the db/migrations
158
+ // folder `lambda:build` copies next to the bundle.
159
+ "import.meta.url": '"file:///var/task/config/lambda.js"'
160
+ },
161
+ // Provided by the managed Lambda runtime.
162
+ external: ["@aws-sdk/*"],
163
+ plugins: [
164
+ {
165
+ name: "guren-lambda-dev-stubs",
166
+ setup(build) {
167
+ build.onResolve({ filter: STUB_FILTER }, (args) => ({
168
+ path: args.path,
169
+ namespace: "guren-lambda-stub"
170
+ }));
171
+ build.onLoad({ filter: /.*/, namespace: "guren-lambda-stub" }, (args) => ({
172
+ contents: DEV_ONLY_STUBS[args.path] ?? unlistedMcpStub,
173
+ loader: "js"
174
+ }));
175
+ }
176
+ }
177
+ ]
178
+ });
179
+ if (!result.success) {
180
+ const details = result.logs.map((log) => String(log)).join("\n");
181
+ throw new Error(`Lambda build: bun build failed.
182
+ ${details}`);
183
+ }
184
+ }
185
+ function zipFunction(out, funcDir) {
186
+ const result = Bun.spawnSync({
187
+ cmd: ["zip", "-qr", resolve(out, "function.zip"), "."],
188
+ cwd: funcDir,
189
+ stdout: "inherit",
190
+ stderr: "inherit"
191
+ });
192
+ if (result.exitCode !== 0) {
193
+ throw new Error("Lambda build: zip failed. Install the `zip` binary or deploy the function directory directly (CDK archives it for you).");
194
+ }
195
+ }
196
+ function hasBuildScript(root) {
197
+ const packageJsonPath = resolve(root, "package.json");
198
+ if (!existsSync(packageJsonPath)) {
199
+ return false;
200
+ }
201
+ try {
202
+ const { scripts } = JSON.parse(readFileSync(packageJsonPath, "utf8"));
203
+ return Boolean(scripts?.build);
204
+ } catch {
205
+ return false;
206
+ }
207
+ }
208
+ function runAppBuild(root) {
209
+ if (!hasBuildScript(root)) {
210
+ console.warn('Lambda build: no "build" script in package.json \u2014 skipping the app build step.');
211
+ return;
212
+ }
213
+ const result = Bun.spawnSync({
214
+ cmd: ["bun", "run", "build"],
215
+ cwd: root,
216
+ stdout: "inherit",
217
+ stderr: "inherit"
218
+ });
219
+ if (result.exitCode !== 0) {
220
+ throw new Error('Lambda build: the app "build" script failed.');
221
+ }
222
+ }
223
+ function resolveSsrEntry(ssrDir, ssrEntryKey) {
224
+ const file = resolveSsrEntryFile(ssrDir, ssrEntryKey, "Lambda build");
225
+ if (!file) {
226
+ return void 0;
227
+ }
228
+ if (!hasRendererExport(readFileSync(file, "utf8"))) {
229
+ throw new Error(
230
+ `Lambda build: SSR entry ${file} does not export a renderer (expected a named "render" or default export).`
231
+ );
232
+ }
233
+ return file;
234
+ }
235
+ function hasRendererExport(source) {
236
+ if (/export\s*\*\s*from/.test(source)) {
237
+ return true;
238
+ }
239
+ return /export\s+default\b/.test(source) || /export\s*\{[^}]*\b(?:render|default)\b[^}]*\}/.test(source) || /export\s+(?:const|let|var|function|async\s+function)\s+render\b/.test(source);
240
+ }
241
+
242
+ export {
243
+ buildLambdaOutput
244
+ };
@@ -0,0 +1,12 @@
1
+ // src/handlers.ts
2
+ var LAMBDA_HANDLER_MODULE = "handler";
3
+ var LAMBDA_HANDLER_EXPORTS = ["http", "queue", "schedule", "console"];
4
+ function lambdaHandlerId(name) {
5
+ return `${LAMBDA_HANDLER_MODULE}.${name}`;
6
+ }
7
+
8
+ export {
9
+ LAMBDA_HANDLER_MODULE,
10
+ LAMBDA_HANDLER_EXPORTS,
11
+ lambdaHandlerId
12
+ };
@@ -0,0 +1,20 @@
1
+ import * as citty from 'citty';
2
+
3
+ declare const _default: {
4
+ 'lambda:build': citty.CommandDef<{
5
+ root: {
6
+ type: "string";
7
+ description: string;
8
+ };
9
+ 'skip-app-build': {
10
+ type: "boolean";
11
+ description: string;
12
+ };
13
+ zip: {
14
+ type: "boolean";
15
+ description: string;
16
+ };
17
+ }>;
18
+ };
19
+
20
+ export { _default as default };
@@ -0,0 +1,40 @@
1
+ import {
2
+ buildLambdaOutput
3
+ } from "./chunk-FVW2RWVN.js";
4
+ import "./chunk-K64F77DP.js";
5
+
6
+ // src/commands.ts
7
+ import { defineCommand } from "citty";
8
+ var lambdaBuild = defineCommand({
9
+ meta: {
10
+ name: "lambda:build",
11
+ description: "Assemble an AWS Lambda deployment (.lambda/) from the app build"
12
+ },
13
+ args: {
14
+ root: {
15
+ type: "string",
16
+ description: "App root directory (defaults to the current working directory)"
17
+ },
18
+ "skip-app-build": {
19
+ type: "boolean",
20
+ description: "Skip running the app's build script before assembling output"
21
+ },
22
+ zip: {
23
+ type: "boolean",
24
+ description: "Also produce .lambda/function.zip (requires the zip binary)"
25
+ }
26
+ },
27
+ async run({ args }) {
28
+ await buildLambdaOutput({
29
+ rootDir: args.root || process.cwd(),
30
+ skipAppBuild: Boolean(args["skip-app-build"]),
31
+ zip: Boolean(args.zip)
32
+ });
33
+ }
34
+ });
35
+ var commands_default = {
36
+ "lambda:build": lambdaBuild
37
+ };
38
+ export {
39
+ commands_default as default
40
+ };
@@ -0,0 +1,61 @@
1
+ import { ServiceProviderConstructor } from '@guren/core';
2
+ import { PathLike } from '@guren/core/internal/deploy-build';
3
+
4
+ interface BuildLambdaOutputOptions {
5
+ /** App root directory. Defaults to the current working directory. */
6
+ rootDir?: PathLike;
7
+ /** Output directory for the assembled function. Defaults to `<root>/.lambda`. */
8
+ outputDir?: PathLike;
9
+ /** Module exporting the Lambda handlers (http/queue/schedule/console). Defaults to `<root>/src/lambda.ts`. */
10
+ entrypoint?: PathLike;
11
+ /** Static files directory staged for S3. Defaults to `<root>/public`. */
12
+ publicDir?: PathLike;
13
+ /** Vite SSR build output. Defaults to `<root>/.guren/ssr`. */
14
+ ssrDir?: PathLike;
15
+ /** Drizzle migrations copied into the function. Defaults to `<root>/db/migrations`. */
16
+ migrationsDir?: PathLike;
17
+ /** Client manifest key for the frontend entry. Defaults to `resources/js/app.tsx`. */
18
+ clientEntryKey?: string;
19
+ /** SSR manifest key for the server entry. Defaults to `resources/js/ssr.tsx`. */
20
+ ssrEntryKey?: string;
21
+ /** Skip running the app's `build` script before assembling output. */
22
+ skipAppBuild?: boolean;
23
+ /** Also produce `<outputDir>/function.zip` (requires the `zip` binary). */
24
+ zip?: boolean;
25
+ }
26
+ /**
27
+ * Assemble a deployable AWS Lambda directory (`.lambda/`) from a built Guren
28
+ * app: a self-contained function bundle for the Node.js runtime, the SSR
29
+ * bundle and migrations alongside it, static assets staged for S3, and an
30
+ * `env.json` with the environment the function expects.
31
+ */
32
+ declare function buildLambdaOutput(options?: BuildLambdaOutputOptions): Promise<void>;
33
+
34
+ /**
35
+ * The single source of truth tying the generated bundle to the
36
+ * infrastructure: `lambda:build` emits a `handler` module re-exporting these
37
+ * names, and the CDK construct maps them to Lambda handler identifiers.
38
+ */
39
+ declare const LAMBDA_HANDLER_MODULE = "handler";
40
+ declare const LAMBDA_HANDLER_EXPORTS: readonly ["http", "queue", "schedule", "console"];
41
+ type LambdaHandlerExport = (typeof LAMBDA_HANDLER_EXPORTS)[number];
42
+ /** Lambda handler identifier for an export, e.g. `handler.http`. */
43
+ declare function lambdaHandlerId(name: LambdaHandlerExport): string;
44
+
45
+ /**
46
+ * Configuration for the Lambda plugin. Currently empty — reserved so future
47
+ * fields never force another registration-shape change.
48
+ */
49
+ interface LambdaPluginConfig {
50
+ }
51
+ /**
52
+ * Register the Lambda plugin.
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * createApp({ providers: [lambdaPlugin()] })
57
+ * ```
58
+ */
59
+ declare function lambdaPlugin(config?: LambdaPluginConfig): ServiceProviderConstructor;
60
+
61
+ export { type BuildLambdaOutputOptions, LAMBDA_HANDLER_EXPORTS, LAMBDA_HANDLER_MODULE, type LambdaHandlerExport, type LambdaPluginConfig, buildLambdaOutput, lambdaHandlerId, lambdaPlugin };
package/dist/index.js ADDED
@@ -0,0 +1,26 @@
1
+ import {
2
+ buildLambdaOutput
3
+ } from "./chunk-FVW2RWVN.js";
4
+ import {
5
+ LAMBDA_HANDLER_EXPORTS,
6
+ LAMBDA_HANDLER_MODULE,
7
+ lambdaHandlerId
8
+ } from "./chunk-K64F77DP.js";
9
+
10
+ // src/index.ts
11
+ import { definePlugin } from "@guren/core";
12
+ var factory = definePlugin({
13
+ name: "lambda",
14
+ register() {
15
+ }
16
+ });
17
+ function lambdaPlugin(config = {}) {
18
+ return factory(config);
19
+ }
20
+ export {
21
+ LAMBDA_HANDLER_EXPORTS,
22
+ LAMBDA_HANDLER_MODULE,
23
+ buildLambdaOutput,
24
+ lambdaHandlerId,
25
+ lambdaPlugin
26
+ };
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@guren/plugin-lambda",
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/gurenjs/guren",
9
+ "directory": "packages/plugin-lambda"
10
+ },
11
+ "homepage": "https://github.com/gurenjs/guren#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/gurenjs/guren/issues"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "gurenPlugin": {
19
+ "compatibility": ">=1.0.0 <2.0.0",
20
+ "commands": {
21
+ "entry": "./dist/commands.js",
22
+ "names": [
23
+ "lambda:build"
24
+ ]
25
+ }
26
+ },
27
+ "files": [
28
+ "dist"
29
+ ],
30
+ "main": "dist/index.js",
31
+ "types": "dist/index.d.ts",
32
+ "exports": {
33
+ ".": {
34
+ "types": "./dist/index.d.ts",
35
+ "default": "./dist/index.js"
36
+ },
37
+ "./cdk": {
38
+ "types": "./dist/cdk/index.d.ts",
39
+ "default": "./dist/cdk/index.js"
40
+ }
41
+ },
42
+ "scripts": {
43
+ "build": "tsup",
44
+ "test": "bun test",
45
+ "typecheck": "tsc --noEmit"
46
+ },
47
+ "dependencies": {
48
+ "@guren/core": "^1.4.0",
49
+ "citty": "^0.1.6"
50
+ },
51
+ "peerDependencies": {
52
+ "aws-cdk-lib": "^2.156.0",
53
+ "constructs": "^10.0.0"
54
+ },
55
+ "peerDependenciesMeta": {
56
+ "aws-cdk-lib": {
57
+ "optional": true
58
+ },
59
+ "constructs": {
60
+ "optional": true
61
+ }
62
+ },
63
+ "devDependencies": {
64
+ "@types/node": "^20.14.10",
65
+ "aws-cdk-lib": "^2.262.1",
66
+ "constructs": "^10.7.1",
67
+ "tsup": "^8.5.0",
68
+ "typescript": "^5.4.0"
69
+ }
70
+ }