@faasjs/react 8.0.0-beta.19 → 8.0.0-beta.20

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.cjs DELETED
@@ -1,1852 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- let react = require("react");
3
- let react_jsx_runtime = require("react/jsx-runtime");
4
- //#region src/generateId.ts
5
- /**
6
- * Generate a random identifier with an optional prefix.
7
- *
8
- * @param prefix - Prefix prepended to the generated identifier.
9
- * @param length - Length of the generated identifier excluding `prefix`. Must be between `8` and `18`.
10
- * @returns Generated identifier string.
11
- * @throws {Error} When `length` is outside the supported `8` to `18` range.
12
- *
13
- * @example
14
- * ```ts
15
- * const id = generateId('prefix-')
16
- *
17
- * id.startsWith('prefix-') // true
18
- * ```
19
- */
20
- function generateId(prefix = "", length = 18) {
21
- if (length < 8 || length > 18) throw new Error("Length must be 8 ~ 18");
22
- return `${prefix}${Date.now().toString(36).padStart(8, "0")}${Math.random().toString(36).substring(2, length - 6).padEnd(length - 8, "0")}`;
23
- }
24
- //#endregion
25
- //#region src/browser.ts
26
- /**
27
- * Wrapper class for HTTP responses from FaasJS functions.
28
- *
29
- * Provides a consistent interface for handling server responses with status code, headers,
30
- * body, and parsed data. Automatically handles JSON serialization and status code defaults.
31
- *
32
- * @template T - The type of the data property for type-safe response handling
33
- *
34
- * @property {number} status - The HTTP status code of the response.
35
- * Defaults to 200 if data or body is provided, 204 if neither is present.
36
- * @property {ResponseHeaders} headers - The response headers as a key-value object.
37
- * Empty object if no headers were provided.
38
- * @property {any} body - The raw response body as a string or object.
39
- * If data is provided without body, body is automatically set to JSON.stringify(data).
40
- * @property {T} [data] - The parsed JSON data from the response.
41
- * Optional property that contains the response payload when JSON is provided.
42
- *
43
- * Notes:
44
- * - status defaults to 200 if data or body is present, 204 otherwise
45
- * - body is automatically populated from data if not explicitly provided
46
- * - headers defaults to an empty object if not provided
47
- * - Use generic type parameter T for type-safe data access
48
- * - Commonly used as the return type from client.action() method
49
- * - Can be used in mock handlers to return structured responses
50
- * - The data property is optional and may be undefined for responses without data
51
- *
52
- * @example Create successful response with data
53
- * ```ts
54
- * const response = new Response({
55
- * status: 200,
56
- * data: {
57
- * id: 123,
58
- * name: 'John Doe'
59
- * }
60
- * })
61
- * console.log(response.status) // 200
62
- * console.log(response.data.name) // 'John Doe'
63
- * ```
64
- *
65
- * @example Create response with type safety
66
- * ```ts
67
- * interface User {
68
- * id: number
69
- * name: string
70
- * email: string
71
- * }
72
- *
73
- * const response = new Response<User>({
74
- * data: {
75
- * id: 123,
76
- * name: 'John',
77
- * email: 'john@example.com'
78
- * }
79
- * })
80
- * // TypeScript knows response.data.name is a string
81
- * ```
82
- *
83
- * @example Create response with headers
84
- * ```ts
85
- * const response = new Response({
86
- * status: 201,
87
- * data: { created: true },
88
- * headers: {
89
- * 'Content-Type': 'application/json',
90
- * 'X-Request-Id': 'req-123',
91
- * 'X-Cache-Key': 'user-123'
92
- * }
93
- * })
94
- * ```
95
- *
96
- * @example Create response with custom body
97
- * ```ts
98
- * const response = new Response({
99
- * status: 200,
100
- * body: JSON.stringify({ custom: 'format' }),
101
- * headers: { 'Content-Type': 'application/json' }
102
- * })
103
- * ```
104
- *
105
- * @example Create empty response (204 No Content)
106
- * ```ts
107
- * const response = new Response()
108
- * // status: 204, headers: {}, body: undefined, data: undefined
109
- * ```
110
- *
111
- * @example Create error response
112
- * ```ts
113
- * const response = new Response({
114
- * status: 404,
115
- * data: {
116
- * error: {
117
- * message: 'User not found',
118
- * code: 'USER_NOT_FOUND'
119
- * }
120
- * }
121
- * })
122
- * ```
123
- *
124
- * @example Use in mock handler
125
- * ```ts
126
- * setMock(async (action, params) => {
127
- * if (action === 'user') {
128
- * return new Response({
129
- * status: 200,
130
- * data: { id: params.id, name: 'Mock User' }
131
- * })
132
- * }
133
- * return new Response({ status: 404, data: { error: 'Not found' } })
134
- * })
135
- * ```
136
- *
137
- * @see ResponseProps for response property type
138
- * @see ResponseError for error response handling
139
- * @see FaasBrowserClient.action for method returning Response
140
- */
141
- var Response = class {
142
- /**
143
- * HTTP status code exposed to callers.
144
- */
145
- status;
146
- /**
147
- * Response headers keyed by header name.
148
- */
149
- headers;
150
- /**
151
- * Raw response body.
152
- */
153
- body;
154
- /**
155
- * Parsed response payload when JSON data is available.
156
- */
157
- data;
158
- /**
159
- * Create a wrapped response object.
160
- *
161
- * @param props - Response properties including status, headers, body, and data.
162
- * @param props.status - HTTP status code. Defaults to `200` when `data` or `body` exists, otherwise `204`.
163
- * @param props.headers - Response headers keyed by header name.
164
- * @param props.body - Raw response body to expose without additional parsing.
165
- * @param props.data - Parsed response payload to expose on `response.data`.
166
- * @returns Wrapped response instance.
167
- */
168
- constructor(props = {}) {
169
- this.status = props.status || (props.data || props.body ? 200 : 204);
170
- this.headers = props.headers || {};
171
- this.body = props.body;
172
- if (props.data !== void 0) this.data = props.data;
173
- if (props.data && !props.body) this.body = JSON.stringify(props.data);
174
- }
175
- };
176
- /**
177
- * Custom error class for handling HTTP response errors from FaasJS requests.
178
- *
179
- * Extends the built-in Error class to provide additional information about failed requests,
180
- * including HTTP status code, response headers, response body, and the original error.
181
- *
182
- * @augments Error
183
- *
184
- * @property {number} status - The HTTP status code of the failed response. Defaults to 500 if not provided.
185
- * @property {ResponseHeaders} headers - The response headers from the failed request.
186
- * @property {any} body - The response body containing error details or the original error if available.
187
- * @property {Error} [originalError] - The original Error object if this ResponseError was created from another Error.
188
- *
189
- * @example Basic error with message
190
- * ```ts
191
- * throw new ResponseError('User not found')
192
- * // or inside action method:
193
- * catch (error) {
194
- * throw new ResponseError(error.message)
195
- * }
196
- * ```
197
- *
198
- * @example Error from existing Error
199
- * ```ts
200
- * try {
201
- * await someOperation()
202
- * } catch (error) {
203
- * throw new ResponseError(error, {
204
- * status: 500,
205
- * headers: { 'X-Error-Type': 'internal' }
206
- * })
207
- * }
208
- * ```
209
- *
210
- * @example Error with complete response details
211
- * ```ts
212
- * throw new ResponseError({
213
- * message: 'Validation failed',
214
- * status: 400,
215
- * headers: { 'X-Error-Code': 'VALIDATION_ERROR' },
216
- * body: {
217
- * error: {
218
- * message: 'Validation failed',
219
- * fields: ['email', 'password']
220
- * }
221
- * }
222
- * })
223
- * ```
224
- *
225
- * @example Handling ResponseError in client
226
- * ```ts
227
- * try {
228
- * const response = await client.action('user', { id: 123 })
229
- * console.log(response.data)
230
- * } catch (error) {
231
- * if (error instanceof ResponseError) {
232
- * console.error(`Request failed: ${error.message}`)
233
- * console.error(`Status: ${error.status}`)
234
- * if (error.body) {
235
- * console.error('Error details:', error.body)
236
- * }
237
- * if (error.headers['X-Request-Id']) {
238
- * console.error('Request ID:', error.headers['X-Request-Id'])
239
- * }
240
- * }
241
- * }
242
- * ```
243
- *
244
- * @example Throwing ResponseError from mock
245
- * ```ts
246
- * setMock(async (action, params) => {
247
- * if (action === 'login') {
248
- * if (!params.email || !params.password) {
249
- * throw new ResponseError({
250
- * message: 'Email and password are required',
251
- * status: 400,
252
- * body: { error: 'missing_fields' }
253
- * })
254
- * }
255
- * return { data: { token: 'abc123' } }
256
- * }
257
- * })
258
- * ```
259
- *
260
- * Notes:
261
- * - ResponseError is automatically thrown by the action method when the server returns an error (status >= 400)
262
- * - The error message from server responses is extracted from body.error.message if available
263
- * - When created from an Error object, the original error is preserved in the originalError property
264
- * - The status property defaults to 500 if not explicitly provided
265
- * - Use instanceof ResponseError to distinguish FaasJS errors from other JavaScript errors
266
- * - The body property can contain structured error information from the server response
267
- *
268
- * @see FaasBrowserClient.action for how ResponseError is thrown in requests
269
- * @see ResponseProps for the structure of response data
270
- * @see setMock for mocking errors in tests
271
- */
272
- var ResponseError = class extends Error {
273
- /**
274
- * HTTP status code reported for the failed request.
275
- */
276
- status;
277
- /**
278
- * Response headers returned with the error.
279
- */
280
- headers;
281
- /**
282
- * Raw error body or fallback error payload.
283
- */
284
- body;
285
- /**
286
- * Original error used to construct this instance, when available.
287
- */
288
- originalError;
289
- constructor(data, options) {
290
- let props;
291
- if (typeof data === "string") props = {
292
- message: data,
293
- ...options
294
- };
295
- else if (data instanceof Error || typeof data === "object" && data !== null && typeof data.constructor?.name === "string" && data.constructor.name.includes("Error")) props = {
296
- message: data.message,
297
- originalError: data,
298
- ...options
299
- };
300
- else props = data;
301
- super(props.message);
302
- this.status = props.status || 500;
303
- this.headers = props.headers || {};
304
- this.body = props.body || props.originalError || { error: { message: props.message } };
305
- if (props.originalError) this.originalError = props.originalError;
306
- }
307
- };
308
- let mock = null;
309
- /**
310
- * Set the global mock handler used by all {@link FaasBrowserClient} instances.
311
- *
312
- * @param handler - Mock handler, can be:
313
- * - MockHandler function: receives (action, params, options) and returns response data
314
- * - ResponseProps object: static response data
315
- * - Response instance: pre-configured Response object
316
- * - null or undefined: clear mock
317
- *
318
- * @example Reset in Vitest shared setup
319
- * ```ts
320
- * import { afterEach } from 'vitest'
321
- *
322
- * afterEach(() => {
323
- * setMock(null)
324
- * })
325
- * ```
326
- *
327
- * @example Use ResponseProps object
328
- * ```ts
329
- * setMock({
330
- * data: { name: 'FaasJS' },
331
- * })
332
- *
333
- * setMock({
334
- * status: 500,
335
- * data: { message: 'Internal Server Error' },
336
- * })
337
- * ```
338
- *
339
- * @example Use MockHandler function
340
- * ```ts
341
- * setMock(async (action) => {
342
- * if (action === '/pages/users/get') {
343
- * return { data: { id: 1, name: 'FaasJS' } }
344
- * }
345
- *
346
- * return { status: 404, data: { message: 'Not Found' } }
347
- * })
348
- *
349
- * const response = await client.action('/pages/users/get')
350
- * ```
351
- *
352
- * @example Branch by action and params
353
- * ```ts
354
- * setMock(async (action, params) => {
355
- * if (action === '/pages/users/get' && params?.id === 1) {
356
- * return { data: { id: 1, name: 'Admin' } }
357
- * }
358
- *
359
- * if (action === '/pages/users/get' && params?.id === 2) {
360
- * return { data: { id: 2, name: 'Editor' } }
361
- * }
362
- *
363
- * return { status: 404, data: { message: 'User not found' } }
364
- * })
365
- * ```
366
- *
367
- * @example Use Response instance
368
- * ```ts
369
- * setMock(new Response({
370
- * status: 200,
371
- * data: { result: 'success' }
372
- * }))
373
- * ```
374
- *
375
- * @example Streaming response
376
- * ```ts
377
- * setMock({
378
- * body: new ReadableStream({
379
- * start(controller) {
380
- * controller.enqueue(new TextEncoder().encode('hello'))
381
- * controller.enqueue(new TextEncoder().encode(' world'))
382
- * controller.close()
383
- * },
384
- * }),
385
- * })
386
- * ```
387
- *
388
- * @example Clear mock
389
- * ```ts
390
- * setMock(null)
391
- * ```
392
- *
393
- * @example Handle errors
394
- * ```ts
395
- * setMock(async () => {
396
- * throw new Error('Internal error')
397
- * })
398
- * // This will reject with ResponseError
399
- * ```
400
- */
401
- function setMock(handler) {
402
- mock = handler;
403
- }
404
- /**
405
- * Browser client for FaasJS - provides HTTP client functionality for making API requests from web applications.
406
- *
407
- * @template PathOrData - Type parameter extending FaasActionUnionType for type-safe requests
408
- *
409
- * Features:
410
- * - Type-safe API requests with TypeScript support
411
- * - Built-in mock support for testing
412
- * - Custom request function support
413
- * - Request/response hooks (beforeRequest)
414
- * - Automatic error handling with ResponseError
415
- * - Streaming support for large responses
416
- * - Multiple instance support with unique IDs
417
- *
418
- * Notes:
419
- * - All requests are POST requests by default
420
- * - Automatically adds X-FaasJS-Request-Id header for request tracking
421
- * - baseUrl must end with '/' (will throw Error if not)
422
- * - Supports global mock via setMock() for testing all instances
423
- *
424
- * @example Basic usage
425
- * ```ts
426
- * import { FaasBrowserClient } from '@faasjs/react'
427
- *
428
- * const client = new FaasBrowserClient('http://localhost:8080/')
429
- * const response = await client.action('func', { key: 'value' })
430
- * console.log(response.data)
431
- * ```
432
- *
433
- * @example With custom headers and options
434
- * ```ts
435
- * const client = new FaasBrowserClient('https://api.example.com/', {
436
- * headers: { 'X-API-Key': 'secret' },
437
- * beforeRequest: async ({ action, params, headers }) => {
438
- * console.log(`Calling ${action} with params:`, params)
439
- * }
440
- * })
441
- * ```
442
- *
443
- * @example Multiple instances
444
- * ```ts
445
- * const apiClient = new FaasBrowserClient('https://api.example.com/')
446
- * const localClient = new FaasBrowserClient('http://localhost:3000/')
447
- *
448
- * const apiData = await apiClient.action('users')
449
- * const localData = await localClient.action('data')
450
- * ```
451
- *
452
- * @example Error handling
453
- * ```ts
454
- * const client = new FaasBrowserClient('https://api.example.com/')
455
- *
456
- * try {
457
- * const response = await client.action('user', { id: 123 })
458
- * console.log(response.data)
459
- * } catch (error) {
460
- * if (error instanceof ResponseError) {
461
- * console.error(`Request failed: ${error.message}`, error.status)
462
- * } else {
463
- * console.error('Unexpected error:', error)
464
- * }
465
- * }
466
- * ```
467
- *
468
- * @throws {Error} When baseUrl does not end with '/'
469
- *
470
- * @see setMock for testing support
471
- * @see ResponseError for error handling
472
- */
473
- var FaasBrowserClient = class {
474
- /**
475
- * Unique identifier for this client instance.
476
- */
477
- id;
478
- /**
479
- * Base URL used to build action request URLs.
480
- */
481
- baseUrl;
482
- /**
483
- * Default request options merged into every request.
484
- */
485
- defaultOptions;
486
- /**
487
- * Creates a new FaasBrowserClient instance.
488
- *
489
- * @param baseUrl - Base URL for all API requests. Must end with `/`. Defaults to `/` for relative requests.
490
- * @param options - Default request options such as headers, hooks, request override, or stream mode.
491
- * See {@link Options} for supported request fields such as `headers`, `beforeRequest`,
492
- * `request`, `baseUrl`, and `stream`.
493
- *
494
- * @example Basic initialization
495
- * ```ts
496
- * const client = new FaasBrowserClient('/')
497
- * ```
498
- *
499
- * @example With API endpoint
500
- * ```ts
501
- * const client = new FaasBrowserClient('https://api.example.com/')
502
- * ```
503
- *
504
- * @example With custom headers
505
- * ```ts
506
- * const client = new FaasBrowserClient('https://api.example.com/', {
507
- * headers: {
508
- * 'Authorization': 'Bearer token123',
509
- * 'X-Custom-Header': 'value'
510
- * }
511
- * })
512
- * ```
513
- *
514
- * @example With beforeRequest hook
515
- * ```ts
516
- * const client = new FaasBrowserClient('https://api.example.com/', {
517
- * beforeRequest: async ({ action, params, headers }) => {
518
- * console.log(`Requesting ${action}`, params)
519
- * // Modify headers before request
520
- * headers['X-Timestamp'] = Date.now().toString()
521
- * }
522
- * })
523
- * ```
524
- *
525
- * @example With custom request function
526
- * ```ts
527
- * import axios from 'axios'
528
- *
529
- * const client = new FaasBrowserClient('/', {
530
- * request: async (url, options) => {
531
- * const response = await axios.post(url, options.body, {
532
- * headers: options.headers
533
- * })
534
- * return new Response({
535
- * status: response.status,
536
- * headers: response.headers,
537
- * data: response.data
538
- * })
539
- * }
540
- * })
541
- * ```
542
- *
543
- * @throws {Error} When `baseUrl` does not end with `/`
544
- */
545
- constructor(baseUrl = "/", options = Object.create(null)) {
546
- if (baseUrl && !baseUrl.endsWith("/")) throw Error("[FaasJS] baseUrl should end with /");
547
- this.id = `FBC-${generateId()}`;
548
- this.baseUrl = baseUrl;
549
- this.defaultOptions = options;
550
- console.debug(`[FaasJS] Initialize with baseUrl: ${this.baseUrl}`);
551
- }
552
- /**
553
- * Makes a request to a FaasJS function.
554
- *
555
- * @template PathOrData - The function path or data type for type safety
556
- * @param action - The function path to call. Converted to lowercase when constructing the URL.
557
- * Must be a non-empty string.
558
- * @param params - The parameters to send to the function. Will be serialized as JSON.
559
- * Optional if the function accepts no parameters.
560
- * @param options - Optional request options that override client defaults.
561
- * Supports headers, beforeRequest hook, custom request function, baseUrl override, and streaming mode.
562
- * See {@link Options} for supported request fields such as `headers`, `beforeRequest`,
563
- * `request`, `baseUrl`, and `stream`.
564
- *
565
- * @returns A promise resolving to the wrapped FaasJS response. When `options.stream`
566
- * is `true`, the runtime returns the native fetch response so callers can read the stream.
567
- *
568
- * @throws {Error} When action is not provided or is empty
569
- * @throws {ResponseError} When the server returns an error response (status >= 400 or body.error exists)
570
- * @throws {Error} When the request fails before a response is received
571
- *
572
- * Notes:
573
- * - All requests are POST requests by default
574
- * - Action path is automatically converted to lowercase
575
- * - A unique request ID is generated for each request and sent in X-FaasJS-Request-Id header
576
- * - Headers are merged from client defaults and request options (request options take precedence)
577
- * - If a global mock is set via setMock(), it will be used instead of making real requests
578
- * - If a custom request function is provided in options, it will be used instead of fetch
579
- * - When stream option is true, returns the native fetch Response instead of a wrapped Response
580
- * - Response body is automatically parsed as JSON when possible
581
- * - Server errors (body.error) are automatically converted to ResponseError
582
- *
583
- * @example Basic request
584
- * ```ts
585
- * const response = await client.action('user', { id: 123 })
586
- * console.log(response.data)
587
- * ```
588
- *
589
- * @example With no parameters
590
- * ```ts
591
- * const response = await client.action('status')
592
- * console.log(response.data.status)
593
- * ```
594
- *
595
- * @example With custom options
596
- * ```ts
597
- * const response = await client.action('data', {
598
- * limit: 10,
599
- * offset: 0
600
- * }, {
601
- * headers: { 'X-Custom-Header': 'value' }
602
- * })
603
- * ```
604
- *
605
- * @example Streaming large response
606
- * ```ts
607
- * const response = await client.action('stream', {
608
- * format: 'json'
609
- * }, {
610
- * stream: true
611
- * })
612
- * // response is native fetch Response with streaming support
613
- * const reader = response.body.getReader()
614
- * ```
615
- *
616
- * @example With type safety
617
- * ```ts
618
- * interface UserData {
619
- * id: number
620
- * name: string
621
- * email: string
622
- * }
623
- *
624
- * const response = await client.action<UserData>('user', { id: 123 })
625
- * console.log(response.data.name) // TypeScript knows it's a string
626
- * ```
627
- *
628
- * @example Handling errors
629
- * ```ts
630
- * try {
631
- * const response = await client.action('user', { id: 123 })
632
- * console.log(response.data)
633
- * } catch (error) {
634
- * if (error instanceof ResponseError) {
635
- * console.error(`Server error: ${error.message}`, error.status)
636
- * if (error.body) console.error('Error details:', error.body)
637
- * } else {
638
- * console.error('Network error:', error)
639
- * }
640
- * }
641
- * ```
642
- *
643
- * @example Chaining requests
644
- * ```ts
645
- * const userId = await client.action('createUser', {
646
- * name: 'John',
647
- * email: 'john@example.com'
648
- * })
649
- *
650
- * const profile = await client.action('getProfile', {
651
- * userId: userId.data.id
652
- * })
653
- * ```
654
- */
655
- async action(action, params, options) {
656
- if (!action) throw Error("[FaasJS] action required");
657
- const id = `F-${generateId()}`;
658
- const url = `${(options?.baseUrl || this.baseUrl) + action.toLowerCase()}?_=${id}`;
659
- if (!params) params = Object.create(null);
660
- if (!options) options = Object.create(null);
661
- const parsedOptions = {
662
- method: "POST",
663
- headers: { "Content-Type": "application/json; charset=UTF-8" },
664
- mode: "cors",
665
- credentials: "include",
666
- body: JSON.stringify(params),
667
- ...this.defaultOptions,
668
- ...options
669
- };
670
- if (!parsedOptions.headers["X-FaasJS-Request-Id"] && !parsedOptions.headers["x-faasjs-request-id"]) parsedOptions.headers["X-FaasJS-Request-Id"] = id;
671
- if (parsedOptions.beforeRequest) await parsedOptions.beforeRequest({
672
- action,
673
- params,
674
- options: parsedOptions,
675
- headers: parsedOptions.headers
676
- });
677
- if (mock) {
678
- console.debug(`[FaasJS] Mock request: ${action} %j`, params);
679
- if (typeof mock === "function") {
680
- const response = await mock(action, params, parsedOptions);
681
- if (response instanceof Error) return Promise.reject(new ResponseError(response));
682
- if (response instanceof Response) return response;
683
- return new Response(response || {});
684
- }
685
- if (mock instanceof Response) return mock;
686
- return new Response(mock || {});
687
- }
688
- if (parsedOptions.request) return parsedOptions.request(url, parsedOptions);
689
- if (parsedOptions.stream) return fetch(url, parsedOptions);
690
- return fetch(url, parsedOptions).then(async (response) => {
691
- const headers = {};
692
- for (const values of response.headers) headers[values[0]] = values[1];
693
- return response.text().then((res) => {
694
- if (response.status >= 200 && response.status < 300) {
695
- if (!res) return new Response({
696
- status: response.status,
697
- headers
698
- });
699
- const body = JSON.parse(res);
700
- if (body.error?.message) return Promise.reject(new ResponseError({
701
- message: body.error.message,
702
- status: response.status,
703
- headers,
704
- body
705
- }));
706
- return new Response({
707
- status: response.status,
708
- headers,
709
- body,
710
- data: body.data
711
- });
712
- }
713
- try {
714
- const body = JSON.parse(res);
715
- if (body.error?.message) return Promise.reject(new ResponseError({
716
- message: body.error.message,
717
- status: response.status,
718
- headers,
719
- body
720
- }));
721
- return Promise.reject(new ResponseError({
722
- message: res,
723
- status: response.status,
724
- headers,
725
- body
726
- }));
727
- } catch {
728
- return Promise.reject(new ResponseError({
729
- message: res,
730
- status: response.status,
731
- headers,
732
- body: res
733
- }));
734
- }
735
- });
736
- });
737
- }
738
- };
739
- //#endregion
740
- //#region src/faas.ts
741
- /**
742
- * Call the currently configured FaasReactClient.
743
- *
744
- * This helper forwards the request to `getClient`. When the registered
745
- * client defines `onError`, the hook is invoked before the promise rejects.
746
- *
747
- * @template PathOrData - Action path or response data type used for inference.
748
- *
749
- * @param action - Action path to invoke.
750
- * @param params - Parameters sent to the action.
751
- * @param options - Optional per-request overrides such as headers or base URL.
752
- * See the request `Options` type for supported fields such as `headers`, `beforeRequest`,
753
- * `request`, `baseUrl`, and `stream`.
754
- * @returns Response returned by the active browser client.
755
- * @throws {ResponseError} When the request fails and the active client does not recover inside `onError`.
756
- *
757
- * @example
758
- * ```ts
759
- * import { faas } from '@faasjs/react'
760
- *
761
- * const response = await faas('posts/get', { id: 1 })
762
- *
763
- * console.log(response.data.title)
764
- * ```
765
- */
766
- async function faas(action, params, options) {
767
- const client = getClient(options?.baseUrl);
768
- const onError = client.onError;
769
- if (onError) return client.browserClient.action(action, params, options).catch(async (res) => {
770
- await onError(action, params)(res);
771
- return Promise.reject(res);
772
- });
773
- return client.browserClient.action(action, params, options);
774
- }
775
- //#endregion
776
- //#region src/equal.ts
777
- const AsyncFunction = (async () => {}).constructor;
778
- /**
779
- * Compares two values for deep equality.
780
- *
781
- * This function checks if two values are deeply equal by comparing their types and contents.
782
- * It handles various data types including primitives, arrays, dates, regular expressions, functions,
783
- * maps, sets, and promises.
784
- *
785
- * @param a - The first value to compare.
786
- * @param b - The second value to compare.
787
- * @returns `true` if the values are deeply equal, `false` otherwise.
788
- *
789
- * @example
790
- * ```ts
791
- * import { equal } from '@faasjs/react'
792
- *
793
- * equal({ page: 1, filters: ['a'] }, { page: 1, filters: ['a'] }) // true
794
- * equal({ page: 1 }, { page: 2 }) // false
795
- * ```
796
- */
797
- function equal(a, b) {
798
- if (a === b) return true;
799
- if ((a === null || a === void 0) && (b === null || b === void 0)) return true;
800
- if (typeof a !== typeof b) return false;
801
- if (a === null || a === void 0 || b === null || b === void 0) return false;
802
- const ctor = a.constructor;
803
- if (ctor !== b.constructor) return false;
804
- switch (ctor) {
805
- case String:
806
- case Boolean: return a === b;
807
- case Number: return Number.isNaN(a) && Number.isNaN(b) || a === b;
808
- case Array:
809
- if (a.length !== b.length) return false;
810
- for (let i = 0; i < a.length; i++) if (!equal(a[i], b[i])) return false;
811
- return true;
812
- case Date: return a.getTime() === b.getTime();
813
- case RegExp:
814
- case Function:
815
- case AsyncFunction: return a.toString() === b.toString();
816
- case Map:
817
- case Set: return equal(Array.from(a), Array.from(b));
818
- case Promise: return a === b;
819
- case Object:
820
- for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) if (!equal(a[key], b[key])) return false;
821
- return true;
822
- default: throw Error(`Unsupported type: ${ctor}`);
823
- }
824
- }
825
- /**
826
- * Custom hook that memoizes a value using deep equality comparison.
827
- *
828
- * @param value - The value to be memoized.
829
- * @returns The memoized value.
830
- *
831
- * @example
832
- * ```tsx
833
- * import { useEqualMemoize } from '@faasjs/react'
834
- *
835
- * function Filters({ filters }: { filters: Record<string, any> }) {
836
- * const memoizedFilters = useEqualMemoize(filters)
837
- *
838
- * return <pre>{JSON.stringify(memoizedFilters)}</pre>
839
- * }
840
- * ```
841
- */
842
- function useEqualMemoize(value) {
843
- const ref = (0, react.useRef)(value);
844
- if (!equal(value, ref.current)) ref.current = value;
845
- return ref.current;
846
- }
847
- function useEqualSignal(value) {
848
- const ref = (0, react.useRef)(value);
849
- const signalRef = (0, react.useRef)(0);
850
- if (!equal(value, ref.current)) {
851
- ref.current = value;
852
- signalRef.current += 1;
853
- }
854
- return signalRef.current;
855
- }
856
- /**
857
- * Custom hook that works like `useEffect` but uses deep comparison on dependencies.
858
- *
859
- * @param callback - The effect callback function to run.
860
- * @param dependencies - The list of dependencies for the effect.
861
- * @returns The result of the `useEffect` hook with memoized dependencies.
862
- *
863
- * @example
864
- * ```tsx
865
- * import { useEqualEffect } from '@faasjs/react'
866
- *
867
- * function Page({ filters }: { filters: Record<string, any> }) {
868
- * useEqualEffect(() => {
869
- * console.log('filters changed', filters)
870
- * }, [filters])
871
- *
872
- * return null
873
- * }
874
- * ```
875
- */
876
- function useEqualEffect(callback, dependencies) {
877
- return (0, react.useEffect)(callback, [useEqualSignal(dependencies)]);
878
- }
879
- /**
880
- * Custom hook that works like `useMemo` but uses deep comparison on dependencies.
881
- *
882
- * @template T - Memoized value type returned by the callback.
883
- *
884
- * @param callback - The callback function to run.
885
- * @param dependencies - The list of dependencies.
886
- * @returns The result of the `useMemo` hook with memoized dependencies.
887
- *
888
- * @example
889
- * ```tsx
890
- * import { useEqualMemo } from '@faasjs/react'
891
- *
892
- * function Page({ filters }: { filters: Record<string, any> }) {
893
- * const queryString = useEqualMemo(() => JSON.stringify(filters), [filters])
894
- *
895
- * return <span>{queryString}</span>
896
- * }
897
- * ```
898
- */
899
- function useEqualMemo(callback, dependencies) {
900
- const signal = useEqualSignal(dependencies);
901
- const callbackRef = (0, react.useRef)(callback);
902
- callbackRef.current = callback;
903
- return (0, react.useMemo)(() => {
904
- return callbackRef.current();
905
- }, [signal]);
906
- }
907
- /**
908
- * Custom hook that works like `useCallback` but uses deep comparison on dependencies.
909
- *
910
- * @template T - Callback signature to memoize.
911
- *
912
- * @param callback - The callback function to run.
913
- * @param dependencies - The list of dependencies.
914
- * @returns The result of the `useCallback` hook with memoized dependencies.
915
- *
916
- * @example
917
- * ```tsx
918
- * import { useEqualCallback } from '@faasjs/react'
919
- *
920
- * function Search({ filters }: { filters: Record<string, any> }) {
921
- * const handleSubmit = useEqualCallback(() => {
922
- * console.log(filters)
923
- * }, [filters])
924
- *
925
- * return <button onClick={handleSubmit}>Search</button>
926
- * }
927
- * ```
928
- */
929
- function useEqualCallback(callback, dependencies) {
930
- return (0, react.useCallback)((...args) => callback(...args), [useEqualSignal(dependencies)]);
931
- }
932
- //#endregion
933
- //#region src/FaasDataWrapper.tsx
934
- const fixedForwardRef = react.forwardRef;
935
- /**
936
- * Fetch FaasJS data and inject the result into a render prop or child element.
937
- *
938
- * The wrapper defers rendering `children` or `render` until the first request
939
- * completes, then keeps passing the latest request state to the rendered output.
940
- *
941
- * @param props - Wrapper props controlling the request and rendered fallback.
942
- * @param props.render - Render prop that receives the resolved Faas request state.
943
- * @param props.children - Child element cloned with injected Faas request state.
944
- * @param props.fallback - Element rendered before the first successful load.
945
- * @param props.action - Action path to request.
946
- * @param props.params - Params sent to the action.
947
- * @param props.onDataChange - Callback invoked when the resolved data value changes.
948
- * @param props.data - Controlled data value used instead of internal state.
949
- * @param props.setData - Controlled setter used instead of internal state.
950
- * @param props.baseUrl - Base URL override used for this wrapper instance.
951
- *
952
- * @example
953
- * ```tsx
954
- * import { FaasDataWrapper } from '@faasjs/react'
955
- *
956
- * type User = {
957
- * name: string
958
- * }
959
- *
960
- * function UserView(props: {
961
- * data?: User
962
- * error?: Error
963
- * reload?: () => void
964
- * }) {
965
- * if (props.error) {
966
- * return (
967
- * <div>
968
- * <p>Failed to load user: {props.error.message}</p>
969
- * <button type="button" onClick={() => props.reload?.()}>
970
- * Retry
971
- * </button>
972
- * </div>
973
- * )
974
- * }
975
- *
976
- * return <div>Hello, {props.data?.name}</div>
977
- * }
978
- *
979
- * // Render-prop mode
980
- * export function UserProfile(props: { id: number }) {
981
- * return (
982
- * <FaasDataWrapper<User>
983
- * action="/pages/users/get"
984
- * params={{ id: props.id }}
985
- * fallback={<div>Loading user...</div>}
986
- * render={({ data, error, reload }) => {
987
- * if (error) {
988
- * return (
989
- * <div>
990
- * <p>Failed to load user: {error.message}</p>
991
- * <button type="button" onClick={() => reload()}>
992
- * Retry
993
- * </button>
994
- * </div>
995
- * )
996
- * }
997
- *
998
- * return <div>Hello, {data.name}</div>
999
- * }}
1000
- * />
1001
- * )
1002
- * }
1003
- *
1004
- * // Children injection mode
1005
- * export function UserProfileWithChildren(props: { id: number }) {
1006
- * return (
1007
- * <FaasDataWrapper<User>
1008
- * action="/pages/users/get"
1009
- * params={{ id: props.id }}
1010
- * fallback={<div>Loading user...</div>}
1011
- * >
1012
- * <UserView />
1013
- * </FaasDataWrapper>
1014
- * )
1015
- * }
1016
- * ```
1017
- *
1018
- * When a ref is provided, it exposes the current Faas request state imperatively.
1019
- */
1020
- const FaasDataWrapper = fixedForwardRef((props, ref) => {
1021
- const requestOptions = {
1022
- ...props.data !== void 0 ? { data: props.data } : {},
1023
- ...props.setData ? { setData: props.setData } : {}
1024
- };
1025
- const request = getClient(props.baseUrl).useFaas(props.action, props.params ?? {}, requestOptions);
1026
- const [loaded, setLoaded] = (0, react.useState)(false);
1027
- (0, react.useImperativeHandle)(ref, () => request, [request]);
1028
- useEqualEffect(() => {
1029
- if (!request.loading) setLoaded((prev) => prev === false ? true : prev);
1030
- }, [request.loading]);
1031
- useEqualEffect(() => {
1032
- if (props.onDataChange) props.onDataChange(request);
1033
- }, [request.data]);
1034
- return useEqualMemo(() => {
1035
- if (loaded) {
1036
- if (props.children) return (0, react.cloneElement)(props.children, request);
1037
- if (props.render) return props.render(request);
1038
- }
1039
- return props.fallback || null;
1040
- }, [
1041
- loaded,
1042
- request.action,
1043
- request.params,
1044
- request.data,
1045
- request.error,
1046
- request.loading
1047
- ]);
1048
- });
1049
- Object.assign(FaasDataWrapper, { displayName: "FaasDataWrapper" });
1050
- /**
1051
- * Wrap a component with {@link FaasDataWrapper} and inject Faas request state as props.
1052
- *
1053
- * `withFaasData` is most useful for wrapper-style exports or compatibility with
1054
- * an existing component boundary. For new code, prefer `useFaas` or
1055
- * `FaasDataWrapper` when they express the request ownership more directly.
1056
- *
1057
- * @template PathOrData - Action path or response data type used for inference.
1058
- * @template TComponentProps - Component props including injected Faas data fields.
1059
- * @param Component - Component that consumes injected Faas data props.
1060
- * @param faasProps - Request configuration forwarded to `FaasDataWrapper`.
1061
- * @returns Component that accepts the original props minus the injected Faas data fields.
1062
- *
1063
- * @example
1064
- * ```tsx
1065
- * import { withFaasData } from '@faasjs/react'
1066
- *
1067
- * const MyComponent = withFaasData(
1068
- * ({ data, error, reload }) => {
1069
- * if (error) {
1070
- * return (
1071
- * <button type="button" onClick={() => reload()}>
1072
- * Retry
1073
- * </button>
1074
- * )
1075
- * }
1076
- *
1077
- * return <div>{data.name}</div>
1078
- * },
1079
- * { action: '/pages/users/get', params: { id: 1 } },
1080
- * )
1081
- * ```
1082
- */
1083
- function withFaasData(Component, faasProps) {
1084
- return (props) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FaasDataWrapper, {
1085
- ...faasProps,
1086
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Component, { ...props })
1087
- });
1088
- }
1089
- //#endregion
1090
- //#region src/useFaas.tsx
1091
- /**
1092
- * Request FaasJS data and keep request state in React state.
1093
- *
1094
- * `useFaas` is the default hook for standard FaasJS request-response flows in React.
1095
- * It sends an initial request unless `skip` is enabled, and returns request state
1096
- * plus helpers for reloading, updating data, and handling errors.
1097
- *
1098
- * @template PathOrData - Action path or response data type used for inference.
1099
- *
1100
- * @param action - Action path to invoke.
1101
- * @param defaultParams - Params used for the initial request and future reloads.
1102
- * @param options - Optional hook configuration such as controlled data, debounce, and skip logic.
1103
- * @param options.params - Request params override used without mutating the hook's stored params state.
1104
- * @param options.data - Controlled data value used instead of the hook's internal state.
1105
- * @param options.setData - Controlled setter used instead of the hook's internal `setData`.
1106
- * @param options.skip - Boolean or predicate that suppresses the automatic request until `reload()` runs.
1107
- * @param options.debounce - Milliseconds to wait before sending the latest request.
1108
- * @param options.baseUrl - Base URL override used for this hook instance.
1109
- * @returns Request state and helper methods described by {@link FaasDataInjection}.
1110
- *
1111
- * @example
1112
- * ```tsx
1113
- * import { useFaas } from '@faasjs/react'
1114
- *
1115
- * function Profile({ id }: { id: number }) {
1116
- * const { data, error, loading, reload } = useFaas('/pages/users/get', { id })
1117
- *
1118
- * if (loading) return <div>Loading...</div>
1119
- *
1120
- * if (error) {
1121
- * return (
1122
- * <div>
1123
- * <div>Load failed: {error.message}</div>
1124
- * <button type="button" onClick={() => reload()}>
1125
- * Retry
1126
- * </button>
1127
- * </div>
1128
- * )
1129
- * }
1130
- *
1131
- * return (
1132
- * <div>
1133
- * <span>{data.name}</span>
1134
- * <button type="button" onClick={() => reload()}>
1135
- * Refresh
1136
- * </button>
1137
- * </div>
1138
- * )
1139
- * }
1140
- * ```
1141
- */
1142
- function useFaas(action, defaultParams, options = {}) {
1143
- const [loading, setLoading] = (0, react.useState)(true);
1144
- const [data, setData] = (0, react.useState)();
1145
- const [error, setError] = (0, react.useState)();
1146
- const [params, setParams] = (0, react.useState)(defaultParams);
1147
- const [reloadTimes, setReloadTimes] = (0, react.useState)(0);
1148
- const [fails, setFails] = (0, react.useState)(0);
1149
- const [skip, setSkip] = (0, react.useState)(typeof options.skip === "function" ? options.skip(defaultParams) : options.skip);
1150
- const promiseRef = (0, react.useRef)(null);
1151
- const controllerRef = (0, react.useRef)(null);
1152
- const localSetData = setData;
1153
- const pendingReloadsRef = (0, react.useRef)(/* @__PURE__ */ new Map());
1154
- const reloadCounterRef = (0, react.useRef)(0);
1155
- useEqualEffect(() => {
1156
- setSkip(typeof options.skip === "function" ? options.skip(params) : options.skip);
1157
- }, [typeof options.skip === "function" ? params : options.skip]);
1158
- useEqualEffect(() => {
1159
- if (!equal(defaultParams, params)) setParams(defaultParams);
1160
- }, [defaultParams]);
1161
- useEqualEffect(() => {
1162
- if (!action || skip) {
1163
- setLoading(false);
1164
- return;
1165
- }
1166
- setLoading(true);
1167
- const controller = new AbortController();
1168
- controllerRef.current = controller;
1169
- const client = getClient(options.baseUrl);
1170
- const requestParams = options.params ?? params;
1171
- function send() {
1172
- const request = client.faas(action, requestParams, { signal: controller.signal });
1173
- promiseRef.current = request;
1174
- request.then((r) => {
1175
- const nextData = r.data;
1176
- setFails(0);
1177
- setError(null);
1178
- if (options.setData) options.setData(nextData);
1179
- else localSetData(nextData);
1180
- setLoading(false);
1181
- for (const { resolve } of pendingReloadsRef.current.values()) resolve(nextData);
1182
- pendingReloadsRef.current.clear();
1183
- }).catch(async (e) => {
1184
- if (typeof e?.message === "string" && e.message.toLowerCase().indexOf("aborted") >= 0) return;
1185
- if (!fails && typeof e?.message === "string" && e.message.indexOf("Failed to fetch") >= 0) {
1186
- console.warn(`FaasReactClient: ${e.message} retry...`);
1187
- setFails(1);
1188
- return send();
1189
- }
1190
- let error = e;
1191
- if (client.onError) try {
1192
- await client.onError(action, requestParams)(e);
1193
- } catch (newError) {
1194
- error = newError;
1195
- }
1196
- setError(error);
1197
- setLoading(false);
1198
- for (const { reject } of pendingReloadsRef.current.values()) reject(error);
1199
- pendingReloadsRef.current.clear();
1200
- });
1201
- }
1202
- if (options.debounce) {
1203
- const timeout = setTimeout(send, options.debounce);
1204
- return () => {
1205
- clearTimeout(timeout);
1206
- controllerRef.current?.abort();
1207
- setLoading(false);
1208
- };
1209
- }
1210
- send();
1211
- return () => {
1212
- controllerRef.current?.abort();
1213
- setLoading(false);
1214
- };
1215
- }, [
1216
- action,
1217
- options.params || params,
1218
- reloadTimes,
1219
- skip
1220
- ]);
1221
- const reload = useEqualCallback((params) => {
1222
- if (skip) setSkip(false);
1223
- if (params) setParams(params);
1224
- const reloadCounter = ++reloadCounterRef.current;
1225
- return new Promise((resolve, reject) => {
1226
- pendingReloadsRef.current.set(reloadCounter, {
1227
- resolve,
1228
- reject
1229
- });
1230
- setReloadTimes((prev) => prev + 1);
1231
- });
1232
- }, [params, skip]);
1233
- const currentData = options.data ?? data;
1234
- const currentPromise = promiseRef.current ?? Promise.resolve({});
1235
- return {
1236
- action,
1237
- params,
1238
- loading,
1239
- data: currentData,
1240
- reloadTimes,
1241
- error,
1242
- promise: currentPromise,
1243
- reload,
1244
- setData: options.setData ?? localSetData,
1245
- setLoading,
1246
- setPromise: (newPromise) => {
1247
- promiseRef.current = typeof newPromise === "function" ? newPromise(currentPromise) : newPromise;
1248
- },
1249
- setError
1250
- };
1251
- }
1252
- //#endregion
1253
- //#region src/client.tsx
1254
- const clients = {};
1255
- /**
1256
- * Create and register a FaasReactClient instance.
1257
- *
1258
- * The returned client is stored by `baseUrl` and becomes the default client
1259
- * used by helpers such as {@link faas} and {@link useFaas}.
1260
- *
1261
- * @param options - Client configuration including base URL, default request options, and error hooks.
1262
- * @param options.baseUrl - Base URL used to register and route the client instance.
1263
- * @param options.options - Default browser-client request options forwarded to `FaasBrowserClient`.
1264
- * @param options.onError - Hook factory used to handle failed `faas` and `useFaas` requests.
1265
- * See {@link Options} for supported browser-client request fields such as `headers`,
1266
- * `beforeRequest`, `request`, `baseUrl`, and `stream`.
1267
- * @returns Registered FaasReactClient instance.
1268
- *
1269
- * @example
1270
- * ```ts
1271
- * import { FaasReactClient, ResponseError } from '@faasjs/react'
1272
- *
1273
- * const client = FaasReactClient({
1274
- * baseUrl: 'http://localhost:8080/api/',
1275
- * onError: (action, params) => async (res) => {
1276
- * if (res instanceof ResponseError) {
1277
- * reportErrorToSentry(res, {
1278
- * tags: { action },
1279
- * extra: { params },
1280
- * })
1281
- * }
1282
- * },
1283
- * })
1284
- * ```
1285
- */
1286
- function FaasReactClient(options = { baseUrl: "/" }) {
1287
- const { baseUrl, options: clientOptions, onError } = options;
1288
- const resolvedBaseUrl = baseUrl ?? "/";
1289
- const client = new FaasBrowserClient(resolvedBaseUrl, clientOptions);
1290
- function withBaseUrl(options) {
1291
- if (options?.baseUrl) return options;
1292
- return {
1293
- ...options ?? {},
1294
- baseUrl: resolvedBaseUrl
1295
- };
1296
- }
1297
- const reactClient = {
1298
- id: client.id,
1299
- faas: async (action, params, requestOptions) => faas(action, params, withBaseUrl(requestOptions)),
1300
- useFaas: (action, defaultParams, requestOptions) => useFaas(action, defaultParams, withBaseUrl(requestOptions)),
1301
- FaasDataWrapper: (props) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FaasDataWrapper, {
1302
- ...props,
1303
- baseUrl: resolvedBaseUrl
1304
- }),
1305
- ...onError ? { onError } : {},
1306
- browserClient: client
1307
- };
1308
- clients[resolvedBaseUrl] = reactClient;
1309
- return reactClient;
1310
- }
1311
- /**
1312
- * Get a registered FaasReactClient instance.
1313
- *
1314
- * When `host` is omitted, the first registered client is returned. If no client
1315
- * has been created yet, a default client is initialized automatically.
1316
- * Use `getClient` only for special cases such as multiple Faas clients with
1317
- * different base URLs. In normal single-client app code, prefer the default
1318
- * `faas`, `useFaas`, or `FaasReactClient` setup directly.
1319
- *
1320
- * @param host - Registered base URL to look up. Omit it to use the default client.
1321
- * @returns Registered or newly created FaasReactClient instance.
1322
- *
1323
- * @example
1324
- * ```ts
1325
- * import { FaasReactClient, getClient } from '@faasjs/react'
1326
- *
1327
- * FaasReactClient({
1328
- * baseUrl: 'https://service-a.example.com/api/',
1329
- * })
1330
- *
1331
- * FaasReactClient({
1332
- * baseUrl: 'https://service-b.example.com/api/',
1333
- * })
1334
- *
1335
- * const client = getClient('https://service-b.example.com/api/')
1336
- *
1337
- * await client.faas('/pages/posts/get', { id: 1 })
1338
- * ```
1339
- */
1340
- function getClient(host) {
1341
- const client = clients[host || Object.keys(clients)[0]];
1342
- if (!client) {
1343
- console.warn("FaasReactClient is not initialized manually, use default.");
1344
- return FaasReactClient();
1345
- }
1346
- return client;
1347
- }
1348
- //#endregion
1349
- //#region src/constant.ts
1350
- /**
1351
- * Returns a constant value that is created by the given function.
1352
- *
1353
- * @template T - Constant value type returned by the initializer.
1354
- * @param fn - Initializer that runs only once for the current component instance.
1355
- *
1356
- * @example
1357
- * ```tsx
1358
- * import { useConstant } from '@faasjs/react'
1359
- *
1360
- * function Page() {
1361
- * const requestId = useConstant(() => crypto.randomUUID())
1362
- *
1363
- * return <span>{requestId}</span>
1364
- * }
1365
- * ```
1366
- */
1367
- function useConstant(fn) {
1368
- const ref = (0, react.useRef)(null);
1369
- if (!ref.current) ref.current = { v: fn() };
1370
- return ref.current.v;
1371
- }
1372
- //#endregion
1373
- //#region src/ErrorBoundary.tsx
1374
- /**
1375
- * React error boundary with an optional custom fallback element.
1376
- *
1377
- * The boundary renders its children until a descendant throws. After that it
1378
- * either clones `errorChildren` with injected error details or renders a simple
1379
- * built-in fallback.
1380
- *
1381
- * @example
1382
- * ```tsx
1383
- * import { ErrorBoundary } from '@faasjs/react'
1384
- *
1385
- * function Fallback({ errorMessage }: { errorMessage?: string }) {
1386
- * return <div>{errorMessage}</div>
1387
- * }
1388
- *
1389
- * <ErrorBoundary errorChildren={<Fallback />}>
1390
- * <DangerousWidget />
1391
- * </ErrorBoundary>
1392
- * ```
1393
- */
1394
- var ErrorBoundary = class extends react.Component {
1395
- /**
1396
- * Stable display name used by React DevTools.
1397
- */
1398
- static displayName = "ErrorBoundary";
1399
- /**
1400
- * Create an error boundary with empty error state.
1401
- *
1402
- * @param props - Boundary props.
1403
- * @param props.children - Descendant elements protected by the boundary.
1404
- * @param props.onError - Callback invoked after a render error is captured.
1405
- * @param props.errorChildren - Custom fallback element that receives error details.
1406
- */
1407
- constructor(props) {
1408
- super(props);
1409
- this.state = {
1410
- error: null,
1411
- info: { componentStack: "" }
1412
- };
1413
- }
1414
- /**
1415
- * Capture rendering errors from descendant components.
1416
- *
1417
- * @param error - Caught render error.
1418
- * @param info - React component stack metadata.
1419
- */
1420
- componentDidCatch(error, info) {
1421
- this.setState({
1422
- error,
1423
- info
1424
- });
1425
- }
1426
- /**
1427
- * Render children or the configured fallback for the captured error.
1428
- */
1429
- render() {
1430
- const { error, info } = this.state;
1431
- const errorMessage = String(error ?? "");
1432
- const errorDescription = info.componentStack || void 0;
1433
- if (error) {
1434
- if (this.props.onError) this.props.onError(error, info);
1435
- if (this.props.errorChildren) return (0, react.cloneElement)(this.props.errorChildren, {
1436
- error,
1437
- info,
1438
- errorMessage,
1439
- ...errorDescription ? { errorDescription } : {}
1440
- });
1441
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: errorMessage }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", { children: errorDescription })] });
1442
- }
1443
- return this.props.children ?? null;
1444
- }
1445
- };
1446
- //#endregion
1447
- //#region src/OptionalWrapper.tsx
1448
- /**
1449
- * Conditionally wrap children with another component.
1450
- *
1451
- * @param props - Wrapper condition, wrapper component, and child content.
1452
- * @param props.condition - When `true`, wrap children with `Wrapper`.
1453
- * @param props.Wrapper - Component used as the wrapper when the condition passes.
1454
- * @param props.wrapperProps - Props forwarded to the wrapper component.
1455
- * @param props.children - Content rendered directly or inside the wrapper.
1456
- * @returns Wrapped children or the original children when `condition` is false.
1457
- *
1458
- * @example
1459
- * ```tsx
1460
- * import { OptionalWrapper } from '@faasjs/react'
1461
- *
1462
- * const Wrapper = ({ children }: { children: React.ReactNode }) => (
1463
- * <div className='wrapper'>{children}</div>
1464
- * )
1465
- *
1466
- * const App = () => (
1467
- * <OptionalWrapper condition={true} Wrapper={Wrapper}>
1468
- * <span>Test</span>
1469
- * </OptionalWrapper>
1470
- * )
1471
- * ```
1472
- */
1473
- function OptionalWrapper(props) {
1474
- const { condition, Wrapper, wrapperProps, children } = props;
1475
- if (condition) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Wrapper, {
1476
- ...wrapperProps,
1477
- children
1478
- });
1479
- return children;
1480
- }
1481
- OptionalWrapper.displayName = "OptionalWrapper";
1482
- //#endregion
1483
- //#region src/splittingState.tsx
1484
- /**
1485
- * Create local state entries and matching setters for each key in an object.
1486
- *
1487
- * @template T - A generic type that extends a record with string keys and any values.
1488
- * @param initialStates - Object whose keys become state values and `setXxx` setters.
1489
- * @returns Object containing the original keys plus generated setter functions.
1490
- *
1491
- * @example
1492
- * ```tsx
1493
- * function Counter() {
1494
- * const { count, setCount, name, setName } = useSplittingState({ count: 0, name: 'John' })
1495
- *
1496
- * return <>{name}: {count}</>
1497
- * }
1498
- * ```
1499
- */
1500
- function useSplittingState(initialStates) {
1501
- const states = {};
1502
- for (const key of Object.keys(initialStates)) {
1503
- const state = (0, react.useState)(initialStates[key]);
1504
- Object.assign(states, {
1505
- [key]: state[0],
1506
- [`set${String(key).charAt(0).toUpperCase()}${String(key).slice(1)}`]: state[1]
1507
- });
1508
- }
1509
- return states;
1510
- }
1511
- //#endregion
1512
- //#region src/splittingContext.tsx
1513
- /**
1514
- * Create a context whose keys can be consumed independently.
1515
- *
1516
- * `createSplittingContext` returns a `Provider` and a `use` hook. Each key in
1517
- * the provided shape is backed by a separate React context so readers only
1518
- * subscribe to the values they access.
1519
- *
1520
- * @template T - Context value shape exposed by the provider and hook.
1521
- * @param defaultValue - Default value map or key list used to create split contexts.
1522
- * @returns Provider and hook helpers for the split context.
1523
- *
1524
- * @example
1525
- * ```tsx
1526
- * const { Provider, use } = createSplittingContext<{
1527
- * value: number
1528
- * setValue: React.Dispatch<React.SetStateAction<number>>
1529
- * }>({
1530
- * value: 0,
1531
- * setValue: null,
1532
- * })
1533
- *
1534
- * function ReaderComponent() {
1535
- * const { value } = use()
1536
- *
1537
- * return <div>{value}</div>
1538
- * }
1539
- *
1540
- * function WriterComponent() {
1541
- * const { setValue } = use()
1542
- *
1543
- * return (
1544
- * <button type='button' onClick={() => setValue((p: number) => p + 1)}>
1545
- * Change
1546
- * </button>
1547
- * )
1548
- * }
1549
- *
1550
- * function App() {
1551
- * const [value, setValue] = useState(0)
1552
- *
1553
- * return (
1554
- * <Provider value={{ value, setValue }}>
1555
- * <ReaderComponent />
1556
- * <WriterComponent />
1557
- * </Provider>
1558
- * )
1559
- * }
1560
- * ```
1561
- */
1562
- function createSplittingContext(defaultValue) {
1563
- const keys = Array.isArray(defaultValue) ? defaultValue : Object.keys(defaultValue);
1564
- const defaultValues = Array.isArray(defaultValue) ? keys.reduce((prev, cur) => {
1565
- prev[cur] = null;
1566
- return prev;
1567
- }, {}) : defaultValue;
1568
- const contexts = {};
1569
- for (const key of keys) contexts[key] = (0, react.createContext)(defaultValues[key]);
1570
- function Provider(props) {
1571
- const states = props.initializeStates ? useSplittingState(props.initializeStates) : {};
1572
- let children = props.memo ? useEqualMemo(() => props.children, props.memo === true ? [] : props.memo) : props.children;
1573
- for (const key of keys) {
1574
- const Context = contexts[key];
1575
- const value = props.value?.[key] ?? states[key] ?? defaultValues[key];
1576
- children = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Context.Provider, {
1577
- value,
1578
- children
1579
- });
1580
- }
1581
- return children;
1582
- }
1583
- Provider.displayName = "SplittingContextProvider";
1584
- function use() {
1585
- return useConstant(() => {
1586
- const obj = Object.create(null);
1587
- for (const key of Object.keys(contexts)) Object.defineProperty(obj, key, { get: () => {
1588
- if (!contexts[key]) throw new Error(`Context for key "${key}" is undefined`);
1589
- return (0, react.useContext)(contexts[key]);
1590
- } });
1591
- return Object.freeze(obj);
1592
- });
1593
- }
1594
- return {
1595
- Provider,
1596
- use
1597
- };
1598
- }
1599
- //#endregion
1600
- //#region src/useFaasStream.tsx
1601
- /**
1602
- * Stream a FaasJS response into React state.
1603
- *
1604
- * `useFaasStream` is the default hook for streaming FaasJS responses in React.
1605
- * It sends a streaming request, appends decoded text chunks to `data`, and
1606
- * exposes reload helpers for retrying the same action.
1607
- *
1608
- * @param action - Action path to invoke.
1609
- * @param defaultParams - Params used for the initial request and future reloads.
1610
- * @param options - Optional hook configuration such as controlled data, debounce, and skip logic.
1611
- * @param options.params - Request params override used without mutating the hook's stored params state.
1612
- * @param options.data - Controlled stream text used instead of the hook's internal state.
1613
- * @param options.setData - Controlled setter used instead of the hook's internal `setData`.
1614
- * @param options.skip - Boolean or predicate that suppresses the automatic request until `reload()` runs.
1615
- * @param options.debounce - Milliseconds to wait before sending the latest request.
1616
- * @param options.baseUrl - Base URL override used for this hook instance.
1617
- * @returns Streaming request state and helper methods described by {@link UseFaasStreamResult}.
1618
- *
1619
- * @example
1620
- * ```tsx
1621
- * import { useFaasStream } from '@faasjs/react'
1622
- *
1623
- * function Chat({ prompt }: { prompt: string }) {
1624
- * const { data, error, loading, reload } = useFaasStream('/pages/chat/stream', { prompt })
1625
- *
1626
- * if (loading) return <div>Streaming...</div>
1627
- *
1628
- * if (error) {
1629
- * return (
1630
- * <div>
1631
- * <div>Stream failed: {error.message}</div>
1632
- * <button type="button" onClick={() => reload()}>
1633
- * Retry
1634
- * </button>
1635
- * </div>
1636
- * )
1637
- * }
1638
- *
1639
- * return <pre>{data}</pre>
1640
- * }
1641
- * ```
1642
- */
1643
- function useFaasStream(action, defaultParams, options = {}) {
1644
- const [loading, setLoading] = (0, react.useState)(true);
1645
- const [data, setData] = (0, react.useState)(options.data || "");
1646
- const [error, setError] = (0, react.useState)();
1647
- const [params, setParams] = (0, react.useState)(defaultParams);
1648
- const [reloadTimes, setReloadTimes] = (0, react.useState)(0);
1649
- const [fails, setFails] = (0, react.useState)(0);
1650
- const [skip, setSkip] = (0, react.useState)(typeof options.skip === "function" ? options.skip(defaultParams) : options.skip);
1651
- const controllerRef = (0, react.useRef)(null);
1652
- const pendingReloadsRef = (0, react.useRef)(/* @__PURE__ */ new Map());
1653
- const reloadCounterRef = (0, react.useRef)(0);
1654
- useEqualEffect(() => {
1655
- setSkip(typeof options.skip === "function" ? options.skip(params) : options.skip);
1656
- }, [typeof options.skip === "function" ? params : options.skip]);
1657
- useEqualEffect(() => {
1658
- if (!equal(defaultParams, params)) setParams(defaultParams);
1659
- }, [defaultParams]);
1660
- useEqualEffect(() => {
1661
- if (!action || skip) {
1662
- setLoading(false);
1663
- return;
1664
- }
1665
- setLoading(true);
1666
- setData("");
1667
- const controller = new AbortController();
1668
- controllerRef.current = controller;
1669
- const client = getClient(options.baseUrl);
1670
- const requestParams = options.params ?? params;
1671
- function send() {
1672
- client.browserClient.action(action, requestParams, {
1673
- signal: controller.signal,
1674
- stream: true
1675
- }).then(async (response) => {
1676
- if (!response.body) {
1677
- setError(/* @__PURE__ */ new Error("Response body is null"));
1678
- setLoading(false);
1679
- return;
1680
- }
1681
- const reader = response.body.getReader();
1682
- const decoder = new TextDecoder();
1683
- let accumulatedText = "";
1684
- try {
1685
- while (true) {
1686
- const { done, value } = await reader.read();
1687
- if (done) break;
1688
- accumulatedText += decoder.decode(value, { stream: true });
1689
- setData(accumulatedText);
1690
- }
1691
- setFails(0);
1692
- setError(null);
1693
- setLoading(false);
1694
- for (const { resolve } of pendingReloadsRef.current.values()) resolve(accumulatedText);
1695
- pendingReloadsRef.current.clear();
1696
- } catch (readError) {
1697
- reader.releaseLock();
1698
- throw readError;
1699
- }
1700
- }).catch(async (e) => {
1701
- if (typeof e?.message === "string" && e.message.toLowerCase().indexOf("aborted") >= 0) return;
1702
- if (!fails && typeof e?.message === "string" && e.message.indexOf("Failed to fetch") >= 0) {
1703
- console.warn(`FaasReactClient: ${e.message} retry...`);
1704
- setFails(1);
1705
- return send();
1706
- }
1707
- let error = e;
1708
- if (client.onError) try {
1709
- await client.onError(action, requestParams)(e);
1710
- } catch (newError) {
1711
- error = newError;
1712
- }
1713
- setError(error);
1714
- setLoading(false);
1715
- for (const { reject } of pendingReloadsRef.current.values()) reject(error);
1716
- pendingReloadsRef.current.clear();
1717
- });
1718
- }
1719
- if (options.debounce) {
1720
- const timeout = setTimeout(send, options.debounce);
1721
- return () => {
1722
- clearTimeout(timeout);
1723
- controllerRef.current?.abort();
1724
- setLoading(false);
1725
- };
1726
- }
1727
- send();
1728
- return () => {
1729
- controllerRef.current?.abort();
1730
- setLoading(false);
1731
- };
1732
- }, [
1733
- action,
1734
- options.params || params,
1735
- reloadTimes,
1736
- skip
1737
- ]);
1738
- const reload = useEqualCallback((params) => {
1739
- if (skip) setSkip(false);
1740
- if (params) setParams(params);
1741
- const reloadCounter = ++reloadCounterRef.current;
1742
- return new Promise((resolve, reject) => {
1743
- pendingReloadsRef.current.set(reloadCounter, {
1744
- resolve,
1745
- reject
1746
- });
1747
- setReloadTimes((prev) => prev + 1);
1748
- });
1749
- }, [params, skip]);
1750
- return {
1751
- action,
1752
- params,
1753
- loading,
1754
- data: options.data || data,
1755
- reloadTimes,
1756
- error,
1757
- reload,
1758
- setData: options.setData || setData,
1759
- setLoading,
1760
- setError
1761
- };
1762
- }
1763
- //#endregion
1764
- //#region src/usePrevious.ts
1765
- /**
1766
- * Hook to store the previous value of a state or prop.
1767
- *
1768
- * @template T - The type of the value.
1769
- * @param value - The current value to track.
1770
- * @returns Previous value from the prior render, or `undefined` on the first render.
1771
- *
1772
- * @example
1773
- * ```tsx
1774
- * import { usePrevious } from '@faasjs/react'
1775
- *
1776
- * function Counter({ count }: { count: number }) {
1777
- * const previous = usePrevious(count)
1778
- *
1779
- * return <span>{previous} -> {count}</span>
1780
- * }
1781
- * ```
1782
- */
1783
- function usePrevious(value) {
1784
- const ref = (0, react.useRef)(void 0);
1785
- (0, react.useEffect)(() => {
1786
- ref.current = value;
1787
- });
1788
- return ref.current;
1789
- }
1790
- //#endregion
1791
- //#region src/useStateRef.ts
1792
- /**
1793
- * Custom hook that returns a stateful value and a ref to that value.
1794
- *
1795
- * @template T - The type of the value.
1796
- * @param initialValue - Initial state value. When omitted, state starts as `null`.
1797
- * @returns Tuple containing the current state, the state setter, and a ref that always points at the latest state.
1798
- *
1799
- * @example
1800
- * ```tsx
1801
- * import { useStateRef } from '@faasjs/react'
1802
- *
1803
- * function MyComponent() {
1804
- * const [value, setValue, ref] = useStateRef(0)
1805
- *
1806
- * return (
1807
- * <div>
1808
- * <p>Value: {value}</p>
1809
- * <button onClick={() => setValue(value + 1)}>Increment</button>
1810
- * <button onClick={() => console.log(ref.current)}>Submit</button>
1811
- * </div>
1812
- * )
1813
- * }
1814
- * ```
1815
- */
1816
- function useStateRef(initialValue) {
1817
- const [state, setState] = (0, react.useState)(initialValue ?? null);
1818
- const ref = (0, react.useRef)(state);
1819
- (0, react.useEffect)(() => {
1820
- ref.current = state;
1821
- }, [state]);
1822
- return [
1823
- state,
1824
- setState,
1825
- ref
1826
- ];
1827
- }
1828
- //#endregion
1829
- exports.ErrorBoundary = ErrorBoundary;
1830
- exports.FaasBrowserClient = FaasBrowserClient;
1831
- exports.FaasDataWrapper = FaasDataWrapper;
1832
- exports.FaasReactClient = FaasReactClient;
1833
- exports.OptionalWrapper = OptionalWrapper;
1834
- exports.Response = Response;
1835
- exports.ResponseError = ResponseError;
1836
- exports.createSplittingContext = createSplittingContext;
1837
- exports.equal = equal;
1838
- exports.faas = faas;
1839
- exports.generateId = generateId;
1840
- exports.getClient = getClient;
1841
- exports.setMock = setMock;
1842
- exports.useConstant = useConstant;
1843
- exports.useEqualCallback = useEqualCallback;
1844
- exports.useEqualEffect = useEqualEffect;
1845
- exports.useEqualMemo = useEqualMemo;
1846
- exports.useEqualMemoize = useEqualMemoize;
1847
- exports.useFaas = useFaas;
1848
- exports.useFaasStream = useFaasStream;
1849
- exports.usePrevious = usePrevious;
1850
- exports.useSplittingState = useSplittingState;
1851
- exports.useStateRef = useStateRef;
1852
- exports.withFaasData = withFaasData;