lambder 1.0.131 → 1.0.132

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Readme.md CHANGED
@@ -5,11 +5,9 @@ Lambder is a highly opinionated dynamic serverless framework designed to facilit
5
5
  ## Features
6
6
 
7
7
  - **Simple API & Route Declaration**: Define your APIs and routes using concise and expressive syntax.
8
- - **Type-Safe API Contracts**: Full TypeScript type safety across frontend and backend with zero runtime overhead.
9
8
  - **Session Management**: Built-in session management to secure and personalize user experiences.
10
9
  - **Flexible Hooks System**: Employ hooks to execute code at different stages of the request lifecycle, enabling fine-grained control over the application flow.
11
10
  - **Error Handling**: Comprehensive error handling capabilities, including global error handlers and route-specific fallbacks.
12
- - **MSW Mocking Support**: Optional Mock Service Worker integration for easy API mocking in tests and development.
13
11
  - **Seamless Integration**: Designed to work effortlessly with AWS Lambda and API Gateway, providing a straightforward path to deploy serverless applications.
14
12
 
15
13
  ## Installation
@@ -546,53 +544,6 @@ const user = await caller.api('getUserById', { userId: '123' });
546
544
 
547
545
  📖 **[Read the Quick Start Guide](docs/TYPE_SAFE_QUICK_START.md)** for more details and examples!
548
546
 
549
- ## Testing & Mocking with MSW
550
-
551
- Lambder provides optional integration with [Mock Service Worker (MSW)](https://mswjs.io/) for easy API mocking in tests and development.
552
-
553
- ### Installation
554
-
555
- ```bash
556
- npm install --save-dev msw
557
- ```
558
-
559
- ### Quick Example
560
-
561
- ```typescript
562
- import { mockLambderApi } from 'lambder';
563
- import { setupServer } from 'msw/node';
564
- import type { MyApiContract } from './apiContract';
565
-
566
- // Create type-safe mock handlers
567
- const handlers = [
568
- mockLambderApi<MyApiContract, 'getUserById'>(
569
- 'getUserById',
570
- (input) => ({
571
- id: input.userId,
572
- name: 'Test User',
573
- email: 'test@example.com'
574
- })
575
- )
576
- ];
577
-
578
- // Set up MSW server
579
- const server = setupServer(...handlers);
580
-
581
- beforeAll(() => server.listen());
582
- afterEach(() => server.resetHandlers());
583
- afterAll(() => server.close());
584
- ```
585
-
586
- ### Benefits
587
-
588
- ✅ **Type-Safe Mocking** - Full TypeScript support for mock responses
589
- ✅ **Easy Setup** - Simple functions that match your API contract
590
- ✅ **Test Scenarios** - Mock errors, session expired, not authorized, etc.
591
- ✅ **Development Mode** - Use mocks while developing frontend features
592
- ✅ **Storybook Ready** - Perfect for component stories
593
-
594
- 📖 **[Read the MSW Mocking Guide](docs/MSW_MOCKING.md)** for detailed setup and examples!
595
-
596
547
  ## Contributing
597
548
 
598
549
  Contributions are welcome! Especially for documentation. If you have an idea for an improvement or have found a bug, please open an issue or submit a pull request.
@@ -1,102 +1,49 @@
1
- import type { ApiContractShape } from './LambderApiContract.js';
2
- /**
3
- * Creates a mock handler for a Lambder API endpoint
4
- *
5
- * @example
6
- * ```typescript
7
- * mockLambderApi('public.getInitialPageData', () => ({
8
- * userLocationData: { ... },
9
- * sessionUser: null
10
- * }))
11
- * ```
12
- *
13
- * @example with dynamic response based on input
14
- * ```typescript
15
- * mockLambderApi('user.updateProfile', (input) => ({
16
- * success: true,
17
- * userId: input.userId
18
- * }))
19
- * ```
20
- */
21
- export declare function mockLambderApi<TContract extends ApiContractShape, TApiName extends keyof TContract & string>(apiName: TApiName, responseFactory: (input: TContract[TApiName]['input']) => TContract[TApiName]['output'] | Promise<TContract[TApiName]['output']>, options?: {
22
- /** Custom API path, defaults to '/api' */
23
- apiPath?: string;
24
- /** Delay in ms before responding (for testing loading states) */
1
+ import type { ApiContractShape } from './LambderApiContract';
2
+ type RequestHandler = any;
3
+ type MockApiOptions = {
4
+ versionExpired?: boolean;
5
+ sessionExpired?: boolean;
6
+ notAuthorized?: boolean;
7
+ message?: any;
8
+ errorMessage?: any;
9
+ logList?: any[];
25
10
  delay?: number;
26
- /** Custom apiVersion to include in response */
27
- apiVersion?: string | null;
28
- }): any;
29
- /**
30
- * Creates a mock handler that returns an error for a Lambder API endpoint
31
- *
32
- * @example
33
- * ```typescript
34
- * mockLambderApiError('user.deleteAccount', 'Account deletion failed')
35
- * ```
36
- */
37
- export declare function mockLambderApiError<TContract extends ApiContractShape, TApiName extends keyof TContract & string>(apiName: TApiName, errorMessage: string, options?: {
38
- /** Custom API path, defaults to '/api' */
39
- apiPath?: string;
40
- /** Delay in ms before responding */
41
- delay?: number;
42
- /** Custom apiVersion to include in response */
43
- apiVersion?: string | null;
44
- }): any;
45
- /**
46
- * Creates a mock handler that simulates a session expired error
47
- *
48
- * @example
49
- * ```typescript
50
- * mockLambderSessionExpired('user.updateProfile')
51
- * ```
52
- */
53
- export declare function mockLambderSessionExpired<TContract extends ApiContractShape, TApiName extends keyof TContract & string>(apiName: TApiName, options?: {
54
- /** Custom API path, defaults to '/api' */
55
- apiPath?: string;
56
- /** Custom apiVersion to include in response */
57
- apiVersion?: string | null;
58
- }): any;
59
- /**
60
- * Creates a mock handler that simulates a "not authorized" error
61
- *
62
- * @example
63
- * ```typescript
64
- * mockLambderNotAuthorized('admin.deleteUser')
65
- * ```
66
- */
67
- export declare function mockLambderNotAuthorized<TContract extends ApiContractShape, TApiName extends keyof TContract & string>(apiName: TApiName, options?: {
68
- /** Custom API path, defaults to '/api' */
69
- apiPath?: string;
70
- /** Custom apiVersion to include in response */
71
- apiVersion?: string | null;
72
- }): any;
73
- /**
74
- * Creates a mock handler that simulates a version expired error
75
- *
76
- * @example
77
- * ```typescript
78
- * mockLambderVersionExpired('user.updateProfile')
79
- * ```
80
- */
81
- export declare function mockLambderVersionExpired<TContract extends ApiContractShape, TApiName extends keyof TContract & string>(apiName: TApiName, options?: {
82
- /** Custom API path, defaults to '/api' */
83
- apiPath?: string;
84
- /** Custom apiVersion to include in response */
85
- apiVersion?: string | null;
86
- }): any;
87
- /**
88
- * Helper to combine multiple Lambder mock handlers
89
- * Since each handler checks for its specific apiName, you can just spread them into setupWorker/setupServer
90
- *
91
- * @deprecated This helper is not needed - just spread handlers directly into setupWorker/setupServer
92
- * @example
93
- * ```typescript
94
- * import { setupServer } from 'msw/node';
95
- *
96
- * const server = setupServer(
97
- * mockLambderApi('user.getProfile', () => ({ name: 'Test User' })),
98
- * mockLambderApi('user.updateProfile', (input) => ({ success: true }))
99
- * );
100
- * ```
101
- */
102
- export declare function createLambderApiHandler(apiPath: string, handlers: any[]): any[];
11
+ };
12
+ export default class LambderMSW<TContract extends ApiContractShape = any> {
13
+ private apiPath;
14
+ private apiVersion?;
15
+ private http;
16
+ private HttpResponse;
17
+ constructor({ apiPath, apiVersion, }: {
18
+ apiPath: string;
19
+ apiVersion?: string;
20
+ });
21
+ /**
22
+ * Mock an API endpoint with MSW
23
+ * @param apiName - The name of the API to mock
24
+ * @param handler - Function that returns the mock payload
25
+ * @param options - Additional response options (session expired, version expired, etc.)
26
+ */
27
+ mockApi<TApiName extends keyof TContract & string, TOutput = TApiName extends keyof TContract ? TContract[TApiName]['output'] : any, TInput = TApiName extends keyof TContract ? TContract[TApiName]['input'] : any>(apiName: TApiName, handler: (payload?: TInput) => Promise<TOutput> | TOutput, options?: MockApiOptions): RequestHandler;
28
+ /**
29
+ * Mock an API endpoint that returns a session expired error
30
+ */
31
+ mockSessionExpired<TApiName extends keyof TContract & string>(apiName: TApiName): RequestHandler;
32
+ /**
33
+ * Mock an API endpoint that returns a version expired error
34
+ */
35
+ mockVersionExpired<TApiName extends keyof TContract & string>(apiName: TApiName): RequestHandler;
36
+ /**
37
+ * Mock an API endpoint that returns a not authorized error
38
+ */
39
+ mockNotAuthorized<TApiName extends keyof TContract & string>(apiName: TApiName): RequestHandler;
40
+ /**
41
+ * Mock an API endpoint that returns an error message
42
+ */
43
+ mockError<TApiName extends keyof TContract & string>(apiName: TApiName, errorMessage: string): RequestHandler;
44
+ /**
45
+ * Mock an API endpoint with a custom message
46
+ */
47
+ mockWithMessage<TApiName extends keyof TContract & string, TOutput = TApiName extends keyof TContract ? TContract[TApiName]['output'] : any, TInput = TApiName extends keyof TContract ? TContract[TApiName]['input'] : any>(apiName: TApiName, handler: (payload?: TInput) => Promise<TOutput> | TOutput, message: any): RequestHandler;
48
+ }
49
+ export {};
@@ -1,176 +1,95 @@
1
- /**
2
- * Creates a mock handler for a Lambder API endpoint
3
- *
4
- * @example
5
- * ```typescript
6
- * mockLambderApi('public.getInitialPageData', () => ({
7
- * userLocationData: { ... },
8
- * sessionUser: null
9
- * }))
10
- * ```
11
- *
12
- * @example with dynamic response based on input
13
- * ```typescript
14
- * mockLambderApi('user.updateProfile', (input) => ({
15
- * success: true,
16
- * userId: input.userId
17
- * }))
18
- * ```
19
- */
20
- export function mockLambderApi(apiName, responseFactory, options) {
21
- const apiPath = options?.apiPath ?? '/api';
22
- const delay = options?.delay ?? 0;
23
- const apiVersion = options?.apiVersion ?? null;
24
- // @ts-ignore - MSW is an optional peer dependency
25
- const { http, HttpResponse } = require('msw');
26
- return http.post(apiPath, async ({ request }) => {
27
- const body = (await request.json());
28
- // Only handle this specific API
29
- if (body.apiName !== apiName) {
30
- return;
1
+ export default class LambderMSW {
2
+ apiPath;
3
+ apiVersion;
4
+ http;
5
+ HttpResponse;
6
+ constructor({ apiPath, apiVersion, }) {
7
+ this.apiPath = apiPath;
8
+ this.apiVersion = apiVersion;
9
+ // Dynamically import MSW - it needs to be installed by the user
10
+ try {
11
+ const msw = require('msw');
12
+ this.http = msw.http;
13
+ this.HttpResponse = msw.HttpResponse;
31
14
  }
32
- console.log(`[MSW Lambder] Mocking ${apiName}`, body.payload);
33
- // Apply delay if specified
34
- if (delay > 0) {
35
- await new Promise((resolve) => setTimeout(resolve, delay));
15
+ catch (err) {
16
+ throw new Error('MSW (Mock Service Worker) is required. Install it with: npm install msw --save-dev');
36
17
  }
37
- // Generate the response
38
- const payload = await responseFactory(body.payload);
39
- // Return in Lambder API response format
40
- return HttpResponse.json({
41
- ...(apiVersion !== null ? { apiVersion } : {}),
42
- payload,
18
+ }
19
+ /**
20
+ * Mock an API endpoint with MSW
21
+ * @param apiName - The name of the API to mock
22
+ * @param handler - Function that returns the mock payload
23
+ * @param options - Additional response options (session expired, version expired, etc.)
24
+ */
25
+ mockApi(apiName, handler, options) {
26
+ return this.http.post(this.apiPath, async ({ request }) => {
27
+ try {
28
+ const body = await request.json();
29
+ console.log("LambderMSW called for:", body?.apiName, "matching against:", apiName);
30
+ // Check if this is the API we're mocking
31
+ if (body?.apiName === apiName) {
32
+ // Add artificial delay if specified
33
+ if (options?.delay) {
34
+ await new Promise(resolve => setTimeout(resolve, options.delay));
35
+ }
36
+ // Call the handler with the payload from the request
37
+ const payload = await handler(body?.payload);
38
+ console.log("Matched! Returning payload for:", apiName);
39
+ const response = {
40
+ apiVersion: this.apiVersion,
41
+ payload,
42
+ ...(options?.versionExpired ? { versionExpired: options.versionExpired } : {}),
43
+ ...(options?.sessionExpired ? { sessionExpired: options.sessionExpired } : {}),
44
+ ...(options?.notAuthorized ? { notAuthorized: options.notAuthorized } : {}),
45
+ ...(options?.message ? { message: options.message } : {}),
46
+ ...(options?.errorMessage ? { errorMessage: options.errorMessage } : {}),
47
+ ...(options?.logList?.length ? { logList: options.logList } : {}),
48
+ };
49
+ return this.HttpResponse.json(response);
50
+ }
51
+ // If this handler doesn't match, return undefined to let MSW try other handlers
52
+ return;
53
+ }
54
+ catch (err) {
55
+ console.error("Error in LambderMSW:", err);
56
+ const errorResponse = {
57
+ apiVersion: this.apiVersion,
58
+ payload: null,
59
+ errorMessage: err.message || "Unknown error",
60
+ };
61
+ return this.HttpResponse.json(errorResponse, { status: 500 });
62
+ }
43
63
  });
44
- });
45
- }
46
- /**
47
- * Creates a mock handler that returns an error for a Lambder API endpoint
48
- *
49
- * @example
50
- * ```typescript
51
- * mockLambderApiError('user.deleteAccount', 'Account deletion failed')
52
- * ```
53
- */
54
- export function mockLambderApiError(apiName, errorMessage, options) {
55
- const apiPath = options?.apiPath ?? '/api';
56
- const delay = options?.delay ?? 0;
57
- const apiVersion = options?.apiVersion ?? null;
58
- // @ts-ignore - MSW is an optional peer dependency
59
- const { http, HttpResponse } = require('msw');
60
- return http.post(apiPath, async ({ request }) => {
61
- const body = (await request.json());
62
- if (body.apiName !== apiName) {
63
- return;
64
- }
65
- console.log(`[MSW Lambder] Mocking error for ${apiName}:`, errorMessage);
66
- if (delay > 0) {
67
- await new Promise((resolve) => setTimeout(resolve, delay));
68
- }
69
- return HttpResponse.json({
70
- ...(apiVersion !== null ? { apiVersion } : {}),
71
- payload: null,
72
- errorMessage,
73
- });
74
- });
75
- }
76
- /**
77
- * Creates a mock handler that simulates a session expired error
78
- *
79
- * @example
80
- * ```typescript
81
- * mockLambderSessionExpired('user.updateProfile')
82
- * ```
83
- */
84
- export function mockLambderSessionExpired(apiName, options) {
85
- const apiPath = options?.apiPath ?? '/api';
86
- const apiVersion = options?.apiVersion ?? null;
87
- // @ts-ignore - MSW is an optional peer dependency
88
- const { http, HttpResponse } = require('msw');
89
- return http.post(apiPath, async ({ request }) => {
90
- const body = (await request.json());
91
- if (body.apiName !== apiName) {
92
- return;
93
- }
94
- console.log(`[MSW Lambder] Mocking session expired for ${apiName}`);
95
- return HttpResponse.json({
96
- ...(apiVersion !== null ? { apiVersion } : {}),
97
- payload: null,
98
- sessionExpired: true,
99
- errorMessage: 'Session expired',
100
- });
101
- });
102
- }
103
- /**
104
- * Creates a mock handler that simulates a "not authorized" error
105
- *
106
- * @example
107
- * ```typescript
108
- * mockLambderNotAuthorized('admin.deleteUser')
109
- * ```
110
- */
111
- export function mockLambderNotAuthorized(apiName, options) {
112
- const apiPath = options?.apiPath ?? '/api';
113
- const apiVersion = options?.apiVersion ?? null;
114
- // @ts-ignore - MSW is an optional peer dependency
115
- const { http, HttpResponse } = require('msw');
116
- return http.post(apiPath, async ({ request }) => {
117
- const body = (await request.json());
118
- if (body.apiName !== apiName) {
119
- return;
120
- }
121
- console.log(`[MSW Lambder] Mocking not authorized for ${apiName}`);
122
- return HttpResponse.json({
123
- ...(apiVersion !== null ? { apiVersion } : {}),
124
- payload: null,
125
- notAuthorized: true,
126
- errorMessage: 'Not authorized',
127
- });
128
- });
129
- }
130
- /**
131
- * Creates a mock handler that simulates a version expired error
132
- *
133
- * @example
134
- * ```typescript
135
- * mockLambderVersionExpired('user.updateProfile')
136
- * ```
137
- */
138
- export function mockLambderVersionExpired(apiName, options) {
139
- const apiPath = options?.apiPath ?? '/api';
140
- const apiVersion = options?.apiVersion ?? null;
141
- // @ts-ignore - MSW is an optional peer dependency
142
- const { http, HttpResponse } = require('msw');
143
- return http.post(apiPath, async ({ request }) => {
144
- const body = (await request.json());
145
- if (body.apiName !== apiName) {
146
- return;
147
- }
148
- console.log(`[MSW Lambder] Mocking version expired for ${apiName}`);
149
- return HttpResponse.json({
150
- ...(apiVersion !== null ? { apiVersion } : {}),
151
- payload: null,
152
- versionExpired: true,
153
- errorMessage: 'Version expired',
154
- });
155
- });
156
- }
157
- /**
158
- * Helper to combine multiple Lambder mock handlers
159
- * Since each handler checks for its specific apiName, you can just spread them into setupWorker/setupServer
160
- *
161
- * @deprecated This helper is not needed - just spread handlers directly into setupWorker/setupServer
162
- * @example
163
- * ```typescript
164
- * import { setupServer } from 'msw/node';
165
- *
166
- * const server = setupServer(
167
- * mockLambderApi('user.getProfile', () => ({ name: 'Test User' })),
168
- * mockLambderApi('user.updateProfile', (input) => ({ success: true }))
169
- * );
170
- * ```
171
- */
172
- export function createLambderApiHandler(apiPath, handlers) {
173
- // This is deprecated - users should just spread handlers directly
174
- // Kept for backward compatibility
175
- return handlers;
64
+ }
65
+ /**
66
+ * Mock an API endpoint that returns a session expired error
67
+ */
68
+ mockSessionExpired(apiName) {
69
+ return this.mockApi(apiName, async () => null, { sessionExpired: true });
70
+ }
71
+ /**
72
+ * Mock an API endpoint that returns a version expired error
73
+ */
74
+ mockVersionExpired(apiName) {
75
+ return this.mockApi(apiName, async () => null, { versionExpired: true });
76
+ }
77
+ /**
78
+ * Mock an API endpoint that returns a not authorized error
79
+ */
80
+ mockNotAuthorized(apiName) {
81
+ return this.mockApi(apiName, async () => null, { notAuthorized: true });
82
+ }
83
+ /**
84
+ * Mock an API endpoint that returns an error message
85
+ */
86
+ mockError(apiName, errorMessage) {
87
+ return this.mockApi(apiName, async () => null, { errorMessage });
88
+ }
89
+ /**
90
+ * Mock an API endpoint with a custom message
91
+ */
92
+ mockWithMessage(apiName, handler, message) {
93
+ return this.mockApi(apiName, handler, { message });
94
+ }
176
95
  }
package/dist/index.d.ts CHANGED
@@ -4,5 +4,5 @@ export { default as LambderCaller } from "./LambderCaller.js";
4
4
  export { default as LambderResponseBuilder } from "./LambderResponseBuilder.js";
5
5
  export { default as LambderResolver } from "./LambderResolver.js";
6
6
  export { default as LambderSessionManager } from "./LambderSessionManager.js";
7
+ export { default as LambderMSW } from "./LambderMSW.js";
7
8
  export { type ApiContractShape, type ApiContract, type ApiInput, type ApiOutput, } from "./LambderApiContract.js";
8
- export { mockLambderApi, mockLambderApiError, mockLambderSessionExpired, mockLambderNotAuthorized, mockLambderVersionExpired, createLambderApiHandler, } from "./LambderMSW.js";
package/dist/index.js CHANGED
@@ -4,5 +4,4 @@ export { default as LambderCaller } from "./LambderCaller.js";
4
4
  export { default as LambderResponseBuilder } from "./LambderResponseBuilder.js";
5
5
  export { default as LambderResolver } from "./LambderResolver.js";
6
6
  export { default as LambderSessionManager } from "./LambderSessionManager.js";
7
- // MSW mocking utilities (optional - requires msw to be installed)
8
- export { mockLambderApi, mockLambderApiError, mockLambderSessionExpired, mockLambderNotAuthorized, mockLambderVersionExpired, createLambderApiHandler, } from "./LambderMSW.js";
7
+ export { default as LambderMSW } from "./LambderMSW.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lambder",
3
- "version": "1.0.131",
3
+ "version": "1.0.132",
4
4
  "description": "",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",