@analogjs/router 2.7.3-beta.2 → 2.8.0-beta.2
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/fesm2022/analogjs-router-server-actions.mjs +470 -1
- package/fesm2022/analogjs-router-server-actions.mjs.map +1 -1
- package/fesm2022/analogjs-router-tanstack-query-server.mjs +90 -0
- package/fesm2022/analogjs-router-tanstack-query-server.mjs.map +1 -0
- package/fesm2022/analogjs-router-tanstack-query.mjs +142 -0
- package/fesm2022/analogjs-router-tanstack-query.mjs.map +1 -0
- package/fesm2022/analogjs-router.mjs +227 -3
- package/fesm2022/analogjs-router.mjs.map +1 -1
- package/package.json +17 -3
- package/types/analogjs-router-server-actions.d.ts +265 -2
- package/types/analogjs-router-tanstack-query-server.d.ts +70 -0
- package/types/analogjs-router-tanstack-query.d.ts +33 -0
- package/types/analogjs-router.d.ts +180 -17
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { toWebRequest, getRequestURL, readBody, readFormData } from 'h3';
|
|
2
|
+
|
|
1
3
|
function fail(status, errors) {
|
|
2
4
|
return new Response(JSON.stringify(errors), {
|
|
3
5
|
status,
|
|
@@ -31,9 +33,476 @@ function redirect(url, config = 302) {
|
|
|
31
33
|
});
|
|
32
34
|
}
|
|
33
35
|
|
|
36
|
+
function appendEntry(target, key, value) {
|
|
37
|
+
const existingValue = target[key];
|
|
38
|
+
if (existingValue === undefined) {
|
|
39
|
+
target[key] = value;
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
if (Array.isArray(existingValue)) {
|
|
43
|
+
existingValue.push(value);
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
target[key] = [existingValue, value];
|
|
47
|
+
}
|
|
48
|
+
function getRequest(event) {
|
|
49
|
+
return event.web?.request ?? toWebRequest(event);
|
|
50
|
+
}
|
|
51
|
+
function getRequestUrl(event) {
|
|
52
|
+
return event.web?.request?.url ?? getRequestURL(event).href;
|
|
53
|
+
}
|
|
54
|
+
function getContentType(event) {
|
|
55
|
+
return (event.web?.request?.headers.get('content-type') ??
|
|
56
|
+
event.headers.get('content-type') ??
|
|
57
|
+
'');
|
|
58
|
+
}
|
|
59
|
+
function isJsonContentType(contentType) {
|
|
60
|
+
const mimeType = contentType.split(';', 1)[0]?.trim().toLowerCase() ?? '';
|
|
61
|
+
return mimeType === 'application/json' || mimeType.endsWith('+json');
|
|
62
|
+
}
|
|
63
|
+
function isFormContentType(contentType) {
|
|
64
|
+
return (contentType.includes('multipart/form-data') ||
|
|
65
|
+
contentType.includes('application/x-www-form-urlencoded'));
|
|
66
|
+
}
|
|
67
|
+
function parseSearchParams(searchParams) {
|
|
68
|
+
const result = Object.create(null);
|
|
69
|
+
searchParams.forEach((value, key) => {
|
|
70
|
+
appendEntry(result, key, value);
|
|
71
|
+
});
|
|
72
|
+
return result;
|
|
73
|
+
}
|
|
74
|
+
function parseFormData(formData) {
|
|
75
|
+
const result = Object.create(null);
|
|
76
|
+
formData.forEach((value, key) => {
|
|
77
|
+
appendEntry(result, key, value);
|
|
78
|
+
});
|
|
79
|
+
return result;
|
|
80
|
+
}
|
|
81
|
+
async function parseRequestData(event) {
|
|
82
|
+
const method = event.method.toUpperCase();
|
|
83
|
+
if (method === 'GET' || method === 'HEAD') {
|
|
84
|
+
const url = new URL(getRequestUrl(event), 'http://localhost');
|
|
85
|
+
return parseSearchParams(url.searchParams);
|
|
86
|
+
}
|
|
87
|
+
const contentType = getContentType(event);
|
|
88
|
+
if (isJsonContentType(contentType)) {
|
|
89
|
+
try {
|
|
90
|
+
return (await readBody(event)) ?? {};
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
try {
|
|
94
|
+
return await getRequest(event).json();
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return {};
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (isFormContentType(contentType)) {
|
|
102
|
+
try {
|
|
103
|
+
return parseFormData(await readFormData(event));
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
const request = getRequest(event);
|
|
107
|
+
if (typeof request.formData === 'function') {
|
|
108
|
+
try {
|
|
109
|
+
return parseFormData(await request.formData());
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return {};
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return {};
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
return (await readBody(event)) ?? {};
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
try {
|
|
123
|
+
return await getRequest(event).json();
|
|
124
|
+
}
|
|
125
|
+
catch {
|
|
126
|
+
return {};
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Validates unknown input against a Standard Schema.
|
|
133
|
+
*
|
|
134
|
+
* Handles both sync and async `validate` implementations — the Standard
|
|
135
|
+
* Schema spec allows either return shape.
|
|
136
|
+
*/
|
|
137
|
+
async function validateWithSchema(schema, data) {
|
|
138
|
+
return schema['~standard'].validate(data);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function isDevEnvironment$1() {
|
|
142
|
+
return (typeof process !== 'undefined' &&
|
|
143
|
+
(process.env['NODE_ENV'] === 'development' ||
|
|
144
|
+
process.env['NODE_ENV'] === 'test'));
|
|
145
|
+
}
|
|
146
|
+
function warnOnOutputIssues$1(issues) {
|
|
147
|
+
console.warn(`[analog] Server route output validation failed:\n` +
|
|
148
|
+
issues
|
|
149
|
+
.map((i) => {
|
|
150
|
+
const path = i.path
|
|
151
|
+
? ` at "${i.path.map((p) => (typeof p === 'object' ? p.key : p)).join('.')}"`
|
|
152
|
+
: '';
|
|
153
|
+
return ` - ${i.message}${path}`;
|
|
154
|
+
})
|
|
155
|
+
.join('\n'));
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Creates an h3-compatible event handler with Standard Schema validation.
|
|
159
|
+
*
|
|
160
|
+
* - `input` schema validates the request body (POST/PUT/PATCH) or query
|
|
161
|
+
* params (GET). Returns 422 with `StandardSchemaV1.Issue[]` on failure.
|
|
162
|
+
* - `output` schema validates the response in development only (stripped
|
|
163
|
+
* in production for zero overhead). Logs a warning on mismatch.
|
|
164
|
+
* - Plain return values are serialized with `json(...)`; raw `Response`
|
|
165
|
+
* objects are returned unchanged.
|
|
166
|
+
*
|
|
167
|
+
* @example
|
|
168
|
+
* ```typescript
|
|
169
|
+
* import { defineServerRoute } from '@analogjs/router/server/actions';
|
|
170
|
+
* import * as v from 'valibot';
|
|
171
|
+
*
|
|
172
|
+
* const Input = v.object({
|
|
173
|
+
* name: v.pipe(v.string(), v.minLength(1)),
|
|
174
|
+
* email: v.pipe(v.string(), v.email()),
|
|
175
|
+
* });
|
|
176
|
+
* const Output = v.object({
|
|
177
|
+
* id: v.string(),
|
|
178
|
+
* name: v.string(),
|
|
179
|
+
* });
|
|
180
|
+
*
|
|
181
|
+
* export default defineServerRoute({
|
|
182
|
+
* input: Input,
|
|
183
|
+
* output: Output,
|
|
184
|
+
* handler: async ({ data }) => {
|
|
185
|
+
* const user = await db.users.create(data);
|
|
186
|
+
* return user;
|
|
187
|
+
* },
|
|
188
|
+
* });
|
|
189
|
+
* ```
|
|
190
|
+
*/
|
|
191
|
+
function defineServerRoute(options) {
|
|
192
|
+
return (async (event) => {
|
|
193
|
+
const method = event.method.toUpperCase();
|
|
194
|
+
let data;
|
|
195
|
+
let query;
|
|
196
|
+
let body;
|
|
197
|
+
let params = event.context?.params ?? {};
|
|
198
|
+
if (options.params) {
|
|
199
|
+
const paramsResult = await validateWithSchema(options.params, params);
|
|
200
|
+
if (paramsResult.issues) {
|
|
201
|
+
return fail(422, paramsResult.issues);
|
|
202
|
+
}
|
|
203
|
+
params = paramsResult.value;
|
|
204
|
+
}
|
|
205
|
+
const hasBody = method !== 'GET' && method !== 'HEAD';
|
|
206
|
+
const requestData = options.input || (options.body && hasBody)
|
|
207
|
+
? await parseRequestData(event)
|
|
208
|
+
: undefined;
|
|
209
|
+
if (options.input) {
|
|
210
|
+
const inputResult = await validateWithSchema(options.input, requestData);
|
|
211
|
+
if (inputResult.issues) {
|
|
212
|
+
return fail(422, inputResult.issues);
|
|
213
|
+
}
|
|
214
|
+
data = inputResult.value;
|
|
215
|
+
}
|
|
216
|
+
if (options.query) {
|
|
217
|
+
const url = new URL(getRequestUrl(event), 'http://localhost');
|
|
218
|
+
const queryResult = await validateWithSchema(options.query, parseSearchParams(url.searchParams));
|
|
219
|
+
if (queryResult.issues) {
|
|
220
|
+
return fail(422, queryResult.issues);
|
|
221
|
+
}
|
|
222
|
+
query = queryResult.value;
|
|
223
|
+
}
|
|
224
|
+
if (options.body && hasBody) {
|
|
225
|
+
const bodyResult = await validateWithSchema(options.body, requestData);
|
|
226
|
+
if (bodyResult.issues) {
|
|
227
|
+
return fail(422, bodyResult.issues);
|
|
228
|
+
}
|
|
229
|
+
body = bodyResult.value;
|
|
230
|
+
}
|
|
231
|
+
if (!options.input) {
|
|
232
|
+
if (!hasBody) {
|
|
233
|
+
data = query;
|
|
234
|
+
}
|
|
235
|
+
else if (body !== undefined) {
|
|
236
|
+
data = body;
|
|
237
|
+
}
|
|
238
|
+
else {
|
|
239
|
+
data = query;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const result = await options.handler({
|
|
243
|
+
data: data,
|
|
244
|
+
query: query,
|
|
245
|
+
body: body,
|
|
246
|
+
params: params,
|
|
247
|
+
event,
|
|
248
|
+
});
|
|
249
|
+
if (result instanceof Response) {
|
|
250
|
+
return result;
|
|
251
|
+
}
|
|
252
|
+
if (options.output && isDevEnvironment$1()) {
|
|
253
|
+
const outputResult = await validateWithSchema(options.output, result);
|
|
254
|
+
if (outputResult.issues) {
|
|
255
|
+
warnOnOutputIssues$1(outputResult.issues);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return json(result);
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Creates a typed page server load function with optional
|
|
264
|
+
* Standard Schema validation for route params and query.
|
|
265
|
+
*
|
|
266
|
+
* Follows the same validation pattern as `defineServerRoute`:
|
|
267
|
+
* validates before invoking the handler and returns
|
|
268
|
+
* `fail(422, issues)` on validation failure.
|
|
269
|
+
*
|
|
270
|
+
* @example
|
|
271
|
+
* ```typescript
|
|
272
|
+
* // src/app/pages/users/[id].server.ts
|
|
273
|
+
* import { definePageLoad } from '@analogjs/router/server/actions';
|
|
274
|
+
* import * as v from 'valibot';
|
|
275
|
+
*
|
|
276
|
+
* export const routeParamsSchema = v.object({
|
|
277
|
+
* id: v.pipe(v.string(), v.regex(/^\d+$/)),
|
|
278
|
+
* });
|
|
279
|
+
*
|
|
280
|
+
* export const load = definePageLoad({
|
|
281
|
+
* params: routeParamsSchema,
|
|
282
|
+
* handler: async ({ params, fetch }) => {
|
|
283
|
+
* // params.id is typed as string (validated)
|
|
284
|
+
* const user = await fetch(`/api/users/${params.id}`);
|
|
285
|
+
* return user;
|
|
286
|
+
* },
|
|
287
|
+
* });
|
|
288
|
+
* ```
|
|
289
|
+
*/
|
|
290
|
+
function definePageLoad(options) {
|
|
291
|
+
return async (ctx) => {
|
|
292
|
+
let params = ctx.params ?? {};
|
|
293
|
+
const url = new URL(getRequestUrl(ctx.event), 'http://localhost');
|
|
294
|
+
let query = parseSearchParams(url.searchParams);
|
|
295
|
+
// Validate params
|
|
296
|
+
if (options.params) {
|
|
297
|
+
const result = await validateWithSchema(options.params, params);
|
|
298
|
+
if (result.issues) {
|
|
299
|
+
return fail(422, result.issues);
|
|
300
|
+
}
|
|
301
|
+
params = result.value;
|
|
302
|
+
}
|
|
303
|
+
// Validate query
|
|
304
|
+
if (options.query) {
|
|
305
|
+
const result = await validateWithSchema(options.query, query);
|
|
306
|
+
if (result.issues) {
|
|
307
|
+
return fail(422, result.issues);
|
|
308
|
+
}
|
|
309
|
+
query = result.value;
|
|
310
|
+
}
|
|
311
|
+
return options.handler({
|
|
312
|
+
params: params,
|
|
313
|
+
query: query,
|
|
314
|
+
req: ctx.req,
|
|
315
|
+
res: ctx.res,
|
|
316
|
+
fetch: ctx.fetch,
|
|
317
|
+
event: ctx.event,
|
|
318
|
+
});
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* Creates a server action handler with Standard Schema input validation.
|
|
324
|
+
*
|
|
325
|
+
* Parses the request body (JSON or FormData) and validates it against the
|
|
326
|
+
* provided schema before invoking the handler. On validation failure,
|
|
327
|
+
* returns `fail(422, issues)` with `StandardSchemaV1.Issue[]`.
|
|
328
|
+
* Repeated form fields are preserved as arrays instead of being collapsed
|
|
329
|
+
* to the last value.
|
|
330
|
+
*
|
|
331
|
+
* @example
|
|
332
|
+
* ```typescript
|
|
333
|
+
* import { defineAction, json } from '@analogjs/router/server/actions';
|
|
334
|
+
* import * as v from 'valibot';
|
|
335
|
+
*
|
|
336
|
+
* const Schema = v.object({
|
|
337
|
+
* email: v.pipe(v.string(), v.email()),
|
|
338
|
+
* });
|
|
339
|
+
*
|
|
340
|
+
* export const action = defineAction({
|
|
341
|
+
* schema: Schema,
|
|
342
|
+
* handler: async ({ data }) => {
|
|
343
|
+
* // data is typed as { email: string }
|
|
344
|
+
* return json({ ok: true });
|
|
345
|
+
* },
|
|
346
|
+
* });
|
|
347
|
+
* ```
|
|
348
|
+
*/
|
|
349
|
+
function defineAction(options) {
|
|
350
|
+
function getParams(params) {
|
|
351
|
+
return (params ?? {});
|
|
352
|
+
}
|
|
353
|
+
return async (ctx) => {
|
|
354
|
+
const rawParams = getParams(ctx.params);
|
|
355
|
+
if (options.params) {
|
|
356
|
+
const paramsResult = await validateWithSchema(options.params, rawParams);
|
|
357
|
+
if (paramsResult.issues) {
|
|
358
|
+
return fail(422, paramsResult.issues);
|
|
359
|
+
}
|
|
360
|
+
return handleValidatedRequest(ctx, options, paramsResult.value);
|
|
361
|
+
}
|
|
362
|
+
return handleValidatedRequest(ctx, options, rawParams);
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
async function handleValidatedRequest(ctx, options, params) {
|
|
366
|
+
const body = await parseRequestData(ctx.event);
|
|
367
|
+
let data = body;
|
|
368
|
+
if (options.schema) {
|
|
369
|
+
const result = await validateWithSchema(options.schema, body);
|
|
370
|
+
if (result.issues) {
|
|
371
|
+
return fail(422, result.issues);
|
|
372
|
+
}
|
|
373
|
+
data = result.value;
|
|
374
|
+
}
|
|
375
|
+
return options.handler({
|
|
376
|
+
data: data,
|
|
377
|
+
params,
|
|
378
|
+
req: ctx.req,
|
|
379
|
+
res: ctx.res,
|
|
380
|
+
fetch: ctx.fetch,
|
|
381
|
+
event: ctx.event,
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
function isDevEnvironment() {
|
|
386
|
+
return (typeof process !== 'undefined' &&
|
|
387
|
+
(process.env['NODE_ENV'] === 'development' ||
|
|
388
|
+
process.env['NODE_ENV'] === 'test'));
|
|
389
|
+
}
|
|
390
|
+
function warnOnOutputIssues(issues) {
|
|
391
|
+
console.warn(`[analog] API route output validation failed:\n` +
|
|
392
|
+
issues
|
|
393
|
+
.map((i) => {
|
|
394
|
+
const path = i.path
|
|
395
|
+
? ` at "${i.path.map((p) => (typeof p === 'object' ? p.key : p)).join('.')}"`
|
|
396
|
+
: '';
|
|
397
|
+
return ` - ${i.message}${path}`;
|
|
398
|
+
})
|
|
399
|
+
.join('\n'));
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Creates an h3-compatible event handler with Standard Schema validation.
|
|
403
|
+
*
|
|
404
|
+
* - `input` schema validates the request body (POST/PUT/PATCH) or query
|
|
405
|
+
* params (GET). Returns 422 with `StandardSchemaV1.Issue[]` on failure.
|
|
406
|
+
* - `output` schema validates the response in development and tests only. Logs a warning on mismatch.
|
|
407
|
+
* - Plain return values are serialized with `json(...)`; raw `Response`
|
|
408
|
+
* objects are returned unchanged.
|
|
409
|
+
*
|
|
410
|
+
* @example
|
|
411
|
+
* ```typescript
|
|
412
|
+
* import { defineApiRoute } from '@analogjs/router/server/actions';
|
|
413
|
+
* import * as v from 'valibot';
|
|
414
|
+
*
|
|
415
|
+
* const Input = v.object({
|
|
416
|
+
* name: v.pipe(v.string(), v.minLength(1)),
|
|
417
|
+
* email: v.pipe(v.string(), v.email()),
|
|
418
|
+
* });
|
|
419
|
+
* const Output = v.object({
|
|
420
|
+
* id: v.string(),
|
|
421
|
+
* name: v.string(),
|
|
422
|
+
* });
|
|
423
|
+
*
|
|
424
|
+
* export default defineApiRoute({
|
|
425
|
+
* input: Input,
|
|
426
|
+
* output: Output,
|
|
427
|
+
* handler: async ({ data }) => {
|
|
428
|
+
* const user = await db.users.create(data);
|
|
429
|
+
* return user;
|
|
430
|
+
* },
|
|
431
|
+
* });
|
|
432
|
+
* ```
|
|
433
|
+
*/
|
|
434
|
+
function defineApiRoute(options) {
|
|
435
|
+
return async (event) => {
|
|
436
|
+
const method = event.method.toUpperCase();
|
|
437
|
+
let data;
|
|
438
|
+
let query;
|
|
439
|
+
let body;
|
|
440
|
+
let params = event.context?.params ?? {};
|
|
441
|
+
if (options.params) {
|
|
442
|
+
const paramsResult = await validateWithSchema(options.params, params);
|
|
443
|
+
if (paramsResult.issues) {
|
|
444
|
+
return fail(422, paramsResult.issues);
|
|
445
|
+
}
|
|
446
|
+
params = paramsResult.value;
|
|
447
|
+
}
|
|
448
|
+
const requestData = options.input || (options.body && method !== 'GET' && method !== 'HEAD')
|
|
449
|
+
? await parseRequestData(event)
|
|
450
|
+
: undefined;
|
|
451
|
+
if (options.input) {
|
|
452
|
+
data = requestData;
|
|
453
|
+
const inputResult = await validateWithSchema(options.input, data);
|
|
454
|
+
if (inputResult.issues) {
|
|
455
|
+
return fail(422, inputResult.issues);
|
|
456
|
+
}
|
|
457
|
+
data = inputResult.value;
|
|
458
|
+
}
|
|
459
|
+
if (options.query) {
|
|
460
|
+
const url = new URL(getRequestUrl(event), 'http://localhost');
|
|
461
|
+
const queryResult = await validateWithSchema(options.query, parseSearchParams(url.searchParams));
|
|
462
|
+
if (queryResult.issues) {
|
|
463
|
+
return fail(422, queryResult.issues);
|
|
464
|
+
}
|
|
465
|
+
query = queryResult.value;
|
|
466
|
+
}
|
|
467
|
+
if (options.body && method !== 'GET' && method !== 'HEAD') {
|
|
468
|
+
body = requestData;
|
|
469
|
+
const bodyResult = await validateWithSchema(options.body, body);
|
|
470
|
+
if (bodyResult.issues) {
|
|
471
|
+
return fail(422, bodyResult.issues);
|
|
472
|
+
}
|
|
473
|
+
body = bodyResult.value;
|
|
474
|
+
}
|
|
475
|
+
if (!options.input) {
|
|
476
|
+
data =
|
|
477
|
+
method === 'GET' || method === 'HEAD'
|
|
478
|
+
? query
|
|
479
|
+
: body !== undefined
|
|
480
|
+
? body
|
|
481
|
+
: query;
|
|
482
|
+
}
|
|
483
|
+
const result = await options.handler({
|
|
484
|
+
data: data,
|
|
485
|
+
query: query,
|
|
486
|
+
body: body,
|
|
487
|
+
params: params,
|
|
488
|
+
event,
|
|
489
|
+
});
|
|
490
|
+
if (result instanceof Response) {
|
|
491
|
+
return result;
|
|
492
|
+
}
|
|
493
|
+
if (options.output && isDevEnvironment()) {
|
|
494
|
+
const outputResult = await validateWithSchema(options.output, result);
|
|
495
|
+
if (outputResult.issues) {
|
|
496
|
+
warnOnOutputIssues(outputResult.issues);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
return json(result);
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
|
|
34
503
|
/**
|
|
35
504
|
* Generated bundle index. Do not edit.
|
|
36
505
|
*/
|
|
37
506
|
|
|
38
|
-
export { fail, json, redirect };
|
|
507
|
+
export { defineAction, defineApiRoute, definePageLoad, defineServerRoute, fail, json, redirect, validateWithSchema };
|
|
39
508
|
//# sourceMappingURL=analogjs-router-server-actions.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analogjs-router-server-actions.mjs","sources":["../../../../packages/router/server/actions/src/actions.ts","../../../../packages/router/server/actions/src/analogjs-router-server-actions.ts"],"sourcesContent":["import type { H3Event, H3EventContext } from 'h3';\nimport type { $Fetch } from 'nitropack';\n\nexport type PageServerAction = {\n params: H3EventContext['params'];\n req: H3Event['node']['req'];\n res: H3Event['node']['res'];\n fetch: $Fetch;\n event: H3Event;\n};\n\nexport function fail<T = object>(status: number, errors: T) {\n return new Response(JSON.stringify(errors), {\n status,\n headers: {\n 'X-Analog-Errors': 'true',\n },\n });\n}\n\nexport function json<T = object>(data: T, config?: ResponseInit) {\n return new Response(JSON.stringify(data), {\n headers: {\n 'Content-Type': 'application/json; charset=utf-8',\n },\n ...config,\n });\n}\n\nexport function redirect(url: string, config: number | ResponseInit = 302) {\n if (typeof config === 'number') {\n return new Response(null, {\n status: config,\n headers: {\n Location: `${url}`,\n },\n });\n }\n\n return new Response(null, {\n headers: {\n Location: `${url}`,\n },\n ...config,\n });\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":[],"mappings":"AAWM,SAAU,IAAI,CAAa,MAAc,EAAE,MAAS,EAAA;IACxD,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE;QAC1C,MAAM;AACN,QAAA,OAAO,EAAE;AACP,YAAA,iBAAiB,EAAE,MAAM;AAC1B,SAAA;AACF,KAAA,CAAC;AACJ;AAEM,SAAU,IAAI,CAAa,IAAO,EAAE,MAAqB,EAAA;IAC7D,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE;AACxC,QAAA,OAAO,EAAE;AACP,YAAA,cAAc,EAAE,iCAAiC;AAClD,SAAA;AACD,QAAA,GAAG,MAAM;AACV,KAAA,CAAC;AACJ;SAEgB,QAAQ,CAAC,GAAW,EAAE,SAAgC,GAAG,EAAA;AACvE,IAAA,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;AAC9B,QAAA,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE;AACxB,YAAA,MAAM,EAAE,MAAM;AACd,YAAA,OAAO,EAAE;gBACP,QAAQ,EAAE,CAAA,EAAG,GAAG,CAAA,CAAE;AACnB,aAAA;AACF,SAAA,CAAC;IACJ;AAEA,IAAA,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE;AACxB,QAAA,OAAO,EAAE;YACP,QAAQ,EAAE,CAAA,EAAG,GAAG,CAAA,CAAE;AACnB,SAAA;AACD,QAAA,GAAG,MAAM;AACV,KAAA,CAAC;AACJ;;AC7CA;;AAEG;;;;"}
|
|
1
|
+
{"version":3,"file":"analogjs-router-server-actions.mjs","sources":["../../../../packages/router/server/actions/src/actions.ts","../../../../packages/router/server/actions/src/parse-request-data.ts","../../../../packages/router/server/actions/src/validate.ts","../../../../packages/router/server/actions/src/define-server-route.ts","../../../../packages/router/server/actions/src/define-page-load.ts","../../../../packages/router/server/actions/src/define-action.ts","../../../../packages/router/server/actions/src/define-api-route.ts","../../../../packages/router/server/actions/src/analogjs-router-server-actions.ts"],"sourcesContent":["import type { H3Event, H3EventContext } from 'h3';\nimport type { $Fetch } from 'nitropack';\n\nexport type PageServerAction = {\n params: H3EventContext['params'];\n req: H3Event['node']['req'];\n res: H3Event['node']['res'];\n fetch: $Fetch;\n event: H3Event;\n};\n\nexport function fail<T = object>(status: number, errors: T) {\n return new Response(JSON.stringify(errors), {\n status,\n headers: {\n 'X-Analog-Errors': 'true',\n },\n });\n}\n\nexport function json<T = object>(data: T, config?: ResponseInit) {\n return new Response(JSON.stringify(data), {\n headers: {\n 'Content-Type': 'application/json; charset=utf-8',\n },\n ...config,\n });\n}\n\nexport function redirect(url: string, config: number | ResponseInit = 302) {\n if (typeof config === 'number') {\n return new Response(null, {\n status: config,\n headers: {\n Location: `${url}`,\n },\n });\n }\n\n return new Response(null, {\n headers: {\n Location: `${url}`,\n },\n ...config,\n });\n}\n","import type { H3Event } from 'h3';\nimport { getRequestURL, readBody, readFormData, toWebRequest } from 'h3';\n\ntype RequestEntryValue = string | File;\ntype ParsedRequestValue = RequestEntryValue | RequestEntryValue[];\n\nfunction appendEntry(\n target: Record<string, ParsedRequestValue>,\n key: string,\n value: RequestEntryValue,\n) {\n const existingValue = target[key];\n\n if (existingValue === undefined) {\n target[key] = value;\n return;\n }\n\n if (Array.isArray(existingValue)) {\n existingValue.push(value);\n return;\n }\n\n target[key] = [existingValue, value];\n}\n\nfunction getRequest(event: H3Event): Request {\n return event.web?.request ?? toWebRequest(event);\n}\n\nexport function getRequestUrl(event: H3Event): string {\n return event.web?.request?.url ?? getRequestURL(event).href;\n}\n\nfunction getContentType(event: H3Event): string {\n return (\n event.web?.request?.headers.get('content-type') ??\n event.headers.get('content-type') ??\n ''\n );\n}\n\nfunction isJsonContentType(contentType: string): boolean {\n const mimeType = contentType.split(';', 1)[0]?.trim().toLowerCase() ?? '';\n return mimeType === 'application/json' || mimeType.endsWith('+json');\n}\n\nfunction isFormContentType(contentType: string): boolean {\n return (\n contentType.includes('multipart/form-data') ||\n contentType.includes('application/x-www-form-urlencoded')\n );\n}\n\nexport function parseSearchParams(\n searchParams: URLSearchParams,\n): Record<string, ParsedRequestValue> {\n const result: Record<string, ParsedRequestValue> = Object.create(null);\n searchParams.forEach((value, key) => {\n appendEntry(result, key, value);\n });\n return result;\n}\n\nexport function parseFormData(\n formData: FormData,\n): Record<string, ParsedRequestValue> {\n const result: Record<string, ParsedRequestValue> = Object.create(null);\n formData.forEach((value, key) => {\n appendEntry(result, key, value as RequestEntryValue);\n });\n return result;\n}\n\nexport async function parseRequestData(event: H3Event): Promise<unknown> {\n const method = event.method.toUpperCase();\n\n if (method === 'GET' || method === 'HEAD') {\n const url = new URL(getRequestUrl(event), 'http://localhost');\n return parseSearchParams(url.searchParams);\n }\n\n const contentType = getContentType(event);\n\n if (isJsonContentType(contentType)) {\n try {\n return (await readBody(event)) ?? {};\n } catch {\n try {\n return await getRequest(event).json();\n } catch {\n return {};\n }\n }\n }\n\n if (isFormContentType(contentType)) {\n try {\n return parseFormData(await readFormData(event));\n } catch {\n const request = getRequest(event);\n if (typeof request.formData === 'function') {\n try {\n return parseFormData(await request.formData());\n } catch {\n return {};\n }\n }\n\n return {};\n }\n }\n\n try {\n return (await readBody(event)) ?? {};\n } catch {\n try {\n return await getRequest(event).json();\n } catch {\n return {};\n }\n }\n}\n","import type { StandardSchemaV1 } from './standard-schema';\n\n/**\n * Validates unknown input against a Standard Schema.\n *\n * Handles both sync and async `validate` implementations — the Standard\n * Schema spec allows either return shape.\n */\nexport async function validateWithSchema<T extends StandardSchemaV1>(\n schema: T,\n data: unknown,\n): Promise<StandardSchemaV1.Result<StandardSchemaV1.InferOutput<T>>> {\n return schema['~standard'].validate(data);\n}\n","import type { StandardSchemaV1 } from './standard-schema';\nimport type { H3Event } from 'h3';\nimport { fail, json } from './actions';\nimport {\n getRequestUrl,\n parseRequestData,\n parseSearchParams,\n} from './parse-request-data';\nimport { validateWithSchema } from './validate';\n\nexport type DefineServerRouteResult = Response | unknown;\n\nexport interface ServerRouteHandler<\n TQuery = unknown,\n TBody = unknown,\n TResult = unknown,\n> {\n (event: H3Event): Promise<Response>;\n readonly _types: {\n readonly query: TQuery;\n readonly body: TBody;\n readonly result: TResult;\n };\n}\n\nexport type InferRouteQuery<T> =\n T extends ServerRouteHandler<infer Q, any, any> ? Q : never;\nexport type InferRouteBody<T> =\n T extends ServerRouteHandler<any, infer B, any> ? B : never;\nexport type InferRouteResult<T> =\n T extends ServerRouteHandler<any, any, infer R>\n ? Exclude<R, Response>\n : never;\n\ntype OptionalSchema = StandardSchemaV1 | undefined;\ntype InferSchema<\n TSchema extends OptionalSchema,\n TFallback = unknown,\n> = TSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TSchema>\n : TFallback;\ntype ResolveDataSchema<\n TInput extends OptionalSchema,\n TQuery extends OptionalSchema,\n TBody extends OptionalSchema,\n> = TInput extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TInput>\n : TQuery extends StandardSchemaV1\n ? TBody extends StandardSchemaV1\n ?\n | StandardSchemaV1.InferOutput<TQuery>\n | StandardSchemaV1.InferOutput<TBody>\n : StandardSchemaV1.InferOutput<TQuery>\n : TBody extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TBody>\n : unknown;\n\nexport interface DefineServerRouteContext<\n TInput extends StandardSchemaV1 | undefined = undefined,\n TQuery extends StandardSchemaV1 | undefined = undefined,\n TBody extends StandardSchemaV1 | undefined = undefined,\n TParams extends StandardSchemaV1 | undefined = undefined,\n> {\n data: ResolveDataSchema<TInput, TQuery, TBody>;\n query: InferSchema<TQuery, undefined>;\n body: InferSchema<TBody, undefined>;\n params: InferSchema<TParams, H3Event['context']['params']>;\n event: H3Event;\n}\n\nexport interface DefineServerRouteOptions<\n TInput extends StandardSchemaV1 | undefined = undefined,\n TOutput extends StandardSchemaV1 | undefined = undefined,\n TQuery extends StandardSchemaV1 | undefined = undefined,\n TBody extends StandardSchemaV1 | undefined = undefined,\n TParams extends StandardSchemaV1 | undefined = undefined,\n TResult extends DefineServerRouteResult = DefineServerRouteResult,\n> {\n input?: TInput;\n query?: TQuery;\n body?: TBody;\n params?: TParams;\n output?: TOutput;\n handler: (\n context: DefineServerRouteContext<TInput, TQuery, TBody, TParams>,\n ) => Promise<TResult> | TResult;\n}\n\nfunction isDevEnvironment() {\n return (\n typeof process !== 'undefined' &&\n (process.env['NODE_ENV'] === 'development' ||\n process.env['NODE_ENV'] === 'test')\n );\n}\n\nfunction warnOnOutputIssues(issues: ReadonlyArray<StandardSchemaV1.Issue>) {\n console.warn(\n `[analog] Server route output validation failed:\\n` +\n issues\n .map((i) => {\n const path = i.path\n ? ` at \"${i.path.map((p) => (typeof p === 'object' ? (p as { key: string }).key : p)).join('.')}\"`\n : '';\n return ` - ${i.message}${path}`;\n })\n .join('\\n'),\n );\n}\n\n/**\n * Creates an h3-compatible event handler with Standard Schema validation.\n *\n * - `input` schema validates the request body (POST/PUT/PATCH) or query\n * params (GET). Returns 422 with `StandardSchemaV1.Issue[]` on failure.\n * - `output` schema validates the response in development only (stripped\n * in production for zero overhead). Logs a warning on mismatch.\n * - Plain return values are serialized with `json(...)`; raw `Response`\n * objects are returned unchanged.\n *\n * @example\n * ```typescript\n * import { defineServerRoute } from '@analogjs/router/server/actions';\n * import * as v from 'valibot';\n *\n * const Input = v.object({\n * name: v.pipe(v.string(), v.minLength(1)),\n * email: v.pipe(v.string(), v.email()),\n * });\n * const Output = v.object({\n * id: v.string(),\n * name: v.string(),\n * });\n *\n * export default defineServerRoute({\n * input: Input,\n * output: Output,\n * handler: async ({ data }) => {\n * const user = await db.users.create(data);\n * return user;\n * },\n * });\n * ```\n */\nexport function defineServerRoute<\n TInput extends StandardSchemaV1 | undefined = undefined,\n TOutput extends StandardSchemaV1 | undefined = undefined,\n TQuery extends StandardSchemaV1 | undefined = undefined,\n TBody extends StandardSchemaV1 | undefined = undefined,\n TParams extends StandardSchemaV1 | undefined = undefined,\n TResult extends DefineServerRouteResult = DefineServerRouteResult,\n>(\n options: DefineServerRouteOptions<\n TInput,\n TOutput,\n TQuery,\n TBody,\n TParams,\n TResult\n >,\n): ServerRouteHandler<\n InferSchema<TQuery, undefined>,\n InferSchema<TBody, undefined>,\n TResult\n> {\n return (async (event: H3Event): Promise<Response> => {\n const method = event.method.toUpperCase();\n let data: unknown;\n let query: unknown;\n let body: unknown;\n let params: unknown = event.context?.params ?? {};\n\n if (options.params) {\n const paramsResult = await validateWithSchema(options.params, params);\n if (paramsResult.issues) {\n return fail(422, paramsResult.issues);\n }\n params = paramsResult.value;\n }\n\n const hasBody = method !== 'GET' && method !== 'HEAD';\n const requestData =\n options.input || (options.body && hasBody)\n ? await parseRequestData(event)\n : undefined;\n\n if (options.input) {\n const inputResult = await validateWithSchema(options.input, requestData);\n if (inputResult.issues) {\n return fail(422, inputResult.issues);\n }\n data = inputResult.value;\n }\n\n if (options.query) {\n const url = new URL(getRequestUrl(event), 'http://localhost');\n const queryResult = await validateWithSchema(\n options.query,\n parseSearchParams(url.searchParams),\n );\n if (queryResult.issues) {\n return fail(422, queryResult.issues);\n }\n query = queryResult.value;\n }\n\n if (options.body && hasBody) {\n const bodyResult = await validateWithSchema(options.body, requestData);\n if (bodyResult.issues) {\n return fail(422, bodyResult.issues);\n }\n body = bodyResult.value;\n }\n\n if (!options.input) {\n if (!hasBody) {\n data = query;\n } else if (body !== undefined) {\n data = body;\n } else {\n data = query;\n }\n }\n\n const result = await options.handler({\n data: data as ResolveDataSchema<TInput, TQuery, TBody>,\n query: query as InferSchema<TQuery, undefined>,\n body: body as InferSchema<TBody, undefined>,\n params: params as InferSchema<TParams, H3Event['context']['params']>,\n event,\n });\n\n if (result instanceof Response) {\n return result;\n }\n\n if (options.output && isDevEnvironment()) {\n const outputResult = await validateWithSchema(options.output, result);\n if (outputResult.issues) {\n warnOnOutputIssues(outputResult.issues);\n }\n }\n\n return json(result);\n }) as ServerRouteHandler<\n InferSchema<TQuery, undefined>,\n InferSchema<TBody, undefined>,\n TResult\n >;\n}\n","import type { StandardSchemaV1 } from './standard-schema';\nimport type { H3Event, H3EventContext } from 'h3';\nimport type { $Fetch } from 'nitropack';\nimport { fail } from './actions';\nimport { getRequestUrl, parseSearchParams } from './parse-request-data';\nimport { validateWithSchema } from './validate';\n\ntype OptionalSchema = StandardSchemaV1 | undefined;\ntype InferSchema<\n TSchema extends OptionalSchema,\n TFallback,\n> = TSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TSchema>\n : TFallback;\n\nexport interface PageLoadContext<\n TParamsSchema extends OptionalSchema = undefined,\n TQuerySchema extends OptionalSchema = undefined,\n> {\n params: InferSchema<TParamsSchema, H3EventContext['params']>;\n query: InferSchema<\n TQuerySchema,\n Record<string, string | string[] | undefined>\n >;\n req: H3Event['node']['req'];\n res: H3Event['node']['res'];\n fetch: $Fetch;\n event: H3Event;\n}\n\nexport interface DefinePageLoadOptions<\n TParamsSchema extends OptionalSchema = undefined,\n TQuerySchema extends OptionalSchema = undefined,\n TResult = unknown,\n> {\n params?: TParamsSchema;\n query?: TQuerySchema;\n handler: (\n context: PageLoadContext<TParamsSchema, TQuerySchema>,\n ) => Promise<TResult> | TResult;\n}\n\n/**\n * Creates a typed page server load function with optional\n * Standard Schema validation for route params and query.\n *\n * Follows the same validation pattern as `defineServerRoute`:\n * validates before invoking the handler and returns\n * `fail(422, issues)` on validation failure.\n *\n * @example\n * ```typescript\n * // src/app/pages/users/[id].server.ts\n * import { definePageLoad } from '@analogjs/router/server/actions';\n * import * as v from 'valibot';\n *\n * export const routeParamsSchema = v.object({\n * id: v.pipe(v.string(), v.regex(/^\\d+$/)),\n * });\n *\n * export const load = definePageLoad({\n * params: routeParamsSchema,\n * handler: async ({ params, fetch }) => {\n * // params.id is typed as string (validated)\n * const user = await fetch(`/api/users/${params.id}`);\n * return user;\n * },\n * });\n * ```\n */\nexport function definePageLoad<\n TParamsSchema extends OptionalSchema = undefined,\n TQuerySchema extends OptionalSchema = undefined,\n TResult = unknown,\n>(\n options: DefinePageLoadOptions<TParamsSchema, TQuerySchema, TResult>,\n): (ctx: {\n params: H3EventContext['params'];\n req: H3Event['node']['req'];\n res: H3Event['node']['res'];\n fetch: $Fetch;\n event: H3Event;\n}) => Promise<TResult | Response> {\n type Params = InferSchema<TParamsSchema, H3EventContext['params']>;\n type Query = InferSchema<\n TQuerySchema,\n Record<string, string | string[] | undefined>\n >;\n\n return async (ctx: {\n params: H3EventContext['params'];\n req: H3Event['node']['req'];\n res: H3Event['node']['res'];\n fetch: $Fetch;\n event: H3Event;\n }) => {\n let params: unknown = ctx.params ?? {};\n\n const url = new URL(getRequestUrl(ctx.event), 'http://localhost');\n let query: unknown = parseSearchParams(url.searchParams);\n\n // Validate params\n if (options.params) {\n const result = await validateWithSchema(options.params, params);\n if (result.issues) {\n return fail(422, result.issues);\n }\n params = result.value;\n }\n\n // Validate query\n if (options.query) {\n const result = await validateWithSchema(options.query, query);\n if (result.issues) {\n return fail(422, result.issues);\n }\n query = result.value;\n }\n\n return options.handler({\n params: params as Params,\n query: query as Query,\n req: ctx.req,\n res: ctx.res,\n fetch: ctx.fetch,\n event: ctx.event,\n });\n };\n}\n","import type { StandardSchemaV1 } from './standard-schema';\nimport type { H3EventContext } from 'h3';\nimport type { PageServerAction } from './actions';\nimport { fail } from './actions';\nimport { parseRequestData } from './parse-request-data';\nimport { validateWithSchema } from './validate';\n\ntype OptionalSchema = StandardSchemaV1 | undefined;\ntype InferSchema<\n TSchema extends OptionalSchema,\n TFallback,\n> = TSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TSchema>\n : TFallback;\n\nexport interface DefineActionContext<\n TSchema extends OptionalSchema = undefined,\n TParamsSchema extends OptionalSchema = undefined,\n> {\n data: InferSchema<TSchema, Record<string, unknown>>;\n params: InferSchema<TParamsSchema, H3EventContext['params']>;\n req: PageServerAction['req'];\n res: PageServerAction['res'];\n fetch: PageServerAction['fetch'];\n event: PageServerAction['event'];\n}\n\nexport interface DefineActionOptions<\n TSchema extends OptionalSchema = undefined,\n TParamsSchema extends OptionalSchema = undefined,\n> {\n schema?: TSchema;\n params?: TParamsSchema;\n handler: (\n context: DefineActionContext<TSchema, TParamsSchema>,\n ) => Promise<Response> | Response;\n}\n\n/**\n * Creates a server action handler with Standard Schema input validation.\n *\n * Parses the request body (JSON or FormData) and validates it against the\n * provided schema before invoking the handler. On validation failure,\n * returns `fail(422, issues)` with `StandardSchemaV1.Issue[]`.\n * Repeated form fields are preserved as arrays instead of being collapsed\n * to the last value.\n *\n * @example\n * ```typescript\n * import { defineAction, json } from '@analogjs/router/server/actions';\n * import * as v from 'valibot';\n *\n * const Schema = v.object({\n * email: v.pipe(v.string(), v.email()),\n * });\n *\n * export const action = defineAction({\n * schema: Schema,\n * handler: async ({ data }) => {\n * // data is typed as { email: string }\n * return json({ ok: true });\n * },\n * });\n * ```\n */\nexport function defineAction<\n TSchema extends OptionalSchema = undefined,\n TParamsSchema extends OptionalSchema = undefined,\n>(options: DefineActionOptions<TSchema, TParamsSchema>) {\n type Params = InferSchema<TParamsSchema, H3EventContext['params']>;\n\n function getParams(\n params: H3EventContext['params'],\n ): Params | Record<string, never> {\n return (params ?? {}) as Params | Record<string, never>;\n }\n\n return async (ctx: PageServerAction): Promise<Response> => {\n const rawParams = getParams(ctx.params);\n\n if (options.params) {\n const paramsResult = await validateWithSchema(options.params, rawParams);\n if (paramsResult.issues) {\n return fail(422, paramsResult.issues);\n }\n return handleValidatedRequest(ctx, options, paramsResult.value as Params);\n }\n\n return handleValidatedRequest(ctx, options, rawParams as Params);\n };\n}\n\nasync function handleValidatedRequest<\n TSchema extends OptionalSchema = undefined,\n TParamsSchema extends OptionalSchema = undefined,\n>(\n ctx: PageServerAction,\n options: DefineActionOptions<TSchema, TParamsSchema>,\n params: InferSchema<TParamsSchema, H3EventContext['params']>,\n) {\n type Data = InferSchema<TSchema, Record<string, unknown>>;\n const body = await parseRequestData(ctx.event);\n\n let data: unknown = body;\n\n if (options.schema) {\n const result = await validateWithSchema(options.schema, body);\n if (result.issues) {\n return fail(422, result.issues);\n }\n data = result.value;\n }\n\n return options.handler({\n data: data as Data,\n params,\n req: ctx.req,\n res: ctx.res,\n fetch: ctx.fetch,\n event: ctx.event,\n });\n}\n","import type { StandardSchemaV1 } from './standard-schema';\nimport type { H3Event } from 'h3';\nimport { fail, json } from './actions';\nimport {\n getRequestUrl,\n parseRequestData,\n parseSearchParams,\n} from './parse-request-data';\nimport { validateWithSchema } from './validate';\n\nexport type DefineApiRouteResult = Response | unknown;\ntype OptionalSchema = StandardSchemaV1 | undefined;\ntype InferSchema<\n TSchema extends OptionalSchema,\n TFallback = unknown,\n> = TSchema extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TSchema>\n : TFallback;\ntype ResolveDataSchema<\n TInput extends OptionalSchema,\n TQuery extends OptionalSchema,\n TBody extends OptionalSchema,\n> = TInput extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TInput>\n : TQuery extends StandardSchemaV1\n ? TBody extends StandardSchemaV1\n ?\n | StandardSchemaV1.InferOutput<TQuery>\n | StandardSchemaV1.InferOutput<TBody>\n : StandardSchemaV1.InferOutput<TQuery>\n : TBody extends StandardSchemaV1\n ? StandardSchemaV1.InferOutput<TBody>\n : unknown;\n\nexport interface DefineApiRouteContext<\n TInput extends StandardSchemaV1 | undefined = undefined,\n TQuery extends StandardSchemaV1 | undefined = undefined,\n TBody extends StandardSchemaV1 | undefined = undefined,\n TParams extends StandardSchemaV1 | undefined = undefined,\n> {\n data: ResolveDataSchema<TInput, TQuery, TBody>;\n query: InferSchema<TQuery, undefined>;\n body: InferSchema<TBody, undefined>;\n params: InferSchema<TParams, H3Event['context']['params']>;\n event: H3Event;\n}\n\nexport interface DefineApiRouteOptions<\n TInput extends StandardSchemaV1 | undefined = undefined,\n TOutput extends StandardSchemaV1 | undefined = undefined,\n TQuery extends StandardSchemaV1 | undefined = undefined,\n TBody extends StandardSchemaV1 | undefined = undefined,\n TParams extends StandardSchemaV1 | undefined = undefined,\n TResult extends DefineApiRouteResult = DefineApiRouteResult,\n> {\n input?: TInput;\n query?: TQuery;\n body?: TBody;\n params?: TParams;\n output?: TOutput;\n handler: (\n context: DefineApiRouteContext<TInput, TQuery, TBody, TParams>,\n ) => Promise<TResult> | TResult;\n}\n\nfunction isDevEnvironment() {\n return (\n typeof process !== 'undefined' &&\n (process.env['NODE_ENV'] === 'development' ||\n process.env['NODE_ENV'] === 'test')\n );\n}\n\nfunction warnOnOutputIssues(issues: ReadonlyArray<StandardSchemaV1.Issue>) {\n console.warn(\n `[analog] API route output validation failed:\\n` +\n issues\n .map((i) => {\n const path = i.path\n ? ` at \"${i.path.map((p) => (typeof p === 'object' ? p.key : p)).join('.')}\"`\n : '';\n return ` - ${i.message}${path}`;\n })\n .join('\\n'),\n );\n}\n\n/**\n * Creates an h3-compatible event handler with Standard Schema validation.\n *\n * - `input` schema validates the request body (POST/PUT/PATCH) or query\n * params (GET). Returns 422 with `StandardSchemaV1.Issue[]` on failure.\n * - `output` schema validates the response in development and tests only. Logs a warning on mismatch.\n * - Plain return values are serialized with `json(...)`; raw `Response`\n * objects are returned unchanged.\n *\n * @example\n * ```typescript\n * import { defineApiRoute } from '@analogjs/router/server/actions';\n * import * as v from 'valibot';\n *\n * const Input = v.object({\n * name: v.pipe(v.string(), v.minLength(1)),\n * email: v.pipe(v.string(), v.email()),\n * });\n * const Output = v.object({\n * id: v.string(),\n * name: v.string(),\n * });\n *\n * export default defineApiRoute({\n * input: Input,\n * output: Output,\n * handler: async ({ data }) => {\n * const user = await db.users.create(data);\n * return user;\n * },\n * });\n * ```\n */\nexport function defineApiRoute<\n TInput extends StandardSchemaV1 | undefined = undefined,\n TOutput extends StandardSchemaV1 | undefined = undefined,\n TQuery extends StandardSchemaV1 | undefined = undefined,\n TBody extends StandardSchemaV1 | undefined = undefined,\n TParams extends StandardSchemaV1 | undefined = undefined,\n TResult extends DefineApiRouteResult = DefineApiRouteResult,\n>(\n options: DefineApiRouteOptions<\n TInput,\n TOutput,\n TQuery,\n TBody,\n TParams,\n TResult\n >,\n) {\n return async (event: H3Event): Promise<Response> => {\n const method = event.method.toUpperCase();\n let data: unknown;\n let query: unknown;\n let body: unknown;\n let params: unknown = event.context?.params ?? {};\n\n if (options.params) {\n const paramsResult = await validateWithSchema(options.params, params);\n if (paramsResult.issues) {\n return fail(422, paramsResult.issues);\n }\n params = paramsResult.value;\n }\n\n const requestData =\n options.input || (options.body && method !== 'GET' && method !== 'HEAD')\n ? await parseRequestData(event)\n : undefined;\n\n if (options.input) {\n data = requestData;\n\n const inputResult = await validateWithSchema(options.input, data);\n if (inputResult.issues) {\n return fail(422, inputResult.issues);\n }\n data = inputResult.value;\n }\n\n if (options.query) {\n const url = new URL(getRequestUrl(event), 'http://localhost');\n const queryResult = await validateWithSchema(\n options.query,\n parseSearchParams(url.searchParams),\n );\n if (queryResult.issues) {\n return fail(422, queryResult.issues);\n }\n query = queryResult.value;\n }\n\n if (options.body && method !== 'GET' && method !== 'HEAD') {\n body = requestData;\n const bodyResult = await validateWithSchema(options.body, body);\n if (bodyResult.issues) {\n return fail(422, bodyResult.issues);\n }\n body = bodyResult.value;\n }\n\n if (!options.input) {\n data =\n method === 'GET' || method === 'HEAD'\n ? query\n : body !== undefined\n ? body\n : query;\n }\n\n const result = await options.handler({\n data: data as ResolveDataSchema<TInput, TQuery, TBody>,\n query: query as InferSchema<TQuery, undefined>,\n body: body as InferSchema<TBody, undefined>,\n params: params as InferSchema<TParams, H3Event['context']['params']>,\n event,\n });\n\n if (result instanceof Response) {\n return result;\n }\n\n if (options.output && isDevEnvironment()) {\n const outputResult = await validateWithSchema(options.output, result);\n if (outputResult.issues) {\n warnOnOutputIssues(outputResult.issues);\n }\n }\n\n return json(result);\n };\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":["isDevEnvironment","warnOnOutputIssues"],"mappings":";;AAWM,SAAU,IAAI,CAAa,MAAc,EAAE,MAAS,EAAA;IACxD,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE;QAC1C,MAAM;AACN,QAAA,OAAO,EAAE;AACP,YAAA,iBAAiB,EAAE,MAAM;AAC1B,SAAA;AACF,KAAA,CAAC;AACJ;AAEM,SAAU,IAAI,CAAa,IAAO,EAAE,MAAqB,EAAA;IAC7D,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE;AACxC,QAAA,OAAO,EAAE;AACP,YAAA,cAAc,EAAE,iCAAiC;AAClD,SAAA;AACD,QAAA,GAAG,MAAM;AACV,KAAA,CAAC;AACJ;SAEgB,QAAQ,CAAC,GAAW,EAAE,SAAgC,GAAG,EAAA;AACvE,IAAA,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;AAC9B,QAAA,OAAO,IAAI,QAAQ,CAAC,IAAI,EAAE;AACxB,YAAA,MAAM,EAAE,MAAM;A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AC;AACnC,YAAA,IAAI,EAAE,IAAgD;AACtD,YAAA,KAAK,EAAE,KAAuC;AAC9C,YAAA,IAAI,EAAE,IAAqC;AAC3C,YAAA,MAAM,EAAE,MAA4D;YACpE,KAAK;AACN,SAAA,CAAC;AAEF,QAAA,IAAI,MAAM,YAAY,QAAQ,EAAE;AAC9B,YAAA,OAAO,MAAM;QACf;AAEA,QAAA,IAAI,OAAO,CAAC,MAAM,IAAI,gBAAgB,EAAE,EAAE;YACxC,MAAM,YAAY,GAAG,MAAM,kBAAkB,CAAC,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC;AACrE,YAAA,IAAI,YAAY,CAAC,MAAM,EAAE;AACvB,gBAAA,kBAAkB,CAAC,YAAY,CAAC,MAAM,CAAC;YACzC;QACF;AAEA,QAAA,OAAO,IAAI,CAAC,MAAM,CAAC;AACrB,IAAA,CAAC;AACH;;AC1NA;;AAEG;;;;"}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { makeEnvironmentProviders, ENVIRONMENT_INITIALIZER, inject, ApplicationRef, TransferState } from '@angular/core';
|
|
2
|
+
import { skipWhile, filter, take } from 'rxjs/operators';
|
|
3
|
+
import { QueryClient, dehydrate } from '@tanstack/angular-query-experimental';
|
|
4
|
+
import { ANALOG_QUERY_STATE_KEY, ANALOG_QUERIES_KEY } from '@analogjs/router/tanstack-query';
|
|
5
|
+
export { ANALOG_QUERIES_KEY } from '@analogjs/router/tanstack-query';
|
|
6
|
+
import { definePageLoad } from '@analogjs/router/server/actions';
|
|
7
|
+
|
|
8
|
+
function provideServerAnalogQuery() {
|
|
9
|
+
return makeEnvironmentProviders([
|
|
10
|
+
{
|
|
11
|
+
provide: ENVIRONMENT_INITIALIZER,
|
|
12
|
+
multi: true,
|
|
13
|
+
useValue() {
|
|
14
|
+
// Dehydrate the QueryClient into `TransferState` once the app
|
|
15
|
+
// becomes stable POST-RENDER on the server. `renderApplication`
|
|
16
|
+
// awaits `whenStable()` itself before invoking
|
|
17
|
+
// `BEFORE_APP_SERIALIZED` (which is where Angular's
|
|
18
|
+
// `TRANSFER_STATE_SERIALIZATION_PROVIDERS` reads the store and
|
|
19
|
+
// writes the `ng-state` script). Settling our write at the same
|
|
20
|
+
// point — but ahead of Angular's own subscriber — lets the
|
|
21
|
+
// dehydrated cache land in `TransferState` before the serializer
|
|
22
|
+
// snapshots it, so component-issued queries make it to the client
|
|
23
|
+
// without depending on provider declaration order.
|
|
24
|
+
//
|
|
25
|
+
// `skipWhile(stable => stable)` waits past the initial "no
|
|
26
|
+
// pending tasks yet" emission `BehaviorSubject` semantics give
|
|
27
|
+
// us at subscribe time; the next stable transition is the
|
|
28
|
+
// post-render one with all queries settled.
|
|
29
|
+
const appRef = inject(ApplicationRef);
|
|
30
|
+
const queryClient = inject(QueryClient);
|
|
31
|
+
const transferState = inject(TransferState);
|
|
32
|
+
const subscription = appRef.isStable
|
|
33
|
+
.pipe(skipWhile((stable) => stable), filter((stable) => stable), take(1))
|
|
34
|
+
.subscribe(() => {
|
|
35
|
+
transferState.set(ANALOG_QUERY_STATE_KEY, dehydrate(queryClient));
|
|
36
|
+
});
|
|
37
|
+
appRef.onDestroy(() => subscription.unsubscribe());
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
]);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Page load helper that prefetches TanStack Query queries inside the
|
|
45
|
+
* `.server.ts` handler and ships the dehydrated cache alongside any
|
|
46
|
+
* additional data. The router-side hydrator in `provideAnalogQuery()`
|
|
47
|
+
* merges the dehydrated payload into the active `QueryClient` on
|
|
48
|
+
* `ResolveEnd`, so components reading the same query options see a
|
|
49
|
+
* warm cache on first render.
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* ```ts
|
|
53
|
+
* // src/app/pages/posts.server.ts
|
|
54
|
+
* import { definePageLoadQueries } from '@analogjs/router/tanstack-query/server';
|
|
55
|
+
* import { queryOptions } from '@tanstack/angular-query-experimental';
|
|
56
|
+
*
|
|
57
|
+
* export const postsQuery = queryOptions({
|
|
58
|
+
* queryKey: ['posts'],
|
|
59
|
+
* queryFn: async ({ signal }) =>
|
|
60
|
+
* fetch('https://api.example.com/posts', { signal }).then((r) => r.json()),
|
|
61
|
+
* });
|
|
62
|
+
*
|
|
63
|
+
* export const load = definePageLoadQueries({
|
|
64
|
+
* handler: async ({ client }) => {
|
|
65
|
+
* await client.prefetchQuery(postsQuery);
|
|
66
|
+
* },
|
|
67
|
+
* });
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
function definePageLoadQueries(options) {
|
|
71
|
+
return definePageLoad({
|
|
72
|
+
params: options.params,
|
|
73
|
+
query: options.query,
|
|
74
|
+
handler: async (ctx) => {
|
|
75
|
+
const client = options.client?.() ?? new QueryClient();
|
|
76
|
+
const data = await options.handler({ ...ctx, client });
|
|
77
|
+
return {
|
|
78
|
+
[ANALOG_QUERIES_KEY]: dehydrate(client),
|
|
79
|
+
data,
|
|
80
|
+
};
|
|
81
|
+
},
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Generated bundle index. Do not edit.
|
|
87
|
+
*/
|
|
88
|
+
|
|
89
|
+
export { definePageLoadQueries, provideServerAnalogQuery };
|
|
90
|
+
//# sourceMappingURL=analogjs-router-tanstack-query-server.mjs.map
|