effortless-aws 0.1.0 → 0.2.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/{chunk-I5TS7O5S.js → chunk-7JVA4742.js} +149 -2
- package/dist/cli/index.js +190 -141
- package/dist/cli/index.js.map +1 -1
- package/dist/index.d.ts +40 -1
- package/dist/index.js +92 -0
- package/dist/index.js.map +1 -1
- package/dist/runtime/wrap-http.js +25 -43
- package/dist/runtime/wrap-table-stream.js +47 -74
- package/package.json +1 -2
package/dist/index.d.ts
CHANGED
|
@@ -600,4 +600,43 @@ type HttpHandler<T = undefined, C = undefined, D = undefined, P = undefined> = {
|
|
|
600
600
|
*/
|
|
601
601
|
declare const defineHttp: <T = undefined, C = undefined, D extends Record<string, AnyTableHandler> | undefined = undefined, P extends Record<string, AnyParamRef> | undefined = undefined>(options: DefineHttpOptions<T, C, D, P>) => HttpHandler<T, C, D, P>;
|
|
602
602
|
|
|
603
|
-
|
|
603
|
+
type BasePlatformEntity = {
|
|
604
|
+
pk: string;
|
|
605
|
+
sk: string;
|
|
606
|
+
type: string;
|
|
607
|
+
ttl?: number;
|
|
608
|
+
};
|
|
609
|
+
type ExecutionEntry = {
|
|
610
|
+
id: string;
|
|
611
|
+
ts: string;
|
|
612
|
+
ms: number;
|
|
613
|
+
in: unknown;
|
|
614
|
+
out?: unknown;
|
|
615
|
+
};
|
|
616
|
+
type ErrorEntry = {
|
|
617
|
+
id: string;
|
|
618
|
+
ts: string;
|
|
619
|
+
ms: number;
|
|
620
|
+
in: unknown;
|
|
621
|
+
err: string;
|
|
622
|
+
};
|
|
623
|
+
type ExecutionLogEntity = BasePlatformEntity & {
|
|
624
|
+
type: "execution-log";
|
|
625
|
+
handlerName: string;
|
|
626
|
+
handlerType: "http" | "table";
|
|
627
|
+
executions: ExecutionEntry[];
|
|
628
|
+
errors: ErrorEntry[];
|
|
629
|
+
};
|
|
630
|
+
type PlatformEntity = ExecutionLogEntity;
|
|
631
|
+
|
|
632
|
+
type PlatformClient = {
|
|
633
|
+
appendExecution(handlerName: string, handlerType: "http" | "table", entry: ExecutionEntry): Promise<void>;
|
|
634
|
+
appendError(handlerName: string, handlerType: "http" | "table", entry: ErrorEntry): Promise<void>;
|
|
635
|
+
get<T extends PlatformEntity>(pk: string, sk: string): Promise<T | undefined>;
|
|
636
|
+
query<T extends PlatformEntity>(pk: string, skPrefix?: string): Promise<T[]>;
|
|
637
|
+
put(entity: PlatformEntity): Promise<void>;
|
|
638
|
+
tableName: string;
|
|
639
|
+
};
|
|
640
|
+
declare const createPlatformClient: () => PlatformClient | undefined;
|
|
641
|
+
|
|
642
|
+
export { type BasePlatformEntity, type DefineHttpOptions, type DefineTableOptions, type EffortlessConfig, type ErrorEntry, type ExecutionEntry, type ExecutionLogEntity, type FailedRecord, type HttpConfig, type HttpHandler, type HttpHandlerFn, type HttpMethod, type HttpRequest, type HttpResponse, type KeyType, type ParamRef, type PlatformClient, type PlatformEntity, type QueryParams, type ResolveDeps, type ResolveParams, type StreamView, type TableBatchCompleteFn, type TableBatchFn, type TableClient, type TableConfig, type TableHandler, type TableKey, type TableRecord, type TableRecordFn, createPlatformClient, defineConfig, defineHttp, defineTable, param };
|
package/dist/index.js
CHANGED
|
@@ -39,7 +39,99 @@ var param = (key, transform) => ({
|
|
|
39
39
|
key,
|
|
40
40
|
...transform ? { transform } : {}
|
|
41
41
|
});
|
|
42
|
+
|
|
43
|
+
// src/runtime/platform-client.ts
|
|
44
|
+
import { DynamoDB } from "@aws-sdk/client-dynamodb";
|
|
45
|
+
import { marshall, unmarshall } from "@aws-sdk/util-dynamodb";
|
|
46
|
+
|
|
47
|
+
// src/runtime/platform-types.ts
|
|
48
|
+
var ENV_PLATFORM_TABLE = "EFF_PLATFORM_TABLE";
|
|
49
|
+
var DEFAULT_TTL_SECONDS = 7 * 24 * 60 * 60;
|
|
50
|
+
var dateBucket = (date = /* @__PURE__ */ new Date()) => date.toISOString().slice(0, 10);
|
|
51
|
+
var computeTtl = (ttlSeconds = DEFAULT_TTL_SECONDS) => Math.floor(Date.now() / 1e3) + ttlSeconds;
|
|
52
|
+
|
|
53
|
+
// src/runtime/platform-client.ts
|
|
54
|
+
var createPlatformClient = () => {
|
|
55
|
+
const tableName = process.env[ENV_PLATFORM_TABLE];
|
|
56
|
+
if (!tableName) return void 0;
|
|
57
|
+
let client = null;
|
|
58
|
+
const getClient = () => client ??= new DynamoDB({});
|
|
59
|
+
const appendToList = async (handlerName, handlerType, listAttr, entry) => {
|
|
60
|
+
const sk = `EXEC#${dateBucket()}`;
|
|
61
|
+
try {
|
|
62
|
+
await getClient().updateItem({
|
|
63
|
+
TableName: tableName,
|
|
64
|
+
Key: marshall({ pk: `HANDLER#${handlerName}`, sk }),
|
|
65
|
+
UpdateExpression: "SET #list = list_append(if_not_exists(#list, :empty), :entry), #type = :type, #hn = :hn, #ht = :ht, #ttl = :ttl",
|
|
66
|
+
ExpressionAttributeNames: {
|
|
67
|
+
"#list": listAttr,
|
|
68
|
+
"#type": "type",
|
|
69
|
+
"#hn": "handlerName",
|
|
70
|
+
"#ht": "handlerType",
|
|
71
|
+
"#ttl": "ttl"
|
|
72
|
+
},
|
|
73
|
+
ExpressionAttributeValues: marshall(
|
|
74
|
+
{
|
|
75
|
+
":entry": [entry],
|
|
76
|
+
":empty": [],
|
|
77
|
+
":type": "execution-log",
|
|
78
|
+
":hn": handlerName,
|
|
79
|
+
":ht": handlerType,
|
|
80
|
+
":ttl": computeTtl()
|
|
81
|
+
},
|
|
82
|
+
{ removeUndefinedValues: true }
|
|
83
|
+
)
|
|
84
|
+
});
|
|
85
|
+
} catch (err) {
|
|
86
|
+
console.error("[effortless] Failed to write platform record:", err);
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
return {
|
|
90
|
+
tableName,
|
|
91
|
+
async appendExecution(handlerName, handlerType, entry) {
|
|
92
|
+
await appendToList(handlerName, handlerType, "executions", entry);
|
|
93
|
+
},
|
|
94
|
+
async appendError(handlerName, handlerType, entry) {
|
|
95
|
+
await appendToList(handlerName, handlerType, "errors", entry);
|
|
96
|
+
},
|
|
97
|
+
async get(pk, sk) {
|
|
98
|
+
const result = await getClient().getItem({
|
|
99
|
+
TableName: tableName,
|
|
100
|
+
Key: marshall({ pk, sk })
|
|
101
|
+
});
|
|
102
|
+
return result.Item ? unmarshall(result.Item) : void 0;
|
|
103
|
+
},
|
|
104
|
+
async query(pk, skPrefix) {
|
|
105
|
+
const names = { "#pk": "pk" };
|
|
106
|
+
const values = { ":pk": pk };
|
|
107
|
+
let keyCondition = "#pk = :pk";
|
|
108
|
+
if (skPrefix) {
|
|
109
|
+
names["#sk"] = "sk";
|
|
110
|
+
values[":sk"] = skPrefix;
|
|
111
|
+
keyCondition += " AND begins_with(#sk, :sk)";
|
|
112
|
+
}
|
|
113
|
+
const result = await getClient().query({
|
|
114
|
+
TableName: tableName,
|
|
115
|
+
KeyConditionExpression: keyCondition,
|
|
116
|
+
ExpressionAttributeNames: names,
|
|
117
|
+
ExpressionAttributeValues: marshall(values, { removeUndefinedValues: true })
|
|
118
|
+
});
|
|
119
|
+
return (result.Items ?? []).map((item) => unmarshall(item));
|
|
120
|
+
},
|
|
121
|
+
async put(entity) {
|
|
122
|
+
try {
|
|
123
|
+
await getClient().putItem({
|
|
124
|
+
TableName: tableName,
|
|
125
|
+
Item: marshall(entity, { removeUndefinedValues: true })
|
|
126
|
+
});
|
|
127
|
+
} catch (err) {
|
|
128
|
+
console.error("[effortless] Failed to write platform record:", err);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
};
|
|
42
133
|
export {
|
|
134
|
+
createPlatformClient,
|
|
43
135
|
defineConfig,
|
|
44
136
|
defineHttp,
|
|
45
137
|
defineTable,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config.ts","../src/handlers/define-http.ts","../src/handlers/define-table.ts","../src/handlers/param.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 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 settings applied to all handlers unless overridden.\n */\n defaults?: {\n /**\n * Lambda memory in MB.\n * @default 256\n */\n memory?: number;\n\n /**\n * Lambda timeout as a human-readable string.\n * @example \"30 seconds\", \"5 minutes\"\n */\n timeout?: string;\n\n /**\n * Lambda runtime.\n * @default \"nodejs22.x\"\n */\n runtime?: string;\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 { Permission } from \"./permissions\";\nimport type { TableHandler } from \"./define-table\";\nimport type { TableClient } from \"../runtime/table-client\";\nimport type { AnyParamRef, ResolveParams } from \"./param\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTableHandler = TableHandler<any, any, any, any, any>;\n\n/** Maps a deps declaration to resolved runtime client types */\nexport type ResolveDeps<D> = {\n [K in keyof D]: D[K] extends TableHandler<infer T, any, any, any, any> ? TableClient<T> : never;\n};\n\n/** HTTP methods supported by API Gateway */\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\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 (will be JSON serialized) */\n body?: unknown;\n /** Response headers */\n headers?: Record<string, string>;\n};\n\n/**\n * Configuration options extracted from DefineHttpOptions (without onRequest callback)\n */\nexport type HttpConfig = {\n /** Handler name. Defaults to export name if not specified */\n name?: string;\n /** HTTP method for the route */\n method: HttpMethod;\n /** Route path (e.g., \"/api/users\", \"/api/users/{id}\") */\n path: string;\n /** Lambda memory in MB (default: 256) */\n memory?: number;\n /** Lambda timeout in seconds (default: 30) */\n timeout?: number;\n /** Additional IAM permissions for the Lambda */\n permissions?: Permission[];\n};\n\n/**\n * Handler function type for HTTP endpoints\n *\n * @typeParam T - Type of the validated request body (from schema function)\n * @typeParam C - Type of the context/dependencies (from context function)\n * @typeParam D - Type of the deps (from deps declaration)\n * @typeParam P - Type of the params (from params declaration)\n */\nexport type HttpHandlerFn<T = undefined, C = undefined, D = undefined, P = undefined> =\n (args: { req: HttpRequest }\n & ([T] extends [undefined] ? {} : { data: T })\n & ([C] extends [undefined] ? {} : { ctx: C })\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { params: ResolveParams<P> })\n ) => Promise<HttpResponse>;\n\n/**\n * Context factory type — conditional on whether params are declared.\n * Without params: `() => C | Promise<C>`\n * With params: `(args: { params: ResolveParams<P> }) => C | Promise<C>`\n */\ntype ContextFactory<C, P> = [P] extends [undefined]\n ? () => C | Promise<C>\n : (args: { params: ResolveParams<P & {}> }) => C | Promise<C>;\n\n/**\n * Options for defining an HTTP endpoint\n *\n * @typeParam T - Type of the validated request body (inferred from schema function)\n * @typeParam C - Type of the context/dependencies returned by context function\n * @typeParam D - Type of the deps (from deps declaration)\n * @typeParam P - Type of the params (from params declaration)\n */\nexport type DefineHttpOptions<\n T = undefined,\n C = undefined,\n D extends Record<string, AnyTableHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined\n> = HttpConfig & {\n /**\n * Decode/validate function for the request body.\n * Called with the parsed body; should return typed data or throw on validation failure.\n * When provided, the handler receives validated `data` and invalid requests get a 400 response.\n *\n * Works with any validation library:\n * - Effect: `S.decodeUnknownSync(MySchema)`\n * - Zod: `(body) => myZodSchema.parse(body)`\n */\n schema?: (input: unknown) => T;\n /**\n * Error handler called when schema validation or onRequest throws.\n * Receives the error and request, returns an HttpResponse.\n * If not provided, defaults to 400 for validation errors and 500 for handler errors.\n */\n onError?: (error: unknown, req: HttpRequest) => HttpResponse;\n /**\n * Factory function to create context/dependencies for the request handler.\n * Called once on cold start, result is cached and reused across invocations.\n * When params are declared, receives resolved params as argument.\n * Supports both sync and async return values.\n */\n context?: ContextFactory<C, P>;\n /**\n * Dependencies on other handlers (tables, queues, etc.).\n * Typed clients are injected into the handler via the `deps` argument.\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 `params` argument.\n */\n params?: P;\n /** HTTP request handler function */\n onRequest: HttpHandlerFn<T, C, D, P>;\n};\n\n/**\n * Internal handler object created by defineHttp\n * @internal\n */\nexport type HttpHandler<T = undefined, C = undefined, D = undefined, P = undefined> = {\n readonly __brand: \"effortless-http\";\n readonly config: HttpConfig;\n readonly schema?: (input: unknown) => T;\n readonly onError?: (error: unknown, req: HttpRequest) => HttpResponse;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly context?: (...args: any[]) => C | Promise<C>;\n readonly deps?: D;\n readonly params?: P;\n readonly onRequest: HttpHandlerFn<T, C, D, P>;\n};\n\n/**\n * Define an HTTP endpoint that creates an API Gateway route + Lambda function\n *\n * @typeParam T - Type of the validated request body (inferred from schema function)\n * @typeParam C - Type of the context/dependencies (inferred from context function)\n * @typeParam D - Type of the deps (from deps declaration)\n * @typeParam P - Type of the params (from params declaration)\n * @param options - Configuration, optional schema, optional context factory, and request handler\n * @returns Handler object used by the deployment system\n *\n * @example Basic GET endpoint\n * ```typescript\n * export const hello = defineHttp({\n * method: \"GET\",\n * path: \"/hello\",\n * onRequest: async ({ req }) => ({\n * status: 200,\n * body: { message: \"Hello World!\" }\n * })\n * });\n * ```\n *\n * @example With SSM parameters\n * ```typescript\n * import { param } from \"effortless-aws\";\n *\n * export const api = defineHttp({\n * method: \"GET\",\n * path: \"/orders\",\n * params: {\n * dbUrl: param(\"database-url\"),\n * },\n * context: async ({ params }) => ({\n * pool: createPool(params.dbUrl),\n * }),\n * onRequest: async ({ req, ctx, params }) => ({\n * status: 200,\n * body: { dbUrl: params.dbUrl }\n * })\n * });\n * ```\n */\nexport const defineHttp = <\n T = undefined,\n C = undefined,\n D extends Record<string, AnyTableHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined\n>(\n options: DefineHttpOptions<T, C, D, P>\n): HttpHandler<T, C, D, P> => {\n const { onRequest, onError, context, schema, deps, params, ...config } = options;\n return {\n __brand: \"effortless-http\",\n config,\n ...(schema ? { schema } : {}),\n ...(onError ? { onError } : {}),\n ...(context ? { context } : {}),\n ...(deps ? { deps } : {}),\n ...(params ? { params } : {}),\n onRequest\n } as HttpHandler<T, C, D, P>;\n};\n","import type { Permission } from \"./permissions\";\nimport type { TableClient } from \"../runtime/table-client\";\nimport type { AnyParamRef, ResolveParams } from \"./param\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTableHandler = TableHandler<any, any, any, any, any>;\n\n/** Maps a deps declaration to resolved runtime client types */\ntype ResolveDeps<D> = {\n [K in keyof D]: D[K] extends TableHandler<infer T, any, any, any, any> ? TableClient<T> : never;\n};\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 extracted from DefineTableOptions (without onRecord/context)\n */\nexport type TableConfig = {\n /** Table/handler name. Defaults to export name if not specified */\n name?: string;\n /** Partition key definition */\n pk: TableKey;\n /** Sort key definition (optional) */\n sk?: TableKey;\n /** DynamoDB billing mode (default: \"PAY_PER_REQUEST\") */\n billingMode?: \"PAY_PER_REQUEST\" | \"PROVISIONED\";\n /** TTL attribute name for automatic item expiration */\n ttlAttribute?: string;\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 in seconds to gather records before invoking (0-300, default: 2) */\n batchWindow?: number;\n /** Where to start reading the stream (default: \"LATEST\") */\n startingPosition?: \"LATEST\" | \"TRIM_HORIZON\";\n /** Lambda memory in MB (default: 256) */\n memory?: number;\n /** Lambda timeout in seconds (default: 30) */\n timeout?: number;\n /** Additional IAM permissions for the Lambda */\n permissions?: Permission[];\n};\n\n/**\n * DynamoDB stream record passed to onRecord callback\n *\n * @typeParam T - Type of the table items (new/old values)\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?: T;\n /** Old item value (present for MODIFY and REMOVE) */\n old?: T;\n /** Primary key of the affected item */\n keys: Record<string, unknown>;\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 table items\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 * Context factory type — conditional on whether params are declared.\n * Without params: `() => C | Promise<C>`\n * With params: `(args: { params: ResolveParams<P> }) => C | Promise<C>`\n */\ntype ContextFactory<C, P> = [P] extends [undefined]\n ? () => C | Promise<C>\n : (args: { params: ResolveParams<P & {}> }) => 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> =\n (args: { record: TableRecord<T>; table: TableClient<T> }\n & ([C] extends [undefined] ? {} : { ctx: C })\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { params: ResolveParams<P> })\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> =\n (args: { results: R[]; failures: FailedRecord<T>[]; table: TableClient<T> }\n & ([C] extends [undefined] ? {} : { ctx: C })\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { params: ResolveParams<P> })\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> =\n (args: { records: TableRecord<T>[]; table: TableClient<T> }\n & ([C] extends [undefined] ? {} : { ctx: C })\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { params: ResolveParams<P> })\n ) => Promise<void>;\n\n/** Base options shared by all defineTable variants */\ntype DefineTableBase<T = Record<string, unknown>, C = undefined, D = undefined, P = undefined> = TableConfig & {\n /**\n * Decode/validate function for stream record items (new/old images).\n * Called with the unmarshalled DynamoDB item; 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?: (error: unknown) => void;\n /**\n * Factory function to create context/dependencies for callbacks.\n * Called once on cold start, result is cached and reused across invocations.\n * When params are declared, receives resolved params as argument.\n * Supports both sync and async return values.\n */\n context?: ContextFactory<C, P>;\n /**\n * Dependencies on other handlers (tables, queues, etc.).\n * Typed clients are injected into the handler via the `deps` argument.\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 `params` argument.\n */\n params?: P;\n};\n\n/** Per-record processing: onRecord with optional onBatchComplete */\ntype DefineTableWithOnRecord<T = Record<string, unknown>, C = undefined, R = void, D = undefined, P = undefined> = DefineTableBase<T, C, D, P> & {\n onRecord: TableRecordFn<T, C, R, D, P>;\n onBatchComplete?: TableBatchCompleteFn<T, C, R, D, P>;\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> = DefineTableBase<T, C, D, P> & {\n onBatch: TableBatchFn<T, C, D, P>;\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> = DefineTableBase<T, C, D, P> & {\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, AnyTableHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined\n> =\n | DefineTableWithOnRecord<T, C, R, D, P>\n | DefineTableWithOnBatch<T, C, D, P>\n | DefineTableResourceOnly<T, C, D, P>;\n\n/**\n * Internal handler object created by defineTable\n * @internal\n */\nexport type TableHandler<T = Record<string, unknown>, C = undefined, R = void, D = undefined, P = undefined> = {\n readonly __brand: \"effortless-table\";\n readonly config: TableConfig;\n readonly schema?: (input: unknown) => T;\n readonly onError?: (error: unknown) => void;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly context?: (...args: any[]) => C | Promise<C>;\n readonly deps?: D;\n readonly params?: P;\n readonly onRecord?: TableRecordFn<T, C, R, D, P>;\n readonly onBatchComplete?: TableBatchCompleteFn<T, C, R, D, P>;\n readonly onBatch?: TableBatchFn<T, C, D, P>;\n};\n\n/**\n * Define a DynamoDB table with optional stream handler\n *\n * Creates:\n * - DynamoDB table with specified key schema\n * - (If onRecord or onBatch provided) DynamoDB Stream + Lambda + Event Source Mapping\n *\n * @example Table with stream handler (typed)\n * ```typescript\n * type Order = { id: string; amount: number; status: string };\n *\n * export const orders = defineTable<Order>({\n * pk: { name: \"id\", type: \"string\" },\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?.amount);\n * }\n * }\n * });\n * ```\n *\n * @example Table only (no Lambda)\n * ```typescript\n * export const users = defineTable({\n * pk: { name: \"id\", type: \"string\" },\n * sk: { name: \"email\", type: \"string\" }\n * });\n * ```\n */\nexport const defineTable = <\n T = Record<string, unknown>,\n C = undefined,\n R = void,\n D extends Record<string, AnyTableHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined\n>(\n options: DefineTableOptions<T, C, R, D, P>\n): TableHandler<T, C, R, D, P> => {\n const { onRecord, onBatchComplete, onBatch, onError, schema, context, deps, params, ...config } = options;\n return {\n __brand: \"effortless-table\",\n config,\n ...(schema ? { schema } : {}),\n ...(onError ? { onError } : {}),\n ...(context ? { context } : {}),\n ...(deps ? { deps } : {}),\n ...(params ? { params } : {}),\n ...(onRecord ? { onRecord } : {}),\n ...(onBatchComplete ? { onBatchComplete } : {}),\n ...(onBatch ? { onBatch } : {})\n } as TableHandler<T, C, R, D, P>;\n};\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyParamRef = ParamRef<any>;\n\n/**\n * Reference to an SSM Parameter Store parameter.\n *\n * @typeParam T - The resolved type after optional transform (default: string)\n */\nexport type ParamRef<T = string> = {\n readonly __brand: \"effortless-param\";\n readonly key: string;\n readonly transform?: (raw: string) => T;\n};\n\n/**\n * Maps a params declaration to resolved value types.\n *\n * @typeParam P - Record of param names to ParamRef instances\n */\nexport type ResolveParams<P> = {\n [K in keyof P]: P[K] extends ParamRef<infer T> ? T : never;\n};\n\n/**\n * Declare an SSM Parameter Store parameter.\n *\n * The key is combined with project and stage at deploy time to form the full\n * SSM path: `/${project}/${stage}/${key}`.\n *\n * @param key - Parameter key (e.g., \"database-url\")\n * @param transform - Optional function to transform the raw string value\n * @returns A ParamRef used by the deployment and runtime systems\n *\n * @example Simple string parameter\n * ```typescript\n * params: {\n * dbUrl: param(\"database-url\"),\n * }\n * ```\n *\n * @example With transform (e.g., TOML parsing)\n * ```typescript\n * import TOML from \"smol-toml\";\n *\n * params: {\n * config: param(\"app-config\", TOML.parse),\n * }\n * ```\n */\nexport const param = <T = string>(\n key: string,\n transform?: (raw: string) => T\n): ParamRef<T> => ({\n __brand: \"effortless-param\",\n key,\n ...(transform ? { transform } : {}),\n});\n"],"mappings":";AA0FO,IAAM,eAAe,CAAC,WAA+C;;;AC+GrE,IAAM,aAAa,CAMxB,YAC4B;AAC5B,QAAM,EAAE,WAAW,SAAS,SAAS,QAAQ,MAAM,QAAQ,GAAG,OAAO,IAAI;AACzE,SAAO;AAAA,IACL,SAAS;AAAA,IACT;AAAA,IACA,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,IAC3B,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC7B,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC7B,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;AAAA,IACvB,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,IAC3B;AAAA,EACF;AACF;;;ACuBO,IAAM,cAAc,CAOzB,YACgC;AAChC,QAAM,EAAE,UAAU,iBAAiB,SAAS,SAAS,QAAQ,SAAS,MAAM,QAAQ,GAAG,OAAO,IAAI;AAClG,SAAO;AAAA,IACL,SAAS;AAAA,IACT;AAAA,IACA,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,IAC3B,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC7B,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;AAAA,IAC7B,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;AAAA,IACvB,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,IAC3B,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;AAAA,IAC/B,GAAI,kBAAkB,EAAE,gBAAgB,IAAI,CAAC;AAAA,IAC7C,GAAI,UAAU,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC/B;AACF;;;ACxNO,IAAM,QAAQ,CACnB,KACA,eACiB;AAAA,EACjB,SAAS;AAAA,EACT;AAAA,EACA,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;AACnC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/config.ts","../src/handlers/define-http.ts","../src/handlers/define-table.ts","../src/handlers/param.ts","../src/runtime/platform-client.ts","../src/runtime/platform-types.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 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 settings applied to all handlers unless overridden.\n */\n defaults?: {\n /**\n * Lambda memory in MB.\n * @default 256\n */\n memory?: number;\n\n /**\n * Lambda timeout as a human-readable string.\n * @example \"30 seconds\", \"5 minutes\"\n */\n timeout?: string;\n\n /**\n * Lambda runtime.\n * @default \"nodejs22.x\"\n */\n runtime?: string;\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 { Permission } from \"./permissions\";\nimport type { TableHandler } from \"./define-table\";\nimport type { TableClient } from \"../runtime/table-client\";\nimport type { AnyParamRef, ResolveParams } from \"./param\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTableHandler = TableHandler<any, any, any, any, any>;\n\n/** Maps a deps declaration to resolved runtime client types */\nexport type ResolveDeps<D> = {\n [K in keyof D]: D[K] extends TableHandler<infer T, any, any, any, any> ? TableClient<T> : never;\n};\n\n/** HTTP methods supported by API Gateway */\nexport type HttpMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\";\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 (will be JSON serialized) */\n body?: unknown;\n /** Response headers */\n headers?: Record<string, string>;\n};\n\n/**\n * Configuration options extracted from DefineHttpOptions (without onRequest callback)\n */\nexport type HttpConfig = {\n /** Handler name. Defaults to export name if not specified */\n name?: string;\n /** HTTP method for the route */\n method: HttpMethod;\n /** Route path (e.g., \"/api/users\", \"/api/users/{id}\") */\n path: string;\n /** Lambda memory in MB (default: 256) */\n memory?: number;\n /** Lambda timeout in seconds (default: 30) */\n timeout?: number;\n /** Additional IAM permissions for the Lambda */\n permissions?: Permission[];\n};\n\n/**\n * Handler function type for HTTP endpoints\n *\n * @typeParam T - Type of the validated request body (from schema function)\n * @typeParam C - Type of the context/dependencies (from context function)\n * @typeParam D - Type of the deps (from deps declaration)\n * @typeParam P - Type of the params (from params declaration)\n */\nexport type HttpHandlerFn<T = undefined, C = undefined, D = undefined, P = undefined> =\n (args: { req: HttpRequest }\n & ([T] extends [undefined] ? {} : { data: T })\n & ([C] extends [undefined] ? {} : { ctx: C })\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { params: ResolveParams<P> })\n ) => Promise<HttpResponse>;\n\n/**\n * Context factory type — conditional on whether params are declared.\n * Without params: `() => C | Promise<C>`\n * With params: `(args: { params: ResolveParams<P> }) => C | Promise<C>`\n */\ntype ContextFactory<C, P> = [P] extends [undefined]\n ? () => C | Promise<C>\n : (args: { params: ResolveParams<P & {}> }) => C | Promise<C>;\n\n/**\n * Options for defining an HTTP endpoint\n *\n * @typeParam T - Type of the validated request body (inferred from schema function)\n * @typeParam C - Type of the context/dependencies returned by context function\n * @typeParam D - Type of the deps (from deps declaration)\n * @typeParam P - Type of the params (from params declaration)\n */\nexport type DefineHttpOptions<\n T = undefined,\n C = undefined,\n D extends Record<string, AnyTableHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined\n> = HttpConfig & {\n /**\n * Decode/validate function for the request body.\n * Called with the parsed body; should return typed data or throw on validation failure.\n * When provided, the handler receives validated `data` and invalid requests get a 400 response.\n *\n * Works with any validation library:\n * - Effect: `S.decodeUnknownSync(MySchema)`\n * - Zod: `(body) => myZodSchema.parse(body)`\n */\n schema?: (input: unknown) => T;\n /**\n * Error handler called when schema validation or onRequest throws.\n * Receives the error and request, returns an HttpResponse.\n * If not provided, defaults to 400 for validation errors and 500 for handler errors.\n */\n onError?: (error: unknown, req: HttpRequest) => HttpResponse;\n /**\n * Factory function to create context/dependencies for the request handler.\n * Called once on cold start, result is cached and reused across invocations.\n * When params are declared, receives resolved params as argument.\n * Supports both sync and async return values.\n */\n context?: ContextFactory<C, P>;\n /**\n * Dependencies on other handlers (tables, queues, etc.).\n * Typed clients are injected into the handler via the `deps` argument.\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 `params` argument.\n */\n params?: P;\n /** HTTP request handler function */\n onRequest: HttpHandlerFn<T, C, D, P>;\n};\n\n/**\n * Internal handler object created by defineHttp\n * @internal\n */\nexport type HttpHandler<T = undefined, C = undefined, D = undefined, P = undefined> = {\n readonly __brand: \"effortless-http\";\n readonly config: HttpConfig;\n readonly schema?: (input: unknown) => T;\n readonly onError?: (error: unknown, req: HttpRequest) => HttpResponse;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly context?: (...args: any[]) => C | Promise<C>;\n readonly deps?: D;\n readonly params?: P;\n readonly onRequest: HttpHandlerFn<T, C, D, P>;\n};\n\n/**\n * Define an HTTP endpoint that creates an API Gateway route + Lambda function\n *\n * @typeParam T - Type of the validated request body (inferred from schema function)\n * @typeParam C - Type of the context/dependencies (inferred from context function)\n * @typeParam D - Type of the deps (from deps declaration)\n * @typeParam P - Type of the params (from params declaration)\n * @param options - Configuration, optional schema, optional context factory, and request handler\n * @returns Handler object used by the deployment system\n *\n * @example Basic GET endpoint\n * ```typescript\n * export const hello = defineHttp({\n * method: \"GET\",\n * path: \"/hello\",\n * onRequest: async ({ req }) => ({\n * status: 200,\n * body: { message: \"Hello World!\" }\n * })\n * });\n * ```\n *\n * @example With SSM parameters\n * ```typescript\n * import { param } from \"effortless-aws\";\n *\n * export const api = defineHttp({\n * method: \"GET\",\n * path: \"/orders\",\n * params: {\n * dbUrl: param(\"database-url\"),\n * },\n * context: async ({ params }) => ({\n * pool: createPool(params.dbUrl),\n * }),\n * onRequest: async ({ req, ctx, params }) => ({\n * status: 200,\n * body: { dbUrl: params.dbUrl }\n * })\n * });\n * ```\n */\nexport const defineHttp = <\n T = undefined,\n C = undefined,\n D extends Record<string, AnyTableHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined\n>(\n options: DefineHttpOptions<T, C, D, P>\n): HttpHandler<T, C, D, P> => {\n const { onRequest, onError, context, schema, deps, params, ...config } = options;\n return {\n __brand: \"effortless-http\",\n config,\n ...(schema ? { schema } : {}),\n ...(onError ? { onError } : {}),\n ...(context ? { context } : {}),\n ...(deps ? { deps } : {}),\n ...(params ? { params } : {}),\n onRequest\n } as HttpHandler<T, C, D, P>;\n};\n","import type { Permission } from \"./permissions\";\nimport type { TableClient } from \"../runtime/table-client\";\nimport type { AnyParamRef, ResolveParams } from \"./param\";\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype AnyTableHandler = TableHandler<any, any, any, any, any>;\n\n/** Maps a deps declaration to resolved runtime client types */\ntype ResolveDeps<D> = {\n [K in keyof D]: D[K] extends TableHandler<infer T, any, any, any, any> ? TableClient<T> : never;\n};\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 extracted from DefineTableOptions (without onRecord/context)\n */\nexport type TableConfig = {\n /** Table/handler name. Defaults to export name if not specified */\n name?: string;\n /** Partition key definition */\n pk: TableKey;\n /** Sort key definition (optional) */\n sk?: TableKey;\n /** DynamoDB billing mode (default: \"PAY_PER_REQUEST\") */\n billingMode?: \"PAY_PER_REQUEST\" | \"PROVISIONED\";\n /** TTL attribute name for automatic item expiration */\n ttlAttribute?: string;\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 in seconds to gather records before invoking (0-300, default: 2) */\n batchWindow?: number;\n /** Where to start reading the stream (default: \"LATEST\") */\n startingPosition?: \"LATEST\" | \"TRIM_HORIZON\";\n /** Lambda memory in MB (default: 256) */\n memory?: number;\n /** Lambda timeout in seconds (default: 30) */\n timeout?: number;\n /** Additional IAM permissions for the Lambda */\n permissions?: Permission[];\n};\n\n/**\n * DynamoDB stream record passed to onRecord callback\n *\n * @typeParam T - Type of the table items (new/old values)\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?: T;\n /** Old item value (present for MODIFY and REMOVE) */\n old?: T;\n /** Primary key of the affected item */\n keys: Record<string, unknown>;\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 table items\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 * Context factory type — conditional on whether params are declared.\n * Without params: `() => C | Promise<C>`\n * With params: `(args: { params: ResolveParams<P> }) => C | Promise<C>`\n */\ntype ContextFactory<C, P> = [P] extends [undefined]\n ? () => C | Promise<C>\n : (args: { params: ResolveParams<P & {}> }) => 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> =\n (args: { record: TableRecord<T>; table: TableClient<T> }\n & ([C] extends [undefined] ? {} : { ctx: C })\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { params: ResolveParams<P> })\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> =\n (args: { results: R[]; failures: FailedRecord<T>[]; table: TableClient<T> }\n & ([C] extends [undefined] ? {} : { ctx: C })\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { params: ResolveParams<P> })\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> =\n (args: { records: TableRecord<T>[]; table: TableClient<T> }\n & ([C] extends [undefined] ? {} : { ctx: C })\n & ([D] extends [undefined] ? {} : { deps: ResolveDeps<D> })\n & ([P] extends [undefined] ? {} : { params: ResolveParams<P> })\n ) => Promise<void>;\n\n/** Base options shared by all defineTable variants */\ntype DefineTableBase<T = Record<string, unknown>, C = undefined, D = undefined, P = undefined> = TableConfig & {\n /**\n * Decode/validate function for stream record items (new/old images).\n * Called with the unmarshalled DynamoDB item; 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?: (error: unknown) => void;\n /**\n * Factory function to create context/dependencies for callbacks.\n * Called once on cold start, result is cached and reused across invocations.\n * When params are declared, receives resolved params as argument.\n * Supports both sync and async return values.\n */\n context?: ContextFactory<C, P>;\n /**\n * Dependencies on other handlers (tables, queues, etc.).\n * Typed clients are injected into the handler via the `deps` argument.\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 `params` argument.\n */\n params?: P;\n};\n\n/** Per-record processing: onRecord with optional onBatchComplete */\ntype DefineTableWithOnRecord<T = Record<string, unknown>, C = undefined, R = void, D = undefined, P = undefined> = DefineTableBase<T, C, D, P> & {\n onRecord: TableRecordFn<T, C, R, D, P>;\n onBatchComplete?: TableBatchCompleteFn<T, C, R, D, P>;\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> = DefineTableBase<T, C, D, P> & {\n onBatch: TableBatchFn<T, C, D, P>;\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> = DefineTableBase<T, C, D, P> & {\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, AnyTableHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined\n> =\n | DefineTableWithOnRecord<T, C, R, D, P>\n | DefineTableWithOnBatch<T, C, D, P>\n | DefineTableResourceOnly<T, C, D, P>;\n\n/**\n * Internal handler object created by defineTable\n * @internal\n */\nexport type TableHandler<T = Record<string, unknown>, C = undefined, R = void, D = undefined, P = undefined> = {\n readonly __brand: \"effortless-table\";\n readonly config: TableConfig;\n readonly schema?: (input: unknown) => T;\n readonly onError?: (error: unknown) => void;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n readonly context?: (...args: any[]) => C | Promise<C>;\n readonly deps?: D;\n readonly params?: P;\n readonly onRecord?: TableRecordFn<T, C, R, D, P>;\n readonly onBatchComplete?: TableBatchCompleteFn<T, C, R, D, P>;\n readonly onBatch?: TableBatchFn<T, C, D, P>;\n};\n\n/**\n * Define a DynamoDB table with optional stream handler\n *\n * Creates:\n * - DynamoDB table with specified key schema\n * - (If onRecord or onBatch provided) DynamoDB Stream + Lambda + Event Source Mapping\n *\n * @example Table with stream handler (typed)\n * ```typescript\n * type Order = { id: string; amount: number; status: string };\n *\n * export const orders = defineTable<Order>({\n * pk: { name: \"id\", type: \"string\" },\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?.amount);\n * }\n * }\n * });\n * ```\n *\n * @example Table only (no Lambda)\n * ```typescript\n * export const users = defineTable({\n * pk: { name: \"id\", type: \"string\" },\n * sk: { name: \"email\", type: \"string\" }\n * });\n * ```\n */\nexport const defineTable = <\n T = Record<string, unknown>,\n C = undefined,\n R = void,\n D extends Record<string, AnyTableHandler> | undefined = undefined,\n P extends Record<string, AnyParamRef> | undefined = undefined\n>(\n options: DefineTableOptions<T, C, R, D, P>\n): TableHandler<T, C, R, D, P> => {\n const { onRecord, onBatchComplete, onBatch, onError, schema, context, deps, params, ...config } = options;\n return {\n __brand: \"effortless-table\",\n config,\n ...(schema ? { schema } : {}),\n ...(onError ? { onError } : {}),\n ...(context ? { context } : {}),\n ...(deps ? { deps } : {}),\n ...(params ? { params } : {}),\n ...(onRecord ? { onRecord } : {}),\n ...(onBatchComplete ? { onBatchComplete } : {}),\n ...(onBatch ? { onBatch } : {})\n } as TableHandler<T, C, R, D, P>;\n};\n","// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type AnyParamRef = ParamRef<any>;\n\n/**\n * Reference to an SSM Parameter Store parameter.\n *\n * @typeParam T - The resolved type after optional transform (default: string)\n */\nexport type ParamRef<T = string> = {\n readonly __brand: \"effortless-param\";\n readonly key: string;\n readonly transform?: (raw: string) => T;\n};\n\n/**\n * Maps a params declaration to resolved value types.\n *\n * @typeParam P - Record of param names to ParamRef instances\n */\nexport type ResolveParams<P> = {\n [K in keyof P]: P[K] extends ParamRef<infer T> ? T : never;\n};\n\n/**\n * Declare an SSM Parameter Store parameter.\n *\n * The key is combined with project and stage at deploy time to form the full\n * SSM path: `/${project}/${stage}/${key}`.\n *\n * @param key - Parameter key (e.g., \"database-url\")\n * @param transform - Optional function to transform the raw string value\n * @returns A ParamRef used by the deployment and runtime systems\n *\n * @example Simple string parameter\n * ```typescript\n * params: {\n * dbUrl: param(\"database-url\"),\n * }\n * ```\n *\n * @example With transform (e.g., TOML parsing)\n * ```typescript\n * import TOML from \"smol-toml\";\n *\n * params: {\n * config: param(\"app-config\", TOML.parse),\n * }\n * ```\n */\nexport const param = <T = string>(\n key: string,\n transform?: (raw: string) => T\n): ParamRef<T> => ({\n __brand: \"effortless-param\",\n key,\n ...(transform ? { transform } : {}),\n});\n","import { DynamoDB } from \"@aws-sdk/client-dynamodb\";\nimport { marshall, unmarshall } from \"@aws-sdk/util-dynamodb\";\nimport type {\n PlatformEntity,\n ExecutionEntry,\n ErrorEntry,\n} from \"./platform-types\";\nimport {\n ENV_PLATFORM_TABLE,\n dateBucket,\n computeTtl,\n} from \"./platform-types\";\n\nexport type PlatformClient = {\n appendExecution(handlerName: string, handlerType: \"http\" | \"table\", entry: ExecutionEntry): Promise<void>;\n appendError(handlerName: string, handlerType: \"http\" | \"table\", entry: ErrorEntry): Promise<void>;\n get<T extends PlatformEntity>(pk: string, sk: string): Promise<T | undefined>;\n query<T extends PlatformEntity>(pk: string, skPrefix?: string): Promise<T[]>;\n put(entity: PlatformEntity): Promise<void>;\n tableName: string;\n};\n\nexport const createPlatformClient = (): PlatformClient | undefined => {\n const tableName = process.env[ENV_PLATFORM_TABLE];\n if (!tableName) return undefined;\n\n let client: DynamoDB | null = null;\n const getClient = () => (client ??= new DynamoDB({}));\n\n const appendToList = async (\n handlerName: string,\n handlerType: \"http\" | \"table\",\n listAttr: \"executions\" | \"errors\",\n entry: ExecutionEntry | ErrorEntry\n ): Promise<void> => {\n const sk = `EXEC#${dateBucket()}`;\n\n try {\n await getClient().updateItem({\n TableName: tableName,\n Key: marshall({ pk: `HANDLER#${handlerName}`, sk }),\n UpdateExpression:\n \"SET #list = list_append(if_not_exists(#list, :empty), :entry), \" +\n \"#type = :type, #hn = :hn, #ht = :ht, #ttl = :ttl\",\n ExpressionAttributeNames: {\n \"#list\": listAttr,\n \"#type\": \"type\",\n \"#hn\": \"handlerName\",\n \"#ht\": \"handlerType\",\n \"#ttl\": \"ttl\",\n },\n ExpressionAttributeValues: marshall(\n {\n \":entry\": [entry],\n \":empty\": [],\n \":type\": \"execution-log\",\n \":hn\": handlerName,\n \":ht\": handlerType,\n \":ttl\": computeTtl(),\n },\n { removeUndefinedValues: true }\n ),\n });\n } catch (err) {\n console.error(\"[effortless] Failed to write platform record:\", err);\n }\n };\n\n return {\n tableName,\n\n async appendExecution(handlerName, handlerType, entry) {\n await appendToList(handlerName, handlerType, \"executions\", entry);\n },\n\n async appendError(handlerName, handlerType, entry) {\n await appendToList(handlerName, handlerType, \"errors\", entry);\n },\n\n async get<T extends PlatformEntity>(pk: string, sk: string): Promise<T | undefined> {\n const result = await getClient().getItem({\n TableName: tableName,\n Key: marshall({ pk, sk }),\n });\n return result.Item ? (unmarshall(result.Item) as T) : undefined;\n },\n\n async query<T extends PlatformEntity>(pk: string, skPrefix?: string): Promise<T[]> {\n const names: Record<string, string> = { \"#pk\": \"pk\" };\n const values: Record<string, unknown> = { \":pk\": pk };\n let keyCondition = \"#pk = :pk\";\n\n if (skPrefix) {\n names[\"#sk\"] = \"sk\";\n values[\":sk\"] = skPrefix;\n keyCondition += \" AND begins_with(#sk, :sk)\";\n }\n\n const result = await getClient().query({\n TableName: tableName,\n KeyConditionExpression: keyCondition,\n ExpressionAttributeNames: names,\n ExpressionAttributeValues: marshall(values, { removeUndefinedValues: true }),\n });\n\n return (result.Items ?? []).map(item => unmarshall(item) as T);\n },\n\n async put(entity: PlatformEntity) {\n try {\n await getClient().putItem({\n TableName: tableName,\n Item: marshall(entity as Record<string, unknown>, { removeUndefinedValues: true }),\n });\n } catch (err) {\n console.error(\"[effortless] Failed to write platform record:\", err);\n }\n },\n };\n};\n","export const ENV_PLATFORM_TABLE = \"EFF_PLATFORM_TABLE\";\n\nexport const DEFAULT_TTL_SECONDS = 7 * 24 * 60 * 60; // 7 days\n\n// ============ Base ============\n\nexport type BasePlatformEntity = {\n pk: string;\n sk: string;\n type: string;\n ttl?: number;\n};\n\n// ============ Execution Log ============\n\nexport type ExecutionEntry = {\n id: string;\n ts: string;\n ms: number;\n in: unknown;\n out?: unknown;\n};\n\nexport type ErrorEntry = {\n id: string;\n ts: string;\n ms: number;\n in: unknown;\n err: string;\n};\n\nexport type ExecutionLogEntity = BasePlatformEntity & {\n type: \"execution-log\";\n handlerName: string;\n handlerType: \"http\" | \"table\";\n executions: ExecutionEntry[];\n errors: ErrorEntry[];\n};\n\n// ============ Discriminated Union ============\n\nexport type PlatformEntity =\n | ExecutionLogEntity;\n // future: | IdempotencyEntity | HandlerMetaEntity\n\n// ============ Helpers ============\n\nexport const truncateForStorage = (value: unknown, maxLength = 4096): unknown => {\n if (value === undefined || value === null) return value;\n const str = typeof value === \"string\" ? value : JSON.stringify(value);\n if (str.length <= maxLength) return value;\n return str.slice(0, maxLength) + \"...[truncated]\";\n};\n\nexport const dateBucket = (date = new Date()): string =>\n date.toISOString().slice(0, 10);\n\nexport const computeTtl = (ttlSeconds = DEFAULT_TTL_SECONDS): number =>\n Math.floor(Date.now() / 1000) + ttlSeconds;\n"],"mappings":"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","names":[]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
} from "../chunk-
|
|
2
|
+
createHandlerRuntime,
|
|
3
|
+
truncateForStorage
|
|
4
|
+
} from "../chunk-7JVA4742.js";
|
|
5
5
|
|
|
6
6
|
// src/runtime/wrap-http.ts
|
|
7
7
|
var parseBody = (body, isBase64) => {
|
|
@@ -14,24 +14,25 @@ var parseBody = (body, isBase64) => {
|
|
|
14
14
|
}
|
|
15
15
|
};
|
|
16
16
|
var wrapHttp = (handler) => {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
17
|
+
const rt = createHandlerRuntime(handler, "http");
|
|
18
|
+
const toResult = (r) => ({
|
|
19
|
+
statusCode: r.status,
|
|
20
|
+
headers: { "Content-Type": "application/json", ...r.headers },
|
|
21
|
+
body: JSON.stringify(r.body)
|
|
22
|
+
});
|
|
23
|
+
const defaultError = (error, status) => {
|
|
24
|
+
console.error(`[effortless:${rt.handlerName}]`, error);
|
|
25
|
+
return {
|
|
26
|
+
statusCode: status,
|
|
27
|
+
headers: { "Content-Type": "application/json" },
|
|
28
|
+
body: JSON.stringify({
|
|
29
|
+
error: status === 400 ? "Validation failed" : "Internal server error",
|
|
30
|
+
details: error instanceof Error ? error.message : String(error)
|
|
31
|
+
})
|
|
32
|
+
};
|
|
33
33
|
};
|
|
34
34
|
return async (event) => {
|
|
35
|
+
const startTime = Date.now();
|
|
35
36
|
const req = {
|
|
36
37
|
method: event.requestContext?.http?.method ?? event.httpMethod ?? "GET",
|
|
37
38
|
path: event.requestContext?.http?.path ?? event.path ?? "/",
|
|
@@ -41,42 +42,23 @@ var wrapHttp = (handler) => {
|
|
|
41
42
|
body: parseBody(event.body, event.isBase64Encoded ?? false),
|
|
42
43
|
rawBody: event.body
|
|
43
44
|
};
|
|
44
|
-
const
|
|
45
|
-
statusCode: r.status,
|
|
46
|
-
headers: { "Content-Type": "application/json", ...r.headers },
|
|
47
|
-
body: JSON.stringify(r.body)
|
|
48
|
-
});
|
|
49
|
-
const defaultError = (error, status) => ({
|
|
50
|
-
statusCode: status,
|
|
51
|
-
headers: { "Content-Type": "application/json" },
|
|
52
|
-
body: JSON.stringify({
|
|
53
|
-
error: status === 400 ? "Validation failed" : "Internal server error",
|
|
54
|
-
details: error instanceof Error ? error.message : String(error)
|
|
55
|
-
})
|
|
56
|
-
});
|
|
45
|
+
const input = truncateForStorage({ method: req.method, path: req.path, query: req.query, body: req.body });
|
|
57
46
|
const args = { req };
|
|
58
47
|
if (handler.schema) {
|
|
59
48
|
try {
|
|
60
49
|
args.data = handler.schema(req.body);
|
|
61
50
|
} catch (error) {
|
|
51
|
+
rt.logError(startTime, input, error);
|
|
62
52
|
return handler.onError ? toResult(handler.onError(error, req)) : defaultError(error, 400);
|
|
63
53
|
}
|
|
64
54
|
}
|
|
65
|
-
|
|
66
|
-
args.ctx = await getCtx();
|
|
67
|
-
}
|
|
68
|
-
const deps = getDeps();
|
|
69
|
-
if (deps) {
|
|
70
|
-
args.deps = deps;
|
|
71
|
-
}
|
|
72
|
-
const params = await getParams();
|
|
73
|
-
if (params) {
|
|
74
|
-
args.params = params;
|
|
75
|
-
}
|
|
55
|
+
Object.assign(args, await rt.commonArgs());
|
|
76
56
|
try {
|
|
77
57
|
const response = await handler.onRequest(args);
|
|
58
|
+
rt.logExecution(startTime, input, response.body);
|
|
78
59
|
return toResult(response);
|
|
79
60
|
} catch (error) {
|
|
61
|
+
rt.logError(startTime, input, error);
|
|
80
62
|
return handler.onError ? toResult(handler.onError(error, req)) : defaultError(error, 500);
|
|
81
63
|
}
|
|
82
64
|
};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
} from "../chunk-
|
|
2
|
+
createHandlerRuntime,
|
|
3
|
+
createTableClient,
|
|
4
|
+
truncateForStorage
|
|
5
|
+
} from "../chunk-7JVA4742.js";
|
|
6
6
|
|
|
7
7
|
// src/runtime/wrap-table-stream.ts
|
|
8
8
|
import { unmarshall } from "@aws-sdk/util-dynamodb";
|
|
@@ -29,29 +29,21 @@ var parseRecords = (rawRecords, schema) => {
|
|
|
29
29
|
}
|
|
30
30
|
return { records, sequenceNumbers };
|
|
31
31
|
};
|
|
32
|
+
var collectFailures = (records, sequenceNumbers) => {
|
|
33
|
+
const failures = [];
|
|
34
|
+
for (const record of records) {
|
|
35
|
+
const seq = sequenceNumbers.get(record);
|
|
36
|
+
if (seq) failures.push({ itemIdentifier: seq });
|
|
37
|
+
}
|
|
38
|
+
return failures;
|
|
39
|
+
};
|
|
32
40
|
var ENV_TABLE_SELF = "EFF_TABLE_SELF";
|
|
33
41
|
var wrapTableStream = (handler) => {
|
|
34
42
|
if (!handler.onRecord && !handler.onBatch) {
|
|
35
43
|
throw new Error("wrapTableStream requires a handler with onRecord or onBatch defined");
|
|
36
44
|
}
|
|
37
|
-
const
|
|
38
|
-
|
|
39
|
-
let resolvedDeps;
|
|
40
|
-
let resolvedParams = null;
|
|
41
|
-
const getDeps = () => resolvedDeps ??= buildDeps(handler.deps);
|
|
42
|
-
const getParams = async () => {
|
|
43
|
-
if (resolvedParams !== null) return resolvedParams;
|
|
44
|
-
resolvedParams = await buildParams(handler.params);
|
|
45
|
-
return resolvedParams;
|
|
46
|
-
};
|
|
47
|
-
const getCtx = async () => {
|
|
48
|
-
if (ctx !== null) return ctx;
|
|
49
|
-
if (handler.context) {
|
|
50
|
-
const params = await getParams();
|
|
51
|
-
ctx = params ? await handler.context({ params }) : await handler.context();
|
|
52
|
-
}
|
|
53
|
-
return ctx;
|
|
54
|
-
};
|
|
45
|
+
const rt = createHandlerRuntime(handler, "table");
|
|
46
|
+
const handleError = handler.onError ?? ((e) => console.error(`[effortless:${rt.handlerName}]`, e));
|
|
55
47
|
let selfClient = null;
|
|
56
48
|
const getSelfClient = () => {
|
|
57
49
|
if (selfClient) return selfClient;
|
|
@@ -60,81 +52,62 @@ var wrapTableStream = (handler) => {
|
|
|
60
52
|
selfClient = createTableClient(tableName);
|
|
61
53
|
return selfClient;
|
|
62
54
|
};
|
|
63
|
-
const commonArgs = async () => {
|
|
64
|
-
const args = {};
|
|
65
|
-
if (handler.context) args.ctx = await getCtx();
|
|
66
|
-
const deps = getDeps();
|
|
67
|
-
if (deps) args.deps = deps;
|
|
68
|
-
const params = await getParams();
|
|
69
|
-
if (params) args.params = params;
|
|
70
|
-
const table = getSelfClient();
|
|
71
|
-
if (table) args.table = table;
|
|
72
|
-
return args;
|
|
73
|
-
};
|
|
74
55
|
return async (event) => {
|
|
56
|
+
const startTime = Date.now();
|
|
75
57
|
const rawRecords = event.Records ?? [];
|
|
58
|
+
const input = truncateForStorage({ recordCount: rawRecords.length });
|
|
76
59
|
let records;
|
|
77
60
|
let sequenceNumbers;
|
|
78
61
|
try {
|
|
79
62
|
({ records, sequenceNumbers } = parseRecords(rawRecords, handler.schema));
|
|
80
63
|
} catch (error) {
|
|
81
64
|
handleError(error);
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
};
|
|
65
|
+
rt.logError(startTime, input, error);
|
|
66
|
+
return { batchItemFailures: rawRecords.map((r) => r.dynamodb?.SequenceNumber).filter((s) => !!s).map((seq) => ({ itemIdentifier: seq })) };
|
|
85
67
|
}
|
|
68
|
+
const shared = { ...await rt.commonArgs(), table: getSelfClient() };
|
|
86
69
|
const batchItemFailures = [];
|
|
87
70
|
if (handler.onBatch) {
|
|
88
71
|
try {
|
|
89
|
-
|
|
90
|
-
await onBatch({ records, ...await commonArgs() });
|
|
72
|
+
await handler.onBatch({ records, ...shared });
|
|
91
73
|
} catch (error) {
|
|
92
74
|
handleError(error);
|
|
93
|
-
|
|
94
|
-
const seq = sequenceNumbers.get(record);
|
|
95
|
-
if (seq) {
|
|
96
|
-
batchItemFailures.push({ itemIdentifier: seq });
|
|
97
|
-
}
|
|
98
|
-
}
|
|
75
|
+
batchItemFailures.push(...collectFailures(records, sequenceNumbers));
|
|
99
76
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
handleError(error);
|
|
114
|
-
failures.push({ record, error });
|
|
115
|
-
const seq = sequenceNumbers.get(record);
|
|
116
|
-
if (seq) {
|
|
117
|
-
batchItemFailures.push({ itemIdentifier: seq });
|
|
77
|
+
} else {
|
|
78
|
+
const results = [];
|
|
79
|
+
const failures = [];
|
|
80
|
+
const onRecord = handler.onRecord;
|
|
81
|
+
for (const record of records) {
|
|
82
|
+
try {
|
|
83
|
+
const result = await onRecord({ record, ...shared });
|
|
84
|
+
if (result !== void 0) results.push(result);
|
|
85
|
+
} catch (error) {
|
|
86
|
+
handleError(error);
|
|
87
|
+
failures.push({ record, error });
|
|
88
|
+
const seq = sequenceNumbers.get(record);
|
|
89
|
+
if (seq) batchItemFailures.push({ itemIdentifier: seq });
|
|
118
90
|
}
|
|
119
91
|
}
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
const seq = sequenceNumbers.get(record);
|
|
129
|
-
if (seq) {
|
|
130
|
-
const alreadyFailed = batchItemFailures.some((f) => f.itemIdentifier === seq);
|
|
131
|
-
if (!alreadyFailed) {
|
|
92
|
+
if (handler.onBatchComplete) {
|
|
93
|
+
try {
|
|
94
|
+
await handler.onBatchComplete({ results, failures, ...shared });
|
|
95
|
+
} catch (error) {
|
|
96
|
+
handleError(error);
|
|
97
|
+
for (const record of records) {
|
|
98
|
+
const seq = sequenceNumbers.get(record);
|
|
99
|
+
if (seq && !batchItemFailures.some((f) => f.itemIdentifier === seq)) {
|
|
132
100
|
batchItemFailures.push({ itemIdentifier: seq });
|
|
133
101
|
}
|
|
134
102
|
}
|
|
135
103
|
}
|
|
136
104
|
}
|
|
137
105
|
}
|
|
106
|
+
if (batchItemFailures.length > 0) {
|
|
107
|
+
rt.logError(startTime, input, `${batchItemFailures.length} record(s) failed`);
|
|
108
|
+
} else {
|
|
109
|
+
rt.logExecution(startTime, input, { processedCount: records.length });
|
|
110
|
+
}
|
|
138
111
|
return { batchItemFailures };
|
|
139
112
|
};
|
|
140
113
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "effortless-aws",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Code-first AWS Lambda framework",
|
|
@@ -39,7 +39,6 @@
|
|
|
39
39
|
"@aws-sdk/client-resource-groups-tagging-api": "^3.975.0",
|
|
40
40
|
"@aws-sdk/client-ssm": "^3.985.0",
|
|
41
41
|
"@aws-sdk/util-dynamodb": "^3.975.0",
|
|
42
|
-
"@vercel/nft": "^1.3.0",
|
|
43
42
|
"archiver": "^7.0.1",
|
|
44
43
|
"esbuild": "^0.25.0",
|
|
45
44
|
"glob": "^13.0.0",
|