@trpc/client 11.0.0-alpha-tmp-export-from-main.213 → 11.0.0-alpha-tmp-export-from-main.217

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 (45) hide show
  1. package/dist/{TRPCClientError-3414c3d5.mjs → TRPCClientError.mjs} +1 -1
  2. package/dist/createTRPCClient.js +50 -0
  3. package/dist/createTRPCClient.mjs +45 -0
  4. package/dist/createTRPCUntypedClient.js +10 -0
  5. package/dist/createTRPCUntypedClient.mjs +7 -0
  6. package/dist/getFetch.js +17 -0
  7. package/dist/getFetch.mjs +15 -0
  8. package/dist/index.js +32 -367
  9. package/dist/index.mjs +9 -351
  10. package/dist/internals/TRPCUntypedClient.js +113 -0
  11. package/dist/internals/TRPCUntypedClient.mjs +111 -0
  12. package/dist/{httpBatchLink-c5101526.mjs → internals/dataLoader.js} +2 -116
  13. package/dist/{httpBatchLink-63113d09.js → internals/dataLoader.mjs} +1 -120
  14. package/dist/internals/getAbortController.js +18 -0
  15. package/dist/internals/getAbortController.mjs +16 -0
  16. package/dist/links/httpBatchLink.js +37 -8
  17. package/dist/links/httpBatchLink.mjs +39 -4
  18. package/dist/links/httpBatchStreamLink.js +43 -0
  19. package/dist/links/httpBatchStreamLink.mjs +41 -0
  20. package/dist/links/httpFormDataLink.js +31 -0
  21. package/dist/links/httpFormDataLink.mjs +29 -0
  22. package/dist/links/httpLink.js +2 -4
  23. package/dist/links/httpLink.mjs +2 -2
  24. package/dist/{splitLink-f52aa788.js → links/internals/createChain.js} +0 -22
  25. package/dist/{splitLink-47716d78.mjs → links/internals/createChain.mjs} +1 -22
  26. package/dist/links/internals/createHTTPBatchLink.js +85 -0
  27. package/dist/links/internals/createHTTPBatchLink.mjs +83 -0
  28. package/dist/links/internals/getTextDecoder.js +18 -0
  29. package/dist/links/internals/getTextDecoder.mjs +16 -0
  30. package/dist/{httpUtils-60af4c3d.js → links/internals/httpUtils.js} +5 -33
  31. package/dist/{httpUtils-82ae6a64.mjs → links/internals/httpUtils.mjs} +4 -31
  32. package/dist/links/internals/parseJSONStream.js +118 -0
  33. package/dist/links/internals/parseJSONStream.mjs +115 -0
  34. package/dist/links/loggerLink.js +4 -2
  35. package/dist/links/loggerLink.mjs +4 -0
  36. package/dist/links/splitLink.js +23 -6
  37. package/dist/links/splitLink.mjs +25 -2
  38. package/dist/links/wsLink.js +1 -3
  39. package/dist/links/wsLink.mjs +1 -1
  40. package/package.json +4 -4
  41. package/dist/TRPCClientError-27d80214.js +0 -61
  42. package/dist/httpBatchLink-1de0fe31.js +0 -246
  43. package/dist/httpUtils-49fa3edc.js +0 -151
  44. package/dist/splitLink-7dca81ef.js +0 -41
  45. /package/dist/{TRPCClientError-67aefe1c.js → TRPCClientError.js} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trpc/client",
3
- "version": "11.0.0-alpha-tmp-export-from-main.213+855f8bc75",
3
+ "version": "11.0.0-alpha-tmp-export-from-main.217+ef6ef3e1c",
4
4
  "description": "The tRPC client library",
5
5
  "author": "KATT",
6
6
  "license": "MIT",
@@ -100,7 +100,7 @@
100
100
  "!**/*.test.*"
101
101
  ],
102
102
  "dependencies": {
103
- "@trpc/core": "11.0.0-alpha-tmp-export-from-main.213+855f8bc75"
103
+ "@trpc/core": "11.0.0-alpha-tmp-export-from-main.217+ef6ef3e1c"
104
104
  },
105
105
  "devDependencies": {
106
106
  "@testing-library/dom": "^9.0.0",
@@ -109,7 +109,7 @@
109
109
  "eslint": "^8.40.0",
110
110
  "isomorphic-fetch": "^3.0.0",
111
111
  "node-fetch": "^3.3.0",
112
- "rollup": "^2.79.1",
112
+ "rollup": "^4.9.5",
113
113
  "tsx": "^4.0.0",
114
114
  "undici": "^6.0.1",
115
115
  "vitest": "^0.32.0"
@@ -120,5 +120,5 @@
120
120
  "funding": [
121
121
  "https://trpc.io/sponsor"
122
122
  ],
123
- "gitHead": "855f8bc75d6f11780eabf92376c6297f9edf6107"
123
+ "gitHead": "ef6ef3e1c3a4966d30335864d6edf9c94f096717"
124
124
  }
@@ -1,61 +0,0 @@
1
- import { getCauseFromUnknown, isObject } from '@trpc/core';
2
-
3
- function isTRPCClientError(cause) {
4
- return (cause instanceof TRPCClientError ||
5
- /**
6
- * @deprecated
7
- * Delete in next major
8
- */
9
- (cause instanceof Error && cause.name === 'TRPCClientError'));
10
- }
11
- function isTRPCErrorResponse(obj) {
12
- return (isObject(obj) &&
13
- isObject(obj['error']) &&
14
- typeof obj['error']['code'] === 'number' &&
15
- typeof obj['error']['message'] === 'string');
16
- }
17
- class TRPCClientError extends Error {
18
- constructor(message, opts) {
19
- const cause = opts?.cause;
20
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
21
- // @ts-ignore https://github.com/tc39/proposal-error-cause
22
- super(message, { cause });
23
- this.meta = opts?.meta;
24
- this.cause = cause;
25
- this.shape = opts?.result?.error;
26
- this.data = opts?.result?.error.data;
27
- this.name = 'TRPCClientError';
28
- Object.setPrototypeOf(this, TRPCClientError.prototype);
29
- }
30
- static from(_cause, opts = {}) {
31
- const cause = _cause;
32
- if (isTRPCClientError(cause)) {
33
- if (opts.meta) {
34
- // Decorate with meta error data
35
- cause.meta = {
36
- ...cause.meta,
37
- ...opts.meta,
38
- };
39
- }
40
- return cause;
41
- }
42
- if (isTRPCErrorResponse(cause)) {
43
- return new TRPCClientError(cause.error.message, {
44
- ...opts,
45
- result: cause,
46
- });
47
- }
48
- if (!(cause instanceof Error)) {
49
- return new TRPCClientError('Unknown error', {
50
- ...opts,
51
- cause: cause,
52
- });
53
- }
54
- return new TRPCClientError(cause.message, {
55
- ...opts,
56
- cause: getCauseFromUnknown(cause),
57
- });
58
- }
59
- }
60
-
61
- export { TRPCClientError as T };
@@ -1,246 +0,0 @@
1
- import { observable, transformResult } from '@trpc/core';
2
- import { T as TRPCClientError } from './TRPCClientError-27d80214.js';
3
- import { r as resolveHTTPLinkOptions, g as getUrl, j as jsonHttpRequester } from './httpUtils-49fa3edc.js';
4
-
5
- /**
6
- * A function that should never be called unless we messed something up.
7
- */
8
- const throwFatalError = () => {
9
- throw new Error('Something went wrong. Please submit an issue at https://github.com/trpc/trpc/issues/new');
10
- };
11
- /**
12
- * Dataloader that's very inspired by https://github.com/graphql/dataloader
13
- * Less configuration, no caching, and allows you to cancel requests
14
- * When cancelling a single fetch the whole batch will be cancelled only when _all_ items are cancelled
15
- */
16
- function dataLoader(batchLoader) {
17
- let pendingItems = null;
18
- let dispatchTimer = null;
19
- const destroyTimerAndPendingItems = () => {
20
- clearTimeout(dispatchTimer);
21
- dispatchTimer = null;
22
- pendingItems = null;
23
- };
24
- /**
25
- * Iterate through the items and split them into groups based on the `batchLoader`'s validate function
26
- */
27
- function groupItems(items) {
28
- const groupedItems = [[]];
29
- let index = 0;
30
- while (true) {
31
- const item = items[index];
32
- if (!item) {
33
- // we're done
34
- break;
35
- }
36
- const lastGroup = groupedItems[groupedItems.length - 1];
37
- if (item.aborted) {
38
- // Item was aborted before it was dispatched
39
- item.reject?.(new Error('Aborted'));
40
- index++;
41
- continue;
42
- }
43
- const isValid = batchLoader.validate(lastGroup.concat(item).map((it) => it.key));
44
- if (isValid) {
45
- lastGroup.push(item);
46
- index++;
47
- continue;
48
- }
49
- if (lastGroup.length === 0) {
50
- item.reject?.(new Error('Input is too big for a single dispatch'));
51
- index++;
52
- continue;
53
- }
54
- // Create new group, next iteration will try to add the item to that
55
- groupedItems.push([]);
56
- }
57
- return groupedItems;
58
- }
59
- function dispatch() {
60
- const groupedItems = groupItems(pendingItems);
61
- destroyTimerAndPendingItems();
62
- // Create batches for each group of items
63
- for (const items of groupedItems) {
64
- if (!items.length) {
65
- continue;
66
- }
67
- const batch = {
68
- items,
69
- cancel: throwFatalError,
70
- };
71
- for (const item of items) {
72
- item.batch = batch;
73
- }
74
- const unitResolver = (index, value) => {
75
- const item = batch.items[index];
76
- item.resolve?.(value);
77
- item.batch = null;
78
- item.reject = null;
79
- item.resolve = null;
80
- };
81
- const { promise, cancel } = batchLoader.fetch(batch.items.map((_item) => _item.key), unitResolver);
82
- batch.cancel = cancel;
83
- promise
84
- .then((result) => {
85
- for (let i = 0; i < result.length; i++) {
86
- const value = result[i];
87
- unitResolver(i, value);
88
- }
89
- for (const item of batch.items) {
90
- item.reject?.(new Error('Missing result'));
91
- item.batch = null;
92
- }
93
- })
94
- .catch((cause) => {
95
- for (const item of batch.items) {
96
- item.reject?.(cause);
97
- item.batch = null;
98
- }
99
- });
100
- }
101
- }
102
- function load(key) {
103
- const item = {
104
- aborted: false,
105
- key,
106
- batch: null,
107
- resolve: throwFatalError,
108
- reject: throwFatalError,
109
- };
110
- const promise = new Promise((resolve, reject) => {
111
- item.reject = reject;
112
- item.resolve = resolve;
113
- if (!pendingItems) {
114
- pendingItems = [];
115
- }
116
- pendingItems.push(item);
117
- });
118
- if (!dispatchTimer) {
119
- dispatchTimer = setTimeout(dispatch);
120
- }
121
- const cancel = () => {
122
- item.aborted = true;
123
- if (item.batch?.items.every((item) => item.aborted)) {
124
- // All items in the batch have been cancelled
125
- item.batch.cancel();
126
- item.batch = null;
127
- }
128
- };
129
- return { promise, cancel };
130
- }
131
- return {
132
- load,
133
- };
134
- }
135
-
136
- /**
137
- * @internal
138
- */
139
- function createHTTPBatchLink(requester) {
140
- return function httpBatchLink(opts) {
141
- const resolvedOpts = resolveHTTPLinkOptions(opts);
142
- const maxURLLength = opts.maxURLLength ?? Infinity;
143
- // initialized config
144
- return (runtime) => {
145
- const batchLoader = (type) => {
146
- const validate = (batchOps) => {
147
- if (maxURLLength === Infinity) {
148
- // escape hatch for quick calcs
149
- return true;
150
- }
151
- const path = batchOps.map((op) => op.path).join(',');
152
- const inputs = batchOps.map((op) => op.input);
153
- const url = getUrl({
154
- ...resolvedOpts,
155
- runtime,
156
- type,
157
- path,
158
- inputs,
159
- });
160
- return url.length <= maxURLLength;
161
- };
162
- const fetch = requester({
163
- ...resolvedOpts,
164
- runtime,
165
- type,
166
- opts,
167
- });
168
- return { validate, fetch };
169
- };
170
- const query = dataLoader(batchLoader('query'));
171
- const mutation = dataLoader(batchLoader('mutation'));
172
- const subscription = dataLoader(batchLoader('subscription'));
173
- const loaders = { query, subscription, mutation };
174
- return ({ op }) => {
175
- return observable((observer) => {
176
- const loader = loaders[op.type];
177
- const { promise, cancel } = loader.load(op);
178
- let _res = undefined;
179
- promise
180
- .then((res) => {
181
- _res = res;
182
- const transformed = transformResult(res.json, runtime.transformer);
183
- if (!transformed.ok) {
184
- observer.error(TRPCClientError.from(transformed.error, {
185
- meta: res.meta,
186
- }));
187
- return;
188
- }
189
- observer.next({
190
- context: res.meta,
191
- result: transformed.result,
192
- });
193
- observer.complete();
194
- })
195
- .catch((err) => {
196
- observer.error(TRPCClientError.from(err, {
197
- meta: _res?.meta,
198
- }));
199
- });
200
- return () => {
201
- cancel();
202
- };
203
- });
204
- };
205
- };
206
- };
207
- }
208
-
209
- const batchRequester = (requesterOpts) => {
210
- return (batchOps) => {
211
- const path = batchOps.map((op) => op.path).join(',');
212
- const inputs = batchOps.map((op) => op.input);
213
- const { promise, cancel } = jsonHttpRequester({
214
- ...requesterOpts,
215
- path,
216
- inputs,
217
- headers() {
218
- if (!requesterOpts.opts.headers) {
219
- return {};
220
- }
221
- if (typeof requesterOpts.opts.headers === 'function') {
222
- return requesterOpts.opts.headers({
223
- opList: batchOps,
224
- });
225
- }
226
- return requesterOpts.opts.headers;
227
- },
228
- });
229
- return {
230
- promise: promise.then((res) => {
231
- const resJSON = Array.isArray(res.json)
232
- ? res.json
233
- : batchOps.map(() => res.json);
234
- const result = resJSON.map((item) => ({
235
- meta: res.meta,
236
- json: item,
237
- }));
238
- return result;
239
- }),
240
- cancel,
241
- };
242
- };
243
- };
244
- const httpBatchLink = createHTTPBatchLink(batchRequester);
245
-
246
- export { createHTTPBatchLink as c, httpBatchLink as h };
@@ -1,151 +0,0 @@
1
- import { T as TRPCClientError } from './TRPCClientError-27d80214.js';
2
-
3
- const isFunction = (fn) => typeof fn === 'function';
4
- function getFetch(customFetchImpl) {
5
- if (customFetchImpl) {
6
- return customFetchImpl;
7
- }
8
- if (typeof window !== 'undefined' && isFunction(window.fetch)) {
9
- return window.fetch;
10
- }
11
- if (typeof globalThis !== 'undefined' && isFunction(globalThis.fetch)) {
12
- return globalThis.fetch;
13
- }
14
- throw new Error('No fetch implementation found');
15
- }
16
-
17
- function getAbortController(customAbortControllerImpl) {
18
- if (customAbortControllerImpl) {
19
- return customAbortControllerImpl;
20
- }
21
- // eslint-disable-next-line @typescript-eslint/prefer-optional-chain
22
- if (typeof window !== 'undefined' && window.AbortController) {
23
- return window.AbortController;
24
- }
25
- // eslint-disable-next-line @typescript-eslint/prefer-optional-chain
26
- if (typeof globalThis !== 'undefined' && globalThis.AbortController) {
27
- return globalThis.AbortController;
28
- }
29
- return null;
30
- }
31
-
32
- function resolveHTTPLinkOptions(opts) {
33
- return {
34
- url: opts.url.toString().replace(/\/$/, ''), // Remove any trailing slashes
35
- fetch: opts.fetch,
36
- AbortController: getAbortController(opts.AbortController),
37
- };
38
- }
39
- // https://github.com/trpc/trpc/pull/669
40
- function arrayToDict(array) {
41
- const dict = {};
42
- for (let index = 0; index < array.length; index++) {
43
- const element = array[index];
44
- dict[index] = element;
45
- }
46
- return dict;
47
- }
48
- const METHOD = {
49
- query: 'GET',
50
- mutation: 'POST',
51
- };
52
- function getInput(opts) {
53
- return 'input' in opts
54
- ? opts.runtime.transformer.serialize(opts.input)
55
- : arrayToDict(opts.inputs.map((_input) => opts.runtime.transformer.serialize(_input)));
56
- }
57
- const getUrl = (opts) => {
58
- let url = opts.url + '/' + opts.path;
59
- const queryParts = [];
60
- if ('inputs' in opts) {
61
- queryParts.push('batch=1');
62
- }
63
- if (opts.type === 'query') {
64
- const input = getInput(opts);
65
- if (input !== undefined) {
66
- queryParts.push(`input=${encodeURIComponent(JSON.stringify(input))}`);
67
- }
68
- }
69
- if (queryParts.length) {
70
- url += '?' + queryParts.join('&');
71
- }
72
- return url;
73
- };
74
- const getBody = (opts) => {
75
- if (opts.type === 'query') {
76
- return undefined;
77
- }
78
- const input = getInput(opts);
79
- return input !== undefined ? JSON.stringify(input) : undefined;
80
- };
81
- const jsonHttpRequester = (opts) => {
82
- return httpRequest({
83
- ...opts,
84
- contentTypeHeader: 'application/json',
85
- getUrl,
86
- getBody,
87
- });
88
- };
89
- async function fetchHTTPResponse(opts, ac) {
90
- const url = opts.getUrl(opts);
91
- const body = opts.getBody(opts);
92
- const { type } = opts;
93
- const resolvedHeaders = await (async () => {
94
- const heads = await opts.headers();
95
- if (Symbol.iterator in heads) {
96
- return Object.fromEntries(heads);
97
- }
98
- return heads;
99
- })();
100
- /* istanbul ignore if -- @preserve */
101
- if (type === 'subscription') {
102
- throw new Error('Subscriptions should use wsLink');
103
- }
104
- const headers = {
105
- ...(opts.contentTypeHeader
106
- ? { 'content-type': opts.contentTypeHeader }
107
- : {}),
108
- ...(opts.batchModeHeader
109
- ? { 'trpc-batch-mode': opts.batchModeHeader }
110
- : {}),
111
- ...resolvedHeaders,
112
- };
113
- return getFetch(opts.fetch)(url, {
114
- method: METHOD[type],
115
- signal: ac?.signal,
116
- body: body,
117
- headers,
118
- });
119
- }
120
- function httpRequest(opts) {
121
- const ac = opts.AbortController ? new opts.AbortController() : null;
122
- const meta = {};
123
- let done = false;
124
- const promise = new Promise((resolve, reject) => {
125
- fetchHTTPResponse(opts, ac)
126
- .then((_res) => {
127
- meta.response = _res;
128
- done = true;
129
- return _res.json();
130
- })
131
- .then((json) => {
132
- meta.responseJSON = json;
133
- resolve({
134
- json: json,
135
- meta,
136
- });
137
- })
138
- .catch((err) => {
139
- done = true;
140
- reject(TRPCClientError.from(err, { meta }));
141
- });
142
- });
143
- const cancel = () => {
144
- if (!done) {
145
- ac?.abort();
146
- }
147
- };
148
- return { promise, cancel };
149
- }
150
-
151
- export { getBody as a, getFetch as b, fetchHTTPResponse as f, getUrl as g, httpRequest as h, jsonHttpRequester as j, resolveHTTPLinkOptions as r };
@@ -1,41 +0,0 @@
1
- import { observable } from '@trpc/core';
2
-
3
- /** @internal */
4
- function createChain(opts) {
5
- return observable((observer) => {
6
- function execute(index = 0, op = opts.op) {
7
- const next = opts.links[index];
8
- if (!next) {
9
- throw new Error('No more links to execute - did you forget to add an ending link?');
10
- }
11
- const subscription = next({
12
- op,
13
- next(nextOp) {
14
- const nextObserver = execute(index + 1, nextOp);
15
- return nextObserver;
16
- },
17
- });
18
- return subscription;
19
- }
20
- const obs$ = execute();
21
- return obs$.subscribe(observer);
22
- });
23
- }
24
-
25
- function asArray(value) {
26
- return Array.isArray(value) ? value : [value];
27
- }
28
- function splitLink(opts) {
29
- return (runtime) => {
30
- const yes = asArray(opts.true).map((link) => link(runtime));
31
- const no = asArray(opts.false).map((link) => link(runtime));
32
- return (props) => {
33
- return observable((observer) => {
34
- const links = opts.condition(props.op) ? yes : no;
35
- return createChain({ op: props.op, links }).subscribe(observer);
36
- });
37
- };
38
- };
39
- }
40
-
41
- export { createChain as c, splitLink as s };