parallel-web 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/client.d.mts +29 -8
  3. package/client.d.mts.map +1 -1
  4. package/client.d.ts +29 -8
  5. package/client.d.ts.map +1 -1
  6. package/client.js +34 -4
  7. package/client.js.map +1 -1
  8. package/client.mjs +34 -4
  9. package/client.mjs.map +1 -1
  10. package/internal/qs/formats.d.mts +7 -0
  11. package/internal/qs/formats.d.mts.map +1 -0
  12. package/internal/qs/formats.d.ts +7 -0
  13. package/internal/qs/formats.d.ts.map +1 -0
  14. package/internal/qs/formats.js +13 -0
  15. package/internal/qs/formats.js.map +1 -0
  16. package/internal/qs/formats.mjs +9 -0
  17. package/internal/qs/formats.mjs.map +1 -0
  18. package/internal/qs/index.d.mts +10 -0
  19. package/internal/qs/index.d.mts.map +1 -0
  20. package/internal/qs/index.d.ts +10 -0
  21. package/internal/qs/index.d.ts.map +1 -0
  22. package/internal/qs/index.js +14 -0
  23. package/internal/qs/index.js.map +1 -0
  24. package/internal/qs/index.mjs +10 -0
  25. package/internal/qs/index.mjs.map +1 -0
  26. package/internal/qs/stringify.d.mts +3 -0
  27. package/internal/qs/stringify.d.mts.map +1 -0
  28. package/internal/qs/stringify.d.ts +3 -0
  29. package/internal/qs/stringify.d.ts.map +1 -0
  30. package/internal/qs/stringify.js +277 -0
  31. package/internal/qs/stringify.js.map +1 -0
  32. package/internal/qs/stringify.mjs +274 -0
  33. package/internal/qs/stringify.mjs.map +1 -0
  34. package/internal/qs/types.d.mts +57 -0
  35. package/internal/qs/types.d.mts.map +1 -0
  36. package/internal/qs/types.d.ts +57 -0
  37. package/internal/qs/types.d.ts.map +1 -0
  38. package/internal/qs/types.js +3 -0
  39. package/internal/qs/types.js.map +1 -0
  40. package/internal/qs/types.mjs +2 -0
  41. package/internal/qs/types.mjs.map +1 -0
  42. package/internal/qs/utils.d.mts +15 -0
  43. package/internal/qs/utils.d.mts.map +1 -0
  44. package/internal/qs/utils.d.ts +15 -0
  45. package/internal/qs/utils.d.ts.map +1 -0
  46. package/internal/qs/utils.js +230 -0
  47. package/internal/qs/utils.js.map +1 -0
  48. package/internal/qs/utils.mjs +217 -0
  49. package/internal/qs/utils.mjs.map +1 -0
  50. package/internal/types.d.mts +6 -6
  51. package/internal/types.d.mts.map +1 -1
  52. package/internal/types.d.ts +6 -6
  53. package/internal/types.d.ts.map +1 -1
  54. package/internal/utils/query.d.mts +0 -3
  55. package/internal/utils/query.d.mts.map +1 -1
  56. package/internal/utils/query.d.ts +0 -3
  57. package/internal/utils/query.d.ts.map +1 -1
  58. package/internal/utils/query.js +3 -16
  59. package/internal/utils/query.js.map +1 -1
  60. package/internal/utils/query.mjs +2 -16
  61. package/internal/utils/query.mjs.map +1 -1
  62. package/package.json +1 -1
  63. package/resources/beta/beta.d.mts +11 -19
  64. package/resources/beta/beta.d.mts.map +1 -1
  65. package/resources/beta/beta.d.ts +11 -19
  66. package/resources/beta/beta.d.ts.map +1 -1
  67. package/resources/beta/beta.js +2 -0
  68. package/resources/beta/beta.js.map +1 -1
  69. package/resources/beta/beta.mjs +2 -0
  70. package/resources/beta/beta.mjs.map +1 -1
  71. package/resources/beta/findall.d.mts +127 -177
  72. package/resources/beta/findall.d.mts.map +1 -1
  73. package/resources/beta/findall.d.ts +127 -177
  74. package/resources/beta/findall.d.ts.map +1 -1
  75. package/resources/beta/findall.js +2 -4
  76. package/resources/beta/findall.js.map +1 -1
  77. package/resources/beta/findall.mjs +2 -4
  78. package/resources/beta/findall.mjs.map +1 -1
  79. package/resources/beta/index.d.mts +2 -2
  80. package/resources/beta/index.d.mts.map +1 -1
  81. package/resources/beta/index.d.ts +2 -2
  82. package/resources/beta/index.d.ts.map +1 -1
  83. package/resources/beta/index.js.map +1 -1
  84. package/resources/beta/index.mjs.map +1 -1
  85. package/resources/beta/task-group.d.mts +22 -143
  86. package/resources/beta/task-group.d.mts.map +1 -1
  87. package/resources/beta/task-group.d.ts +22 -143
  88. package/resources/beta/task-group.d.ts.map +1 -1
  89. package/resources/beta/task-group.js +7 -42
  90. package/resources/beta/task-group.js.map +1 -1
  91. package/resources/beta/task-group.mjs +7 -42
  92. package/resources/beta/task-group.mjs.map +1 -1
  93. package/resources/beta/task-run.d.mts +22 -70
  94. package/resources/beta/task-run.d.mts.map +1 -1
  95. package/resources/beta/task-run.d.ts +22 -70
  96. package/resources/beta/task-run.d.ts.map +1 -1
  97. package/resources/beta/task-run.js +1 -1
  98. package/resources/beta/task-run.mjs +1 -1
  99. package/resources/index.d.mts +4 -2
  100. package/resources/index.d.mts.map +1 -1
  101. package/resources/index.d.ts +4 -2
  102. package/resources/index.d.ts.map +1 -1
  103. package/resources/index.js +5 -1
  104. package/resources/index.js.map +1 -1
  105. package/resources/index.mjs +2 -0
  106. package/resources/index.mjs.map +1 -1
  107. package/resources/monitor.d.mts +625 -0
  108. package/resources/monitor.d.mts.map +1 -0
  109. package/resources/monitor.d.ts +625 -0
  110. package/resources/monitor.d.ts.map +1 -0
  111. package/resources/monitor.js +140 -0
  112. package/resources/monitor.js.map +1 -0
  113. package/resources/monitor.mjs +136 -0
  114. package/resources/monitor.mjs.map +1 -0
  115. package/resources/task-group.d.mts +213 -0
  116. package/resources/task-group.d.mts.map +1 -0
  117. package/resources/task-group.d.ts +213 -0
  118. package/resources/task-group.d.ts.map +1 -0
  119. package/resources/task-group.js +95 -0
  120. package/resources/task-group.js.map +1 -0
  121. package/resources/task-group.mjs +91 -0
  122. package/resources/task-group.mjs.map +1 -0
  123. package/resources/task-run.d.mts +97 -80
  124. package/resources/task-run.d.mts.map +1 -1
  125. package/resources/task-run.d.ts +97 -80
  126. package/resources/task-run.d.ts.map +1 -1
  127. package/resources/task-run.js +14 -1
  128. package/resources/task-run.js.map +1 -1
  129. package/resources/task-run.mjs +14 -1
  130. package/resources/task-run.mjs.map +1 -1
  131. package/resources/top-level.d.mts +19 -15
  132. package/resources/top-level.d.mts.map +1 -1
  133. package/resources/top-level.d.ts +19 -15
  134. package/resources/top-level.d.ts.map +1 -1
  135. package/src/client.ts +120 -4
  136. package/src/internal/qs/LICENSE.md +13 -0
  137. package/src/internal/qs/README.md +3 -0
  138. package/src/internal/qs/formats.ts +10 -0
  139. package/src/internal/qs/index.ts +13 -0
  140. package/src/internal/qs/stringify.ts +385 -0
  141. package/src/internal/qs/types.ts +71 -0
  142. package/src/internal/qs/utils.ts +265 -0
  143. package/src/internal/types.ts +6 -8
  144. package/src/internal/utils/query.ts +2 -18
  145. package/src/resources/beta/api.md +9 -5
  146. package/src/resources/beta/beta.ts +26 -20
  147. package/src/resources/beta/findall.ts +153 -202
  148. package/src/resources/beta/index.ts +7 -4
  149. package/src/resources/beta/task-group.ts +30 -157
  150. package/src/resources/beta/task-run.ts +26 -86
  151. package/src/resources/index.ts +42 -0
  152. package/src/resources/monitor.ts +752 -0
  153. package/src/resources/task-group.ts +315 -0
  154. package/src/resources/task-run.ts +122 -95
  155. package/src/resources/top-level.ts +23 -15
  156. package/src/version.ts +1 -1
  157. package/version.d.mts +1 -1
  158. package/version.d.ts +1 -1
  159. package/version.js +1 -1
  160. package/version.mjs +1 -1
package/src/client.ts CHANGED
@@ -26,12 +26,50 @@ import {
26
26
  ExtractResponse,
27
27
  ExtractResult,
28
28
  FetchPolicy,
29
+ FullContentSettings,
29
30
  SearchParams,
30
31
  SearchResult,
31
32
  UsageItem,
32
33
  WebSearchResult,
33
34
  } from './resources/top-level';
34
35
  import { APIPromise } from './core/api-promise';
36
+ import {
37
+ AdvancedMonitorSettings,
38
+ CreateMonitorRequest,
39
+ Monitor,
40
+ MonitorCompletionEvent,
41
+ MonitorCreateParams,
42
+ MonitorErrorEvent,
43
+ MonitorEventStreamEvent,
44
+ MonitorEventStreamResponseSettings,
45
+ MonitorEventStreamSettings,
46
+ MonitorEventsParams,
47
+ MonitorListParams,
48
+ MonitorResource,
49
+ MonitorSnapshotEvent,
50
+ MonitorSnapshotOutput,
51
+ MonitorSnapshotResponseSettings,
52
+ MonitorSnapshotSettings,
53
+ MonitorUpdateParams,
54
+ MonitorWebhook,
55
+ PaginatedMonitorEvents,
56
+ PaginatedMonitorResponse,
57
+ UpdateMonitorEventStreamSettings,
58
+ UpdateMonitorRequest,
59
+ } from './resources/monitor';
60
+ import {
61
+ TaskGroup,
62
+ TaskGroupAddRunsParams,
63
+ TaskGroupCreateParams,
64
+ TaskGroupEventsParams,
65
+ TaskGroupEventsResponse,
66
+ TaskGroupGetRunsParams,
67
+ TaskGroupGetRunsResponse,
68
+ TaskGroupRetrieveRunParams,
69
+ TaskGroupRunResponse,
70
+ TaskGroupStatus,
71
+ TaskGroupStatusEvent,
72
+ } from './resources/task-group';
35
73
  import {
36
74
  AutoSchema,
37
75
  Citation,
@@ -41,13 +79,17 @@ import {
41
79
  McpServer,
42
80
  McpToolCall,
43
81
  RunInput,
82
+ TaskAdvancedSettings,
44
83
  TaskRun,
45
84
  TaskRunCreateParams,
46
85
  TaskRunEvent,
47
86
  TaskRunEventsResponse,
48
87
  TaskRunJsonOutput,
88
+ TaskRunProgressMessageEvent,
89
+ TaskRunProgressStatsEvent,
49
90
  TaskRunResult,
50
91
  TaskRunResultParams,
92
+ TaskRunSourceStats,
51
93
  TaskRunTextOutput,
52
94
  TaskSpec,
53
95
  TextSchema,
@@ -204,6 +246,18 @@ export class Parallel {
204
246
  this.fetch = options.fetch ?? Shims.getDefaultFetch();
205
247
  this.#encoder = Opts.FallbackEncoder;
206
248
 
249
+ const customHeadersEnv = readEnv('PARALLEL_CUSTOM_HEADERS');
250
+ if (customHeadersEnv) {
251
+ const parsed: Record<string, string> = {};
252
+ for (const line of customHeadersEnv.split('\n')) {
253
+ const colon = line.indexOf(':');
254
+ if (colon >= 0) {
255
+ parsed[line.substring(0, colon).trim()] = line.substring(colon + 1).trim();
256
+ }
257
+ }
258
+ options.defaultHeaders = { ...parsed, ...options.defaultHeaders };
259
+ }
260
+
207
261
  this._options = options;
208
262
 
209
263
  this.apiKey = apiKey;
@@ -288,9 +342,6 @@ export class Parallel {
288
342
  return buildHeaders([{ 'x-api-key': this.apiKey }]);
289
343
  }
290
344
 
291
- /**
292
- * Basic re-implementation of `qs.stringify` for primitive types.
293
- */
294
345
  protected stringifyQuery(query: object | Record<string, unknown>): string {
295
346
  return stringifyQuery(query);
296
347
  }
@@ -800,16 +851,37 @@ export class Parallel {
800
851
  * - Output metadata: citations, excerpts, reasoning, and confidence per field
801
852
  *
802
853
  * Task Groups enable batch execution of many independent Task runs with group-level monitoring and failure handling.
803
- * - Submit hundreds or thousands of Tasks as a single group
854
+ * - Submit hundreds or thousands of Tasks as a single group
804
855
  * - Observe group progress and receive results as they complete
805
856
  * - Real-time updates via Server-Sent Events (SSE)
806
857
  * - Add tasks to an existing group while it is running
807
858
  * - Group-level retry and error aggregation
808
859
  */
809
860
  taskRun: API.TaskRun = new API.TaskRun(this);
861
+ /**
862
+ * The Task API executes web research and extraction tasks. Clients submit a natural-language objective with an optional input schema; the service plans retrieval, fetches relevant URLs, and returns outputs that conform to a provided or inferred JSON schema. Supports deep research style queries and can return rich structured JSON outputs. Processors trade-off between cost, latency, and quality. Each processor supports calibrated confidences.
863
+ * - Output metadata: citations, excerpts, reasoning, and confidence per field
864
+ *
865
+ * Task Groups enable batch execution of many independent Task runs with group-level monitoring and failure handling.
866
+ * - Submit hundreds or thousands of Tasks as a single group
867
+ * - Observe group progress and receive results as they complete
868
+ * - Real-time updates via Server-Sent Events (SSE)
869
+ * - Add tasks to an existing group while it is running
870
+ * - Group-level retry and error aggregation
871
+ */
872
+ taskGroup: API.TaskGroup = new API.TaskGroup(this);
873
+ /**
874
+ * The Monitor API watches the web for material changes on a fixed frequency. Each monitor runs once on creation and then on its configured schedule, emitting events when meaningful changes are detected.
875
+ * - `event_stream` monitors track a search query and emit an event for each new material change.
876
+ * - `snapshot` monitors track a specific task run's output and emit an event when the output changes.
877
+ *
878
+ * Results can be polled via the events endpoint or delivered via webhooks.
879
+ */
880
+ monitor: API.MonitorResource = new API.MonitorResource(this);
810
881
  beta: API.Beta = new API.Beta(this);
811
882
  }
812
883
 
884
+ Parallel.MonitorResource = MonitorResource;
813
885
  Parallel.Beta = Beta;
814
886
 
815
887
  export declare namespace Parallel {
@@ -823,6 +895,7 @@ export declare namespace Parallel {
823
895
  type ExtractResponse as ExtractResponse,
824
896
  type ExtractResult as ExtractResult,
825
897
  type FetchPolicy as FetchPolicy,
898
+ type FullContentSettings as FullContentSettings,
826
899
  type SearchResult as SearchResult,
827
900
  type UsageItem as UsageItem,
828
901
  type WebSearchResult as WebSearchResult,
@@ -840,9 +913,13 @@ export declare namespace Parallel {
840
913
  type McpServer as McpServer,
841
914
  type McpToolCall as McpToolCall,
842
915
  type RunInput as RunInput,
916
+ type TaskAdvancedSettings as TaskAdvancedSettings,
843
917
  type TaskRunEvent as TaskRunEvent,
844
918
  type TaskRunJsonOutput as TaskRunJsonOutput,
919
+ type TaskRunProgressMessageEvent as TaskRunProgressMessageEvent,
920
+ type TaskRunProgressStatsEvent as TaskRunProgressStatsEvent,
845
921
  type TaskRunResult as TaskRunResult,
922
+ type TaskRunSourceStats as TaskRunSourceStats,
846
923
  type TaskRunTextOutput as TaskRunTextOutput,
847
924
  type TaskSpec as TaskSpec,
848
925
  type TextSchema as TextSchema,
@@ -852,6 +929,45 @@ export declare namespace Parallel {
852
929
  type TaskRunResultParams as TaskRunResultParams,
853
930
  };
854
931
 
932
+ export {
933
+ type TaskGroup as TaskGroup,
934
+ type TaskGroupRunResponse as TaskGroupRunResponse,
935
+ type TaskGroupStatus as TaskGroupStatus,
936
+ type TaskGroupStatusEvent as TaskGroupStatusEvent,
937
+ type TaskGroupEventsResponse as TaskGroupEventsResponse,
938
+ type TaskGroupGetRunsResponse as TaskGroupGetRunsResponse,
939
+ type TaskGroupCreateParams as TaskGroupCreateParams,
940
+ type TaskGroupAddRunsParams as TaskGroupAddRunsParams,
941
+ type TaskGroupEventsParams as TaskGroupEventsParams,
942
+ type TaskGroupGetRunsParams as TaskGroupGetRunsParams,
943
+ type TaskGroupRetrieveRunParams as TaskGroupRetrieveRunParams,
944
+ };
945
+
946
+ export {
947
+ MonitorResource as MonitorResource,
948
+ type AdvancedMonitorSettings as AdvancedMonitorSettings,
949
+ type CreateMonitorRequest as CreateMonitorRequest,
950
+ type Monitor as Monitor,
951
+ type MonitorCompletionEvent as MonitorCompletionEvent,
952
+ type MonitorErrorEvent as MonitorErrorEvent,
953
+ type MonitorEventStreamEvent as MonitorEventStreamEvent,
954
+ type MonitorEventStreamResponseSettings as MonitorEventStreamResponseSettings,
955
+ type MonitorEventStreamSettings as MonitorEventStreamSettings,
956
+ type MonitorSnapshotEvent as MonitorSnapshotEvent,
957
+ type MonitorSnapshotOutput as MonitorSnapshotOutput,
958
+ type MonitorSnapshotResponseSettings as MonitorSnapshotResponseSettings,
959
+ type MonitorSnapshotSettings as MonitorSnapshotSettings,
960
+ type MonitorWebhook as MonitorWebhook,
961
+ type PaginatedMonitorEvents as PaginatedMonitorEvents,
962
+ type PaginatedMonitorResponse as PaginatedMonitorResponse,
963
+ type UpdateMonitorEventStreamSettings as UpdateMonitorEventStreamSettings,
964
+ type UpdateMonitorRequest as UpdateMonitorRequest,
965
+ type MonitorCreateParams as MonitorCreateParams,
966
+ type MonitorUpdateParams as MonitorUpdateParams,
967
+ type MonitorListParams as MonitorListParams,
968
+ type MonitorEventsParams as MonitorEventsParams,
969
+ };
970
+
855
971
  export { Beta as Beta };
856
972
 
857
973
  export type ErrorObject = API.ErrorObject;
@@ -0,0 +1,13 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2014, Nathan LaFreniere and other [contributors](https://github.com/puruvj/neoqs/graphs/contributors) All rights reserved.
4
+
5
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
8
+
9
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
10
+
11
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
12
+
13
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,3 @@
1
+ # qs
2
+
3
+ This is a vendored version of [neoqs](https://github.com/PuruVJ/neoqs) which is a TypeScript rewrite of [qs](https://github.com/ljharb/qs), a query string library.
@@ -0,0 +1,10 @@
1
+ import type { Format } from './types';
2
+
3
+ export const default_format: Format = 'RFC3986';
4
+ export const default_formatter = (v: PropertyKey) => String(v);
5
+ export const formatters: Record<Format, (str: PropertyKey) => string> = {
6
+ RFC1738: (v: PropertyKey) => String(v).replace(/%20/g, '+'),
7
+ RFC3986: default_formatter,
8
+ };
9
+ export const RFC1738 = 'RFC1738';
10
+ export const RFC3986 = 'RFC3986';
@@ -0,0 +1,13 @@
1
+ import { default_format, formatters, RFC1738, RFC3986 } from './formats';
2
+
3
+ const formats = {
4
+ formatters,
5
+ RFC1738,
6
+ RFC3986,
7
+ default: default_format,
8
+ };
9
+
10
+ export { stringify } from './stringify';
11
+ export { formats };
12
+
13
+ export type { DefaultDecoder, DefaultEncoder, Format, ParseOptions, StringifyOptions } from './types';
@@ -0,0 +1,385 @@
1
+ import { encode, is_buffer, maybe_map, has } from './utils';
2
+ import { default_format, default_formatter, formatters } from './formats';
3
+ import type { NonNullableProperties, StringifyOptions } from './types';
4
+ import { isArray } from '../utils/values';
5
+
6
+ const array_prefix_generators = {
7
+ brackets(prefix: PropertyKey) {
8
+ return String(prefix) + '[]';
9
+ },
10
+ comma: 'comma',
11
+ indices(prefix: PropertyKey, key: string) {
12
+ return String(prefix) + '[' + key + ']';
13
+ },
14
+ repeat(prefix: PropertyKey) {
15
+ return String(prefix);
16
+ },
17
+ };
18
+
19
+ const push_to_array = function (arr: any[], value_or_array: any) {
20
+ Array.prototype.push.apply(arr, isArray(value_or_array) ? value_or_array : [value_or_array]);
21
+ };
22
+
23
+ let toISOString;
24
+
25
+ const defaults = {
26
+ addQueryPrefix: false,
27
+ allowDots: false,
28
+ allowEmptyArrays: false,
29
+ arrayFormat: 'indices',
30
+ charset: 'utf-8',
31
+ charsetSentinel: false,
32
+ delimiter: '&',
33
+ encode: true,
34
+ encodeDotInKeys: false,
35
+ encoder: encode,
36
+ encodeValuesOnly: false,
37
+ format: default_format,
38
+ formatter: default_formatter,
39
+ /** @deprecated */
40
+ indices: false,
41
+ serializeDate(date) {
42
+ return (toISOString ??= Function.prototype.call.bind(Date.prototype.toISOString))(date);
43
+ },
44
+ skipNulls: false,
45
+ strictNullHandling: false,
46
+ } as NonNullableProperties<StringifyOptions & { formatter: (typeof formatters)['RFC1738'] }>;
47
+
48
+ function is_non_nullish_primitive(v: unknown): v is string | number | boolean | symbol | bigint {
49
+ return (
50
+ typeof v === 'string' ||
51
+ typeof v === 'number' ||
52
+ typeof v === 'boolean' ||
53
+ typeof v === 'symbol' ||
54
+ typeof v === 'bigint'
55
+ );
56
+ }
57
+
58
+ const sentinel = {};
59
+
60
+ function inner_stringify(
61
+ object: any,
62
+ prefix: PropertyKey,
63
+ generateArrayPrefix: StringifyOptions['arrayFormat'] | ((prefix: string, key: string) => string),
64
+ commaRoundTrip: boolean,
65
+ allowEmptyArrays: boolean,
66
+ strictNullHandling: boolean,
67
+ skipNulls: boolean,
68
+ encodeDotInKeys: boolean,
69
+ encoder: StringifyOptions['encoder'],
70
+ filter: StringifyOptions['filter'],
71
+ sort: StringifyOptions['sort'],
72
+ allowDots: StringifyOptions['allowDots'],
73
+ serializeDate: StringifyOptions['serializeDate'],
74
+ format: StringifyOptions['format'],
75
+ formatter: StringifyOptions['formatter'],
76
+ encodeValuesOnly: boolean,
77
+ charset: StringifyOptions['charset'],
78
+ sideChannel: WeakMap<any, any>,
79
+ ) {
80
+ let obj = object;
81
+
82
+ let tmp_sc = sideChannel;
83
+ let step = 0;
84
+ let find_flag = false;
85
+ while ((tmp_sc = tmp_sc.get(sentinel)) !== void undefined && !find_flag) {
86
+ // Where object last appeared in the ref tree
87
+ const pos = tmp_sc.get(object);
88
+ step += 1;
89
+ if (typeof pos !== 'undefined') {
90
+ if (pos === step) {
91
+ throw new RangeError('Cyclic object value');
92
+ } else {
93
+ find_flag = true; // Break while
94
+ }
95
+ }
96
+ if (typeof tmp_sc.get(sentinel) === 'undefined') {
97
+ step = 0;
98
+ }
99
+ }
100
+
101
+ if (typeof filter === 'function') {
102
+ obj = filter(prefix, obj);
103
+ } else if (obj instanceof Date) {
104
+ obj = serializeDate?.(obj);
105
+ } else if (generateArrayPrefix === 'comma' && isArray(obj)) {
106
+ obj = maybe_map(obj, function (value) {
107
+ if (value instanceof Date) {
108
+ return serializeDate?.(value);
109
+ }
110
+ return value;
111
+ });
112
+ }
113
+
114
+ if (obj === null) {
115
+ if (strictNullHandling) {
116
+ return encoder && !encodeValuesOnly ?
117
+ // @ts-expect-error
118
+ encoder(prefix, defaults.encoder, charset, 'key', format)
119
+ : prefix;
120
+ }
121
+
122
+ obj = '';
123
+ }
124
+
125
+ if (is_non_nullish_primitive(obj) || is_buffer(obj)) {
126
+ if (encoder) {
127
+ const key_value =
128
+ encodeValuesOnly ? prefix
129
+ // @ts-expect-error
130
+ : encoder(prefix, defaults.encoder, charset, 'key', format);
131
+ return [
132
+ formatter?.(key_value) +
133
+ '=' +
134
+ // @ts-expect-error
135
+ formatter?.(encoder(obj, defaults.encoder, charset, 'value', format)),
136
+ ];
137
+ }
138
+ return [formatter?.(prefix) + '=' + formatter?.(String(obj))];
139
+ }
140
+
141
+ const values: string[] = [];
142
+
143
+ if (typeof obj === 'undefined') {
144
+ return values;
145
+ }
146
+
147
+ let obj_keys;
148
+ if (generateArrayPrefix === 'comma' && isArray(obj)) {
149
+ // we need to join elements in
150
+ if (encodeValuesOnly && encoder) {
151
+ // @ts-expect-error values only
152
+ obj = maybe_map(obj, encoder);
153
+ }
154
+ obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];
155
+ } else if (isArray(filter)) {
156
+ obj_keys = filter;
157
+ } else {
158
+ const keys = Object.keys(obj);
159
+ obj_keys = sort ? keys.sort(sort) : keys;
160
+ }
161
+
162
+ const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix);
163
+
164
+ const adjusted_prefix =
165
+ commaRoundTrip && isArray(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix;
166
+
167
+ if (allowEmptyArrays && isArray(obj) && obj.length === 0) {
168
+ return adjusted_prefix + '[]';
169
+ }
170
+
171
+ for (let j = 0; j < obj_keys.length; ++j) {
172
+ const key = obj_keys[j];
173
+ const value =
174
+ // @ts-ignore
175
+ typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key as any];
176
+
177
+ if (skipNulls && value === null) {
178
+ continue;
179
+ }
180
+
181
+ // @ts-ignore
182
+ const encoded_key = allowDots && encodeDotInKeys ? (key as any).replace(/\./g, '%2E') : key;
183
+ const key_prefix =
184
+ isArray(obj) ?
185
+ typeof generateArrayPrefix === 'function' ?
186
+ generateArrayPrefix(adjusted_prefix, encoded_key)
187
+ : adjusted_prefix
188
+ : adjusted_prefix + (allowDots ? '.' + encoded_key : '[' + encoded_key + ']');
189
+
190
+ sideChannel.set(object, step);
191
+ const valueSideChannel = new WeakMap();
192
+ valueSideChannel.set(sentinel, sideChannel);
193
+ push_to_array(
194
+ values,
195
+ inner_stringify(
196
+ value,
197
+ key_prefix,
198
+ generateArrayPrefix,
199
+ commaRoundTrip,
200
+ allowEmptyArrays,
201
+ strictNullHandling,
202
+ skipNulls,
203
+ encodeDotInKeys,
204
+ // @ts-ignore
205
+ generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder,
206
+ filter,
207
+ sort,
208
+ allowDots,
209
+ serializeDate,
210
+ format,
211
+ formatter,
212
+ encodeValuesOnly,
213
+ charset,
214
+ valueSideChannel,
215
+ ),
216
+ );
217
+ }
218
+
219
+ return values;
220
+ }
221
+
222
+ function normalize_stringify_options(
223
+ opts: StringifyOptions = defaults,
224
+ ): NonNullableProperties<Omit<StringifyOptions, 'indices'>> & { indices?: boolean } {
225
+ if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') {
226
+ throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided');
227
+ }
228
+
229
+ if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') {
230
+ throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided');
231
+ }
232
+
233
+ if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') {
234
+ throw new TypeError('Encoder has to be a function.');
235
+ }
236
+
237
+ const charset = opts.charset || defaults.charset;
238
+ if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {
239
+ throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');
240
+ }
241
+
242
+ let format = default_format;
243
+ if (typeof opts.format !== 'undefined') {
244
+ if (!has(formatters, opts.format)) {
245
+ throw new TypeError('Unknown format option provided.');
246
+ }
247
+ format = opts.format;
248
+ }
249
+ const formatter = formatters[format];
250
+
251
+ let filter = defaults.filter;
252
+ if (typeof opts.filter === 'function' || isArray(opts.filter)) {
253
+ filter = opts.filter;
254
+ }
255
+
256
+ let arrayFormat: StringifyOptions['arrayFormat'];
257
+ if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) {
258
+ arrayFormat = opts.arrayFormat;
259
+ } else if ('indices' in opts) {
260
+ arrayFormat = opts.indices ? 'indices' : 'repeat';
261
+ } else {
262
+ arrayFormat = defaults.arrayFormat;
263
+ }
264
+
265
+ if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') {
266
+ throw new TypeError('`commaRoundTrip` must be a boolean, or absent');
267
+ }
268
+
269
+ const allowDots =
270
+ typeof opts.allowDots === 'undefined' ?
271
+ !!opts.encodeDotInKeys === true ?
272
+ true
273
+ : defaults.allowDots
274
+ : !!opts.allowDots;
275
+
276
+ return {
277
+ addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,
278
+ // @ts-ignore
279
+ allowDots: allowDots,
280
+ allowEmptyArrays:
281
+ typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,
282
+ arrayFormat: arrayFormat,
283
+ charset: charset,
284
+ charsetSentinel:
285
+ typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,
286
+ commaRoundTrip: !!opts.commaRoundTrip,
287
+ delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,
288
+ encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,
289
+ encodeDotInKeys:
290
+ typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys,
291
+ encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,
292
+ encodeValuesOnly:
293
+ typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,
294
+ filter: filter,
295
+ format: format,
296
+ formatter: formatter,
297
+ serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,
298
+ skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,
299
+ // @ts-ignore
300
+ sort: typeof opts.sort === 'function' ? opts.sort : null,
301
+ strictNullHandling:
302
+ typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling,
303
+ };
304
+ }
305
+
306
+ export function stringify(object: any, opts: StringifyOptions = {}) {
307
+ let obj = object;
308
+ const options = normalize_stringify_options(opts);
309
+
310
+ let obj_keys: PropertyKey[] | undefined;
311
+ let filter;
312
+
313
+ if (typeof options.filter === 'function') {
314
+ filter = options.filter;
315
+ obj = filter('', obj);
316
+ } else if (isArray(options.filter)) {
317
+ filter = options.filter;
318
+ obj_keys = filter;
319
+ }
320
+
321
+ const keys: string[] = [];
322
+
323
+ if (typeof obj !== 'object' || obj === null) {
324
+ return '';
325
+ }
326
+
327
+ const generateArrayPrefix = array_prefix_generators[options.arrayFormat];
328
+ const commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip;
329
+
330
+ if (!obj_keys) {
331
+ obj_keys = Object.keys(obj);
332
+ }
333
+
334
+ if (options.sort) {
335
+ obj_keys.sort(options.sort);
336
+ }
337
+
338
+ const sideChannel = new WeakMap();
339
+ for (let i = 0; i < obj_keys.length; ++i) {
340
+ const key = obj_keys[i]!;
341
+
342
+ if (options.skipNulls && obj[key] === null) {
343
+ continue;
344
+ }
345
+ push_to_array(
346
+ keys,
347
+ inner_stringify(
348
+ obj[key],
349
+ key,
350
+ // @ts-expect-error
351
+ generateArrayPrefix,
352
+ commaRoundTrip,
353
+ options.allowEmptyArrays,
354
+ options.strictNullHandling,
355
+ options.skipNulls,
356
+ options.encodeDotInKeys,
357
+ options.encode ? options.encoder : null,
358
+ options.filter,
359
+ options.sort,
360
+ options.allowDots,
361
+ options.serializeDate,
362
+ options.format,
363
+ options.formatter,
364
+ options.encodeValuesOnly,
365
+ options.charset,
366
+ sideChannel,
367
+ ),
368
+ );
369
+ }
370
+
371
+ const joined = keys.join(options.delimiter);
372
+ let prefix = options.addQueryPrefix === true ? '?' : '';
373
+
374
+ if (options.charsetSentinel) {
375
+ if (options.charset === 'iso-8859-1') {
376
+ // encodeURIComponent('&#10003;'), the "numeric entity" representation of a checkmark
377
+ prefix += 'utf8=%26%2310003%3B&';
378
+ } else {
379
+ // encodeURIComponent('✓')
380
+ prefix += 'utf8=%E2%9C%93&';
381
+ }
382
+ }
383
+
384
+ return joined.length > 0 ? prefix + joined : '';
385
+ }