effortless-aws 0.28.0 → 0.30.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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/config.ts","../src/handlers/define-table.ts","../src/handlers/define-app.ts","../src/handlers/define-static-site.ts","../src/handlers/define-fifo-queue.ts","../src/handlers/define-bucket.ts","../src/handlers/define-mailer.ts","../src/handlers/define-api.ts","../src/handlers/handler-options.ts","../src/handlers/auth.ts","../src/handlers/shared.ts"],"sourcesContent":["/**\n * Configuration for an Effortless project.\n *\n * @example\n * ```typescript\n * // effortless.config.ts\n * import { defineConfig } from \"effortless-aws\";\n *\n * export default defineConfig({\n * name: \"my-service\",\n * region: \"eu-central-1\",\n * handlers: \"src\",\n * });\n * ```\n */\nexport type EffortlessConfig = {\n /**\n * Project root directory. All relative paths (handlers, server, assets, etc.)\n * are resolved from this directory.\n * Resolved relative to where the CLI runs (process.cwd()).\n * @default \".\" (current working directory)\n */\n root?: string;\n\n /**\n * Project name used for resource naming and tagging.\n * This becomes part of Lambda function names, IAM roles, etc.\n */\n name: string;\n\n /**\n * Default AWS region for all handlers.\n * Can be overridden per-handler or via CLI `--region` flag.\n * @default \"eu-central-1\"\n */\n region?: string;\n\n /**\n * Deployment stage (e.g., \"dev\", \"staging\", \"prod\").\n * Used for resource isolation and tagging.\n * @default \"dev\"\n */\n stage?: string;\n\n /**\n * Glob patterns or directory paths to scan for handlers.\n * Used by `eff deploy` (without file argument) to auto-discover handlers.\n *\n * @example\n * ```typescript\n * // Single directory - scans for all .ts files\n * handlers: \"src\"\n *\n * // Glob patterns\n * handlers: [\"src/**\\/*.ts\", \"lib/**\\/*.handler.ts\"]\n * ```\n */\n handlers?: string | string[];\n\n /**\n * Default Lambda settings applied to all handlers unless overridden.\n *\n * All Lambdas run on ARM64 (Graviton2) architecture — ~20% cheaper than x86_64\n * with better price-performance for most workloads.\n */\n lambda?: {\n /**\n * Lambda memory in MB. AWS allocates proportional CPU —\n * 1769 MB gives one full vCPU.\n * @default 256\n */\n memory?: number;\n\n /**\n * Lambda timeout as a human-readable string.\n * AWS maximum is 15 minutes.\n * @example \"30 seconds\", \"5 minutes\"\n */\n timeout?: string;\n\n /**\n * Node.js Lambda runtime version.\n * @default \"nodejs24.x\"\n */\n runtime?: string;\n };\n\n};\n\n/**\n * Helper function for type-safe configuration.\n * Returns the config object as-is, but provides TypeScript autocompletion.\n *\n * @example\n * ```typescript\n * import { defineConfig } from \"effortless-aws\";\n *\n * export default defineConfig({\n * name: \"my-service\",\n * region: \"eu-central-1\",\n * handlers: \"src\",\n * });\n * ```\n */\nexport const defineConfig = (config: EffortlessConfig): EffortlessConfig => config;\n","import type { LambdaWithPermissions, AnyParamRef, ResolveConfig, TableItem, Duration } from \"./handler-options\";\nimport type { TableClient } from \"../runtime/table-client\";\nimport type { AnyDepHandler, ResolveDeps } from \"./handler-deps\";\nimport type { StaticFiles } from \"./shared\";\nimport type { HandlerArgs } from \"./handler-args\";\n\n/** DynamoDB attribute types for keys */\nexport type KeyType = \"string\" | \"number\" | \"binary\";\n\n/**\n * DynamoDB table key definition\n */\nexport type TableKey = {\n /** Attribute name */\n name: string;\n /** Attribute type */\n type: KeyType;\n};\n\n/** DynamoDB Streams view type - determines what data is captured in stream records */\nexport type StreamView = \"NEW_AND_OLD_IMAGES\" | \"NEW_IMAGE\" | \"OLD_IMAGE\" | \"KEYS_ONLY\";\n\n/**\n * Configuration options for defineTable (single-table design).\n *\n * Tables always use `pk (S)` + `sk (S)` keys, `tag (S)` discriminator,\n * `data (M)` for domain fields, and `ttl (N)` for optional expiration.\n */\nexport type TableConfig = {\n /** Lambda function settings (memory, timeout, permissions, etc.) */\n lambda?: LambdaWithPermissions;\n /** DynamoDB billing mode (default: \"PAY_PER_REQUEST\") */\n billingMode?: \"PAY_PER_REQUEST\" | \"PROVISIONED\";\n /** Stream view type - what data to include in stream records (default: \"NEW_AND_OLD_IMAGES\") */\n streamView?: StreamView;\n /** Number of records to process in each Lambda invocation (1-10000, default: 100) */\n batchSize?: number;\n /** Maximum time to gather records before invoking (default: `\"2s\"`). Accepts `\"5s\"`, `\"1m\"`, etc. */\n batchWindow?: Duration;\n /** Where to start reading the stream (default: \"LATEST\") */\n startingPosition?: \"LATEST\" | \"TRIM_HORIZON\";\n /**\n * Name of the field in `data` that serves as the entity type discriminant.\n * Effortless auto-copies `data[tagField]` to the top-level DynamoDB `tag` attribute on `put()`.\n * Defaults to `\"tag\"`.\n *\n * @example\n * ```typescript\n * export const orders = defineTable<{ type: \"order\"; amount: number }>({\n * tagField: \"type\",\n * onRecord: async ({ record }) => { ... }\n * });\n * ```\n */\n tagField?: string;\n};\n\n/**\n * DynamoDB stream record passed to onRecord callback.\n *\n * `new` and `old` are full `TableItem<T>` objects with the single-table envelope.\n *\n * @typeParam T - Type of the domain data (inside `data`)\n */\nexport type TableRecord<T = Record<string, unknown>> = {\n /** Type of modification: INSERT, MODIFY, or REMOVE */\n eventName: \"INSERT\" | \"MODIFY\" | \"REMOVE\";\n /** New item value (present for INSERT and MODIFY) */\n new?: TableItem<T>;\n /** Old item value (present for MODIFY and REMOVE) */\n old?: TableItem<T>;\n /** Primary key of the affected item */\n keys: { pk: string; sk: string };\n /** Sequence number for ordering */\n sequenceNumber?: string;\n /** Approximate timestamp when the modification occurred */\n timestamp?: number;\n};\n\n/**\n * Information about a failed record during batch processing\n *\n * @typeParam T - Type of the domain data\n */\nexport type FailedRecord<T = Record<string, unknown>> = {\n /** The record that failed to process */\n record: TableRecord<T>;\n /** The error that occurred */\n error: unknown;\n};\n\n/**\n * Setup factory type for table handlers.\n * Always receives `table: TableClient<T>` (self-client for the handler's own table).\n * Also receives `deps` and/or `config` when declared.\n */\ntype SetupFactory<C, T, D, P, S extends string[] | undefined = undefined> = (args:\n & { table: TableClient<T> }\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { config: ResolveConfig<P & {}> })\n & ([S] extends [undefined] ? {} : { files: StaticFiles })\n ) => C | Promise<C>;\n\n/**\n * Callback function type for processing a single DynamoDB stream record\n */\nexport type TableRecordFn<T = Record<string, unknown>, C = undefined, R = void, D = undefined, P = undefined, S extends string[] | undefined = undefined> =\n (args: { record: TableRecord<T>; table: TableClient<T> }\n & HandlerArgs<C, D, P, S>\n ) => Promise<R>;\n\n/**\n * Callback function type for processing accumulated batch results\n */\nexport type TableBatchCompleteFn<T = Record<string, unknown>, C = undefined, R = void, D = undefined, P = undefined, S extends string[] | undefined = undefined> =\n (args: { results: R[]; failures: FailedRecord<T>[]; table: TableClient<T> }\n & HandlerArgs<C, D, P, S>\n ) => Promise<void>;\n\n/**\n * Callback function type for processing all records in a batch at once\n */\nexport type TableBatchFn<T = Record<string, unknown>, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> =\n (args: { records: TableRecord<T>[]; table: TableClient<T> }\n & HandlerArgs<C, D, P, S>\n ) => Promise<void>;\n\n/** Base options shared by all defineTable variants */\ntype DefineTableBase<T = Record<string, unknown>, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = Omit<TableConfig, \"tagField\"> & {\n /** Name of the field in `data` that serves as the entity type discriminant (default: `\"tag\"`). */\n tagField?: Extract<keyof T, string>;\n /**\n * Decode/validate function for the `data` portion of stream record items.\n * Called with the unmarshalled `data` attribute; should return typed data or throw on validation failure.\n * When provided, T is inferred from the return type — no need to specify generic parameters.\n */\n schema?: (input: unknown) => T;\n /**\n * Error handler called when onRecord, onBatch, or onBatchComplete throws.\n * Receives the error. If not provided, defaults to `console.error`.\n */\n onError?: (args: { error: unknown } & HandlerArgs<C, D, P, S>) => void;\n /** Called after each invocation completes, right before Lambda freezes the process */\n onAfterInvoke?: (args: HandlerArgs<C, D, P, S>) => void | Promise<void>;\n /**\n * Factory function to initialize shared state for callbacks.\n * Called once on cold start, result is cached and reused across invocations.\n * When deps/params are declared, receives them as argument.\n * Supports both sync and async return values.\n */\n setup?: SetupFactory<C, T, D, P, S>;\n /**\n * Dependencies on other handlers (tables, queues, etc.).\n * Typed clients are injected into the handler via the `deps` argument.\n * Pass a function returning the deps object: `deps: () => ({ orders })`.\n */\n deps?: () => D & {};\n /**\n * SSM Parameter Store parameters.\n * Declare with `param()` helper. Values are fetched and cached at cold start.\n * Typed values are injected into the handler via the `config` argument.\n */\n config?: P;\n /**\n * Static file glob patterns to bundle into the Lambda ZIP.\n * Files are accessible at runtime via the `files` callback argument.\n */\n static?: S;\n};\n\n/** Per-record processing: onRecord with optional onBatchComplete */\ntype DefineTableWithOnRecord<T = Record<string, unknown>, C = undefined, R = void, D = undefined, P = undefined, S extends string[] | undefined = undefined> = DefineTableBase<T, C, D, P, S> & {\n onRecord: TableRecordFn<T, C, R, D, P, S>;\n onBatchComplete?: TableBatchCompleteFn<T, C, R, D, P, S>;\n onBatch?: never;\n};\n\n/** Batch processing: onBatch processes all records at once */\ntype DefineTableWithOnBatch<T = Record<string, unknown>, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = DefineTableBase<T, C, D, P, S> & {\n onBatch: TableBatchFn<T, C, D, P, S>;\n onRecord?: never;\n onBatchComplete?: never;\n};\n\n/** Resource-only: no handler, just creates the table */\ntype DefineTableResourceOnly<T = Record<string, unknown>, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = DefineTableBase<T, C, D, P, S> & {\n onRecord?: never;\n onBatch?: never;\n onBatchComplete?: never;\n};\n\nexport type DefineTableOptions<\n T = Record<string, unknown>,\n C = undefined,\n R = void,\n D extends Record<string, AnyDepHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined,\n S extends string[] | undefined = undefined\n> =\n | DefineTableWithOnRecord<T, C, R, D, P, S>\n | DefineTableWithOnBatch<T, C, D, P, S>\n | DefineTableResourceOnly<T, C, D, P, S>;\n\n/**\n * Internal handler object created by defineTable\n * @internal\n */\nexport type TableHandler<T = Record<string, unknown>, C = any> = {\n readonly __brand: \"effortless-table\";\n readonly __spec: TableConfig;\n readonly schema?: (input: unknown) => T;\n readonly onError?: (...args: any[]) => any;\n readonly onAfterInvoke?: (...args: any[]) => any;\n readonly setup?: (...args: any[]) => C | Promise<C>;\n readonly deps?: Record<string, unknown> | (() => Record<string, unknown>);\n readonly config?: Record<string, unknown>;\n readonly static?: string[];\n readonly onRecord?: (...args: any[]) => any;\n readonly onBatchComplete?: (...args: any[]) => any;\n readonly onBatch?: (...args: any[]) => any;\n};\n\n/**\n * Define a DynamoDB table with optional stream handler (single-table design).\n *\n * Creates a table with fixed key schema: `pk (S)` + `sk (S)`, plus `tag (S)`,\n * `data (M)`, and `ttl (N)` attributes. TTL is always enabled.\n *\n * @example Table with stream handler\n * ```typescript\n * type OrderData = { amount: number; status: string };\n *\n * export const orders = defineTable<OrderData>({\n * streamView: \"NEW_AND_OLD_IMAGES\",\n * batchSize: 10,\n * onRecord: async ({ record }) => {\n * if (record.eventName === \"INSERT\") {\n * console.log(\"New order:\", record.new?.data.amount);\n * }\n * }\n * });\n * ```\n *\n * @example Table only (no Lambda)\n * ```typescript\n * export const users = defineTable({});\n * ```\n */\nexport const defineTable = <\n T = Record<string, unknown>,\n C = undefined,\n R = void,\n D extends Record<string, AnyDepHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined,\n S extends string[] | undefined = undefined\n>(\n options: DefineTableOptions<T, C, R, D, P, S>\n): TableHandler<T, C> => {\n const { onRecord, onBatchComplete, onBatch, onError, onAfterInvoke, schema, setup, deps, config, static: staticFiles, ...__spec } = options;\n return {\n __brand: \"effortless-table\",\n __spec,\n ...(schema ? { schema } : {}),\n ...(onError ? { onError } : {}),\n ...(onAfterInvoke ? { onAfterInvoke } : {}),\n ...(setup ? { setup } : {}),\n ...(deps ? { deps } : {}),\n ...(config ? { config } : {}),\n ...(staticFiles ? { static: staticFiles } : {}),\n ...(onRecord ? { onRecord } : {}),\n ...(onBatchComplete ? { onBatchComplete } : {}),\n ...(onBatch ? { onBatch } : {})\n } as TableHandler<T, C>;\n};\n","import type { LambdaWithPermissions } from \"./handler-options\";\n\n/**\n * Configuration for deploying an SSR framework (Nuxt, Astro, etc.)\n * via CloudFront + S3 (static assets) + Lambda Function URL (server-side rendering).\n */\nexport type AppConfig = {\n /** Lambda function settings (memory, timeout, permissions, etc.) */\n lambda?: LambdaWithPermissions;\n /** Directory containing the Lambda server handler (e.g., \".output/server\").\n * Must contain an `index.mjs` (or `index.js`) that exports a `handler` function. */\n server: string;\n /** Directory containing static assets for S3 (e.g., \".output/public\") */\n assets: string;\n /** Base URL path (default: \"/\") */\n path?: string;\n /** Shell command to build the framework output (e.g., \"nuxt build\") */\n build?: string;\n /** Custom domain name. String or stage-keyed record (e.g., { prod: \"app.example.com\" }). */\n domain?: string | Record<string, string>;\n /** CloudFront route overrides: path patterns forwarded to API Gateway instead of the SSR Lambda.\n * Keys are CloudFront path patterns (e.g., \"/api/*\"), values are handler references.\n * Example: `routes: { \"/api/*\": api }` */\n routes?: Record<string, { readonly __brand: string }>;\n};\n\n/**\n * Internal handler object created by defineApp\n * @internal\n */\nexport type AppHandler = {\n readonly __brand: \"effortless-app\";\n readonly __spec: AppConfig;\n};\n\n/**\n * Deploy an SSR framework application via CloudFront + Lambda Function URL.\n *\n * Static assets from the `assets` directory are served via S3 + CloudFront CDN.\n * Server-rendered pages are handled by a Lambda function using the framework's\n * built output from the `server` directory.\n *\n * For static-only sites (no SSR), use {@link defineStaticSite} instead.\n *\n * @param options - App configuration: server directory, assets directory, optional build command\n * @returns Handler object used by the deployment system\n *\n * @example Nuxt SSR\n * ```typescript\n * export const app = defineApp({\n * build: \"nuxt build\",\n * server: \".output/server\",\n * assets: \".output/public\",\n * lambda: { memory: 1024 },\n * });\n * ```\n */\nexport const defineApp = (options: AppConfig): AppHandler => ({\n __brand: \"effortless-app\",\n __spec: options,\n});\n","import type { Auth } from \"./auth\";\n\n/** Any branded handler that deploys to API Gateway (HttpHandler, ApiHandler, etc.) */\ntype AnyRoutableHandler = { readonly __brand: string };\n\n/** Simplified request object passed to middleware */\nexport type MiddlewareRequest = {\n uri: string;\n method: string;\n querystring: string;\n headers: Record<string, string>;\n cookies: Record<string, string>;\n};\n\n/** Redirect the user to another URL */\nexport type MiddlewareRedirect = {\n redirect: string;\n status?: 301 | 302 | 307 | 308;\n};\n\n/** Deny access with a 403 status */\nexport type MiddlewareDeny = {\n status: 403;\n body?: string;\n};\n\n/** Middleware return type: redirect, deny, or void (continue serving) */\nexport type MiddlewareResult = MiddlewareRedirect | MiddlewareDeny | void;\n\n/** Function that runs before serving static files via Lambda@Edge */\nexport type MiddlewareHandler = (\n request: MiddlewareRequest\n) => Promise<MiddlewareResult> | MiddlewareResult;\n\n/** SEO options for auto-generating sitemap.xml, robots.txt, and submitting to Google Indexing API */\nexport type StaticSiteSeo = {\n /** Sitemap filename (e.g. \"sitemap.xml\", \"sitemap-v2.xml\") */\n sitemap: string;\n /** Path to Google service account JSON key file for Indexing API batch submission.\n * Requires adding the service account email as an owner in Google Search Console. */\n googleIndexing?: string;\n};\n\n/**\n * Configuration for a static site handler (S3 + CloudFront)\n */\nexport type StaticSiteConfig = {\n /** Handler name. Defaults to export name if not specified */\n name?: string;\n /** Directory containing the static site files, relative to project root */\n dir: string;\n /** Default file for directory requests (default: \"index.html\") */\n index?: string;\n /** SPA mode: serve index.html for all paths that don't match a file (default: false) */\n spa?: boolean;\n /** Shell command to run before deploy to generate site content (e.g., \"npx astro build\") */\n build?: string;\n /** Custom domain name. Accepts a string (same domain for all stages) or a Record mapping stage names to domains (e.g., `{ prod: \"example.com\", dev: \"dev.example.com\" }`). Requires an ACM certificate in us-east-1. If the cert also covers www, a 301 redirect from www to non-www is set up automatically. */\n domain?: string | Record<string, string>;\n /** CloudFront route overrides: path patterns forwarded to API Gateway instead of S3.\n * Keys are CloudFront path patterns (e.g., \"/api/*\"), values are HTTP handlers.\n * Example: `routes: { \"/api/*\": api }` */\n routes?: Record<string, AnyRoutableHandler>;\n /** Custom 404 error page path relative to `dir` (e.g. \"404.html\").\n * For non-SPA sites only. If not set, a default page is generated automatically. */\n errorPage?: string;\n /** Lambda@Edge middleware that runs before serving pages. Use for auth checks, redirects, etc. */\n middleware?: MiddlewareHandler;\n /** Cookie-based authentication. Auto-generates Lambda@Edge middleware that verifies signed cookies. */\n auth?: Auth<any>;\n /** SEO: auto-generate sitemap.xml and robots.txt at deploy time, optionally submit URLs to Google Indexing API */\n seo?: StaticSiteSeo;\n};\n\n/**\n * Internal handler object created by defineStaticSite\n * @internal\n */\nexport type StaticSiteHandler = {\n readonly __brand: \"effortless-static-site\";\n readonly __spec: StaticSiteConfig;\n};\n\n/**\n * Deploy a static site via S3 + CloudFront CDN.\n *\n * @param options - Static site configuration: directory, optional SPA mode, build command\n * @returns Handler object used by the deployment system\n *\n * @example Documentation site\n * ```typescript\n * export const docs = defineStaticSite({\n * dir: \"dist\",\n * build: \"npx astro build\",\n * });\n * ```\n *\n * @example SPA with client-side routing\n * ```typescript\n * export const app = defineStaticSite({\n * dir: \"dist\",\n * spa: true,\n * build: \"npm run build\",\n * });\n * ```\n *\n * @example Protected site with middleware (Lambda@Edge)\n * ```typescript\n * export const admin = defineStaticSite({\n * dir: \"admin/dist\",\n * middleware: async (request) => {\n * if (!request.cookies.session) {\n * return { redirect: \"/login\" };\n * }\n * },\n * });\n * ```\n */\nexport const defineStaticSite = (options: StaticSiteConfig): StaticSiteHandler => ({\n __brand: \"effortless-static-site\",\n __spec: options,\n});\n","import type { LambdaWithPermissions, AnyParamRef, ResolveConfig, Duration } from \"./handler-options\";\nimport type { AnyDepHandler, ResolveDeps } from \"./handler-deps\";\nimport type { StaticFiles } from \"./shared\";\nimport type { HandlerArgs } from \"./handler-args\";\n\n/**\n * Parsed SQS FIFO message passed to the handler callbacks.\n *\n * @typeParam T - Type of the decoded message body (from schema function)\n */\nexport type FifoQueueMessage<T = unknown> = {\n /** Unique message identifier */\n messageId: string;\n /** Receipt handle for acknowledgement */\n receiptHandle: string;\n /** Parsed message body (JSON-decoded, then optionally schema-validated) */\n body: T;\n /** Raw unparsed message body string */\n rawBody: string;\n /** Message group ID (FIFO ordering key) */\n messageGroupId: string;\n /** Message deduplication ID */\n messageDeduplicationId?: string;\n /** SQS message attributes */\n messageAttributes: Record<string, { dataType?: string; stringValue?: string }>;\n /** Approximate first receive timestamp */\n approximateFirstReceiveTimestamp?: string;\n /** Approximate receive count */\n approximateReceiveCount?: string;\n /** Sent timestamp */\n sentTimestamp?: string;\n};\n\n/**\n * Configuration options for a FIFO queue handler\n */\nexport type FifoQueueConfig = {\n /** Lambda function settings (memory, timeout, permissions, etc.) */\n lambda?: LambdaWithPermissions;\n /** Number of messages per Lambda invocation (1-10 for FIFO, default: 10) */\n batchSize?: number;\n /** Maximum time to gather messages before invoking (default: 0). Accepts `\"5s\"`, `\"1m\"`, etc. */\n batchWindow?: Duration;\n /** Visibility timeout (default: max of timeout or 30s). Accepts `\"30s\"`, `\"5m\"`, etc. */\n visibilityTimeout?: Duration;\n /** Message retention period (default: `\"4d\"`). Accepts `\"1h\"`, `\"7d\"`, etc. */\n retentionPeriod?: Duration;\n /** Delivery delay for all messages in the queue (default: 0). Accepts `\"30s\"`, `\"5m\"`, etc. */\n delay?: Duration;\n /** Enable content-based deduplication (default: true) */\n contentBasedDeduplication?: boolean;\n /** Max number of receives before a message is sent to the dead-letter queue (default: 3) */\n maxReceiveCount?: number;\n};\n\n/**\n * Setup factory type — always receives an args object.\n * Args include `deps` and/or `config` when declared (empty `{}` otherwise).\n */\ntype SetupFactory<C, D, P, S extends string[] | undefined = undefined> =\n (args:\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { config: ResolveConfig<P & {}> })\n & ([S] extends [undefined] ? {} : { files: StaticFiles })\n ) => C | Promise<C>;\n\n/**\n * Per-message handler function.\n * Called once per message in the batch. Failures are reported individually.\n */\nexport type FifoQueueMessageFn<T = unknown, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> =\n (args: { message: FifoQueueMessage<T> }\n & HandlerArgs<C, D, P, S>\n ) => Promise<void>;\n\n/**\n * Batch handler function.\n * Called once with all messages in the batch.\n */\nexport type FifoQueueBatchFn<T = unknown, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> =\n (args: { messages: FifoQueueMessage<T>[] }\n & HandlerArgs<C, D, P, S>\n ) => Promise<void>;\n\n/** Base options shared by all defineFifoQueue variants */\ntype DefineFifoQueueBase<T = unknown, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = FifoQueueConfig & {\n /**\n * Decode/validate function for the message body.\n * Called with the JSON-parsed body; should return typed data or throw on validation failure.\n */\n schema?: (input: unknown) => T;\n /**\n * Error handler called when onMessage or onBatch throws.\n * If not provided, defaults to `console.error`.\n */\n onError?: (args: { error: unknown } & HandlerArgs<C, D, P, S>) => void;\n /** Called after each invocation completes, right before Lambda freezes the process */\n onAfterInvoke?: (args: HandlerArgs<C, D, P, S>) => void | Promise<void>;\n /**\n * Factory function to initialize shared state for the handler.\n * Called once on cold start, result is cached and reused across invocations.\n * When deps/params are declared, receives them as argument.\n */\n setup?: SetupFactory<C, D, P, S>;\n /**\n * Dependencies on other handlers (tables, queues, etc.).\n * Typed clients are injected into the handler via the `deps` argument.\n * Pass a function returning the deps object: `deps: () => ({ orders })`.\n */\n deps?: () => D & {};\n /**\n * SSM Parameter Store parameters.\n * Declare with `param()` helper. Values are fetched and cached at cold start.\n */\n config?: P;\n /**\n * Static file glob patterns to bundle into the Lambda ZIP.\n * Files are accessible at runtime via the `files` callback argument.\n */\n static?: S;\n};\n\n/** Per-message processing */\ntype DefineFifoQueueWithOnMessage<T = unknown, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = DefineFifoQueueBase<T, C, D, P, S> & {\n onMessage: FifoQueueMessageFn<T, C, D, P, S>;\n onBatch?: never;\n};\n\n/** Batch processing: all messages at once */\ntype DefineFifoQueueWithOnBatch<T = unknown, C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = DefineFifoQueueBase<T, C, D, P, S> & {\n onBatch: FifoQueueBatchFn<T, C, D, P, S>;\n onMessage?: never;\n};\n\nexport type DefineFifoQueueOptions<\n T = unknown,\n C = undefined,\n D extends Record<string, AnyDepHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined,\n S extends string[] | undefined = undefined\n> =\n | DefineFifoQueueWithOnMessage<T, C, D, P, S>\n | DefineFifoQueueWithOnBatch<T, C, D, P, S>;\n\n/**\n * Internal handler object created by defineFifoQueue\n * @internal\n */\nexport type FifoQueueHandler<T = unknown, C = any> = {\n readonly __brand: \"effortless-fifo-queue\";\n readonly __spec: FifoQueueConfig;\n readonly schema?: (input: unknown) => T;\n readonly onError?: (...args: any[]) => any;\n readonly onAfterInvoke?: (...args: any[]) => any;\n readonly setup?: (...args: any[]) => C | Promise<C>;\n readonly deps?: Record<string, unknown> | (() => Record<string, unknown>);\n readonly config?: Record<string, unknown>;\n readonly static?: string[];\n readonly onMessage?: (...args: any[]) => any;\n readonly onBatch?: (...args: any[]) => any;\n};\n\n/**\n * Define a FIFO SQS queue with a Lambda message handler\n *\n * Creates:\n * - SQS FIFO queue (with `.fifo` suffix)\n * - Lambda function triggered by the queue\n * - Event source mapping with partial batch failure support\n *\n * @example Per-message processing\n * ```typescript\n * type OrderEvent = { orderId: string; action: string };\n *\n * export const orderQueue = defineFifoQueue<OrderEvent>({\n * onMessage: async ({ message }) => {\n * console.log(\"Processing order:\", message.body.orderId);\n * }\n * });\n * ```\n *\n * @example Batch processing with schema\n * ```typescript\n * export const notifications = defineFifoQueue({\n * schema: (input) => NotificationSchema.parse(input),\n * batchSize: 5,\n * onBatch: async ({ messages }) => {\n * await sendAll(messages.map(m => m.body));\n * }\n * });\n * ```\n */\nexport const defineFifoQueue = <\n T = unknown,\n C = undefined,\n D extends Record<string, AnyDepHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined,\n S extends string[] | undefined = undefined\n>(\n options: DefineFifoQueueOptions<T, C, D, P, S>\n): FifoQueueHandler<T, C> => {\n const { onMessage, onBatch, onError, onAfterInvoke, schema, setup, deps, config, static: staticFiles, ...__spec } = options;\n return {\n __brand: \"effortless-fifo-queue\",\n __spec,\n ...(schema ? { schema } : {}),\n ...(onError ? { onError } : {}),\n ...(onAfterInvoke ? { onAfterInvoke } : {}),\n ...(setup ? { setup } : {}),\n ...(deps ? { deps } : {}),\n ...(config ? { config } : {}),\n ...(staticFiles ? { static: staticFiles } : {}),\n ...(onMessage ? { onMessage } : {}),\n ...(onBatch ? { onBatch } : {})\n } as FifoQueueHandler<T, C>;\n};\n","import type { LambdaWithPermissions, AnyParamRef, ResolveConfig } from \"./handler-options\";\nimport type { AnyDepHandler, ResolveDeps } from \"./handler-deps\";\nimport type { StaticFiles } from \"./shared\";\nimport type { BucketClient } from \"../runtime/bucket-client\";\nimport type { HandlerArgs } from \"./handler-args\";\n\n/**\n * Configuration options for defineBucket.\n */\nexport type BucketConfig = {\n /** Lambda function settings (memory, timeout, permissions, etc.) */\n lambda?: LambdaWithPermissions;\n /** S3 key prefix filter for event notifications (e.g., \"uploads/\") */\n prefix?: string;\n /** S3 key suffix filter for event notifications (e.g., \".jpg\") */\n suffix?: string;\n};\n\n/**\n * S3 event record passed to onObjectCreated/onObjectRemoved callbacks.\n */\nexport type BucketEvent = {\n /** S3 event name (e.g., \"ObjectCreated:Put\", \"ObjectRemoved:Delete\") */\n eventName: string;\n /** Object key (path within the bucket) */\n key: string;\n /** Object size in bytes (present for created events) */\n size?: number;\n /** Object ETag (present for created events) */\n eTag?: string;\n /** ISO 8601 timestamp of when the event occurred */\n eventTime?: string;\n /** S3 bucket name */\n bucketName: string;\n};\n\n/**\n * Callback function type for S3 ObjectCreated events\n */\nexport type BucketObjectCreatedFn<C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> =\n (args: { event: BucketEvent; bucket: BucketClient }\n & HandlerArgs<C, D, P, S>\n ) => Promise<void>;\n\n/**\n * Callback function type for S3 ObjectRemoved events\n */\nexport type BucketObjectRemovedFn<C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> =\n (args: { event: BucketEvent; bucket: BucketClient }\n & HandlerArgs<C, D, P, S>\n ) => Promise<void>;\n\n/**\n * Setup factory type for bucket handlers.\n * Always receives `bucket: BucketClient` (self-client for the handler's own bucket).\n * Also receives `deps` and/or `config` when declared.\n */\ntype SetupFactory<C, D, P, S extends string[] | undefined = undefined> = (args:\n & { bucket: BucketClient }\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { config: ResolveConfig<P & {}> })\n & ([S] extends [undefined] ? {} : { files: StaticFiles })\n ) => C | Promise<C>;\n\n/** Base options shared by all defineBucket variants */\ntype DefineBucketBase<C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = BucketConfig & {\n /**\n * Error handler called when onObjectCreated or onObjectRemoved throws.\n * If not provided, defaults to `console.error`.\n */\n onError?: (args: { error: unknown } & HandlerArgs<C, D, P, S>) => void;\n /** Called after each invocation completes, right before Lambda freezes the process */\n onAfterInvoke?: (args: HandlerArgs<C, D, P, S>) => void | Promise<void>;\n /**\n * Factory function to initialize shared state for callbacks.\n * Called once on cold start, result is cached and reused across invocations.\n * Always receives `bucket: BucketClient` (self-client). When deps/config\n * are declared, receives them as well.\n */\n setup?: SetupFactory<C, D, P, S>;\n /**\n * Dependencies on other handlers (tables, buckets, etc.).\n * Typed clients are injected into the handler via the `deps` argument.\n * Pass a function returning the deps object: `deps: () => ({ uploads })`.\n */\n deps?: () => D & {};\n /**\n * SSM Parameter Store parameters.\n * Declare with `param()` helper. Values are fetched and cached at cold start.\n */\n config?: P;\n /**\n * Static file glob patterns to bundle into the Lambda ZIP.\n * Files are accessible at runtime via the `files` callback argument.\n */\n static?: S;\n};\n\n/** With event handlers (at least one callback) */\ntype DefineBucketWithHandlers<C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = DefineBucketBase<C, D, P, S> & {\n onObjectCreated?: BucketObjectCreatedFn<C, D, P, S>;\n onObjectRemoved?: BucketObjectRemovedFn<C, D, P, S>;\n};\n\n/** Resource-only: no Lambda, just creates the bucket */\ntype DefineBucketResourceOnly<C = undefined, D = undefined, P = undefined, S extends string[] | undefined = undefined> = DefineBucketBase<C, D, P, S> & {\n onObjectCreated?: never;\n onObjectRemoved?: never;\n};\n\nexport type DefineBucketOptions<\n C = undefined,\n D extends Record<string, AnyDepHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined,\n S extends string[] | undefined = undefined\n> =\n | DefineBucketWithHandlers<C, D, P, S>\n | DefineBucketResourceOnly<C, D, P, S>;\n\n/**\n * Internal handler object created by defineBucket\n * @internal\n */\nexport type BucketHandler<C = any> = {\n readonly __brand: \"effortless-bucket\";\n readonly __spec: BucketConfig;\n readonly onError?: (...args: any[]) => any;\n readonly onAfterInvoke?: (...args: any[]) => any;\n readonly setup?: (...args: any[]) => C | Promise<C>;\n readonly deps?: Record<string, unknown> | (() => Record<string, unknown>);\n readonly config?: Record<string, unknown>;\n readonly static?: string[];\n readonly onObjectCreated?: (...args: any[]) => any;\n readonly onObjectRemoved?: (...args: any[]) => any;\n};\n\n/**\n * Define an S3 bucket with optional event handlers.\n *\n * Creates an S3 bucket. When event handlers are provided, also creates a Lambda\n * function triggered by S3 event notifications.\n *\n * @example Bucket with event handler\n * ```typescript\n * export const uploads = defineBucket({\n * prefix: \"images/\",\n * suffix: \".jpg\",\n * onObjectCreated: async ({ event, bucket }) => {\n * const file = await bucket.get(event.key);\n * console.log(\"New upload:\", event.key, file?.body.length);\n * }\n * });\n * ```\n *\n * @example Resource-only bucket (no Lambda)\n * ```typescript\n * export const assets = defineBucket({});\n * ```\n *\n * @example As a dependency\n * ```typescript\n * export const api = defineApi({\n * basePath: \"/process\",\n * deps: { uploads },\n * post: async ({ req, deps }) => {\n * await deps.uploads.put(\"output.jpg\", buffer);\n * return { status: 200, body: \"OK\" };\n * },\n * });\n * ```\n */\nexport const defineBucket = <\n C = undefined,\n D extends Record<string, AnyDepHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined,\n S extends string[] | undefined = undefined\n>(\n options: DefineBucketOptions<C, D, P, S>\n): BucketHandler<C> => {\n const { onObjectCreated, onObjectRemoved, onError, onAfterInvoke, setup, deps, config, static: staticFiles, ...__spec } = options;\n return {\n __brand: \"effortless-bucket\",\n __spec,\n ...(onError ? { onError } : {}),\n ...(onAfterInvoke ? { onAfterInvoke } : {}),\n ...(setup ? { setup } : {}),\n ...(deps ? { deps } : {}),\n ...(config ? { config } : {}),\n ...(staticFiles ? { static: staticFiles } : {}),\n ...(onObjectCreated ? { onObjectCreated } : {}),\n ...(onObjectRemoved ? { onObjectRemoved } : {}),\n } as BucketHandler<C>;\n};\n","/**\n * Configuration options for defining a mailer (SES email identity)\n */\nexport type MailerConfig = {\n /** Domain to verify and send emails from (e.g., \"myapp.com\") */\n domain: string;\n};\n\n/**\n * Internal handler object created by defineMailer\n * @internal\n */\nexport type MailerHandler = {\n readonly __brand: \"effortless-mailer\";\n readonly __spec: MailerConfig;\n};\n\n/**\n * Define an email sender backed by Amazon SES.\n *\n * Creates an SES Email Identity for the specified domain and provides\n * a typed `EmailClient` to other handlers via `deps`.\n *\n * On first deploy, DKIM DNS records are printed to the console.\n * Add them to your DNS provider to verify the domain.\n *\n * @param options - Mailer configuration with the domain to send from\n * @returns Handler object used by the deployment system and as a `deps` value\n *\n * @example Basic mailer with HTTP handler\n * ```typescript\n * export const mailer = defineMailer({ domain: \"myapp.com\" });\n *\n * export const api = defineApi({\n * basePath: \"/signup\",\n * deps: { mailer },\n * post: async ({ req, deps }) => {\n * await deps.mailer.send({\n * from: \"hello@myapp.com\",\n * to: req.body.email,\n * subject: \"Welcome!\",\n * html: \"<h1>Hi!</h1>\",\n * });\n * return { status: 200, body: { ok: true } };\n * },\n * });\n * ```\n */\nexport const defineMailer = (options: MailerConfig): MailerHandler => ({\n __brand: \"effortless-mailer\",\n __spec: options,\n});\n","import type { LambdaWithPermissions, AnyParamRef, ResolveConfig } from \"./handler-options\";\nimport type { AnyDepHandler, ResolveDeps } from \"./handler-deps\";\nimport type { StaticFiles, ResponseStream } from \"./shared\";\nimport type { HttpRequest, HttpResponse } from \"./shared\";\nimport type { Auth, AuthHelpers, ApiTokenStrategy } from \"./auth\";\nimport type { HandlerArgs } from \"./handler-args\";\n\n/** Extract session type T from Auth<T> */\ntype SessionOf<A> = A extends Auth<infer T> ? T : undefined;\n\n/** GET route handler — no schema, no data */\nexport type ApiGetHandlerFn<\n C = undefined,\n D = undefined,\n P = undefined,\n S extends string[] | undefined = undefined,\n ST extends boolean | undefined = undefined,\n A extends Auth<any> | undefined = undefined\n> =\n (args: { req: HttpRequest }\n & HandlerArgs<C, D, P, S>\n & ([ST] extends [true] ? { stream: ResponseStream } : {})\n & ([A] extends [undefined] ? {} : { auth: AuthHelpers<SessionOf<A>> })\n ) => Promise<HttpResponse | void> | HttpResponse | void;\n\n/** POST handler — with typed data from schema */\nexport type ApiPostHandlerFn<\n T = undefined,\n C = undefined,\n D = undefined,\n P = undefined,\n S extends string[] | undefined = undefined,\n ST extends boolean | undefined = undefined,\n A extends Auth<any> | undefined = undefined\n> =\n (args: { req: HttpRequest }\n & ([T] extends [undefined] ? {} : { data: T })\n & HandlerArgs<C, D, P, S>\n & ([ST] extends [true] ? { stream: ResponseStream } : {})\n & ([A] extends [undefined] ? {} : { auth: AuthHelpers<SessionOf<A>> })\n ) => Promise<HttpResponse | void> | HttpResponse | void;\n\n/** Setup factory — receives deps/config/files when declared */\ntype SetupFactory<C, D, P, S extends string[] | undefined = undefined> =\n (args:\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { config: ResolveConfig<P & {}> })\n & ([S] extends [undefined] ? {} : { files: StaticFiles })\n ) => C | Promise<C>;\n\n/** Static config extracted by AST (no runtime callbacks) */\nexport type ApiConfig = {\n /** Lambda function settings (memory, timeout, permissions, etc.) */\n lambda?: LambdaWithPermissions;\n /** Base path prefix for all routes (e.g., \"/api\") */\n basePath: `/${string}`;\n /** Enable response streaming. When true, the Lambda Function URL uses RESPONSE_STREAM invoke mode. */\n stream?: boolean;\n};\n\n/**\n * Options for defining a CQRS-style API endpoint.\n *\n * - `get` routes handle queries (path-based routing, no body)\n * - `post` handles commands (single entry point, discriminated union via `schema`)\n */\nexport type DefineApiOptions<\n T = undefined,\n C = undefined,\n D extends Record<string, AnyDepHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined,\n S extends string[] | undefined = undefined,\n ST extends boolean | undefined = undefined,\n A extends Auth<any> | undefined = undefined\n> = {\n /** Lambda function settings (memory, timeout, permissions, etc.) */\n lambda?: LambdaWithPermissions;\n /** Base path prefix for all routes (e.g., \"/api\") */\n basePath: `/${string}`;\n /** Enable response streaming. When true, routes receive a `stream` arg for SSE. Routes can still return HttpResponse normally. */\n stream?: ST;\n /** Session-based authentication. Injects `auth` helpers (createSession/clearSession/session) into handler args. */\n auth?: A;\n /** API token authentication for external clients (Bearer tokens, API keys). Has access to deps. */\n apiToken?: ApiTokenStrategy<SessionOf<A>, [D] extends [undefined] ? undefined : ResolveDeps<D>>;\n /**\n * Factory function to initialize shared state.\n * Called once on cold start, result is cached and reused across invocations.\n */\n setup?: SetupFactory<C, D, P, S>;\n /** Dependencies on other handlers (tables, queues, etc.): `deps: () => ({ users })` */\n deps?: () => D & {};\n /** SSM Parameter Store parameters */\n config?: P;\n /** Static file glob patterns to bundle into the Lambda ZIP */\n static?: S;\n /** Error handler called when schema validation or handler throws */\n onError?: (args: { error: unknown; req: HttpRequest } & HandlerArgs<C, D, P, S>) => HttpResponse;\n /** Called after each invocation completes, right before Lambda freezes the process */\n onAfterInvoke?: (args: HandlerArgs<C, D, P, S>) => void | Promise<void>;\n\n /** GET routes — query handlers keyed by relative path (e.g., \"/users/{id}\") */\n get?: Record<`/${string}`, ApiGetHandlerFn<C, D, P, S, ST, A>>;\n\n /**\n * Schema for POST body validation. Use with discriminated unions:\n * ```typescript\n * schema: Action.parse,\n * post: async ({ data }) => { switch (data.action) { ... } }\n * ```\n */\n schema?: (input: unknown) => T;\n /** POST handler — single entry point for commands */\n post?: ApiPostHandlerFn<T, C, D, P, S, ST, A>;\n};\n\n/** Internal handler object created by defineApi */\nexport type ApiHandler<\n T = undefined,\n C = undefined,\n> = {\n readonly __brand: \"effortless-api\";\n readonly __spec: ApiConfig;\n readonly schema?: (input: unknown) => T;\n readonly onError?: (...args: any[]) => any;\n readonly onAfterInvoke?: (...args: any[]) => any;\n readonly setup?: (...args: any[]) => C | Promise<C>;\n readonly deps?: Record<string, unknown> | (() => Record<string, unknown>);\n readonly config?: Record<string, unknown>;\n readonly static?: string[];\n readonly auth?: Auth;\n readonly apiToken?: ApiTokenStrategy<any, any>;\n readonly get?: Record<`/${string}`, (...args: any[]) => any>;\n readonly post?: (...args: any[]) => any;\n};\n\n/**\n * Define a CQRS-style API with typed GET routes and POST commands.\n *\n * GET routes handle queries — path-based routing, no request body.\n * POST handles commands — single entry point with discriminated union schema.\n * Deploys as a single Lambda (fat Lambda) with one API Gateway catch-all route.\n *\n * @example\n * ```typescript\n * export default defineApi({\n * basePath: \"/api\",\n * deps: { users },\n *\n * get: {\n * \"/users\": async ({ req, deps }) => ({\n * status: 200,\n * body: await deps.users.scan()\n * }),\n * \"/users/{id}\": async ({ req, deps }) => ({\n * status: 200,\n * body: await deps.users.get(req.params.id)\n * }),\n * },\n *\n * schema: Action.parse,\n * post: async ({ data, deps }) => {\n * switch (data.action) {\n * case \"create\": return { status: 201, body: await deps.users.put(data) }\n * case \"delete\": return { status: 200, body: await deps.users.delete(data.id) }\n * }\n * },\n * })\n * ```\n */\nexport const defineApi = <\n T = undefined,\n C = undefined,\n D extends Record<string, AnyDepHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined,\n S extends string[] | undefined = undefined,\n ST extends boolean | undefined = undefined,\n A extends Auth<any> | undefined = undefined\n>(\n options: DefineApiOptions<T, C, D, P, S, ST, A>\n): ApiHandler<T, C> => {\n const { get, post, schema, onError, onAfterInvoke, setup, deps, config, auth: authConfig, apiToken, static: staticFiles, ...__spec } = options;\n return {\n __brand: \"effortless-api\",\n __spec,\n ...(get ? { get } : {}),\n ...(post ? { post } : {}),\n ...(schema ? { schema } : {}),\n ...(onError ? { onError } : {}),\n ...(onAfterInvoke ? { onAfterInvoke } : {}),\n ...(setup ? { setup } : {}),\n ...(deps ? { deps } : {}),\n ...(config ? { config } : {}),\n ...(staticFiles ? { static: staticFiles } : {}),\n ...(authConfig ? { auth: authConfig } : {}),\n ...(apiToken ? { apiToken } : {}),\n } as ApiHandler<T, C>;\n};\n","// Public helpers — this file must have ZERO heavy imports (no effect, no AWS SDK, no deploy code).\n// It is the source of truth for param(), unsafeAs(), and related types used by the public API.\n\n// ============ Permissions ============\n\ntype AwsService =\n | \"dynamodb\"\n | \"s3\"\n | \"sqs\"\n | \"sns\"\n | \"ses\"\n | \"ssm\"\n | \"lambda\"\n | \"events\"\n | \"secretsmanager\"\n | \"cognito-idp\"\n | \"logs\";\n\nexport type Permission = `${AwsService}:${string}` | (string & {});\n\n// ============ Duration ============\n\n/**\n * Human-readable duration. Accepts a plain number (seconds) or a string\n * with a unit suffix: `\"30s\"`, `\"5m\"`, `\"1h\"`, `\"2d\"`.\n *\n * @example\n * ```typescript\n * timeout: 30 // 30 seconds\n * timeout: \"30s\" // 30 seconds\n * timeout: \"5m\" // 300 seconds\n * timeout: \"1h\" // 3600 seconds\n * retentionPeriod: \"4d\" // 345600 seconds\n * ```\n */\nexport type Duration = number | `${number}s` | `${number}m` | `${number}h` | `${number}d`;\n\n/** Convert a Duration to seconds. */\nexport const toSeconds = (d: Duration): number => {\n if (typeof d === \"number\") return d;\n const match = d.match(/^(\\d+(?:\\.\\d+)?)(s|m|h|d)$/);\n if (!match) throw new Error(`Invalid duration: \"${d}\"`);\n const n = Number(match[1]);\n const unit = match[2];\n if (unit === \"d\") return n * 86400;\n if (unit === \"h\") return n * 3600;\n if (unit === \"m\") return n * 60;\n return n;\n};\n\n// ============ Lambda config ============\n\n/** Logging verbosity level for Lambda handlers */\nexport type LogLevel = \"error\" | \"info\" | \"debug\";\n\n/**\n * Common Lambda configuration shared by all handler types.\n */\nexport type LambdaConfig = {\n /** Lambda memory in MB (default: 256) */\n memory?: number;\n /** Lambda timeout (default: 30s). Accepts seconds or duration string: `\"30s\"`, `\"5m\"` */\n timeout?: Duration;\n /** Logging verbosity: \"error\" (errors only), \"info\" (+ execution summary), \"debug\" (+ input/output). Default: \"info\" */\n logLevel?: LogLevel;\n};\n\n/**\n * Lambda configuration with additional IAM permissions.\n * Used by handler types that support custom permissions (http, table, fifo-queue).\n */\nexport type LambdaWithPermissions = LambdaConfig & {\n /** Additional IAM permissions for the Lambda */\n permissions?: Permission[];\n};\n\n// ============ Secrets (SSM Parameters) ============\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnySecretRef = SecretRef<any>;\n\n/**\n * Reference to an SSM Parameter Store secret.\n *\n * @typeParam T - The resolved type after optional transform (default: string)\n */\nexport type SecretRef<T = string> = {\n readonly __brand: \"effortless-secret\";\n readonly key?: string;\n readonly generate?: () => string;\n readonly transform?: (raw: string) => T;\n};\n\n/**\n * Maps a config declaration to resolved value types.\n * `SecretRef<T>` resolves to `T`.\n *\n * @typeParam P - Record of config keys to SecretRef instances\n */\nexport type ResolveConfig<P> = {\n [K in keyof P]: P[K] extends SecretRef<infer T> ? T : string;\n};\n\n/** Options for `secret()` without a transform. */\nexport type SecretOptions = {\n /** Custom SSM key (default: derived from config property name in kebab-case) */\n key?: string;\n /** Generator function called at deploy time if the SSM parameter doesn't exist yet */\n generate?: () => string;\n};\n\n/** Options for `secret()` with a transform. */\nexport type SecretOptionsWithTransform<T> = SecretOptions & {\n /** Transform the raw SSM string value into a typed value */\n transform: (raw: string) => T;\n};\n\n/**\n * Declare an SSM Parameter Store secret.\n *\n * The SSM key is derived from the config property name (camelCase → kebab-case)\n * unless overridden with `key`. The full SSM path is `/${project}/${stage}/${key}`.\n *\n * @param options - Optional configuration (key override, generator, transform)\n * @returns A SecretRef used by the deployment and runtime systems\n *\n * @example Simple secret\n * ```typescript\n * config: {\n * dbUrl: secret(),\n * // → SSM path: /${project}/${stage}/db-url\n * }\n * ```\n *\n * @example Auto-generated secret\n * ```typescript\n * config: {\n * authSecret: secret({ generate: generateHex(64) }),\n * // → auto-creates SSM param if missing\n * }\n * ```\n *\n * @example With transform\n * ```typescript\n * config: {\n * appConfig: secret({ transform: TOML.parse }),\n * }\n * ```\n */\nexport function secret(): SecretRef<string>;\nexport function secret(options: SecretOptions): SecretRef<string>;\nexport function secret<T>(options: SecretOptionsWithTransform<T>): SecretRef<T>;\nexport function secret<T = string>(\n options?: SecretOptions | SecretOptionsWithTransform<T>\n): SecretRef<T> {\n return {\n __brand: \"effortless-secret\",\n ...(options?.key ? { key: options.key } : {}),\n ...(options?.generate ? { generate: options.generate } : {}),\n ...(\"transform\" in (options ?? {}) ? { transform: (options as SecretOptionsWithTransform<T>).transform } : {}),\n } as SecretRef<T>;\n}\n\n// ============ Secret generators ============\n\n/**\n * Returns a generator that produces a random hex string.\n * @param bytes - Number of random bytes (output will be 2x this length in hex chars)\n */\nexport const generateHex = (bytes: number) => (): string => {\n const crypto = require(\"crypto\") as typeof import(\"crypto\");\n return crypto.randomBytes(bytes).toString(\"hex\");\n};\n\n/**\n * Returns a generator that produces a random base64url string.\n * @param bytes - Number of random bytes\n */\nexport const generateBase64 = (bytes: number) => (): string => {\n const crypto = require(\"crypto\") as typeof import(\"crypto\");\n return crypto.randomBytes(bytes).toString(\"base64url\");\n};\n\n/**\n * Returns a generator that produces a random UUID v4.\n */\nexport const generateUuid = () => (): string => {\n const crypto = require(\"crypto\") as typeof import(\"crypto\");\n return crypto.randomUUID();\n};\n\n// ============ Backwards compatibility ============\n\n/** @deprecated Use `SecretRef` instead */\nexport type ParamRef<T = string> = SecretRef<T>;\n/** @deprecated Use `AnySecretRef` instead */\nexport type AnyParamRef = AnySecretRef;\n\n/**\n * @deprecated Use `secret()` instead. `param(\"key\")` is equivalent to `secret({ key: \"key\" })`.\n */\nexport function param(key: string): SecretRef<string>;\nexport function param<T>(key: string, transform: (raw: string) => T): SecretRef<T>;\nexport function param<T = string>(\n key: string,\n transform?: (raw: string) => T\n): SecretRef<T> {\n return {\n __brand: \"effortless-secret\",\n key,\n ...(transform ? { transform } : {}),\n } as SecretRef<T>;\n}\n\n// ============ Single-table types ============\n\n/**\n * DynamoDB table key (always pk + sk strings in single-table design).\n */\nexport type TableKey = { pk: string; sk: string };\n\n/**\n * Full DynamoDB item in the single-table design.\n *\n * Every item has a fixed envelope: `pk`, `sk`, `tag`, `data`, and optional `ttl`.\n * `tag` is stored as a top-level DynamoDB attribute (GSI-ready).\n * If your domain type `T` includes a `tag` field, effortless auto-copies\n * `data.tag` to the top-level `tag` on `put()`, so you don't have to pass it twice.\n *\n * @typeParam T - The domain data type stored in the `data` attribute\n */\nexport type TableItem<T> = {\n pk: string;\n sk: string;\n tag: string;\n data: T;\n ttl?: number;\n};\n\n/**\n * Input type for `TableClient.put()`.\n *\n * Unlike `TableItem<T>`, this does NOT include `tag` — effortless auto-extracts\n * the top-level DynamoDB `tag` attribute from your data using the configured\n * tag field (defaults to `data.tag`, configurable via `defineTable({ tag: \"type\" })`).\n *\n * @typeParam T - The domain data type stored in the `data` attribute\n */\nexport type PutInput<T> = {\n pk: string;\n sk: string;\n data: T;\n ttl?: number;\n};\n\n/**\n * Create a schema function that casts input to T without runtime validation.\n * Use when you need T inference alongside other generics (deps, config).\n * For handlers without deps/config, prefer `defineTable<Order>({...})`.\n * For untrusted input, prefer a real parser (Zod, Effect Schema).\n *\n * @example\n * ```typescript\n * export const orders = defineTable({\n * schema: unsafeAs<Order>(),\n * deps: () => ({ notifications }),\n * onRecord: async ({ record, deps }) => { ... }\n * });\n * ```\n */\nexport function unsafeAs<T>(): (input: unknown) => T {\n return (input: unknown) => input as T;\n}\n","import * as crypto from \"crypto\";\nimport type { Duration } from \"./handler-options\";\nimport { toSeconds } from \"./handler-options\";\n\n// ============ Cookie name ============\n\nexport const AUTH_COOKIE_NAME = \"__eff_session\";\n\n// ============ Auth config ============\n\nexport type AuthConfig<_T = undefined> = {\n /** Path to redirect unauthenticated users to (used by static sites). */\n loginPath: string;\n /** Paths that don't require authentication. Supports trailing `*` wildcard. */\n public?: string[];\n /** Default session lifetime (default: \"7d\"). Accepts seconds or duration string. */\n expiresIn?: Duration;\n};\n\n/**\n * Branded auth object returned by `defineAuth()`.\n * Pass to `defineApi({ auth })` and `defineStaticSite({ auth })`.\n */\nexport type Auth<T = undefined> = AuthConfig<T> & {\n readonly __brand: \"effortless-auth\";\n /** @internal phantom type marker for session data */\n readonly __session?: T;\n};\n\n// ============ API Token strategy (used by defineApi) ============\n\n/** API token authentication strategy. Verifies tokens from HTTP headers (e.g. Authorization: Bearer). */\nexport type ApiTokenStrategy<T, D = undefined> = {\n /** HTTP header to read the token from. Default: \"authorization\" (strips \"Bearer \" prefix). */\n header?: string;\n /** Verify the token value and return session data, or null if invalid. */\n verify: [D] extends [undefined]\n ? (value: string) => T | null | Promise<T | null>\n : (value: string, ctx: { deps: D }) => T | null | Promise<T | null>;\n /** Cache verified token results for this duration. Avoids calling verify on every request. */\n cacheTtl?: Duration;\n};\n\n// ============ defineAuth ============\n\n/**\n * Define authentication for API handlers and static sites.\n *\n * Session-based auth uses HMAC-signed cookies (auto-managed by the framework).\n *\n * - Lambda@Edge middleware verifies cookie signatures for static sites\n * - API handler gets `auth.createSession()` / `auth.clearSession()` / `auth.session` helpers\n * - HMAC secret is auto-generated and stored in SSM Parameter Store\n *\n * @typeParam T - Session data type. When provided, `createSession(data)` requires typed payload\n * and `auth.session` is typed as `T` in handler args.\n *\n * @example\n * ```typescript\n * type Session = { userId: string; role: \"admin\" | \"user\" };\n *\n * const auth = defineAuth<Session>({\n * loginPath: '/login',\n * public: ['/login', '/api/login'],\n * expiresIn: '7d',\n * })\n *\n * export const api = defineApi({ auth, ... })\n * export const webapp = defineStaticSite({ auth, ... })\n * ```\n */\nexport const defineAuth = <T = undefined>(options: AuthConfig<T>): Auth<T> => ({\n __brand: \"effortless-auth\",\n ...options,\n}) as Auth<T>;\n\n// ============ Runtime helpers (API Lambda) ============\n\n/** Options for creating a session */\ntype SessionOptions = { expiresIn?: Duration };\n/** Session response with Set-Cookie header */\ntype SessionResponse = { status: 200; body: { ok: true }; headers: Record<string, string> };\n\n/**\n * Auth helpers injected into API handler callback args when `auth` is configured.\n * @typeParam T - Session data type (undefined = no custom data)\n */\nexport type AuthHelpers<T = undefined> =\n { /** Clear the session cookie. */\n clearSession(): { status: 200; body: { ok: true }; headers: Record<string, string> };\n /** The current session data (from cookie or API token). Undefined if no valid session. */\n session: T extends undefined ? undefined : T | undefined;\n }\n & ([T] extends [undefined]\n ? { /** Create a signed session cookie. */ createSession(options?: SessionOptions): SessionResponse }\n : { /** Create a signed session cookie with typed data. */ createSession(data: T, options?: SessionOptions): SessionResponse });\n\n// ============ Cookie format ============\n// Payload: base64url(JSON.stringify({ exp, ...data }))\n// Cookie value: {payload}.{hmac-sha256(payload, secret)}\n\n/**\n * Auth runtime created once on cold start. Holds the HMAC key and optional token verifier.\n * Call `forRequest(cookieValue, authHeader, deps)` per request to get typed helpers.\n * @internal\n */\nexport type AuthRuntime = {\n forRequest(cookieValue: string | undefined, authHeader: string | undefined, deps?: Record<string, unknown>): Promise<AuthHelpers<any>>;\n};\n\n/**\n * Create auth runtime for an API handler.\n * Called once on cold start with the HMAC secret from SSM.\n * @internal\n */\nexport const createAuthRuntime = (\n secret: string,\n defaultExpiresIn: number,\n apiTokenVerify?: (value: string, ctx: { deps: unknown }) => unknown | Promise<unknown>,\n apiTokenHeader?: string,\n apiTokenCacheTtlSeconds?: number,\n): AuthRuntime => {\n // Token verification cache: token → { session, expiresAt }\n const tokenCache = apiTokenCacheTtlSeconds\n ? new Map<string, { session: unknown; expiresAt: number }>()\n : undefined;\n\n const sign = (payload: string): string =>\n crypto.createHmac(\"sha256\", secret).update(payload).digest(\"base64url\");\n\n const cookieBase = `${AUTH_COOKIE_NAME}=`;\n const cookieAttrs = \"; HttpOnly; Secure; SameSite=Lax; Path=/\";\n\n const decodeSession = (cookieValue: string | undefined): unknown => {\n if (!cookieValue) return undefined;\n const dot = cookieValue.indexOf(\".\");\n if (dot === -1) return undefined;\n const payload = cookieValue.slice(0, dot);\n const sig = cookieValue.slice(dot + 1);\n if (sign(payload) !== sig) return undefined;\n try {\n const parsed = JSON.parse(Buffer.from(payload, \"base64url\").toString(\"utf-8\"));\n if (parsed.exp <= Math.floor(Date.now() / 1000)) return undefined;\n const { exp: _, ...data } = parsed;\n return Object.keys(data).length > 0 ? data : undefined;\n } catch { return undefined; }\n };\n\n const extractTokenValue = (headerValue: string): string => {\n const isDefaultHeader = !apiTokenHeader || apiTokenHeader.toLowerCase() === \"authorization\";\n if (isDefaultHeader && headerValue.toLowerCase().startsWith(\"bearer \")) {\n return headerValue.slice(7);\n }\n return headerValue;\n };\n\n const buildHelpers = (sessionData: unknown): AuthHelpers<any> => ({\n createSession(...args: unknown[]) {\n const hasData = args.length > 0 && (typeof args[0] === \"object\" && args[0] !== null && !(\"expiresIn\" in args[0]));\n const data = hasData ? args[0] as Record<string, unknown> : undefined;\n const options = (hasData ? args[1] : args[0]) as SessionOptions | undefined;\n const seconds = options?.expiresIn ? toSeconds(options.expiresIn) : defaultExpiresIn;\n const exp = Math.floor(Date.now() / 1000) + seconds;\n const payload = Buffer.from(JSON.stringify({ exp, ...data }), \"utf-8\").toString(\"base64url\");\n const sig = sign(payload);\n return {\n status: 200 as const,\n body: { ok: true as const },\n headers: {\n \"set-cookie\": `${cookieBase}${payload}.${sig}${cookieAttrs}; Max-Age=${seconds}`,\n },\n };\n },\n clearSession() {\n return {\n status: 200 as const,\n body: { ok: true as const },\n headers: {\n \"set-cookie\": `${cookieBase}${cookieAttrs}; Max-Age=0`,\n },\n };\n },\n session: sessionData,\n } as AuthHelpers<any>);\n\n return {\n async forRequest(cookieValue, authHeader, deps) {\n // API token takes priority over cookie\n if (authHeader && apiTokenVerify) {\n const tokenValue = extractTokenValue(authHeader);\n\n // Check cache\n if (tokenCache) {\n const cached = tokenCache.get(tokenValue);\n if (cached && cached.expiresAt > Date.now()) {\n return buildHelpers(cached.session);\n }\n }\n\n const session = await apiTokenVerify(tokenValue, { deps });\n\n // Store in cache\n if (tokenCache && apiTokenCacheTtlSeconds) {\n tokenCache.set(tokenValue, { session, expiresAt: Date.now() + apiTokenCacheTtlSeconds * 1000 });\n }\n\n return buildHelpers(session);\n }\n\n // Fall back to cookie-based session\n return buildHelpers(decodeSession(cookieValue));\n },\n };\n};\n","/** HTTP methods supported by Lambda Function URLs */\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\" | \"ANY\";\n\n/** Short content-type aliases for common response formats */\nexport type ContentType = \"json\" | \"html\" | \"text\" | \"css\" | \"js\" | \"xml\" | \"csv\" | \"svg\";\n\n/**\n * Incoming HTTP request object passed to the handler\n */\nexport type HttpRequest = {\n /** HTTP method (GET, POST, etc.) */\n method: string;\n /** Request path (e.g., \"/users/123\") */\n path: string;\n /** Request headers */\n headers: Record<string, string | undefined>;\n /** Query string parameters */\n query: Record<string, string | undefined>;\n /** Path parameters extracted from route (e.g., {id} -> params.id) */\n params: Record<string, string | undefined>;\n /** Parsed request body (JSON parsed if Content-Type is application/json) */\n body: unknown;\n /** Raw unparsed request body */\n rawBody?: string;\n};\n\n/**\n * HTTP response returned from the handler\n */\nexport type HttpResponse = {\n /** HTTP status code (e.g., 200, 404, 500) */\n status: number;\n /** Response body — JSON-serialized by default, or sent as string when contentType is set */\n body?: unknown;\n /**\n * Short content-type alias. Resolves to full MIME type automatically:\n * - `\"json\"` → `application/json` (default if omitted)\n * - `\"html\"` → `text/html; charset=utf-8`\n * - `\"text\"` → `text/plain; charset=utf-8`\n * - `\"css\"` → `text/css; charset=utf-8`\n * - `\"js\"` → `application/javascript; charset=utf-8`\n * - `\"xml\"` → `application/xml; charset=utf-8`\n * - `\"csv\"` → `text/csv; charset=utf-8`\n * - `\"svg\"` → `image/svg+xml; charset=utf-8`\n */\n contentType?: ContentType;\n /** Response headers (use for custom content-types not covered by contentType) */\n headers?: Record<string, string>;\n /**\n * Set to `true` to return binary data.\n * When enabled, `body` must be a base64-encoded string and the response\n * will include `isBase64Encoded: true` so Lambda Function URLs / API Gateway\n * decode it back to binary for the client.\n */\n binary?: boolean;\n};\n\n/** Response helpers for defineApi handlers */\nexport const result = {\n /** Return a JSON response */\n json: (body: unknown, status: number = 200): HttpResponse => ({ status, body }),\n /** Return a binary response. Accepts a Buffer and converts to base64 automatically. */\n binary: (body: Buffer, contentType: string, headers?: Record<string, string>): HttpResponse => ({\n status: 200,\n body: body.toString(\"base64\"),\n binary: true,\n headers: { \"content-type\": contentType, ...headers },\n }),\n};\n\n/** Stream helper injected into route args when `stream: true` is set on defineApi */\nexport type ResponseStream = {\n /** Write a raw string chunk to the response stream */\n write(chunk: string): void;\n /** End the response stream */\n end(): void;\n /** Switch to SSE mode: sets Content-Type to text/event-stream */\n sse(): void;\n /** Write an SSE event: `data: JSON.stringify(data)\\n\\n` */\n event(data: unknown): void;\n};\n\n/** Service for reading static files bundled into the Lambda ZIP */\nexport type StaticFiles = {\n /** Read file as UTF-8 string */\n read(path: string): string;\n /** Read file as Buffer (for binary content) */\n readBuffer(path: string): Buffer;\n /** Resolve absolute path to the bundled file */\n path(path: string): string;\n};\n"],"mappings":";;;;;;;;AAwGO,IAAM,eAAe,CAAC,WAA+C;;;ACgJrE,IAAM,cAAc,CAQzB,YACuB;AACvB,QAAM,EAAE,UAAU,iBAAiB,SAAS,SAAS,eAAe,QAAQ,OAAO,MAAM,QAAQ,QAAQ,aAAa,GAAG,OAAO,IAAI;AACpI,SAAO;AAAA,IACL,SAAS;AAAA,IACT;AAAA,IACA,GAAI,SAAS,EAAE,O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UAAQ,QAAQ;AAC/B,SAAO,OAAO,WAAW;AAC3B;AAcO,SAAS,MACd,KACA,WACc;AACd,SAAO;AAAA,IACL,SAAS;AAAA,IACT;AAAA,IACA,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;AAAA,EACnC;AACF;AA0DO,SAAS,WAAqC;AACnD,SAAO,CAAC,UAAmB;AAC7B;;;ACzMO,IAAM,aAAa,CAAgB,aAAqC;AAAA,EAC7E,SAAS;AAAA,EACT,GAAG;AACL;;;AChBO,IAAM,SAAS;AAAA;AAAA,EAEpB,MAAM,CAAC,MAAe,SAAiB,SAAuB,EAAE,QAAQ,KAAK;AAAA;AAAA,EAE7E,QAAQ,CAAC,MAAc,aAAqB,aAAoD;AAAA,IAC9F,QAAQ;AAAA,IACR,MAAM,KAAK,SAAS,QAAQ;AAAA,IAC5B,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,aAAa,GAAG,QAAQ;AAAA,EACrD;AACF;","names":[]}
1
+ {"version":3,"sources":["../src/config.ts","../src/handlers/handler-options.ts","../src/handlers/define-table.ts","../src/handlers/define-app.ts","../src/handlers/define-static-site.ts","../src/handlers/define-fifo-queue.ts","../src/handlers/define-bucket.ts","../src/handlers/define-mailer.ts","../src/handlers/define-api.ts"],"sourcesContent":["/**\n * Configuration for an Effortless project.\n *\n * @example\n * ```typescript\n * // effortless.config.ts\n * import { defineConfig } from \"effortless-aws\";\n *\n * export default defineConfig({\n * name: \"my-service\",\n * region: \"eu-central-1\",\n * handlers: \"src\",\n * });\n * ```\n */\nexport type EffortlessConfig = {\n /**\n * Project root directory. All relative paths (handlers, server, assets, etc.)\n * are resolved from this directory.\n * Resolved relative to where the CLI runs (process.cwd()).\n * @default \".\" (current working directory)\n */\n root?: string;\n\n /**\n * Project name used for resource naming and tagging.\n * This becomes part of Lambda function names, IAM roles, etc.\n */\n name: string;\n\n /**\n * Default AWS region for all handlers.\n * Can be overridden per-handler or via CLI `--region` flag.\n * @default \"eu-central-1\"\n */\n region?: string;\n\n /**\n * Deployment stage (e.g., \"dev\", \"staging\", \"prod\").\n * Used for resource isolation and tagging.\n * @default \"dev\"\n */\n stage?: string;\n\n /**\n * Glob patterns or directory paths to scan for handlers.\n * Used by `eff deploy` (without file argument) to auto-discover handlers.\n *\n * @example\n * ```typescript\n * // Single directory - scans for all .ts files\n * handlers: \"src\"\n *\n * // Glob patterns\n * handlers: [\"src/**\\/*.ts\", \"lib/**\\/*.handler.ts\"]\n * ```\n */\n handlers?: string | string[];\n\n /**\n * Default Lambda settings applied to all handlers unless overridden.\n *\n * All Lambdas run on ARM64 (Graviton2) architecture — ~20% cheaper than x86_64\n * with better price-performance for most workloads.\n */\n lambda?: {\n /**\n * Lambda memory in MB. AWS allocates proportional CPU —\n * 1769 MB gives one full vCPU.\n * @default 256\n */\n memory?: number;\n\n /**\n * Lambda timeout as a human-readable string.\n * AWS maximum is 15 minutes.\n * @example \"30 seconds\", \"5 minutes\"\n */\n timeout?: string;\n\n /**\n * Node.js Lambda runtime version.\n * @default \"nodejs24.x\"\n */\n runtime?: string;\n };\n\n};\n\n/**\n * Helper function for type-safe configuration.\n * Returns the config object as-is, but provides TypeScript autocompletion.\n *\n * @example\n * ```typescript\n * import { defineConfig } from \"effortless-aws\";\n *\n * export default defineConfig({\n * name: \"my-service\",\n * region: \"eu-central-1\",\n * handlers: \"src\",\n * });\n * ```\n */\nexport const defineConfig = (config: EffortlessConfig): EffortlessConfig => config;\n","// Public helpers — this file must have ZERO heavy imports (no effect, no AWS SDK, no deploy code).\n// It is the source of truth for param(), unsafeAs(), and related types used by the public API.\n\n// ============ Generate spec ============\n\n/** Generator spec for auto-creating secrets at deploy time. */\nexport type GenerateSpec = `hex:${number}` | `base64:${number}` | \"uuid\";\n\n// ============ Permissions ============\n\ntype AwsService =\n | \"dynamodb\"\n | \"s3\"\n | \"sqs\"\n | \"sns\"\n | \"ses\"\n | \"ssm\"\n | \"lambda\"\n | \"events\"\n | \"secretsmanager\"\n | \"cognito-idp\"\n | \"logs\";\n\nexport type Permission = `${AwsService}:${string}` | (string & {});\n\n// ============ Duration ============\n\n/**\n * Human-readable duration. Accepts a plain number (seconds) or a string\n * with a unit suffix: `\"30s\"`, `\"5m\"`, `\"1h\"`, `\"2d\"`.\n *\n * @example\n * ```typescript\n * timeout: 30 // 30 seconds\n * timeout: \"30s\" // 30 seconds\n * timeout: \"5m\" // 300 seconds\n * timeout: \"1h\" // 3600 seconds\n * retentionPeriod: \"4d\" // 345600 seconds\n * ```\n */\nexport type Duration = number | `${number}s` | `${number}m` | `${number}h` | `${number}d`;\n\n/** Convert a Duration to seconds. */\nexport const toSeconds = (d: Duration): number => {\n if (typeof d === \"number\") return d;\n const match = d.match(/^(\\d+(?:\\.\\d+)?)(s|m|h|d)$/);\n if (!match) throw new Error(`Invalid duration: \"${d}\"`);\n const n = Number(match[1]);\n const unit = match[2];\n if (unit === \"d\") return n * 86400;\n if (unit === \"h\") return n * 3600;\n if (unit === \"m\") return n * 60;\n return n;\n};\n\n// ============ Lambda config ============\n\n/** Logging verbosity level for Lambda handlers */\nexport type LogLevel = \"error\" | \"info\" | \"debug\";\n\n/**\n * Common Lambda configuration shared by all handler types.\n */\nexport type LambdaConfig = {\n /** Lambda memory in MB (default: 256) */\n memory?: number;\n /** Lambda timeout (default: 30s). Accepts seconds or duration string: `\"30s\"`, `\"5m\"` */\n timeout?: Duration;\n /** Logging verbosity: \"error\" (errors only), \"info\" (+ execution summary), \"debug\" (+ input/output). Default: \"info\" */\n logLevel?: LogLevel;\n};\n\n/**\n * Lambda configuration with additional IAM permissions.\n * Used by handler types that support custom permissions (http, table, fifo-queue).\n */\nexport type LambdaWithPermissions = LambdaConfig & {\n /** Additional IAM permissions for the Lambda */\n permissions?: Permission[];\n};\n\n// ============ Secrets (SSM Parameters) ============\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnySecretRef = SecretRef<any>;\n\n/**\n * Reference to an SSM Parameter Store secret.\n *\n * @typeParam T - The resolved type after optional transform (default: string)\n */\nexport type SecretRef<T = string> = {\n readonly __brand: \"effortless-secret\";\n readonly key?: string;\n readonly generate?: GenerateSpec;\n readonly transform?: (raw: string) => T;\n};\n\n/**\n * Maps a config declaration to resolved value types.\n * `SecretRef<T>` resolves to `T`.\n *\n * @typeParam P - Record of config keys to SecretRef instances\n */\nexport type ResolveConfig<P> = {\n [K in keyof P]: P[K] extends SecretRef<infer T> ? T : string;\n};\n\n/** Options for `defineSecret()` without a transform. */\nexport type DefineSecretOptions = {\n /** Custom SSM key (default: derived from config property name in kebab-case) */\n key?: string;\n /** Generator spec for auto-creating the secret at deploy time: `\"hex:32\"`, `\"base64:32\"`, `\"uuid\"` */\n generate?: GenerateSpec;\n};\n\n/** Options for `defineSecret()` with a transform. */\nexport type DefineSecretOptionsWithTransform<T> = DefineSecretOptions & {\n /** Transform the raw SSM string value into a typed value */\n transform: (raw: string) => T;\n};\n\n/** The defineSecret helper function type, injected into config callbacks. */\nexport type DefineSecretFn = {\n (): SecretRef<string>;\n (options: DefineSecretOptions): SecretRef<string>;\n <T>(options: DefineSecretOptionsWithTransform<T>): SecretRef<T>;\n};\n\n/** Helpers injected into the `config` callback. */\nexport type ConfigHelpers = {\n defineSecret: DefineSecretFn;\n};\n\n/** Config factory: a function receiving helpers and returning a record of SecretRefs. */\nexport type ConfigFactory<P> = (helpers: ConfigHelpers) => P;\n\n/** The `defineSecret` implementation, passed to config callbacks. */\nexport const defineSecret: DefineSecretFn = <T = string>(\n options?: DefineSecretOptions | DefineSecretOptionsWithTransform<T>\n): SecretRef<T> => {\n return {\n __brand: \"effortless-secret\",\n ...(options?.key ? { key: options.key } : {}),\n ...(options?.generate ? { generate: options.generate } : {}),\n ...(\"transform\" in (options ?? {}) ? { transform: (options as DefineSecretOptionsWithTransform<T>).transform } : {}),\n } as SecretRef<T>;\n};\n\n/** Internal helpers object passed to config callbacks. */\nexport const configHelpers: ConfigHelpers = { defineSecret };\n\n/** Resolve a config factory to a plain record of SecretRefs. */\nexport const resolveConfigFactory = <P>(config: ConfigFactory<P>): P =>\n config(configHelpers);\n\n// ============ Backwards compatibility ============\n\n/** @deprecated Use `defineSecret()` inside a config callback instead. */\nexport const secret = defineSecret;\n/** @deprecated Use `SecretRef` instead */\nexport type ParamRef<T = string> = SecretRef<T>;\n/** @deprecated Use `AnySecretRef` instead */\nexport type AnyParamRef = AnySecretRef;\n/** @deprecated Use `defineSecret()` instead. */\nexport const param = <T = string>(key: string, transform?: (raw: string) => T): SecretRef<T> => {\n return {\n __brand: \"effortless-secret\",\n key,\n ...(transform ? { transform } : {}),\n } as SecretRef<T>;\n};\n/** @deprecated Use `defineSecret({ generate: \"hex:N\" })` instead. */\nexport const generateHex = (bytes: number) => `hex:${bytes}`;\n/** @deprecated Use `defineSecret({ generate: \"base64:N\" })` instead. */\nexport const generateBase64 = (bytes: number) => `base64:${bytes}`;\n/** @deprecated Use `defineSecret({ generate: \"uuid\" })` instead. */\nexport const generateUuid = () => \"uuid\";\n\n// ============ Single-table types ============\n\n/**\n * DynamoDB table key (always pk + sk strings in single-table design).\n */\nexport type TableKey = { pk: string; sk: string };\n\n/**\n * Full DynamoDB item in the single-table design.\n *\n * Every item has a fixed envelope: `pk`, `sk`, `tag`, `data`, and optional `ttl`.\n * `tag` is stored as a top-level DynamoDB attribute (GSI-ready).\n * If your domain type `T` includes a `tag` field, effortless auto-copies\n * `data.tag` to the top-level `tag` on `put()`, so you don't have to pass it twice.\n *\n * @typeParam T - The domain data type stored in the `data` attribute\n */\nexport type TableItem<T> = {\n pk: string;\n sk: string;\n tag: string;\n data: T;\n ttl?: number;\n};\n\n/**\n * Input type for `TableClient.put()`.\n *\n * Unlike `TableItem<T>`, this does NOT include `tag` — effortless auto-extracts\n * the top-level DynamoDB `tag` attribute from your data using the configured\n * tag field (defaults to `data.tag`, configurable via `defineTable({ tag: \"type\" })`).\n *\n * @typeParam T - The domain data type stored in the `data` attribute\n */\nexport type PutInput<T> = {\n pk: string;\n sk: string;\n data: T;\n ttl?: number;\n};\n\n/**\n * Create a schema function that casts input to T without runtime validation.\n * Use when you need T inference alongside other generics (deps, config).\n * For handlers without deps/config, prefer `defineTable<Order>({...})`.\n * For untrusted input, prefer a real parser (Zod, Effect Schema).\n *\n * @example\n * ```typescript\n * export const orders = defineTable({\n * schema: unsafeAs<Order>(),\n * deps: () => ({ notifications }),\n * onRecord: async ({ record, deps }) => { ... }\n * });\n * ```\n */\nexport function unsafeAs<T>(): (input: unknown) => T {\n return (input: unknown) => input as T;\n}\n","import type { AnySecretRef, ResolveConfig, Duration, ConfigFactory, LogLevel, Permission } from \"./handler-options\";\nimport { resolveConfigFactory } from \"./handler-options\";\nimport type { AnyDepHandler, ResolveDeps } from \"./handler-deps\";\nimport type { TableClient } from \"../runtime/table-client\";\nimport type { TableItem } from \"./handler-options\";\nimport type { StaticFiles } from \"./shared\";\n\n/** DynamoDB attribute types for keys */\nexport type KeyType = \"string\" | \"number\" | \"binary\";\n\n/**\n * DynamoDB table key definition\n */\nexport type TableKey = {\n /** Attribute name */\n name: string;\n /** Attribute type */\n type: KeyType;\n};\n\n/** DynamoDB Streams view type - determines what data is captured in stream records */\nexport type StreamView = \"NEW_AND_OLD_IMAGES\" | \"NEW_IMAGE\" | \"OLD_IMAGE\" | \"KEYS_ONLY\";\n\n/**\n * Configuration options for defineTable (single-table design).\n *\n * Tables always use `pk (S)` + `sk (S)` keys, `tag (S)` discriminator,\n * `data (M)` for domain fields, and `ttl (N)` for optional expiration.\n */\nexport type TableConfig = {\n /** Lambda function settings (memory, timeout, permissions, etc.) */\n lambda?: { memory?: number; timeout?: Duration; logLevel?: LogLevel; permissions?: Permission[] };\n /** DynamoDB billing mode (default: \"PAY_PER_REQUEST\") */\n billingMode?: \"PAY_PER_REQUEST\" | \"PROVISIONED\";\n /** Stream view type - what data to include in stream records (default: \"NEW_AND_OLD_IMAGES\") */\n streamView?: StreamView;\n /** Number of records to process in each Lambda invocation (1-10000, default: 100) */\n batchSize?: number;\n /** Maximum time to gather records before invoking (default: `\"2s\"`). Accepts `\"5s\"`, `\"1m\"`, etc. */\n batchWindow?: Duration;\n /** Where to start reading the stream (default: \"LATEST\") */\n startingPosition?: \"LATEST\" | \"TRIM_HORIZON\";\n /** Number of records to process concurrently within a batch (default: 1 — sequential) */\n concurrency?: number;\n /**\n * Name of the field in `data` that serves as the entity type discriminant.\n * Effortless auto-copies `data[tagField]` to the top-level DynamoDB `tag` attribute on `put()`.\n * Defaults to `\"tag\"`.\n */\n tagField?: string;\n};\n\n/**\n * DynamoDB stream record passed to onRecord callback.\n *\n * `new` and `old` are full `TableItem<T>` objects with the single-table envelope.\n *\n * @typeParam T - Type of the domain data (inside `data`)\n */\nexport type TableRecord<T = Record<string, unknown>> = {\n /** Type of modification: INSERT, MODIFY, or REMOVE */\n eventName: \"INSERT\" | \"MODIFY\" | \"REMOVE\";\n /** New item value (present for INSERT and MODIFY) */\n new?: TableItem<T>;\n /** Old item value (present for MODIFY and REMOVE) */\n old?: TableItem<T>;\n /** Primary key of the affected item */\n keys: { pk: string; sk: string };\n /** Sequence number for ordering */\n sequenceNumber?: string;\n /** Approximate timestamp when the modification occurred */\n timestamp?: number;\n};\n\n// ============ Setup args ============\n\n/** Setup factory — receives table/deps/config/files based on what was declared */\ntype SetupArgs<T, D, P, HasFiles extends boolean> =\n & { table: TableClient<T> }\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { config: ResolveConfig<P & {}> })\n & (HasFiles extends true ? { files: StaticFiles } : {});\n\n/** Spread ctx into callback args (empty when no setup) */\ntype SpreadCtx<C> = [C] extends [undefined] ? {} : C & {};\n\n/**\n * Callback function type for processing a single DynamoDB stream record.\n * Receives the current record and the full batch for context.\n */\nexport type TableRecordFn<T = Record<string, unknown>, C = undefined> =\n (args: { record: TableRecord<T>; batch: readonly TableRecord<T>[] }\n & SpreadCtx<C>\n ) => Promise<void>;\n\n/**\n * Batch handler function for DynamoDB stream records.\n * Called once with all records in the batch.\n * Return `{ failures: string[] }` (sequence numbers) for partial batch failure reporting.\n */\nexport type TableBatchFn<T = Record<string, unknown>, C = undefined> =\n (args: { records: readonly TableRecord<T>[] }\n & SpreadCtx<C>\n ) => Promise<void | { failures: string[] }>;\n\n// ============ Static config ============\n\n/** Static config extracted by AST (no runtime callbacks) */\n// TableConfig is already defined above and used as the extracted config type.\n\n// ============ Handler type (base interface for runtime wrappers and annotations) ============\n\n/**\n * Handler object created by defineTable.\n * Used by runtime wrappers and as type annotation for circular deps.\n * @internal\n */\nexport type TableHandler<T = Record<string, unknown>, C = any> = {\n readonly __brand: \"effortless-table\";\n readonly __spec: TableConfig;\n readonly schema?: (input: unknown) => T;\n readonly onError?: (...args: any[]) => any;\n readonly onCleanup?: (...args: any[]) => any;\n readonly setup?: (...args: any[]) => C | Promise<C>;\n readonly deps?: Record<string, unknown> | (() => Record<string, unknown>);\n readonly config?: Record<string, unknown>;\n readonly static?: string[];\n readonly onRecord?: (...args: any[]) => any;\n readonly onRecordBatch?: (...args: any[]) => any;\n};\n\n// ============ Builder options ============\n\n/** Options passed to `defineTable()` — static config, no generics needed for inference */\ntype TableOptions<T> = {\n /** Lambda memory in MB (default: 256) */\n memory?: number;\n /** Lambda timeout (default: 30s). Accepts seconds or duration string: `\"30s\"`, `\"5m\"` */\n timeout?: Duration;\n /** Additional IAM permissions for the Lambda */\n permissions?: Permission[];\n /** Logging verbosity */\n logLevel?: LogLevel;\n /** DynamoDB billing mode (default: \"PAY_PER_REQUEST\") */\n billingMode?: \"PAY_PER_REQUEST\" | \"PROVISIONED\";\n /** Stream view type (default: \"NEW_AND_OLD_IMAGES\") */\n streamView?: StreamView;\n /** Number of records to process in each Lambda invocation (1-10000, default: 100) */\n batchSize?: number;\n /** Maximum time to gather records before invoking (default: \"2s\") */\n batchWindow?: Duration;\n /** Where to start reading the stream (default: \"LATEST\") */\n startingPosition?: \"LATEST\" | \"TRIM_HORIZON\";\n /** Number of records to process concurrently within a batch (default: 1) */\n concurrency?: number;\n /** Name of the field in `data` that serves as the entity type discriminant (default: \"tag\") */\n tagField?: Extract<keyof T, string>;\n /** Decode/validate function for the `data` portion of stream records */\n schema?: (input: unknown) => T;\n /** Static file glob patterns to bundle into the Lambda ZIP */\n static?: string[];\n};\n\n// ============ Builder ============\n\ninterface TableBuilder<\n T = Record<string, unknown>,\n D = undefined,\n P = undefined,\n C = undefined,\n HasFiles extends boolean = false,\n> {\n /** Declare handler dependencies (tables, queues, buckets, mailers) */\n deps<D2 extends Record<string, AnyDepHandler>>(\n fn: () => D2\n ): TableBuilder<T, D2, P, C, HasFiles>;\n\n /** Declare SSM secrets */\n config<P2 extends Record<string, AnySecretRef>>(\n fn: ConfigFactory<P2>\n ): TableBuilder<T, D, P2, C, HasFiles>;\n\n /** Initialize shared state on cold start. Receives table (self-client), deps, config, files. */\n setup<C2>(\n fn: (args: SetupArgs<T, D, P, HasFiles>) => C2 | Promise<C2>\n ): TableBuilder<T, D, P, C2, HasFiles>;\n\n /** Handle errors thrown by onRecord/onRecordBatch */\n onError(\n fn: (args: { error: unknown } & SpreadCtx<C>) => void\n ): TableBuilder<T, D, P, C, HasFiles>;\n\n /** Cleanup callback — runs after each invocation, before Lambda freezes */\n onCleanup(\n fn: (args: SpreadCtx<C>) => void | Promise<void>\n ): TableBuilder<T, D, P, C, HasFiles>;\n\n /** Per-record stream handler (terminal — returns finalized handler) */\n onRecord(\n fn: TableRecordFn<T, C>\n ): TableHandler<T, C>;\n\n /** Batch stream handler (terminal — returns finalized handler) */\n onRecordBatch(\n fn: TableBatchFn<T, C>\n ): TableHandler<T, C>;\n\n /** Finalize as resource-only table (no Lambda) */\n build(): TableHandler<T, C>;\n}\n\n// ============ Implementation ============\n\n/**\n * Define a DynamoDB table with optional stream handler (single-table design).\n *\n * Creates a table with fixed key schema: `pk (S)` + `sk (S)`, plus `tag (S)`,\n * `data (M)`, and `ttl (N)` attributes. TTL is always enabled.\n *\n * @example Table with stream handler\n * ```typescript\n * export const orders = defineTable<OrderData>({ batchSize: 10, concurrency: 5 })\n * .setup(({ table }) => ({ table }))\n * .onRecord(async ({ record, table }) => {\n * if (record.eventName === \"INSERT\") {\n * console.log(\"New order:\", record.new?.data);\n * }\n * })\n * ```\n *\n * @example Table only (no Lambda)\n * ```typescript\n * export const users = defineTable<User>().build()\n * ```\n *\n * @example Table as dependency (resource-only, no Lambda)\n * ```typescript\n * export const sessions = defineTable<Session>().build()\n * ```\n */\nexport function defineTable<T = Record<string, unknown>>(): TableBuilder<T>;\nexport function defineTable<T = Record<string, unknown>>(\n options: TableOptions<T> & { static: string[] },\n): TableBuilder<T, undefined, undefined, undefined, true>;\nexport function defineTable<T = Record<string, unknown>>(\n options: TableOptions<T>,\n): TableBuilder<T>;\nexport function defineTable<T = Record<string, unknown>>(\n options?: TableOptions<T>,\n): TableBuilder<T> {\n const {\n memory, timeout, permissions, logLevel,\n schema, static: staticFiles,\n ...tableConfig\n } = options ?? {} as TableOptions<T>;\n\n const hasLambda = memory != null || timeout != null || permissions != null || logLevel != null;\n const spec: TableConfig = {\n ...tableConfig,\n ...(hasLambda ? { lambda: { ...(memory != null ? { memory } : {}), ...(timeout != null ? { timeout } : {}), ...(permissions ? { permissions } : {}), ...(logLevel ? { logLevel } : {}) } } : {}),\n };\n\n const state: {\n spec: TableConfig;\n deps?: () => Record<string, unknown>;\n config?: Record<string, unknown>;\n static?: string[];\n schema?: (input: unknown) => T;\n setup?: (...args: any[]) => any;\n onError?: (...args: any[]) => any;\n onCleanup?: (...args: any[]) => any;\n onRecord?: (...args: any[]) => any;\n onRecordBatch?: (...args: any[]) => any;\n } = {\n spec,\n ...(schema ? { schema } : {}),\n ...(staticFiles ? { static: staticFiles } : {}),\n };\n\n const finalize = (): TableHandler<T> => ({\n __brand: \"effortless-table\",\n __spec: state.spec,\n ...(state.schema ? { schema: state.schema } : {}),\n ...(state.onError ? { onError: state.onError } : {}),\n ...(state.onCleanup ? { onCleanup: state.onCleanup } : {}),\n ...(state.setup ? { setup: state.setup } : {}),\n ...(state.deps ? { deps: state.deps } : {}),\n ...(state.config ? { config: state.config } : {}),\n ...(state.static ? { static: state.static } : {}),\n ...(state.onRecord ? { onRecord: state.onRecord } : {}),\n ...(state.onRecordBatch ? { onRecordBatch: state.onRecordBatch } : {}),\n }) as TableHandler<T>;\n\n const builder: TableBuilder<T> = {\n deps(fn) {\n state.deps = fn as any;\n return builder as any;\n },\n config(fn) {\n state.config = resolveConfigFactory(fn) as any;\n return builder as any;\n },\n setup(fn) {\n state.setup = fn as any;\n return builder as any;\n },\n onRecord(fn) {\n state.onRecord = fn as any;\n return finalize() as any;\n },\n onRecordBatch(fn) {\n state.onRecordBatch = fn as any;\n return finalize() as any;\n },\n onError(fn) {\n state.onError = fn as any;\n return builder as any;\n },\n onCleanup(fn) {\n state.onCleanup = fn as any;\n return builder as any;\n },\n build() {\n return finalize() as any;\n },\n };\n\n return builder;\n}\n","import type { LambdaWithPermissions } from \"./handler-options\";\n\n/**\n * Configuration for deploying an SSR framework (Nuxt, Astro, etc.)\n * via CloudFront + S3 (static assets) + Lambda Function URL (server-side rendering).\n */\nexport type AppConfig = {\n /** Lambda function settings (memory, timeout, permissions, etc.) */\n lambda?: LambdaWithPermissions;\n /** Directory containing the Lambda server handler (e.g., \".output/server\").\n * Must contain an `index.mjs` (or `index.js`) that exports a `handler` function. */\n server: string;\n /** Directory containing static assets for S3 (e.g., \".output/public\") */\n assets: string;\n /** Base URL path (default: \"/\") */\n path?: string;\n /** Shell command to build the framework output (e.g., \"nuxt build\") */\n build?: string;\n /** Custom domain name. String or stage-keyed record (e.g., { prod: \"app.example.com\" }). */\n domain?: string | Record<string, string>;\n /** CloudFront route overrides: path patterns forwarded to API Gateway instead of the SSR Lambda.\n * Keys are CloudFront path patterns (e.g., \"/api/*\"), values are handler references.\n * Example: `routes: { \"/api/*\": api }` */\n routes?: Record<string, { readonly __brand: string }>;\n};\n\n/**\n * Internal handler object created by defineApp\n * @internal\n */\nexport type AppHandler = {\n readonly __brand: \"effortless-app\";\n readonly __spec: AppConfig;\n};\n\n/**\n * Deploy an SSR framework application via CloudFront + Lambda Function URL.\n *\n * Static assets from the `assets` directory are served via S3 + CloudFront CDN.\n * Server-rendered pages are handled by a Lambda function using the framework's\n * built output from the `server` directory.\n *\n * For static-only sites (no SSR), use {@link defineStaticSite} instead.\n *\n * @param options - App configuration: server directory, assets directory, optional build command\n * @returns Handler object used by the deployment system\n *\n * @example Nuxt SSR\n * ```typescript\n * export const app = defineApp({\n * build: \"nuxt build\",\n * server: \".output/server\",\n * assets: \".output/public\",\n * lambda: { memory: 1024 },\n * });\n * ```\n */\nexport const defineApp = () => (options: AppConfig): AppHandler => ({\n __brand: \"effortless-app\",\n __spec: options,\n});\n","/** Any branded handler that deploys to API Gateway (HttpHandler, ApiHandler, etc.) */\ntype AnyRoutableHandler = { readonly __brand: string };\n\n/** Simplified request object passed to middleware */\nexport type MiddlewareRequest = {\n uri: string;\n method: string;\n querystring: string;\n headers: Record<string, string>;\n cookies: Record<string, string>;\n};\n\n/** Redirect the user to another URL */\nexport type MiddlewareRedirect = {\n redirect: string;\n status?: 301 | 302 | 307 | 308;\n};\n\n/** Deny access with a 403 status */\nexport type MiddlewareDeny = {\n status: 403;\n body?: string;\n};\n\n/** Middleware return type: redirect, deny, or void (continue serving) */\nexport type MiddlewareResult = MiddlewareRedirect | MiddlewareDeny | void;\n\n/** Function that runs before serving static files via Lambda@Edge */\nexport type MiddlewareHandler = (\n request: MiddlewareRequest\n) => Promise<MiddlewareResult> | MiddlewareResult;\n\n/** SEO options for auto-generating sitemap.xml, robots.txt, and submitting to Google Indexing API */\nexport type StaticSiteSeo = {\n /** Sitemap filename (e.g. \"sitemap.xml\", \"sitemap-v2.xml\") */\n sitemap: string;\n /** Path to Google service account JSON key file for Indexing API batch submission.\n * Requires adding the service account email as an owner in Google Search Console. */\n googleIndexing?: string;\n};\n\n/**\n * Configuration for a static site handler (S3 + CloudFront)\n */\nexport type StaticSiteConfig = {\n /** Handler name. Defaults to export name if not specified */\n name?: string;\n /** Directory containing the static site files, relative to project root */\n dir: string;\n /** Default file for directory requests (default: \"index.html\") */\n index?: string;\n /** SPA mode: serve index.html for all paths that don't match a file (default: false) */\n spa?: boolean;\n /** Shell command to run before deploy to generate site content (e.g., \"npx astro build\") */\n build?: string;\n /** Custom domain name. Accepts a string (same domain for all stages) or a Record mapping stage names to domains (e.g., `{ prod: \"example.com\", dev: \"dev.example.com\" }`). Requires an ACM certificate in us-east-1. If the cert also covers www, a 301 redirect from www to non-www is set up automatically. */\n domain?: string | Record<string, string>;\n /** CloudFront route overrides: path patterns forwarded to API Gateway instead of S3.\n * Keys are CloudFront path patterns (e.g., \"/api/*\"), values are HTTP handlers.\n * Example: `routes: { \"/api/*\": api }` */\n routes?: Record<string, AnyRoutableHandler>;\n /** Custom 404 error page path relative to `dir` (e.g. \"404.html\").\n * For non-SPA sites only. If not set, a default page is generated automatically. */\n errorPage?: string;\n /** Lambda@Edge middleware that runs before serving pages. Use for auth checks, redirects, etc. */\n middleware?: MiddlewareHandler;\n /** SEO: auto-generate sitemap.xml and robots.txt at deploy time, optionally submit URLs to Google Indexing API */\n seo?: StaticSiteSeo;\n};\n\n/**\n * Internal handler object created by defineStaticSite\n * @internal\n */\nexport type StaticSiteHandler = {\n readonly __brand: \"effortless-static-site\";\n readonly __spec: StaticSiteConfig;\n};\n\n/**\n * Deploy a static site via S3 + CloudFront CDN.\n *\n * @param options - Static site configuration: directory, optional SPA mode, build command\n * @returns Handler object used by the deployment system\n *\n * @example Documentation site\n * ```typescript\n * export const docs = defineStaticSite({\n * dir: \"dist\",\n * build: \"npx astro build\",\n * });\n * ```\n *\n * @example SPA with client-side routing\n * ```typescript\n * export const app = defineStaticSite({\n * dir: \"dist\",\n * spa: true,\n * build: \"npm run build\",\n * });\n * ```\n *\n */\nexport const defineStaticSite = () => (options: StaticSiteConfig): StaticSiteHandler => ({\n __brand: \"effortless-static-site\",\n __spec: options,\n});\n","import type { AnySecretRef, ResolveConfig, Duration, ConfigFactory, LogLevel, Permission } from \"./handler-options\";\nimport { resolveConfigFactory } from \"./handler-options\";\nimport type { AnyDepHandler, ResolveDeps } from \"./handler-deps\";\nimport type { StaticFiles } from \"./shared\";\n\n/**\n * Parsed SQS FIFO message passed to the handler callbacks.\n *\n * @typeParam T - Type of the decoded message body (from schema function)\n */\nexport type FifoQueueMessage<T = unknown> = {\n /** Unique message identifier */\n messageId: string;\n /** Receipt handle for acknowledgement */\n receiptHandle: string;\n /** Parsed message body (JSON-decoded, then optionally schema-validated) */\n body: T;\n /** Raw unparsed message body string */\n rawBody: string;\n /** Message group ID (FIFO ordering key) */\n messageGroupId: string;\n /** Message deduplication ID */\n messageDeduplicationId?: string;\n /** SQS message attributes */\n messageAttributes: Record<string, { dataType?: string; stringValue?: string }>;\n /** Approximate first receive timestamp */\n approximateFirstReceiveTimestamp?: string;\n /** Approximate receive count */\n approximateReceiveCount?: string;\n /** Sent timestamp */\n sentTimestamp?: string;\n};\n\n/**\n * Configuration options for a FIFO queue handler\n */\nexport type FifoQueueConfig = {\n /** Lambda function settings (memory, timeout, permissions, etc.) */\n lambda?: { memory?: number; timeout?: Duration; logLevel?: LogLevel; permissions?: Permission[] };\n /** Number of messages per Lambda invocation (1-10 for FIFO, default: 10) */\n batchSize?: number;\n /** Maximum time to gather messages before invoking (default: 0). Accepts `\"5s\"`, `\"1m\"`, etc. */\n batchWindow?: Duration;\n /** Visibility timeout (default: max of timeout or 30s). Accepts `\"30s\"`, `\"5m\"`, etc. */\n visibilityTimeout?: Duration;\n /** Message retention period (default: `\"4d\"`). Accepts `\"1h\"`, `\"7d\"`, etc. */\n retentionPeriod?: Duration;\n /** Delivery delay for all messages in the queue (default: 0). Accepts `\"30s\"`, `\"5m\"`, etc. */\n delay?: Duration;\n /** Enable content-based deduplication (default: true) */\n contentBasedDeduplication?: boolean;\n /** Max number of receives before a message is sent to the dead-letter queue (default: 3) */\n maxReceiveCount?: number;\n};\n\n// ============ Setup args ============\n\n/** Spread ctx into callback args (empty when no setup) */\ntype SpreadCtx<C> = [C] extends [undefined] ? {} : C & {};\n\n/** Setup factory — receives deps/config/files based on what was declared */\ntype SetupArgs<D, P, HasFiles extends boolean> =\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { config: ResolveConfig<P & {}> })\n & (HasFiles extends true ? { files: StaticFiles } : {});\n\n/**\n * Per-message handler function.\n * Called once per message in the batch. Failures are reported individually.\n */\nexport type FifoQueueMessageFn<T = unknown, C = undefined> =\n (args: { message: FifoQueueMessage<T> }\n & SpreadCtx<C>\n ) => Promise<void>;\n\n/**\n * Batch handler function.\n * Called once with all messages in the batch.\n * Return `{ failures: string[] }` (messageIds) for partial batch failure reporting.\n */\nexport type FifoQueueBatchFn<T = unknown, C = undefined> =\n (args: { messages: FifoQueueMessage<T>[] }\n & SpreadCtx<C>\n ) => Promise<void | { failures: string[] }>;\n\n// ============ Internal handler object ============\n\n/**\n * Internal handler object created by defineFifoQueue\n * @internal\n */\nexport type FifoQueueHandler<T = unknown, C = any> = {\n readonly __brand: \"effortless-fifo-queue\";\n readonly __spec: FifoQueueConfig;\n readonly schema?: (input: unknown) => T;\n readonly onError?: (...args: any[]) => any;\n readonly onCleanup?: (...args: any[]) => any;\n readonly setup?: (...args: any[]) => C | Promise<C>;\n readonly deps?: Record<string, unknown> | (() => Record<string, unknown>);\n readonly config?: Record<string, unknown>;\n readonly static?: string[];\n readonly onMessage?: (...args: any[]) => any;\n readonly onMessageBatch?: (...args: any[]) => any;\n};\n\n// ============ Builder options ============\n\n/** Options passed to `defineFifoQueue()` — static config */\ntype FifoQueueOptions<T> = {\n /** Lambda memory in MB (default: 256) */\n memory?: number;\n /** Lambda timeout (default: 30s) */\n timeout?: Duration;\n /** Additional IAM permissions for the Lambda */\n permissions?: Permission[];\n /** Logging verbosity */\n logLevel?: LogLevel;\n /** Number of messages per Lambda invocation (1-10 for FIFO, default: 10) */\n batchSize?: number;\n /** Maximum time to gather messages before invoking (default: 0) */\n batchWindow?: Duration;\n /** Visibility timeout (default: max of timeout or 30s) */\n visibilityTimeout?: Duration;\n /** Message retention period (default: \"4d\") */\n retentionPeriod?: Duration;\n /** Delivery delay for all messages in the queue (default: 0) */\n delay?: Duration;\n /** Enable content-based deduplication (default: true) */\n contentBasedDeduplication?: boolean;\n /** Max number of receives before DLQ (default: 3) */\n maxReceiveCount?: number;\n /** Decode/validate function for the message body */\n schema?: (input: unknown) => T;\n /** Static file glob patterns to bundle into the Lambda ZIP */\n static?: string[];\n};\n\n// ============ Builder ============\n\ninterface FifoQueueBuilder<\n T = unknown,\n D = undefined,\n P = undefined,\n C = undefined,\n HasFiles extends boolean = false,\n> {\n /** Declare handler dependencies */\n deps<D2 extends Record<string, AnyDepHandler>>(\n fn: () => D2\n ): FifoQueueBuilder<T, D2, P, C, HasFiles>;\n\n /** Declare SSM secrets */\n config<P2 extends Record<string, AnySecretRef>>(\n fn: ConfigFactory<P2>\n ): FifoQueueBuilder<T, D, P2, C, HasFiles>;\n\n /** Initialize shared state on cold start. Receives deps, config, files. */\n setup<C2>(\n fn: (args: SetupArgs<D, P, HasFiles>) => C2 | Promise<C2>\n ): FifoQueueBuilder<T, D, P, C2, HasFiles>;\n\n /** Handle errors thrown by message handlers */\n onError(\n fn: (args: { error: unknown } & SpreadCtx<C>) => void\n ): FifoQueueBuilder<T, D, P, C, HasFiles>;\n\n /** Cleanup callback — runs after each invocation, before Lambda freezes */\n onCleanup(\n fn: (args: SpreadCtx<C>) => void | Promise<void>\n ): FifoQueueBuilder<T, D, P, C, HasFiles>;\n\n /** Per-message handler (terminal — returns finalized handler) */\n onMessage(\n fn: FifoQueueMessageFn<T, C>\n ): FifoQueueHandler<T, C>;\n\n /** Batch handler (terminal — returns finalized handler) */\n onMessageBatch(\n fn: FifoQueueBatchFn<T, C>\n ): FifoQueueHandler<T, C>;\n}\n\n// ============ Implementation ============\n\n/**\n * Define a FIFO SQS queue with a Lambda message handler.\n *\n * @example Per-message processing\n * ```typescript\n * export const orderQueue = defineFifoQueue<OrderEvent>()\n * .onMessage(async ({ message }) => {\n * console.log(\"Processing order:\", message.body.orderId);\n * })\n *\n * ```\n *\n * @example Batch processing with schema\n * ```typescript\n * export const notifications = defineFifoQueue({ batchSize: 5, schema: (i) => NotifSchema.parse(i) })\n * .onMessageBatch(async ({ messages }) => {\n * await sendAll(messages.map(m => m.body));\n * })\n *\n * ```\n */\nexport function defineFifoQueue<T = unknown>(): FifoQueueBuilder<T>;\nexport function defineFifoQueue<T = unknown>(\n options: FifoQueueOptions<T> & { static: string[] },\n): FifoQueueBuilder<T, undefined, undefined, undefined, true>;\nexport function defineFifoQueue<T = unknown>(\n options: FifoQueueOptions<T>,\n): FifoQueueBuilder<T>;\nexport function defineFifoQueue<T = unknown>(\n options?: FifoQueueOptions<T>,\n): FifoQueueBuilder<T> {\n const {\n memory, timeout, permissions, logLevel,\n schema, static: staticFiles,\n ...queueConfig\n } = options ?? {} as FifoQueueOptions<T>;\n\n const hasLambda = memory != null || timeout != null || permissions != null || logLevel != null;\n const spec: FifoQueueConfig = {\n ...queueConfig,\n ...(hasLambda ? { lambda: { ...(memory != null ? { memory } : {}), ...(timeout != null ? { timeout } : {}), ...(permissions ? { permissions } : {}), ...(logLevel ? { logLevel } : {}) } } : {}),\n };\n\n const state: {\n spec: FifoQueueConfig;\n deps?: () => Record<string, unknown>;\n config?: Record<string, unknown>;\n static?: string[];\n schema?: (input: unknown) => T;\n setup?: (...args: any[]) => any;\n onError?: (...args: any[]) => any;\n onCleanup?: (...args: any[]) => any;\n onMessage?: (...args: any[]) => any;\n onMessageBatch?: (...args: any[]) => any;\n } = {\n spec,\n ...(schema ? { schema } : {}),\n ...(staticFiles ? { static: staticFiles } : {}),\n };\n\n const finalize = (): FifoQueueHandler<T> => ({\n __brand: \"effortless-fifo-queue\",\n __spec: state.spec,\n ...(state.schema ? { schema: state.schema } : {}),\n ...(state.onError ? { onError: state.onError } : {}),\n ...(state.onCleanup ? { onCleanup: state.onCleanup } : {}),\n ...(state.setup ? { setup: state.setup } : {}),\n ...(state.deps ? { deps: state.deps } : {}),\n ...(state.config ? { config: state.config } : {}),\n ...(state.static ? { static: state.static } : {}),\n ...(state.onMessage ? { onMessage: state.onMessage } : {}),\n ...(state.onMessageBatch ? { onMessageBatch: state.onMessageBatch } : {}),\n }) as FifoQueueHandler<T>;\n\n const builder: FifoQueueBuilder<T> = {\n deps(fn) {\n state.deps = fn as any;\n return builder as any;\n },\n config(fn) {\n state.config = resolveConfigFactory(fn) as any;\n return builder as any;\n },\n setup(fn) {\n state.setup = fn as any;\n return builder as any;\n },\n onMessage(fn) {\n state.onMessage = fn as any;\n return finalize() as any;\n },\n onMessageBatch(fn) {\n state.onMessageBatch = fn as any;\n return finalize() as any;\n },\n onError(fn) {\n state.onError = fn as any;\n return builder as any;\n },\n onCleanup(fn) {\n state.onCleanup = fn as any;\n return builder as any;\n },\n };\n\n return builder;\n}\n","import type { AnySecretRef, ResolveConfig, Duration, ConfigFactory, LogLevel, Permission } from \"./handler-options\";\nimport { resolveConfigFactory } from \"./handler-options\";\nimport type { AnyDepHandler, ResolveDeps } from \"./handler-deps\";\nimport type { StaticFiles } from \"./shared\";\nimport type { BucketClient } from \"../runtime/bucket-client\";\n\n/**\n * Configuration options for defineBucket.\n */\nexport type BucketConfig = {\n /** Lambda function settings (memory, timeout, permissions, etc.) */\n lambda?: { memory?: number; timeout?: Duration; logLevel?: LogLevel; permissions?: Permission[] };\n /** S3 key prefix filter for event notifications (e.g., \"uploads/\") */\n prefix?: string;\n /** S3 key suffix filter for event notifications (e.g., \".jpg\") */\n suffix?: string;\n};\n\n/**\n * S3 event record passed to onObjectCreated/onObjectRemoved callbacks.\n */\nexport type BucketEvent = {\n /** S3 event name (e.g., \"ObjectCreated:Put\", \"ObjectRemoved:Delete\") */\n eventName: string;\n /** Object key (path within the bucket) */\n key: string;\n /** Object size in bytes (present for created events) */\n size?: number;\n /** Object ETag (present for created events) */\n eTag?: string;\n /** ISO 8601 timestamp of when the event occurred */\n eventTime?: string;\n /** S3 bucket name */\n bucketName: string;\n};\n\n// ============ Setup args ============\n\n/** Spread ctx into callback args (empty when no setup) */\ntype SpreadCtx<C> = [C] extends [undefined] ? {} : C & {};\n\n/** Setup factory — receives bucket/deps/config/files based on what was declared */\ntype SetupArgs<D, P, HasFiles extends boolean> =\n & { bucket: BucketClient }\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { config: ResolveConfig<P & {}> })\n & (HasFiles extends true ? { files: StaticFiles } : {});\n\n/**\n * Callback function type for S3 ObjectCreated events\n */\nexport type BucketObjectCreatedFn<C = undefined> =\n (args: { event: BucketEvent }\n & SpreadCtx<C>\n ) => Promise<void>;\n\n/**\n * Callback function type for S3 ObjectRemoved events\n */\nexport type BucketObjectRemovedFn<C = undefined> =\n (args: { event: BucketEvent }\n & SpreadCtx<C>\n ) => Promise<void>;\n\n// ============ Internal handler object ============\n\n/**\n * Internal handler object created by defineBucket\n * @internal\n */\nexport type BucketHandler<C = any> = {\n readonly __brand: \"effortless-bucket\";\n readonly __spec: BucketConfig;\n readonly onError?: (...args: any[]) => any;\n readonly onCleanup?: (...args: any[]) => any;\n readonly setup?: (...args: any[]) => C | Promise<C>;\n readonly deps?: Record<string, unknown> | (() => Record<string, unknown>);\n readonly config?: Record<string, unknown>;\n readonly static?: string[];\n readonly onObjectCreated?: (...args: any[]) => any;\n readonly onObjectRemoved?: (...args: any[]) => any;\n};\n\n// ============ Builder options ============\n\n/** Options passed to `defineBucket()` — static config */\ntype BucketOptions = {\n /** Lambda memory in MB (default: 256) */\n memory?: number;\n /** Lambda timeout (default: 30s) */\n timeout?: Duration;\n /** Additional IAM permissions for the Lambda */\n permissions?: Permission[];\n /** Logging verbosity */\n logLevel?: LogLevel;\n /** S3 key prefix filter for event notifications (e.g., \"uploads/\") */\n prefix?: string;\n /** S3 key suffix filter for event notifications (e.g., \".jpg\") */\n suffix?: string;\n /** Static file glob patterns to bundle into the Lambda ZIP */\n static?: string[];\n};\n\n// ============ Builder ============\n\ninterface BucketBuilder<\n D = undefined,\n P = undefined,\n C = undefined,\n HasFiles extends boolean = false,\n> {\n /** Declare handler dependencies */\n deps<D2 extends Record<string, AnyDepHandler>>(\n fn: () => D2\n ): BucketBuilder<D2, P, C, HasFiles>;\n\n /** Declare SSM secrets */\n config<P2 extends Record<string, AnySecretRef>>(\n fn: ConfigFactory<P2>\n ): BucketBuilder<D, P2, C, HasFiles>;\n\n /** Initialize shared state on cold start. Receives bucket (self-client), deps, config, files. */\n setup<C2>(\n fn: (args: SetupArgs<D, P, HasFiles>) => C2 | Promise<C2>\n ): BucketBuilder<D, P, C2, HasFiles>;\n\n /** Handle errors thrown by callbacks */\n onError(\n fn: (args: { error: unknown } & SpreadCtx<C>) => void\n ): BucketBuilder<D, P, C, HasFiles>;\n\n /** Cleanup callback — runs after each invocation, before Lambda freezes */\n onCleanup(\n fn: (args: SpreadCtx<C>) => void | Promise<void>\n ): BucketBuilder<D, P, C, HasFiles>;\n\n /** Handle S3 ObjectCreated events (terminal — returns finalized handler) */\n onObjectCreated(\n fn: BucketObjectCreatedFn<C>\n ): BucketHandler<C>;\n\n /** Handle S3 ObjectRemoved events (terminal — returns finalized handler) */\n onObjectRemoved(\n fn: BucketObjectRemovedFn<C>\n ): BucketHandler<C>;\n\n /** Finalize as resource-only bucket (no Lambda) */\n build(): BucketHandler<C>;\n}\n\n// ============ Implementation ============\n\n/**\n * Define an S3 bucket with optional event handlers.\n *\n * @example Bucket with event handler\n * ```typescript\n * export const uploads = defineBucket({ prefix: \"images/\", suffix: \".jpg\" })\n * .onObjectCreated(async ({ event, bucket }) => {\n * console.log(\"New upload:\", event.key);\n * })\n *\n * ```\n *\n * @example Resource-only bucket (no Lambda)\n * ```typescript\n * export const assets = defineBucket().build()\n * ```\n */\nexport function defineBucket(): BucketBuilder;\nexport function defineBucket(\n options: BucketOptions & { static: string[] },\n): BucketBuilder<undefined, undefined, undefined, true>;\nexport function defineBucket(\n options: BucketOptions,\n): BucketBuilder;\nexport function defineBucket(\n options?: BucketOptions,\n): BucketBuilder {\n const {\n memory, timeout, permissions, logLevel,\n static: staticFiles,\n ...bucketConfig\n } = options ?? {} as BucketOptions;\n\n const hasLambda = memory != null || timeout != null || permissions != null || logLevel != null;\n const spec: BucketConfig = {\n ...bucketConfig,\n ...(hasLambda ? { lambda: { ...(memory != null ? { memory } : {}), ...(timeout != null ? { timeout } : {}), ...(permissions ? { permissions } : {}), ...(logLevel ? { logLevel } : {}) } } : {}),\n };\n\n const state: {\n spec: BucketConfig;\n deps?: () => Record<string, unknown>;\n config?: Record<string, unknown>;\n static?: string[];\n setup?: (...args: any[]) => any;\n onError?: (...args: any[]) => any;\n onCleanup?: (...args: any[]) => any;\n onObjectCreated?: (...args: any[]) => any;\n onObjectRemoved?: (...args: any[]) => any;\n } = {\n spec,\n ...(staticFiles ? { static: staticFiles } : {}),\n };\n\n const finalize = (): BucketHandler => ({\n __brand: \"effortless-bucket\",\n __spec: state.spec,\n ...(state.onError ? { onError: state.onError } : {}),\n ...(state.onCleanup ? { onCleanup: state.onCleanup } : {}),\n ...(state.setup ? { setup: state.setup } : {}),\n ...(state.deps ? { deps: state.deps } : {}),\n ...(state.config ? { config: state.config } : {}),\n ...(state.static ? { static: state.static } : {}),\n ...(state.onObjectCreated ? { onObjectCreated: state.onObjectCreated } : {}),\n ...(state.onObjectRemoved ? { onObjectRemoved: state.onObjectRemoved } : {}),\n }) as BucketHandler;\n\n const builder: BucketBuilder = {\n deps(fn) {\n state.deps = fn as any;\n return builder as any;\n },\n config(fn) {\n state.config = resolveConfigFactory(fn) as any;\n return builder as any;\n },\n setup(fn) {\n state.setup = fn as any;\n return builder as any;\n },\n onObjectCreated(fn) {\n state.onObjectCreated = fn as any;\n return finalize() as any;\n },\n onObjectRemoved(fn) {\n state.onObjectRemoved = fn as any;\n return finalize() as any;\n },\n onError(fn) {\n state.onError = fn as any;\n return builder as any;\n },\n onCleanup(fn) {\n state.onCleanup = fn as any;\n return builder as any;\n },\n build() {\n return finalize() as any;\n },\n };\n\n return builder;\n}\n","/**\n * Configuration options for defining a mailer (SES email identity)\n */\nexport type MailerConfig = {\n /** Domain to verify and send emails from (e.g., \"myapp.com\") */\n domain: string;\n};\n\n/**\n * Internal handler object created by defineMailer\n * @internal\n */\nexport type MailerHandler = {\n readonly __brand: \"effortless-mailer\";\n readonly __spec: MailerConfig;\n};\n\n/**\n * Define an email sender backed by Amazon SES.\n *\n * Creates an SES Email Identity for the specified domain and provides\n * a typed `EmailClient` to other handlers via `deps`.\n *\n * On first deploy, DKIM DNS records are printed to the console.\n * Add them to your DNS provider to verify the domain.\n *\n * @param options - Mailer configuration with the domain to send from\n * @returns Handler object used by the deployment system and as a `deps` value\n *\n * @example Basic mailer with HTTP handler\n * ```typescript\n * export const mailer = defineMailer({ domain: \"myapp.com\" });\n *\n * export const api = defineApi({\n * basePath: \"/signup\",\n * deps: { mailer },\n * post: async ({ req, deps }) => {\n * await deps.mailer.send({\n * from: \"hello@myapp.com\",\n * to: req.body.email,\n * subject: \"Welcome!\",\n * html: \"<h1>Hi!</h1>\",\n * });\n * return { status: 200, body: { ok: true } };\n * },\n * });\n * ```\n */\nexport const defineMailer = () => (options: MailerConfig): MailerHandler => ({\n __brand: \"effortless-mailer\",\n __spec: options,\n});\n","import type { LambdaWithPermissions, AnySecretRef, ResolveConfig, Duration, ConfigFactory, LogLevel, Permission } from \"./handler-options\";\nimport { resolveConfigFactory } from \"./handler-options\";\nimport type { AnyDepHandler, ResolveDeps } from \"./handler-deps\";\nimport type { StaticFiles, ResponseStream } from \"./shared\";\nimport type { HttpRequest, HttpResponse } from \"./shared\";\nimport type { AuthHelpers } from \"./auth\";\n\n// ============ Auth types ============\n\n/** Auth config options (user-facing) */\nexport type AuthOptions<A = unknown> = {\n /** HMAC secret for signing session cookies. Use `secret()` or `param()` in config. */\n secret: string;\n /** Default session lifetime (default: \"7d\"). */\n expiresIn?: Duration;\n /** Optional API token strategy for external clients. */\n apiToken?: {\n /** HTTP header to read the token from. Default: \"authorization\" (strips \"Bearer \" prefix). */\n header?: string;\n /** Verify the token value and return session data, or null if invalid. */\n verify: (value: string) => A | null | Promise<A | null>;\n /** Cache verified token results for this duration. */\n cacheTtl?: Duration;\n };\n};\n\n/** Branded auth config — created by `enableAuth<A>()` helper, carries session type A */\nexport type ApiAuthConfig<A = unknown> = AuthOptions<A> & { readonly __sessionType: A };\n\n/** Type of the `enableAuth` helper injected into setup args */\nexport type EnableAuth = <A = unknown>(options: AuthOptions<A>) => ApiAuthConfig<A>;\n\n/** Runtime implementation of enableAuth — identity function with branded return type */\nexport const enableAuth: EnableAuth = <A = unknown>(options: AuthOptions<A>): ApiAuthConfig<A> =>\n options as ApiAuthConfig<A>;\n\n/** Extract session type A from ctx.auth if present */\ntype ExtractAuth<C> = C extends { auth: ApiAuthConfig<infer A> } ? A : undefined;\n\n/** Property names reserved by the framework — cannot be used in setup return */\ntype ReservedKeys = 'req' | 'input' | 'stream' | 'ok' | 'fail';\n\n// ============ Response helpers ============\n\n/** Success response helper: `ok({ data })` → `{ status: 200, body: { data } }` */\nexport type OkHelper = (body?: unknown, status?: number) => HttpResponse;\n/** Error response helper: `fail(\"message\")` → `{ status: 400, body: { error: \"message\" } }` */\nexport type FailHelper = (message: string, status?: number) => HttpResponse;\n\n// ============ Route types ============\n\ntype HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n\n/** Parsed route definition stored at runtime */\nexport type RouteEntry = {\n method: HttpMethod;\n path: string;\n onRequest: (...args: any[]) => any;\n public?: boolean;\n};\n\n/** Spread ctx into route args: Omit auth config, add AuthHelpers if present */\ntype SpreadCtx<C> =\n & ([C] extends [undefined] ? {} : Omit<C & {}, 'auth'>)\n & ([ExtractAuth<C>] extends [undefined] ? {} : { auth: AuthHelpers<ExtractAuth<C>> });\n\n/** Callback args available inside each route — ctx is spread into args */\ntype RouteArgs<C, ST> =\n & SpreadCtx<C>\n & { req: HttpRequest; input: unknown; ok: OkHelper; fail: FailHelper }\n & ([ST] extends [true] ? { stream: ResponseStream } : {});\n\n/** Route handler function */\ntype RouteHandler<C, ST> = (args: RouteArgs<C, ST>) => Promise<HttpResponse | void> | HttpResponse | void;\n\n/** Route options (e.g. public) */\ntype RouteOptions = { public?: boolean };\n\n// ============ Setup args ============\n\n/** Setup factory — receives deps/config/files/enableAuth based on what was declared */\ntype SetupArgs<D, P, HasFiles extends boolean> =\n & { enableAuth: EnableAuth; ok: OkHelper; fail: FailHelper }\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { config: ResolveConfig<P & {}> })\n & (HasFiles extends true ? { files: StaticFiles } : {});\n\n/** Validate that setup return type does not use reserved property names */\ntype ValidateSetupReturn<C> = C & { [K in ReservedKeys]?: never };\n\n// ============ Static config ============\n\n/** Static config extracted by AST (no runtime callbacks) */\nexport type ApiConfig = {\n /** Lambda function settings (memory, timeout, permissions, etc.) */\n lambda?: LambdaWithPermissions;\n /** Base path prefix for all routes (e.g., \"/api\") */\n basePath: `/${string}`;\n /** Enable response streaming. When true, the Lambda Function URL uses RESPONSE_STREAM invoke mode. */\n stream?: boolean;\n};\n\n// ============ Internal handler object ============\n\n/** Internal handler object created by defineApi */\nexport type ApiHandler<C = undefined> = {\n readonly __brand: \"effortless-api\";\n readonly __spec: ApiConfig;\n readonly onError?: (...args: any[]) => any;\n readonly onCleanup?: (...args: any[]) => any;\n readonly setup?: (...args: any[]) => C | Promise<C>;\n readonly deps?: Record<string, unknown> | (() => Record<string, unknown>);\n readonly config?: Record<string, unknown>;\n readonly static?: string[];\n readonly routes?: RouteEntry[];\n};\n\n// ============ Builder options (plain values, no inference) ============\n\n/** Options passed to `defineApi()` */\ntype ApiOptions = {\n /** Base path prefix for all routes (e.g., \"/api\") */\n basePath: `/${string}`;\n /** Lambda memory in MB (default: 256) */\n memory?: number;\n /** Lambda timeout (default: 30s). Accepts seconds or duration string: `\"30s\"`, `\"5m\"` */\n timeout?: Duration;\n /** Additional IAM permissions for the Lambda */\n permissions?: Permission[];\n /** Logging verbosity: \"error\" (errors only), \"info\" (+ execution summary), \"debug\" (+ input/output). Default: \"info\" */\n logLevel?: LogLevel;\n /** Enable response streaming. When true, routes receive a `stream` arg for SSE. */\n stream?: boolean;\n /** Static file glob patterns to bundle into the Lambda ZIP */\n static?: string[];\n};\n\n// ============ ApiRoutes — returned after first route method ============\n\n/**\n * Finalized API handler with route-adding methods.\n * Has `__brand` so CLI discovers it. Each `.get()/.post()` adds a route and returns self.\n */\nexport interface ApiRoutes<C = undefined, ST extends boolean = false> extends ApiHandler<C> {\n get(path: `/${string}`, handler: RouteHandler<C, ST>, options?: RouteOptions): ApiRoutes<C, ST>;\n post(path: `/${string}`, handler: RouteHandler<C, ST>, options?: RouteOptions): ApiRoutes<C, ST>;\n put(path: `/${string}`, handler: RouteHandler<C, ST>, options?: RouteOptions): ApiRoutes<C, ST>;\n patch(path: `/${string}`, handler: RouteHandler<C, ST>, options?: RouteOptions): ApiRoutes<C, ST>;\n delete(path: `/${string}`, handler: RouteHandler<C, ST>, options?: RouteOptions): ApiRoutes<C, ST>;\n}\n\n// ============ Builder ============\n\n/**\n * Builder interface for defining API handlers.\n *\n * Each method sets exactly one generic, so inference happens one step at a time.\n * This prevents cascading type errors when one property has a mistake.\n */\ninterface ApiBuilder<\n D = undefined,\n P = undefined,\n C = undefined,\n ST extends boolean = false,\n HasFiles extends boolean = false,\n> {\n /** Declare handler dependencies (tables, queues, buckets, mailers) */\n deps<D2 extends Record<string, AnyDepHandler>>(\n fn: () => D2\n ): ApiBuilder<D2, P, C, ST, HasFiles>;\n\n /** Declare SSM secrets */\n config<P2 extends Record<string, AnySecretRef>>(\n fn: ConfigFactory<P2>\n ): ApiBuilder<D, P2, C, ST, HasFiles>;\n\n /** Initialize shared state on cold start. Receives deps/config/files based on what was declared. */\n setup<C2>(\n fn: (args: SetupArgs<D, P, HasFiles>) => ValidateSetupReturn<C2> | Promise<ValidateSetupReturn<C2>>\n ): ApiBuilder<D, P, C2, ST, HasFiles>;\n\n /** Handle errors thrown by routes */\n onError(\n fn: (args: { error: unknown; req: HttpRequest; ok: OkHelper; fail: FailHelper } & SpreadCtx<C>) => HttpResponse\n ): ApiBuilder<D, P, C, ST, HasFiles>;\n\n /** Cleanup callback — runs after each invocation, before Lambda freezes */\n onCleanup(\n fn: (args: SpreadCtx<C>) => void | Promise<void>\n ): ApiBuilder<D, P, C, ST, HasFiles>;\n\n /** Add a GET route (terminal — returns finalized handler with route methods) */\n get(path: `/${string}`, handler: RouteHandler<C, ST>, options?: RouteOptions): ApiRoutes<C, ST>;\n /** Add a POST route (terminal) */\n post(path: `/${string}`, handler: RouteHandler<C, ST>, options?: RouteOptions): ApiRoutes<C, ST>;\n /** Add a PUT route (terminal) */\n put(path: `/${string}`, handler: RouteHandler<C, ST>, options?: RouteOptions): ApiRoutes<C, ST>;\n /** Add a PATCH route (terminal) */\n patch(path: `/${string}`, handler: RouteHandler<C, ST>, options?: RouteOptions): ApiRoutes<C, ST>;\n /** Add a DELETE route (terminal) */\n delete(path: `/${string}`, handler: RouteHandler<C, ST>, options?: RouteOptions): ApiRoutes<C, ST>;\n}\n\n// ============ Implementation ============\n\n/**\n * Define an API with typed routes using a builder pattern.\n *\n * @example\n * ```typescript\n * // Minimal\n * export default defineApi({ basePath: \"/hello\" })\n * .get(\"/\", async ({ req, ok }) => ok({ message: \"Hello!\" }))\n *\n * // Full\n * export const api = defineApi({ basePath: \"/api\", timeout: \"30s\" })\n * .deps(() => ({ users }))\n * .config(({ defineSecret }) => ({ dbUrl: defineSecret() }))\n * .setup(async ({ deps, config, enableAuth }) => ({\n * users: deps.users,\n * auth: enableAuth<Session>({ secret: config.dbUrl }),\n * }))\n * .onError(({ error, fail }) => fail(String(error), 500))\n * .get(\"/me\", async ({ users, auth, ok }) => ok(auth.session))\n * .post(\"/login\", async ({ auth, ok }) => ok(await auth.createSession()), { public: true })\n * ```\n */\nexport function defineApi(options: ApiOptions & { static: string[] }): ApiBuilder<undefined, undefined, undefined, false, true>;\nexport function defineApi<const O extends ApiOptions>(\n options: O,\n): ApiBuilder<undefined, undefined, undefined, O[\"stream\"] extends true ? true : false, O[\"static\"] extends string[] ? true : false>;\nexport function defineApi(\n options: ApiOptions,\n): ApiBuilder {\n const { basePath, stream, static: staticFiles, ...lambdaConfig } = options;\n const hasLambda = Object.keys(lambdaConfig).length > 0;\n\n const state: {\n spec: ApiConfig;\n deps?: () => Record<string, unknown>;\n config?: Record<string, unknown>;\n static?: string[];\n setup?: (...args: any[]) => any;\n onError?: (...args: any[]) => any;\n onCleanup?: (...args: any[]) => any;\n routes: RouteEntry[];\n } = {\n spec: {\n basePath,\n ...(hasLambda ? { lambda: lambdaConfig } : {}),\n ...(stream ? { stream } : {}),\n },\n ...(staticFiles ? { static: staticFiles } : {}),\n routes: [],\n };\n\n const addRoute = (method: HttpMethod, path: string, handler: Function, opts?: RouteOptions) => {\n state.routes.push({\n method,\n path,\n onRequest: handler as any,\n ...(opts?.public ? { public: true } : {}),\n });\n };\n\n const finalize = (): ApiRoutes => {\n const handler: any = {\n __brand: \"effortless-api\",\n __spec: state.spec,\n routes: state.routes,\n ...(state.onError ? { onError: state.onError } : {}),\n ...(state.onCleanup ? { onCleanup: state.onCleanup } : {}),\n ...(state.setup ? { setup: state.setup } : {}),\n ...(state.deps ? { deps: state.deps } : {}),\n ...(state.config ? { config: state.config } : {}),\n ...(state.static ? { static: state.static } : {}),\n };\n\n // Add route methods to the finalized handler\n for (const m of [\"get\", \"post\", \"put\", \"patch\", \"delete\"] as const) {\n handler[m] = (path: string, fn: Function, opts?: RouteOptions) => {\n addRoute(m.toUpperCase() as HttpMethod, path, fn, opts);\n handler.routes = state.routes;\n return handler;\n };\n }\n\n return handler as ApiRoutes;\n };\n\n const builder: ApiBuilder = {\n deps(fn) {\n state.deps = fn as any;\n return builder as any;\n },\n config(fn) {\n state.config = resolveConfigFactory(fn) as any;\n return builder as any;\n },\n setup(fn) {\n state.setup = fn as any;\n return builder as any;\n },\n onError(fn) {\n state.onError = fn as any;\n return builder as any;\n },\n onCleanup(fn) {\n state.onCleanup = fn as any;\n return builder as any;\n },\n get(path, handler, opts) {\n addRoute(\"GET\", path, handler, opts);\n return finalize() as any;\n },\n post(path, handler, opts) {\n addRoute(\"POST\", path, handler, opts);\n return finalize() as any;\n },\n put(path, handler, opts) {\n addRoute(\"PUT\", path, handler, opts);\n return finalize() as any;\n },\n patch(path, handler, opts) {\n addRoute(\"PATCH\", path, handler, opts);\n return finalize() as any;\n },\n delete(path, handler, opts) {\n addRoute(\"DELETE\", path, handler, opts);\n return finalize() as any;\n },\n };\n\n return builder;\n}\n"],"mappings":";AAwGO,IAAM,eAAe,CAAC,WAA+C;;;AC7DrE,IAAM,YAAY,CAAC,MAAwB;AAChD,MAAI,OAAO,MAAM,SAAU,QAAO;AAClC,QAAM,QAAQ,EAAE,MAAM,4BAA4B;AAClD,MAAI,CAAC,MAAO,OAAM,IAAI,MAAM,sBAAsB,CAAC,GAAG;AACtD,QAAM,IAAI,OAAO,MAAM,CAAC,CAAC;AACzB,QAAM,OAAO,MAAM,CAAC;AACpB,MAAI,SAAS,IAAK,QAAO,IAAI;AAC7B,MAAI,SAAS,IAAK,QAAO,IAAI;AAC7B,MAAI,SAAS,IAAK,QAAO,IAAI;AAC7B,SAAO;AACT;AAqFO,IAAM,eAA+B,CAC1C,YACiB;AACjB,SAAO;AAAA,IACL,SAAS;AAAA,IACT,GAAI,SAAS,MAAM,EAAE,KAAK,QAAQ,IAAI,IAAI,CAAC;AAAA,IAC3C,GAAI,SAAS,WAAW,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC;AAAA,IAC1D,GAAI,gBAAgB,WAAW,CAAC,KAAK,EAAE,WAAY,QAAgD,UAAU,IAAI,CAAC;AAAA,EACpH;AACF;AAGO,IAAM,gBAA+B,EAAE,aAAa;AAGpD,IAAM,uBAAuB,CAAI,WACtC,OAA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Y;AAClE,cAAQ,CAAC,IAAI,CAAC,MAAc,IAAc,SAAwB;AAChE,iBAAS,EAAE,YAAY,GAAiB,MAAM,IAAI,IAAI;AACtD,gBAAQ,SAAS,MAAM;AACvB,eAAO;AAAA,MACT;AAAA,IACF;AAEA,WAAO;AAAA,EACT;AAEA,QAAM,UAAsB;AAAA,IAC1B,KAAK,IAAI;AACP,YAAM,OAAO;AACb,aAAO;AAAA,IACT;AAAA,IACA,OAAO,IAAI;AACT,YAAM,SAAS,qBAAqB,EAAE;AACtC,aAAO;AAAA,IACT;AAAA,IACA,MAAM,IAAI;AACR,YAAM,QAAQ;AACd,aAAO;AAAA,IACT;AAAA,IACA,QAAQ,IAAI;AACV,YAAM,UAAU;AAChB,aAAO;AAAA,IACT;AAAA,IACA,UAAU,IAAI;AACZ,YAAM,YAAY;AAClB,aAAO;AAAA,IACT;AAAA,IACA,IAAI,MAAM,SAAS,MAAM;AACvB,eAAS,OAAO,MAAM,SAAS,IAAI;AACnC,aAAO,SAAS;AAAA,IAClB;AAAA,IACA,KAAK,MAAM,SAAS,MAAM;AACxB,eAAS,QAAQ,MAAM,SAAS,IAAI;AACpC,aAAO,SAAS;AAAA,IAClB;AAAA,IACA,IAAI,MAAM,SAAS,MAAM;AACvB,eAAS,OAAO,MAAM,SAAS,IAAI;AACnC,aAAO,SAAS;AAAA,IAClB;AAAA,IACA,MAAM,MAAM,SAAS,MAAM;AACzB,eAAS,SAAS,MAAM,SAAS,IAAI;AACrC,aAAO,SAAS;AAAA,IAClB;AAAA,IACA,OAAO,MAAM,SAAS,MAAM;AAC1B,eAAS,UAAU,MAAM,SAAS,IAAI;AACtC,aAAO,SAAS;AAAA,IAClB;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  AUTH_COOKIE_NAME,
3
3
  createHandlerRuntime
4
- } from "../chunk-EZG3NX42.js";
4
+ } from "../chunk-ISJC6CHC.js";
5
5
 
6
6
  // src/runtime/wrap-api.ts
7
7
  var CONTENT_TYPE_MAP = {
@@ -23,32 +23,6 @@ var parseBody = (body, isBase64) => {
23
23
  return decoded;
24
24
  }
25
25
  };
26
- var buildGetMatchers = (routes, basePath) => Object.entries(routes).map(([pattern, handler]) => {
27
- const fullPattern = (basePath + pattern).replace(/\/\/+/g, "/");
28
- const paramNames = [];
29
- const regexStr = fullPattern.replace(/\{(\w+)\}/g, (_, name) => {
30
- paramNames.push(name);
31
- return "([^/]+)";
32
- });
33
- return {
34
- regex: new RegExp(`^${regexStr}$`),
35
- paramNames,
36
- handler
37
- };
38
- });
39
- var matchRoute = (matchers, path) => {
40
- for (const matcher of matchers) {
41
- const match = path.match(matcher.regex);
42
- if (match) {
43
- const params = {};
44
- matcher.paramNames.forEach((name, i) => {
45
- params[name] = match[i + 1];
46
- });
47
- return { handler: matcher.handler, params };
48
- }
49
- }
50
- return null;
51
- };
52
26
  var toResult = (r) => {
53
27
  const resolved = r.contentType ? CONTENT_TYPE_MAP[r.contentType] : void 0;
54
28
  const customContentType = resolved ?? r.headers?.["content-type"] ?? r.headers?.["Content-Type"];
@@ -74,14 +48,16 @@ var unauthorized = () => ({
74
48
  headers: { "Content-Type": "application/json" },
75
49
  body: JSON.stringify({ error: "Unauthorized" })
76
50
  });
77
- var isPublicPath = (path, patterns) => patterns.some(
78
- (p) => p.endsWith("*") ? path.startsWith(p.slice(0, -1)) : path === p
51
+ var findRoute = (routes, method, relativePath) => routes.find(
52
+ (r) => r.path === relativePath && (r.method === method || r.method === "GET" && method === "HEAD")
79
53
  );
80
54
  var wrapApi = (handler) => {
81
- const rt = createHandlerRuntime(handler, "api", handler.__spec.lambda?.logLevel ?? "info");
55
+ const rt = createHandlerRuntime(handler, "api", handler.__spec.lambda?.logLevel ?? "info", () => ({ ok, fail }));
82
56
  const basePath = handler.__spec.basePath;
83
57
  const isStream = handler.__spec.stream === true;
84
- const getMatchers = handler.get ? buildGetMatchers(handler.get, basePath) : [];
58
+ const routes = handler.routes ?? [];
59
+ const ok = (body, status = 200) => ({ status, body });
60
+ const fail = (message, status = 400) => ({ status, body: { error: message } });
85
61
  const defaultError = (error, status) => {
86
62
  console.error(`[effortless:${rt.handlerName}]`, error);
87
63
  return toResult({
@@ -92,93 +68,91 @@ var wrapApi = (handler) => {
92
68
  }
93
69
  });
94
70
  };
71
+ const extractRelativePath = (fullPath) => {
72
+ const prefix = basePath.endsWith("/") ? basePath.slice(0, -1) : basePath;
73
+ if (!fullPath.startsWith(prefix)) return null;
74
+ const rest = fullPath.slice(prefix.length);
75
+ if (rest === "" || rest === "/") return "/";
76
+ if (!rest.startsWith("/")) return null;
77
+ return rest;
78
+ };
95
79
  const handleRequest = async (event, streamCtx) => {
96
80
  const startTime = Date.now();
97
81
  rt.patchConsole();
98
82
  let sharedArgs;
83
+ let ctxProps = {};
99
84
  try {
85
+ const method = event.requestContext?.http?.method ?? event.httpMethod ?? "GET";
86
+ const path = event.requestContext?.http?.path ?? event.path ?? "/";
87
+ const headers = event.headers ?? {};
88
+ const query = event.queryStringParameters ?? {};
89
+ const params = event.pathParameters ?? {};
90
+ const body = parseBody(event.body, event.isBase64Encoded ?? false);
91
+ const merged = {
92
+ ...query,
93
+ ...typeof body === "object" && body !== null ? body : {},
94
+ ...params
95
+ };
100
96
  const req = {
101
- method: event.requestContext?.http?.method ?? event.httpMethod ?? "GET",
102
- path: event.requestContext?.http?.path ?? event.path ?? "/",
103
- headers: event.headers ?? {},
104
- query: event.queryStringParameters ?? {},
105
- params: event.pathParameters ?? {},
106
- body: parseBody(event.body, event.isBase64Encoded ?? false),
97
+ method,
98
+ path,
99
+ headers,
100
+ query,
101
+ params,
102
+ body,
107
103
  rawBody: event.body
108
104
  };
109
- const input = { method: req.method, path: req.path, query: req.query, body: req.body };
105
+ const logInput = { method, path, query, body };
106
+ const relativePath = extractRelativePath(req.path);
107
+ if (!relativePath) {
108
+ rt.logExecution(startTime, logInput, { status: 404 });
109
+ return notFound();
110
+ }
111
+ const entry = findRoute(routes, req.method, relativePath);
112
+ if (!entry) {
113
+ rt.logExecution(startTime, logInput, { status: 404 });
114
+ return notFound();
115
+ }
110
116
  const cookieHeader = req.headers["cookie"] ?? req.headers["Cookie"] ?? "";
111
117
  let authCookie;
112
118
  if (cookieHeader) {
113
119
  const match = cookieHeader.match(new RegExp(`(?:^|;\\s*)${AUTH_COOKIE_NAME}=([^;]+)`));
114
120
  if (match) authCookie = match[1];
115
121
  }
116
- const authHeaderName = handler.apiToken?.header ?? "authorization";
122
+ const authHeaderName = "authorization";
117
123
  const authHeader = req.headers[authHeaderName] ?? req.headers[authHeaderName.toLowerCase()] ?? void 0;
118
- sharedArgs = await rt.commonArgs(authCookie, authHeader);
119
- if (handler.auth && sharedArgs.auth) {
120
- const auth = sharedArgs.auth;
121
- const publicPaths = handler.auth.public ?? [];
122
- const routePath = req.path.replace(new RegExp(`^${basePath}`), "") || "/";
123
- if (!auth.session && !isPublicPath(routePath, publicPaths) && !isPublicPath(req.path, publicPaths)) {
124
- rt.logExecution(startTime, input, { status: 401 });
124
+ sharedArgs = await rt.commonArgs(authCookie, authHeader, req.headers);
125
+ if (sharedArgs.auth) {
126
+ const auth2 = sharedArgs.auth;
127
+ if (!auth2.session && !entry.public) {
128
+ rt.logExecution(startTime, logInput, { status: 401 });
125
129
  return unauthorized();
126
130
  }
127
131
  }
128
- if (req.method === "GET" || req.method === "HEAD") {
129
- const matched = matchRoute(getMatchers, req.path);
130
- if (!matched) {
131
- rt.logExecution(startTime, input, { status: 404 });
132
- return notFound();
133
- }
134
- req.params = { ...req.params, ...matched.params };
135
- const args = { req, ...sharedArgs };
136
- if (streamCtx) args.stream = streamCtx.stream;
137
- try {
138
- const response = await matched.handler(args);
139
- if (response) {
140
- rt.logExecution(startTime, input, response.body);
141
- return toResult(response);
142
- }
143
- rt.logExecution(startTime, input, "[stream]");
144
- return void 0;
145
- } catch (error) {
146
- rt.logError(startTime, input, error);
147
- return handler.onError ? toResult(handler.onError({ error, req, ...sharedArgs })) : defaultError(error, 500);
148
- }
149
- }
150
- if (req.method === "POST" && handler.post) {
151
- const args = { req, ...sharedArgs };
152
- if (streamCtx) args.stream = streamCtx.stream;
153
- if (handler.schema) {
154
- try {
155
- args.data = handler.schema(req.body);
156
- } catch (error) {
157
- rt.logError(startTime, input, error);
158
- return handler.onError ? toResult(handler.onError({ error, req, ...sharedArgs })) : defaultError(error, 400);
159
- }
160
- }
161
- try {
162
- const response = await handler.post(args);
163
- if (response) {
164
- rt.logExecution(startTime, input, response.body);
165
- return toResult(response);
166
- }
167
- rt.logExecution(startTime, input, "[stream]");
168
- return void 0;
169
- } catch (error) {
170
- rt.logError(startTime, input, error);
171
- return handler.onError ? toResult(handler.onError({ error, req, ...sharedArgs })) : defaultError(error, 500);
132
+ const { ctx, auth, ...rest } = sharedArgs;
133
+ ctxProps = ctx && typeof ctx === "object" ? { ...ctx } : {};
134
+ delete ctxProps.auth;
135
+ const args = { ...ctxProps, req, input: merged, ok, fail, ...rest };
136
+ if (auth) args.auth = auth;
137
+ if (streamCtx) args.stream = streamCtx.stream;
138
+ try {
139
+ const response = await entry.onRequest(args);
140
+ if (response) {
141
+ rt.logExecution(startTime, logInput, response.body);
142
+ return toResult(response);
172
143
  }
144
+ rt.logExecution(startTime, logInput, "[stream]");
145
+ return void 0;
146
+ } catch (error) {
147
+ rt.logError(startTime, logInput, error);
148
+ return handler.onError ? toResult(handler.onError({ error, req, ok, fail, ...ctxProps })) : defaultError(error, 500);
173
149
  }
174
- rt.logExecution(startTime, input, { status: 404 });
175
- return notFound();
176
150
  } finally {
177
- if (handler.onAfterInvoke && sharedArgs) {
151
+ if (handler.onCleanup && sharedArgs) {
178
152
  try {
179
- await handler.onAfterInvoke(sharedArgs);
153
+ await handler.onCleanup(ctxProps);
180
154
  } catch (e) {
181
- console.error(`[effortless:${rt.handlerName}] onAfterInvoke error`, e);
155
+ console.error(`[effortless:${rt.handlerName}] onCleanup error`, e);
182
156
  }
183
157
  }
184
158
  rt.restoreConsole();
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  createBucketClient,
3
3
  createHandlerRuntime
4
- } from "../chunk-EZG3NX42.js";
4
+ } from "../chunk-ISJC6CHC.js";
5
5
 
6
6
  // src/runtime/wrap-bucket.ts
7
7
  var ENV_DEP_SELF = "EFF_DEP_SELF";
@@ -26,11 +26,15 @@ var wrapBucket = (handler) => {
26
26
  return async (event) => {
27
27
  const startTime = Date.now();
28
28
  rt.patchConsole();
29
- let shared;
29
+ let ctxProps = {};
30
30
  try {
31
31
  const rawRecords = event.Records ?? [];
32
32
  const input = { recordCount: rawRecords.length };
33
- shared = { ...await rt.commonArgs(), bucket: getSelfClient() };
33
+ const common = await rt.commonArgs();
34
+ const ctx = common.ctx;
35
+ ctxProps = ctx && typeof ctx === "object" ? { ...ctx } : {};
36
+ const bucket = getSelfClient();
37
+ const shared = { bucket, ...ctxProps };
34
38
  let errorCount = 0;
35
39
  for (const record of rawRecords) {
36
40
  const bucketEvent = {
@@ -58,11 +62,11 @@ var wrapBucket = (handler) => {
58
62
  rt.logExecution(startTime, input, { processedCount: rawRecords.length });
59
63
  }
60
64
  } finally {
61
- if (handler.onAfterInvoke && shared) {
65
+ if (handler.onCleanup) {
62
66
  try {
63
- await handler.onAfterInvoke(shared);
67
+ await handler.onCleanup(ctxProps);
64
68
  } catch (e) {
65
- console.error(`[effortless:${rt.handlerName}] onAfterInvoke error`, e);
69
+ console.error(`[effortless:${rt.handlerName}] onCleanup error`, e);
66
70
  }
67
71
  }
68
72
  rt.restoreConsole();