@trpc/server 11.0.0-alpha-tmp-subscription-connection-state.488 → 11.0.0-alpha-tmp-12-06-react.665

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 (276) hide show
  1. package/dist/@trpc/server/http.d.ts +1 -1
  2. package/dist/@trpc/server/http.d.ts.map +1 -1
  3. package/dist/@trpc/server/index.d.ts +5 -1
  4. package/dist/@trpc/server/index.d.ts.map +1 -1
  5. package/dist/adapters/aws-lambda/getPlanner.d.ts.map +1 -1
  6. package/dist/adapters/aws-lambda/getPlanner.js +2 -2
  7. package/dist/adapters/aws-lambda/getPlanner.mjs +2 -2
  8. package/dist/adapters/aws-lambda/index.d.ts.map +1 -1
  9. package/dist/adapters/aws-lambda/index.js +2 -0
  10. package/dist/adapters/aws-lambda/index.mjs +2 -0
  11. package/dist/adapters/express.d.ts.map +1 -1
  12. package/dist/adapters/express.js +27 -7
  13. package/dist/adapters/express.mjs +27 -7
  14. package/dist/adapters/fastify/fastifyRequestHandler.js +3 -1
  15. package/dist/adapters/fastify/fastifyRequestHandler.mjs +3 -1
  16. package/dist/adapters/fastify/fastifyTRPCPlugin.d.ts.map +1 -1
  17. package/dist/adapters/fastify/fastifyTRPCPlugin.js +9 -2
  18. package/dist/adapters/fastify/fastifyTRPCPlugin.mjs +10 -3
  19. package/dist/adapters/fetch/fetchRequestHandler.js +9 -8
  20. package/dist/adapters/fetch/fetchRequestHandler.mjs +9 -8
  21. package/dist/adapters/next-app-dir/nextAppDirCaller.d.ts.map +1 -1
  22. package/dist/adapters/next-app-dir/nextAppDirCaller.js +10 -5
  23. package/dist/adapters/next-app-dir/nextAppDirCaller.mjs +10 -5
  24. package/dist/adapters/next-app-dir/notFound.js +2 -0
  25. package/dist/adapters/next-app-dir/notFound.mjs +2 -0
  26. package/dist/adapters/next-app-dir/redirect.js +16 -1
  27. package/dist/adapters/next-app-dir/redirect.mjs +16 -1
  28. package/dist/adapters/next-app-dir/rethrowNextErrors.d.ts.map +1 -1
  29. package/dist/adapters/next-app-dir/rethrowNextErrors.js +4 -3
  30. package/dist/adapters/next-app-dir/rethrowNextErrors.mjs +4 -3
  31. package/dist/adapters/next.d.ts.map +1 -1
  32. package/dist/adapters/next.js +23 -30
  33. package/dist/adapters/next.mjs +24 -31
  34. package/dist/adapters/node-http/incomingMessageToRequest.d.ts +2 -1
  35. package/dist/adapters/node-http/incomingMessageToRequest.d.ts.map +1 -1
  36. package/dist/adapters/node-http/incomingMessageToRequest.js +83 -40
  37. package/dist/adapters/node-http/incomingMessageToRequest.mjs +83 -41
  38. package/dist/adapters/node-http/index.js +2 -0
  39. package/dist/adapters/node-http/index.mjs +2 -2
  40. package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts +7 -0
  41. package/dist/adapters/node-http/nodeHTTPRequestHandler.d.ts.map +1 -1
  42. package/dist/adapters/node-http/nodeHTTPRequestHandler.js +70 -58
  43. package/dist/adapters/node-http/nodeHTTPRequestHandler.mjs +70 -59
  44. package/dist/adapters/node-http/writeResponse.d.ts +18 -0
  45. package/dist/adapters/node-http/writeResponse.d.ts.map +1 -0
  46. package/dist/adapters/node-http/writeResponse.js +82 -0
  47. package/dist/adapters/node-http/writeResponse.mjs +79 -0
  48. package/dist/adapters/standalone.d.ts +5 -2
  49. package/dist/adapters/standalone.d.ts.map +1 -1
  50. package/dist/adapters/standalone.js +25 -13
  51. package/dist/adapters/standalone.mjs +26 -14
  52. package/dist/adapters/ws.d.ts +14 -4
  53. package/dist/adapters/ws.d.ts.map +1 -1
  54. package/dist/adapters/ws.js +236 -90
  55. package/dist/adapters/ws.mjs +237 -92
  56. package/dist/bundle-analysis.json +411 -294
  57. package/dist/http.js +2 -4
  58. package/dist/http.mjs +2 -2
  59. package/dist/index.js +6 -2
  60. package/dist/index.mjs +3 -1
  61. package/dist/node_modules/.pnpm/@rollup_plugin-typescript@12.1.1_rollup@4.27.4_tslib@2.8.1_typescript@5.7.2/node_modules/tslib/tslib.es6.js +73 -0
  62. package/dist/observable/behaviorSubject.d.ts +15 -0
  63. package/dist/observable/behaviorSubject.d.ts.map +1 -0
  64. package/dist/observable/behaviorSubject.js +40 -0
  65. package/dist/observable/behaviorSubject.mjs +38 -0
  66. package/dist/observable/index.d.ts +3 -3
  67. package/dist/observable/index.d.ts.map +1 -1
  68. package/dist/observable/index.js +5 -0
  69. package/dist/observable/index.mjs +3 -2
  70. package/dist/observable/observable.d.ts +2 -1
  71. package/dist/observable/observable.d.ts.map +1 -1
  72. package/dist/observable/observable.js +31 -8
  73. package/dist/observable/observable.mjs +31 -8
  74. package/dist/observable/operators.d.ts +2 -0
  75. package/dist/observable/operators.d.ts.map +1 -1
  76. package/dist/observable/operators.js +35 -0
  77. package/dist/observable/operators.mjs +34 -1
  78. package/dist/rpc.js +2 -0
  79. package/dist/rpc.mjs +2 -0
  80. package/dist/shared.js +2 -0
  81. package/dist/shared.mjs +2 -0
  82. package/dist/unstable-core-do-not-import/clientish/inference.d.ts.map +1 -1
  83. package/dist/unstable-core-do-not-import/clientish/inferrable.d.ts.map +1 -1
  84. package/dist/unstable-core-do-not-import/clientish/serialize.d.ts +2 -2
  85. package/dist/unstable-core-do-not-import/clientish/serialize.d.ts.map +1 -1
  86. package/dist/unstable-core-do-not-import/createProxy.js +1 -1
  87. package/dist/unstable-core-do-not-import/createProxy.mjs +1 -1
  88. package/dist/unstable-core-do-not-import/error/TRPCError.d.ts +1 -1
  89. package/dist/unstable-core-do-not-import/error/TRPCError.js +16 -1
  90. package/dist/unstable-core-do-not-import/error/TRPCError.mjs +16 -1
  91. package/dist/unstable-core-do-not-import/error/formatter.js +1 -1
  92. package/dist/unstable-core-do-not-import/error/formatter.mjs +1 -1
  93. package/dist/unstable-core-do-not-import/error/getErrorShape.js +2 -2
  94. package/dist/unstable-core-do-not-import/error/getErrorShape.mjs +2 -2
  95. package/dist/unstable-core-do-not-import/http/contentType.js +3 -3
  96. package/dist/unstable-core-do-not-import/http/contentType.mjs +3 -3
  97. package/dist/unstable-core-do-not-import/http/getHTTPStatusCode.d.ts +6 -1
  98. package/dist/unstable-core-do-not-import/http/getHTTPStatusCode.d.ts.map +1 -1
  99. package/dist/unstable-core-do-not-import/http/getHTTPStatusCode.js +28 -0
  100. package/dist/unstable-core-do-not-import/http/getHTTPStatusCode.mjs +25 -1
  101. package/dist/unstable-core-do-not-import/http/isAbortError.d.ts +4 -0
  102. package/dist/unstable-core-do-not-import/http/isAbortError.d.ts.map +1 -0
  103. package/dist/unstable-core-do-not-import/http/isAbortError.js +9 -0
  104. package/dist/unstable-core-do-not-import/http/isAbortError.mjs +7 -0
  105. package/dist/unstable-core-do-not-import/http/resolveResponse.d.ts.map +1 -1
  106. package/dist/unstable-core-do-not-import/http/resolveResponse.js +187 -92
  107. package/dist/unstable-core-do-not-import/http/resolveResponse.mjs +189 -94
  108. package/dist/unstable-core-do-not-import/http/types.d.ts +1 -1
  109. package/dist/unstable-core-do-not-import/initTRPC.d.ts +11 -11
  110. package/dist/unstable-core-do-not-import/initTRPC.d.ts.map +1 -1
  111. package/dist/unstable-core-do-not-import/initTRPC.js +11 -11
  112. package/dist/unstable-core-do-not-import/initTRPC.mjs +11 -11
  113. package/dist/unstable-core-do-not-import/middleware.d.ts +2 -1
  114. package/dist/unstable-core-do-not-import/middleware.d.ts.map +1 -1
  115. package/dist/unstable-core-do-not-import/middleware.js +2 -2
  116. package/dist/unstable-core-do-not-import/middleware.mjs +2 -2
  117. package/dist/unstable-core-do-not-import/parser.d.ts +5 -1
  118. package/dist/unstable-core-do-not-import/parser.d.ts.map +1 -1
  119. package/dist/unstable-core-do-not-import/parser.js +4 -0
  120. package/dist/unstable-core-do-not-import/parser.mjs +4 -0
  121. package/dist/unstable-core-do-not-import/procedure.d.ts +8 -2
  122. package/dist/unstable-core-do-not-import/procedure.d.ts.map +1 -1
  123. package/dist/unstable-core-do-not-import/procedureBuilder.d.ts +32 -13
  124. package/dist/unstable-core-do-not-import/procedureBuilder.d.ts.map +1 -1
  125. package/dist/unstable-core-do-not-import/procedureBuilder.js +33 -39
  126. package/dist/unstable-core-do-not-import/procedureBuilder.mjs +33 -39
  127. package/dist/unstable-core-do-not-import/rootConfig.d.ts +17 -17
  128. package/dist/unstable-core-do-not-import/rootConfig.d.ts.map +1 -1
  129. package/dist/unstable-core-do-not-import/router.d.ts +4 -3
  130. package/dist/unstable-core-do-not-import/router.d.ts.map +1 -1
  131. package/dist/unstable-core-do-not-import/router.js +6 -5
  132. package/dist/unstable-core-do-not-import/router.mjs +6 -5
  133. package/dist/unstable-core-do-not-import/rpc/codes.d.ts +2 -9
  134. package/dist/unstable-core-do-not-import/rpc/codes.d.ts.map +1 -1
  135. package/dist/unstable-core-do-not-import/rpc/envelopes.d.ts +11 -6
  136. package/dist/unstable-core-do-not-import/rpc/envelopes.d.ts.map +1 -1
  137. package/dist/unstable-core-do-not-import/rpc/parseTRPCMessage.d.ts.map +1 -1
  138. package/dist/unstable-core-do-not-import/rpc/parseTRPCMessage.js +7 -3
  139. package/dist/unstable-core-do-not-import/rpc/parseTRPCMessage.mjs +7 -3
  140. package/dist/unstable-core-do-not-import/stream/jsonl.d.ts +31 -16
  141. package/dist/unstable-core-do-not-import/stream/jsonl.d.ts.map +1 -1
  142. package/dist/unstable-core-do-not-import/stream/jsonl.js +440 -318
  143. package/dist/unstable-core-do-not-import/stream/jsonl.mjs +440 -318
  144. package/dist/unstable-core-do-not-import/stream/sse.d.ts +63 -41
  145. package/dist/unstable-core-do-not-import/stream/sse.d.ts.map +1 -1
  146. package/dist/unstable-core-do-not-import/stream/sse.js +300 -119
  147. package/dist/unstable-core-do-not-import/stream/sse.mjs +302 -119
  148. package/dist/unstable-core-do-not-import/stream/sse.types.d.ts +31 -0
  149. package/dist/unstable-core-do-not-import/stream/sse.types.d.ts.map +1 -0
  150. package/dist/unstable-core-do-not-import/stream/tracked.d.ts +31 -0
  151. package/dist/unstable-core-do-not-import/stream/tracked.d.ts.map +1 -0
  152. package/dist/unstable-core-do-not-import/stream/tracked.js +29 -0
  153. package/dist/unstable-core-do-not-import/stream/tracked.mjs +25 -0
  154. package/dist/unstable-core-do-not-import/stream/utils/asyncIterable.d.ts +17 -0
  155. package/dist/unstable-core-do-not-import/stream/utils/asyncIterable.d.ts.map +1 -0
  156. package/dist/unstable-core-do-not-import/stream/utils/asyncIterable.js +171 -0
  157. package/dist/unstable-core-do-not-import/stream/utils/asyncIterable.mjs +167 -0
  158. package/dist/unstable-core-do-not-import/stream/utils/createDeferred.d.ts +0 -11
  159. package/dist/unstable-core-do-not-import/stream/utils/createDeferred.d.ts.map +1 -1
  160. package/dist/unstable-core-do-not-import/stream/utils/createDeferred.js +0 -29
  161. package/dist/unstable-core-do-not-import/stream/utils/createDeferred.mjs +1 -29
  162. package/dist/unstable-core-do-not-import/stream/utils/disposable.d.ts +17 -0
  163. package/dist/unstable-core-do-not-import/stream/utils/disposable.d.ts.map +1 -0
  164. package/dist/unstable-core-do-not-import/stream/utils/disposable.js +44 -0
  165. package/dist/unstable-core-do-not-import/stream/utils/disposable.mjs +41 -0
  166. package/dist/unstable-core-do-not-import/stream/utils/readableStreamFrom.d.ts +8 -0
  167. package/dist/unstable-core-do-not-import/stream/utils/readableStreamFrom.d.ts.map +1 -0
  168. package/dist/unstable-core-do-not-import/stream/utils/readableStreamFrom.js +25 -0
  169. package/dist/unstable-core-do-not-import/stream/utils/readableStreamFrom.mjs +23 -0
  170. package/dist/unstable-core-do-not-import/stream/utils/timerResource.d.ts +5 -0
  171. package/dist/unstable-core-do-not-import/stream/utils/timerResource.d.ts.map +1 -0
  172. package/dist/unstable-core-do-not-import/stream/utils/timerResource.js +26 -0
  173. package/dist/unstable-core-do-not-import/stream/utils/timerResource.mjs +23 -0
  174. package/dist/unstable-core-do-not-import/stream/utils/withPing.d.ts +7 -0
  175. package/dist/unstable-core-do-not-import/stream/utils/withPing.d.ts.map +1 -0
  176. package/dist/unstable-core-do-not-import/stream/utils/withPing.js +130 -0
  177. package/dist/unstable-core-do-not-import/stream/utils/withPing.mjs +127 -0
  178. package/dist/unstable-core-do-not-import/transformer.d.ts +2 -4
  179. package/dist/unstable-core-do-not-import/transformer.d.ts.map +1 -1
  180. package/dist/unstable-core-do-not-import/transformer.js +1 -1
  181. package/dist/unstable-core-do-not-import/transformer.mjs +1 -1
  182. package/dist/unstable-core-do-not-import/types.d.ts +26 -3
  183. package/dist/unstable-core-do-not-import/types.d.ts.map +1 -1
  184. package/dist/unstable-core-do-not-import/utils.d.ts +15 -0
  185. package/dist/unstable-core-do-not-import/utils.d.ts.map +1 -1
  186. package/dist/unstable-core-do-not-import/utils.js +49 -1
  187. package/dist/unstable-core-do-not-import/utils.mjs +45 -2
  188. package/dist/unstable-core-do-not-import.d.ts +4 -2
  189. package/dist/unstable-core-do-not-import.d.ts.map +1 -1
  190. package/dist/unstable-core-do-not-import.js +18 -9
  191. package/dist/unstable-core-do-not-import.mjs +7 -7
  192. package/dist/vendor/unpromise/index.d.ts +3 -0
  193. package/dist/vendor/unpromise/index.d.ts.map +1 -0
  194. package/dist/vendor/unpromise/types.d.ts +28 -0
  195. package/dist/vendor/unpromise/types.d.ts.map +1 -0
  196. package/dist/vendor/unpromise/unpromise.d.ts +121 -0
  197. package/dist/vendor/unpromise/unpromise.d.ts.map +1 -0
  198. package/dist/vendor/unpromise/unpromise.js +292 -0
  199. package/dist/vendor/unpromise/unpromise.mjs +289 -0
  200. package/package.json +20 -17
  201. package/src/@trpc/server/http.ts +0 -2
  202. package/src/@trpc/server/index.ts +6 -0
  203. package/src/adapters/aws-lambda/getPlanner.ts +2 -2
  204. package/src/adapters/aws-lambda/index.ts +5 -6
  205. package/src/adapters/express.ts +21 -9
  206. package/src/adapters/fastify/fastifyRequestHandler.ts +1 -1
  207. package/src/adapters/fastify/fastifyTRPCPlugin.ts +16 -5
  208. package/src/adapters/fetch/fetchRequestHandler.ts +2 -2
  209. package/src/adapters/next-app-dir/nextAppDirCaller.ts +3 -0
  210. package/src/adapters/next-app-dir/rethrowNextErrors.ts +3 -2
  211. package/src/adapters/next.ts +29 -34
  212. package/src/adapters/node-http/incomingMessageToRequest.ts +110 -40
  213. package/src/adapters/node-http/nodeHTTPRequestHandler.ts +85 -63
  214. package/src/adapters/node-http/writeResponse.ts +94 -0
  215. package/src/adapters/standalone.ts +35 -18
  216. package/src/adapters/ws.ts +152 -62
  217. package/src/observable/behaviorSubject.ts +55 -0
  218. package/src/observable/index.ts +22 -3
  219. package/src/observable/observable.ts +32 -14
  220. package/src/observable/operators.ts +47 -0
  221. package/src/unstable-core-do-not-import/clientish/inference.ts +4 -4
  222. package/src/unstable-core-do-not-import/clientish/inferrable.ts +6 -6
  223. package/src/unstable-core-do-not-import/clientish/serialize.ts +5 -5
  224. package/src/unstable-core-do-not-import/http/getHTTPStatusCode.ts +37 -4
  225. package/src/unstable-core-do-not-import/http/isAbortError.ts +7 -0
  226. package/src/unstable-core-do-not-import/http/resolveResponse.ts +192 -85
  227. package/src/unstable-core-do-not-import/http/types.ts +1 -1
  228. package/src/unstable-core-do-not-import/initTRPC.ts +14 -20
  229. package/src/unstable-core-do-not-import/middleware.ts +5 -4
  230. package/src/unstable-core-do-not-import/parser.ts +17 -6
  231. package/src/unstable-core-do-not-import/procedure.ts +17 -2
  232. package/src/unstable-core-do-not-import/procedureBuilder.ts +138 -123
  233. package/src/unstable-core-do-not-import/rootConfig.ts +20 -17
  234. package/src/unstable-core-do-not-import/router.ts +15 -16
  235. package/src/unstable-core-do-not-import/rpc/codes.ts +2 -10
  236. package/src/unstable-core-do-not-import/rpc/envelopes.ts +18 -7
  237. package/src/unstable-core-do-not-import/rpc/parseTRPCMessage.ts +5 -1
  238. package/src/unstable-core-do-not-import/stream/jsonl.ts +293 -294
  239. package/src/unstable-core-do-not-import/stream/sse.ts +349 -191
  240. package/src/unstable-core-do-not-import/stream/sse.types.ts +44 -0
  241. package/src/unstable-core-do-not-import/stream/tracked.ts +49 -0
  242. package/src/unstable-core-do-not-import/stream/utils/asyncIterable.ts +89 -0
  243. package/src/unstable-core-do-not-import/stream/utils/createDeferred.ts +0 -36
  244. package/src/unstable-core-do-not-import/stream/utils/disposable.ts +52 -0
  245. package/src/unstable-core-do-not-import/stream/utils/readableStreamFrom.ts +28 -0
  246. package/src/unstable-core-do-not-import/stream/utils/timerResource.ts +29 -0
  247. package/src/unstable-core-do-not-import/stream/utils/withPing.ts +47 -0
  248. package/src/unstable-core-do-not-import/transformer.ts +1 -1
  249. package/src/unstable-core-do-not-import/types.ts +35 -10
  250. package/src/unstable-core-do-not-import/utils.ts +56 -1
  251. package/src/unstable-core-do-not-import.ts +4 -2
  252. package/src/vendor/unpromise/ATTRIBUTION.txt +1 -0
  253. package/src/vendor/unpromise/LICENSE +20 -0
  254. package/src/vendor/unpromise/index.ts +7 -0
  255. package/src/vendor/unpromise/types.ts +55 -0
  256. package/src/vendor/unpromise/unpromise.ts +380 -0
  257. package/dist/unstable-core-do-not-import/http/batchStreamFormatter.d.ts +0 -24
  258. package/dist/unstable-core-do-not-import/http/batchStreamFormatter.d.ts.map +0 -1
  259. package/dist/unstable-core-do-not-import/http/batchStreamFormatter.js +0 -32
  260. package/dist/unstable-core-do-not-import/http/batchStreamFormatter.mjs +0 -30
  261. package/dist/unstable-core-do-not-import/http/toURL.d.ts +0 -2
  262. package/dist/unstable-core-do-not-import/http/toURL.d.ts.map +0 -1
  263. package/dist/unstable-core-do-not-import/http/toURL.js +0 -8
  264. package/dist/unstable-core-do-not-import/http/toURL.mjs +0 -6
  265. package/dist/unstable-core-do-not-import/stream/utils/createReadableStream.d.ts +0 -10
  266. package/dist/unstable-core-do-not-import/stream/utils/createReadableStream.d.ts.map +0 -1
  267. package/dist/unstable-core-do-not-import/stream/utils/createReadableStream.js +0 -31
  268. package/dist/unstable-core-do-not-import/stream/utils/createReadableStream.mjs +0 -29
  269. package/dist/unstable-core-do-not-import/stream/utils/createServer.d.ts +0 -7
  270. package/dist/unstable-core-do-not-import/stream/utils/createServer.d.ts.map +0 -1
  271. package/dist/unstable-core-do-not-import/types.js +0 -11
  272. package/dist/unstable-core-do-not-import/types.mjs +0 -9
  273. package/src/unstable-core-do-not-import/http/batchStreamFormatter.ts +0 -29
  274. package/src/unstable-core-do-not-import/http/toURL.ts +0 -7
  275. package/src/unstable-core-do-not-import/stream/utils/createReadableStream.ts +0 -31
  276. package/src/unstable-core-do-not-import/stream/utils/createServer.ts +0 -44
@@ -0,0 +1,380 @@
1
+ /* eslint-disable @typescript-eslint/unbound-method */
2
+
3
+
4
+
5
+ import type {
6
+ PromiseExecutor,
7
+ PromiseWithResolvers,
8
+ ProxyPromise,
9
+ SubscribedPromise,
10
+ } from "./types";
11
+
12
+ /** Memory safe (weakmapped) cache of the ProxyPromise for each Promise,
13
+ * which is retained for the lifetime of the original Promise.
14
+ */
15
+ const subscribableCache = new WeakMap<
16
+ PromiseLike<unknown>,
17
+ ProxyPromise<unknown>
18
+ >();
19
+
20
+ /** A NOOP function allowing a consistent interface for settled
21
+ * SubscribedPromises (settled promises are not subscribed - they resolve
22
+ * immediately). */
23
+ const NOOP = () => {
24
+ // noop
25
+ };
26
+
27
+ /**
28
+ * Every `Promise<T>` can be shadowed by a single `ProxyPromise<T>`. It is
29
+ * created once, cached and reused throughout the lifetime of the Promise. Get a
30
+ * Promise's ProxyPromise using `Unpromise.proxy(promise)`.
31
+ *
32
+ * The `ProxyPromise<T>` attaches handlers to the original `Promise<T>`
33
+ * `.then()` and `.catch()` just once. Promises derived from it use a
34
+ * subscription- (and unsubscription-) based mechanism that monitors these
35
+ * handlers.
36
+ *
37
+ * Every time you call `.subscribe()`, `.then()` `.catch()` or `.finally()` on a
38
+ * `ProxyPromise<T>` it returns a `SubscribedPromise<T>` having an additional
39
+ * `unsubscribe()` method. Calling `unsubscribe()` detaches reference chains
40
+ * from the original, potentially long-lived Promise, eliminating memory leaks.
41
+ *
42
+ * This approach can eliminate the memory leaks that otherwise come about from
43
+ * repeated `race()` or `any()` calls invoking `.then()` and `.catch()` multiple
44
+ * times on the same long-lived native Promise (subscriptions which can never be
45
+ * cleaned up).
46
+ *
47
+ * `Unpromise.race(promises)` is a reference implementation of `Promise.race`
48
+ * avoiding memory leaks when using long-lived unsettled Promises.
49
+ *
50
+ * `Unpromise.any(promises)` is a reference implementation of `Promise.any`
51
+ * avoiding memory leaks when using long-lived unsettled Promises.
52
+ *
53
+ * `Unpromise.resolve(promise)` returns an ephemeral `SubscribedPromise<T>` for
54
+ * any given `Promise<T>` facilitating arbitrary async/await patterns. Behind
55
+ * the scenes, `resolve` is implemented simply as
56
+ * `Unpromise.proxy(promise).subscribe()`. Don't forget to call `.unsubscribe()`
57
+ * to tidy up!
58
+ *
59
+ */
60
+ export class Unpromise<T> implements ProxyPromise<T> {
61
+ /** INSTANCE IMPLEMENTATION */
62
+
63
+ /** The promise shadowed by this Unpromise<T> */
64
+ protected readonly promise: Promise<T> | PromiseLike<T>;
65
+
66
+ /** Promises expecting eventual settlement (unless unsubscribed first). This list is deleted
67
+ * after the original promise settles - no further notifications will be issued. */
68
+ protected subscribers: ReadonlyArray<PromiseWithResolvers<T>> | null = [];
69
+
70
+ /** The Promise's settlement (recorded when it fulfils or rejects). This is consulted when
71
+ * calling .subscribe() .then() .catch() .finally() to see if an immediately-resolving Promise
72
+ * can be returned, and therefore subscription can be bypassed. */
73
+ protected settlement: PromiseSettledResult<T> | null = null;
74
+
75
+ /** Constructor accepts a normal Promise executor function like `new
76
+ * Unpromise((resolve, reject) => {...})` or accepts a pre-existing Promise
77
+ * like `new Unpromise(existingPromise)`. Adds `.then()` and `.catch()`
78
+ * handlers to the Promise. These handlers pass fulfilment and rejection
79
+ * notifications to downstream subscribers and maintains records of value
80
+ * or error if the Promise ever settles. */
81
+ protected constructor(promise: Promise<T>);
82
+ protected constructor(promise: PromiseLike<T>);
83
+ protected constructor(executor: PromiseExecutor<T>);
84
+ protected constructor(arg: Promise<T> | PromiseLike<T> | PromiseExecutor<T>) {
85
+ // handle either a Promise or a Promise executor function
86
+ if (typeof arg === "function") {
87
+ this.promise = new Promise(arg);
88
+ } else {
89
+ this.promise = arg;
90
+ }
91
+
92
+ // subscribe for eventual fulfilment and rejection
93
+
94
+ // handle PromiseLike objects (that at least have .then)
95
+ const thenReturn = this.promise.then((value) => {
96
+ // atomically record fulfilment and detach subscriber list
97
+ const { subscribers } = this;
98
+ this.subscribers = null;
99
+ this.settlement = {
100
+ status: "fulfilled",
101
+ value,
102
+ };
103
+ // notify fulfilment to subscriber list
104
+ subscribers?.forEach(({ resolve }) => {
105
+ resolve(value);
106
+ });
107
+ });
108
+
109
+ // handle Promise (that also have a .catch behaviour)
110
+ if ("catch" in thenReturn) {
111
+ thenReturn.catch((reason) => {
112
+ // atomically record rejection and detach subscriber list
113
+ const { subscribers } = this;
114
+ this.subscribers = null;
115
+ this.settlement = {
116
+ status: "rejected",
117
+ reason,
118
+ };
119
+ // notify rejection to subscriber list
120
+ subscribers?.forEach(({ reject }) => {
121
+ reject(reason);
122
+ });
123
+ });
124
+ }
125
+ }
126
+
127
+ /** Create a promise that mitigates uncontrolled subscription to a long-lived
128
+ * Promise via .then() and .catch() - otherwise a source of memory leaks.
129
+ *
130
+ * The returned promise has an `unsubscribe()` method which can be called when
131
+ * the Promise is no longer being tracked by application logic, and which
132
+ * ensures that there is no reference chain from the original promise to the
133
+ * new one, and therefore no memory leak.
134
+ *
135
+ * If original promise has not yet settled, this adds a new unique promise
136
+ * that listens to then/catch events, along with an `unsubscribe()` method to
137
+ * detach it.
138
+ *
139
+ * If original promise has settled, then creates a new Promise.resolve() or
140
+ * Promise.reject() and provided unsubscribe is a noop.
141
+ *
142
+ * If you call `unsubscribe()` before the returned Promise has settled, it
143
+ * will never settle.
144
+ */
145
+ subscribe(): SubscribedPromise<T> {
146
+ // in all cases we will combine some promise with its unsubscribe function
147
+ let promise: Promise<T>;
148
+ let unsubscribe: () => void;
149
+
150
+ const { settlement } = this;
151
+ if (settlement === null) {
152
+ // not yet settled - subscribe new promise. Expect eventual settlement
153
+ if (this.subscribers === null) {
154
+ // invariant - it is not settled, so it must have subscribers
155
+ throw new Error("Unpromise settled but still has subscribers");
156
+ }
157
+ const subscriber = withResolvers<T>();
158
+ this.subscribers = listWithMember(this.subscribers, subscriber);
159
+ promise = subscriber.promise;
160
+ unsubscribe = () => {
161
+ if (this.subscribers !== null) {
162
+ this.subscribers = listWithoutMember(this.subscribers, subscriber);
163
+ }
164
+ };
165
+ } else {
166
+ // settled - don't create subscribed promise. Just resolve or reject
167
+ const { status } = settlement;
168
+ if (status === "fulfilled") {
169
+ promise = Promise.resolve(settlement.value);
170
+ } else {
171
+ promise = Promise.reject(settlement.reason);
172
+ }
173
+ unsubscribe = NOOP;
174
+ }
175
+
176
+ // extend promise signature with the extra method
177
+ return Object.assign(promise, { unsubscribe });
178
+ }
179
+
180
+ /** STANDARD PROMISE METHODS (but returning a SubscribedPromise) */
181
+
182
+ then<TResult1 = T, TResult2 = never>(
183
+ onfulfilled?:
184
+ | ((value: T) => TResult1 | PromiseLike<TResult1>)
185
+ | null
186
+ ,
187
+ onrejected?:
188
+ | ((reason: any) => TResult2 | PromiseLike<TResult2>)
189
+ | null
190
+
191
+ ): SubscribedPromise<TResult1 | TResult2> {
192
+ const subscribed = this.subscribe();
193
+ const { unsubscribe } = subscribed;
194
+ return Object.assign(subscribed.then(onfulfilled, onrejected), {
195
+ unsubscribe,
196
+ });
197
+ }
198
+
199
+ catch<TResult = never>(
200
+ onrejected?:
201
+ | ((reason: any) => TResult | PromiseLike<TResult>)
202
+ | null
203
+
204
+ ): SubscribedPromise<T | TResult> {
205
+ const subscribed = this.subscribe();
206
+ const { unsubscribe } = subscribed;
207
+ return Object.assign(subscribed.catch(onrejected), {
208
+ unsubscribe,
209
+ });
210
+ }
211
+
212
+ finally(onfinally?: (() => void) | null ): SubscribedPromise<T> {
213
+ const subscribed = this.subscribe();
214
+ const { unsubscribe } = subscribed;
215
+ return Object.assign(subscribed.finally(onfinally), {
216
+ unsubscribe,
217
+ });
218
+ }
219
+
220
+ /** TOSTRING SUPPORT */
221
+
222
+ readonly [Symbol.toStringTag] = "Unpromise";
223
+
224
+ /** Unpromise STATIC METHODS */
225
+
226
+ /** Create or Retrieve the proxy Unpromise (a re-used Unpromise for the VM lifetime
227
+ * of the provided Promise reference) */
228
+ static proxy<T>(promise: PromiseLike<T>): ProxyPromise<T> {
229
+ const cached = Unpromise.getSubscribablePromise(promise);
230
+ return typeof cached !== "undefined"
231
+ ? cached
232
+ : Unpromise.createSubscribablePromise(promise);
233
+ }
234
+
235
+ /** Create and store an Unpromise keyed by an original Promise. */
236
+ protected static createSubscribablePromise<T>(promise: PromiseLike<T>) {
237
+ const created = new Unpromise<T>(promise);
238
+ subscribableCache.set(promise, created as Unpromise<unknown>); // resolve promise to unpromise
239
+ subscribableCache.set(created, created as Unpromise<unknown>); // resolve the unpromise to itself
240
+ return created;
241
+ }
242
+
243
+ /** Retrieve a previously-created Unpromise keyed by an original Promise. */
244
+ protected static getSubscribablePromise<T>(promise: PromiseLike<T>) {
245
+ return subscribableCache.get(promise) as ProxyPromise<T> | undefined;
246
+ }
247
+
248
+ /** Promise STATIC METHODS */
249
+
250
+ /** Lookup the Unpromise for this promise, and derive a SubscribedPromise from
251
+ * it (that can be later unsubscribed to eliminate Memory leaks) */
252
+ static resolve<T>(value: T | PromiseLike<T>) {
253
+ const promise: PromiseLike<T> =
254
+ typeof value === "object" &&
255
+ value !== null &&
256
+ "then" in value &&
257
+ typeof value.then === "function"
258
+ ? value
259
+ : Promise.resolve(value);
260
+ return Unpromise.proxy(promise).subscribe() as SubscribedPromise<
261
+ Awaited<T>
262
+ >;
263
+ }
264
+
265
+ /** Perform Promise.any() via SubscribedPromises, then unsubscribe them.
266
+ * Equivalent to Promise.any but eliminates memory leaks from long-lived
267
+ * promises accumulating .then() and .catch() subscribers. */
268
+ static async any<T extends readonly unknown[] | []>(
269
+ values: T
270
+ ): Promise<Awaited<T[number]>>;
271
+ static async any<T>(
272
+ values: Iterable<T | PromiseLike<T>>
273
+ ): Promise<Awaited<T>> {
274
+ const valuesArray = Array.isArray(values) ? values : [...values];
275
+ const subscribedPromises = valuesArray.map(Unpromise.resolve);
276
+ try {
277
+ return await Promise.any(subscribedPromises);
278
+ } finally {
279
+ subscribedPromises.forEach(({ unsubscribe }) => {
280
+ unsubscribe();
281
+ });
282
+ }
283
+ }
284
+
285
+ /** Perform Promise.race via SubscribedPromises, then unsubscribe them.
286
+ * Equivalent to Promise.race but eliminates memory leaks from long-lived
287
+ * promises accumulating .then() and .catch() subscribers. */
288
+ static async race<T extends readonly unknown[] | []>(
289
+ values: T
290
+ ): Promise<Awaited<T[number]>>;
291
+ static async race<T>(
292
+ values: Iterable<T | PromiseLike<T>>
293
+ ): Promise<Awaited<T>> {
294
+ const valuesArray = Array.isArray(values) ? values : [...values];
295
+ const subscribedPromises = valuesArray.map(Unpromise.resolve);
296
+ try {
297
+ return await Promise.race(subscribedPromises);
298
+ } finally {
299
+ subscribedPromises.forEach(({ unsubscribe }) => {
300
+ unsubscribe();
301
+ });
302
+ }
303
+ }
304
+
305
+ /** Create a race of SubscribedPromises that will fulfil to a single winning
306
+ * Promise (in a 1-Tuple). Eliminates memory leaks from long-lived promises
307
+ * accumulating .then() and .catch() subscribers. Allows simple logic to
308
+ * consume the result, like...
309
+ * ```ts
310
+ * const [ winner ] = await Unpromise.race([ promiseA, promiseB ]);
311
+ * if(winner === promiseB){
312
+ * const result = await promiseB;
313
+ * // do the thing
314
+ * }
315
+ * ```
316
+ * */
317
+ static async raceReferences<TPromise extends Promise<unknown>>(
318
+ promises: readonly TPromise[]
319
+ ) {
320
+ // map each promise to an eventual 1-tuple containing itself
321
+ const selfPromises = promises.map(resolveSelfTuple);
322
+
323
+ // now race them. They will fulfil to a readonly [P] or reject.
324
+ try {
325
+ return await Promise.race(selfPromises);
326
+ } finally {
327
+ for (const promise of selfPromises) {
328
+ // unsubscribe proxy promises when the race is over to mitigate memory leaks
329
+ promise.unsubscribe();
330
+ }
331
+ }
332
+ }
333
+ }
334
+
335
+ /** Promises a 1-tuple containing the original promise when it resolves. Allows
336
+ * awaiting the eventual Promise ***reference*** (easy to destructure and
337
+ * exactly compare with ===). Avoids resolving to the Promise ***value*** (which
338
+ * may be ambiguous and therefore hard to identify as the winner of a race).
339
+ * You can call unsubscribe on the Promise to mitigate memory leaks.
340
+ * */
341
+ export function resolveSelfTuple<TPromise extends Promise<unknown>>(
342
+ promise: TPromise
343
+ ): SubscribedPromise<readonly [TPromise]> {
344
+ return Unpromise.proxy(promise).then(() => [promise] as const);
345
+ }
346
+
347
+ /** VENDORED (Future) PROMISE UTILITIES */
348
+
349
+ /** Reference implementation of https://github.com/tc39/proposal-promise-with-resolvers */
350
+ function withResolvers<T>(): PromiseWithResolvers<T> {
351
+ let resolve!: PromiseWithResolvers<T>["resolve"];
352
+ let reject!: PromiseWithResolvers<T>["reject"];
353
+ const promise = new Promise<T>((_resolve, _reject) => {
354
+ resolve = _resolve;
355
+ reject = _reject;
356
+ });
357
+ return {
358
+ promise,
359
+ resolve,
360
+ reject,
361
+ };
362
+ }
363
+
364
+ /** IMMUTABLE LIST OPERATIONS */
365
+
366
+ function listWithMember<T>(arr: readonly T[], member: T): readonly T[] {
367
+ return [...arr, member];
368
+ }
369
+
370
+ function listWithoutIndex<T>(arr: readonly T[], index: number) {
371
+ return [...arr.slice(0, index), ...arr.slice(index + 1)];
372
+ }
373
+
374
+ function listWithoutMember<T>(arr: readonly T[], member: unknown) {
375
+ const index = arr.indexOf(member as T);
376
+ if (index !== -1) {
377
+ return listWithoutIndex(arr, index);
378
+ }
379
+ return arr;
380
+ }
@@ -1,24 +0,0 @@
1
- /**
2
- * Format a batch response as a line-delimited JSON stream
3
- * that the `unstable_httpBatchStreamLink` can parse:
4
- *
5
- * @example
6
- * ```ts
7
- * const formatter = getBatchStreamFormatter();
8
- * res.send(formatter(1, 'response #2'));
9
- * res.send(formatter(0, 'response #1'));
10
- * res.send(formatter.end());
11
- * ```
12
- *
13
- * Expected format:
14
- * ```json
15
- * {"1":"response #2"
16
- * ,"0":"response #1"
17
- * }
18
- * ```
19
- */
20
- export declare function getBatchStreamFormatter(): {
21
- (index: number, string: string): string;
22
- end(): string;
23
- };
24
- //# sourceMappingURL=batchStreamFormatter.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"batchStreamFormatter.d.ts","sourceRoot":"","sources":["../../../src/unstable-core-do-not-import/http/batchStreamFormatter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,uBAAuB;YAEd,MAAM,UAAU,MAAM;;EAO9C"}
@@ -1,32 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * Format a batch response as a line-delimited JSON stream
5
- * that the `unstable_httpBatchStreamLink` can parse:
6
- *
7
- * @example
8
- * ```ts
9
- * const formatter = getBatchStreamFormatter();
10
- * res.send(formatter(1, 'response #2'));
11
- * res.send(formatter(0, 'response #1'));
12
- * res.send(formatter.end());
13
- * ```
14
- *
15
- * Expected format:
16
- * ```json
17
- * {"1":"response #2"
18
- * ,"0":"response #1"
19
- * }
20
- * ```
21
- */ function getBatchStreamFormatter() {
22
- let first = true;
23
- function format(index, string) {
24
- const prefix = first ? '{' : ',';
25
- first = false;
26
- return `${prefix}"${index}":${string}\n`;
27
- }
28
- format.end = ()=>'}';
29
- return format;
30
- }
31
-
32
- exports.getBatchStreamFormatter = getBatchStreamFormatter;
@@ -1,30 +0,0 @@
1
- /**
2
- * Format a batch response as a line-delimited JSON stream
3
- * that the `unstable_httpBatchStreamLink` can parse:
4
- *
5
- * @example
6
- * ```ts
7
- * const formatter = getBatchStreamFormatter();
8
- * res.send(formatter(1, 'response #2'));
9
- * res.send(formatter(0, 'response #1'));
10
- * res.send(formatter.end());
11
- * ```
12
- *
13
- * Expected format:
14
- * ```json
15
- * {"1":"response #2"
16
- * ,"0":"response #1"
17
- * }
18
- * ```
19
- */ function getBatchStreamFormatter() {
20
- let first = true;
21
- function format(index, string) {
22
- const prefix = first ? '{' : ',';
23
- first = false;
24
- return `${prefix}"${index}":${string}\n`;
25
- }
26
- format.end = ()=>'}';
27
- return format;
28
- }
29
-
30
- export { getBatchStreamFormatter };
@@ -1,2 +0,0 @@
1
- export declare function toURL(urlOrPathname: string): URL;
2
- //# sourceMappingURL=toURL.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"toURL.d.ts","sourceRoot":"","sources":["../../../src/unstable-core-do-not-import/http/toURL.ts"],"names":[],"mappings":"AAAA,wBAAgB,KAAK,CAAC,aAAa,EAAE,MAAM,GAAG,GAAG,CAMhD"}
@@ -1,8 +0,0 @@
1
- 'use strict';
2
-
3
- function toURL(urlOrPathname) {
4
- const url = urlOrPathname.startsWith('/') ? `http://127.0.0.1${urlOrPathname}` : urlOrPathname;
5
- return new URL(url);
6
- }
7
-
8
- exports.toURL = toURL;
@@ -1,6 +0,0 @@
1
- function toURL(urlOrPathname) {
2
- const url = urlOrPathname.startsWith('/') ? `http://127.0.0.1${urlOrPathname}` : urlOrPathname;
3
- return new URL(url);
4
- }
5
-
6
- export { toURL };
@@ -1,10 +0,0 @@
1
- /**
2
- * One-off readable stream
3
- */
4
- export declare function createReadableStream<TValue = unknown>(): {
5
- readonly readable: ReadableStream<TValue>;
6
- readonly controller: ReadableStreamDefaultController<TValue>;
7
- readonly cancelledPromise: Promise<"cancelled">;
8
- readonly cancelled: () => boolean;
9
- };
10
- //# sourceMappingURL=createReadableStream.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"createReadableStream.d.ts","sourceRoot":"","sources":["../../../../src/unstable-core-do-not-import/stream/utils/createReadableStream.ts"],"names":[],"mappings":"AAGA;;GAEG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,GAAG,OAAO;;;;;EAwBpD"}
@@ -1,31 +0,0 @@
1
- 'use strict';
2
-
3
- var createDeferred = require('./createDeferred.js');
4
-
5
- // ---------- utils
6
- /**
7
- * One-off readable stream
8
- */ function createReadableStream() {
9
- let controller = null;
10
- const deferred = createDeferred.createDeferred();
11
- let cancelled = false;
12
- const readable = new ReadableStream({
13
- start (c) {
14
- controller = c;
15
- },
16
- cancel () {
17
- deferred.resolve('cancelled');
18
- cancelled = true;
19
- }
20
- });
21
- return {
22
- readable,
23
- controller,
24
- cancelledPromise: deferred.promise,
25
- cancelled () {
26
- return cancelled;
27
- }
28
- };
29
- }
30
-
31
- exports.createReadableStream = createReadableStream;
@@ -1,29 +0,0 @@
1
- import { createDeferred } from './createDeferred.mjs';
2
-
3
- // ---------- utils
4
- /**
5
- * One-off readable stream
6
- */ function createReadableStream() {
7
- let controller = null;
8
- const deferred = createDeferred();
9
- let cancelled = false;
10
- const readable = new ReadableStream({
11
- start (c) {
12
- controller = c;
13
- },
14
- cancel () {
15
- deferred.resolve('cancelled');
16
- cancelled = true;
17
- }
18
- });
19
- return {
20
- readable,
21
- controller,
22
- cancelledPromise: deferred.promise,
23
- cancelled () {
24
- return cancelled;
25
- }
26
- };
27
- }
28
-
29
- export { createReadableStream };
@@ -1,7 +0,0 @@
1
- import http from 'http';
2
- export declare function createServer(handler: (req: http.IncomingMessage, res: http.ServerResponse) => void): {
3
- url: string;
4
- close: () => Promise<void>;
5
- restart: () => Promise<void>;
6
- };
7
- //# sourceMappingURL=createServer.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"createServer.d.ts","sourceRoot":"","sources":["../../../../src/unstable-core-do-not-import/stream/utils/createServer.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,MAAM,CAAC;AAGxB,wBAAgB,YAAY,CAC1B,OAAO,EAAE,CAAC,GAAG,EAAE,IAAI,CAAC,eAAe,EAAE,GAAG,EAAE,IAAI,CAAC,cAAc,KAAK,IAAI;;;;EAuCvE"}
@@ -1,11 +0,0 @@
1
- 'use strict';
2
-
3
- /**
4
- * ================================
5
- * Useful utility types that doesn't have anything to do with tRPC in particular
6
- * ================================
7
- */ /**
8
- * @public
9
- */ const ERROR_SYMBOL = Symbol('TypeError');
10
-
11
- exports.ERROR_SYMBOL = ERROR_SYMBOL;
@@ -1,9 +0,0 @@
1
- /**
2
- * ================================
3
- * Useful utility types that doesn't have anything to do with tRPC in particular
4
- * ================================
5
- */ /**
6
- * @public
7
- */ const ERROR_SYMBOL = Symbol('TypeError');
8
-
9
- export { ERROR_SYMBOL };
@@ -1,29 +0,0 @@
1
- /**
2
- * Format a batch response as a line-delimited JSON stream
3
- * that the `unstable_httpBatchStreamLink` can parse:
4
- *
5
- * @example
6
- * ```ts
7
- * const formatter = getBatchStreamFormatter();
8
- * res.send(formatter(1, 'response #2'));
9
- * res.send(formatter(0, 'response #1'));
10
- * res.send(formatter.end());
11
- * ```
12
- *
13
- * Expected format:
14
- * ```json
15
- * {"1":"response #2"
16
- * ,"0":"response #1"
17
- * }
18
- * ```
19
- */
20
- export function getBatchStreamFormatter() {
21
- let first = true;
22
- function format(index: number, string: string) {
23
- const prefix = first ? '{' : ',';
24
- first = false;
25
- return `${prefix}"${index}":${string}\n`;
26
- }
27
- format.end = () => '}';
28
- return format;
29
- }
@@ -1,7 +0,0 @@
1
- export function toURL(urlOrPathname: string): URL {
2
- const url = urlOrPathname.startsWith('/')
3
- ? `http://127.0.0.1${urlOrPathname}`
4
- : urlOrPathname;
5
-
6
- return new URL(url);
7
- }
@@ -1,31 +0,0 @@
1
- import { createDeferred } from './createDeferred';
2
-
3
- // ---------- utils
4
- /**
5
- * One-off readable stream
6
- */
7
- export function createReadableStream<TValue = unknown>() {
8
- let controller: ReadableStreamDefaultController<TValue> =
9
- null as unknown as ReadableStreamDefaultController<TValue>;
10
-
11
- const deferred = createDeferred<'cancelled'>();
12
- let cancelled = false;
13
- const readable = new ReadableStream<TValue>({
14
- start(c) {
15
- controller = c;
16
- },
17
- cancel() {
18
- deferred.resolve('cancelled');
19
- cancelled = true;
20
- },
21
- });
22
-
23
- return {
24
- readable,
25
- controller,
26
- cancelledPromise: deferred.promise,
27
- cancelled() {
28
- return cancelled;
29
- },
30
- } as const;
31
- }