@faasjs/react 8.0.0-beta.27 → 8.0.0-beta.29

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/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ import { Component, ComponentProps, ComponentType, Dispatch, ErrorInfo, JSX, Rea
3
3
  import * as _$react_jsx_runtime0 from "react/jsx-runtime";
4
4
  import { FaasAction, FaasAction as FaasAction$1, FaasActionUnionType, FaasActionUnionType as FaasActionUnionType$1, FaasData, FaasData as FaasData$1, FaasParams, FaasParams as FaasParams$1 } from "@faasjs/types";
5
5
 
6
- //#region src/generateId/index.d.ts
6
+ //#region src/generate-id/index.d.ts
7
7
  /**
8
8
  * Generate a random identifier with an optional prefix.
9
9
  *
@@ -23,169 +23,7 @@ import { FaasAction, FaasAction as FaasAction$1, FaasActionUnionType, FaasAction
23
23
  */
24
24
  declare function generateId(prefix?: string, length?: number): string;
25
25
  //#endregion
26
- //#region src/browser/index.d.ts
27
- /**
28
- * Template literal type for URL strings that must end with a forward slash.
29
- *
30
- * Ensures that base URLs used in FaasJS requests always have a trailing '/' character,
31
- * which is required for proper URL construction when appending action paths.
32
- *
33
- * Notes:
34
- * - Type only accepts strings ending with '/' (e.g., 'https://api.example.com/', '/')
35
- * - Strings without trailing '/' will fail TypeScript type checking
36
- * - Used by FaasBrowserClient constructor and Options type
37
- * - Ensures consistent URL formatting across the codebase
38
- * - Throws Error at runtime if baseUrl doesn't end with '/'
39
- *
40
- * @see {@link FaasBrowserClient} for usage in client creation.
41
- * @see {@link Options} for usage in request options.
42
- */
43
- type BaseUrl = `${string}/`;
44
- /**
45
- * Configuration options for FaasJS requests.
46
- *
47
- * Extends the standard RequestInit interface with FaasJS-specific options for
48
- * customizing request behavior, adding request hooks, and overriding defaults.
49
- *
50
- * Notes:
51
- * - Options can be provided at client creation (defaultOptions) or per-request
52
- * - Per-request options override client default options
53
- * - headers are merged: per-request headers override default headers
54
- * - beforeRequest hook is called before the request is sent, allowing modification
55
- * - Custom request function completely replaces the default fetch implementation
56
- * - baseUrl in options overrides the client's baseUrl for this specific request
57
- * - When stream is true, returns the native fetch Response instead of wrapped Response
58
- *
59
- * @property {Record<string, string>} [headers] - Default headers to include in all requests.
60
- * Merged with client default headers, with per-request headers taking precedence.
61
- * Common headers include Content-Type, Authorization, and custom application headers.
62
- *
63
- * @property {Function} [beforeRequest] - Async hook called before sending each request.
64
- * Receives action, params, options, and headers, allowing modification before the request is sent.
65
- * Useful for logging, authentication, adding timestamps, or modifying headers dynamically.
66
- * Any changes to the headers object will affect the actual request.
67
- *
68
- * @property {Function} [request] - Custom request function to replace the default fetch.
69
- * Allows using alternative HTTP clients like axios, XMLHttpRequest, or custom implementations.
70
- * Receives the URL and parsed options, must return a Promise resolving to a Response object.
71
- * When provided, this function is used instead of the native fetch API.
72
- *
73
- * @property {BaseUrl} [baseUrl] - Optional override for the base URL for this specific request.
74
- * If provided, overrides the client's baseUrl. Must end with '/'.
75
- * Useful for making requests to different endpoints or environments from the same client instance.
76
- *
77
- * @property {boolean} [stream] - Enable streaming mode for large responses.
78
- * When true, returns the raw fetch Response object instead of a wrapped Response.
79
- * Useful for processing large data incrementally or working with binary data streams.
80
- * When false or undefined, returns a wrapped Response with automatic JSON parsing.
81
- *
82
- * @augments RequestInit
83
- * @see {@link FaasBrowserClient} for client creation.
84
- * @see {@link Response} for response object structure.
85
- */
86
- type Options = RequestInit & {
87
- headers?: Record<string, string>; /** Async hook called after request options are merged but before the request is sent. */
88
- beforeRequest?: ({
89
- action,
90
- params,
91
- options,
92
- headers
93
- }: {
94
- action: string;
95
- params?: Record<string, any> | undefined;
96
- options: Options;
97
- headers: Record<string, string>;
98
- }) => Promise<void>; /** Custom request implementation used instead of the native `fetch`. */
99
- request?: <PathOrData extends FaasActionUnionType$1>(url: string, options: Options) => Promise<Response<FaasData$1<PathOrData>>>; /** Base URL override for the current request. */
100
- baseUrl?: BaseUrl; /** When `true`, return the native fetch response so callers can consume the stream manually. */
101
- stream?: boolean;
102
- };
103
- /**
104
- * Simple key-value object for HTTP response headers.
105
- *
106
- * Represents headers as a plain object with string keys and string values.
107
- * Used by Response, ResponseError, and Options types.
108
- *
109
- * @property {string} [key] - Dynamic string keys for header names (e.g., 'Content-Type', 'Authorization').
110
- * Values must be strings. Multiple values for the same key are not supported.
111
- *
112
- * Notes:
113
- * - Headers are case-insensitive in HTTP but stored with exact casing in this object
114
- * - Common headers include: Content-Type, Authorization, x-faasjs-request-id, X-Custom-Header
115
- * - No support for multi-value headers (use comma-separated values instead)
116
- * - Used in Response, ResponseError, and Options types
117
- * - Simplified model compared to browser's Headers interface (no .get(), .set() methods)
118
- *
119
- * @see {@link Response} for usage in response objects.
120
- * @see {@link ResponseError} for usage in error objects.
121
- * @see {@link Options} for usage in request options.
122
- */
123
- type ResponseHeaders = {
124
- [key: string]: string;
125
- };
126
- /**
127
- * Type definition for the FaasBrowserClient.action method.
128
- *
129
- * Defines the signature of the method used to make requests to FaasJS functions.
130
- * Provides type-safe parameter and return value handling.
131
- *
132
- * @template PathOrData - The function path or data type for type safety
133
- *
134
- * @param {FaasAction<PathOrData>} action - The function path to call.
135
- * @param {FaasParams<PathOrData>} [params] - Optional parameters for the function.
136
- * @param {Options} [options] - Optional request overrides.
137
- * See {@link Options} for supported request fields such as `headers`, `beforeRequest`,
138
- * `request`, `baseUrl`, and `stream`.
139
- * @returns {Promise<Response<FaasData<PathOrData>> | Response>} Promise resolving to the request response. In streaming mode the runtime returns the native fetch response.
140
- *
141
- * Notes:
142
- * - Used internally by FaasBrowserClient.action method
143
- * - Provides type-safe action method signature
144
- * - Return type includes both typed and untyped Response variants
145
- * - Params are optional and can be undefined
146
- * - Options override client defaults when provided
147
- *
148
- * @see {@link FaasBrowserClient} for the class that uses this type.
149
- * @see {@link Response} for the return type.
150
- * @see {@link Options} for the options parameter type.
151
- */
152
- type FaasBrowserClientAction = <PathOrData extends FaasActionUnionType$1>(action: FaasAction$1<PathOrData>, params?: FaasParams$1<PathOrData>, options?: Options) => Promise<Response<FaasData$1<PathOrData>> | Response>;
153
- /**
154
- * Properties for creating a Response object.
155
- *
156
- * Defines the structure of response data that can be passed to the Response constructor
157
- * or returned from mock handlers.
158
- *
159
- * @template T - The type of the data property for type-safe response creation
160
- *
161
- * @property {number} [status] - The HTTP status code for the response.
162
- * Optional: defaults to 200 if data or body is provided, 204 otherwise.
163
- *
164
- * @property {ResponseHeaders} [headers] - The response headers as a key-value object.
165
- * Optional: defaults to an empty object if not provided.
166
- *
167
- * @property {any} [body] - The raw response body as a string or object.
168
- * Optional: if not provided, body is automatically populated from data using JSON.stringify.
169
- *
170
- * @property {T} [data] - The parsed JSON data to include in the response.
171
- * Optional: contains the response payload when JSON data is provided.
172
- *
173
- * Notes:
174
- * - All properties are optional
175
- * - At least one of data or body should be provided for meaningful responses
176
- * - The Response class automatically defaults status to 200 or 204 based on content
177
- * - If data is provided without body, body is automatically JSON.stringify(data)
178
- * - Used by Response constructor and mock handlers
179
- *
180
- * @see {@link Response} for the class that uses these properties.
181
- * @see {@link ResponseErrorProps} for error response properties.
182
- */
183
- type ResponseProps<T = any> = {
184
- status?: number;
185
- headers?: ResponseHeaders;
186
- body?: any;
187
- data?: T;
188
- };
26
+ //#region src/browser/response.d.ts
189
27
  /**
190
28
  * Wrapper class for HTTP responses from FaasJS functions.
191
29
  *
@@ -193,113 +31,6 @@ type ResponseProps<T = any> = {
193
31
  * body, and parsed data. Automatically handles JSON serialization and status code defaults.
194
32
  *
195
33
  * @template T - The type of the data property for type-safe response handling
196
- *
197
- * @property {number} status - The HTTP status code of the response.
198
- * Defaults to 200 if data or body is provided, 204 if neither is present.
199
- * @property {ResponseHeaders} headers - The response headers as a key-value object.
200
- * Empty object if no headers were provided.
201
- * @property {any} body - The raw response body as a string or object.
202
- * If data is provided without body, body is automatically set to JSON.stringify(data).
203
- * @property {T} [data] - The parsed JSON data from the response.
204
- * Optional property that contains the response payload when JSON is provided.
205
- *
206
- * Notes:
207
- * - status defaults to 200 if data or body is present, 204 otherwise
208
- * - body is automatically populated from data if not explicitly provided
209
- * - headers defaults to an empty object if not provided
210
- * - Use generic type parameter T for type-safe data access
211
- * - Commonly used as the return type from client.action() method
212
- * - Can be used in mock handlers to return structured responses
213
- * - The data property is optional and may be undefined for responses without data
214
- *
215
- * @example Create successful response with data
216
- * ```ts
217
- * const response = new Response({
218
- * status: 200,
219
- * data: {
220
- * id: 123,
221
- * name: 'John Doe'
222
- * }
223
- * })
224
- * console.log(response.status) // 200
225
- * console.log(response.data.name) // 'John Doe'
226
- * ```
227
- *
228
- * @example Create response with type safety
229
- * ```ts
230
- * interface User {
231
- * id: number
232
- * name: string
233
- * email: string
234
- * }
235
- *
236
- * const response = new Response<User>({
237
- * data: {
238
- * id: 123,
239
- * name: 'John',
240
- * email: 'john@example.com'
241
- * }
242
- * })
243
- * // TypeScript knows response.data.name is a string
244
- * ```
245
- *
246
- * @example Create response with headers
247
- * ```ts
248
- * const response = new Response({
249
- * status: 201,
250
- * data: { created: true },
251
- * headers: {
252
- * 'Content-Type': 'application/json',
253
- * 'x-faasjs-request-id': 'req-123',
254
- * 'X-Cache-Key': 'user-123'
255
- * }
256
- * })
257
- * ```
258
- *
259
- * @example Create response with custom body
260
- * ```ts
261
- * const response = new Response({
262
- * status: 200,
263
- * body: JSON.stringify({ custom: 'format' }),
264
- * headers: { 'Content-Type': 'application/json' }
265
- * })
266
- * ```
267
- *
268
- * @example Create empty response (204 No Content)
269
- * ```ts
270
- * const response = new Response()
271
- * // status: 204, headers: {}, body: undefined, data: undefined
272
- * ```
273
- *
274
- * @example Create error response
275
- * ```ts
276
- * const response = new Response({
277
- * status: 404,
278
- * data: {
279
- * error: {
280
- * message: 'User not found',
281
- * code: 'USER_NOT_FOUND'
282
- * }
283
- * }
284
- * })
285
- * ```
286
- *
287
- * @example Use in mock handler
288
- * ```ts
289
- * setMock(async (action, params) => {
290
- * if (action === 'user') {
291
- * return new Response({
292
- * status: 200,
293
- * data: { id: params.id, name: 'Mock User' }
294
- * })
295
- * }
296
- * return new Response({ status: 404, data: { error: 'Not found' } })
297
- * })
298
- * ```
299
- *
300
- * @see {@link ResponseProps} for response property type.
301
- * @see {@link ResponseError} for error response handling.
302
- * @see {@link FaasBrowserClient.action} for method returning Response.
303
34
  */
304
35
  declare class Response<T = any> {
305
36
  /**
@@ -320,121 +51,14 @@ declare class Response<T = any> {
320
51
  readonly data?: T;
321
52
  /**
322
53
  * Create a wrapped response object.
323
- *
324
- * @param {ResponseProps<T>} [props] - Response properties including status, headers, body, and data.
325
- * @param {number} [props.status] - HTTP status code. Defaults to `200` when `data` or `body` exists, otherwise `204`.
326
- * @param {ResponseHeaders} [props.headers] - Response headers keyed by header name.
327
- * @param {any} [props.body] - Raw response body to expose without additional parsing.
328
- * @param {T} [props.data] - Parsed response payload to expose on `response.data`.
329
- * @returns {Response<T>} Wrapped response instance.
330
54
  */
331
55
  constructor(props?: ResponseProps<T>);
332
56
  }
333
- /**
334
- * Input accepted by the {@link ResponseError} constructor.
335
- */
336
- type ResponseErrorProps = {
337
- /** User-facing error message. */message: string; /** HTTP status code reported for the error. @default 500 */
338
- status?: number; /** Response headers returned with the error. @default {} */
339
- headers?: ResponseHeaders; /** Raw error body or structured error payload. @default { error: { message } } */
340
- body?: any; /** Original error preserved when this instance wraps another exception. */
341
- originalError?: Error;
342
- };
343
57
  /**
344
58
  * Custom error class for handling HTTP response errors from FaasJS requests.
345
59
  *
346
60
  * Extends the built-in Error class to provide additional information about failed requests,
347
61
  * including HTTP status code, response headers, response body, and the original error.
348
- *
349
- * @augments Error
350
- *
351
- * @property {number} status - The HTTP status code of the failed response. Defaults to 500 if not provided.
352
- * @property {ResponseHeaders} headers - The response headers from the failed request.
353
- * @property {any} body - The response body containing error details or the original error if available.
354
- * @property {Error} [originalError] - The original Error object if this ResponseError was created from another Error.
355
- *
356
- * @example Basic error with message
357
- * ```ts
358
- * throw new ResponseError('User not found')
359
- * // or inside action method:
360
- * catch (error) {
361
- * throw new ResponseError(error.message)
362
- * }
363
- * ```
364
- *
365
- * @example Error from existing Error
366
- * ```ts
367
- * try {
368
- * await someOperation()
369
- * } catch (error) {
370
- * throw new ResponseError(error, {
371
- * status: 500,
372
- * headers: { 'X-Error-Type': 'internal' }
373
- * })
374
- * }
375
- * ```
376
- *
377
- * @example Error with complete response details
378
- * ```ts
379
- * throw new ResponseError({
380
- * message: 'Validation failed',
381
- * status: 400,
382
- * headers: { 'X-Error-Code': 'VALIDATION_ERROR' },
383
- * body: {
384
- * error: {
385
- * message: 'Validation failed',
386
- * fields: ['email', 'password']
387
- * }
388
- * }
389
- * })
390
- * ```
391
- *
392
- * @example Handling ResponseError in client
393
- * ```ts
394
- * try {
395
- * const response = await client.action('user', { id: 123 })
396
- * console.log(response.data)
397
- * } catch (error) {
398
- * if (error instanceof ResponseError) {
399
- * console.error(`Request failed: ${error.message}`)
400
- * console.error(`Status: ${error.status}`)
401
- * if (error.body) {
402
- * console.error('Error details:', error.body)
403
- * }
404
- * if (error.headers['x-faasjs-request-id']) {
405
- * console.error('Request ID:', error.headers['x-faasjs-request-id'])
406
- * }
407
- * }
408
- * }
409
- * ```
410
- *
411
- * @example Throwing ResponseError from mock
412
- * ```ts
413
- * setMock(async (action, params) => {
414
- * if (action === 'login') {
415
- * if (!params.email || !params.password) {
416
- * throw new ResponseError({
417
- * message: 'Email and password are required',
418
- * status: 400,
419
- * body: { error: 'missing_fields' }
420
- * })
421
- * }
422
- * return { data: { token: 'abc123' } }
423
- * }
424
- * })
425
- * ```
426
- *
427
- * Notes:
428
- * - ResponseError is automatically thrown by the action method when the server returns an error (status >= 400)
429
- * - The error message from server responses is extracted from body.error.message if available
430
- * - When created from an Error object, the original error is preserved in the originalError property
431
- * - The status property defaults to 500 if not explicitly provided
432
- * - Use instanceof ResponseError to distinguish FaasJS errors from other JavaScript errors
433
- * - The body property can contain structured error information from the server response
434
- *
435
- * @see {@link FaasBrowserClient.action} for how ResponseError is thrown in requests.
436
- * @see {@link ResponseProps} for the structure of response data.
437
- * @see {@link setMock} for mocking errors in tests.
438
62
  */
439
63
  declare class ResponseError extends Error {
440
64
  /**
@@ -455,219 +79,82 @@ declare class ResponseError extends Error {
455
79
  readonly originalError?: Error;
456
80
  /**
457
81
  * Create a ResponseError from a message, Error, or structured response error payload.
458
- *
459
- * @param {string | Error | ResponseErrorProps} data - Error message, Error object, or structured response error props.
460
- * @param {string} data.message - User-facing error message when `data` is a structured object.
461
- * @param {number} [data.status] - HTTP status code when `data` is a structured object.
462
- * @param {ResponseHeaders} [data.headers] - Response headers returned with the error when `data` is a structured object.
463
- * @param {any} [data.body] - Raw error body or structured error payload when `data` is a structured object.
464
- * @param {Error} [data.originalError] - Original error preserved on the instance when `data` is a structured object.
465
- * @param {Omit<ResponseErrorProps, 'message' | 'originalError'>} [options] - Additional options such as status, headers, and body.
466
- * @param {number} [options.status] - HTTP status override used when `data` is a string or `Error`.
467
- * @param {ResponseHeaders} [options.headers] - Response headers override used when `data` is a string or `Error`.
468
- * @param {any} [options.body] - Raw error body override used when `data` is a string or `Error`.
469
- * @returns {ResponseError} ResponseError instance.
470
82
  */
471
83
  constructor(data: string | Error, options?: Omit<ResponseErrorProps, 'message' | 'originalError'>);
472
84
  constructor(data: ResponseErrorProps);
473
85
  }
86
+ //#endregion
87
+ //#region src/browser/types.d.ts
474
88
  /**
475
- * Mock handler function type for testing FaasJS requests.
89
+ * Template literal type for URL strings that must end with a forward slash.
90
+ */
91
+ type BaseUrl = `${string}/`;
92
+ /**
93
+ * Configuration options for FaasJS requests.
476
94
  *
477
- * Defines the signature for functions that can mock API requests during testing.
478
- * Mock handlers receive request parameters and return simulated responses or errors.
479
- *
480
- * @param {string} action - The function path/action being requested (for example, `user` or `data/list`).
481
- * Converted to lowercase by the client before being passed to the handler.
482
- *
483
- * @param {Record<string, any> | undefined} params - The parameters passed to the action.
484
- * May be undefined if the action was called without parameters.
485
- * Parameters are passed as a plain object (already JSON-serialized if needed).
486
- *
487
- * @param {Options} options - The full request options including headers, beforeRequest hook, and other config.
488
- * Includes X-FaasJS-Request-Id header in the headers object.
489
- * Contains merged client defaults and per-request options.
490
- * See {@link Options} for supported request fields such as `headers`, `beforeRequest`,
491
- * `request`, `baseUrl`, and `stream`.
492
- *
493
- * @returns {Promise<ResponseProps> | Promise<void> | Promise<Error>} A promise resolving to:
494
- * - ResponseProps: Mock response data (status, headers, body, data)
495
- * - void: Returns an empty response (204 No Content)
496
- * - Error: Throws ResponseError when returning an Error object
497
- *
498
- * Notes:
499
- * - Used by setMock() function to mock API calls during tests
500
- * - Affects all FaasBrowserClient instances when set globally
501
- * - Can return different responses based on action or params
502
- * - Returning an Error object causes the action() method to reject with ResponseError
503
- * - Async function - must return a Promise
504
- * - Receives the fully merged options including default headers
505
- * @see {@link setMock} for setting up mock handlers.
506
- * @see {@link ResponseProps} for response structure.
507
- * @see {@link ResponseError} for error handling.
95
+ * Extends the standard RequestInit interface with FaasJS-specific options for
96
+ * customizing request behavior, adding request hooks, and overriding defaults.
97
+ */
98
+ type Options = RequestInit & {
99
+ headers?: Record<string, string>; /** Async hook called after request options are merged but before the request is sent. */
100
+ beforeRequest?: ({
101
+ action,
102
+ params,
103
+ options,
104
+ headers
105
+ }: {
106
+ action: string;
107
+ params?: Record<string, any> | undefined;
108
+ options: Options;
109
+ headers: Record<string, string>;
110
+ }) => Promise<void>; /** Custom request implementation used instead of the native `fetch`. */
111
+ request?: <PathOrData extends FaasActionUnionType$1>(url: string, options: Options) => Promise<Response<FaasData$1<PathOrData>>>; /** Base URL override for the current request. */
112
+ baseUrl?: BaseUrl; /** When `true`, return the native fetch response so callers can consume the stream manually. */
113
+ stream?: boolean;
114
+ };
115
+ /**
116
+ * Simple key-value object for HTTP response headers.
117
+ */
118
+ type ResponseHeaders = {
119
+ [key: string]: string;
120
+ };
121
+ /**
122
+ * Type definition for the FaasBrowserClient.action method.
123
+ */
124
+ type FaasBrowserClientAction = <PathOrData extends FaasActionUnionType$1>(action: FaasAction$1<PathOrData>, params?: FaasParams$1<PathOrData>, options?: Options) => Promise<Response<FaasData$1<PathOrData>> | Response>;
125
+ /**
126
+ * Properties for creating a Response object.
127
+ */
128
+ type ResponseProps<T = any> = {
129
+ status?: number;
130
+ headers?: ResponseHeaders;
131
+ body?: any;
132
+ data?: T;
133
+ };
134
+ /**
135
+ * Input accepted by the {@link ResponseError} constructor.
136
+ */
137
+ type ResponseErrorProps = {
138
+ /** User-facing error message. */message: string; /** HTTP status code reported for the error. @default 500 */
139
+ status?: number; /** Response headers returned with the error. @default {} */
140
+ headers?: ResponseHeaders; /** Raw error body or structured error payload. @default { error: { message } } */
141
+ body?: any; /** Original error preserved when this instance wraps another exception. */
142
+ originalError?: Error;
143
+ };
144
+ /**
145
+ * Mock handler function type for testing FaasJS requests.
508
146
  */
509
147
  type MockHandler = (action: string, params: Record<string, any> | undefined, options: Options) => Promise<ResponseProps> | Promise<void> | Promise<Error>;
148
+ //#endregion
149
+ //#region src/browser/mock.d.ts
510
150
  /**
511
151
  * Set the global mock handler used by all {@link FaasBrowserClient} instances.
512
- *
513
- * @param {MockHandler | ResponseProps | Response | null | undefined} handler - Mock handler, can be:
514
- * - MockHandler function: receives (action, params, options) and returns response data
515
- * - ResponseProps object: static response data
516
- * - Response instance: pre-configured Response object
517
- * - null or undefined: clear mock
518
- *
519
- * @example Reset in Vitest shared setup
520
- * ```ts
521
- * import { afterEach } from 'vitest'
522
- *
523
- * afterEach(() => {
524
- * setMock(null)
525
- * })
526
- * ```
527
- *
528
- * @example Use ResponseProps object
529
- * ```ts
530
- * setMock({
531
- * data: { name: 'FaasJS' },
532
- * })
533
- *
534
- * setMock({
535
- * status: 500,
536
- * data: { message: 'Internal Server Error' },
537
- * })
538
- * ```
539
- *
540
- * @example Use MockHandler function
541
- * ```ts
542
- * setMock(async (action) => {
543
- * if (action === '/pages/users/get') {
544
- * return { data: { id: 1, name: 'FaasJS' } }
545
- * }
546
- *
547
- * return { status: 404, data: { message: 'Not Found' } }
548
- * })
549
- *
550
- * const response = await client.action('/pages/users/get')
551
- * ```
552
- *
553
- * @example Branch by action and params
554
- * ```ts
555
- * setMock(async (action, params) => {
556
- * if (action === '/pages/users/get' && params?.id === 1) {
557
- * return { data: { id: 1, name: 'Admin' } }
558
- * }
559
- *
560
- * if (action === '/pages/users/get' && params?.id === 2) {
561
- * return { data: { id: 2, name: 'Editor' } }
562
- * }
563
- *
564
- * return { status: 404, data: { message: 'User not found' } }
565
- * })
566
- * ```
567
- *
568
- * @example Use Response instance
569
- * ```ts
570
- * setMock(new Response({
571
- * status: 200,
572
- * data: { result: 'success' }
573
- * }))
574
- * ```
575
- *
576
- * @example Streaming response
577
- * ```ts
578
- * setMock({
579
- * body: new ReadableStream({
580
- * start(controller) {
581
- * controller.enqueue(new TextEncoder().encode('hello'))
582
- * controller.enqueue(new TextEncoder().encode(' world'))
583
- * controller.close()
584
- * },
585
- * }),
586
- * })
587
- * ```
588
- *
589
- * @example Clear mock
590
- * ```ts
591
- * setMock(null)
592
- * ```
593
- *
594
- * @example Handle errors
595
- * ```ts
596
- * setMock(async () => {
597
- * throw new Error('Internal error')
598
- * })
599
- * // This will reject with ResponseError
600
- * ```
601
152
  */
602
153
  declare function setMock(handler: MockHandler | ResponseProps | Response | null | undefined): void;
154
+ //#endregion
155
+ //#region src/browser/client.d.ts
603
156
  /**
604
157
  * Browser client for FaasJS - provides HTTP client functionality for making API requests from web applications.
605
- *
606
- * @template PathOrData - Type parameter extending FaasActionUnionType for type-safe requests
607
- *
608
- * Features:
609
- * - Type-safe API requests with TypeScript support
610
- * - Built-in mock support for testing
611
- * - Custom request function support
612
- * - Request/response hooks (beforeRequest)
613
- * - Automatic error handling with ResponseError
614
- * - Streaming support for large responses
615
- * - Multiple instance support with unique IDs
616
- *
617
- * Notes:
618
- * - All requests are POST requests by default
619
- * - Automatically adds X-FaasJS-Request-Id header for request tracking
620
- * - baseUrl must end with '/' (will throw Error if not)
621
- * - Supports global mock via setMock() for testing all instances
622
- *
623
- * @example Basic usage
624
- * ```ts
625
- * import { FaasBrowserClient } from '@faasjs/react'
626
- *
627
- * const client = new FaasBrowserClient('http://localhost:8080/')
628
- * const response = await client.action('func', { key: 'value' })
629
- * console.log(response.data)
630
- * ```
631
- *
632
- * @example With custom headers and options
633
- * ```ts
634
- * const client = new FaasBrowserClient('https://api.example.com/', {
635
- * headers: { 'X-API-Key': 'secret' },
636
- * beforeRequest: async ({ action, params, headers }) => {
637
- * console.log(`Calling ${action} with params:`, params)
638
- * }
639
- * })
640
- * ```
641
- *
642
- * @example Multiple instances
643
- * ```ts
644
- * const apiClient = new FaasBrowserClient('https://api.example.com/')
645
- * const localClient = new FaasBrowserClient('http://localhost:3000/')
646
- *
647
- * const apiData = await apiClient.action('users')
648
- * const localData = await localClient.action('data')
649
- * ```
650
- *
651
- * @example Error handling
652
- * ```ts
653
- * const client = new FaasBrowserClient('https://api.example.com/')
654
- *
655
- * try {
656
- * const response = await client.action('user', { id: 123 })
657
- * console.log(response.data)
658
- * } catch (error) {
659
- * if (error instanceof ResponseError) {
660
- * console.error(`Request failed: ${error.message}`, error.status)
661
- * } else {
662
- * console.error('Unexpected error:', error)
663
- * }
664
- * }
665
- * ```
666
- *
667
- * @throws {Error} When baseUrl does not end with '/'
668
- *
669
- * @see {@link setMock} for testing support.
670
- * @see {@link ResponseError} for error handling.
671
158
  */
672
159
  declare class FaasBrowserClient {
673
160
  /**
@@ -684,166 +171,10 @@ declare class FaasBrowserClient {
684
171
  defaultOptions: Options;
685
172
  /**
686
173
  * Creates a new FaasBrowserClient instance.
687
- *
688
- * @param {BaseUrl} [baseUrl] - Base URL for all API requests. Must end with `/`. Defaults to `/` for relative requests.
689
- * @param {Options} [options] - Default request options such as headers, hooks, request override, or stream mode.
690
- * See {@link Options} for supported request fields such as `headers`, `beforeRequest`,
691
- * `request`, `baseUrl`, and `stream`.
692
- *
693
- * @example Basic initialization
694
- * ```ts
695
- * const client = new FaasBrowserClient('/')
696
- * ```
697
- *
698
- * @example With API endpoint
699
- * ```ts
700
- * const client = new FaasBrowserClient('https://api.example.com/')
701
- * ```
702
- *
703
- * @example With custom headers
704
- * ```ts
705
- * const client = new FaasBrowserClient('https://api.example.com/', {
706
- * headers: {
707
- * 'Authorization': 'Bearer token123',
708
- * 'X-Custom-Header': 'value'
709
- * }
710
- * })
711
- * ```
712
- *
713
- * @example With beforeRequest hook
714
- * ```ts
715
- * const client = new FaasBrowserClient('https://api.example.com/', {
716
- * beforeRequest: async ({ action, params, headers }) => {
717
- * console.log(`Requesting ${action}`, params)
718
- * // Modify headers before request
719
- * headers['X-Timestamp'] = Date.now().toString()
720
- * }
721
- * })
722
- * ```
723
- *
724
- * @example With custom request function
725
- * ```ts
726
- * import axios from 'axios'
727
- *
728
- * const client = new FaasBrowserClient('/', {
729
- * request: async (url, options) => {
730
- * const response = await axios.post(url, options.body, {
731
- * headers: options.headers
732
- * })
733
- * return new Response({
734
- * status: response.status,
735
- * headers: response.headers,
736
- * data: response.data
737
- * })
738
- * }
739
- * })
740
- * ```
741
- *
742
- * @throws {Error} When `baseUrl` does not end with `/`
743
174
  */
744
175
  constructor(baseUrl?: BaseUrl, options?: Options);
745
176
  /**
746
177
  * Makes a request to a FaasJS function.
747
- *
748
- * @template PathOrData - The function path or data type for type safety
749
- * @param {FaasAction<PathOrData>} action - The function path to call. Converted to lowercase when constructing the URL.
750
- * Must be a non-empty string.
751
- * @param {FaasParams<PathOrData>} [params] - The parameters to send to the function. Will be serialized as JSON.
752
- * Optional if the function accepts no parameters.
753
- * @param {Options} [options] - Optional request options that override client defaults.
754
- * Supports headers, beforeRequest hook, custom request function, baseUrl override, and streaming mode.
755
- * See {@link Options} for supported request fields such as `headers`, `beforeRequest`,
756
- * `request`, `baseUrl`, and `stream`.
757
- *
758
- * @returns {Promise<Response<FaasData<PathOrData>>>} A promise resolving to the wrapped FaasJS response. When `options.stream`
759
- * is `true`, the runtime returns the native fetch response so callers can read the stream.
760
- *
761
- * @throws {Error} When action is not provided or is empty
762
- * @throws {ResponseError} When the server returns an error response (status >= 400 or body.error exists)
763
- * @throws {Error} When the request fails before a response is received
764
- *
765
- * Notes:
766
- * - All requests are POST requests by default
767
- * - Action path is automatically converted to lowercase
768
- * - A unique request ID is generated for each request and sent in X-FaasJS-Request-Id header
769
- * - Headers are merged from client defaults and request options (request options take precedence)
770
- * - If a global mock is set via setMock(), it will be used instead of making real requests
771
- * - If a custom request function is provided in options, it will be used instead of fetch
772
- * - When stream option is true, returns the native fetch Response instead of a wrapped Response
773
- * - Response body is automatically parsed as JSON when possible
774
- * - Server errors (body.error) are automatically converted to ResponseError
775
- *
776
- * @example Basic request
777
- * ```ts
778
- * const response = await client.action('user', { id: 123 })
779
- * console.log(response.data)
780
- * ```
781
- *
782
- * @example With no parameters
783
- * ```ts
784
- * const response = await client.action('status')
785
- * console.log(response.data.status)
786
- * ```
787
- *
788
- * @example With custom options
789
- * ```ts
790
- * const response = await client.action('data', {
791
- * limit: 10,
792
- * offset: 0
793
- * }, {
794
- * headers: { 'X-Custom-Header': 'value' }
795
- * })
796
- * ```
797
- *
798
- * @example Streaming large response
799
- * ```ts
800
- * const response = await client.action('stream', {
801
- * format: 'json'
802
- * }, {
803
- * stream: true
804
- * })
805
- * // response is native fetch Response with streaming support
806
- * const reader = response.body.getReader()
807
- * ```
808
- *
809
- * @example With type safety
810
- * ```ts
811
- * interface UserData {
812
- * id: number
813
- * name: string
814
- * email: string
815
- * }
816
- *
817
- * const response = await client.action<UserData>('user', { id: 123 })
818
- * console.log(response.data.name) // TypeScript knows it's a string
819
- * ```
820
- *
821
- * @example Handling errors
822
- * ```ts
823
- * try {
824
- * const response = await client.action('user', { id: 123 })
825
- * console.log(response.data)
826
- * } catch (error) {
827
- * if (error instanceof ResponseError) {
828
- * console.error(`Server error: ${error.message}`, error.status)
829
- * if (error.body) console.error('Error details:', error.body)
830
- * } else {
831
- * console.error('Network error:', error)
832
- * }
833
- * }
834
- * ```
835
- *
836
- * @example Chaining requests
837
- * ```ts
838
- * const userId = await client.action('createUser', {
839
- * name: 'John',
840
- * email: 'john@example.com'
841
- * })
842
- *
843
- * const profile = await client.action('getProfile', {
844
- * userId: userId.data.id
845
- * })
846
- * ```
847
178
  */
848
179
  action<PathOrData extends FaasActionUnionType$1>(action: FaasAction$1<PathOrData>, params?: FaasParams$1<PathOrData>, options?: Options): Promise<Response<FaasData$1<PathOrData>>>;
849
180
  }
@@ -1079,7 +410,7 @@ type SharedUseFaasOptions<Params, Data> = {
1079
410
  *
1080
411
  * @template PathOrData - Action path or response data type used for inference.
1081
412
  */
1082
- type useFaasOptions<PathOrData extends FaasActionUnionType$1> = SharedUseFaasOptions<FaasParams$1<PathOrData>, FaasData$1<PathOrData>>;
413
+ type UseFaasOptions<PathOrData extends FaasActionUnionType$1> = SharedUseFaasOptions<FaasParams$1<PathOrData>, FaasData$1<PathOrData>>;
1083
414
  /**
1084
415
  * Request FaasJS data and keep request state in React state.
1085
416
  *
@@ -1091,8 +422,8 @@ type useFaasOptions<PathOrData extends FaasActionUnionType$1> = SharedUseFaasOpt
1091
422
  *
1092
423
  * @param {FaasAction<PathOrData>} action - Action path to invoke.
1093
424
  * @param {FaasParams<PathOrData>} defaultParams - Params used for the initial request and future reloads.
1094
- * @param {useFaasOptions<PathOrData>} [options] - Optional hook configuration such as controlled data, skip logic, debounce timing, polling, and base URL overrides.
1095
- * See the `useFaasOptions` type for `params`, `data`, `setData`, `skip`, `debounce`, `polling`, and `baseUrl`.
425
+ * @param {UseFaasOptions<PathOrData>} [options] - Optional hook configuration such as controlled data, skip logic, debounce timing, polling, and base URL overrides.
426
+ * See the `UseFaasOptions` type for `params`, `data`, `setData`, `skip`, `debounce`, `polling`, and `baseUrl`.
1096
427
  * @returns {FaasDataInjection<PathOrData>} Request state and helper methods described by {@link FaasDataInjection}.
1097
428
  *
1098
429
  * @example
@@ -1126,7 +457,7 @@ type useFaasOptions<PathOrData extends FaasActionUnionType$1> = SharedUseFaasOpt
1126
457
  * }
1127
458
  * ```
1128
459
  */
1129
- declare function useFaas<PathOrData extends FaasActionUnionType$1>(action: FaasAction$1<PathOrData>, defaultParams: FaasParams$1<PathOrData>, options?: useFaasOptions<PathOrData>): FaasDataInjection<PathOrData>;
460
+ declare function useFaas<PathOrData extends FaasActionUnionType$1>(action: FaasAction$1<PathOrData>, defaultParams: FaasParams$1<PathOrData>, options?: UseFaasOptions<PathOrData>): FaasDataInjection<PathOrData>;
1130
461
  //#endregion
1131
462
  //#region src/client.d.ts
1132
463
  /**
@@ -1236,7 +567,7 @@ declare function FaasReactClient(options?: FaasReactClientOptions): FaasReactCli
1236
567
  */
1237
568
  declare function getClient(host?: string): FaasReactClientInstance;
1238
569
  //#endregion
1239
- //#region src/constant/index.d.ts
570
+ //#region src/constants/index.d.ts
1240
571
  /**
1241
572
  * Returns a constant value that is created by the given function.
1242
573
  *
@@ -1477,7 +808,7 @@ declare namespace OptionalWrapper {
1477
808
  var displayName: string;
1478
809
  }
1479
810
  //#endregion
1480
- //#region src/splittingContext/index.d.ts
811
+ //#region src/splitting-context/index.d.ts
1481
812
  /**
1482
813
  * Create a context whose keys can be consumed independently.
1483
814
  *
@@ -1593,7 +924,7 @@ declare function createSplittingContext<T extends Record<string, any>>(defaultVa
1593
924
  use: <NewT extends T = T>(this: void) => Readonly<NewT>;
1594
925
  };
1595
926
  //#endregion
1596
- //#region src/splittingState/index.d.ts
927
+ //#region src/splitting-state/index.d.ts
1597
928
  /**
1598
929
  * Setter map generated by {@link useSplittingState} for each state key.
1599
930
  *
@@ -1734,4 +1065,4 @@ declare function usePrevious<T = any>(value: T): T | undefined;
1734
1065
  */
1735
1066
  declare function useStateRef<T = any>(initialValue?: T): [T | null, Dispatch<SetStateAction<T | null>>, RefObject<T | null>];
1736
1067
  //#endregion
1737
- export { BaseUrl, ErrorBoundary, ErrorBoundaryProps, ErrorChildrenProps, type FaasAction, type FaasActionUnionType, FaasBrowserClient, FaasBrowserClientAction, type FaasData, FaasDataInjection, FaasDataWrapper, FaasDataWrapperProps, FaasDataWrapperRef, type FaasParams, FaasReactClient, FaasReactClientInstance, FaasReactClientOptions, MockHandler, OnError, OptionalWrapper, OptionalWrapperProps, Options, Response, ResponseError, ResponseErrorProps, ResponseHeaders, ResponseProps, StateSetters, StatesWithSetters, UseFaasStreamOptions, UseFaasStreamResult, createSplittingContext, equal, faas, generateId, getClient, setMock, useConstant, useEqualCallback, useEqualEffect, useEqualMemo, useEqualMemoize, useFaas, useFaasOptions, useFaasStream, usePrevious, useSplittingState, useStateRef, withFaasData };
1068
+ export { type BaseUrl, ErrorBoundary, ErrorBoundaryProps, ErrorChildrenProps, type FaasAction, type FaasActionUnionType, FaasBrowserClient, type FaasBrowserClientAction, type FaasData, FaasDataInjection, FaasDataWrapper, FaasDataWrapperProps, FaasDataWrapperRef, type FaasParams, FaasReactClient, FaasReactClientInstance, FaasReactClientOptions, type MockHandler, OnError, OptionalWrapper, OptionalWrapperProps, type Options, Response, ResponseError, type ResponseErrorProps, type ResponseHeaders, type ResponseProps, StateSetters, StatesWithSetters, UseFaasOptions, UseFaasStreamOptions, UseFaasStreamResult, createSplittingContext, equal, faas, generateId, getClient, setMock, useConstant, useEqualCallback, useEqualEffect, useEqualMemo, useEqualMemoize, useFaas, useFaasStream, usePrevious, useSplittingState, useStateRef, withFaasData };