@scenarist/nextjs-adapter 0.0.1 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +1450 -27
- package/dist/app/context.d.ts +19 -0
- package/dist/app/context.d.ts.map +1 -0
- package/dist/app/context.js +43 -0
- package/dist/app/endpoints.d.ts +20 -0
- package/dist/app/endpoints.d.ts.map +1 -0
- package/dist/app/endpoints.js +84 -0
- package/dist/app/helpers.d.ts +152 -0
- package/dist/app/helpers.d.ts.map +1 -0
- package/dist/app/helpers.js +173 -0
- package/dist/app/impl.d.ts +155 -0
- package/dist/app/impl.d.ts.map +1 -0
- package/dist/app/impl.js +97 -0
- package/dist/app/index.d.ts +40 -0
- package/dist/app/index.d.ts.map +1 -0
- package/dist/app/index.js +38 -0
- package/dist/app/production.d.ts +34 -0
- package/dist/app/production.d.ts.map +1 -0
- package/dist/app/production.js +38 -0
- package/dist/app/production.test.d.ts +100 -0
- package/dist/app/production.test.d.ts.map +1 -0
- package/dist/app/production.test.js +282 -0
- package/dist/app/setup.d.ts +29 -0
- package/dist/app/setup.d.ts.map +1 -0
- package/dist/app/setup.js +27 -0
- package/dist/common/create-scenarist-base.d.ts +32 -0
- package/dist/common/create-scenarist-base.d.ts.map +1 -0
- package/dist/common/create-scenarist-base.js +63 -0
- package/dist/common/endpoint-handlers.d.ts +99 -0
- package/dist/common/endpoint-handlers.d.ts.map +1 -0
- package/dist/common/endpoint-handlers.js +122 -0
- package/dist/pages/context.d.ts +17 -0
- package/dist/pages/context.d.ts.map +1 -0
- package/dist/pages/context.js +41 -0
- package/dist/pages/endpoints.d.ts +20 -0
- package/dist/pages/endpoints.d.ts.map +1 -0
- package/dist/pages/endpoints.js +84 -0
- package/dist/pages/helpers.d.ts +56 -0
- package/dist/pages/helpers.d.ts.map +1 -0
- package/dist/pages/helpers.js +49 -0
- package/dist/pages/impl.d.ts +124 -0
- package/dist/pages/impl.d.ts.map +1 -0
- package/dist/pages/impl.js +91 -0
- package/dist/pages/index.d.ts +37 -0
- package/dist/pages/index.d.ts.map +1 -0
- package/dist/pages/index.js +35 -0
- package/dist/pages/production.d.ts +18 -0
- package/dist/pages/production.d.ts.map +1 -0
- package/dist/pages/production.js +20 -0
- package/dist/pages/production.test.d.ts +119 -0
- package/dist/pages/production.test.d.ts.map +1 -0
- package/dist/pages/production.test.js +326 -0
- package/dist/pages/setup.d.ts +29 -0
- package/dist/pages/setup.d.ts.map +1 -0
- package/dist/pages/setup.js +27 -0
- package/package.json +86 -7
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Create a Scenarist instance for Next.js App Router.
|
|
3
|
+
*
|
|
4
|
+
* Production tree-shaking is handled via conditional exports in package.json:
|
|
5
|
+
* - Development/test: Uses this file (imports impl.js with full MSW setup)
|
|
6
|
+
* - Production builds: Uses production.js (returns undefined, zero imports)
|
|
7
|
+
*
|
|
8
|
+
* This ensures all test code is eliminated from production bundles.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* // lib/scenarist.ts
|
|
13
|
+
* import { createScenarist } from '@scenarist/nextjs-adapter/app';
|
|
14
|
+
* import { scenarios } from './scenarios';
|
|
15
|
+
*
|
|
16
|
+
* export const scenarist = createScenarist({
|
|
17
|
+
* enabled: true,
|
|
18
|
+
* scenarios,
|
|
19
|
+
* });
|
|
20
|
+
*
|
|
21
|
+
* // Start MSW in Node.js environment
|
|
22
|
+
* if (typeof window === 'undefined') {
|
|
23
|
+
* scenarist.start();
|
|
24
|
+
* }
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
export { createScenaristImpl as createScenarist } from './impl.js';
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { setupServer } from 'msw/node';
|
|
2
|
+
import { type BaseAdapterOptions, type ScenaristConfig, type ScenarioManager, type ResponseSelector } from '@scenarist/core';
|
|
3
|
+
/**
|
|
4
|
+
* Shared setup logic for both Pages Router and App Router adapters.
|
|
5
|
+
*
|
|
6
|
+
* Contains all common initialization: config building, manager creation,
|
|
7
|
+
* MSW handler setup, and server initialization. This eliminates ~150 lines
|
|
8
|
+
* of duplication between the two adapter implementations.
|
|
9
|
+
*/
|
|
10
|
+
export type ScenaristBaseSetup = {
|
|
11
|
+
readonly config: ScenaristConfig;
|
|
12
|
+
readonly manager: ScenarioManager;
|
|
13
|
+
readonly responseSelector: ResponseSelector;
|
|
14
|
+
readonly server: ReturnType<typeof setupServer>;
|
|
15
|
+
readonly currentTestId: {
|
|
16
|
+
value: string;
|
|
17
|
+
};
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* Creates the base Scenarist setup shared by both Pages and App Router.
|
|
21
|
+
*
|
|
22
|
+
* Follows hexagonal architecture:
|
|
23
|
+
* - Accepts optional port implementations via dependency injection
|
|
24
|
+
* - Uses in-memory defaults if not provided
|
|
25
|
+
* - Sets up MSW dynamic handler with response selector
|
|
26
|
+
* - Initializes MSW server
|
|
27
|
+
*
|
|
28
|
+
* @param options - Adapter configuration options
|
|
29
|
+
* @returns Shared setup objects for both router implementations
|
|
30
|
+
*/
|
|
31
|
+
export declare const createScenaristBase: (options: BaseAdapterOptions) => ScenaristBaseSetup;
|
|
32
|
+
//# sourceMappingURL=create-scenarist-base.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"create-scenarist-base.d.ts","sourceRoot":"","sources":["../../src/common/create-scenarist-base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EASL,KAAK,kBAAkB,EACvB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,gBAAgB,EACtB,MAAM,iBAAiB,CAAC;AAGzB;;;;;;GAMG;AACH,MAAM,MAAM,kBAAkB,GAAG;IAC/B,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAC;IACjC,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAC;IAClC,QAAQ,CAAC,gBAAgB,EAAE,gBAAgB,CAAC;IAC5C,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC,OAAO,WAAW,CAAC,CAAC;IAChD,QAAQ,CAAC,aAAa,EAAE;QAAE,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;CAC3C,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,mBAAmB,GAC9B,SAAS,kBAAkB,KAC1B,kBAwDF,CAAC"}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { setupServer } from 'msw/node';
|
|
2
|
+
import { buildConfig, createScenarioManager, createResponseSelector, InMemoryScenarioRegistry, InMemoryScenarioStore, createInMemorySequenceTracker, createInMemoryStateManager, SCENARIST_TEST_ID_HEADER, } from '@scenarist/core';
|
|
3
|
+
import { createDynamicHandler } from '@scenarist/msw-adapter';
|
|
4
|
+
/**
|
|
5
|
+
* Creates the base Scenarist setup shared by both Pages and App Router.
|
|
6
|
+
*
|
|
7
|
+
* Follows hexagonal architecture:
|
|
8
|
+
* - Accepts optional port implementations via dependency injection
|
|
9
|
+
* - Uses in-memory defaults if not provided
|
|
10
|
+
* - Sets up MSW dynamic handler with response selector
|
|
11
|
+
* - Initializes MSW server
|
|
12
|
+
*
|
|
13
|
+
* @param options - Adapter configuration options
|
|
14
|
+
* @returns Shared setup objects for both router implementations
|
|
15
|
+
*/
|
|
16
|
+
export const createScenaristBase = (options) => {
|
|
17
|
+
const config = buildConfig(options);
|
|
18
|
+
// Use injected ports or in-memory defaults
|
|
19
|
+
const registry = options.registry ?? new InMemoryScenarioRegistry();
|
|
20
|
+
const store = options.store ?? new InMemoryScenarioStore();
|
|
21
|
+
// Create state and sequence managers
|
|
22
|
+
const stateManager = createInMemoryStateManager();
|
|
23
|
+
const sequenceTracker = createInMemorySequenceTracker();
|
|
24
|
+
// Create scenario manager with all dependencies
|
|
25
|
+
const manager = createScenarioManager({
|
|
26
|
+
registry,
|
|
27
|
+
store,
|
|
28
|
+
stateManager,
|
|
29
|
+
sequenceTracker,
|
|
30
|
+
});
|
|
31
|
+
// Register all scenarios upfront from scenarios object
|
|
32
|
+
Object.values(options.scenarios).forEach((scenario) => {
|
|
33
|
+
manager.registerScenario(scenario);
|
|
34
|
+
});
|
|
35
|
+
// Create response selector for dynamic responses
|
|
36
|
+
const responseSelector = createResponseSelector({
|
|
37
|
+
sequenceTracker,
|
|
38
|
+
stateManager,
|
|
39
|
+
});
|
|
40
|
+
// Mutable ref to current test ID (updated by adapter methods)
|
|
41
|
+
const currentTestId = { value: config.defaultTestId };
|
|
42
|
+
// Create MSW dynamic handler
|
|
43
|
+
const handler = createDynamicHandler({
|
|
44
|
+
getTestId: (request) => {
|
|
45
|
+
// Extract test ID from request headers (MSW Request object)
|
|
46
|
+
const headerValue = request.headers.get(SCENARIST_TEST_ID_HEADER);
|
|
47
|
+
return headerValue || config.defaultTestId;
|
|
48
|
+
},
|
|
49
|
+
getActiveScenario: (testId) => manager.getActiveScenario(testId),
|
|
50
|
+
getScenarioDefinition: (scenarioId) => manager.getScenarioById(scenarioId),
|
|
51
|
+
strictMode: config.strictMode,
|
|
52
|
+
responseSelector,
|
|
53
|
+
});
|
|
54
|
+
// Initialize MSW server
|
|
55
|
+
const server = setupServer(handler);
|
|
56
|
+
return {
|
|
57
|
+
config,
|
|
58
|
+
manager,
|
|
59
|
+
responseSelector,
|
|
60
|
+
server,
|
|
61
|
+
currentTestId,
|
|
62
|
+
};
|
|
63
|
+
};
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { type ScenarioManager, type RequestContext } from '@scenarist/core';
|
|
2
|
+
/**
|
|
3
|
+
* Result type for POST endpoint business logic.
|
|
4
|
+
*
|
|
5
|
+
* Represents the outcome of attempting to switch scenarios,
|
|
6
|
+
* with appropriate status codes for different failure modes.
|
|
7
|
+
*/
|
|
8
|
+
export type PostResult = {
|
|
9
|
+
readonly success: true;
|
|
10
|
+
readonly testId: string;
|
|
11
|
+
readonly scenarioId: string;
|
|
12
|
+
} | {
|
|
13
|
+
readonly success: false;
|
|
14
|
+
readonly status: 400 | 500;
|
|
15
|
+
readonly error: string;
|
|
16
|
+
readonly details?: unknown;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Business logic for POST scenario endpoint.
|
|
20
|
+
*
|
|
21
|
+
* Handles scenario switching with complete validation and error handling.
|
|
22
|
+
* Framework-agnostic - can be used by any adapter (Pages, App, Express, etc.).
|
|
23
|
+
*
|
|
24
|
+
* Steps:
|
|
25
|
+
* 1. Validate request body against schema
|
|
26
|
+
* 2. Extract test ID from request context
|
|
27
|
+
* 3. Attempt scenario switch via manager
|
|
28
|
+
* 4. Return appropriate success/error result
|
|
29
|
+
*
|
|
30
|
+
* Error Handling:
|
|
31
|
+
* - Zod validation error → 400 with validation details
|
|
32
|
+
* - Scenario not found → 400 with error message
|
|
33
|
+
* - Unexpected error → 500 with generic message
|
|
34
|
+
*
|
|
35
|
+
* @param body - Raw request body (to be validated)
|
|
36
|
+
* @param context - Request context for test ID extraction
|
|
37
|
+
* @param manager - Scenario manager for switching scenarios
|
|
38
|
+
* @returns Result with success/failure status and appropriate data
|
|
39
|
+
*
|
|
40
|
+
* @example
|
|
41
|
+
* ```typescript
|
|
42
|
+
* // In framework-specific endpoint
|
|
43
|
+
* const result = await handlePostLogic(req.body, context, manager);
|
|
44
|
+
*
|
|
45
|
+
* if (!result.success) {
|
|
46
|
+
* return res.status(result.status).json({ error: result.error });
|
|
47
|
+
* }
|
|
48
|
+
*
|
|
49
|
+
* return res.status(200).json({ success: true, ...result });
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
export declare const handlePostLogic: (body: unknown, context: RequestContext, manager: ScenarioManager) => Promise<PostResult>;
|
|
53
|
+
/**
|
|
54
|
+
* Result type for GET endpoint business logic.
|
|
55
|
+
*
|
|
56
|
+
* Represents the outcome of attempting to retrieve active scenario,
|
|
57
|
+
* with appropriate status code for not found case.
|
|
58
|
+
*/
|
|
59
|
+
export type GetResult = {
|
|
60
|
+
readonly success: true;
|
|
61
|
+
readonly testId: string;
|
|
62
|
+
readonly scenarioId: string;
|
|
63
|
+
readonly scenarioName?: string;
|
|
64
|
+
} | {
|
|
65
|
+
readonly success: false;
|
|
66
|
+
readonly status: 404;
|
|
67
|
+
readonly error: string;
|
|
68
|
+
readonly testId: string;
|
|
69
|
+
};
|
|
70
|
+
/**
|
|
71
|
+
* Business logic for GET scenario endpoint.
|
|
72
|
+
*
|
|
73
|
+
* Retrieves the active scenario for the current test ID.
|
|
74
|
+
* Framework-agnostic - can be used by any adapter.
|
|
75
|
+
*
|
|
76
|
+
* Steps:
|
|
77
|
+
* 1. Extract test ID from request context
|
|
78
|
+
* 2. Get active scenario from manager
|
|
79
|
+
* 3. If found, enrich with scenario name
|
|
80
|
+
* 4. Return appropriate success/error result
|
|
81
|
+
*
|
|
82
|
+
* @param context - Request context for test ID extraction
|
|
83
|
+
* @param manager - Scenario manager for retrieving active scenario
|
|
84
|
+
* @returns Result with success/failure status and appropriate data
|
|
85
|
+
*
|
|
86
|
+
* @example
|
|
87
|
+
* ```typescript
|
|
88
|
+
* // In framework-specific endpoint
|
|
89
|
+
* const result = handleGetLogic(context, manager);
|
|
90
|
+
*
|
|
91
|
+
* if (!result.success) {
|
|
92
|
+
* return res.status(result.status).json({ error: result.error });
|
|
93
|
+
* }
|
|
94
|
+
*
|
|
95
|
+
* return res.status(200).json(result);
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
98
|
+
export declare const handleGetLogic: (context: RequestContext, manager: ScenarioManager) => GetResult;
|
|
99
|
+
//# sourceMappingURL=endpoint-handlers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"endpoint-handlers.d.ts","sourceRoot":"","sources":["../../src/common/endpoint-handlers.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,cAAc,EACpB,MAAM,iBAAiB,CAAC;AAEzB;;;;;GAKG;AACH,MAAM,MAAM,UAAU,GAClB;IACE,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC7B,GACD;IACE,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,GAAG,GAAG,GAAG,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAC;CAC5B,CAAC;AAEN;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,eAAO,MAAM,eAAe,GAC1B,MAAM,OAAO,EACb,SAAS,cAAc,EACvB,SAAS,eAAe,KACvB,OAAO,CAAC,UAAU,CA0CpB,CAAC;AAEF;;;;;GAKG;AACH,MAAM,MAAM,SAAS,GACjB;IACE,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;CAChC,GACD;IACE,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC;IACxB,QAAQ,CAAC,MAAM,EAAE,GAAG,CAAC;IACrB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;CACzB,CAAC;AAEN;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,eAAO,MAAM,cAAc,GACzB,SAAS,cAAc,EACvB,SAAS,eAAe,KACvB,SAqBF,CAAC"}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { ScenarioRequestSchema, } from '@scenarist/core';
|
|
3
|
+
/**
|
|
4
|
+
* Business logic for POST scenario endpoint.
|
|
5
|
+
*
|
|
6
|
+
* Handles scenario switching with complete validation and error handling.
|
|
7
|
+
* Framework-agnostic - can be used by any adapter (Pages, App, Express, etc.).
|
|
8
|
+
*
|
|
9
|
+
* Steps:
|
|
10
|
+
* 1. Validate request body against schema
|
|
11
|
+
* 2. Extract test ID from request context
|
|
12
|
+
* 3. Attempt scenario switch via manager
|
|
13
|
+
* 4. Return appropriate success/error result
|
|
14
|
+
*
|
|
15
|
+
* Error Handling:
|
|
16
|
+
* - Zod validation error → 400 with validation details
|
|
17
|
+
* - Scenario not found → 400 with error message
|
|
18
|
+
* - Unexpected error → 500 with generic message
|
|
19
|
+
*
|
|
20
|
+
* @param body - Raw request body (to be validated)
|
|
21
|
+
* @param context - Request context for test ID extraction
|
|
22
|
+
* @param manager - Scenario manager for switching scenarios
|
|
23
|
+
* @returns Result with success/failure status and appropriate data
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```typescript
|
|
27
|
+
* // In framework-specific endpoint
|
|
28
|
+
* const result = await handlePostLogic(req.body, context, manager);
|
|
29
|
+
*
|
|
30
|
+
* if (!result.success) {
|
|
31
|
+
* return res.status(result.status).json({ error: result.error });
|
|
32
|
+
* }
|
|
33
|
+
*
|
|
34
|
+
* return res.status(200).json({ success: true, ...result });
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export const handlePostLogic = async (body, context, manager) => {
|
|
38
|
+
try {
|
|
39
|
+
// Validate request body
|
|
40
|
+
const { scenario } = ScenarioRequestSchema.parse(body);
|
|
41
|
+
// Extract test ID from context
|
|
42
|
+
const testId = context.getTestId();
|
|
43
|
+
// Attempt scenario switch
|
|
44
|
+
const result = manager.switchScenario(testId, scenario);
|
|
45
|
+
if (!result.success) {
|
|
46
|
+
return {
|
|
47
|
+
success: false,
|
|
48
|
+
status: 400,
|
|
49
|
+
error: result.error.message,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
return {
|
|
53
|
+
success: true,
|
|
54
|
+
testId,
|
|
55
|
+
scenarioId: scenario,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
// Zod validation error
|
|
60
|
+
if (error instanceof z.ZodError) {
|
|
61
|
+
return {
|
|
62
|
+
success: false,
|
|
63
|
+
status: 400,
|
|
64
|
+
error: 'Invalid request body',
|
|
65
|
+
details: error.issues,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
// Unexpected error
|
|
69
|
+
return {
|
|
70
|
+
success: false,
|
|
71
|
+
status: 500,
|
|
72
|
+
error: 'Internal server error',
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* Business logic for GET scenario endpoint.
|
|
78
|
+
*
|
|
79
|
+
* Retrieves the active scenario for the current test ID.
|
|
80
|
+
* Framework-agnostic - can be used by any adapter.
|
|
81
|
+
*
|
|
82
|
+
* Steps:
|
|
83
|
+
* 1. Extract test ID from request context
|
|
84
|
+
* 2. Get active scenario from manager
|
|
85
|
+
* 3. If found, enrich with scenario name
|
|
86
|
+
* 4. Return appropriate success/error result
|
|
87
|
+
*
|
|
88
|
+
* @param context - Request context for test ID extraction
|
|
89
|
+
* @param manager - Scenario manager for retrieving active scenario
|
|
90
|
+
* @returns Result with success/failure status and appropriate data
|
|
91
|
+
*
|
|
92
|
+
* @example
|
|
93
|
+
* ```typescript
|
|
94
|
+
* // In framework-specific endpoint
|
|
95
|
+
* const result = handleGetLogic(context, manager);
|
|
96
|
+
*
|
|
97
|
+
* if (!result.success) {
|
|
98
|
+
* return res.status(result.status).json({ error: result.error });
|
|
99
|
+
* }
|
|
100
|
+
*
|
|
101
|
+
* return res.status(200).json(result);
|
|
102
|
+
* ```
|
|
103
|
+
*/
|
|
104
|
+
export const handleGetLogic = (context, manager) => {
|
|
105
|
+
const testId = context.getTestId();
|
|
106
|
+
const activeScenario = manager.getActiveScenario(testId);
|
|
107
|
+
if (!activeScenario) {
|
|
108
|
+
return {
|
|
109
|
+
success: false,
|
|
110
|
+
status: 404,
|
|
111
|
+
error: 'No active scenario for this test ID',
|
|
112
|
+
testId,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
const scenarioDefinition = manager.getScenarioById(activeScenario.scenarioId);
|
|
116
|
+
return {
|
|
117
|
+
success: true,
|
|
118
|
+
testId,
|
|
119
|
+
scenarioId: activeScenario.scenarioId,
|
|
120
|
+
...(scenarioDefinition && { scenarioName: scenarioDefinition.name }),
|
|
121
|
+
};
|
|
122
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { NextApiRequest } from 'next';
|
|
2
|
+
import { type RequestContext, type ScenaristConfig } from '@scenarist/core';
|
|
3
|
+
/**
|
|
4
|
+
* RequestContext implementation for Next.js Pages Router.
|
|
5
|
+
*
|
|
6
|
+
* Adapts NextApiRequest to the RequestContext port interface,
|
|
7
|
+
* enabling test ID extraction and mock control for Pages Router API routes.
|
|
8
|
+
*/
|
|
9
|
+
export declare class PagesRequestContext implements RequestContext {
|
|
10
|
+
private readonly req;
|
|
11
|
+
private readonly config;
|
|
12
|
+
constructor(req: NextApiRequest, config: ScenaristConfig);
|
|
13
|
+
getTestId(): string;
|
|
14
|
+
getHeaders(): Record<string, string | string[] | undefined>;
|
|
15
|
+
getHostname(): string;
|
|
16
|
+
}
|
|
17
|
+
//# sourceMappingURL=context.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/pages/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,MAAM,CAAC;AAC3C,OAAO,EAA4B,KAAK,cAAc,EAAE,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAEtG;;;;;GAKG;AACH,qBAAa,mBAAoB,YAAW,cAAc;IAEtD,OAAO,CAAC,QAAQ,CAAC,GAAG;IACpB,OAAO,CAAC,QAAQ,CAAC,MAAM;gBADN,GAAG,EAAE,cAAc,EACnB,MAAM,EAAE,eAAe;IAG1C,SAAS,IAAI,MAAM;IAcnB,UAAU,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;IAI3D,WAAW,IAAI,MAAM;CAgBtB"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { SCENARIST_TEST_ID_HEADER } from '@scenarist/core';
|
|
2
|
+
/**
|
|
3
|
+
* RequestContext implementation for Next.js Pages Router.
|
|
4
|
+
*
|
|
5
|
+
* Adapts NextApiRequest to the RequestContext port interface,
|
|
6
|
+
* enabling test ID extraction and mock control for Pages Router API routes.
|
|
7
|
+
*/
|
|
8
|
+
export class PagesRequestContext {
|
|
9
|
+
req;
|
|
10
|
+
config;
|
|
11
|
+
constructor(req, config) {
|
|
12
|
+
this.req = req;
|
|
13
|
+
this.config = config;
|
|
14
|
+
}
|
|
15
|
+
getTestId() {
|
|
16
|
+
const header = this.req.headers[SCENARIST_TEST_ID_HEADER];
|
|
17
|
+
if (typeof header === 'string') {
|
|
18
|
+
return header;
|
|
19
|
+
}
|
|
20
|
+
if (Array.isArray(header) && header.length > 0 && header[0]) {
|
|
21
|
+
return header[0];
|
|
22
|
+
}
|
|
23
|
+
return this.config.defaultTestId;
|
|
24
|
+
}
|
|
25
|
+
getHeaders() {
|
|
26
|
+
return this.req.headers;
|
|
27
|
+
}
|
|
28
|
+
getHostname() {
|
|
29
|
+
const host = this.req.headers.host;
|
|
30
|
+
if (!host) {
|
|
31
|
+
return '';
|
|
32
|
+
}
|
|
33
|
+
// After null check, host is string | string[]
|
|
34
|
+
if (typeof host === 'string') {
|
|
35
|
+
return host;
|
|
36
|
+
}
|
|
37
|
+
// host must be string[] at this point (type assertion needed due to TS control flow limitation)
|
|
38
|
+
const hostArray = host;
|
|
39
|
+
return hostArray.length > 0 ? hostArray[0] ?? '' : '';
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { NextApiRequest, NextApiResponse } from 'next';
|
|
2
|
+
import type { ScenarioManager, ScenaristConfig } from '@scenarist/core';
|
|
3
|
+
/**
|
|
4
|
+
* Create scenario endpoint handler for Next.js Pages Router.
|
|
5
|
+
*
|
|
6
|
+
* Returns a Next.js API route handler that supports:
|
|
7
|
+
* - POST: Switch scenario
|
|
8
|
+
* - GET: Retrieve active scenario
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```typescript
|
|
12
|
+
* // pages/api/__scenario__.ts
|
|
13
|
+
* import { createScenarioEndpoint } from '@scenarist/nextjs-adapter/pages';
|
|
14
|
+
* import { scenarist } from '../../lib/scenarist';
|
|
15
|
+
*
|
|
16
|
+
* export default createScenarioEndpoint(scenarist.manager, scenarist.config);
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export declare const createScenarioEndpoint: (manager: ScenarioManager, config: ScenaristConfig) => (req: NextApiRequest, res: NextApiResponse) => Promise<void>;
|
|
20
|
+
//# sourceMappingURL=endpoints.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"endpoints.d.ts","sourceRoot":"","sources":["../../src/pages/endpoints.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,MAAM,CAAC;AAC5D,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AA6DxE;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,sBAAsB,GACjC,SAAS,eAAe,EACxB,QAAQ,eAAe,MAKT,KAAK,cAAc,EAAE,KAAK,eAAe,KAAG,OAAO,CAAC,IAAI,CAavE,CAAC"}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { PagesRequestContext } from './context.js';
|
|
2
|
+
import { handlePostLogic, handleGetLogic } from '../common/endpoint-handlers.js';
|
|
3
|
+
/**
|
|
4
|
+
* Handle POST request to switch scenarios.
|
|
5
|
+
*
|
|
6
|
+
* Thin wrapper that adapts Next.js Pages Router Request/Response
|
|
7
|
+
* to shared business logic.
|
|
8
|
+
*/
|
|
9
|
+
const handlePost = (manager, config) => {
|
|
10
|
+
return async (req, res) => {
|
|
11
|
+
const context = new PagesRequestContext(req, config);
|
|
12
|
+
const result = await handlePostLogic(req.body, context, manager);
|
|
13
|
+
if (!result.success) {
|
|
14
|
+
const response = {
|
|
15
|
+
error: result.error,
|
|
16
|
+
};
|
|
17
|
+
if (result.details) {
|
|
18
|
+
response.details = result.details;
|
|
19
|
+
}
|
|
20
|
+
res.status(result.status).json(response);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
res.status(200).json({
|
|
24
|
+
success: true,
|
|
25
|
+
testId: result.testId,
|
|
26
|
+
scenarioId: result.scenarioId,
|
|
27
|
+
});
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Handle GET request to retrieve active scenario.
|
|
32
|
+
*
|
|
33
|
+
* Thin wrapper that adapts Next.js Pages Router Request/Response
|
|
34
|
+
* to shared business logic.
|
|
35
|
+
*/
|
|
36
|
+
const handleGet = (manager, config) => {
|
|
37
|
+
return async (req, res) => {
|
|
38
|
+
const context = new PagesRequestContext(req, config);
|
|
39
|
+
const result = handleGetLogic(context, manager);
|
|
40
|
+
if (!result.success) {
|
|
41
|
+
res.status(result.status).json({
|
|
42
|
+
error: result.error,
|
|
43
|
+
testId: result.testId,
|
|
44
|
+
});
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
res.status(200).json({
|
|
48
|
+
testId: result.testId,
|
|
49
|
+
scenarioId: result.scenarioId,
|
|
50
|
+
...(result.scenarioName && { scenarioName: result.scenarioName }),
|
|
51
|
+
});
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Create scenario endpoint handler for Next.js Pages Router.
|
|
56
|
+
*
|
|
57
|
+
* Returns a Next.js API route handler that supports:
|
|
58
|
+
* - POST: Switch scenario
|
|
59
|
+
* - GET: Retrieve active scenario
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```typescript
|
|
63
|
+
* // pages/api/__scenario__.ts
|
|
64
|
+
* import { createScenarioEndpoint } from '@scenarist/nextjs-adapter/pages';
|
|
65
|
+
* import { scenarist } from '../../lib/scenarist';
|
|
66
|
+
*
|
|
67
|
+
* export default createScenarioEndpoint(scenarist.manager, scenarist.config);
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
export const createScenarioEndpoint = (manager, config) => {
|
|
71
|
+
const postHandler = handlePost(manager, config);
|
|
72
|
+
const getHandler = handleGet(manager, config);
|
|
73
|
+
return async (req, res) => {
|
|
74
|
+
if (req.method === 'POST') {
|
|
75
|
+
return postHandler(req, res);
|
|
76
|
+
}
|
|
77
|
+
if (req.method === 'GET') {
|
|
78
|
+
return getHandler(req, res);
|
|
79
|
+
}
|
|
80
|
+
res.status(405).json({
|
|
81
|
+
error: 'Method not allowed',
|
|
82
|
+
});
|
|
83
|
+
};
|
|
84
|
+
};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { IncomingMessage } from 'http';
|
|
2
|
+
/**
|
|
3
|
+
* Type for request objects that have headers.
|
|
4
|
+
* Compatible with both NextApiRequest and GetServerSidePropsContext.req
|
|
5
|
+
*/
|
|
6
|
+
type RequestWithHeaders = {
|
|
7
|
+
headers: IncomingMessage['headers'];
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Safe helper to extract Scenarist infrastructure headers from a request.
|
|
11
|
+
*
|
|
12
|
+
* This helper accesses the global scenarist instance and safely returns headers
|
|
13
|
+
* even when scenarist is undefined (production builds). It respects the configured
|
|
14
|
+
* test ID header name and default test ID.
|
|
15
|
+
*
|
|
16
|
+
* **Production Behavior:**
|
|
17
|
+
* - Returns `{}` (empty object) when scenarist is undefined
|
|
18
|
+
* - Safe to spread in fetch headers without guards
|
|
19
|
+
* - Zero runtime overhead (tree-shaken in production builds)
|
|
20
|
+
*
|
|
21
|
+
* **Why use this instead of scenarist.getHeaders()?**
|
|
22
|
+
* - No need to check if scenarist is defined (`scenarist?.getHeaders(req) ?? {}`)
|
|
23
|
+
* - Works automatically by accessing the global singleton
|
|
24
|
+
* - Consistent API across development, test, and production
|
|
25
|
+
*
|
|
26
|
+
* @param req - Request object with headers (NextApiRequest or GetServerSidePropsContext.req)
|
|
27
|
+
* @returns Object with single entry: configured test ID header name → value from request or default
|
|
28
|
+
* Returns `{}` in production when scenarist is undefined
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```typescript
|
|
32
|
+
* // API Route
|
|
33
|
+
* import { getScenaristHeaders } from '@scenarist/nextjs-adapter/pages';
|
|
34
|
+
*
|
|
35
|
+
* export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
36
|
+
* const response = await fetch('http://localhost:3001/products', {
|
|
37
|
+
* headers: {
|
|
38
|
+
* ...getScenaristHeaders(req), // Always safe, no guards needed
|
|
39
|
+
* 'x-user-tier': 'premium',
|
|
40
|
+
* },
|
|
41
|
+
* });
|
|
42
|
+
* }
|
|
43
|
+
*
|
|
44
|
+
* // getServerSideProps
|
|
45
|
+
* import { getScenaristHeaders } from '@scenarist/nextjs-adapter/pages';
|
|
46
|
+
*
|
|
47
|
+
* export const getServerSideProps: GetServerSideProps = async (context) => {
|
|
48
|
+
* const response = await fetch('http://localhost:3001/products', {
|
|
49
|
+
* headers: getScenaristHeaders(context.req),
|
|
50
|
+
* });
|
|
51
|
+
* };
|
|
52
|
+
* ```
|
|
53
|
+
*/
|
|
54
|
+
export declare function getScenaristHeaders(req: RequestWithHeaders): Record<string, string>;
|
|
55
|
+
export {};
|
|
56
|
+
//# sourceMappingURL=helpers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/pages/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,MAAM,CAAC;AAE5C;;;GAGG;AACH,KAAK,kBAAkB,GAAG;IACxB,OAAO,EAAE,eAAe,CAAC,SAAS,CAAC,CAAC;CACrC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,kBAAkB,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAGnF"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Safe helper to extract Scenarist infrastructure headers from a request.
|
|
3
|
+
*
|
|
4
|
+
* This helper accesses the global scenarist instance and safely returns headers
|
|
5
|
+
* even when scenarist is undefined (production builds). It respects the configured
|
|
6
|
+
* test ID header name and default test ID.
|
|
7
|
+
*
|
|
8
|
+
* **Production Behavior:**
|
|
9
|
+
* - Returns `{}` (empty object) when scenarist is undefined
|
|
10
|
+
* - Safe to spread in fetch headers without guards
|
|
11
|
+
* - Zero runtime overhead (tree-shaken in production builds)
|
|
12
|
+
*
|
|
13
|
+
* **Why use this instead of scenarist.getHeaders()?**
|
|
14
|
+
* - No need to check if scenarist is defined (`scenarist?.getHeaders(req) ?? {}`)
|
|
15
|
+
* - Works automatically by accessing the global singleton
|
|
16
|
+
* - Consistent API across development, test, and production
|
|
17
|
+
*
|
|
18
|
+
* @param req - Request object with headers (NextApiRequest or GetServerSidePropsContext.req)
|
|
19
|
+
* @returns Object with single entry: configured test ID header name → value from request or default
|
|
20
|
+
* Returns `{}` in production when scenarist is undefined
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* ```typescript
|
|
24
|
+
* // API Route
|
|
25
|
+
* import { getScenaristHeaders } from '@scenarist/nextjs-adapter/pages';
|
|
26
|
+
*
|
|
27
|
+
* export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|
28
|
+
* const response = await fetch('http://localhost:3001/products', {
|
|
29
|
+
* headers: {
|
|
30
|
+
* ...getScenaristHeaders(req), // Always safe, no guards needed
|
|
31
|
+
* 'x-user-tier': 'premium',
|
|
32
|
+
* },
|
|
33
|
+
* });
|
|
34
|
+
* }
|
|
35
|
+
*
|
|
36
|
+
* // getServerSideProps
|
|
37
|
+
* import { getScenaristHeaders } from '@scenarist/nextjs-adapter/pages';
|
|
38
|
+
*
|
|
39
|
+
* export const getServerSideProps: GetServerSideProps = async (context) => {
|
|
40
|
+
* const response = await fetch('http://localhost:3001/products', {
|
|
41
|
+
* headers: getScenaristHeaders(context.req),
|
|
42
|
+
* });
|
|
43
|
+
* };
|
|
44
|
+
* ```
|
|
45
|
+
*/
|
|
46
|
+
export function getScenaristHeaders(req) {
|
|
47
|
+
const scenarist = global.__scenarist_instance_pages;
|
|
48
|
+
return scenarist?.getHeaders(req) ?? {};
|
|
49
|
+
}
|