@tanstack/router-ssr-query-core 1.121.0-alpha.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021-present Tanner Linsley
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+ <img src="https://static.scarf.sh/a.png?x-pxid=d988eb79-b0fc-4a2b-8514-6a1ab932d188" />
2
+
3
+ # TanStack Router Core
4
+
5
+ See [https://tanstack.com/router](https://tanstack.com/router) for documentation.
@@ -0,0 +1,137 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const queryCore = require("@tanstack/query-core");
4
+ const routerCore = require("@tanstack/router-core");
5
+ function setupCoreRouterSsrQueryIntegration({
6
+ router,
7
+ queryClient,
8
+ handleRedirects = true
9
+ }) {
10
+ const ogHydrate = router.options.hydrate;
11
+ const ogDehydrate = router.options.dehydrate;
12
+ if (router.isServer) {
13
+ const sentQueries = /* @__PURE__ */ new Set();
14
+ const queryStream = createPushableStream();
15
+ router.options.dehydrate = async () => {
16
+ router.serverSsr.onRenderFinished(() => queryStream.close());
17
+ const ogDehydrated = await ogDehydrate?.();
18
+ const dehydratedRouter = {
19
+ ...ogDehydrated,
20
+ // prepare the stream for queries coming up during rendering
21
+ queryStream: queryStream.stream
22
+ };
23
+ const dehydratedQueryClient = queryCore.dehydrate(queryClient);
24
+ if (dehydratedQueryClient.queries.length > 0) {
25
+ dehydratedQueryClient.queries.forEach((query) => {
26
+ sentQueries.add(query.queryHash);
27
+ });
28
+ dehydratedRouter.dehydratedQueryClient = dehydratedQueryClient;
29
+ }
30
+ return dehydratedRouter;
31
+ };
32
+ const ogClientOptions = queryClient.getDefaultOptions();
33
+ queryClient.setDefaultOptions({
34
+ ...ogClientOptions,
35
+ dehydrate: {
36
+ shouldDehydrateQuery: () => true,
37
+ ...ogClientOptions.dehydrate
38
+ }
39
+ });
40
+ queryClient.getQueryCache().subscribe((event) => {
41
+ if (!router.serverSsr?.isDehydrated()) {
42
+ return;
43
+ }
44
+ if (sentQueries.has(event.query.queryHash)) {
45
+ return;
46
+ }
47
+ if (queryStream.isClosed()) {
48
+ console.warn(
49
+ `tried to stream query ${event.query.queryHash} after stream was already closed`
50
+ );
51
+ return;
52
+ }
53
+ if (!event.query.promise) {
54
+ return;
55
+ }
56
+ sentQueries.add(event.query.queryHash);
57
+ queryStream.enqueue(
58
+ queryCore.dehydrate(queryClient, {
59
+ shouldDehydrateQuery: (query) => {
60
+ if (query.queryHash === event.query.queryHash) {
61
+ return ogClientOptions.dehydrate?.shouldDehydrateQuery?.(query) ?? true;
62
+ }
63
+ return false;
64
+ }
65
+ })
66
+ );
67
+ });
68
+ } else {
69
+ router.options.hydrate = async (dehydrated) => {
70
+ await ogHydrate?.(dehydrated);
71
+ if (dehydrated.dehydratedQueryClient) {
72
+ queryCore.hydrate(queryClient, dehydrated.dehydratedQueryClient);
73
+ }
74
+ const reader = dehydrated.queryStream.getReader();
75
+ reader.read().then(async function handle({ done, value }) {
76
+ queryCore.hydrate(queryClient, value);
77
+ if (done) {
78
+ return;
79
+ }
80
+ const result = await reader.read();
81
+ return handle(result);
82
+ }).catch((err) => {
83
+ console.error("Error reading query stream:", err);
84
+ });
85
+ };
86
+ if (handleRedirects) {
87
+ const ogMutationCacheConfig = queryClient.getMutationCache().config;
88
+ queryClient.getMutationCache().config = {
89
+ ...ogMutationCacheConfig,
90
+ onError: (error, _variables, _context, _mutation) => {
91
+ if (routerCore.isRedirect(error)) {
92
+ error.options._fromLocation = router.state.location;
93
+ return router.navigate(router.resolveRedirect(error).options);
94
+ }
95
+ return ogMutationCacheConfig.onError?.(
96
+ error,
97
+ _variables,
98
+ _context,
99
+ _mutation
100
+ );
101
+ }
102
+ };
103
+ const ogQueryCacheConfig = queryClient.getQueryCache().config;
104
+ queryClient.getQueryCache().config = {
105
+ ...ogQueryCacheConfig,
106
+ onError: (error, _query) => {
107
+ if (routerCore.isRedirect(error)) {
108
+ error.options._fromLocation = router.state.location;
109
+ return router.navigate(router.resolveRedirect(error).options);
110
+ }
111
+ return ogQueryCacheConfig.onError?.(error, _query);
112
+ }
113
+ };
114
+ }
115
+ }
116
+ }
117
+ function createPushableStream() {
118
+ let controllerRef;
119
+ const stream = new ReadableStream({
120
+ start(controller) {
121
+ controllerRef = controller;
122
+ }
123
+ });
124
+ let _isClosed = false;
125
+ return {
126
+ stream,
127
+ enqueue: (chunk) => controllerRef.enqueue(chunk),
128
+ close: () => {
129
+ controllerRef.close();
130
+ _isClosed = true;
131
+ },
132
+ isClosed: () => _isClosed,
133
+ error: (err) => controllerRef.error(err)
134
+ };
135
+ }
136
+ exports.setupCoreRouterSsrQueryIntegration = setupCoreRouterSsrQueryIntegration;
137
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":["../../src/index.ts"],"sourcesContent":["import {\n dehydrate as queryDehydrate,\n hydrate as queryHydrate,\n} from '@tanstack/query-core'\nimport { isRedirect } from '@tanstack/router-core'\nimport type { AnyRouter } from '@tanstack/router-core'\nimport type {\n QueryClient,\n DehydratedState as QueryDehydratedState,\n} from '@tanstack/query-core'\n\nexport type RouterSsrQueryOptions<TRouter extends AnyRouter> = {\n router: TRouter\n queryClient: QueryClient\n\n /**\n * If `true`, the QueryClient will handle errors thrown by `redirect()` inside of mutations and queries.\n *\n * @default true\n * @link [Guide](https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction)\n */\n handleRedirects?: boolean\n}\n\ntype DehydratedRouterQueryState = {\n dehydratedQueryClient?: QueryDehydratedState\n queryStream: ReadableStream<QueryDehydratedState>\n}\n\nexport function setupCoreRouterSsrQueryIntegration<TRouter extends AnyRouter>({\n router,\n queryClient,\n handleRedirects = true,\n}: RouterSsrQueryOptions<TRouter>) {\n const ogHydrate = router.options.hydrate\n const ogDehydrate = router.options.dehydrate\n\n if (router.isServer) {\n const sentQueries = new Set<string>()\n const queryStream = createPushableStream()\n\n router.options.dehydrate =\n async (): Promise<DehydratedRouterQueryState> => {\n router.serverSsr!.onRenderFinished(() => queryStream.close())\n const ogDehydrated = await ogDehydrate?.()\n\n const dehydratedRouter = {\n ...ogDehydrated,\n // prepare the stream for queries coming up during rendering\n queryStream: queryStream.stream,\n }\n\n const dehydratedQueryClient = queryDehydrate(queryClient)\n if (dehydratedQueryClient.queries.length > 0) {\n dehydratedQueryClient.queries.forEach((query) => {\n sentQueries.add(query.queryHash)\n })\n dehydratedRouter.dehydratedQueryClient = dehydratedQueryClient\n }\n\n return dehydratedRouter\n }\n\n const ogClientOptions = queryClient.getDefaultOptions()\n queryClient.setDefaultOptions({\n ...ogClientOptions,\n dehydrate: {\n shouldDehydrateQuery: () => true,\n ...ogClientOptions.dehydrate,\n },\n })\n\n queryClient.getQueryCache().subscribe((event) => {\n // before rendering starts, we do not stream individual queries\n // instead we dehydrate the entire query client in router's dehydrate()\n // if attachRouterServerSsrUtils() has not been called yet, `router.serverSsr` will be undefined and we also do not stream\n if (!router.serverSsr?.isDehydrated()) {\n return\n }\n if (sentQueries.has(event.query.queryHash)) {\n return\n }\n if (queryStream.isClosed()) {\n console.warn(\n `tried to stream query ${event.query.queryHash} after stream was already closed`,\n )\n return\n }\n // promise not yet set on the query, so we cannot stream it yet\n if (!event.query.promise) {\n return\n }\n sentQueries.add(event.query.queryHash)\n queryStream.enqueue(\n queryDehydrate(queryClient, {\n shouldDehydrateQuery: (query) => {\n if (query.queryHash === event.query.queryHash) {\n return (\n ogClientOptions.dehydrate?.shouldDehydrateQuery?.(query) ?? true\n )\n }\n return false\n },\n }),\n )\n })\n // on the client\n } else {\n router.options.hydrate = async (dehydrated: DehydratedRouterQueryState) => {\n await ogHydrate?.(dehydrated)\n // hydrate the query client with the dehydrated data (if it was dehydrated on the server)\n if (dehydrated.dehydratedQueryClient) {\n queryHydrate(queryClient, dehydrated.dehydratedQueryClient)\n }\n\n // read the query stream and hydrate the queries as they come in\n const reader = dehydrated.queryStream.getReader()\n reader\n .read()\n .then(async function handle({ done, value }) {\n queryHydrate(queryClient, value)\n if (done) {\n return\n }\n const result = await reader.read()\n return handle(result)\n })\n .catch((err) => {\n console.error('Error reading query stream:', err)\n })\n }\n if (handleRedirects) {\n const ogMutationCacheConfig = queryClient.getMutationCache().config\n queryClient.getMutationCache().config = {\n ...ogMutationCacheConfig,\n onError: (error, _variables, _context, _mutation) => {\n if (isRedirect(error)) {\n error.options._fromLocation = router.state.location\n return router.navigate(router.resolveRedirect(error).options)\n }\n\n return ogMutationCacheConfig.onError?.(\n error,\n _variables,\n _context,\n _mutation,\n )\n },\n }\n\n const ogQueryCacheConfig = queryClient.getQueryCache().config\n queryClient.getQueryCache().config = {\n ...ogQueryCacheConfig,\n onError: (error, _query) => {\n if (isRedirect(error)) {\n error.options._fromLocation = router.state.location\n return router.navigate(router.resolveRedirect(error).options)\n }\n\n return ogQueryCacheConfig.onError?.(error, _query)\n },\n }\n }\n }\n}\n\ntype PushableStream = {\n stream: ReadableStream\n enqueue: (chunk: unknown) => void\n close: () => void\n isClosed: () => boolean\n error: (err: unknown) => void\n}\n\nfunction createPushableStream(): PushableStream {\n let controllerRef: ReadableStreamDefaultController\n const stream = new ReadableStream({\n start(controller) {\n controllerRef = controller\n },\n })\n let _isClosed = false\n\n return {\n stream,\n enqueue: (chunk) => controllerRef.enqueue(chunk),\n close: () => {\n controllerRef.close()\n _isClosed = true\n },\n isClosed: () => _isClosed,\n error: (err: unknown) => controllerRef.error(err),\n }\n}\n"],"names":["queryDehydrate","queryHydrate","isRedirect"],"mappings":";;;;AA6BO,SAAS,mCAA8D;AAAA,EAC5E;AAAA,EACA;AAAA,EACA,kBAAkB;AACpB,GAAmC;AACjC,QAAM,YAAY,OAAO,QAAQ;AACjC,QAAM,cAAc,OAAO,QAAQ;AAEnC,MAAI,OAAO,UAAU;AACnB,UAAM,kCAAkB,IAAA;AACxB,UAAM,cAAc,qBAAA;AAEpB,WAAO,QAAQ,YACb,YAAiD;AAC/C,aAAO,UAAW,iBAAiB,MAAM,YAAY,OAAO;AAC5D,YAAM,eAAe,MAAM,cAAA;AAE3B,YAAM,mBAAmB;AAAA,QACvB,GAAG;AAAA;AAAA,QAEH,aAAa,YAAY;AAAA,MAAA;AAG3B,YAAM,wBAAwBA,UAAAA,UAAe,WAAW;AACxD,UAAI,sBAAsB,QAAQ,SAAS,GAAG;AAC5C,8BAAsB,QAAQ,QAAQ,CAAC,UAAU;AAC/C,sBAAY,IAAI,MAAM,SAAS;AAAA,QACjC,CAAC;AACD,yBAAiB,wBAAwB;AAAA,MAC3C;AAEA,aAAO;AAAA,IACT;AAEF,UAAM,kBAAkB,YAAY,kBAAA;AACpC,gBAAY,kBAAkB;AAAA,MAC5B,GAAG;AAAA,MACH,WAAW;AAAA,QACT,sBAAsB,MAAM;AAAA,QAC5B,GAAG,gBA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QACtC,GAAG;AAAA,QACH,SAAS,CAAC,OAAO,YAAY,UAAU,cAAc;AACnD,cAAIC,WAAAA,WAAW,KAAK,GAAG;AACrB,kBAAM,QAAQ,gBAAgB,OAAO,MAAM;AAC3C,mBAAO,OAAO,SAAS,OAAO,gBAAgB,KAAK,EAAE,OAAO;AAAA,UAC9D;AAEA,iBAAO,sBAAsB;AAAA,YAC3B;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UAAA;AAAA,QAEJ;AAAA,MAAA;AAGF,YAAM,qBAAqB,YAAY,cAAA,EAAgB;AACvD,kBAAY,cAAA,EAAgB,SAAS;AAAA,QACnC,GAAG;AAAA,QACH,SAAS,CAAC,OAAO,WAAW;AAC1B,cAAIA,WAAAA,WAAW,KAAK,GAAG;AACrB,kBAAM,QAAQ,gBAAgB,OAAO,MAAM;AAC3C,mBAAO,OAAO,SAAS,OAAO,gBAAgB,KAAK,EAAE,OAAO;AAAA,UAC9D;AAEA,iBAAO,mBAAmB,UAAU,OAAO,MAAM;AAAA,QACnD;AAAA,MAAA;AAAA,IAEJ;AAAA,EACF;AACF;AAUA,SAAS,uBAAuC;AAC9C,MAAI;AACJ,QAAM,SAAS,IAAI,eAAe;AAAA,IAChC,MAAM,YAAY;AAChB,sBAAgB;AAAA,IAClB;AAAA,EAAA,CACD;AACD,MAAI,YAAY;AAEhB,SAAO;AAAA,IACL;AAAA,IACA,SAAS,CAAC,UAAU,cAAc,QAAQ,KAAK;AAAA,IAC/C,OAAO,MAAM;AACX,oBAAc,MAAA;AACd,kBAAY;AAAA,IACd;AAAA,IACA,UAAU,MAAM;AAAA,IAChB,OAAO,CAAC,QAAiB,cAAc,MAAM,GAAG;AAAA,EAAA;AAEpD;;"}
@@ -0,0 +1,14 @@
1
+ import { AnyRouter } from '@tanstack/router-core';
2
+ import { QueryClient } from '@tanstack/query-core';
3
+ export type RouterSsrQueryOptions<TRouter extends AnyRouter> = {
4
+ router: TRouter;
5
+ queryClient: QueryClient;
6
+ /**
7
+ * If `true`, the QueryClient will handle errors thrown by `redirect()` inside of mutations and queries.
8
+ *
9
+ * @default true
10
+ * @link [Guide](https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction)
11
+ */
12
+ handleRedirects?: boolean;
13
+ };
14
+ export declare function setupCoreRouterSsrQueryIntegration<TRouter extends AnyRouter>({ router, queryClient, handleRedirects, }: RouterSsrQueryOptions<TRouter>): void;
@@ -0,0 +1,14 @@
1
+ import { AnyRouter } from '@tanstack/router-core';
2
+ import { QueryClient } from '@tanstack/query-core';
3
+ export type RouterSsrQueryOptions<TRouter extends AnyRouter> = {
4
+ router: TRouter;
5
+ queryClient: QueryClient;
6
+ /**
7
+ * If `true`, the QueryClient will handle errors thrown by `redirect()` inside of mutations and queries.
8
+ *
9
+ * @default true
10
+ * @link [Guide](https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction)
11
+ */
12
+ handleRedirects?: boolean;
13
+ };
14
+ export declare function setupCoreRouterSsrQueryIntegration<TRouter extends AnyRouter>({ router, queryClient, handleRedirects, }: RouterSsrQueryOptions<TRouter>): void;
@@ -0,0 +1,137 @@
1
+ import { dehydrate, hydrate } from "@tanstack/query-core";
2
+ import { isRedirect } from "@tanstack/router-core";
3
+ function setupCoreRouterSsrQueryIntegration({
4
+ router,
5
+ queryClient,
6
+ handleRedirects = true
7
+ }) {
8
+ const ogHydrate = router.options.hydrate;
9
+ const ogDehydrate = router.options.dehydrate;
10
+ if (router.isServer) {
11
+ const sentQueries = /* @__PURE__ */ new Set();
12
+ const queryStream = createPushableStream();
13
+ router.options.dehydrate = async () => {
14
+ router.serverSsr.onRenderFinished(() => queryStream.close());
15
+ const ogDehydrated = await ogDehydrate?.();
16
+ const dehydratedRouter = {
17
+ ...ogDehydrated,
18
+ // prepare the stream for queries coming up during rendering
19
+ queryStream: queryStream.stream
20
+ };
21
+ const dehydratedQueryClient = dehydrate(queryClient);
22
+ if (dehydratedQueryClient.queries.length > 0) {
23
+ dehydratedQueryClient.queries.forEach((query) => {
24
+ sentQueries.add(query.queryHash);
25
+ });
26
+ dehydratedRouter.dehydratedQueryClient = dehydratedQueryClient;
27
+ }
28
+ return dehydratedRouter;
29
+ };
30
+ const ogClientOptions = queryClient.getDefaultOptions();
31
+ queryClient.setDefaultOptions({
32
+ ...ogClientOptions,
33
+ dehydrate: {
34
+ shouldDehydrateQuery: () => true,
35
+ ...ogClientOptions.dehydrate
36
+ }
37
+ });
38
+ queryClient.getQueryCache().subscribe((event) => {
39
+ if (!router.serverSsr?.isDehydrated()) {
40
+ return;
41
+ }
42
+ if (sentQueries.has(event.query.queryHash)) {
43
+ return;
44
+ }
45
+ if (queryStream.isClosed()) {
46
+ console.warn(
47
+ `tried to stream query ${event.query.queryHash} after stream was already closed`
48
+ );
49
+ return;
50
+ }
51
+ if (!event.query.promise) {
52
+ return;
53
+ }
54
+ sentQueries.add(event.query.queryHash);
55
+ queryStream.enqueue(
56
+ dehydrate(queryClient, {
57
+ shouldDehydrateQuery: (query) => {
58
+ if (query.queryHash === event.query.queryHash) {
59
+ return ogClientOptions.dehydrate?.shouldDehydrateQuery?.(query) ?? true;
60
+ }
61
+ return false;
62
+ }
63
+ })
64
+ );
65
+ });
66
+ } else {
67
+ router.options.hydrate = async (dehydrated) => {
68
+ await ogHydrate?.(dehydrated);
69
+ if (dehydrated.dehydratedQueryClient) {
70
+ hydrate(queryClient, dehydrated.dehydratedQueryClient);
71
+ }
72
+ const reader = dehydrated.queryStream.getReader();
73
+ reader.read().then(async function handle({ done, value }) {
74
+ hydrate(queryClient, value);
75
+ if (done) {
76
+ return;
77
+ }
78
+ const result = await reader.read();
79
+ return handle(result);
80
+ }).catch((err) => {
81
+ console.error("Error reading query stream:", err);
82
+ });
83
+ };
84
+ if (handleRedirects) {
85
+ const ogMutationCacheConfig = queryClient.getMutationCache().config;
86
+ queryClient.getMutationCache().config = {
87
+ ...ogMutationCacheConfig,
88
+ onError: (error, _variables, _context, _mutation) => {
89
+ if (isRedirect(error)) {
90
+ error.options._fromLocation = router.state.location;
91
+ return router.navigate(router.resolveRedirect(error).options);
92
+ }
93
+ return ogMutationCacheConfig.onError?.(
94
+ error,
95
+ _variables,
96
+ _context,
97
+ _mutation
98
+ );
99
+ }
100
+ };
101
+ const ogQueryCacheConfig = queryClient.getQueryCache().config;
102
+ queryClient.getQueryCache().config = {
103
+ ...ogQueryCacheConfig,
104
+ onError: (error, _query) => {
105
+ if (isRedirect(error)) {
106
+ error.options._fromLocation = router.state.location;
107
+ return router.navigate(router.resolveRedirect(error).options);
108
+ }
109
+ return ogQueryCacheConfig.onError?.(error, _query);
110
+ }
111
+ };
112
+ }
113
+ }
114
+ }
115
+ function createPushableStream() {
116
+ let controllerRef;
117
+ const stream = new ReadableStream({
118
+ start(controller) {
119
+ controllerRef = controller;
120
+ }
121
+ });
122
+ let _isClosed = false;
123
+ return {
124
+ stream,
125
+ enqueue: (chunk) => controllerRef.enqueue(chunk),
126
+ close: () => {
127
+ controllerRef.close();
128
+ _isClosed = true;
129
+ },
130
+ isClosed: () => _isClosed,
131
+ error: (err) => controllerRef.error(err)
132
+ };
133
+ }
134
+ export {
135
+ setupCoreRouterSsrQueryIntegration
136
+ };
137
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../../src/index.ts"],"sourcesContent":["import {\n dehydrate as queryDehydrate,\n hydrate as queryHydrate,\n} from '@tanstack/query-core'\nimport { isRedirect } from '@tanstack/router-core'\nimport type { AnyRouter } from '@tanstack/router-core'\nimport type {\n QueryClient,\n DehydratedState as QueryDehydratedState,\n} from '@tanstack/query-core'\n\nexport type RouterSsrQueryOptions<TRouter extends AnyRouter> = {\n router: TRouter\n queryClient: QueryClient\n\n /**\n * If `true`, the QueryClient will handle errors thrown by `redirect()` inside of mutations and queries.\n *\n * @default true\n * @link [Guide](https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction)\n */\n handleRedirects?: boolean\n}\n\ntype DehydratedRouterQueryState = {\n dehydratedQueryClient?: QueryDehydratedState\n queryStream: ReadableStream<QueryDehydratedState>\n}\n\nexport function setupCoreRouterSsrQueryIntegration<TRouter extends AnyRouter>({\n router,\n queryClient,\n handleRedirects = true,\n}: RouterSsrQueryOptions<TRouter>) {\n const ogHydrate = router.options.hydrate\n const ogDehydrate = router.options.dehydrate\n\n if (router.isServer) {\n const sentQueries = new Set<string>()\n const queryStream = createPushableStream()\n\n router.options.dehydrate =\n async (): Promise<DehydratedRouterQueryState> => {\n router.serverSsr!.onRenderFinished(() => queryStream.close())\n const ogDehydrated = await ogDehydrate?.()\n\n const dehydratedRouter = {\n ...ogDehydrated,\n // prepare the stream for queries coming up during rendering\n queryStream: queryStream.stream,\n }\n\n const dehydratedQueryClient = queryDehydrate(queryClient)\n if (dehydratedQueryClient.queries.length > 0) {\n dehydratedQueryClient.queries.forEach((query) => {\n sentQueries.add(query.queryHash)\n })\n dehydratedRouter.dehydratedQueryClient = dehydratedQueryClient\n }\n\n return dehydratedRouter\n }\n\n const ogClientOptions = queryClient.getDefaultOptions()\n queryClient.setDefaultOptions({\n ...ogClientOptions,\n dehydrate: {\n shouldDehydrateQuery: () => true,\n ...ogClientOptions.dehydrate,\n },\n })\n\n queryClient.getQueryCache().subscribe((event) => {\n // before rendering starts, we do not stream individual queries\n // instead we dehydrate the entire query client in router's dehydrate()\n // if attachRouterServerSsrUtils() has not been called yet, `router.serverSsr` will be undefined and we also do not stream\n if (!router.serverSsr?.isDehydrated()) {\n return\n }\n if (sentQueries.has(event.query.queryHash)) {\n return\n }\n if (queryStream.isClosed()) {\n console.warn(\n `tried to stream query ${event.query.queryHash} after stream was already closed`,\n )\n return\n }\n // promise not yet set on the query, so we cannot stream it yet\n if (!event.query.promise) {\n return\n }\n sentQueries.add(event.query.queryHash)\n queryStream.enqueue(\n queryDehydrate(queryClient, {\n shouldDehydrateQuery: (query) => {\n if (query.queryHash === event.query.queryHash) {\n return (\n ogClientOptions.dehydrate?.shouldDehydrateQuery?.(query) ?? true\n )\n }\n return false\n },\n }),\n )\n })\n // on the client\n } else {\n router.options.hydrate = async (dehydrated: DehydratedRouterQueryState) => {\n await ogHydrate?.(dehydrated)\n // hydrate the query client with the dehydrated data (if it was dehydrated on the server)\n if (dehydrated.dehydratedQueryClient) {\n queryHydrate(queryClient, dehydrated.dehydratedQueryClient)\n }\n\n // read the query stream and hydrate the queries as they come in\n const reader = dehydrated.queryStream.getReader()\n reader\n .read()\n .then(async function handle({ done, value }) {\n queryHydrate(queryClient, value)\n if (done) {\n return\n }\n const result = await reader.read()\n return handle(result)\n })\n .catch((err) => {\n console.error('Error reading query stream:', err)\n })\n }\n if (handleRedirects) {\n const ogMutationCacheConfig = queryClient.getMutationCache().config\n queryClient.getMutationCache().config = {\n ...ogMutationCacheConfig,\n onError: (error, _variables, _context, _mutation) => {\n if (isRedirect(error)) {\n error.options._fromLocation = router.state.location\n return router.navigate(router.resolveRedirect(error).options)\n }\n\n return ogMutationCacheConfig.onError?.(\n error,\n _variables,\n _context,\n _mutation,\n )\n },\n }\n\n const ogQueryCacheConfig = queryClient.getQueryCache().config\n queryClient.getQueryCache().config = {\n ...ogQueryCacheConfig,\n onError: (error, _query) => {\n if (isRedirect(error)) {\n error.options._fromLocation = router.state.location\n return router.navigate(router.resolveRedirect(error).options)\n }\n\n return ogQueryCacheConfig.onError?.(error, _query)\n },\n }\n }\n }\n}\n\ntype PushableStream = {\n stream: ReadableStream\n enqueue: (chunk: unknown) => void\n close: () => void\n isClosed: () => boolean\n error: (err: unknown) => void\n}\n\nfunction createPushableStream(): PushableStream {\n let controllerRef: ReadableStreamDefaultController\n const stream = new ReadableStream({\n start(controller) {\n controllerRef = controller\n },\n })\n let _isClosed = false\n\n return {\n stream,\n enqueue: (chunk) => controllerRef.enqueue(chunk),\n close: () => {\n controllerRef.close()\n _isClosed = true\n },\n isClosed: () => _isClosed,\n error: (err: unknown) => controllerRef.error(err),\n }\n}\n"],"names":["queryDehydrate","queryHydrate"],"mappings":";;AA6BO,SAAS,m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AgB,OAAO,MAAM;AAC3C,mBAAO,OAAO,SAAS,OAAO,gBAAgB,KAAK,EAAE,OAAO;AAAA,UAC9D;AAEA,iBAAO,mBAAmB,UAAU,OAAO,MAAM;AAAA,QACnD;AAAA,MAAA;AAAA,IAEJ;AAAA,EACF;AACF;AAUA,SAAS,uBAAuC;AAC9C,MAAI;AACJ,QAAM,SAAS,IAAI,eAAe;AAAA,IAChC,MAAM,YAAY;AAChB,sBAAgB;AAAA,IAClB;AAAA,EAAA,CACD;AACD,MAAI,YAAY;AAEhB,SAAO;AAAA,IACL;AAAA,IACA,SAAS,CAAC,UAAU,cAAc,QAAQ,KAAK;AAAA,IAC/C,OAAO,MAAM;AACX,oBAAc,MAAA;AACd,kBAAY;AAAA,IACd;AAAA,IACA,UAAU,MAAM;AAAA,IAChB,OAAO,CAAC,QAAiB,cAAc,MAAM,GAAG;AAAA,EAAA;AAEpD;"}
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "@tanstack/router-ssr-query-core",
3
+ "version": "1.121.0-alpha.28",
4
+ "description": "Modern and scalable routing for React applications",
5
+ "author": "Tanner Linsley",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/TanStack/router.git",
10
+ "directory": "packages/router-ssr-query-core"
11
+ },
12
+ "homepage": "https://tanstack.com/router",
13
+ "funding": {
14
+ "type": "github",
15
+ "url": "https://github.com/sponsors/tannerlinsley"
16
+ },
17
+ "keywords": [
18
+ "react",
19
+ "location",
20
+ "router",
21
+ "routing",
22
+ "async",
23
+ "async router",
24
+ "typescript"
25
+ ],
26
+ "type": "module",
27
+ "types": "dist/esm/index.d.ts",
28
+ "main": "dist/cjs/index.cjs",
29
+ "module": "dist/esm/index.js",
30
+ "exports": {
31
+ ".": {
32
+ "import": {
33
+ "types": "./dist/esm/index.d.ts",
34
+ "default": "./dist/esm/index.js"
35
+ },
36
+ "require": {
37
+ "types": "./dist/cjs/index.d.cts",
38
+ "default": "./dist/cjs/index.cjs"
39
+ }
40
+ },
41
+ "./package.json": "./package.json"
42
+ },
43
+ "sideEffects": false,
44
+ "files": [
45
+ "dist",
46
+ "src"
47
+ ],
48
+ "engines": {
49
+ "node": ">=12"
50
+ },
51
+ "devDependencies": {
52
+ "@tanstack/router-core": ">=1.127.0",
53
+ "@tanstack/query-core": ">=5.66.0"
54
+ },
55
+ "peerDependencies": {
56
+ "@tanstack/router-core": ">=1.127.0",
57
+ "@tanstack/query-core": ">=5.66.0"
58
+ },
59
+ "scripts": {}
60
+ }
package/src/index.ts ADDED
@@ -0,0 +1,194 @@
1
+ import {
2
+ dehydrate as queryDehydrate,
3
+ hydrate as queryHydrate,
4
+ } from '@tanstack/query-core'
5
+ import { isRedirect } from '@tanstack/router-core'
6
+ import type { AnyRouter } from '@tanstack/router-core'
7
+ import type {
8
+ QueryClient,
9
+ DehydratedState as QueryDehydratedState,
10
+ } from '@tanstack/query-core'
11
+
12
+ export type RouterSsrQueryOptions<TRouter extends AnyRouter> = {
13
+ router: TRouter
14
+ queryClient: QueryClient
15
+
16
+ /**
17
+ * If `true`, the QueryClient will handle errors thrown by `redirect()` inside of mutations and queries.
18
+ *
19
+ * @default true
20
+ * @link [Guide](https://tanstack.com/router/latest/docs/framework/react/api/router/redirectFunction)
21
+ */
22
+ handleRedirects?: boolean
23
+ }
24
+
25
+ type DehydratedRouterQueryState = {
26
+ dehydratedQueryClient?: QueryDehydratedState
27
+ queryStream: ReadableStream<QueryDehydratedState>
28
+ }
29
+
30
+ export function setupCoreRouterSsrQueryIntegration<TRouter extends AnyRouter>({
31
+ router,
32
+ queryClient,
33
+ handleRedirects = true,
34
+ }: RouterSsrQueryOptions<TRouter>) {
35
+ const ogHydrate = router.options.hydrate
36
+ const ogDehydrate = router.options.dehydrate
37
+
38
+ if (router.isServer) {
39
+ const sentQueries = new Set<string>()
40
+ const queryStream = createPushableStream()
41
+
42
+ router.options.dehydrate =
43
+ async (): Promise<DehydratedRouterQueryState> => {
44
+ router.serverSsr!.onRenderFinished(() => queryStream.close())
45
+ const ogDehydrated = await ogDehydrate?.()
46
+
47
+ const dehydratedRouter = {
48
+ ...ogDehydrated,
49
+ // prepare the stream for queries coming up during rendering
50
+ queryStream: queryStream.stream,
51
+ }
52
+
53
+ const dehydratedQueryClient = queryDehydrate(queryClient)
54
+ if (dehydratedQueryClient.queries.length > 0) {
55
+ dehydratedQueryClient.queries.forEach((query) => {
56
+ sentQueries.add(query.queryHash)
57
+ })
58
+ dehydratedRouter.dehydratedQueryClient = dehydratedQueryClient
59
+ }
60
+
61
+ return dehydratedRouter
62
+ }
63
+
64
+ const ogClientOptions = queryClient.getDefaultOptions()
65
+ queryClient.setDefaultOptions({
66
+ ...ogClientOptions,
67
+ dehydrate: {
68
+ shouldDehydrateQuery: () => true,
69
+ ...ogClientOptions.dehydrate,
70
+ },
71
+ })
72
+
73
+ queryClient.getQueryCache().subscribe((event) => {
74
+ // before rendering starts, we do not stream individual queries
75
+ // instead we dehydrate the entire query client in router's dehydrate()
76
+ // if attachRouterServerSsrUtils() has not been called yet, `router.serverSsr` will be undefined and we also do not stream
77
+ if (!router.serverSsr?.isDehydrated()) {
78
+ return
79
+ }
80
+ if (sentQueries.has(event.query.queryHash)) {
81
+ return
82
+ }
83
+ if (queryStream.isClosed()) {
84
+ console.warn(
85
+ `tried to stream query ${event.query.queryHash} after stream was already closed`,
86
+ )
87
+ return
88
+ }
89
+ // promise not yet set on the query, so we cannot stream it yet
90
+ if (!event.query.promise) {
91
+ return
92
+ }
93
+ sentQueries.add(event.query.queryHash)
94
+ queryStream.enqueue(
95
+ queryDehydrate(queryClient, {
96
+ shouldDehydrateQuery: (query) => {
97
+ if (query.queryHash === event.query.queryHash) {
98
+ return (
99
+ ogClientOptions.dehydrate?.shouldDehydrateQuery?.(query) ?? true
100
+ )
101
+ }
102
+ return false
103
+ },
104
+ }),
105
+ )
106
+ })
107
+ // on the client
108
+ } else {
109
+ router.options.hydrate = async (dehydrated: DehydratedRouterQueryState) => {
110
+ await ogHydrate?.(dehydrated)
111
+ // hydrate the query client with the dehydrated data (if it was dehydrated on the server)
112
+ if (dehydrated.dehydratedQueryClient) {
113
+ queryHydrate(queryClient, dehydrated.dehydratedQueryClient)
114
+ }
115
+
116
+ // read the query stream and hydrate the queries as they come in
117
+ const reader = dehydrated.queryStream.getReader()
118
+ reader
119
+ .read()
120
+ .then(async function handle({ done, value }) {
121
+ queryHydrate(queryClient, value)
122
+ if (done) {
123
+ return
124
+ }
125
+ const result = await reader.read()
126
+ return handle(result)
127
+ })
128
+ .catch((err) => {
129
+ console.error('Error reading query stream:', err)
130
+ })
131
+ }
132
+ if (handleRedirects) {
133
+ const ogMutationCacheConfig = queryClient.getMutationCache().config
134
+ queryClient.getMutationCache().config = {
135
+ ...ogMutationCacheConfig,
136
+ onError: (error, _variables, _context, _mutation) => {
137
+ if (isRedirect(error)) {
138
+ error.options._fromLocation = router.state.location
139
+ return router.navigate(router.resolveRedirect(error).options)
140
+ }
141
+
142
+ return ogMutationCacheConfig.onError?.(
143
+ error,
144
+ _variables,
145
+ _context,
146
+ _mutation,
147
+ )
148
+ },
149
+ }
150
+
151
+ const ogQueryCacheConfig = queryClient.getQueryCache().config
152
+ queryClient.getQueryCache().config = {
153
+ ...ogQueryCacheConfig,
154
+ onError: (error, _query) => {
155
+ if (isRedirect(error)) {
156
+ error.options._fromLocation = router.state.location
157
+ return router.navigate(router.resolveRedirect(error).options)
158
+ }
159
+
160
+ return ogQueryCacheConfig.onError?.(error, _query)
161
+ },
162
+ }
163
+ }
164
+ }
165
+ }
166
+
167
+ type PushableStream = {
168
+ stream: ReadableStream
169
+ enqueue: (chunk: unknown) => void
170
+ close: () => void
171
+ isClosed: () => boolean
172
+ error: (err: unknown) => void
173
+ }
174
+
175
+ function createPushableStream(): PushableStream {
176
+ let controllerRef: ReadableStreamDefaultController
177
+ const stream = new ReadableStream({
178
+ start(controller) {
179
+ controllerRef = controller
180
+ },
181
+ })
182
+ let _isClosed = false
183
+
184
+ return {
185
+ stream,
186
+ enqueue: (chunk) => controllerRef.enqueue(chunk),
187
+ close: () => {
188
+ controllerRef.close()
189
+ _isClosed = true
190
+ },
191
+ isClosed: () => _isClosed,
192
+ error: (err: unknown) => controllerRef.error(err),
193
+ }
194
+ }