@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.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1450 -27
  3. package/dist/app/context.d.ts +19 -0
  4. package/dist/app/context.d.ts.map +1 -0
  5. package/dist/app/context.js +43 -0
  6. package/dist/app/endpoints.d.ts +20 -0
  7. package/dist/app/endpoints.d.ts.map +1 -0
  8. package/dist/app/endpoints.js +84 -0
  9. package/dist/app/helpers.d.ts +152 -0
  10. package/dist/app/helpers.d.ts.map +1 -0
  11. package/dist/app/helpers.js +173 -0
  12. package/dist/app/impl.d.ts +155 -0
  13. package/dist/app/impl.d.ts.map +1 -0
  14. package/dist/app/impl.js +97 -0
  15. package/dist/app/index.d.ts +40 -0
  16. package/dist/app/index.d.ts.map +1 -0
  17. package/dist/app/index.js +38 -0
  18. package/dist/app/production.d.ts +34 -0
  19. package/dist/app/production.d.ts.map +1 -0
  20. package/dist/app/production.js +38 -0
  21. package/dist/app/production.test.d.ts +100 -0
  22. package/dist/app/production.test.d.ts.map +1 -0
  23. package/dist/app/production.test.js +282 -0
  24. package/dist/app/setup.d.ts +29 -0
  25. package/dist/app/setup.d.ts.map +1 -0
  26. package/dist/app/setup.js +27 -0
  27. package/dist/common/create-scenarist-base.d.ts +32 -0
  28. package/dist/common/create-scenarist-base.d.ts.map +1 -0
  29. package/dist/common/create-scenarist-base.js +63 -0
  30. package/dist/common/endpoint-handlers.d.ts +99 -0
  31. package/dist/common/endpoint-handlers.d.ts.map +1 -0
  32. package/dist/common/endpoint-handlers.js +122 -0
  33. package/dist/pages/context.d.ts +17 -0
  34. package/dist/pages/context.d.ts.map +1 -0
  35. package/dist/pages/context.js +41 -0
  36. package/dist/pages/endpoints.d.ts +20 -0
  37. package/dist/pages/endpoints.d.ts.map +1 -0
  38. package/dist/pages/endpoints.js +84 -0
  39. package/dist/pages/helpers.d.ts +56 -0
  40. package/dist/pages/helpers.d.ts.map +1 -0
  41. package/dist/pages/helpers.js +49 -0
  42. package/dist/pages/impl.d.ts +124 -0
  43. package/dist/pages/impl.d.ts.map +1 -0
  44. package/dist/pages/impl.js +91 -0
  45. package/dist/pages/index.d.ts +37 -0
  46. package/dist/pages/index.d.ts.map +1 -0
  47. package/dist/pages/index.js +35 -0
  48. package/dist/pages/production.d.ts +18 -0
  49. package/dist/pages/production.d.ts.map +1 -0
  50. package/dist/pages/production.js +20 -0
  51. package/dist/pages/production.test.d.ts +119 -0
  52. package/dist/pages/production.test.d.ts.map +1 -0
  53. package/dist/pages/production.test.js +326 -0
  54. package/dist/pages/setup.d.ts +29 -0
  55. package/dist/pages/setup.d.ts.map +1 -0
  56. package/dist/pages/setup.js +27 -0
  57. package/package.json +86 -7
@@ -0,0 +1,326 @@
1
+ /**
2
+ * Production Entry Point Tests - Next.js Pages Router Adapter
3
+ *
4
+ * These tests verify the production stub implementations that enable tree-shaking
5
+ * of Scenarist from production builds.
6
+ *
7
+ * ## How Next.js Conditional Exports Work
8
+ *
9
+ * Next.js respects Node.js conditional exports (package.json "exports" field).
10
+ * When NODE_ENV=production, Next.js uses the "production" export path instead
11
+ * of the default export.
12
+ *
13
+ * Example from package.json:
14
+ * ```json
15
+ * {
16
+ * "exports": {
17
+ * "./pages": {
18
+ * "production": "./dist/pages/production.js",
19
+ * "default": "./dist/pages/index.js"
20
+ * }
21
+ * }
22
+ * }
23
+ * ```
24
+ *
25
+ * This means:
26
+ * - In development/test: `import { createScenarist } from '@scenarist/nextjs-adapter/pages'`
27
+ * resolves to `dist/pages/index.js` (full Scenarist implementation)
28
+ * - In production: Same import resolves to `dist/pages/production.js` (stubs only)
29
+ *
30
+ * ## Why This Achieves Tree-Shaking
31
+ *
32
+ * Because production.js:
33
+ * 1. Does NOT import from @scenarist/core or @scenarist/msw-adapter
34
+ * 2. Does NOT import from 'msw'
35
+ * 3. Only exports stub functions with zero dependencies
36
+ *
37
+ * Result: Bundlers like Next.js/Webpack can completely eliminate:
38
+ * - All MSW code (~50kb)
39
+ * - All Scenarist core logic
40
+ * - All scenario definitions
41
+ * - All test infrastructure
42
+ *
43
+ * Final production bundle: 0kb overhead from Scenarist
44
+ *
45
+ * ## Why Stubs Return Safe Defaults
46
+ *
47
+ * Application code can import and use Scenarist helpers without guards:
48
+ *
49
+ * ```typescript
50
+ * // API Route - works in ALL environments
51
+ * import { getScenaristHeaders } from '@scenarist/nextjs-adapter/pages';
52
+ * import type { NextApiRequest, NextApiResponse } from 'next';
53
+ *
54
+ * export default async function handler(req: NextApiRequest, res: NextApiResponse) {
55
+ * const response = await fetch('http://api.example.com/data', {
56
+ * headers: {
57
+ * ...getScenaristHeaders(req), // ✅ Safe: {} in production
58
+ * 'x-api-key': 'abc123',
59
+ * },
60
+ * });
61
+ *
62
+ * res.json(await response.json());
63
+ * }
64
+ * ```
65
+ *
66
+ * In production, `getScenaristHeaders()` returns `{}`, so spreading it is a no-op.
67
+ * No runtime errors, no guards needed, same code everywhere.
68
+ *
69
+ * ## Pages Router vs App Router
70
+ *
71
+ * The Pages Router adapter has simpler helper functions than App Router because:
72
+ * - Pages Router only has API Routes (no Server Components)
73
+ * - API Routes use NextApiRequest (not Web Request or ReadonlyHeaders)
74
+ * - Only one helper needed: getScenaristHeaders(req: NextApiRequest)
75
+ *
76
+ * App Router needs more helpers to support:
77
+ * - Route Handlers (Web Request API)
78
+ * - Server Components (ReadonlyHeaders from next/headers)
79
+ * - Both getHeaders() and getTestId() variants for each context
80
+ *
81
+ * ## Related Documentation
82
+ *
83
+ * **Core Feature (Node.js Conditional Exports):**
84
+ * - https://nodejs.org/api/packages.html#conditional-exports
85
+ * Defines how package.json "exports" field works with conditions like "production"
86
+ * - https://nodejs.org/api/packages.html#exports
87
+ * Complete specification for package.json exports field
88
+ *
89
+ * **Next.js Build Optimizations:**
90
+ * - https://nextjs.org/blog/next-14-2
91
+ * Next.js 14.2 tree-shaking improvements (see "Improved Tree Shaking" section)
92
+ * - https://nextjs.org/docs/app/guides/package-bundling
93
+ * Next.js package bundling and optimization strategies
94
+ *
95
+ * **Next.js Pages Router:**
96
+ * - https://nextjs.org/docs/pages/building-your-application/routing/api-routes
97
+ * Pages Router API route handler pattern (NextApiRequest/NextApiResponse)
98
+ *
99
+ * **Bundler Documentation:**
100
+ * - https://webpack.js.org/configuration/mode/#mode-production
101
+ * Webpack production mode (sets NODE_ENV=production, enables conditional exports)
102
+ * - https://turbo.build/pack/docs
103
+ * Turbopack (Next.js's new bundler, also respects conditional exports)
104
+ *
105
+ * **Note:** Next.js doesn't document conditional exports specifically because it's a
106
+ * Node.js feature that Next.js (via Webpack/Turbopack) automatically respects during
107
+ * production builds. The key is that NODE_ENV=production triggers the "production"
108
+ * export path in package.json.
109
+ *
110
+ * ## Testing Strategy
111
+ *
112
+ * These tests verify:
113
+ * 1. All stub functions return safe, expected defaults
114
+ * 2. createScenarist returns undefined (no Scenarist instance in production)
115
+ * 3. Helper functions can be called without errors
116
+ * 4. No imports from test dependencies (tree-shaking verification)
117
+ */
118
+ import { describe, it, expect } from 'vitest';
119
+ import * as production from './production.js';
120
+ describe('Pages Router production entry point', () => {
121
+ describe('createScenarist', () => {
122
+ it('should return undefined (Scenarist disabled in production)', () => {
123
+ // In production builds, Scenarist should not exist at all
124
+ // API routes check: if (scenarist) { return scenarist.createScenarioEndpoint() }
125
+ const scenarist = production.createScenarist({
126
+ enabled: true,
127
+ scenarios: {
128
+ test: {
129
+ id: 'test',
130
+ name: 'Test Scenario',
131
+ description: 'A test scenario',
132
+ mocks: [],
133
+ },
134
+ },
135
+ });
136
+ expect(scenarist).toBeUndefined();
137
+ });
138
+ it('should accept same options as development version (type safety)', () => {
139
+ // This ensures the production stub has the same TypeScript signature
140
+ // as the real implementation, preventing type errors in user code
141
+ const scenarist = production.createScenarist({
142
+ enabled: false,
143
+ scenarios: {
144
+ default: {
145
+ id: 'default',
146
+ name: 'Default Scenario',
147
+ description: 'Default test scenario',
148
+ mocks: [],
149
+ },
150
+ },
151
+ defaultTestId: 'test-123',
152
+ });
153
+ expect(scenarist).toBeUndefined();
154
+ });
155
+ });
156
+ describe('getScenaristHeaders', () => {
157
+ it('should return empty object (no test headers in production)', () => {
158
+ const mockRequest = {
159
+ headers: {
160
+ 'x-scenarist-test-id': 'test-123',
161
+ 'x-user-id': 'user-456',
162
+ },
163
+ method: 'GET',
164
+ url: '/api/test',
165
+ };
166
+ const headers = production.getScenaristHeaders(mockRequest);
167
+ // Production: No test infrastructure headers added
168
+ expect(headers).toEqual({});
169
+ expect(Object.keys(headers)).toHaveLength(0);
170
+ });
171
+ it('should be safe to spread in fetch headers', () => {
172
+ const mockRequest = {
173
+ headers: {},
174
+ method: 'GET',
175
+ url: '/api/test',
176
+ };
177
+ const headers = production.getScenaristHeaders(mockRequest);
178
+ // This pattern works in all environments without guards
179
+ const fetchHeaders = {
180
+ 'content-type': 'application/json',
181
+ ...headers, // Spreading {} is a no-op
182
+ };
183
+ expect(fetchHeaders).toEqual({
184
+ 'content-type': 'application/json',
185
+ });
186
+ });
187
+ it('should ignore NextApiRequest properties in production', () => {
188
+ const mockRequest = {
189
+ headers: {
190
+ 'x-scenarist-test-id': 'test-abc',
191
+ 'x-scenario': 'premium',
192
+ },
193
+ method: 'POST',
194
+ url: '/api/cart/add',
195
+ body: { item: 'product-1' },
196
+ };
197
+ const headers = production.getScenaristHeaders(mockRequest);
198
+ // Production stub doesn't read request properties, just returns {}
199
+ expect(headers).toEqual({});
200
+ });
201
+ });
202
+ describe('tree-shaking verification', () => {
203
+ it('should export only stub functions with no test dependencies', () => {
204
+ // Verify all expected exports exist
205
+ expect(production.createScenarist).toBeDefined();
206
+ expect(production.getScenaristHeaders).toBeDefined();
207
+ // Verify stubs are simple functions (not complex objects)
208
+ expect(typeof production.createScenarist).toBe('function');
209
+ expect(typeof production.getScenaristHeaders).toBe('function');
210
+ });
211
+ it('should not have any Scenarist instance methods', () => {
212
+ const scenarist = production.createScenarist({
213
+ enabled: true,
214
+ scenarios: {
215
+ default: {
216
+ id: 'default',
217
+ name: 'Default',
218
+ description: 'Default scenario',
219
+ mocks: [],
220
+ },
221
+ },
222
+ });
223
+ // Production stub returns undefined, not a Scenarist instance
224
+ expect(scenarist).toBeUndefined();
225
+ // These methods exist in development but NOT in production
226
+ // Optional chaining prevents errors when accessing properties on undefined
227
+ expect(scenarist?.start).toBeUndefined();
228
+ expect(scenarist?.stop).toBeUndefined();
229
+ expect(scenarist?.createScenarioEndpoint).toBeUndefined();
230
+ });
231
+ it('should have fewer exports than App Router (simpler API surface)', () => {
232
+ const exports = Object.keys(production);
233
+ // Pages Router only needs:
234
+ // - createScenarist
235
+ // - getScenaristHeaders
236
+ // (No ReadonlyHeaders variants, no getTestId variants)
237
+ expect(exports).toContain('createScenarist');
238
+ expect(exports).toContain('getScenaristHeaders');
239
+ // App Router has these additional exports:
240
+ // - getScenaristHeadersFromReadonlyHeaders
241
+ // - getScenaristTestId
242
+ // - getScenaristTestIdFromReadonlyHeaders
243
+ expect(exports).not.toContain('getScenaristHeadersFromReadonlyHeaders');
244
+ expect(exports).not.toContain('getScenaristTestId');
245
+ expect(exports).not.toContain('getScenaristTestIdFromReadonlyHeaders');
246
+ });
247
+ });
248
+ describe('production safety', () => {
249
+ it('should handle being called multiple times without errors', () => {
250
+ // Production code might call these helpers frequently
251
+ const mockRequest = {
252
+ headers: {},
253
+ method: 'GET',
254
+ url: '/api/test',
255
+ };
256
+ expect(() => {
257
+ for (let i = 0; i < 100; i++) {
258
+ production.getScenaristHeaders(mockRequest);
259
+ }
260
+ }).not.toThrow();
261
+ });
262
+ it('should return consistent results for same inputs', () => {
263
+ const mockRequest = {
264
+ headers: { 'x-scenarist-test-id': 'test-123' },
265
+ method: 'GET',
266
+ url: '/api/test',
267
+ };
268
+ const headers1 = production.getScenaristHeaders(mockRequest);
269
+ const headers2 = production.getScenaristHeaders(mockRequest);
270
+ expect(headers1).toEqual(headers2);
271
+ });
272
+ it('should work with various NextApiRequest shapes', () => {
273
+ // Different request shapes should all work safely
274
+ const requests = [
275
+ { headers: {}, method: 'GET', url: '/' },
276
+ { headers: { 'x-scenarist-test-id': 'abc' }, method: 'POST', url: '/api/test' },
277
+ { headers: { 'x-custom': 'value' }, method: 'PUT', url: '/api/update' },
278
+ ];
279
+ requests.forEach((req) => {
280
+ expect(production.getScenaristHeaders(req)).toEqual({});
281
+ });
282
+ });
283
+ });
284
+ describe('Pages Router specific behavior', () => {
285
+ it('should be compatible with Pages Router API route pattern', () => {
286
+ // Typical Pages Router API route usage
287
+ const mockRequest = {
288
+ headers: {
289
+ 'content-type': 'application/json',
290
+ },
291
+ method: 'POST',
292
+ url: '/api/cart/add',
293
+ body: { productId: 1 },
294
+ };
295
+ const scenaristHeaders = production.getScenaristHeaders(mockRequest);
296
+ // In production, this should be a no-op
297
+ const requestHeaders = {
298
+ 'content-type': 'application/json',
299
+ ...scenaristHeaders,
300
+ };
301
+ expect(requestHeaders).toEqual({
302
+ 'content-type': 'application/json',
303
+ });
304
+ });
305
+ it('should not interfere with existing headers', () => {
306
+ const mockRequest = {
307
+ headers: {
308
+ authorization: 'Bearer token123',
309
+ 'x-api-key': 'secret',
310
+ },
311
+ method: 'GET',
312
+ url: '/api/protected',
313
+ };
314
+ const scenaristHeaders = production.getScenaristHeaders(mockRequest);
315
+ const allHeaders = {
316
+ ...mockRequest.headers,
317
+ ...scenaristHeaders,
318
+ };
319
+ // Production stub shouldn't modify or remove existing headers
320
+ expect(allHeaders).toEqual({
321
+ authorization: 'Bearer token123',
322
+ 'x-api-key': 'secret',
323
+ });
324
+ });
325
+ });
326
+ });
@@ -0,0 +1,29 @@
1
+ export type { PagesAdapterOptions, PagesScenarist } from './impl.js';
2
+ /**
3
+ * Create a Scenarist instance for Next.js Pages Router.
4
+ *
5
+ * Production tree-shaking is handled via conditional exports in package.json:
6
+ * - Development/test: Uses this file (imports impl.js with full MSW setup)
7
+ * - Production builds: Uses production.js (returns undefined, zero imports)
8
+ *
9
+ * This ensures all test code is eliminated from production bundles.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * // lib/scenarist.ts
14
+ * import { createScenarist } from '@scenarist/nextjs-adapter/pages';
15
+ * import { scenarios } from './scenarios';
16
+ *
17
+ * export const scenarist = createScenarist({
18
+ * enabled: true,
19
+ * scenarios,
20
+ * });
21
+ *
22
+ * // Start MSW in Node.js environment
23
+ * if (typeof window === 'undefined') {
24
+ * scenarist.start();
25
+ * }
26
+ * ```
27
+ */
28
+ export { createScenaristImpl as createScenarist } from './impl.js';
29
+ //# sourceMappingURL=setup.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup.d.ts","sourceRoot":"","sources":["../../src/pages/setup.ts"],"names":[],"mappings":"AACA,YAAY,EAAE,mBAAmB,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAErE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,OAAO,EAAE,mBAAmB,IAAI,eAAe,EAAE,MAAM,WAAW,CAAC"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Create a Scenarist instance for Next.js Pages 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/pages';
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';
package/package.json CHANGED
@@ -1,10 +1,89 @@
1
1
  {
2
2
  "name": "@scenarist/nextjs-adapter",
3
- "version": "0.0.1",
4
- "description": "OIDC trusted publishing setup package for @scenarist/nextjs-adapter",
3
+ "version": "0.1.1",
4
+ "description": "Next.js adapter for Scenarist (Pages Router and App Router)",
5
+ "author": "Paul Hammond (citypaul) <paul@packsoftware.co.uk>",
6
+ "license": "MIT",
7
+ "homepage": "https://github.com/citypaul/scenarist#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/citypaul/scenarist.git",
11
+ "directory": "packages/nextjs-adapter"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/citypaul/scenarist/issues"
15
+ },
5
16
  "keywords": [
6
- "oidc",
7
- "trusted-publishing",
8
- "setup"
9
- ]
10
- }
17
+ "nextjs",
18
+ "next",
19
+ "app-router",
20
+ "pages-router",
21
+ "react-server-components",
22
+ "msw",
23
+ "testing",
24
+ "scenario-testing",
25
+ "mock-service-worker",
26
+ "integration-testing",
27
+ "e2e-testing",
28
+ "typescript"
29
+ ],
30
+ "engines": {
31
+ "node": ">=18.0.0"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "type": "module",
37
+ "main": "./dist/index.js",
38
+ "types": "./dist/index.d.ts",
39
+ "exports": {
40
+ ".": {
41
+ "types": "./dist/index.d.ts",
42
+ "import": "./dist/index.js"
43
+ },
44
+ "./pages": {
45
+ "types": "./dist/pages/index.d.ts",
46
+ "production": "./dist/pages/production.js",
47
+ "import": "./dist/pages/index.js"
48
+ },
49
+ "./app": {
50
+ "types": "./dist/app/index.d.ts",
51
+ "production": "./dist/app/production.js",
52
+ "import": "./dist/app/index.js"
53
+ }
54
+ },
55
+ "files": [
56
+ "dist",
57
+ "README.md",
58
+ "LICENSE"
59
+ ],
60
+ "dependencies": {
61
+ "zod": "^4.1.12",
62
+ "@scenarist/core": "0.0.1",
63
+ "@scenarist/msw-adapter": "0.0.1"
64
+ },
65
+ "peerDependencies": {
66
+ "msw": "^2.0.0",
67
+ "next": "^14.0.0 || ^15.0.0"
68
+ },
69
+ "devDependencies": {
70
+ "@types/node": "^24.10.1",
71
+ "@vitest/coverage-v8": "^4.0.8",
72
+ "eslint": "^9.39.1",
73
+ "msw": "^2.12.1",
74
+ "next": "^14.0.0",
75
+ "typescript": "^5.9.3",
76
+ "vitest": "^4.0.8",
77
+ "@scenarist/eslint-config": "^0.0.0",
78
+ "@scenarist/typescript-config": "0.0.0"
79
+ },
80
+ "scripts": {
81
+ "build": "tsc",
82
+ "dev": "tsc --watch",
83
+ "test": "vitest run",
84
+ "test:watch": "vitest",
85
+ "typecheck": "tsc --project tsconfig.typecheck.json --noEmit",
86
+ "lint": "eslint .",
87
+ "clean": "rm -rf dist"
88
+ }
89
+ }