@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,19 @@
|
|
|
1
|
+
import { type RequestContext, type ScenaristConfig } from '@scenarist/core';
|
|
2
|
+
/**
|
|
3
|
+
* RequestContext implementation for Next.js App Router.
|
|
4
|
+
*
|
|
5
|
+
* Adapts Web standard Request to the RequestContext port interface,
|
|
6
|
+
* enabling test ID extraction and mock control for App Router API routes.
|
|
7
|
+
*
|
|
8
|
+
* Unlike Pages Router, App Router uses the Web standard Request/Response API
|
|
9
|
+
* with Headers object instead of Node.js-style headers.
|
|
10
|
+
*/
|
|
11
|
+
export declare class AppRequestContext implements RequestContext {
|
|
12
|
+
private readonly req;
|
|
13
|
+
private readonly config;
|
|
14
|
+
constructor(req: Request, config: ScenaristConfig);
|
|
15
|
+
getTestId(): string;
|
|
16
|
+
getHeaders(): Record<string, string | string[] | undefined>;
|
|
17
|
+
getHostname(): string;
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=context.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/app/context.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4B,KAAK,cAAc,EAAE,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAEtG;;;;;;;;GAQG;AACH,qBAAa,iBAAkB,YAAW,cAAc;IAEpD,OAAO,CAAC,QAAQ,CAAC,GAAG;IACpB,OAAO,CAAC,QAAQ,CAAC,MAAM;gBADN,GAAG,EAAE,OAAO,EACZ,MAAM,EAAE,eAAe;IAG1C,SAAS,IAAI,MAAM;IAUnB,UAAU,IAAI,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;IAU3D,WAAW,IAAI,MAAM;CAUtB"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { SCENARIST_TEST_ID_HEADER } from '@scenarist/core';
|
|
2
|
+
/**
|
|
3
|
+
* RequestContext implementation for Next.js App Router.
|
|
4
|
+
*
|
|
5
|
+
* Adapts Web standard Request to the RequestContext port interface,
|
|
6
|
+
* enabling test ID extraction and mock control for App Router API routes.
|
|
7
|
+
*
|
|
8
|
+
* Unlike Pages Router, App Router uses the Web standard Request/Response API
|
|
9
|
+
* with Headers object instead of Node.js-style headers.
|
|
10
|
+
*/
|
|
11
|
+
export class AppRequestContext {
|
|
12
|
+
req;
|
|
13
|
+
config;
|
|
14
|
+
constructor(req, config) {
|
|
15
|
+
this.req = req;
|
|
16
|
+
this.config = config;
|
|
17
|
+
}
|
|
18
|
+
getTestId() {
|
|
19
|
+
const header = this.req.headers.get(SCENARIST_TEST_ID_HEADER);
|
|
20
|
+
if (header) {
|
|
21
|
+
return header;
|
|
22
|
+
}
|
|
23
|
+
return this.config.defaultTestId;
|
|
24
|
+
}
|
|
25
|
+
getHeaders() {
|
|
26
|
+
const headers = {};
|
|
27
|
+
this.req.headers.forEach((value, key) => {
|
|
28
|
+
headers[key] = value;
|
|
29
|
+
});
|
|
30
|
+
return headers;
|
|
31
|
+
}
|
|
32
|
+
getHostname() {
|
|
33
|
+
try {
|
|
34
|
+
const url = new URL(this.req.url);
|
|
35
|
+
return url.host;
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
// Return empty string for malformed URLs (e.g., relative URLs without base)
|
|
39
|
+
// This is expected behavior - hostname extraction is best-effort
|
|
40
|
+
return '';
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { ScenarioManager, ScenaristConfig } from '@scenarist/core';
|
|
2
|
+
/**
|
|
3
|
+
* Create scenario endpoint handler for Next.js App Router.
|
|
4
|
+
*
|
|
5
|
+
* Returns a Web standard Request/Response handler that supports:
|
|
6
|
+
* - POST: Switch scenario
|
|
7
|
+
* - GET: Retrieve active scenario
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* // app/api/%5F%5Fscenario%5F%5F/route.ts
|
|
12
|
+
* import { createScenarioEndpoint } from '@scenarist/nextjs-adapter/app';
|
|
13
|
+
* import { scenarist } from '@/lib/scenarist';
|
|
14
|
+
*
|
|
15
|
+
* export const POST = scenarist.createScenarioEndpoint();
|
|
16
|
+
* export const GET = scenarist.createScenarioEndpoint();
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export declare const createScenarioEndpoint: (manager: ScenarioManager, config: ScenaristConfig) => (req: Request) => Promise<Response>;
|
|
20
|
+
//# sourceMappingURL=endpoints.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"endpoints.d.ts","sourceRoot":"","sources":["../../src/app/endpoints.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAqExE;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,sBAAsB,GACjC,SAAS,eAAe,EACxB,QAAQ,eAAe,MAKT,KAAK,OAAO,KAAG,OAAO,CAAC,QAAQ,CAgB9C,CAAC"}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { AppRequestContext } 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 App Router Request/Response
|
|
7
|
+
* to shared business logic.
|
|
8
|
+
*/
|
|
9
|
+
const handlePost = (manager, config) => {
|
|
10
|
+
return async (req) => {
|
|
11
|
+
const body = await req.json();
|
|
12
|
+
const context = new AppRequestContext(req, config);
|
|
13
|
+
const result = await handlePostLogic(body, context, manager);
|
|
14
|
+
if (!result.success) {
|
|
15
|
+
const response = {
|
|
16
|
+
error: result.error,
|
|
17
|
+
};
|
|
18
|
+
if (result.details) {
|
|
19
|
+
response.details = result.details;
|
|
20
|
+
}
|
|
21
|
+
return Response.json(response, { status: result.status });
|
|
22
|
+
}
|
|
23
|
+
return Response.json({
|
|
24
|
+
success: true,
|
|
25
|
+
testId: result.testId,
|
|
26
|
+
scenarioId: result.scenarioId,
|
|
27
|
+
}, { status: 200 });
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Handle GET request to retrieve active scenario.
|
|
32
|
+
*
|
|
33
|
+
* Thin wrapper that adapts Next.js App Router Request/Response
|
|
34
|
+
* to shared business logic.
|
|
35
|
+
*/
|
|
36
|
+
const handleGet = (manager, config) => {
|
|
37
|
+
return async (req) => {
|
|
38
|
+
const context = new AppRequestContext(req, config);
|
|
39
|
+
const result = handleGetLogic(context, manager);
|
|
40
|
+
if (!result.success) {
|
|
41
|
+
return Response.json({
|
|
42
|
+
error: result.error,
|
|
43
|
+
testId: result.testId,
|
|
44
|
+
}, { status: result.status });
|
|
45
|
+
}
|
|
46
|
+
return Response.json({
|
|
47
|
+
testId: result.testId,
|
|
48
|
+
scenarioId: result.scenarioId,
|
|
49
|
+
...(result.scenarioName && { scenarioName: result.scenarioName }),
|
|
50
|
+
}, { status: 200 });
|
|
51
|
+
};
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Create scenario endpoint handler for Next.js App Router.
|
|
55
|
+
*
|
|
56
|
+
* Returns a Web standard Request/Response handler that supports:
|
|
57
|
+
* - POST: Switch scenario
|
|
58
|
+
* - GET: Retrieve active scenario
|
|
59
|
+
*
|
|
60
|
+
* @example
|
|
61
|
+
* ```typescript
|
|
62
|
+
* // app/api/%5F%5Fscenario%5F%5F/route.ts
|
|
63
|
+
* import { createScenarioEndpoint } from '@scenarist/nextjs-adapter/app';
|
|
64
|
+
* import { scenarist } from '@/lib/scenarist';
|
|
65
|
+
*
|
|
66
|
+
* export const POST = scenarist.createScenarioEndpoint();
|
|
67
|
+
* export const GET = scenarist.createScenarioEndpoint();
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
export const createScenarioEndpoint = (manager, config) => {
|
|
71
|
+
const postHandler = handlePost(manager, config);
|
|
72
|
+
const getHandler = handleGet(manager, config);
|
|
73
|
+
return async (req) => {
|
|
74
|
+
if (req.method === 'POST') {
|
|
75
|
+
return postHandler(req);
|
|
76
|
+
}
|
|
77
|
+
if (req.method === 'GET') {
|
|
78
|
+
return getHandler(req);
|
|
79
|
+
}
|
|
80
|
+
return Response.json({
|
|
81
|
+
error: 'Method not allowed',
|
|
82
|
+
}, { status: 405 });
|
|
83
|
+
};
|
|
84
|
+
};
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Safe helper to extract Scenarist infrastructure headers from a Request object.
|
|
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 - The Web standard Request object
|
|
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
|
+
* // Route Handler
|
|
25
|
+
* import { getScenaristHeaders } from '@scenarist/nextjs-adapter/app';
|
|
26
|
+
*
|
|
27
|
+
* export async function GET(request: Request) {
|
|
28
|
+
* const response = await fetch('http://localhost:3001/products', {
|
|
29
|
+
* headers: {
|
|
30
|
+
* ...getScenaristHeaders(request), // Always safe, no guards needed
|
|
31
|
+
* 'x-user-tier': 'premium',
|
|
32
|
+
* },
|
|
33
|
+
* });
|
|
34
|
+
* }
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
export declare function getScenaristHeaders(req: Request): Record<string, string>;
|
|
38
|
+
/**
|
|
39
|
+
* Safe helper to extract Scenarist infrastructure headers from ReadonlyHeaders.
|
|
40
|
+
*
|
|
41
|
+
* This helper is designed for Next.js Server Components that use headers() from 'next/headers',
|
|
42
|
+
* which returns ReadonlyHeaders (not a Request object). It accesses the global scenarist instance
|
|
43
|
+
* and safely returns headers even when scenarist is undefined (production builds).
|
|
44
|
+
*
|
|
45
|
+
* **Production Behavior:**
|
|
46
|
+
* - Returns `{}` (empty object) when scenarist is undefined
|
|
47
|
+
* - Safe to spread in fetch headers without guards
|
|
48
|
+
* - Zero runtime overhead (tree-shaken in production builds)
|
|
49
|
+
*
|
|
50
|
+
* **Why use this instead of scenarist.getHeadersFromReadonlyHeaders()?**
|
|
51
|
+
* - No need to check if scenarist is defined
|
|
52
|
+
* - Works automatically by accessing the global singleton
|
|
53
|
+
* - Consistent API across development, test, and production
|
|
54
|
+
*
|
|
55
|
+
* @param headers - The ReadonlyHeaders object from headers() in 'next/headers'
|
|
56
|
+
* @returns Object with single entry: configured test ID header name → value from headers or default
|
|
57
|
+
* Returns `{}` in production when scenarist is undefined
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```typescript
|
|
61
|
+
* // Server Component
|
|
62
|
+
* import { headers } from 'next/headers';
|
|
63
|
+
* import { getScenaristHeadersFromReadonlyHeaders } from '@scenarist/nextjs-adapter/app';
|
|
64
|
+
*
|
|
65
|
+
* export default async function ProductsPage() {
|
|
66
|
+
* const headersList = await headers();
|
|
67
|
+
*
|
|
68
|
+
* const response = await fetch('http://localhost:3001/products', {
|
|
69
|
+
* headers: {
|
|
70
|
+
* ...getScenaristHeadersFromReadonlyHeaders(headersList), // Always safe
|
|
71
|
+
* 'x-user-tier': 'premium',
|
|
72
|
+
* },
|
|
73
|
+
* });
|
|
74
|
+
*
|
|
75
|
+
* const data = await response.json();
|
|
76
|
+
* return <ProductList products={data.products} />;
|
|
77
|
+
* }
|
|
78
|
+
* ```
|
|
79
|
+
*/
|
|
80
|
+
export declare function getScenaristHeadersFromReadonlyHeaders(headers: {
|
|
81
|
+
get(name: string): string | null;
|
|
82
|
+
}): Record<string, string>;
|
|
83
|
+
/**
|
|
84
|
+
* Safe helper to extract just the test ID from ReadonlyHeaders.
|
|
85
|
+
*
|
|
86
|
+
* This helper is designed for scenarios where you need the test ID value directly,
|
|
87
|
+
* such as when integrating with repository patterns or other test-scoped systems.
|
|
88
|
+
*
|
|
89
|
+
* **Production Behavior:**
|
|
90
|
+
* - Returns `'default-test'` when scenarist is undefined
|
|
91
|
+
* - Safe to use for partitioning data without guards
|
|
92
|
+
* - Zero runtime overhead (tree-shaken in production builds)
|
|
93
|
+
*
|
|
94
|
+
* **Use this when:**
|
|
95
|
+
* - You need to partition in-memory data by test ID
|
|
96
|
+
* - You're integrating Scenarist with custom test isolation mechanisms
|
|
97
|
+
* - You need the test ID for logging/debugging
|
|
98
|
+
*
|
|
99
|
+
* @param headers - The ReadonlyHeaders object from headers() in 'next/headers'
|
|
100
|
+
* @returns The test ID string extracted from headers, or configured default if not found
|
|
101
|
+
*
|
|
102
|
+
* @example
|
|
103
|
+
* ```typescript
|
|
104
|
+
* // Server Component with repository pattern
|
|
105
|
+
* import { headers } from 'next/headers';
|
|
106
|
+
* import { getScenaristTestIdFromReadonlyHeaders } from '@scenarist/nextjs-adapter/app';
|
|
107
|
+
* import { runWithTestId, getUserRepository } from '@/lib/container';
|
|
108
|
+
*
|
|
109
|
+
* export default async function UserPage() {
|
|
110
|
+
* const headersList = await headers();
|
|
111
|
+
* const testId = getScenaristTestIdFromReadonlyHeaders(headersList);
|
|
112
|
+
*
|
|
113
|
+
* // Use test ID for repository isolation
|
|
114
|
+
* const user = await runWithTestId(testId, async () => {
|
|
115
|
+
* const userRepo = getUserRepository();
|
|
116
|
+
* return userRepo.findById('user-123');
|
|
117
|
+
* });
|
|
118
|
+
*
|
|
119
|
+
* return <UserProfile user={user} />;
|
|
120
|
+
* }
|
|
121
|
+
* ```
|
|
122
|
+
*/
|
|
123
|
+
export declare function getScenaristTestIdFromReadonlyHeaders(headers: {
|
|
124
|
+
get(name: string): string | null;
|
|
125
|
+
}): string;
|
|
126
|
+
/**
|
|
127
|
+
* Safe helper to extract just the test ID from a Request object.
|
|
128
|
+
*
|
|
129
|
+
* This helper is designed for Route Handlers where you need the test ID value directly.
|
|
130
|
+
*
|
|
131
|
+
* **Production Behavior:**
|
|
132
|
+
* - Returns `'default-test'` when scenarist is undefined
|
|
133
|
+
* - Safe to use for partitioning data without guards
|
|
134
|
+
* - Zero runtime overhead (tree-shaken in production builds)
|
|
135
|
+
*
|
|
136
|
+
* @param req - The Web standard Request object
|
|
137
|
+
* @returns The test ID string extracted from request headers, or configured default if not found
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* ```typescript
|
|
141
|
+
* // Route Handler
|
|
142
|
+
* import { getScenaristTestId } from '@scenarist/nextjs-adapter/app';
|
|
143
|
+
*
|
|
144
|
+
* export async function GET(request: Request) {
|
|
145
|
+
* const testId = getScenaristTestId(request);
|
|
146
|
+
* console.log('Processing request for test:', testId);
|
|
147
|
+
* // ...
|
|
148
|
+
* }
|
|
149
|
+
* ```
|
|
150
|
+
*/
|
|
151
|
+
export declare function getScenaristTestId(req: Request): string;
|
|
152
|
+
//# sourceMappingURL=helpers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"helpers.d.ts","sourceRoot":"","sources":["../../src/app/helpers.ts"],"names":[],"mappings":"AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAGxE;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AACH,wBAAgB,sCAAsC,CAAC,OAAO,EAAE;IAAE,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAA;CAAE,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAG5H;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AACH,wBAAgB,qCAAqC,CAAC,OAAO,EAAE;IAAE,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAA;CAAE,GAAG,MAAM,CAQ3G;AAED;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAQvD"}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { SCENARIST_TEST_ID_HEADER } from '@scenarist/core';
|
|
2
|
+
/**
|
|
3
|
+
* Fallback constant for default test ID when scenarist is undefined (production builds).
|
|
4
|
+
* In development/test, this is overridden by values from scenarist.config.
|
|
5
|
+
*/
|
|
6
|
+
const FALLBACK_DEFAULT_TEST_ID = 'default-test';
|
|
7
|
+
/**
|
|
8
|
+
* Safe helper to extract Scenarist infrastructure headers from a Request object.
|
|
9
|
+
*
|
|
10
|
+
* This helper accesses the global scenarist instance and safely returns headers
|
|
11
|
+
* even when scenarist is undefined (production builds). It respects the configured
|
|
12
|
+
* test ID header name and default test ID.
|
|
13
|
+
*
|
|
14
|
+
* **Production Behavior:**
|
|
15
|
+
* - Returns `{}` (empty object) when scenarist is undefined
|
|
16
|
+
* - Safe to spread in fetch headers without guards
|
|
17
|
+
* - Zero runtime overhead (tree-shaken in production builds)
|
|
18
|
+
*
|
|
19
|
+
* **Why use this instead of scenarist.getHeaders()?**
|
|
20
|
+
* - No need to check if scenarist is defined (`scenarist?.getHeaders(req) ?? {}`)
|
|
21
|
+
* - Works automatically by accessing the global singleton
|
|
22
|
+
* - Consistent API across development, test, and production
|
|
23
|
+
*
|
|
24
|
+
* @param req - The Web standard Request object
|
|
25
|
+
* @returns Object with single entry: configured test ID header name → value from request or default
|
|
26
|
+
* Returns `{}` in production when scenarist is undefined
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* // Route Handler
|
|
31
|
+
* import { getScenaristHeaders } from '@scenarist/nextjs-adapter/app';
|
|
32
|
+
*
|
|
33
|
+
* export async function GET(request: Request) {
|
|
34
|
+
* const response = await fetch('http://localhost:3001/products', {
|
|
35
|
+
* headers: {
|
|
36
|
+
* ...getScenaristHeaders(request), // Always safe, no guards needed
|
|
37
|
+
* 'x-user-tier': 'premium',
|
|
38
|
+
* },
|
|
39
|
+
* });
|
|
40
|
+
* }
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export function getScenaristHeaders(req) {
|
|
44
|
+
const scenarist = global.__scenarist_instance;
|
|
45
|
+
return scenarist?.getHeaders(req) ?? {};
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Safe helper to extract Scenarist infrastructure headers from ReadonlyHeaders.
|
|
49
|
+
*
|
|
50
|
+
* This helper is designed for Next.js Server Components that use headers() from 'next/headers',
|
|
51
|
+
* which returns ReadonlyHeaders (not a Request object). It accesses the global scenarist instance
|
|
52
|
+
* and safely returns headers even when scenarist is undefined (production builds).
|
|
53
|
+
*
|
|
54
|
+
* **Production Behavior:**
|
|
55
|
+
* - Returns `{}` (empty object) when scenarist is undefined
|
|
56
|
+
* - Safe to spread in fetch headers without guards
|
|
57
|
+
* - Zero runtime overhead (tree-shaken in production builds)
|
|
58
|
+
*
|
|
59
|
+
* **Why use this instead of scenarist.getHeadersFromReadonlyHeaders()?**
|
|
60
|
+
* - No need to check if scenarist is defined
|
|
61
|
+
* - Works automatically by accessing the global singleton
|
|
62
|
+
* - Consistent API across development, test, and production
|
|
63
|
+
*
|
|
64
|
+
* @param headers - The ReadonlyHeaders object from headers() in 'next/headers'
|
|
65
|
+
* @returns Object with single entry: configured test ID header name → value from headers or default
|
|
66
|
+
* Returns `{}` in production when scenarist is undefined
|
|
67
|
+
*
|
|
68
|
+
* @example
|
|
69
|
+
* ```typescript
|
|
70
|
+
* // Server Component
|
|
71
|
+
* import { headers } from 'next/headers';
|
|
72
|
+
* import { getScenaristHeadersFromReadonlyHeaders } from '@scenarist/nextjs-adapter/app';
|
|
73
|
+
*
|
|
74
|
+
* export default async function ProductsPage() {
|
|
75
|
+
* const headersList = await headers();
|
|
76
|
+
*
|
|
77
|
+
* const response = await fetch('http://localhost:3001/products', {
|
|
78
|
+
* headers: {
|
|
79
|
+
* ...getScenaristHeadersFromReadonlyHeaders(headersList), // Always safe
|
|
80
|
+
* 'x-user-tier': 'premium',
|
|
81
|
+
* },
|
|
82
|
+
* });
|
|
83
|
+
*
|
|
84
|
+
* const data = await response.json();
|
|
85
|
+
* return <ProductList products={data.products} />;
|
|
86
|
+
* }
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
export function getScenaristHeadersFromReadonlyHeaders(headers) {
|
|
90
|
+
const scenarist = global.__scenarist_instance;
|
|
91
|
+
return scenarist?.getHeadersFromReadonlyHeaders(headers) ?? {};
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Safe helper to extract just the test ID from ReadonlyHeaders.
|
|
95
|
+
*
|
|
96
|
+
* This helper is designed for scenarios where you need the test ID value directly,
|
|
97
|
+
* such as when integrating with repository patterns or other test-scoped systems.
|
|
98
|
+
*
|
|
99
|
+
* **Production Behavior:**
|
|
100
|
+
* - Returns `'default-test'` when scenarist is undefined
|
|
101
|
+
* - Safe to use for partitioning data without guards
|
|
102
|
+
* - Zero runtime overhead (tree-shaken in production builds)
|
|
103
|
+
*
|
|
104
|
+
* **Use this when:**
|
|
105
|
+
* - You need to partition in-memory data by test ID
|
|
106
|
+
* - You're integrating Scenarist with custom test isolation mechanisms
|
|
107
|
+
* - You need the test ID for logging/debugging
|
|
108
|
+
*
|
|
109
|
+
* @param headers - The ReadonlyHeaders object from headers() in 'next/headers'
|
|
110
|
+
* @returns The test ID string extracted from headers, or configured default if not found
|
|
111
|
+
*
|
|
112
|
+
* @example
|
|
113
|
+
* ```typescript
|
|
114
|
+
* // Server Component with repository pattern
|
|
115
|
+
* import { headers } from 'next/headers';
|
|
116
|
+
* import { getScenaristTestIdFromReadonlyHeaders } from '@scenarist/nextjs-adapter/app';
|
|
117
|
+
* import { runWithTestId, getUserRepository } from '@/lib/container';
|
|
118
|
+
*
|
|
119
|
+
* export default async function UserPage() {
|
|
120
|
+
* const headersList = await headers();
|
|
121
|
+
* const testId = getScenaristTestIdFromReadonlyHeaders(headersList);
|
|
122
|
+
*
|
|
123
|
+
* // Use test ID for repository isolation
|
|
124
|
+
* const user = await runWithTestId(testId, async () => {
|
|
125
|
+
* const userRepo = getUserRepository();
|
|
126
|
+
* return userRepo.findById('user-123');
|
|
127
|
+
* });
|
|
128
|
+
*
|
|
129
|
+
* return <UserProfile user={user} />;
|
|
130
|
+
* }
|
|
131
|
+
* ```
|
|
132
|
+
*/
|
|
133
|
+
export function getScenaristTestIdFromReadonlyHeaders(headers) {
|
|
134
|
+
const scenarist = global.__scenarist_instance;
|
|
135
|
+
if (!scenarist) {
|
|
136
|
+
return FALLBACK_DEFAULT_TEST_ID;
|
|
137
|
+
}
|
|
138
|
+
const defaultTestId = scenarist.config?.defaultTestId ?? FALLBACK_DEFAULT_TEST_ID;
|
|
139
|
+
return headers.get(SCENARIST_TEST_ID_HEADER) ?? defaultTestId;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Safe helper to extract just the test ID from a Request object.
|
|
143
|
+
*
|
|
144
|
+
* This helper is designed for Route Handlers where you need the test ID value directly.
|
|
145
|
+
*
|
|
146
|
+
* **Production Behavior:**
|
|
147
|
+
* - Returns `'default-test'` when scenarist is undefined
|
|
148
|
+
* - Safe to use for partitioning data without guards
|
|
149
|
+
* - Zero runtime overhead (tree-shaken in production builds)
|
|
150
|
+
*
|
|
151
|
+
* @param req - The Web standard Request object
|
|
152
|
+
* @returns The test ID string extracted from request headers, or configured default if not found
|
|
153
|
+
*
|
|
154
|
+
* @example
|
|
155
|
+
* ```typescript
|
|
156
|
+
* // Route Handler
|
|
157
|
+
* import { getScenaristTestId } from '@scenarist/nextjs-adapter/app';
|
|
158
|
+
*
|
|
159
|
+
* export async function GET(request: Request) {
|
|
160
|
+
* const testId = getScenaristTestId(request);
|
|
161
|
+
* console.log('Processing request for test:', testId);
|
|
162
|
+
* // ...
|
|
163
|
+
* }
|
|
164
|
+
* ```
|
|
165
|
+
*/
|
|
166
|
+
export function getScenaristTestId(req) {
|
|
167
|
+
const scenarist = global.__scenarist_instance;
|
|
168
|
+
if (!scenarist) {
|
|
169
|
+
return FALLBACK_DEFAULT_TEST_ID;
|
|
170
|
+
}
|
|
171
|
+
const defaultTestId = scenarist.config?.defaultTestId ?? FALLBACK_DEFAULT_TEST_ID;
|
|
172
|
+
return req.headers.get(SCENARIST_TEST_ID_HEADER) ?? defaultTestId;
|
|
173
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import type { BaseAdapterOptions, ScenaristAdapter, ScenarioRegistry, ScenarioStore } from '@scenarist/core';
|
|
2
|
+
import { createScenarioEndpoint } from './endpoints.js';
|
|
3
|
+
/**
|
|
4
|
+
* Global state for Next.js App Router adapter.
|
|
5
|
+
*
|
|
6
|
+
* Next.js (Turbopack) creates multiple module instances, causing createScenarist()
|
|
7
|
+
* to be called multiple times. These globals ensure:
|
|
8
|
+
* 1. MSW server.listen() is only called once
|
|
9
|
+
* 2. All instances share the same scenario registry and store
|
|
10
|
+
* 3. The same Scenarist instance is returned when called multiple times
|
|
11
|
+
*
|
|
12
|
+
* IMPORTANT: App Router and Pages Router use separate global keys to enable isolation.
|
|
13
|
+
* This allows a single Next.js application to use both routers simultaneously with
|
|
14
|
+
* independent scenario states. For example, App Router pages can be on scenario A
|
|
15
|
+
* while Pages Router pages are on scenario B, enabling gradual migration patterns.
|
|
16
|
+
*
|
|
17
|
+
* If shared globals were used, switching scenarios in App Router would affect Pages
|
|
18
|
+
* Router and vice versa, breaking test isolation when both routers are present.
|
|
19
|
+
*/
|
|
20
|
+
declare global {
|
|
21
|
+
var __scenarist_msw_started: boolean | undefined;
|
|
22
|
+
var __scenarist_registry: ScenarioRegistry | undefined;
|
|
23
|
+
var __scenarist_store: ScenarioStore | undefined;
|
|
24
|
+
var __scenarist_instance: AppScenarist | undefined;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Next.js App Router adapter options.
|
|
28
|
+
*
|
|
29
|
+
* Extends BaseAdapterOptions to ensure consistency across all adapters.
|
|
30
|
+
*/
|
|
31
|
+
export type AppAdapterOptions = BaseAdapterOptions;
|
|
32
|
+
/**
|
|
33
|
+
* Next.js App Router adapter instance.
|
|
34
|
+
*
|
|
35
|
+
* Provides MSW server lifecycle management and scenario endpoint factory.
|
|
36
|
+
* Unlike Express adapter, doesn't provide middleware (Next.js doesn't have global middleware for App Router).
|
|
37
|
+
*/
|
|
38
|
+
export type AppScenarist = Omit<ScenaristAdapter<never>, 'middleware'> & {
|
|
39
|
+
/**
|
|
40
|
+
* Create scenario endpoint handler for use in app/api/%5F%5Fscenario%5F%5F/route.ts
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```typescript
|
|
44
|
+
* // app/api/%5F%5Fscenario%5F%5F/route.ts
|
|
45
|
+
* import { scenarist } from '@/lib/scenarist';
|
|
46
|
+
*
|
|
47
|
+
* const handler = scenarist?.createScenarioEndpoint();
|
|
48
|
+
* export const POST = handler;
|
|
49
|
+
* export const GET = handler;
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
createScenarioEndpoint: () => ReturnType<typeof createScenarioEndpoint>;
|
|
53
|
+
/**
|
|
54
|
+
* Extract Scenarist infrastructure headers from the request.
|
|
55
|
+
*
|
|
56
|
+
* This helper respects the configured test ID header name and default test ID,
|
|
57
|
+
* ensuring headers are forwarded correctly when making external API calls.
|
|
58
|
+
*
|
|
59
|
+
* Works with Web standard Request objects (App Router, Server Components, Route Handlers).
|
|
60
|
+
*
|
|
61
|
+
* @param req - The Web standard Request object
|
|
62
|
+
* @returns Object with single entry: configured test ID header name → value from request or default
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```typescript
|
|
66
|
+
* // Route Handler
|
|
67
|
+
* export async function GET(request: Request) {
|
|
68
|
+
* const response = await fetch('http://localhost:3001/products', {
|
|
69
|
+
* headers: scenarist.getHeaders(request),
|
|
70
|
+
* });
|
|
71
|
+
* }
|
|
72
|
+
*
|
|
73
|
+
* // Server Component
|
|
74
|
+
* async function ProductsPage() {
|
|
75
|
+
* const response = await fetch('http://localhost:3001/products', {
|
|
76
|
+
* headers: scenarist.getHeaders(request),
|
|
77
|
+
* });
|
|
78
|
+
* }
|
|
79
|
+
* ```
|
|
80
|
+
*/
|
|
81
|
+
getHeaders: (req: Request) => Record<string, string>;
|
|
82
|
+
/**
|
|
83
|
+
* Extract Scenarist infrastructure headers from ReadonlyHeaders.
|
|
84
|
+
*
|
|
85
|
+
* This helper is designed for Next.js Server Components that use headers() from 'next/headers',
|
|
86
|
+
* which returns ReadonlyHeaders (not a Request object).
|
|
87
|
+
*
|
|
88
|
+
* Respects the configured test ID header name and default test ID,
|
|
89
|
+
* ensuring headers are forwarded correctly when making external API calls.
|
|
90
|
+
*
|
|
91
|
+
* @param headers - The ReadonlyHeaders object from headers() in 'next/headers'
|
|
92
|
+
* @returns Object with single entry: configured test ID header name → value from headers or default
|
|
93
|
+
*
|
|
94
|
+
* @example
|
|
95
|
+
* ```typescript
|
|
96
|
+
* // Server Component
|
|
97
|
+
* import { headers } from 'next/headers';
|
|
98
|
+
* import { scenarist } from '@/lib/scenarist';
|
|
99
|
+
*
|
|
100
|
+
* export default async function ProductsPage() {
|
|
101
|
+
* const headersList = await headers();
|
|
102
|
+
*
|
|
103
|
+
* const response = await fetch('http://localhost:3001/products', {
|
|
104
|
+
* headers: {
|
|
105
|
+
* ...scenarist.getHeadersFromReadonlyHeaders(headersList),
|
|
106
|
+
* 'x-user-tier': 'premium',
|
|
107
|
+
* },
|
|
108
|
+
* });
|
|
109
|
+
*
|
|
110
|
+
* const data = await response.json();
|
|
111
|
+
* return <ProductList products={data.products} />;
|
|
112
|
+
* }
|
|
113
|
+
* ```
|
|
114
|
+
*/
|
|
115
|
+
getHeadersFromReadonlyHeaders: (headers: {
|
|
116
|
+
get(name: string): string | null;
|
|
117
|
+
}) => Record<string, string>;
|
|
118
|
+
};
|
|
119
|
+
/**
|
|
120
|
+
* Create a Scenarist instance for Next.js App Router (implementation).
|
|
121
|
+
*
|
|
122
|
+
* This is the actual implementation that wires everything automatically:
|
|
123
|
+
* - MSW server with dynamic handler
|
|
124
|
+
* - Scenario manager
|
|
125
|
+
* - State manager and sequence tracker
|
|
126
|
+
* - Response selector
|
|
127
|
+
*
|
|
128
|
+
* Unlike Express adapter, this doesn't return middleware. Instead, use `createScenarioEndpoint()`
|
|
129
|
+
* to create the handler for your app/api/%5F%5Fscenario%5F%5F/route.ts file.
|
|
130
|
+
*
|
|
131
|
+
* @example
|
|
132
|
+
* ```typescript
|
|
133
|
+
* // lib/scenarist.ts
|
|
134
|
+
* import { createScenarist } from '@scenarist/nextjs-adapter/app';
|
|
135
|
+
* import { defaultScenario } from './scenarios';
|
|
136
|
+
*
|
|
137
|
+
* export const scenarist = createScenarist({
|
|
138
|
+
* enabled: process.env.NODE_ENV === 'development',
|
|
139
|
+
* defaultScenario,
|
|
140
|
+
* });
|
|
141
|
+
*
|
|
142
|
+
* // app/api/%5F%5Fscenario%5F%5F/route.ts
|
|
143
|
+
* const handler = scenarist?.createScenarioEndpoint();
|
|
144
|
+
* export const POST = handler;
|
|
145
|
+
* export const GET = handler;
|
|
146
|
+
*
|
|
147
|
+
* // tests/setup.ts
|
|
148
|
+
* if (scenarist) {
|
|
149
|
+
* beforeAll(() => scenarist.start());
|
|
150
|
+
* afterAll(() => scenarist.stop());
|
|
151
|
+
* }
|
|
152
|
+
* ```
|
|
153
|
+
*/
|
|
154
|
+
export declare const createScenaristImpl: (options: AppAdapterOptions) => AppScenarist;
|
|
155
|
+
//# sourceMappingURL=impl.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"impl.d.ts","sourceRoot":"","sources":["../../src/app/impl.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAG7G,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAExD;;;;;;;;;;;;;;;;GAgBG;AACH,OAAO,CAAC,MAAM,CAAC;IAEb,IAAI,uBAAuB,EAAE,OAAO,GAAG,SAAS,CAAC;IAEjD,IAAI,oBAAoB,EAAE,gBAAgB,GAAG,SAAS,CAAC;IAEvD,IAAI,iBAAiB,EAAE,aAAa,GAAG,SAAS,CAAC;IAEjD,IAAI,oBAAoB,EAAE,YAAY,GAAG,SAAS,CAAC;CACpD;AAED;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,GAAG,kBAAkB,CAAC;AAEnD;;;;;GAKG;AACH,MAAM,MAAM,YAAY,GAAG,IAAI,CAAC,gBAAgB,CAAC,KAAK,CAAC,EAAE,YAAY,CAAC,GAAG;IACvE;;;;;;;;;;;;OAYG;IACH,sBAAsB,EAAE,MAAM,UAAU,CAAC,OAAO,sBAAsB,CAAC,CAAC;IAExE;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACH,UAAU,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAErD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAgCG;IACH,6BAA6B,EAAE,CAAC,OAAO,EAAE;QAAE,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAAA;KAAE,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC1G,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,eAAO,MAAM,mBAAmB,GAAI,SAAS,iBAAiB,KAAG,YAgEhE,CAAC"}
|