@guren/plugin-lambda 0.1.0 → 0.2.1
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 +3 -1
- package/dist/build-56qBHosh.js +221 -0
- package/dist/cdk/index.d.ts +56 -56
- package/dist/cdk/index.js +164 -178
- package/dist/commands.d.ts +21 -18
- package/dist/commands.js +36 -39
- package/dist/handlers-CkWGWQQX.js +19 -0
- package/dist/index.d.ts +38 -30
- package/dist/index.js +17 -22
- package/package.json +5 -5
- package/dist/chunk-FVW2RWVN.js +0 -244
- package/dist/chunk-K64F77DP.js +0 -12
package/README.md
CHANGED
|
@@ -49,7 +49,9 @@ new GurenLambdaApp(stack, 'App', {
|
|
|
49
49
|
resourceArn: process.env.DATABASE_RESOURCE_ARN!,
|
|
50
50
|
secretArn: process.env.DATABASE_SECRET_ARN!,
|
|
51
51
|
},
|
|
52
|
-
|
|
52
|
+
// APP_URL is the app's public base URL. Emailed links (password reset,
|
|
53
|
+
// email verification) are built from it rather than the request host.
|
|
54
|
+
environment: { APP_KEY: process.env.APP_KEY!, APP_URL: process.env.APP_URL! },
|
|
53
55
|
})
|
|
54
56
|
```
|
|
55
57
|
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { n as LAMBDA_HANDLER_MODULE, t as LAMBDA_HANDLER_EXPORTS } from "./handlers-CkWGWQQX.js";
|
|
2
|
+
import { cpSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { resolve } from "node:path";
|
|
4
|
+
import { DEV_ONLY_MODULES, MCP_SDK_SUBPATH_PREFIX, assertOutputDirOutsideRoot, importSpecifier, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, unusedSqlClients } from "@guren/core/internal/deploy-build";
|
|
5
|
+
//#region src/build.ts
|
|
6
|
+
const MCP_UNAVAILABLE = "The MCP endpoint is unavailable on AWS Lambda — it generates files on disk.";
|
|
7
|
+
/**
|
|
8
|
+
* Why the dev-only modules in `DEV_ONLY_MODULES` cannot run here, worded for
|
|
9
|
+
* this platform: each names the Lambda-appropriate replacement.
|
|
10
|
+
*
|
|
11
|
+
* Keyed on the kinds this platform stubs unconditionally, not on every kind
|
|
12
|
+
* that exists. The SQL clients are load-bearing on Lambda — the app connects
|
|
13
|
+
* to Postgres or the Data API through them — so which of those are dead
|
|
14
|
+
* weight is decided per app, not here, and their messages come from
|
|
15
|
+
* `unusedSqlClients`.
|
|
16
|
+
*/
|
|
17
|
+
const UNAVAILABLE_ON_LAMBDA = {
|
|
18
|
+
sqlite: "bun:sqlite is unavailable on AWS Lambda — use createAwsDataApiDatabase() or createPostgresDatabase().",
|
|
19
|
+
vite: "The Vite dev server is unavailable on AWS Lambda — serve assets from S3/CloudFront.",
|
|
20
|
+
mcp: MCP_UNAVAILABLE
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Dev-only modules replaced with throwing stubs rather than left external.
|
|
24
|
+
* Inlining a lazily-imported module hoists that module's own static imports to
|
|
25
|
+
* the bundle top level, so an external module reached this way (the MCP SDK)
|
|
26
|
+
* would fail at import time on Lambda even though no code path ever runs it.
|
|
27
|
+
* Stubbing also keeps megabytes of dev tooling out of the bundle.
|
|
28
|
+
*
|
|
29
|
+
* Unconditional, unlike the database clients: nothing an app can declare makes
|
|
30
|
+
* the Vite dev server or the MCP endpoint's generators run on Lambda.
|
|
31
|
+
*/
|
|
32
|
+
const DEV_ONLY_STUBS = Object.fromEntries(DEV_ONLY_MODULES.map((module) => [module.specifier, renderDevOnlyStub(module, UNAVAILABLE_ON_LAMBDA[module.kind])]));
|
|
33
|
+
/**
|
|
34
|
+
* The dev-only stubs plus one per database client this app does not connect
|
|
35
|
+
* through. Unlike the dev-only set this depends on the app, so it is built
|
|
36
|
+
* per build rather than at module scope.
|
|
37
|
+
*
|
|
38
|
+
* A stub here also *overrides* `external`, verified against Bun 1.3.14: the
|
|
39
|
+
* bundler consults plugins before it consults the external list, so stubbing
|
|
40
|
+
* `@aws-sdk/client-rds-data` for a Postgres app really does replace it rather
|
|
41
|
+
* than leaving `external: ['@aws-sdk/*']` to keep drizzle's hoisted top-level
|
|
42
|
+
* import of a package the runtime may not provide.
|
|
43
|
+
*/
|
|
44
|
+
function stubsFor(root, dialects) {
|
|
45
|
+
const unused = unusedSqlClients({
|
|
46
|
+
root,
|
|
47
|
+
label: "Lambda build",
|
|
48
|
+
dialects
|
|
49
|
+
});
|
|
50
|
+
return {
|
|
51
|
+
...DEV_ONLY_STUBS,
|
|
52
|
+
...Object.fromEntries(unused.map(({ module, message }) => [module.specifier, renderDevOnlyStub(module, message)]))
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Fallback for an MCP SDK subpath `DEV_ONLY_MODULES` does not name. It cannot
|
|
57
|
+
* know which names the importer destructures, so it throws on evaluation
|
|
58
|
+
* rather than resolving to an empty module: a subpath reached from app code
|
|
59
|
+
* (not Guren's disabled MCP endpoint) must fail loudly at build or cold start,
|
|
60
|
+
* never silently hand back missing exports.
|
|
61
|
+
*/
|
|
62
|
+
const unlistedMcpStub = `throw new Error(${JSON.stringify(MCP_UNAVAILABLE)})\n`;
|
|
63
|
+
function escapeRegExp(value) {
|
|
64
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
65
|
+
}
|
|
66
|
+
function stubFilter(stubs) {
|
|
67
|
+
return new RegExp(`^(?:${[...Object.keys(stubs).map(escapeRegExp), `${escapeRegExp(MCP_SDK_SUBPATH_PREFIX)}.+`].join("|")})$`);
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Assemble a deployable AWS Lambda directory (`.lambda/`) from a built Guren
|
|
71
|
+
* app: a self-contained function bundle for the Node.js runtime, the SSR
|
|
72
|
+
* bundle and migrations alongside it, static assets staged for S3, and an
|
|
73
|
+
* `env.json` with the environment the function expects.
|
|
74
|
+
*/
|
|
75
|
+
async function buildLambdaOutput(options = {}) {
|
|
76
|
+
const root = resolvePathLike(options.rootDir ?? process.cwd());
|
|
77
|
+
const out = resolvePathLike(options.outputDir ?? resolve(root, ".lambda"));
|
|
78
|
+
const entrypoint = resolvePathLike(options.entrypoint ?? resolve(root, "src/lambda.ts"));
|
|
79
|
+
const publicDir = resolvePathLike(options.publicDir ?? resolve(root, "public"));
|
|
80
|
+
const ssrDir = resolvePathLike(options.ssrDir ?? resolve(root, ".guren/ssr"));
|
|
81
|
+
const migrationsDir = resolvePathLike(options.migrationsDir ?? resolve(root, "db/migrations"));
|
|
82
|
+
const clientEntryKey = options.clientEntryKey ?? "resources/js/app.tsx";
|
|
83
|
+
const ssrEntryKey = options.ssrEntryKey ?? "resources/js/ssr.tsx";
|
|
84
|
+
assertOutputDirOutsideRoot(out, root, "Lambda build");
|
|
85
|
+
if (!options.skipAppBuild) runAppBuild(root);
|
|
86
|
+
if (!existsSync(entrypoint)) throw new Error(`Lambda build: entrypoint not found at ${entrypoint}. Run \`bunx guren plugin @guren/plugin-lambda\` to scaffold src/lambda.ts, or pass "entrypoint".`);
|
|
87
|
+
const ssrFile = resolveSsrEntry(ssrDir, ssrEntryKey);
|
|
88
|
+
const assetEnv = resolveClientAssetEnv(publicDir, clientEntryKey, "Lambda build");
|
|
89
|
+
resetOutputDir(out, root, "Lambda build");
|
|
90
|
+
const funcDir = resolve(out, "function");
|
|
91
|
+
mkdirSync(funcDir, { recursive: true });
|
|
92
|
+
stageStaticAssets(publicDir, resolve(out, "assets"));
|
|
93
|
+
const env = buildLambdaEnvironment(assetEnv, ssrFile, ssrDir);
|
|
94
|
+
const wrapperPath = resolve(out, `${LAMBDA_HANDLER_MODULE}.ts`);
|
|
95
|
+
writeFileSync(wrapperPath, renderHandlerModule({
|
|
96
|
+
out,
|
|
97
|
+
entrypoint,
|
|
98
|
+
env
|
|
99
|
+
}));
|
|
100
|
+
await bundleHandler(wrapperPath, funcDir, stubsFor(root, options.databaseDialects));
|
|
101
|
+
writeFileSync(resolve(funcDir, "package.json"), `${JSON.stringify({ type: "module" }, null, 2)}\n`);
|
|
102
|
+
if (ssrFile) cpSync(ssrDir, resolve(funcDir, ".guren/ssr"), { recursive: true });
|
|
103
|
+
if (existsSync(migrationsDir)) cpSync(migrationsDir, resolve(funcDir, "db/migrations"), { recursive: true });
|
|
104
|
+
writeFileSync(resolve(out, "env.json"), `${JSON.stringify({
|
|
105
|
+
NODE_ENV: "production",
|
|
106
|
+
...env
|
|
107
|
+
}, null, 2)}\n`);
|
|
108
|
+
if (options.zip) zipFunction(out, funcDir);
|
|
109
|
+
}
|
|
110
|
+
function buildLambdaEnvironment(assetEnv, ssrFile, ssrDir) {
|
|
111
|
+
const env = {};
|
|
112
|
+
if (assetEnv.entry) env.GUREN_INERTIA_ENTRY = assetEnv.entry;
|
|
113
|
+
if (assetEnv.styles) env.GUREN_INERTIA_STYLES = assetEnv.styles;
|
|
114
|
+
if (ssrFile) {
|
|
115
|
+
const ssrPaths = ssrRuntimePaths(ssrDir, ssrFile, "./.guren/ssr");
|
|
116
|
+
env.GUREN_INERTIA_SSR_ENTRY = ssrPaths.entry;
|
|
117
|
+
if (ssrPaths.manifest) env.GUREN_INERTIA_SSR_MANIFEST = ssrPaths.manifest;
|
|
118
|
+
}
|
|
119
|
+
return env;
|
|
120
|
+
}
|
|
121
|
+
function renderHandlerModule(input) {
|
|
122
|
+
const lines = ["// Generated by `guren lambda:build`. Do not edit — regenerate instead.", ""];
|
|
123
|
+
const envEntries = Object.entries(input.env);
|
|
124
|
+
if (envEntries.length > 0) lines.push("// Baked as defaults so a deploy needs no function configuration; real", "// environment variables (e.g. absolute CloudFront URLs) still win.", ...envEntries.map(([key, value]) => `process.env.${key} ??= ${JSON.stringify(value)}`), "");
|
|
125
|
+
lines.push("// Imported dynamically so the assignments above run before the app module", "// graph evaluates — static imports are hoisted past them.", `const module = await import(${JSON.stringify(importSpecifier(input.out, input.entrypoint, "Lambda build"))})`, "");
|
|
126
|
+
for (const name of LAMBDA_HANDLER_EXPORTS) if (name === "console") lines.push("const consoleHandler = module.console", "export { consoleHandler as console }");
|
|
127
|
+
else lines.push(`export const ${name} = module.${name}`);
|
|
128
|
+
lines.push("");
|
|
129
|
+
return lines.join("\n");
|
|
130
|
+
}
|
|
131
|
+
async function bundleHandler(handlerEntry, funcDir, stubs) {
|
|
132
|
+
const filter = stubFilter(stubs);
|
|
133
|
+
const result = await Bun.build({
|
|
134
|
+
entrypoints: [handlerEntry],
|
|
135
|
+
throw: false,
|
|
136
|
+
outdir: funcDir,
|
|
137
|
+
target: "node",
|
|
138
|
+
minify: {
|
|
139
|
+
whitespace: true,
|
|
140
|
+
syntax: true,
|
|
141
|
+
identifiers: false
|
|
142
|
+
},
|
|
143
|
+
define: {
|
|
144
|
+
"process.env.NODE_ENV": "\"production\"",
|
|
145
|
+
"import.meta.url": "\"file:///var/task/config/lambda.js\""
|
|
146
|
+
},
|
|
147
|
+
external: ["@aws-sdk/*"],
|
|
148
|
+
plugins: [{
|
|
149
|
+
name: "guren-lambda-stubs",
|
|
150
|
+
setup(build) {
|
|
151
|
+
build.onResolve({ filter }, (args) => ({
|
|
152
|
+
path: args.path,
|
|
153
|
+
namespace: "guren-lambda-stub"
|
|
154
|
+
}));
|
|
155
|
+
build.onLoad({
|
|
156
|
+
filter: /.*/,
|
|
157
|
+
namespace: "guren-lambda-stub"
|
|
158
|
+
}, (args) => ({
|
|
159
|
+
contents: stubs[args.path] ?? unlistedMcpStub,
|
|
160
|
+
loader: "js"
|
|
161
|
+
}));
|
|
162
|
+
}
|
|
163
|
+
}]
|
|
164
|
+
});
|
|
165
|
+
if (!result.success) {
|
|
166
|
+
const details = result.logs.map((log) => String(log)).join("\n");
|
|
167
|
+
throw new Error(`Lambda build: bun build failed.\n${details}`);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
function zipFunction(out, funcDir) {
|
|
171
|
+
if (Bun.spawnSync({
|
|
172
|
+
cmd: [
|
|
173
|
+
"zip",
|
|
174
|
+
"-qr",
|
|
175
|
+
resolve(out, "function.zip"),
|
|
176
|
+
"."
|
|
177
|
+
],
|
|
178
|
+
cwd: funcDir,
|
|
179
|
+
stdout: "inherit",
|
|
180
|
+
stderr: "inherit"
|
|
181
|
+
}).exitCode !== 0) throw new Error("Lambda build: zip failed. Install the `zip` binary or deploy the function directory directly (CDK archives it for you).");
|
|
182
|
+
}
|
|
183
|
+
function hasBuildScript(root) {
|
|
184
|
+
const packageJsonPath = resolve(root, "package.json");
|
|
185
|
+
if (!existsSync(packageJsonPath)) return false;
|
|
186
|
+
try {
|
|
187
|
+
const { scripts } = JSON.parse(readFileSync(packageJsonPath, "utf8"));
|
|
188
|
+
return Boolean(scripts?.build);
|
|
189
|
+
} catch {
|
|
190
|
+
return false;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
function runAppBuild(root) {
|
|
194
|
+
if (!hasBuildScript(root)) {
|
|
195
|
+
console.warn("Lambda build: no \"build\" script in package.json — skipping the app build step.");
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
if (Bun.spawnSync({
|
|
199
|
+
cmd: [
|
|
200
|
+
"bun",
|
|
201
|
+
"run",
|
|
202
|
+
"build"
|
|
203
|
+
],
|
|
204
|
+
cwd: root,
|
|
205
|
+
stdout: "inherit",
|
|
206
|
+
stderr: "inherit"
|
|
207
|
+
}).exitCode !== 0) throw new Error("Lambda build: the app \"build\" script failed.");
|
|
208
|
+
}
|
|
209
|
+
/** Absolute path of the built SSR entry chunk, or undefined for CSR-only apps. */
|
|
210
|
+
function resolveSsrEntry(ssrDir, ssrEntryKey) {
|
|
211
|
+
const file = resolveSsrEntryFile(ssrDir, ssrEntryKey, "Lambda build");
|
|
212
|
+
if (!file) return;
|
|
213
|
+
if (!hasRendererExport(readFileSync(file, "utf8"))) throw new Error(`Lambda build: SSR entry ${file} does not export a renderer (expected a named "render" or default export).`);
|
|
214
|
+
return file;
|
|
215
|
+
}
|
|
216
|
+
function hasRendererExport(source) {
|
|
217
|
+
if (/export\s*\*\s*from/.test(source)) return true;
|
|
218
|
+
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);
|
|
219
|
+
}
|
|
220
|
+
//#endregion
|
|
221
|
+
export { buildLambdaOutput as t };
|
package/dist/cdk/index.d.ts
CHANGED
|
@@ -1,56 +1,56 @@
|
|
|
1
|
-
import { Duration } from
|
|
2
|
-
import * as apigwv2 from
|
|
3
|
-
import * as cloudfront from
|
|
4
|
-
import * as lambda from
|
|
5
|
-
import * as s3 from
|
|
6
|
-
import * as sqs from
|
|
7
|
-
import { Construct } from
|
|
8
|
-
|
|
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
|
+
//#region src/cdk/index.d.ts
|
|
9
9
|
interface GurenLambdaQueueProps {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
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
16
|
}
|
|
17
17
|
interface GurenLambdaScheduleProps {
|
|
18
|
-
|
|
19
|
-
|
|
18
|
+
/** How often the scheduler handler runs. Defaults to every minute. */
|
|
19
|
+
rate?: Duration;
|
|
20
20
|
}
|
|
21
21
|
interface GurenLambdaAssetsProps {
|
|
22
|
-
|
|
23
|
-
|
|
22
|
+
/** The staged assets directory produced by `guren lambda:build` (`.lambda/assets`). */
|
|
23
|
+
dir: string;
|
|
24
24
|
}
|
|
25
25
|
interface GurenLambdaDataApiProps {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
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
32
|
}
|
|
33
33
|
interface GurenLambdaAppProps {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
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
54
|
}
|
|
55
55
|
/**
|
|
56
56
|
* The full serverless topology for a Guren app in one construct: an HTTP API
|
|
@@ -69,16 +69,16 @@ interface GurenLambdaAppProps {
|
|
|
69
69
|
* ```
|
|
70
70
|
*/
|
|
71
71
|
declare class GurenLambdaApp extends Construct {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
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
82
|
}
|
|
83
|
-
|
|
84
|
-
export { GurenLambdaApp,
|
|
83
|
+
//#endregion
|
|
84
|
+
export { GurenLambdaApp, GurenLambdaAppProps, GurenLambdaAssetsProps, GurenLambdaDataApiProps, GurenLambdaQueueProps, GurenLambdaScheduleProps };
|
package/dist/cdk/index.js
CHANGED
|
@@ -1,10 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
} from "
|
|
4
|
-
|
|
5
|
-
// src/cdk/index.ts
|
|
6
|
-
import { existsSync, readdirSync, readFileSync } from "fs";
|
|
7
|
-
import { resolve } from "path";
|
|
1
|
+
import { r as lambdaHandlerId } from "../handlers-CkWGWQQX.js";
|
|
2
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
3
|
+
import { resolve } from "node:path";
|
|
8
4
|
import { CfnOutput, Duration } from "aws-cdk-lib";
|
|
9
5
|
import * as apigwv2 from "aws-cdk-lib/aws-apigatewayv2";
|
|
10
6
|
import { HttpLambdaIntegration } from "aws-cdk-lib/aws-apigatewayv2-integrations";
|
|
@@ -19,180 +15,170 @@ import * as s3 from "aws-cdk-lib/aws-s3";
|
|
|
19
15
|
import * as s3deploy from "aws-cdk-lib/aws-s3-deployment";
|
|
20
16
|
import * as sqs from "aws-cdk-lib/aws-sqs";
|
|
21
17
|
import { Construct } from "constructs";
|
|
18
|
+
//#region src/cdk/index.ts
|
|
19
|
+
/**
|
|
20
|
+
* The full serverless topology for a Guren app in one construct: an HTTP API
|
|
21
|
+
* in front of the `http` handler, and opt-in SQS/EventBridge/console wiring
|
|
22
|
+
* plus CloudFront + S3 for static assets. Handler names follow the module
|
|
23
|
+
* `guren lambda:build` emits (`handler.http`, `handler.queue`, ...).
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```typescript
|
|
27
|
+
* new GurenLambdaApp(this, 'App', {
|
|
28
|
+
* functionDir: '../.lambda/function',
|
|
29
|
+
* assets: { dir: '../.lambda/assets' },
|
|
30
|
+
* queue: {},
|
|
31
|
+
* environment: { DATABASE_NAME: 'appdb', DATABASE_RESOURCE_ARN: '...', DATABASE_SECRET_ARN: '...' },
|
|
32
|
+
* })
|
|
33
|
+
* ```
|
|
34
|
+
*/
|
|
22
35
|
var GurenLambdaApp = class extends Construct {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
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
|
-
}
|
|
36
|
+
httpFunction;
|
|
37
|
+
httpApi;
|
|
38
|
+
queue;
|
|
39
|
+
deadLetterQueue;
|
|
40
|
+
queueFunction;
|
|
41
|
+
scheduleFunction;
|
|
42
|
+
consoleFunction;
|
|
43
|
+
assetsBucket;
|
|
44
|
+
distribution;
|
|
45
|
+
constructor(scope, id, props) {
|
|
46
|
+
super(scope, id);
|
|
47
|
+
const functionDefaults = {
|
|
48
|
+
code: lambda.Code.fromAsset(props.functionDir),
|
|
49
|
+
runtime: props.runtime ?? lambda.Runtime.NODEJS_22_X,
|
|
50
|
+
memorySize: props.memorySize ?? 512,
|
|
51
|
+
environment: {
|
|
52
|
+
NODE_ENV: "production",
|
|
53
|
+
...dataApiEnvironment(props.dataApi),
|
|
54
|
+
...readBuildEnvironment(props.functionDir),
|
|
55
|
+
...props.environment
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
this.httpFunction = new lambda.Function(this, "Http", {
|
|
59
|
+
...functionDefaults,
|
|
60
|
+
handler: lambdaHandlerId("http"),
|
|
61
|
+
timeout: props.timeout ?? Duration.seconds(30)
|
|
62
|
+
});
|
|
63
|
+
this.httpApi = new apigwv2.HttpApi(this, "Api", { defaultIntegration: new HttpLambdaIntegration("HttpIntegration", this.httpFunction) });
|
|
64
|
+
if (props.queue) {
|
|
65
|
+
const workerTimeout = props.queue.timeout ?? Duration.seconds(60);
|
|
66
|
+
this.deadLetterQueue = new sqs.Queue(this, "JobDeadLetterQueue");
|
|
67
|
+
this.queue = new sqs.Queue(this, "JobQueue", {
|
|
68
|
+
visibilityTimeout: Duration.seconds(workerTimeout.toSeconds() * 6),
|
|
69
|
+
deadLetterQueue: {
|
|
70
|
+
queue: this.deadLetterQueue,
|
|
71
|
+
maxReceiveCount: props.queue.maxReceiveCount ?? 3
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
this.queueFunction = new lambda.Function(this, "QueueWorker", {
|
|
75
|
+
...functionDefaults,
|
|
76
|
+
handler: lambdaHandlerId("queue"),
|
|
77
|
+
timeout: workerTimeout
|
|
78
|
+
});
|
|
79
|
+
this.queueFunction.addEventSource(new SqsEventSource(this.queue, {
|
|
80
|
+
batchSize: props.queue.batchSize ?? 10,
|
|
81
|
+
reportBatchItemFailures: true
|
|
82
|
+
}));
|
|
83
|
+
}
|
|
84
|
+
if (props.schedule) {
|
|
85
|
+
this.scheduleFunction = new lambda.Function(this, "Scheduler", {
|
|
86
|
+
...functionDefaults,
|
|
87
|
+
handler: lambdaHandlerId("schedule"),
|
|
88
|
+
timeout: Duration.seconds(60)
|
|
89
|
+
});
|
|
90
|
+
new events.Rule(this, "ScheduleRule", {
|
|
91
|
+
schedule: events.Schedule.rate(props.schedule.rate ?? Duration.minutes(1)),
|
|
92
|
+
targets: [new targets.LambdaFunction(this.scheduleFunction)]
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
if (props.console) this.consoleFunction = new lambda.Function(this, "Console", {
|
|
96
|
+
...functionDefaults,
|
|
97
|
+
handler: lambdaHandlerId("console"),
|
|
98
|
+
timeout: Duration.minutes(5)
|
|
99
|
+
});
|
|
100
|
+
const functions = [
|
|
101
|
+
this.httpFunction,
|
|
102
|
+
this.queueFunction,
|
|
103
|
+
this.scheduleFunction,
|
|
104
|
+
this.consoleFunction
|
|
105
|
+
].filter((fn) => fn !== void 0);
|
|
106
|
+
if (this.queue) for (const fn of functions) {
|
|
107
|
+
fn.addEnvironment("SQS_QUEUE_URL", this.queue.queueUrl);
|
|
108
|
+
this.queue.grantSendMessages(fn);
|
|
109
|
+
}
|
|
110
|
+
if (props.dataApi) for (const fn of functions) {
|
|
111
|
+
fn.addToRolePolicy(new iam.PolicyStatement({
|
|
112
|
+
actions: [
|
|
113
|
+
"rds-data:ExecuteStatement",
|
|
114
|
+
"rds-data:BatchExecuteStatement",
|
|
115
|
+
"rds-data:BeginTransaction",
|
|
116
|
+
"rds-data:CommitTransaction",
|
|
117
|
+
"rds-data:RollbackTransaction"
|
|
118
|
+
],
|
|
119
|
+
resources: [props.dataApi.resourceArn]
|
|
120
|
+
}));
|
|
121
|
+
fn.addToRolePolicy(new iam.PolicyStatement({
|
|
122
|
+
actions: ["secretsmanager:GetSecretValue"],
|
|
123
|
+
resources: [props.dataApi.secretArn]
|
|
124
|
+
}));
|
|
125
|
+
}
|
|
126
|
+
if (props.assets) {
|
|
127
|
+
this.assetsBucket = new s3.Bucket(this, "Assets", {
|
|
128
|
+
blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL,
|
|
129
|
+
enforceSSL: true
|
|
130
|
+
});
|
|
131
|
+
const apiDomain = `${this.httpApi.apiId}.execute-api.${this.httpApi.stack.region}.${this.httpApi.stack.urlSuffix}`;
|
|
132
|
+
const assetBehavior = {
|
|
133
|
+
origin: origins.S3BucketOrigin.withOriginAccessControl(this.assetsBucket),
|
|
134
|
+
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
|
|
135
|
+
cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED
|
|
136
|
+
};
|
|
137
|
+
const additionalBehaviors = {
|
|
138
|
+
"/assets/*": assetBehavior,
|
|
139
|
+
"/public/*": assetBehavior
|
|
140
|
+
};
|
|
141
|
+
if (existsSync(props.assets.dir)) for (const entry of readdirSync(props.assets.dir, { withFileTypes: true })) {
|
|
142
|
+
if (entry.name === "assets" || entry.name === "public") continue;
|
|
143
|
+
additionalBehaviors[entry.isDirectory() ? `/${entry.name}/*` : `/${entry.name}`] = assetBehavior;
|
|
144
|
+
}
|
|
145
|
+
this.distribution = new cloudfront.Distribution(this, "Distribution", {
|
|
146
|
+
defaultBehavior: {
|
|
147
|
+
origin: new origins.HttpOrigin(apiDomain),
|
|
148
|
+
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
|
|
149
|
+
allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL,
|
|
150
|
+
cachePolicy: cloudfront.CachePolicy.CACHING_DISABLED,
|
|
151
|
+
originRequestPolicy: cloudfront.OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER
|
|
152
|
+
},
|
|
153
|
+
additionalBehaviors
|
|
154
|
+
});
|
|
155
|
+
new s3deploy.BucketDeployment(this, "AssetsDeployment", {
|
|
156
|
+
sources: [s3deploy.Source.asset(props.assets.dir)],
|
|
157
|
+
destinationBucket: this.assetsBucket,
|
|
158
|
+
distribution: this.distribution,
|
|
159
|
+
distributionPaths: ["/*"]
|
|
160
|
+
});
|
|
161
|
+
new CfnOutput(this, "DistributionUrl", { value: `https://${this.distribution.distributionDomainName}` });
|
|
162
|
+
}
|
|
163
|
+
new CfnOutput(this, "ApiUrl", { value: this.httpApi.apiEndpoint });
|
|
164
|
+
}
|
|
174
165
|
};
|
|
175
166
|
function dataApiEnvironment(dataApi) {
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
...dataApi.database ? { DATABASE_NAME: dataApi.database } : {}
|
|
183
|
-
};
|
|
167
|
+
if (!dataApi) return {};
|
|
168
|
+
return {
|
|
169
|
+
DATABASE_RESOURCE_ARN: dataApi.resourceArn,
|
|
170
|
+
DATABASE_SECRET_ARN: dataApi.secretArn,
|
|
171
|
+
...dataApi.database ? { DATABASE_NAME: dataApi.database } : {}
|
|
172
|
+
};
|
|
184
173
|
}
|
|
185
174
|
function readBuildEnvironment(functionDir) {
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
return {};
|
|
194
|
-
}
|
|
175
|
+
const envPath = resolve(functionDir, "../env.json");
|
|
176
|
+
if (!existsSync(envPath)) return {};
|
|
177
|
+
try {
|
|
178
|
+
return JSON.parse(readFileSync(envPath, "utf8"));
|
|
179
|
+
} catch {
|
|
180
|
+
return {};
|
|
181
|
+
}
|
|
195
182
|
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
};
|
|
183
|
+
//#endregion
|
|
184
|
+
export { GurenLambdaApp };
|
package/dist/commands.d.ts
CHANGED
|
@@ -1,20 +1,23 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
//#region src/commands.d.ts
|
|
3
2
|
declare const _default: {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
3
|
+
'lambda:build': import("citty").CommandDef<{
|
|
4
|
+
root: {
|
|
5
|
+
type: "string";
|
|
6
|
+
description: string;
|
|
7
|
+
};
|
|
8
|
+
'skip-app-build': {
|
|
9
|
+
type: "boolean";
|
|
10
|
+
description: string;
|
|
11
|
+
};
|
|
12
|
+
zip: {
|
|
13
|
+
type: "boolean";
|
|
14
|
+
description: string;
|
|
15
|
+
};
|
|
16
|
+
database: {
|
|
17
|
+
type: "string";
|
|
18
|
+
description: string;
|
|
19
|
+
};
|
|
20
|
+
}>;
|
|
18
21
|
};
|
|
19
|
-
|
|
20
|
-
export { _default as default };
|
|
22
|
+
//#endregion
|
|
23
|
+
export { _default as default };
|
package/dist/commands.js
CHANGED
|
@@ -1,40 +1,37 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
} from "./chunk-FVW2RWVN.js";
|
|
4
|
-
import "./chunk-K64F77DP.js";
|
|
5
|
-
|
|
6
|
-
// src/commands.ts
|
|
1
|
+
import { t as buildLambdaOutput } from "./build-56qBHosh.js";
|
|
2
|
+
import { DATABASE_DIALECTS, parseDatabaseDialects } from "@guren/core/internal/deploy-build";
|
|
7
3
|
import { defineCommand } from "citty";
|
|
8
|
-
var
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
};
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
4
|
+
var commands_default = { "lambda:build": defineCommand({
|
|
5
|
+
meta: {
|
|
6
|
+
name: "lambda:build",
|
|
7
|
+
description: "Assemble an AWS Lambda deployment (.lambda/) from the app build"
|
|
8
|
+
},
|
|
9
|
+
args: {
|
|
10
|
+
root: {
|
|
11
|
+
type: "string",
|
|
12
|
+
description: "App root directory (defaults to the current working directory)"
|
|
13
|
+
},
|
|
14
|
+
"skip-app-build": {
|
|
15
|
+
type: "boolean",
|
|
16
|
+
description: "Skip running the app's build script before assembling output"
|
|
17
|
+
},
|
|
18
|
+
zip: {
|
|
19
|
+
type: "boolean",
|
|
20
|
+
description: "Also produce .lambda/function.zip (requires the zip binary)"
|
|
21
|
+
},
|
|
22
|
+
database: {
|
|
23
|
+
type: "string",
|
|
24
|
+
description: `Databases this app connects to (comma-separated: ${DATABASE_DIALECTS.join(", ")}). Defaults to what config/database.ts declares; every other dialect's client is stubbed out of the bundle.`
|
|
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
|
+
databaseDialects: args.database ? parseDatabaseDialects(args.database, "Lambda build") : void 0
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
}) };
|
|
36
|
+
//#endregion
|
|
37
|
+
export { commands_default as default };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
//#region src/handlers.ts
|
|
2
|
+
/**
|
|
3
|
+
* The single source of truth tying the generated bundle to the
|
|
4
|
+
* infrastructure: `lambda:build` emits a `handler` module re-exporting these
|
|
5
|
+
* names, and the CDK construct maps them to Lambda handler identifiers.
|
|
6
|
+
*/
|
|
7
|
+
const LAMBDA_HANDLER_MODULE = "handler";
|
|
8
|
+
const LAMBDA_HANDLER_EXPORTS = [
|
|
9
|
+
"http",
|
|
10
|
+
"queue",
|
|
11
|
+
"schedule",
|
|
12
|
+
"console"
|
|
13
|
+
];
|
|
14
|
+
/** Lambda handler identifier for an export, e.g. `handler.http`. */
|
|
15
|
+
function lambdaHandlerId(name) {
|
|
16
|
+
return `${LAMBDA_HANDLER_MODULE}.${name}`;
|
|
17
|
+
}
|
|
18
|
+
//#endregion
|
|
19
|
+
export { LAMBDA_HANDLER_MODULE as n, lambdaHandlerId as r, LAMBDA_HANDLER_EXPORTS as t };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,27 +1,34 @@
|
|
|
1
|
-
import { ServiceProviderConstructor } from
|
|
2
|
-
import { PathLike } from
|
|
3
|
-
|
|
1
|
+
import { ServiceProviderConstructor } from "@guren/core";
|
|
2
|
+
import { DatabaseDialect, PathLike } from "@guren/core/internal/deploy-build";
|
|
3
|
+
//#region src/build.d.ts
|
|
4
4
|
interface BuildLambdaOutputOptions {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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
|
+
* Databases this app connects to, overriding what is read from
|
|
27
|
+
* `config/database.ts`. Every other dialect's client is stubbed out of the
|
|
28
|
+
* bundle. Pass this when the config reaches a factory without naming it and
|
|
29
|
+
* the build reports that it could not tell.
|
|
30
|
+
*/
|
|
31
|
+
databaseDialects?: readonly DatabaseDialect[];
|
|
25
32
|
}
|
|
26
33
|
/**
|
|
27
34
|
* Assemble a deployable AWS Lambda directory (`.lambda/`) from a built Guren
|
|
@@ -30,24 +37,25 @@ interface BuildLambdaOutputOptions {
|
|
|
30
37
|
* `env.json` with the environment the function expects.
|
|
31
38
|
*/
|
|
32
39
|
declare function buildLambdaOutput(options?: BuildLambdaOutputOptions): Promise<void>;
|
|
33
|
-
|
|
40
|
+
//#endregion
|
|
41
|
+
//#region src/handlers.d.ts
|
|
34
42
|
/**
|
|
35
43
|
* The single source of truth tying the generated bundle to the
|
|
36
44
|
* infrastructure: `lambda:build` emits a `handler` module re-exporting these
|
|
37
45
|
* names, and the CDK construct maps them to Lambda handler identifiers.
|
|
38
46
|
*/
|
|
39
47
|
declare const LAMBDA_HANDLER_MODULE = "handler";
|
|
40
|
-
declare const LAMBDA_HANDLER_EXPORTS: readonly [
|
|
48
|
+
declare const LAMBDA_HANDLER_EXPORTS: readonly ['http', 'queue', 'schedule', 'console'];
|
|
41
49
|
type LambdaHandlerExport = (typeof LAMBDA_HANDLER_EXPORTS)[number];
|
|
42
50
|
/** Lambda handler identifier for an export, e.g. `handler.http`. */
|
|
43
51
|
declare function lambdaHandlerId(name: LambdaHandlerExport): string;
|
|
44
|
-
|
|
52
|
+
//#endregion
|
|
53
|
+
//#region src/index.d.ts
|
|
45
54
|
/**
|
|
46
55
|
* Configuration for the Lambda plugin. Currently empty — reserved so future
|
|
47
56
|
* fields never force another registration-shape change.
|
|
48
57
|
*/
|
|
49
|
-
interface LambdaPluginConfig {
|
|
50
|
-
}
|
|
58
|
+
interface LambdaPluginConfig {}
|
|
51
59
|
/**
|
|
52
60
|
* Register the Lambda plugin.
|
|
53
61
|
*
|
|
@@ -57,5 +65,5 @@ interface LambdaPluginConfig {
|
|
|
57
65
|
* ```
|
|
58
66
|
*/
|
|
59
67
|
declare function lambdaPlugin(config?: LambdaPluginConfig): ServiceProviderConstructor;
|
|
60
|
-
|
|
61
|
-
export { type BuildLambdaOutputOptions, LAMBDA_HANDLER_EXPORTS, LAMBDA_HANDLER_MODULE, type LambdaHandlerExport,
|
|
68
|
+
//#endregion
|
|
69
|
+
export { type BuildLambdaOutputOptions, LAMBDA_HANDLER_EXPORTS, LAMBDA_HANDLER_MODULE, type LambdaHandlerExport, LambdaPluginConfig, buildLambdaOutput, lambdaHandlerId, lambdaPlugin };
|
package/dist/index.js
CHANGED
|
@@ -1,26 +1,21 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
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
|
|
1
|
+
import { n as LAMBDA_HANDLER_MODULE, r as lambdaHandlerId, t as LAMBDA_HANDLER_EXPORTS } from "./handlers-CkWGWQQX.js";
|
|
2
|
+
import { t as buildLambdaOutput } from "./build-56qBHosh.js";
|
|
11
3
|
import { definePlugin } from "@guren/core";
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
4
|
+
//#region src/index.ts
|
|
5
|
+
const factory = definePlugin({
|
|
6
|
+
name: "lambda",
|
|
7
|
+
register() {}
|
|
16
8
|
});
|
|
9
|
+
/**
|
|
10
|
+
* Register the Lambda plugin.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```typescript
|
|
14
|
+
* createApp({ providers: [lambdaPlugin()] })
|
|
15
|
+
* ```
|
|
16
|
+
*/
|
|
17
17
|
function lambdaPlugin(config = {}) {
|
|
18
|
-
|
|
18
|
+
return factory(config);
|
|
19
19
|
}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
LAMBDA_HANDLER_MODULE,
|
|
23
|
-
buildLambdaOutput,
|
|
24
|
-
lambdaHandlerId,
|
|
25
|
-
lambdaPlugin
|
|
26
|
-
};
|
|
20
|
+
//#endregion
|
|
21
|
+
export { LAMBDA_HANDLER_EXPORTS, LAMBDA_HANDLER_MODULE, buildLambdaOutput, lambdaHandlerId, lambdaPlugin };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@guren/plugin-lambda",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -40,12 +40,12 @@
|
|
|
40
40
|
}
|
|
41
41
|
},
|
|
42
42
|
"scripts": {
|
|
43
|
-
"build": "
|
|
43
|
+
"build": "bun --bun tsdown",
|
|
44
44
|
"test": "bun test",
|
|
45
45
|
"typecheck": "tsc --noEmit"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@guren/core": "^1.
|
|
48
|
+
"@guren/core": "^1.8.1",
|
|
49
49
|
"citty": "^0.1.6"
|
|
50
50
|
},
|
|
51
51
|
"peerDependencies": {
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
"@types/node": "^20.14.10",
|
|
65
65
|
"aws-cdk-lib": "^2.262.1",
|
|
66
66
|
"constructs": "^10.7.1",
|
|
67
|
-
"
|
|
68
|
-
"typescript": "^
|
|
67
|
+
"tsdown": "^0.22.14",
|
|
68
|
+
"typescript": "^7.0.2"
|
|
69
69
|
}
|
|
70
70
|
}
|
package/dist/chunk-FVW2RWVN.js
DELETED
|
@@ -1,244 +0,0 @@
|
|
|
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
|
-
};
|
package/dist/chunk-K64F77DP.js
DELETED
|
@@ -1,12 +0,0 @@
|
|
|
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
|
-
};
|