@guren/plugin-lambda 0.3.0 → 0.5.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 CHANGED
@@ -15,7 +15,7 @@ Installing registers a `lambda:build` command and scaffolds `src/lambda.ts` —
15
15
  bunx guren lambda:build
16
16
  ```
17
17
 
18
- `lambda:build` runs your app's `build` script, then assembles a `.lambda/` directory:
18
+ `lambda:build` runs the deploy-runtime checks `guren doctor` reports (a warning, never a failure, on an in-memory session or OAuth store, a `ScryptHasher`, or filesystem provider discovery), then your app's `build` script, then assembles a `.lambda/` directory:
19
19
 
20
20
  | Path | Contents |
21
21
  |------|----------|
@@ -1,18 +1,15 @@
1
- import { n as LAMBDA_HANDLER_MODULE, t as LAMBDA_HANDLER_EXPORTS } from "./handlers-CkWGWQQX.js";
1
+ import { n as LAMBDA_HANDLER_MODULE, t as LAMBDA_HANDLER_EXPORTS } from "./handlers-Dtt3k5Ue.js";
2
2
  import { cpSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
- import { DEV_ONLY_MODULES, MCP_SDK_SUBPATH_PREFIX, assertOutputDirOutsideRoot, clientManifestJson, importSpecifier, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, unusedSqlClients } from "@guren/core/internal/deploy-build";
4
+ import { MCP_SDK_SUBPATH_PREFIX, appUsesMcpPlugin, assertOutputDirOutsideRoot, clientManifestJson, importSpecifier, renderDevOnlyStub, resetOutputDir, resolveClientAssetEnv, resolvePathLike, resolveSsrEntryFile, ssrRuntimePaths, stageStaticAssets, stubbableDevOnlyModules, unusedSqlClients } from "@guren/core/internal/deploy-build";
5
+ import { reportDeployRuntimeHazards } from "@guren/core/internal/deploy-check";
5
6
  //#region src/build.ts
6
7
  const MCP_UNAVAILABLE = "The MCP endpoint is unavailable on AWS Lambda — it generates files on disk.";
7
8
  /**
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`.
9
+ * Why the dev-only modules in `DEV_ONLY_MODULES` cannot run here, each naming
10
+ * the Lambda-appropriate replacement. Keyed only on the kinds this platform
11
+ * stubs unconditionally: the SQL clients are load-bearing on Lambda, so which
12
+ * of those are dead weight is decided per app by `unusedSqlClients`.
16
13
  */
17
14
  const UNAVAILABLE_ON_LAMBDA = {
18
15
  sqlite: "bun:sqlite is unavailable on AWS Lambda — use createAwsDataApiDatabase() or createPostgresDatabase().",
@@ -20,51 +17,48 @@ const UNAVAILABLE_ON_LAMBDA = {
20
17
  mcp: MCP_UNAVAILABLE
21
18
  };
22
19
  /**
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.
20
+ * Stubs rather than externals: inlining a lazily-imported module hoists its
21
+ * static imports to the bundle top level, so an external reached that way (the
22
+ * MCP SDK) fails at import time though no code path runs it. An app declaring
23
+ * `@guren/plugin-mcp` serves the endpoint here, so its transport must reach the
24
+ * bundle (RFC 0016 §7) — `stubbableDevOnlyModules` owns that split.
31
25
  */
32
- const DEV_ONLY_STUBS = Object.fromEntries(DEV_ONLY_MODULES.map((module) => [module.specifier, renderDevOnlyStub(module, UNAVAILABLE_ON_LAMBDA[module.kind])]));
26
+ function devOnlyStubs(mcpPlugin) {
27
+ return Object.fromEntries(stubbableDevOnlyModules({ mcpPlugin }).map((module) => [module.specifier, renderDevOnlyStub(module, UNAVAILABLE_ON_LAMBDA[module.kind])]));
28
+ }
33
29
  /**
34
30
  * 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.
31
+ * through. A stub also *overrides* `external`, verified against Bun 1.3.14: the
32
+ * bundler consults plugins before the external list, so stubbing
33
+ * `@aws-sdk/client-rds-data` for a Postgres app really does replace drizzle's
34
+ * hoisted top-level import of it.
43
35
  */
44
- function stubsFor(root, dialects) {
36
+ function stubsFor(root, dialects, mcpPlugin) {
45
37
  const unused = unusedSqlClients({
46
38
  root,
47
39
  label: "Lambda build",
48
40
  dialects
49
41
  });
50
42
  return {
51
- ...DEV_ONLY_STUBS,
43
+ ...devOnlyStubs(mcpPlugin),
52
44
  ...Object.fromEntries(unused.map(({ module, message }) => [module.specifier, renderDevOnlyStub(module, message)]))
53
45
  };
54
46
  }
55
47
  /**
56
48
  * 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.
49
+ * know which names the importer destructures, so it throws on evaluation rather
50
+ * than handing back missing exports. Reachable only for an app that does *not*
51
+ * declare `@guren/plugin-mcp`, whose statically imported `server/index.js` and
52
+ * `types.js` it would otherwise stub shut — see `stubFilter`.
61
53
  */
62
54
  const unlistedMcpStub = `throw new Error(${JSON.stringify(MCP_UNAVAILABLE)})\n`;
63
55
  function escapeRegExp(value) {
64
56
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
65
57
  }
66
- function stubFilter(stubs) {
67
- return new RegExp(`^(?:${[...Object.keys(stubs).map(escapeRegExp), `${escapeRegExp(MCP_SDK_SUBPATH_PREFIX)}.+`].join("|")})$`);
58
+ function stubFilter(stubs, mcpPlugin) {
59
+ const terms = Object.keys(stubs).map(escapeRegExp);
60
+ if (!mcpPlugin) terms.push(`${escapeRegExp(MCP_SDK_SUBPATH_PREFIX)}.+`);
61
+ return new RegExp(`^(?:${terms.join("|")})$`);
68
62
  }
69
63
  /**
70
64
  * Assemble a deployable AWS Lambda directory (`.lambda/`) from a built Guren
@@ -82,6 +76,10 @@ async function buildLambdaOutput(options = {}) {
82
76
  const clientEntryKey = options.clientEntryKey ?? "resources/js/app.tsx";
83
77
  const ssrEntryKey = options.ssrEntryKey ?? "resources/js/ssr.tsx";
84
78
  assertOutputDirOutsideRoot(out, root, "Lambda build");
79
+ await reportDeployRuntimeHazards({
80
+ root,
81
+ label: "Lambda build"
82
+ });
85
83
  if (!options.skipAppBuild) runAppBuild(root);
86
84
  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
85
  const ssrFile = resolveSsrEntry(ssrDir, ssrEntryKey);
@@ -102,7 +100,8 @@ async function buildLambdaOutput(options = {}) {
102
100
  entrypoint,
103
101
  env: bakedEnv
104
102
  }));
105
- await bundleHandler(wrapperPath, funcDir, stubsFor(root, options.databaseDialects));
103
+ const mcpPlugin = appUsesMcpPlugin(root);
104
+ await bundleHandler(wrapperPath, funcDir, stubsFor(root, options.databaseDialects, mcpPlugin), mcpPlugin);
106
105
  writeFileSync(resolve(funcDir, "package.json"), `${JSON.stringify({ type: "module" }, null, 2)}\n`);
107
106
  if (ssrFile) cpSync(ssrDir, resolve(funcDir, ".guren/ssr"), { recursive: true });
108
107
  if (existsSync(migrationsDir)) cpSync(migrationsDir, resolve(funcDir, "db/migrations"), { recursive: true });
@@ -133,8 +132,8 @@ function renderHandlerModule(input) {
133
132
  lines.push("");
134
133
  return lines.join("\n");
135
134
  }
136
- async function bundleHandler(handlerEntry, funcDir, stubs) {
137
- const filter = stubFilter(stubs);
135
+ async function bundleHandler(handlerEntry, funcDir, stubs, mcpPlugin) {
136
+ const filter = stubFilter(stubs, mcpPlugin);
138
137
  const result = await Bun.build({
139
138
  entrypoints: [handlerEntry],
140
139
  throw: false,
@@ -53,20 +53,11 @@ interface GurenLambdaAppProps {
53
53
  dataApi?: GurenLambdaDataApiProps;
54
54
  }
55
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`, ...).
56
+ * The full serverless topology in one construct: an HTTP API in front of the
57
+ * `http` handler, opt-in SQS/EventBridge/console wiring, and CloudFront + S3
58
+ * assets. Handler names follow `guren lambda:build` (`handler.http`, ...).
60
59
  *
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
- * ```
60
+ * @example new GurenLambdaApp(this, 'App', { functionDir: '../.lambda/function' })
70
61
  */
71
62
  declare class GurenLambdaApp extends Construct {
72
63
  readonly httpFunction: lambda.Function;
package/dist/cdk/index.js CHANGED
@@ -1,6 +1,7 @@
1
- import { r as lambdaHandlerId } from "../handlers-CkWGWQQX.js";
1
+ import { r as lambdaHandlerId } from "../handlers-Dtt3k5Ue.js";
2
2
  import { existsSync, readFileSync, readdirSync } from "node:fs";
3
3
  import { resolve } from "node:path";
4
+ import { DOCUMENT_ASSET_EXTENSIONS, DOCUMENT_ASSET_HEADERS } from "@guren/core/internal/deploy-build";
4
5
  import { CfnOutput, Duration } from "aws-cdk-lib";
5
6
  import * as apigwv2 from "aws-cdk-lib/aws-apigatewayv2";
6
7
  import { HttpLambdaIntegration } from "aws-cdk-lib/aws-apigatewayv2-integrations";
@@ -17,20 +18,11 @@ import * as sqs from "aws-cdk-lib/aws-sqs";
17
18
  import { Construct } from "constructs";
18
19
  //#region src/cdk/index.ts
19
20
  /**
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`, ...).
21
+ * The full serverless topology in one construct: an HTTP API in front of the
22
+ * `http` handler, opt-in SQS/EventBridge/console wiring, and CloudFront + S3
23
+ * assets. Handler names follow `guren lambda:build` (`handler.http`, ...).
24
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
- * ```
25
+ * @example new GurenLambdaApp(this, 'App', { functionDir: '../.lambda/function' })
34
26
  */
35
27
  var GurenLambdaApp = class extends Construct {
36
28
  httpFunction;
@@ -129,10 +121,19 @@ var GurenLambdaApp = class extends Construct {
129
121
  enforceSSL: true
130
122
  });
131
123
  const apiDomain = `${this.httpApi.apiId}.execute-api.${this.httpApi.stack.region}.${this.httpApi.stack.urlSuffix}`;
124
+ const assetOrigin = origins.S3BucketOrigin.withOriginAccessControl(this.assetsBucket);
125
+ const documentGuard = new cloudfront.Function(this, "AssetDocumentGuard", {
126
+ code: cloudfront.FunctionCode.fromInline(renderAssetDocumentGuard()),
127
+ runtime: cloudfront.FunctionRuntime.JS_2_0
128
+ });
132
129
  const assetBehavior = {
133
- origin: origins.S3BucketOrigin.withOriginAccessControl(this.assetsBucket),
130
+ origin: assetOrigin,
134
131
  viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
135
- cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED
132
+ cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED,
133
+ functionAssociations: [{
134
+ function: documentGuard,
135
+ eventType: cloudfront.FunctionEventType.VIEWER_RESPONSE
136
+ }]
136
137
  };
137
138
  const additionalBehaviors = {
138
139
  "/assets/*": assetBehavior,
@@ -163,6 +164,58 @@ var GurenLambdaApp = class extends Construct {
163
164
  new CfnOutput(this, "ApiUrl", { value: this.httpApi.apiEndpoint });
164
165
  }
165
166
  };
167
+ /**
168
+ * CloudFront answers asset behaviours from S3 directly, so `guardStaticDocument`
169
+ * never sees these files and an SVG would render inline, script and all. A
170
+ * viewer-response function, not a cache behaviour per extension: those match by
171
+ * path, so `*.svg` would also capture a `/feed.svg` the *app* renders, and the
172
+ * limit of 25 is spent one per staged root entry. Lowercased, so `logo.SVG` too.
173
+ */
174
+ function renderAssetDocumentGuard() {
175
+ const headers = Object.fromEntries(Object.entries(DOCUMENT_ASSET_HEADERS).map(([name, value]) => [name.toLowerCase(), value]));
176
+ return [
177
+ `var DOCUMENT_EXTENSIONS = ${JSON.stringify(DOCUMENT_ASSET_EXTENSIONS)}`,
178
+ `var DOCUMENT_HEADERS = ${JSON.stringify(headers)}`,
179
+ "",
180
+ ASSET_DOCUMENT_GUARD_BODY
181
+ ].join("\n");
182
+ }
183
+ /**
184
+ * The function CloudFront runs, verbatim, reading the two constants
185
+ * {@link renderAssetDocumentGuard} declares above it. Free of interpolation on
186
+ * purpose: a `$` or a backtick in the JavaScript would change how the
187
+ * TypeScript reads, and as written the string is exactly the deployed program.
188
+ */
189
+ const ASSET_DOCUMENT_GUARD_BODY = `function handler(event) {
190
+ var uri = event.request.uri
191
+ var response = event.response
192
+
193
+ // Decoded first: CloudFront picks the behavior from a normalized path but
194
+ // hands the function the raw one, and S3 resolves percent-encoding when it
195
+ // matches a key. So /evil%2Esvg reaches the object evil.svg while the raw
196
+ // string holds no dot at all — the extension test would find nothing and
197
+ // the document would come back inline. A malformed sequence throws rather
198
+ // than decoding; the raw path is the safe thing to judge in that case,
199
+ // since it is also what no key will match.
200
+ try {
201
+ uri = decodeURIComponent(uri)
202
+ } catch (error) {
203
+ uri = event.request.uri
204
+ }
205
+
206
+ var dot = uri.lastIndexOf('.')
207
+
208
+ // A dot only ends the last segment when it follows the last slash: without
209
+ // the comparison, /v1.2/app reads as an extension of "2/app".
210
+ if (dot > uri.lastIndexOf('/') && DOCUMENT_EXTENSIONS.indexOf(uri.substring(dot + 1).toLowerCase()) !== -1) {
211
+ for (var name in DOCUMENT_HEADERS) {
212
+ response.headers[name] = { value: DOCUMENT_HEADERS[name] }
213
+ }
214
+ }
215
+
216
+ return response
217
+ }
218
+ `;
166
219
  function dataApiEnvironment(dataApi) {
167
220
  if (!dataApi) return {};
168
221
  return {
package/dist/commands.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as buildLambdaOutput } from "./build-BYE_vKGQ.js";
1
+ import { t as buildLambdaOutput } from "./build-Dn_V0LNZ.js";
2
2
  import { DATABASE_DIALECTS, parseDatabaseDialects } from "@guren/core/internal/deploy-build";
3
3
  import { defineCommand } from "citty";
4
4
  var commands_default = { "lambda:build": defineCommand({
@@ -11,7 +11,7 @@ const LAMBDA_HANDLER_EXPORTS = [
11
11
  "schedule",
12
12
  "console"
13
13
  ];
14
- /** Lambda handler identifier for an export, e.g. `handler.http`. */
14
+ /** Lambda handler identifier for an export. */
15
15
  function lambdaHandlerId(name) {
16
16
  return `${LAMBDA_HANDLER_MODULE}.${name}`;
17
17
  }
package/dist/index.d.ts CHANGED
@@ -47,7 +47,7 @@ declare function buildLambdaOutput(options?: BuildLambdaOutputOptions): Promise<
47
47
  declare const LAMBDA_HANDLER_MODULE = "handler";
48
48
  declare const LAMBDA_HANDLER_EXPORTS: readonly ['http', 'queue', 'schedule', 'console'];
49
49
  type LambdaHandlerExport = (typeof LAMBDA_HANDLER_EXPORTS)[number];
50
- /** Lambda handler identifier for an export, e.g. `handler.http`. */
50
+ /** Lambda handler identifier for an export. */
51
51
  declare function lambdaHandlerId(name: LambdaHandlerExport): string;
52
52
  //#endregion
53
53
  //#region src/index.d.ts
@@ -59,10 +59,7 @@ interface LambdaPluginConfig {}
59
59
  /**
60
60
  * Register the Lambda plugin.
61
61
  *
62
- * @example
63
- * ```typescript
64
- * createApp({ providers: [lambdaPlugin()] })
65
- * ```
62
+ * @example createApp({ providers: [lambdaPlugin()] })
66
63
  */
67
64
  declare function lambdaPlugin(config?: LambdaPluginConfig): ServiceProviderConstructor;
68
65
  //#endregion
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
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-BYE_vKGQ.js";
1
+ import { n as LAMBDA_HANDLER_MODULE, r as lambdaHandlerId, t as LAMBDA_HANDLER_EXPORTS } from "./handlers-Dtt3k5Ue.js";
2
+ import { t as buildLambdaOutput } from "./build-Dn_V0LNZ.js";
3
3
  import { definePlugin } from "@guren/core";
4
4
  //#region src/index.ts
5
5
  const factory = definePlugin({
@@ -9,10 +9,7 @@ const factory = definePlugin({
9
9
  /**
10
10
  * Register the Lambda plugin.
11
11
  *
12
- * @example
13
- * ```typescript
14
- * createApp({ providers: [lambdaPlugin()] })
15
- * ```
12
+ * @example createApp({ providers: [lambdaPlugin()] })
16
13
  */
17
14
  function lambdaPlugin(config = {}) {
18
15
  return factory(config);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/plugin-lambda",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -45,7 +45,7 @@
45
45
  "typecheck": "tsc --noEmit"
46
46
  },
47
47
  "dependencies": {
48
- "@guren/core": "^1.10.0",
48
+ "@guren/core": "^1.15.0",
49
49
  "citty": "^0.1.6"
50
50
  },
51
51
  "peerDependencies": {