@go-go-scope/adapter-nextjs 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 thelinuxlich (Alisson Cavalcante Agiani)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,229 @@
1
+ import { Scope } from 'go-go-scope';
2
+
3
+ /**
4
+ * Next.js adapter for go-go-scope
5
+ *
6
+ * Provides structured concurrency for Next.js API routes, Edge functions,
7
+ * and Server Components with automatic cleanup.
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * // API Route (app/api/users/route.ts)
12
+ * import { withScope } from '@go-go-scope/adapter-nextjs'
13
+ *
14
+ * export const GET = withScope(async (req, ctx) => {
15
+ * const [err, users] = await ctx.scope.task(() => fetchUsers())
16
+ * if (err) return Response.json({ error: err.message }, { status: 500 })
17
+ * return Response.json(users)
18
+ * })
19
+ * ```
20
+ */
21
+
22
+ interface NextRequest extends Request {
23
+ cookies: {
24
+ get(name: string): {
25
+ name: string;
26
+ value: string;
27
+ } | undefined;
28
+ getAll(): {
29
+ name: string;
30
+ value: string;
31
+ }[];
32
+ has(name: string): boolean;
33
+ };
34
+ nextUrl: {
35
+ pathname: string;
36
+ search: string;
37
+ };
38
+ ip?: string;
39
+ geo?: {
40
+ city?: string;
41
+ country?: string;
42
+ region?: string;
43
+ };
44
+ }
45
+ declare global {
46
+ namespace JSX {
47
+ interface Element {
48
+ }
49
+ interface IntrinsicElements {
50
+ }
51
+ }
52
+ }
53
+ /**
54
+ * Context passed to Next.js route handlers
55
+ */
56
+ interface NextJSContext<T extends Record<string, unknown> = Record<string, never>> {
57
+ /** The scope for this request */
58
+ scope: Scope<T>;
59
+ /** Request signal for cancellation */
60
+ signal: AbortSignal;
61
+ }
62
+ /**
63
+ * API Route handler with scope
64
+ */
65
+ type APIRouteHandler<T extends Record<string, unknown> = Record<string, never>> = (req: NextRequest, context: NextJSContext<T>) => Promise<Response> | Response;
66
+ /**
67
+ * Edge Route handler with scope
68
+ */
69
+ type EdgeRouteHandler<T extends Record<string, unknown> = Record<string, never>> = (req: Request, context: NextJSContext<T>) => Promise<Response> | Response;
70
+ /**
71
+ * Options for withScope wrapper
72
+ */
73
+ interface WithScopeOptions<T extends Record<string, unknown> = Record<string, never>> {
74
+ /** Scope timeout in milliseconds */
75
+ timeout?: number;
76
+ /** Initial services to provide */
77
+ services?: T;
78
+ /** Enable request tracing */
79
+ trace?: boolean;
80
+ /** Error handler for uncaught errors */
81
+ onError?: (error: unknown, req: NextRequest) => Response | Promise<Response>;
82
+ }
83
+ /**
84
+ * Wrap a Next.js API route handler with a scope
85
+ *
86
+ * @example
87
+ * ```typescript
88
+ * // app/api/users/route.ts
89
+ * import { withScope } from '@go-go-scope/adapter-nextjs'
90
+ *
91
+ * export const GET = withScope(async (req, { scope }) => {
92
+ * const [err, users] = await scope.task(() => db.query('SELECT * FROM users'))
93
+ * if (err) return Response.json({ error: err.message }, { status: 500 })
94
+ * return Response.json(users)
95
+ * })
96
+ *
97
+ * // With custom options
98
+ * export const POST = withScope(
99
+ * async (req, { scope }) => {
100
+ * const [err, result] = await scope.task(() => createUser(req))
101
+ * if (err) return Response.json({ error: err.message }, { status: 400 })
102
+ * return Response.json(result, { status: 201 })
103
+ * },
104
+ * { timeout: 5000 }
105
+ * )
106
+ * ```
107
+ */
108
+ declare function withScope<T extends Record<string, unknown> = Record<string, never>>(handler: APIRouteHandler<T>, options?: WithScopeOptions<T>): (req: NextRequest) => Promise<Response>;
109
+ /**
110
+ * Wrap a Next.js Edge route handler with a scope
111
+ *
112
+ * @example
113
+ * ```typescript
114
+ * // middleware.ts or edge route
115
+ * import { withScopeEdge } from '@go-go-scope/adapter-nextjs'
116
+ *
117
+ * export const config = {
118
+ * runtime: 'edge',
119
+ * }
120
+ *
121
+ * export default withScopeEdge(async (req, { scope }) => {
122
+ * const [err, result] = await scope.task(() => fetchEdgeData())
123
+ * if (err) return new Response('Error', { status: 500 })
124
+ * return new Response(JSON.stringify(result))
125
+ * })
126
+ * ```
127
+ */
128
+ declare function withScopeEdge<T extends Record<string, unknown> = Record<string, never>>(handler: EdgeRouteHandler<T>, options?: WithScopeOptions<T>): (req: Request) => Promise<Response>;
129
+ /**
130
+ * Server Component wrapper with scope
131
+ *
132
+ * @example
133
+ * ```typescript
134
+ * // app/users/page.tsx
135
+ * import { withScopeServer } from '@go-go-scope/adapter-nextjs'
136
+ *
137
+ * export default withScopeServer(async (searchParams, { scope }) => {
138
+ * const [err, users] = await scope.task(() => fetchUsers())
139
+ * if (err) return <Error message={err.message} />
140
+ * return <UserList users={users} />
141
+ * })
142
+ * ```
143
+ */
144
+ declare function withScopeServer<T extends Record<string, unknown> = Record<string, never>, Props extends Record<string, unknown> = Record<string, never>>(component: (props: Props, context: NextJSContext<T>) => Promise<JSX.Element> | JSX.Element, options?: WithScopeOptions<T>): (props: Props) => Promise<JSX.Element>;
145
+ /**
146
+ * Middleware wrapper with scope
147
+ *
148
+ * @example
149
+ * ```typescript
150
+ * // middleware.ts
151
+ * import { withScopeMiddleware } from '@go-go-scope/adapter-nextjs'
152
+ * import { NextResponse } from 'next/server'
153
+ *
154
+ * export default withScopeMiddleware(async (req, { scope }) => {
155
+ * const [err, session] = await scope.task(() => validateSession(req))
156
+ * if (err || !session) {
157
+ * return NextResponse.redirect(new URL('/login', req.url))
158
+ * }
159
+ * return NextResponse.next()
160
+ * })
161
+ * ```
162
+ */
163
+ declare function withScopeMiddleware<T extends Record<string, unknown> = Record<string, never>>(handler: (req: NextRequest, context: NextJSContext<T>) => Promise<Response> | Response, options?: WithScopeOptions<T>): (req: NextRequest) => Promise<Response>;
164
+ /**
165
+ * Higher-order function for route handlers with dependency injection
166
+ *
167
+ * @example
168
+ * ```typescript
169
+ * // With dependency injection
170
+ * const handler = withScopeAndServices(
171
+ * { db: createDatabase() },
172
+ * async (req, { scope }) => {
173
+ * const db = scope.use('db')
174
+ * const [err, users] = await scope.task(() => db.query('SELECT * FROM users'))
175
+ * return Response.json(users)
176
+ * }
177
+ * )
178
+ * ```
179
+ */
180
+ declare function withScopeAndServices<T extends Record<string, unknown>>(services: T, handler: APIRouteHandler<T>, options?: Omit<WithScopeOptions<T>, "services">): (req: NextRequest) => Promise<Response>;
181
+ /**
182
+ * Create a reusable scope configuration for API routes
183
+ *
184
+ * @example
185
+ * ```typescript
186
+ * // lib/scope.ts
187
+ * import { createRouteConfig } from '@go-go-scope/adapter-nextjs'
188
+ * import { createDatabase } from './db'
189
+ *
190
+ * export const routeConfig = createRouteConfig({
191
+ * timeout: 10000,
192
+ * services: { db: createDatabase() },
193
+ * onError: (err) => Response.json({ error: err.message }, { status: 500 })
194
+ * })
195
+ *
196
+ * // app/api/users/route.ts
197
+ * import { routeConfig } from '@/lib/scope'
198
+ *
199
+ * export const GET = routeConfig.wrap(async (req, { scope }) => {
200
+ * const db = scope.use('db')
201
+ * // ...
202
+ * })
203
+ * ```
204
+ */
205
+ declare function createRouteConfig<T extends Record<string, unknown>>(config: WithScopeOptions<T>): {
206
+ wrap: (handler: APIRouteHandler<T>) => (req: NextRequest) => Promise<Response>;
207
+ wrapEdge: (handler: EdgeRouteHandler<T>) => (req: Request) => Promise<Response>;
208
+ wrapServer: <Props extends Record<string, unknown>>(component: (props: Props, context: NextJSContext<T>) => Promise<JSX.Element> | JSX.Element) => (props: Props) => Promise<JSX.Element>;
209
+ };
210
+ /**
211
+ * Error classes for Next.js adapter
212
+ */
213
+ declare class NextJSRouteError extends Error {
214
+ readonly statusCode: number;
215
+ readonly code?: string | undefined;
216
+ constructor(message: string, statusCode?: number, code?: string | undefined);
217
+ }
218
+ /**
219
+ * Helper to create typed error responses
220
+ */
221
+ declare function errorResponse(error: unknown, statusCode?: number): Response;
222
+ /**
223
+ * Helper to create success responses with proper typing
224
+ */
225
+ declare function jsonResponse<T>(data: T, statusCode?: number): Response;
226
+
227
+ export { NextJSRouteError, createRouteConfig, errorResponse, jsonResponse, withScope, withScopeAndServices, withScopeEdge, withScopeMiddleware, withScopeServer };
228
+ export type { APIRouteHandler, EdgeRouteHandler, NextJSContext, NextRequest, WithScopeOptions };
229
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","sources":["../src/index.ts"],"mappings":";;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;GACG;;UAKc,WAAY,SAAQ,OAAO;IAC3C,OAAO,EAAE;QACR,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,KAAK,EAAE,MAAM,CAAA;SAAE,GAAG,SAAS,CAAC;QAC/D,MAAM,IAAI;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,KAAK,EAAE,MAAM,CAAA;SAAE,EAAE,CAAC;QAC5C,GAAG,C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CAAC,QAAQ,CAAC,CAEzC;AAED;AAtJA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;GAwJG;iBACa,iBAAiB,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClE,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAC;oBAGV,eAAe,CAAC,CAAC,CAAC,WA1O3B,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC;wBA2OpB,gBAAgB,CAAC,CAAC,CAAC,WAnLhC,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC;iBAoLvB,KAAK,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,aACtC,CACV,KAAK,EAAE,KAAK,EACZ,OAAO,EAAE,aAAa,CAAC,CAAC,CAAC,KACrB,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,GAAG,CAAC,OAAO,uBApHrB,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC;EAuHxC;AAED;AAhKA;GAkKG;cACU,gBAAiB,SAAQ,KAAK;aAGzB,UAAU,EAAE,MAAM;aAClB,IAAI,CAAC,EAAE,MAAM;gBAF7B,OAAO,EAAE,MAAM,EACC,UAAU,GAAE,MAAY,EACxB,IAAI,CAAC,EAAE,MAAM,YAAA;CAK9B;AAED;AAtKA;GAwKG;iBACa,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE,UAAU,SAAM,GAAG,QAAQ,CAUxE;AAED;AAjLA;GAmLG;iBACa,YAAY,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,UAAU,SAAM,GAAG,QAAQ,CAEnE;;;;","names":[]}
@@ -0,0 +1,224 @@
1
+ /**
2
+ * Next.js adapter for go-go-scope
3
+ *
4
+ * Provides structured concurrency for Next.js API routes, Edge functions,
5
+ * and Server Components with automatic cleanup.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * // API Route (app/api/users/route.ts)
10
+ * import { withScope } from '@go-go-scope/adapter-nextjs'
11
+ *
12
+ * export const GET = withScope(async (req, ctx) => {
13
+ * const [err, users] = await ctx.scope.task(() => fetchUsers())
14
+ * if (err) return Response.json({ error: err.message }, { status: 500 })
15
+ * return Response.json(users)
16
+ * })
17
+ * ```
18
+ */
19
+ import { type Scope } from "go-go-scope";
20
+ export interface NextRequest extends Request {
21
+ cookies: {
22
+ get(name: string): {
23
+ name: string;
24
+ value: string;
25
+ } | undefined;
26
+ getAll(): {
27
+ name: string;
28
+ value: string;
29
+ }[];
30
+ has(name: string): boolean;
31
+ };
32
+ nextUrl: {
33
+ pathname: string;
34
+ search: string;
35
+ };
36
+ ip?: string;
37
+ geo?: {
38
+ city?: string;
39
+ country?: string;
40
+ region?: string;
41
+ };
42
+ }
43
+ declare global {
44
+ namespace JSX {
45
+ interface Element {
46
+ }
47
+ interface IntrinsicElements {
48
+ }
49
+ }
50
+ }
51
+ /**
52
+ * Context passed to Next.js route handlers
53
+ */
54
+ export interface NextJSContext<T extends Record<string, unknown> = Record<string, never>> {
55
+ /** The scope for this request */
56
+ scope: Scope<T>;
57
+ /** Request signal for cancellation */
58
+ signal: AbortSignal;
59
+ }
60
+ /**
61
+ * API Route handler with scope
62
+ */
63
+ export type APIRouteHandler<T extends Record<string, unknown> = Record<string, never>> = (req: NextRequest, context: NextJSContext<T>) => Promise<Response> | Response;
64
+ /**
65
+ * Edge Route handler with scope
66
+ */
67
+ export type EdgeRouteHandler<T extends Record<string, unknown> = Record<string, never>> = (req: Request, context: NextJSContext<T>) => Promise<Response> | Response;
68
+ /**
69
+ * Options for withScope wrapper
70
+ */
71
+ export interface WithScopeOptions<T extends Record<string, unknown> = Record<string, never>> {
72
+ /** Scope timeout in milliseconds */
73
+ timeout?: number;
74
+ /** Initial services to provide */
75
+ services?: T;
76
+ /** Enable request tracing */
77
+ trace?: boolean;
78
+ /** Error handler for uncaught errors */
79
+ onError?: (error: unknown, req: NextRequest) => Response | Promise<Response>;
80
+ }
81
+ /**
82
+ * Wrap a Next.js API route handler with a scope
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * // app/api/users/route.ts
87
+ * import { withScope } from '@go-go-scope/adapter-nextjs'
88
+ *
89
+ * export const GET = withScope(async (req, { scope }) => {
90
+ * const [err, users] = await scope.task(() => db.query('SELECT * FROM users'))
91
+ * if (err) return Response.json({ error: err.message }, { status: 500 })
92
+ * return Response.json(users)
93
+ * })
94
+ *
95
+ * // With custom options
96
+ * export const POST = withScope(
97
+ * async (req, { scope }) => {
98
+ * const [err, result] = await scope.task(() => createUser(req))
99
+ * if (err) return Response.json({ error: err.message }, { status: 400 })
100
+ * return Response.json(result, { status: 201 })
101
+ * },
102
+ * { timeout: 5000 }
103
+ * )
104
+ * ```
105
+ */
106
+ export declare function withScope<T extends Record<string, unknown> = Record<string, never>>(handler: APIRouteHandler<T>, options?: WithScopeOptions<T>): (req: NextRequest) => Promise<Response>;
107
+ /**
108
+ * Wrap a Next.js Edge route handler with a scope
109
+ *
110
+ * @example
111
+ * ```typescript
112
+ * // middleware.ts or edge route
113
+ * import { withScopeEdge } from '@go-go-scope/adapter-nextjs'
114
+ *
115
+ * export const config = {
116
+ * runtime: 'edge',
117
+ * }
118
+ *
119
+ * export default withScopeEdge(async (req, { scope }) => {
120
+ * const [err, result] = await scope.task(() => fetchEdgeData())
121
+ * if (err) return new Response('Error', { status: 500 })
122
+ * return new Response(JSON.stringify(result))
123
+ * })
124
+ * ```
125
+ */
126
+ export declare function withScopeEdge<T extends Record<string, unknown> = Record<string, never>>(handler: EdgeRouteHandler<T>, options?: WithScopeOptions<T>): (req: Request) => Promise<Response>;
127
+ /**
128
+ * Server Component wrapper with scope
129
+ *
130
+ * @example
131
+ * ```typescript
132
+ * // app/users/page.tsx
133
+ * import { withScopeServer } from '@go-go-scope/adapter-nextjs'
134
+ *
135
+ * export default withScopeServer(async (searchParams, { scope }) => {
136
+ * const [err, users] = await scope.task(() => fetchUsers())
137
+ * if (err) return <Error message={err.message} />
138
+ * return <UserList users={users} />
139
+ * })
140
+ * ```
141
+ */
142
+ export declare function withScopeServer<T extends Record<string, unknown> = Record<string, never>, Props extends Record<string, unknown> = Record<string, never>>(component: (props: Props, context: NextJSContext<T>) => Promise<JSX.Element> | JSX.Element, options?: WithScopeOptions<T>): (props: Props) => Promise<JSX.Element>;
143
+ /**
144
+ * Middleware wrapper with scope
145
+ *
146
+ * @example
147
+ * ```typescript
148
+ * // middleware.ts
149
+ * import { withScopeMiddleware } from '@go-go-scope/adapter-nextjs'
150
+ * import { NextResponse } from 'next/server'
151
+ *
152
+ * export default withScopeMiddleware(async (req, { scope }) => {
153
+ * const [err, session] = await scope.task(() => validateSession(req))
154
+ * if (err || !session) {
155
+ * return NextResponse.redirect(new URL('/login', req.url))
156
+ * }
157
+ * return NextResponse.next()
158
+ * })
159
+ * ```
160
+ */
161
+ export declare function withScopeMiddleware<T extends Record<string, unknown> = Record<string, never>>(handler: (req: NextRequest, context: NextJSContext<T>) => Promise<Response> | Response, options?: WithScopeOptions<T>): (req: NextRequest) => Promise<Response>;
162
+ /**
163
+ * Higher-order function for route handlers with dependency injection
164
+ *
165
+ * @example
166
+ * ```typescript
167
+ * // With dependency injection
168
+ * const handler = withScopeAndServices(
169
+ * { db: createDatabase() },
170
+ * async (req, { scope }) => {
171
+ * const db = scope.use('db')
172
+ * const [err, users] = await scope.task(() => db.query('SELECT * FROM users'))
173
+ * return Response.json(users)
174
+ * }
175
+ * )
176
+ * ```
177
+ */
178
+ export declare function withScopeAndServices<T extends Record<string, unknown>>(services: T, handler: APIRouteHandler<T>, options?: Omit<WithScopeOptions<T>, "services">): (req: NextRequest) => Promise<Response>;
179
+ /**
180
+ * Create a reusable scope configuration for API routes
181
+ *
182
+ * @example
183
+ * ```typescript
184
+ * // lib/scope.ts
185
+ * import { createRouteConfig } from '@go-go-scope/adapter-nextjs'
186
+ * import { createDatabase } from './db'
187
+ *
188
+ * export const routeConfig = createRouteConfig({
189
+ * timeout: 10000,
190
+ * services: { db: createDatabase() },
191
+ * onError: (err) => Response.json({ error: err.message }, { status: 500 })
192
+ * })
193
+ *
194
+ * // app/api/users/route.ts
195
+ * import { routeConfig } from '@/lib/scope'
196
+ *
197
+ * export const GET = routeConfig.wrap(async (req, { scope }) => {
198
+ * const db = scope.use('db')
199
+ * // ...
200
+ * })
201
+ * ```
202
+ */
203
+ export declare function createRouteConfig<T extends Record<string, unknown>>(config: WithScopeOptions<T>): {
204
+ wrap: (handler: APIRouteHandler<T>) => (req: NextRequest) => Promise<Response>;
205
+ wrapEdge: (handler: EdgeRouteHandler<T>) => (req: Request) => Promise<Response>;
206
+ wrapServer: <Props extends Record<string, unknown>>(component: (props: Props, context: NextJSContext<T>) => Promise<JSX.Element> | JSX.Element) => (props: Props) => Promise<JSX.Element>;
207
+ };
208
+ /**
209
+ * Error classes for Next.js adapter
210
+ */
211
+ export declare class NextJSRouteError extends Error {
212
+ readonly statusCode: number;
213
+ readonly code?: string | undefined;
214
+ constructor(message: string, statusCode?: number, code?: string | undefined);
215
+ }
216
+ /**
217
+ * Helper to create typed error responses
218
+ */
219
+ export declare function errorResponse(error: unknown, statusCode?: number): Response;
220
+ /**
221
+ * Helper to create success responses with proper typing
222
+ */
223
+ export declare function jsonResponse<T>(data: T, statusCode?: number): Response;
224
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,EAAE,KAAK,KAAK,EAAS,MAAM,aAAa,CAAC;AAGhD,MAAM,WAAW,WAAY,SAAQ,OAAO;IAC3C,OAAO,EAAE;QACR,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,KAAK,EAAE,MAAM,CAAA;SAAE,GAAG,SAAS,CAAC;QAC/D,MAAM,IAAI;YAAE,IAAI,EAAE,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CAAC,CAAC,CAAC;oBAGV,eAAe,CAAC,CAAC,CAAC,WA1O3B,WAAW,KAAK,OAAO,CAAC,QAAQ,CAAC;wBA2OpB,gBAAgB,CAAC,CAAC,CAAC,WAnLhC,OAAO,KAAK,OAAO,CAAC,QAAQ,CAAC;iBAoLvB,KAAK,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,aACtC,CACV,KAAK,EAAE,KAAK,EACZ,OAAO,EAAE,aAAa,CAAC,CAAC,CAAC,KACrB,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,GAAG,CAAC,OAAO,uBApHrB,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC;EAuHxC;AAED;;GAEG;AACH,qBAAa,gBAAiB,SAAQ,KAAK;aAGzB,UAAU,EAAE,MAAM;aAClB,IAAI,CAAC,EAAE,MAAM;gBAF7B,OAAO,EAAE,MAAM,EACC,UAAU,GAAE,MAAY,EACxB,IAAI,CAAC,EAAE,MAAM,YAAA;CAK9B;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,EAAE,UAAU,SAAM,GAAG,QAAQ,CAUxE;AAED;;GAEG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,UAAU,SAAM,GAAG,QAAQ,CAEnE"}
package/dist/index.js ADDED
@@ -0,0 +1,357 @@
1
+ /**
2
+ * Next.js adapter for go-go-scope
3
+ *
4
+ * Provides structured concurrency for Next.js API routes, Edge functions,
5
+ * and Server Components with automatic cleanup.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * // API Route (app/api/users/route.ts)
10
+ * import { withScope } from '@go-go-scope/adapter-nextjs'
11
+ *
12
+ * export const GET = withScope(async (req, ctx) => {
13
+ * const [err, users] = await ctx.scope.task(() => fetchUsers())
14
+ * if (err) return Response.json({ error: err.message }, { status: 500 })
15
+ * return Response.json(users)
16
+ * })
17
+ * ```
18
+ */
19
+ var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
20
+ if (value !== null && value !== void 0) {
21
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
22
+ var dispose, inner;
23
+ if (async) {
24
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
25
+ dispose = value[Symbol.asyncDispose];
26
+ }
27
+ if (dispose === void 0) {
28
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
29
+ dispose = value[Symbol.dispose];
30
+ if (async) inner = dispose;
31
+ }
32
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
33
+ if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
34
+ env.stack.push({ value: value, dispose: dispose, async: async });
35
+ }
36
+ else if (async) {
37
+ env.stack.push({ async: true });
38
+ }
39
+ return value;
40
+ };
41
+ var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
42
+ return function (env) {
43
+ function fail(e) {
44
+ env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
45
+ env.hasError = true;
46
+ }
47
+ var r, s = 0;
48
+ function next() {
49
+ while (r = env.stack.pop()) {
50
+ try {
51
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
52
+ if (r.dispose) {
53
+ var result = r.dispose.call(r.value);
54
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
55
+ }
56
+ else s |= 1;
57
+ }
58
+ catch (e) {
59
+ fail(e);
60
+ }
61
+ }
62
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
63
+ if (env.hasError) throw env.error;
64
+ }
65
+ return next();
66
+ };
67
+ })(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
68
+ var e = new Error(message);
69
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
70
+ });
71
+ import { scope } from "go-go-scope";
72
+ /**
73
+ * Wrap a Next.js API route handler with a scope
74
+ *
75
+ * @example
76
+ * ```typescript
77
+ * // app/api/users/route.ts
78
+ * import { withScope } from '@go-go-scope/adapter-nextjs'
79
+ *
80
+ * export const GET = withScope(async (req, { scope }) => {
81
+ * const [err, users] = await scope.task(() => db.query('SELECT * FROM users'))
82
+ * if (err) return Response.json({ error: err.message }, { status: 500 })
83
+ * return Response.json(users)
84
+ * })
85
+ *
86
+ * // With custom options
87
+ * export const POST = withScope(
88
+ * async (req, { scope }) => {
89
+ * const [err, result] = await scope.task(() => createUser(req))
90
+ * if (err) return Response.json({ error: err.message }, { status: 400 })
91
+ * return Response.json(result, { status: 201 })
92
+ * },
93
+ * { timeout: 5000 }
94
+ * )
95
+ * ```
96
+ */
97
+ export function withScope(handler, options = {}) {
98
+ return async (req) => {
99
+ const env_1 = { stack: [], error: void 0, hasError: false };
100
+ try {
101
+ const s = __addDisposableResource(env_1, scope({
102
+ timeout: options.timeout,
103
+ signal: req.signal,
104
+ name: `nextjs-${req.method}-${req.url}`,
105
+ }), true);
106
+ // Provide initial services
107
+ if (options.services) {
108
+ for (const [key, value] of Object.entries(options.services)) {
109
+ s.provide(key, value);
110
+ }
111
+ }
112
+ const context = {
113
+ scope: s,
114
+ signal: req.signal,
115
+ };
116
+ try {
117
+ return await handler(req, context);
118
+ }
119
+ catch (error) {
120
+ if (options.onError) {
121
+ return await options.onError(error, req);
122
+ }
123
+ console.error("Unhandled error in Next.js route:", error);
124
+ return Response.json({ error: "Internal Server Error" }, { status: 500 });
125
+ }
126
+ }
127
+ catch (e_1) {
128
+ env_1.error = e_1;
129
+ env_1.hasError = true;
130
+ }
131
+ finally {
132
+ const result_1 = __disposeResources(env_1);
133
+ if (result_1)
134
+ await result_1;
135
+ }
136
+ };
137
+ }
138
+ /**
139
+ * Wrap a Next.js Edge route handler with a scope
140
+ *
141
+ * @example
142
+ * ```typescript
143
+ * // middleware.ts or edge route
144
+ * import { withScopeEdge } from '@go-go-scope/adapter-nextjs'
145
+ *
146
+ * export const config = {
147
+ * runtime: 'edge',
148
+ * }
149
+ *
150
+ * export default withScopeEdge(async (req, { scope }) => {
151
+ * const [err, result] = await scope.task(() => fetchEdgeData())
152
+ * if (err) return new Response('Error', { status: 500 })
153
+ * return new Response(JSON.stringify(result))
154
+ * })
155
+ * ```
156
+ */
157
+ export function withScopeEdge(handler, options = {}) {
158
+ return async (req) => {
159
+ const env_2 = { stack: [], error: void 0, hasError: false };
160
+ try {
161
+ const abortController = new AbortController();
162
+ // Link to request signal if available
163
+ if (req.signal) {
164
+ req.signal.addEventListener("abort", () => {
165
+ abortController.abort();
166
+ });
167
+ }
168
+ const s = __addDisposableResource(env_2, scope({
169
+ timeout: options.timeout,
170
+ signal: abortController.signal,
171
+ name: `nextjs-edge-${req.url}`,
172
+ }), true);
173
+ // Provide initial services
174
+ if (options.services) {
175
+ for (const [key, value] of Object.entries(options.services)) {
176
+ s.provide(key, value);
177
+ }
178
+ }
179
+ const context = {
180
+ scope: s,
181
+ signal: abortController.signal,
182
+ };
183
+ try {
184
+ return await handler(req, context);
185
+ }
186
+ catch (error) {
187
+ if (options.onError) {
188
+ return await options.onError(error, req);
189
+ }
190
+ console.error("Unhandled error in Edge route:", error);
191
+ return new Response("Internal Server Error", { status: 500 });
192
+ }
193
+ }
194
+ catch (e_2) {
195
+ env_2.error = e_2;
196
+ env_2.hasError = true;
197
+ }
198
+ finally {
199
+ const result_2 = __disposeResources(env_2);
200
+ if (result_2)
201
+ await result_2;
202
+ }
203
+ };
204
+ }
205
+ /**
206
+ * Server Component wrapper with scope
207
+ *
208
+ * @example
209
+ * ```typescript
210
+ * // app/users/page.tsx
211
+ * import { withScopeServer } from '@go-go-scope/adapter-nextjs'
212
+ *
213
+ * export default withScopeServer(async (searchParams, { scope }) => {
214
+ * const [err, users] = await scope.task(() => fetchUsers())
215
+ * if (err) return <Error message={err.message} />
216
+ * return <UserList users={users} />
217
+ * })
218
+ * ```
219
+ */
220
+ export function withScopeServer(component, options = {}) {
221
+ return async (props) => {
222
+ const env_3 = { stack: [], error: void 0, hasError: false };
223
+ try {
224
+ const s = __addDisposableResource(env_3, scope({
225
+ timeout: options.timeout,
226
+ name: `nextjs-server-component`,
227
+ }), true);
228
+ // Provide initial services
229
+ if (options.services) {
230
+ for (const [key, value] of Object.entries(options.services)) {
231
+ s.provide(key, value);
232
+ }
233
+ }
234
+ const context = {
235
+ scope: s,
236
+ signal: s.signal,
237
+ };
238
+ try {
239
+ return await component(props, context);
240
+ }
241
+ catch (error) {
242
+ console.error("Unhandled error in Server Component:", error);
243
+ throw error;
244
+ }
245
+ }
246
+ catch (e_3) {
247
+ env_3.error = e_3;
248
+ env_3.hasError = true;
249
+ }
250
+ finally {
251
+ const result_3 = __disposeResources(env_3);
252
+ if (result_3)
253
+ await result_3;
254
+ }
255
+ };
256
+ }
257
+ /**
258
+ * Middleware wrapper with scope
259
+ *
260
+ * @example
261
+ * ```typescript
262
+ * // middleware.ts
263
+ * import { withScopeMiddleware } from '@go-go-scope/adapter-nextjs'
264
+ * import { NextResponse } from 'next/server'
265
+ *
266
+ * export default withScopeMiddleware(async (req, { scope }) => {
267
+ * const [err, session] = await scope.task(() => validateSession(req))
268
+ * if (err || !session) {
269
+ * return NextResponse.redirect(new URL('/login', req.url))
270
+ * }
271
+ * return NextResponse.next()
272
+ * })
273
+ * ```
274
+ */
275
+ export function withScopeMiddleware(handler, options = {}) {
276
+ return withScope(handler, options);
277
+ }
278
+ /**
279
+ * Higher-order function for route handlers with dependency injection
280
+ *
281
+ * @example
282
+ * ```typescript
283
+ * // With dependency injection
284
+ * const handler = withScopeAndServices(
285
+ * { db: createDatabase() },
286
+ * async (req, { scope }) => {
287
+ * const db = scope.use('db')
288
+ * const [err, users] = await scope.task(() => db.query('SELECT * FROM users'))
289
+ * return Response.json(users)
290
+ * }
291
+ * )
292
+ * ```
293
+ */
294
+ export function withScopeAndServices(services, handler, options = {}) {
295
+ return withScope(handler, { ...options, services });
296
+ }
297
+ /**
298
+ * Create a reusable scope configuration for API routes
299
+ *
300
+ * @example
301
+ * ```typescript
302
+ * // lib/scope.ts
303
+ * import { createRouteConfig } from '@go-go-scope/adapter-nextjs'
304
+ * import { createDatabase } from './db'
305
+ *
306
+ * export const routeConfig = createRouteConfig({
307
+ * timeout: 10000,
308
+ * services: { db: createDatabase() },
309
+ * onError: (err) => Response.json({ error: err.message }, { status: 500 })
310
+ * })
311
+ *
312
+ * // app/api/users/route.ts
313
+ * import { routeConfig } from '@/lib/scope'
314
+ *
315
+ * export const GET = routeConfig.wrap(async (req, { scope }) => {
316
+ * const db = scope.use('db')
317
+ * // ...
318
+ * })
319
+ * ```
320
+ */
321
+ export function createRouteConfig(config) {
322
+ return {
323
+ wrap: (handler) => withScope(handler, config),
324
+ wrapEdge: (handler) => withScopeEdge(handler, config),
325
+ wrapServer: (component) => withScopeServer(component, config),
326
+ };
327
+ }
328
+ /**
329
+ * Error classes for Next.js adapter
330
+ */
331
+ export class NextJSRouteError extends Error {
332
+ statusCode;
333
+ code;
334
+ constructor(message, statusCode = 500, code) {
335
+ super(message);
336
+ this.statusCode = statusCode;
337
+ this.code = code;
338
+ this.name = "NextJSRouteError";
339
+ }
340
+ }
341
+ /**
342
+ * Helper to create typed error responses
343
+ */
344
+ export function errorResponse(error, statusCode = 500) {
345
+ if (error instanceof NextJSRouteError) {
346
+ return Response.json({ error: error.message, code: error.code }, { status: error.statusCode });
347
+ }
348
+ const message = error instanceof Error ? error.message : "Unknown error";
349
+ return Response.json({ error: message }, { status: statusCode });
350
+ }
351
+ /**
352
+ * Helper to create success responses with proper typing
353
+ */
354
+ export function jsonResponse(data, statusCode = 200) {
355
+ return Response.json(data, { status: statusCode });
356
+ }
357
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,OAAO,EAAc,K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I,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,CAAC;AAClE,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,YAAY,CAAI,IAAO,EAAE,UAAU,GAAG,GAAG;IACxD,OAAO,QAAQ,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,CAAC;AACpD,CAAC"}
package/dist/index.mjs ADDED
@@ -0,0 +1,193 @@
1
+ import { scope } from 'go-go-scope';
2
+
3
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
4
+ var __typeError = (msg) => {
5
+ throw TypeError(msg);
6
+ };
7
+ var __using = (stack, value, async) => {
8
+ if (value != null) {
9
+ if (typeof value !== "object" && typeof value !== "function") __typeError("Object expected");
10
+ var dispose, inner;
11
+ dispose = value[__knownSymbol("asyncDispose")];
12
+ if (dispose === void 0) {
13
+ dispose = value[__knownSymbol("dispose")];
14
+ inner = dispose;
15
+ }
16
+ if (typeof dispose !== "function") __typeError("Object not disposable");
17
+ if (inner) dispose = function() {
18
+ try {
19
+ inner.call(this);
20
+ } catch (e) {
21
+ return Promise.reject(e);
22
+ }
23
+ };
24
+ stack.push([async, dispose, value]);
25
+ } else {
26
+ stack.push([async]);
27
+ }
28
+ return value;
29
+ };
30
+ var __callDispose = (stack, error, hasError) => {
31
+ var E = typeof SuppressedError === "function" ? SuppressedError : function(e, s, m, _) {
32
+ return _ = Error(m), _.name = "SuppressedError", _.error = e, _.suppressed = s, _;
33
+ };
34
+ var fail = (e) => error = hasError ? new E(e, error, "An error was suppressed during disposal") : (hasError = true, e);
35
+ var next = (it) => {
36
+ while (it = stack.pop()) {
37
+ try {
38
+ var result = it[1] && it[1].call(it[2]);
39
+ if (it[0]) return Promise.resolve(result).then(next, (e) => (fail(e), next()));
40
+ } catch (e) {
41
+ fail(e);
42
+ }
43
+ }
44
+ if (hasError) throw error;
45
+ };
46
+ return next();
47
+ };
48
+ function withScope(handler, options = {}) {
49
+ return async (req) => {
50
+ var _stack = [];
51
+ try {
52
+ const s = __using(_stack, scope({
53
+ timeout: options.timeout,
54
+ signal: req.signal,
55
+ name: `nextjs-${req.method}-${req.url}`
56
+ }), true);
57
+ if (options.services) {
58
+ for (const [key, value] of Object.entries(options.services)) {
59
+ s.provide(key, value);
60
+ }
61
+ }
62
+ const context = {
63
+ scope: s,
64
+ signal: req.signal
65
+ };
66
+ try {
67
+ return await handler(req, context);
68
+ } catch (error) {
69
+ if (options.onError) {
70
+ return await options.onError(error, req);
71
+ }
72
+ console.error("Unhandled error in Next.js route:", error);
73
+ return Response.json({ error: "Internal Server Error" }, { status: 500 });
74
+ }
75
+ } catch (_) {
76
+ var _error = _, _hasError = true;
77
+ } finally {
78
+ var _promise = __callDispose(_stack, _error, _hasError);
79
+ _promise && await _promise;
80
+ }
81
+ };
82
+ }
83
+ function withScopeEdge(handler, options = {}) {
84
+ return async (req) => {
85
+ var _stack = [];
86
+ try {
87
+ const abortController = new AbortController();
88
+ if (req.signal) {
89
+ req.signal.addEventListener(
90
+ "abort",
91
+ () => {
92
+ abortController.abort();
93
+ }
94
+ );
95
+ }
96
+ const s = __using(_stack, scope({
97
+ timeout: options.timeout,
98
+ signal: abortController.signal,
99
+ name: `nextjs-edge-${req.url}`
100
+ }), true);
101
+ if (options.services) {
102
+ for (const [key, value] of Object.entries(options.services)) {
103
+ s.provide(key, value);
104
+ }
105
+ }
106
+ const context = {
107
+ scope: s,
108
+ signal: abortController.signal
109
+ };
110
+ try {
111
+ return await handler(req, context);
112
+ } catch (error) {
113
+ if (options.onError) {
114
+ return await options.onError(error, req);
115
+ }
116
+ console.error("Unhandled error in Edge route:", error);
117
+ return new Response("Internal Server Error", { status: 500 });
118
+ }
119
+ } catch (_) {
120
+ var _error = _, _hasError = true;
121
+ } finally {
122
+ var _promise = __callDispose(_stack, _error, _hasError);
123
+ _promise && await _promise;
124
+ }
125
+ };
126
+ }
127
+ function withScopeServer(component, options = {}) {
128
+ return async (props) => {
129
+ var _stack = [];
130
+ try {
131
+ const s = __using(_stack, scope({
132
+ timeout: options.timeout,
133
+ name: `nextjs-server-component`
134
+ }), true);
135
+ if (options.services) {
136
+ for (const [key, value] of Object.entries(options.services)) {
137
+ s.provide(key, value);
138
+ }
139
+ }
140
+ const context = {
141
+ scope: s,
142
+ signal: s.signal
143
+ };
144
+ try {
145
+ return await component(props, context);
146
+ } catch (error) {
147
+ console.error("Unhandled error in Server Component:", error);
148
+ throw error;
149
+ }
150
+ } catch (_) {
151
+ var _error = _, _hasError = true;
152
+ } finally {
153
+ var _promise = __callDispose(_stack, _error, _hasError);
154
+ _promise && await _promise;
155
+ }
156
+ };
157
+ }
158
+ function withScopeMiddleware(handler, options = {}) {
159
+ return withScope(handler, options);
160
+ }
161
+ function withScopeAndServices(services, handler, options = {}) {
162
+ return withScope(handler, { ...options, services });
163
+ }
164
+ function createRouteConfig(config) {
165
+ return {
166
+ wrap: (handler) => withScope(handler, config),
167
+ wrapEdge: (handler) => withScopeEdge(handler, config),
168
+ wrapServer: (component) => withScopeServer(component, config)
169
+ };
170
+ }
171
+ class NextJSRouteError extends Error {
172
+ constructor(message, statusCode = 500, code) {
173
+ super(message);
174
+ this.statusCode = statusCode;
175
+ this.code = code;
176
+ this.name = "NextJSRouteError";
177
+ }
178
+ }
179
+ function errorResponse(error, statusCode = 500) {
180
+ if (error instanceof NextJSRouteError) {
181
+ return Response.json(
182
+ { error: error.message, code: error.code },
183
+ { status: error.statusCode }
184
+ );
185
+ }
186
+ const message = error instanceof Error ? error.message : "Unknown error";
187
+ return Response.json({ error: message }, { status: statusCode });
188
+ }
189
+ function jsonResponse(data, statusCode = 200) {
190
+ return Response.json(data, { status: statusCode });
191
+ }
192
+
193
+ export { NextJSRouteError, createRouteConfig, errorResponse, jsonResponse, withScope, withScopeAndServices, withScopeEdge, withScopeMiddleware, withScopeServer };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Integration tests for Next.js adapter
3
+ */
4
+ export {};
5
+ //# sourceMappingURL=index.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.test.d.ts","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":"AAAA;;GAEG"}
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Integration tests for Next.js adapter
3
+ */
4
+ import { describe, expect, test, vi } from "vitest";
5
+ import { createRouteConfig, NextJSRouteError, withScope, withScopeEdge, withScopeServer, } from "./index.js";
6
+ // Mock NextRequest
7
+ function createMockRequest(url, options = {}) {
8
+ return {
9
+ url,
10
+ method: options.method ?? "GET",
11
+ signal: new AbortController().signal,
12
+ json: async () => options.body,
13
+ };
14
+ }
15
+ describe("Next.js Adapter", () => {
16
+ describe("withScope", () => {
17
+ test("should execute handler with scope", async () => {
18
+ const handler = withScope(async (_req, { scope }) => {
19
+ const [err, result] = await scope.task(() => Promise.resolve({ message: "Hello" }));
20
+ if (err)
21
+ return Response.json({ error: err.message }, { status: 500 });
22
+ return Response.json(result);
23
+ });
24
+ const req = createMockRequest("http://localhost:3000/api/hello");
25
+ const response = await handler(req);
26
+ const data = await response.json();
27
+ expect(data).toEqual({ message: "Hello" });
28
+ });
29
+ test("should handle errors with custom error handler", async () => {
30
+ const customError = new Error("Custom error");
31
+ const errorHandler = vi
32
+ .fn()
33
+ .mockReturnValue(Response.json({ error: "Handled" }, { status: 500 }));
34
+ const handler = withScope(async () => {
35
+ throw customError;
36
+ }, { onError: errorHandler });
37
+ const req = createMockRequest("http://localhost:3000/api/test");
38
+ const response = await handler(req);
39
+ const data = (await response.json());
40
+ expect(errorHandler).toHaveBeenCalledWith(customError, req);
41
+ expect(data).toEqual({ error: "Handled" });
42
+ });
43
+ test("should inject services into scope", async () => {
44
+ const db = { query: vi.fn().mockResolvedValue([{ id: 1 }]) };
45
+ const handler = withScope(async (_req, { scope }) => {
46
+ const database = scope.use("db");
47
+ const result = await database.query();
48
+ return Response.json(result);
49
+ }, { services: { db } });
50
+ const req = createMockRequest("http://localhost:3000/api/users");
51
+ const response = await handler(req);
52
+ const data = await response.json();
53
+ expect(data).toEqual([{ id: 1 }]);
54
+ expect(db.query).toHaveBeenCalled();
55
+ });
56
+ test("should timeout long-running requests", async () => {
57
+ const handler = withScope(async (_req, { scope }) => {
58
+ const [err] = await scope.task(() => new Promise((resolve) => setTimeout(resolve, 1000)));
59
+ if (err) {
60
+ return Response.json({ error: "Request timeout" }, { status: 504 });
61
+ }
62
+ return Response.json({ success: true });
63
+ }, { timeout: 100 });
64
+ const req = createMockRequest("http://localhost:3000/api/slow");
65
+ // Should return timeout error response
66
+ const response = await handler(req);
67
+ expect(response.status).toBe(504);
68
+ const data = (await response.json());
69
+ expect(data.error).toBe("Request timeout");
70
+ });
71
+ });
72
+ describe("withScopeEdge", () => {
73
+ test("should execute edge handler with scope", async () => {
74
+ const handler = withScopeEdge(async (_req, { scope }) => {
75
+ const [err, result] = await scope.task(() => Promise.resolve("edge-result"));
76
+ if (err)
77
+ return new Response("Error", { status: 500 });
78
+ return new Response(result);
79
+ });
80
+ const req = new Request("https://example.com/api/edge");
81
+ const response = await handler(req);
82
+ const text = await response.text();
83
+ expect(text).toBe("edge-result");
84
+ });
85
+ test("should handle abort signal", async () => {
86
+ const abortController = new AbortController();
87
+ const handler = withScopeEdge(async (_req, { signal }) => {
88
+ // Check if signal is properly linked
89
+ expect(signal).toBeDefined();
90
+ return new Response("OK");
91
+ });
92
+ const req = new Request("https://example.com/api/test", {
93
+ signal: abortController.signal,
94
+ });
95
+ const response = await handler(req);
96
+ expect(response.status).toBe(200);
97
+ });
98
+ });
99
+ describe("withScopeServer", () => {
100
+ test("should execute server component with scope", async () => {
101
+ const component = withScopeServer(async (_props, { scope }) => {
102
+ const [err, data] = await scope.task(() => Promise.resolve({ users: [] }));
103
+ if (err)
104
+ throw err;
105
+ return {
106
+ type: "div",
107
+ props: { children: `Users: ${data.users.length}` },
108
+ };
109
+ });
110
+ const result = await component({});
111
+ expect(result).toBeDefined();
112
+ });
113
+ });
114
+ describe("createRouteConfig", () => {
115
+ test("should create reusable route configuration", async () => {
116
+ const db = { query: vi.fn() };
117
+ const errorHandler = vi
118
+ .fn()
119
+ .mockReturnValue(Response.json({ error: "Route error" }, { status: 500 }));
120
+ const config = createRouteConfig({
121
+ timeout: 5000,
122
+ services: { db },
123
+ onError: errorHandler,
124
+ });
125
+ const handler = config.wrap(async (_req, { scope }) => {
126
+ const database = scope.use("db");
127
+ await database.query();
128
+ return Response.json({ success: true });
129
+ });
130
+ const req = createMockRequest("http://localhost:3000/api/configured");
131
+ const response = await handler(req);
132
+ const data = await response.json();
133
+ expect(data).toEqual({ success: true });
134
+ });
135
+ });
136
+ describe("NextJSRouteError", () => {
137
+ test("should create error with status code", () => {
138
+ const error = new NextJSRouteError("Not found", 404, "NOT_FOUND");
139
+ expect(error.message).toBe("Not found");
140
+ expect(error.statusCode).toBe(404);
141
+ expect(error.code).toBe("NOT_FOUND");
142
+ });
143
+ });
144
+ });
145
+ //# sourceMappingURL=index.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.test.js","sourceRoot":"","sources":["../src/index.test.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAEpD,OAAO,EACN,iBAAiB,EACjB,gBAAgB,EAChB,SAAS,EACT,aAAa,EACb,eAAe,GACf,MAAM,YAAY,CAAC;AAEpB,mBAAmB;AACnB,SAAS,iBAAiB,CACzB,GAAW,EACX,UAA+C,EAAE;IAEjD,OAAO;QACN,GAAG;QACH,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,KAAK;QAC/B,MAAM,EAAE,IAAI,eAAe,EAAE,CAAC,MAAM;QACpC,IAAI,EAAE,KAAK,IAAI,EAAE,CAAC,OAAO,CAAC,IAAI;KACJ,CAAC;AAC7B,CAAC;AAED,QAAQ,CAAC,iBAAiB,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WAAW,CAAC,CAAC;QACtC,CAAC,CAAC,CAAC;IACJ,CAAC,CAAC,CAAC;AACJ,CAAC,CAAC,CAAC"}
package/package.json ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@go-go-scope/adapter-nextjs",
3
+ "version": "2.5.0",
4
+ "description": "Next.js adapter for go-go-scope",
5
+ "type": "module",
6
+ "main": "./dist/index.mjs",
7
+ "types": "./dist/index.d.mts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.mts",
11
+ "default": "./dist/index.mjs"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist"
16
+ ],
17
+ "keywords": [
18
+ "structured-concurrency",
19
+ "nextjs",
20
+ "next",
21
+ "edge",
22
+ "api-routes",
23
+ "typescript"
24
+ ],
25
+ "author": "Your Name",
26
+ "license": "MIT",
27
+ "peerDependencies": {
28
+ "go-go-scope": "^2.4.0",
29
+ "next": "^14.0.0 || ^15.0.0"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "^22.13.15",
33
+ "next": "^15.0.0",
34
+ "pkgroll": "^2.6.1",
35
+ "typescript": "^5.8.3",
36
+ "vitest": "^3.1.1",
37
+ "go-go-scope": "2.5.0"
38
+ },
39
+ "scripts": {
40
+ "build": "pkgroll",
41
+ "typecheck": "tsc --noEmit",
42
+ "lint": "biome check --fix src",
43
+ "test": "vitest run",
44
+ "test:watch": "vitest",
45
+ "clean": "rm -rf dist"
46
+ }
47
+ }