@hyper-fetch/core 9.6.1 → 9.7.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 (134) hide show
  1. package/__tests__/features/adapter/adapter.bindings.progress.spec.ts +120 -0
  2. package/__tests__/features/adapter/adapter.bindings.spec.ts +4 -6
  3. package/__tests__/features/adapter/adapter.defaults.spec.ts +87 -0
  4. package/__tests__/features/adapter/adapter.mapping.spec.ts +257 -0
  5. package/__tests__/features/cache/cache.lazy-storage.clear.spec.ts +145 -0
  6. package/__tests__/features/cache/cache.lazy-storage.resilience.spec.ts +667 -0
  7. package/__tests__/features/cache/cache.scoped-events.spec.ts +183 -0
  8. package/__tests__/features/cache/cache.semantics.spec.ts +785 -0
  9. package/__tests__/features/cache/cache.structural-sharing.spec.ts +565 -0
  10. package/__tests__/features/cache/cache.timing.spec.ts +448 -0
  11. package/__tests__/features/client/client.clear.spec.ts +313 -0
  12. package/__tests__/features/client/client.configuration.spec.ts +416 -0
  13. package/__tests__/features/client/client.hydration.round-trip.spec.ts +324 -0
  14. package/__tests__/features/client/client.interceptor.spec.ts +54 -45
  15. package/__tests__/features/client/client.interceptors.pipeline.spec.ts +599 -0
  16. package/__tests__/features/client/client.user-errors.spec.ts +220 -0
  17. package/__tests__/features/dispatcher/dispatcher.cleanup.spec.ts +534 -0
  18. package/__tests__/features/dispatcher/dispatcher.control.spec.ts +381 -0
  19. package/__tests__/features/dispatcher/dispatcher.modes.spec.ts +527 -0
  20. package/__tests__/features/dispatcher/dispatcher.offline.spec.ts +278 -0
  21. package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +35 -12
  22. package/__tests__/features/dispatcher/dispatcher.reentrancy.spec.ts +309 -0
  23. package/__tests__/features/dispatcher/dispatcher.response-order.spec.ts +241 -0
  24. package/__tests__/features/dispatcher/dispatcher.retry-flow.spec.ts +554 -0
  25. package/__tests__/features/dispatcher/dispatcher.retry-removal.spec.ts +196 -0
  26. package/__tests__/features/dispatcher/dispatcher.retry.spec.ts +4 -3
  27. package/__tests__/features/http-adapter/http-adapter.e2e.spec.ts +917 -0
  28. package/__tests__/features/managers/app/app.manager.events.spec.ts +434 -0
  29. package/__tests__/features/managers/logger/logger.levels.spec.ts +199 -0
  30. package/__tests__/features/managers/request/request.manager.abort.spec.ts +449 -0
  31. package/__tests__/features/mocker/mocker.base.spec.ts +22 -3
  32. package/__tests__/features/mocker/mocker.errors.spec.ts +99 -0
  33. package/__tests__/features/mocker/mocker.outcomes.spec.ts +308 -0
  34. package/__tests__/features/optimistic/optimistic.concurrency.spec.ts +278 -0
  35. package/__tests__/features/optimistic/optimistic.helpers.spec.ts +307 -0
  36. package/__tests__/features/optimistic/optimistic.matrix.spec.ts +315 -0
  37. package/__tests__/features/optimistic/optimistic.races.spec.ts +270 -0
  38. package/__tests__/features/optimistic/optimistic.random.spec.ts +191 -0
  39. package/__tests__/features/optimistic/optimistic.rollback.spec.ts +1001 -0
  40. package/__tests__/features/optimistic/optimistic.typescript.spec.ts +196 -0
  41. package/__tests__/features/plugin/plugin.lifecycle.spec.ts +457 -0
  42. package/__tests__/features/request/request.async-mapper-removal.spec.ts +138 -0
  43. package/__tests__/features/request/request.immutability.spec.ts +259 -0
  44. package/__tests__/features/request/request.inference.spec.ts +269 -0
  45. package/__tests__/features/request/request.lifecycle.spec.ts +682 -0
  46. package/__tests__/features/request/request.optimistic-settlement.spec.ts +35 -17
  47. package/__tests__/features/request/request.optimistic.spec.ts +12 -1
  48. package/__tests__/features/request/request.values.spec.ts +408 -0
  49. package/__tests__/features/sdk/sdk.builder.spec.ts +304 -0
  50. package/__tests__/features/utils/emitter.listeners.spec.ts +202 -0
  51. package/__tests__/utils/controlled-adapter.utils.ts +119 -0
  52. package/__tests__/utils/fixtures.utils.ts +193 -0
  53. package/__tests__/utils/optimistic.utils.ts +124 -0
  54. package/dist/adapter/adapter.bindings.d.ts.map +1 -1
  55. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  56. package/dist/cache/cache.d.ts +12 -1
  57. package/dist/cache/cache.d.ts.map +1 -1
  58. package/dist/cache/cache.events.d.ts +20 -6
  59. package/dist/cache/cache.events.d.ts.map +1 -1
  60. package/dist/cache/cache.utils.d.ts +1 -0
  61. package/dist/cache/cache.utils.d.ts.map +1 -1
  62. package/dist/client/client.d.ts +3 -3
  63. package/dist/client/client.d.ts.map +1 -1
  64. package/dist/client/client.utils.d.ts.map +1 -1
  65. package/dist/dispatcher/dispatcher.d.ts +26 -5
  66. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  67. package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
  68. package/dist/index.d.ts +1 -0
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.mjs +2787 -1893
  71. package/dist/index.mjs.map +1 -1
  72. package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
  73. package/dist/managers/app/app.manager.d.ts +9 -0
  74. package/dist/managers/app/app.manager.d.ts.map +1 -1
  75. package/dist/managers/app/app.manager.utils.d.ts.map +1 -1
  76. package/dist/managers/logger/logger.manager.d.ts.map +1 -1
  77. package/dist/managers/request/request.manager.d.ts.map +1 -1
  78. package/dist/managers/request/request.manager.types.d.ts +2 -0
  79. package/dist/managers/request/request.manager.types.d.ts.map +1 -1
  80. package/dist/mocker/mocker.d.ts +1 -1
  81. package/dist/mocker/mocker.d.ts.map +1 -1
  82. package/dist/optimistic/index.d.ts +5 -0
  83. package/dist/optimistic/index.d.ts.map +1 -0
  84. package/dist/optimistic/optimistic.d.ts +67 -0
  85. package/dist/optimistic/optimistic.d.ts.map +1 -0
  86. package/dist/optimistic/optimistic.settlement.d.ts +60 -0
  87. package/dist/optimistic/optimistic.settlement.d.ts.map +1 -0
  88. package/dist/optimistic/optimistic.types.d.ts +109 -0
  89. package/dist/optimistic/optimistic.types.d.ts.map +1 -0
  90. package/dist/optimistic/optimistic.utils.d.ts +29 -0
  91. package/dist/optimistic/optimistic.utils.d.ts.map +1 -0
  92. package/dist/plugin/plugin.d.ts +2 -0
  93. package/dist/plugin/plugin.d.ts.map +1 -1
  94. package/dist/request/request.d.ts +14 -6
  95. package/dist/request/request.d.ts.map +1 -1
  96. package/dist/request/request.types.d.ts +40 -1
  97. package/dist/request/request.types.d.ts.map +1 -1
  98. package/dist/request/request.utils.d.ts.map +1 -1
  99. package/dist/utils/emitter.utils.d.ts.map +1 -1
  100. package/dist/utils/error.utils.d.ts +17 -0
  101. package/dist/utils/error.utils.d.ts.map +1 -0
  102. package/dist/utils/index.d.ts +1 -0
  103. package/dist/utils/index.d.ts.map +1 -1
  104. package/package.json +1 -1
  105. package/src/adapter/adapter.bindings.ts +46 -18
  106. package/src/adapter/adapter.utils.ts +47 -7
  107. package/src/cache/cache.events.ts +24 -8
  108. package/src/cache/cache.ts +110 -21
  109. package/src/cache/cache.utils.ts +33 -10
  110. package/src/client/client.ts +101 -7
  111. package/src/client/client.utils.ts +10 -4
  112. package/src/dispatcher/dispatcher.ts +285 -132
  113. package/src/http-adapter/http-adapter.fetch.ts +15 -3
  114. package/src/index.ts +4 -0
  115. package/src/managers/app/app.manager.constants.ts +12 -1
  116. package/src/managers/app/app.manager.ts +43 -23
  117. package/src/managers/app/app.manager.utils.ts +8 -4
  118. package/src/managers/logger/logger.manager.ts +21 -8
  119. package/src/managers/request/request.manager.ts +7 -1
  120. package/src/managers/request/request.manager.types.ts +2 -0
  121. package/src/mocker/mocker.ts +14 -11
  122. package/src/optimistic/index.ts +4 -0
  123. package/src/optimistic/optimistic.settlement.ts +406 -0
  124. package/src/optimistic/optimistic.ts +162 -0
  125. package/src/optimistic/optimistic.types.ts +175 -0
  126. package/src/optimistic/optimistic.utils.ts +112 -0
  127. package/src/plugin/plugin.ts +6 -0
  128. package/src/request/request.ts +50 -28
  129. package/src/request/request.types.ts +41 -1
  130. package/src/request/request.utils.ts +51 -66
  131. package/src/utils/emitter.utils.ts +9 -2
  132. package/src/utils/error.utils.ts +29 -0
  133. package/src/utils/index.ts +1 -0
  134. package/tsconfig.json +2 -0
@@ -0,0 +1,138 @@
1
+ import { DeletedError } from "adapter";
2
+ import { Client } from "client";
3
+
4
+ const createDeferred = <T = void>() => {
5
+ let resolve!: (value: T) => void;
6
+ const promise = new Promise<T>((done) => {
7
+ resolve = done;
8
+ });
9
+ return { promise, resolve };
10
+ };
11
+
12
+ /**
13
+ * The dispatcher removes a request from its queue right after emitting the response. That removal must neither win
14
+ * over a finished response whose async mapper is still running, nor get lost for a request that waits for a retry.
15
+ */
16
+ describe("Request [ Async response mapper and removal ]", () => {
17
+ const fast = { requestTime: 0, responseTime: 0 };
18
+
19
+ let client = new Client({ url: "http://mocked" });
20
+
21
+ beforeEach(() => {
22
+ client = new Client({ url: "http://mocked" });
23
+ });
24
+
25
+ afterEach(() => {
26
+ vi.useRealTimers();
27
+ });
28
+
29
+ const createRequest = () =>
30
+ client.createRequest<{ response: string; error: { message: string } }>()({ endpoint: "/mapped", method: "POST" });
31
+
32
+ it("should resolve with the mapped response and not report a removal", async () => {
33
+ const request = createRequest()
34
+ .setMock(() => ({ data: "plain", status: 200 }), fast)
35
+ .setResponseMapper(async (response) => ({ ...response, data: `${response.data} mapped` }) as typeof response);
36
+ const onRemove = vi.fn();
37
+ const onResponse = vi.fn();
38
+
39
+ const { data, success, error } = await request.send({ onRemove, onResponse });
40
+
41
+ expect(success).toBe(true);
42
+ expect(error).toBeNull();
43
+ expect(data).toBe("plain mapped");
44
+ expect(onResponse).toHaveBeenCalledTimes(1);
45
+ expect(onRemove).not.toHaveBeenCalled();
46
+ });
47
+
48
+ it("should resolve with the mapped error of a failed request and not report a removal", async () => {
49
+ const request = createRequest()
50
+ .setMock(() => ({ error: { message: "nope" }, status: 400, success: false }), fast)
51
+ .setResponseMapper(async (response) => ({ ...response, error: { message: "mapped nope" } }) as typeof response);
52
+ const onRemove = vi.fn();
53
+
54
+ const { data, success, error, status } = await request.send({ onRemove });
55
+
56
+ expect(success).toBe(false);
57
+ expect(status).toBe(400);
58
+ expect(data).toBeNull();
59
+ expect(error).toEqual({ message: "mapped nope" });
60
+ expect(onRemove).not.toHaveBeenCalled();
61
+ });
62
+
63
+ it("should resolve with the deleted error when removed while the mapper of a retried attempt is running", async () => {
64
+ // The retry timer never fires - only the removal can end this request
65
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
66
+ const mapperStarted = createDeferred();
67
+ const mapperGate = createDeferred();
68
+ const request = createRequest()
69
+ .setRetry(1)
70
+ .setRetryTime(60_000)
71
+ .setMock(() => ({ error: { message: "failed" }, status: 500, success: false }), fast)
72
+ .setResponseMapper(async (response) => {
73
+ mapperStarted.resolve();
74
+ await mapperGate.promise;
75
+ return response;
76
+ });
77
+ const onRemove = vi.fn();
78
+ const onResponse = vi.fn();
79
+ let requestId = "";
80
+
81
+ const response = request.send({
82
+ onBeforeSent: (event) => {
83
+ requestId = event.requestId;
84
+ },
85
+ onRemove,
86
+ onResponse,
87
+ });
88
+ await mapperStarted.promise;
89
+ client.submitDispatcher.delete(request.queryKey, requestId, request.abortKey);
90
+
91
+ // The removal ends the request right away, without waiting for the mapper that is still running
92
+ const { data, error, success, status } = await response;
93
+
94
+ expect(success).toBe(false);
95
+ expect(data).toBeNull();
96
+ expect(status).toBeNull();
97
+ expect(error).toBeInstanceOf(DeletedError);
98
+ expect(onRemove).toHaveBeenCalledTimes(1);
99
+
100
+ // The mapper finishing later changes nothing
101
+ mapperGate.resolve();
102
+ await mapperGate.promise;
103
+ await Promise.resolve();
104
+
105
+ expect(onRemove).toHaveBeenCalledTimes(1);
106
+ expect(onResponse).not.toHaveBeenCalled();
107
+ });
108
+
109
+ it("should resolve with the deleted error when removed while waiting for a retry after the mapper finished", async () => {
110
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
111
+ const mapped = createDeferred();
112
+ const request = createRequest()
113
+ .setRetry(1)
114
+ .setRetryTime(60_000)
115
+ .setMock(() => ({ error: { message: "failed" }, status: 500, success: false }), fast)
116
+ .setResponseMapper(async (response) => {
117
+ // Resolved after this mapper returned, so the send call handled the attempt before the test continues
118
+ queueMicrotask(() => queueMicrotask(() => mapped.resolve()));
119
+ return response;
120
+ });
121
+ const onRemove = vi.fn();
122
+ let requestId = "";
123
+
124
+ const response = request.send({
125
+ onBeforeSent: (event) => {
126
+ requestId = event.requestId;
127
+ },
128
+ onRemove,
129
+ });
130
+ await mapped.promise;
131
+ client.submitDispatcher.delete(request.queryKey, requestId, request.abortKey);
132
+ const { error, success } = await response;
133
+
134
+ expect(success).toBe(false);
135
+ expect(error).toBeInstanceOf(DeletedError);
136
+ expect(onRemove).toHaveBeenCalledTimes(1);
137
+ });
138
+ });
@@ -0,0 +1,259 @@
1
+ import { Client } from "client";
2
+ import type { RequestInstance } from "request";
3
+
4
+ describe("Request [ Immutability ]", () => {
5
+ const client = new Client({ url: "http://immutable" });
6
+ const createRequest = () =>
7
+ client.createRequest<{ response: { id: number }; payload: any; queryParams: any }>()({
8
+ endpoint: "/users/:userId/posts/:postId",
9
+ method: "POST",
10
+ });
11
+
12
+ const mapper = (value: any) => value;
13
+ const callback = () => true;
14
+
15
+ const setters: [name: string, apply: (request: RequestInstance) => RequestInstance, field: string, value: unknown][] =
16
+ [
17
+ ["setHeaders", (request) => request.setHeaders({ "X-Test": "1" }), "headers", { "X-Test": "1" }],
18
+ ["setAuth", (request) => request.setAuth(false), "auth", false],
19
+ [
20
+ "setParams",
21
+ (request) => request.setParams({ userId: 1, postId: 2 } as never),
22
+ "params",
23
+ { userId: 1, postId: 2 },
24
+ ],
25
+ ["setPayload", (request) => request.setPayload({ title: "Post" }), "payload", { title: "Post" }],
26
+ ["setQueryParams", (request) => request.setQueryParams({ page: 2 }), "queryParams", { page: 2 }],
27
+ ["setOptions", (request) => request.setOptions({ timeout: 100 }), "options", { timeout: 100 }],
28
+ ["setScope", (request) => request.setScope("session"), "scope", "session"],
29
+ ["setCancelable", (request) => request.setCancelable(true), "cancelable", true],
30
+ ["setRetry", (request) => request.setRetry(3), "retry", 3],
31
+ ["setRetryTime", (request) => request.setRetryTime(1500), "retryTime", 1500],
32
+ ["setRetryOnError", (request) => request.setRetryOnError(callback), "retryOnError", callback],
33
+ ["setOptimistic", (request) => request.setOptimistic(mapper), "optimistic", mapper],
34
+ ["setCacheTime", (request) => request.setCacheTime(1), "cacheTime", 1],
35
+ ["setCache", (request) => request.setCache(false), "cache", false],
36
+ ["setStaleTime", (request) => request.setStaleTime(2), "staleTime", 2],
37
+ ["setQueued", (request) => request.setQueued(true), "queued", true],
38
+ ["setAbortKey", (request) => request.setAbortKey("abort"), "abortKey", "abort"],
39
+ ["setCacheKey", (request) => request.setCacheKey("cache"), "cacheKey", "cache"],
40
+ ["setQueryKey", (request) => request.setQueryKey("query"), "queryKey", "query"],
41
+ ["setDeduplicate", (request) => request.setDeduplicate(true), "deduplicate", true],
42
+ ["setDeduplicateTime", (request) => request.setDeduplicateTime(300), "deduplicateTime", 300],
43
+ ["setStructuralSharing", (request) => request.setStructuralSharing(false), "structuralSharing", false],
44
+ ["setUsed", (request) => request.setUsed(true), "used", true],
45
+ ["setOffline", (request) => request.setOffline(false), "offline", false],
46
+ ["setPayloadMapper", (request) => request.setPayloadMapper(mapper), "unstable_payloadMapper", mapper],
47
+ ["setRequestMapper", (request) => request.setRequestMapper(mapper), "unstable_requestMapper", mapper],
48
+ ["setResponseMapper", (request) => request.setResponseMapper(mapper), "unstable_responseMapper", mapper],
49
+ ];
50
+
51
+ /** Everything the request holds, including the functions which are not part of the JSON dump */
52
+ const getSnapshot = (request: RequestInstance) => ({
53
+ ...request.toJSON(),
54
+ retryOnError: request.retryOnError,
55
+ optimistic: request.optimistic,
56
+ payloadMapper: request.unstable_payloadMapper,
57
+ requestMapper: request.unstable_requestMapper,
58
+ responseMapper: request.unstable_responseMapper,
59
+ mock: request.unstable_mock,
60
+ });
61
+
62
+ describe.each(setters)("When using %s", (...[, apply, field, value]) => {
63
+ it("should return a new request with the value", () => {
64
+ const request = createRequest();
65
+
66
+ const updated = apply(request);
67
+
68
+ expect(updated).not.toBe(request);
69
+ expect((updated as Record<string, any>)[field]).toEqual(value);
70
+ });
71
+
72
+ it("should not change the original request", () => {
73
+ const request = createRequest();
74
+ const before = getSnapshot(request);
75
+
76
+ apply(request);
77
+
78
+ expect(getSnapshot(request)).toEqual(before);
79
+ });
80
+
81
+ it("should keep the values set before", () => {
82
+ const configured = setters
83
+ .filter(([, , otherField]) => otherField !== field)
84
+ .reduce<RequestInstance>((request, [, applyOther]) => applyOther(request), createRequest());
85
+
86
+ const updated = apply(configured);
87
+
88
+ setters
89
+ .filter(([, , otherField]) => otherField !== field)
90
+ .forEach(([, , otherField, otherValue]) => {
91
+ expect((updated as Record<string, any>)[otherField]).toEqual(otherValue);
92
+ });
93
+ });
94
+ });
95
+
96
+ describe("When keys are set by hand", () => {
97
+ it.each([
98
+ ["setCacheKey", "cacheKey"],
99
+ ["setQueryKey", "queryKey"],
100
+ ["setAbortKey", "abortKey"],
101
+ ] as const)("should keep generating the %s result for the original request", (setter, key) => {
102
+ const request = client.createRequest()({ endpoint: "/keys/:id", cancelable: false });
103
+ const generated = request.setParams({ id: 1 }).setCancelable(true)[key];
104
+
105
+ request[setter]("custom");
106
+
107
+ // Using the setter on a template must not freeze the keys of the requests made from it later
108
+ expect(request.setParams({ id: 1 }).setCancelable(true)[key]).toBe(generated);
109
+ expect(request.setParams({ id: 1 })[key]).not.toBe(request.setParams({ id: 2 }).setCancelable(true)[key]);
110
+ });
111
+
112
+ it("should not make requests created from one template share a cache key", () => {
113
+ const getUser = client.createRequest()({ endpoint: "/users/:userId" });
114
+
115
+ getUser.setCacheKey("current-user");
116
+ const first = getUser.setParams({ userId: 1 });
117
+ const second = getUser.setParams({ userId: 2 });
118
+
119
+ expect(first.cacheKey).not.toBe(second.cacheKey);
120
+ expect(first.queryKey).not.toBe(second.queryKey);
121
+ });
122
+
123
+ it.each([
124
+ ["setCacheKey", "cacheKey"],
125
+ ["setQueryKey", "queryKey"],
126
+ ["setAbortKey", "abortKey"],
127
+ ] as const)("should keep the key from %s in all the next clones", (setter, key) => {
128
+ const request = client.createRequest<{ queryParams: any; payload: any }>()({ endpoint: "/keys/:id" });
129
+
130
+ const custom = request[setter]("custom");
131
+ const cloned = custom
132
+ .setParams({ id: 1 })
133
+ .setQueryParams({ page: 1 })
134
+ .setPayload({ a: 1 })
135
+ .setCancelable(true)
136
+ .clone();
137
+
138
+ expect(cloned[key]).toBe("custom");
139
+ });
140
+
141
+ it("should use the keys passed to the clone method", () => {
142
+ const request = client.createRequest()({ endpoint: "/keys/:id" });
143
+
144
+ const cloned = request.clone({ cacheKey: "cache", queryKey: "query", abortKey: "abort" });
145
+
146
+ expect([cloned.cacheKey, cloned.queryKey, cloned.abortKey]).toEqual(["cache", "query", "abort"]);
147
+ expect(cloned.setParams({ id: 1 }).cacheKey).toBe("cache");
148
+ });
149
+
150
+ it("should keep the keys given with the request options", () => {
151
+ const request = client.createRequest()({
152
+ endpoint: "/keys/:id",
153
+ cacheKey: "cache",
154
+ queryKey: "query",
155
+ abortKey: "abort",
156
+ });
157
+
158
+ const cloned = request.setParams({ id: 1 }).setRetry(1);
159
+
160
+ expect([cloned.cacheKey, cloned.queryKey, cloned.abortKey]).toEqual(["cache", "query", "abort"]);
161
+ });
162
+ });
163
+
164
+ describe("When cloning", () => {
165
+ it("should give an equal request for a clone without changes", () => {
166
+ const request = setters.reduce<RequestInstance>((current, [, apply]) => apply(current), createRequest());
167
+
168
+ const cloned = request.clone();
169
+
170
+ expect(cloned).not.toBe(request);
171
+ expect(getSnapshot(cloned)).toEqual(getSnapshot(request));
172
+ });
173
+
174
+ it("should keep the mock and its enabled state", () => {
175
+ const request = createRequest().setMock(() => ({ data: { id: 1 }, status: 200 }));
176
+ request.setMockingEnabled(false);
177
+
178
+ const cloned = request.setRetry(1);
179
+
180
+ expect(cloned.unstable_mock).toBe(request.unstable_mock);
181
+ expect(cloned.isMockerEnabled).toBe(false);
182
+ });
183
+
184
+ it("should copy the hooks without sharing later subscriptions", () => {
185
+ const request = createRequest();
186
+ const inherited = vi.fn();
187
+ const added = vi.fn();
188
+ request.$hooks.onBeforeSent(inherited);
189
+
190
+ const cloned = request.clone();
191
+ cloned.$hooks.onBeforeSent(added);
192
+ request.$hooks.__emit("onBeforeSent", {});
193
+
194
+ expect(inherited).toHaveBeenCalledTimes(1);
195
+ expect(added).not.toHaveBeenCalled();
196
+ });
197
+
198
+ it("should share the client", () => {
199
+ const request = createRequest();
200
+
201
+ expect(request.clone().client).toBe(client);
202
+ });
203
+
204
+ it("should not change the request when it is sent with other values", async () => {
205
+ const request = createRequest().setMock(() => ({ data: { id: 1 }, status: 200 }), {
206
+ requestTime: 0,
207
+ responseTime: 0,
208
+ });
209
+ const before = getSnapshot(request);
210
+
211
+ await request.send({
212
+ params: { userId: 1, postId: 2 },
213
+ payload: { title: "Post" },
214
+ queryParams: { page: 1 },
215
+ headers: { "X-Test": "1" },
216
+ retry: 2,
217
+ });
218
+
219
+ expect(getSnapshot(request)).toEqual(before);
220
+ });
221
+
222
+ it("should not change the request when it is aborted", () => {
223
+ const request = createRequest();
224
+ const before = getSnapshot(request);
225
+
226
+ const aborted = request.abort();
227
+
228
+ expect(aborted).not.toBe(request);
229
+ expect(getSnapshot(request)).toEqual(before);
230
+ });
231
+ });
232
+
233
+ describe("When using the mock methods", () => {
234
+ it("should set the mock on the same request - the only documented exception", () => {
235
+ const request = createRequest();
236
+
237
+ expect(request.setMock(() => ({ data: { id: 1 }, status: 200 }))).toBe(request);
238
+ expect(request.isMockerEnabled).toBe(true);
239
+ expect(request.toJSON().hasMock).toBe(true);
240
+ });
241
+
242
+ it("should clear the mock on the same request", () => {
243
+ const request = createRequest().setMock(() => ({ data: { id: 1 }, status: 200 }));
244
+
245
+ expect(request.clearMock()).toBe(request);
246
+ expect(request.unstable_mock).toBeUndefined();
247
+ expect(request.isMockerEnabled).toBe(false);
248
+ });
249
+
250
+ it("should not add the mock to the requests cloned before", () => {
251
+ const request = createRequest();
252
+ const clonedBefore = request.clone();
253
+
254
+ request.setMock(() => ({ data: { id: 1 }, status: 200 }));
255
+
256
+ expect(clonedBefore.unstable_mock).toBeUndefined();
257
+ });
258
+ });
259
+ });
@@ -0,0 +1,269 @@
1
+ import { Client } from "client";
2
+ import type { ExtractUrlParams, ParamType, RequestInstance } from "request";
3
+ import type {
4
+ ExtractErrorType,
5
+ ExtractParamsType,
6
+ ExtractPayloadType,
7
+ ExtractQueryParamsType,
8
+ ExtractResponseType,
9
+ } from "types";
10
+
11
+ type User = { id: number; name: string };
12
+ type ApiError = { message: string; code: number };
13
+ type GlobalError = { reason: string };
14
+
15
+ /**
16
+ * Type-level tests - they are verified by `pnpm typecheck`, the runtime assertions only keep the spec alive.
17
+ */
18
+ describe("Request [ Type inference ]", () => {
19
+ const client = new Client<GlobalError>({ url: "http://types" });
20
+
21
+ const getUsers = client.createRequest<{ response: User[]; queryParams?: { page?: number } }>()({
22
+ endpoint: "/users",
23
+ });
24
+ const getUser = client.createRequest<{ response: User; error: ApiError }>()({ endpoint: "/users/:userId" });
25
+ const postUser = client.createRequest<{ response: User; payload: { name: string }; error: ApiError }>()({
26
+ endpoint: "/users",
27
+ method: "POST",
28
+ });
29
+ const patchUser = client.createRequest<{ response: User; payload: { name: string } }>()({
30
+ endpoint: "/teams/:teamId/users/:userId",
31
+ method: "PATCH",
32
+ });
33
+ const searchUsers = client.createRequest<{ response: User[]; queryParams: { search: string } }>()({
34
+ endpoint: "/users/search",
35
+ });
36
+
37
+ type SendResult<T extends RequestInstance> = Awaited<ReturnType<T["send"]>>;
38
+ type SendOptions<T extends RequestInstance> = NonNullable<Parameters<T["send"]>[0]>;
39
+
40
+ describe("When reading the generics of a request", () => {
41
+ it("should infer the response", () => {
42
+ expectTypeOf<ExtractResponseType<typeof getUsers>>().toEqualTypeOf<User[]>();
43
+ expectTypeOf<ExtractResponseType<typeof getUser>>().toEqualTypeOf<User>();
44
+ expect(getUsers.endpoint).toBe("/users");
45
+ });
46
+
47
+ it("should infer the payload", () => {
48
+ expectTypeOf<ExtractPayloadType<typeof postUser>>().toEqualTypeOf<{ name: string }>();
49
+ expectTypeOf<ExtractPayloadType<typeof getUser>>().toEqualTypeOf<undefined>();
50
+ expect(postUser.method).toBe("POST");
51
+ });
52
+
53
+ it("should join the error of the request with the global error of the client", () => {
54
+ expectTypeOf<ExtractErrorType<typeof getUser>>().toEqualTypeOf<ApiError | GlobalError>();
55
+ expectTypeOf<ExtractErrorType<typeof getUsers>>().toEqualTypeOf<GlobalError>();
56
+ expect(getUser.auth).toBe(true);
57
+ });
58
+
59
+ it("should infer the query params", () => {
60
+ expectTypeOf<ExtractQueryParamsType<typeof searchUsers>>().toEqualTypeOf<{ search: string }>();
61
+ expect(searchUsers.queryParams).toBeUndefined();
62
+ });
63
+
64
+ it("should infer the params from the endpoint", () => {
65
+ expectTypeOf<ExtractParamsType<typeof getUser>>().toEqualTypeOf<{ userId: ParamType }>();
66
+ expectTypeOf<ExtractParamsType<typeof patchUser>>().toEqualTypeOf<{ teamId: ParamType; userId: ParamType }>();
67
+ expectTypeOf<ExtractParamsType<typeof getUsers>>().toEqualTypeOf<null | undefined>();
68
+ expect(patchUser.endpoint).toBe("/teams/:teamId/users/:userId");
69
+ });
70
+
71
+ it("should read the params of any endpoint literal", () => {
72
+ expectTypeOf<ExtractUrlParams<"/a/:first/b/:second/c/:third">>().toEqualTypeOf<{
73
+ first: ParamType;
74
+ second: ParamType;
75
+ third: ParamType;
76
+ }>();
77
+ expectTypeOf<ExtractUrlParams<":only">>().toEqualTypeOf<{ only: ParamType }>();
78
+ expectTypeOf<ExtractUrlParams<"/static/path">>().toEqualTypeOf<null | undefined>();
79
+ expectTypeOf<ExtractUrlParams<string>>().toEqualTypeOf<null | undefined>();
80
+ expect(true).toBe(true);
81
+ });
82
+
83
+ it("should keep the literal type of the endpoint", () => {
84
+ expectTypeOf(getUser.requestOptions.endpoint).toEqualTypeOf<"/users/:userId">();
85
+ expect(getUser.requestOptions.endpoint).toBe("/users/:userId");
86
+ });
87
+ });
88
+
89
+ describe("When reading the result of send", () => {
90
+ it("should give the typed data or null", () => {
91
+ expectTypeOf<SendResult<typeof getUsers>["data"]>().toEqualTypeOf<User[] | null>();
92
+ expectTypeOf<SendResult<typeof postUser>["data"]>().toEqualTypeOf<User | null>();
93
+ expect(getUsers.cache).toBe(true);
94
+ });
95
+
96
+ it("should give the typed error or null", () => {
97
+ expectTypeOf<SendResult<typeof getUser>["error"]>().toEqualTypeOf<ApiError | GlobalError | null>();
98
+ expect(getUser.retry).toBe(0);
99
+ });
100
+
101
+ it("should give the status, the success flag and the extra of the http adapter", () => {
102
+ expectTypeOf<SendResult<typeof getUser>["status"]>().toEqualTypeOf<number | null>();
103
+ expectTypeOf<SendResult<typeof getUser>["success"]>().toEqualTypeOf<boolean>();
104
+ expectTypeOf<SendResult<typeof getUser>["extra"]>().toEqualTypeOf<{ headers: Record<string, string> } | null>();
105
+ expect(getUser.offline).toBe(true);
106
+ });
107
+
108
+ it("should give the same result type from exec", () => {
109
+ expectTypeOf<Awaited<ReturnType<typeof getUser.exec>>>().toEqualTypeOf<SendResult<typeof getUser>>();
110
+ expect(getUser.queued).toBe(false);
111
+ });
112
+
113
+ it("should give the response type of the response mapper", () => {
114
+ const mapped = getUser.setResponseMapper((response) => ({
115
+ ...response,
116
+ data: { fullName: "John" },
117
+ error: null,
118
+ success: true as const,
119
+ }));
120
+
121
+ expectTypeOf<SendResult<typeof mapped>["data"]>().toEqualTypeOf<{ fullName: string } | null>();
122
+ expect(mapped.unstable_responseMapper).toBeDefined();
123
+ });
124
+ });
125
+
126
+ describe("When checking the arguments of send", () => {
127
+ it("should not require anything for a request without params, payload and required query params", () => {
128
+ expectTypeOf(getUsers.send).toBeCallableWith();
129
+ expectTypeOf(getUsers.send).toBeCallableWith({ queryParams: { page: 1 } });
130
+ expectTypeOf(getUsers.send).toBeCallableWith({ retry: 2, onResponse: () => {} });
131
+ expect(getUsers.params).toBeUndefined();
132
+ });
133
+
134
+ it("should require the params of the endpoint", () => {
135
+ expectTypeOf<SendOptions<typeof getUser>["params"]>().toEqualTypeOf<{ userId: ParamType }>();
136
+ expectTypeOf(getUser.send).toBeCallableWith({ params: { userId: 1 } });
137
+ expectTypeOf(getUser.send).toBeCallableWith({ params: { userId: "john" } });
138
+ // @ts-expect-error params are required
139
+ expectTypeOf(getUser.send).toBeCallableWith();
140
+ // @ts-expect-error all the params of the endpoint are required
141
+ expectTypeOf(patchUser.send).toBeCallableWith({ params: { userId: 1 }, payload: { name: "John" } });
142
+ expect(getUser.params).toBeUndefined();
143
+ });
144
+
145
+ it("should not require the params which were already set", () => {
146
+ const withParams = getUser.setParams({ userId: 1 });
147
+
148
+ expectTypeOf(withParams.send).toBeCallableWith();
149
+ expect(withParams.endpoint).toBe("/users/1");
150
+ });
151
+
152
+ it("should require the payload", () => {
153
+ expectTypeOf<SendOptions<typeof postUser>["payload"]>().toEqualTypeOf<{ name: string }>();
154
+ expectTypeOf(postUser.send).toBeCallableWith({ payload: { name: "John" } });
155
+ // @ts-expect-error payload is required
156
+ expectTypeOf(postUser.send).toBeCallableWith();
157
+ // @ts-expect-error payload has to match its type
158
+ expectTypeOf(postUser.send).toBeCallableWith({ payload: { name: 1 } });
159
+ expect(postUser.payload).toBeUndefined();
160
+ });
161
+
162
+ it("should not require the payload which was already set", () => {
163
+ const withPayload = postUser.setPayload({ name: "John" });
164
+
165
+ expectTypeOf(withPayload.send).toBeCallableWith();
166
+ expect(withPayload.payload).toEqual({ name: "John" });
167
+ });
168
+
169
+ it("should require the required query params", () => {
170
+ expectTypeOf(searchUsers.send).toBeCallableWith({ queryParams: { search: "john" } });
171
+ // @ts-expect-error query params are required
172
+ expectTypeOf(searchUsers.send).toBeCallableWith();
173
+ // @ts-expect-error query params have to match their type
174
+ expectTypeOf(searchUsers.send).toBeCallableWith({ queryParams: { search: 1 } });
175
+ expect(searchUsers.endpoint).toBe("/users/search");
176
+ });
177
+
178
+ it("should not require the query params which were already set", () => {
179
+ const withQueryParams = searchUsers.setQueryParams({ search: "john" });
180
+
181
+ expectTypeOf(withQueryParams.send).toBeCallableWith();
182
+ expect(withQueryParams.queryParams).toEqual({ search: "john" });
183
+ });
184
+
185
+ it("should require everything that is still missing", () => {
186
+ const withParams = patchUser.setParams({ teamId: 1, userId: 2 });
187
+
188
+ expectTypeOf(patchUser.send).toBeCallableWith({ params: { teamId: 1, userId: 2 }, payload: { name: "John" } });
189
+ expectTypeOf(withParams.send).toBeCallableWith({ payload: { name: "John" } });
190
+ expectTypeOf(withParams.setPayload({ name: "John" }).send).toBeCallableWith();
191
+ // @ts-expect-error payload is still required
192
+ expectTypeOf(withParams.send).toBeCallableWith();
193
+ expect(withParams.endpoint).toBe("/teams/1/users/2");
194
+ });
195
+ });
196
+
197
+ describe("When checking the arguments of the setters", () => {
198
+ it("should accept only the params of the endpoint", () => {
199
+ // @ts-expect-error unknown param
200
+ getUser.setParams({ id: 1 });
201
+ // @ts-expect-error missing param
202
+ patchUser.setParams({ userId: 1 });
203
+ expect(getUser.setParams({ userId: 1 }).params).toEqual({ userId: 1 });
204
+ });
205
+
206
+ it("should accept only the payload of the request", () => {
207
+ // @ts-expect-error wrong payload
208
+ postUser.setPayload({ title: "John" });
209
+ // @ts-expect-error wrong type of the value
210
+ postUser.setPayload({ name: 1 });
211
+ expect(postUser.setPayload({ name: "John" }).payload).toEqual({ name: "John" });
212
+ });
213
+
214
+ it("should accept only the methods of the adapter", () => {
215
+ client.createRequest()({ endpoint: "/methods", method: "DELETE" });
216
+ // @ts-expect-error unknown method
217
+ client.createRequest()({ endpoint: "/methods", method: "FETCH" });
218
+ expect(client.adapter.defaultMethod).toBe("GET");
219
+ });
220
+
221
+ it("should accept only the options of the adapter", () => {
222
+ expectTypeOf(getUser.setOptions).toBeCallableWith({ timeout: 1000, credentials: "include" });
223
+ // @ts-expect-error unknown option
224
+ expectTypeOf(getUser.setOptions).toBeCallableWith({ unknownOption: true });
225
+ expect(getUser.options).toBeUndefined();
226
+ });
227
+ });
228
+
229
+ describe("When using the callbacks", () => {
230
+ it("should give the typed response to the onResponse callback", () => {
231
+ type OnResponse = NonNullable<SendOptions<typeof postUser>["onResponse"]>;
232
+ type Event = Parameters<OnResponse>[0];
233
+
234
+ expectTypeOf<Event["response"]["data"]>().toEqualTypeOf<User | null>();
235
+ expectTypeOf<Event["requestId"]>().toEqualTypeOf<string>();
236
+ expectTypeOf<Event["details"]["retries"]>().toEqualTypeOf<number>();
237
+ expect(postUser.retryTime).toBe(500);
238
+ });
239
+
240
+ it("should give the context of the optimistic callback to the callbacks", () => {
241
+ type OnResponse = NonNullable<SendOptions<typeof postUser>["onResponse"]>;
242
+ type OnBeforeSent = NonNullable<SendOptions<typeof postUser>["onBeforeSent"]>;
243
+
244
+ expectTypeOf<Parameters<OnResponse>[0]>().toHaveProperty("mutationContext");
245
+ expectTypeOf<Parameters<OnBeforeSent>[0]>().toHaveProperty("mutationContext");
246
+ expect(postUser.optimistic).toBeUndefined();
247
+ });
248
+
249
+ it("should give the progress values to the progress callbacks", () => {
250
+ type OnUploadProgress = NonNullable<SendOptions<typeof postUser>["onUploadProgress"]>;
251
+ type Event = Parameters<OnUploadProgress>[0];
252
+
253
+ expectTypeOf<Event["progress"]>().toEqualTypeOf<number>();
254
+ expectTypeOf<Event["loaded"]>().toEqualTypeOf<number>();
255
+ expectTypeOf<Event["total"]>().toEqualTypeOf<number>();
256
+ expectTypeOf<Event["timeLeft"]>().toEqualTypeOf<number | null>();
257
+ expect(postUser.cancelable).toBe(false);
258
+ });
259
+
260
+ it("should give the typed response to the retryOnError callback", () => {
261
+ const withCallback = getUser.setRetryOnError((response) => {
262
+ expectTypeOf(response.error).toEqualTypeOf<ApiError | GlobalError | null>();
263
+ return response.status === 503;
264
+ });
265
+
266
+ expect(withCallback.retryOnError).toBeDefined();
267
+ });
268
+ });
269
+ });