@sidekickdb/react 0.0.0-stage → 2.0.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.
- package/.tshy/build.json +8 -0
- package/.tshy/commonjs.json +16 -0
- package/.tshy/esm.json +15 -0
- package/LICENSE.md +202 -0
- package/NOTICE +27 -0
- package/README.md +44 -2
- package/__example__/standalone.esm.html +32 -0
- package/__example__/standalone.umd.html +27 -0
- package/dist/commonjs/Cursors.d.ts +19 -0
- package/dist/commonjs/Cursors.d.ts.map +1 -0
- package/dist/commonjs/Cursors.js +107 -0
- package/dist/commonjs/Cursors.js.map +1 -0
- package/dist/commonjs/InstantReactWebDatabase.d.ts +7 -0
- package/dist/commonjs/InstantReactWebDatabase.d.ts.map +1 -0
- package/dist/commonjs/InstantReactWebDatabase.js +9 -0
- package/dist/commonjs/InstantReactWebDatabase.js.map +1 -0
- package/dist/commonjs/__types__/typeUtils.d.ts +20 -0
- package/dist/commonjs/__types__/typeUtils.d.ts.map +1 -0
- package/dist/commonjs/__types__/typeUtils.js +5 -0
- package/dist/commonjs/__types__/typeUtils.js.map +1 -0
- package/dist/commonjs/__types__/typesTests.d.ts +2 -0
- package/dist/commonjs/__types__/typesTests.d.ts.map +1 -0
- package/dist/commonjs/__types__/typesTests.js +57 -0
- package/dist/commonjs/__types__/typesTests.js.map +1 -0
- package/dist/commonjs/index.d.ts +7 -0
- package/dist/commonjs/index.d.ts.map +1 -0
- package/dist/commonjs/index.js +30 -0
- package/dist/commonjs/index.js.map +1 -0
- package/dist/commonjs/init.d.ts +41 -0
- package/dist/commonjs/init.d.ts.map +1 -0
- package/dist/commonjs/init.js +57 -0
- package/dist/commonjs/init.js.map +1 -0
- package/dist/commonjs/next-ssr/HydrationStreamProvider.d.ts +66 -0
- package/dist/commonjs/next-ssr/HydrationStreamProvider.d.ts.map +1 -0
- package/dist/commonjs/next-ssr/HydrationStreamProvider.js +134 -0
- package/dist/commonjs/next-ssr/HydrationStreamProvider.js.map +1 -0
- package/dist/commonjs/next-ssr/InstantNextDatabase.d.ts +12 -0
- package/dist/commonjs/next-ssr/InstantNextDatabase.d.ts.map +1 -0
- package/dist/commonjs/next-ssr/InstantNextDatabase.js +39 -0
- package/dist/commonjs/next-ssr/InstantNextDatabase.js.map +1 -0
- package/dist/commonjs/next-ssr/InstantSuspenseProvider.d.ts +25 -0
- package/dist/commonjs/next-ssr/InstantSuspenseProvider.d.ts.map +1 -0
- package/dist/commonjs/next-ssr/InstantSuspenseProvider.js +168 -0
- package/dist/commonjs/next-ssr/InstantSuspenseProvider.js.map +1 -0
- package/dist/commonjs/next-ssr/getUserFromInstantCookie.d.ts +10 -0
- package/dist/commonjs/next-ssr/getUserFromInstantCookie.d.ts.map +1 -0
- package/dist/commonjs/next-ssr/getUserFromInstantCookie.js +22 -0
- package/dist/commonjs/next-ssr/getUserFromInstantCookie.js.map +1 -0
- package/dist/commonjs/next-ssr/htmlescape.d.ts +3 -0
- package/dist/commonjs/next-ssr/htmlescape.d.ts.map +1 -0
- package/dist/commonjs/next-ssr/htmlescape.js +25 -0
- package/dist/commonjs/next-ssr/htmlescape.js.map +1 -0
- package/dist/commonjs/next-ssr/index.d.ts +30 -0
- package/dist/commonjs/next-ssr/index.d.ts.map +1 -0
- package/dist/commonjs/next-ssr/index.js +47 -0
- package/dist/commonjs/next-ssr/index.js.map +1 -0
- package/dist/commonjs/package.json +3 -0
- package/dist/commonjs/version.d.ts +3 -0
- package/dist/commonjs/version.d.ts.map +1 -0
- package/dist/commonjs/version.js +5 -0
- package/dist/commonjs/version.js.map +1 -0
- package/dist/esm/Cursors.d.ts +19 -0
- package/dist/esm/Cursors.d.ts.map +1 -0
- package/dist/esm/Cursors.js +104 -0
- package/dist/esm/Cursors.js.map +1 -0
- package/dist/esm/InstantReactWebDatabase.d.ts +7 -0
- package/dist/esm/InstantReactWebDatabase.d.ts.map +1 -0
- package/dist/esm/InstantReactWebDatabase.js +6 -0
- package/dist/esm/InstantReactWebDatabase.js.map +1 -0
- package/dist/esm/__types__/typeUtils.d.ts +20 -0
- package/dist/esm/__types__/typeUtils.d.ts.map +1 -0
- package/dist/esm/__types__/typeUtils.js +4 -0
- package/dist/esm/__types__/typeUtils.js.map +1 -0
- package/dist/esm/__types__/typesTests.d.ts +2 -0
- package/dist/esm/__types__/typesTests.d.ts.map +1 -0
- package/dist/esm/__types__/typesTests.js +55 -0
- package/dist/esm/__types__/typesTests.js.map +1 -0
- package/dist/esm/index.d.ts +7 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +23 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/init.d.ts +41 -0
- package/dist/esm/init.d.ts.map +1 -0
- package/dist/esm/init.js +50 -0
- package/dist/esm/init.js.map +1 -0
- package/dist/esm/next-ssr/HydrationStreamProvider.d.ts +66 -0
- package/dist/esm/next-ssr/HydrationStreamProvider.d.ts.map +1 -0
- package/dist/esm/next-ssr/HydrationStreamProvider.js +97 -0
- package/dist/esm/next-ssr/HydrationStreamProvider.js.map +1 -0
- package/dist/esm/next-ssr/InstantNextDatabase.d.ts +12 -0
- package/dist/esm/next-ssr/InstantNextDatabase.d.ts.map +1 -0
- package/dist/esm/next-ssr/InstantNextDatabase.js +32 -0
- package/dist/esm/next-ssr/InstantNextDatabase.js.map +1 -0
- package/dist/esm/next-ssr/InstantSuspenseProvider.d.ts +25 -0
- package/dist/esm/next-ssr/InstantSuspenseProvider.d.ts.map +1 -0
- package/dist/esm/next-ssr/InstantSuspenseProvider.js +163 -0
- package/dist/esm/next-ssr/InstantSuspenseProvider.js.map +1 -0
- package/dist/esm/next-ssr/getUserFromInstantCookie.d.ts +10 -0
- package/dist/esm/next-ssr/getUserFromInstantCookie.d.ts.map +1 -0
- package/dist/esm/next-ssr/getUserFromInstantCookie.js +17 -0
- package/dist/esm/next-ssr/getUserFromInstantCookie.js.map +1 -0
- package/dist/esm/next-ssr/htmlescape.d.ts +3 -0
- package/dist/esm/next-ssr/htmlescape.d.ts.map +1 -0
- package/dist/esm/next-ssr/htmlescape.js +21 -0
- package/dist/esm/next-ssr/htmlescape.js.map +1 -0
- package/dist/esm/next-ssr/index.d.ts +30 -0
- package/dist/esm/next-ssr/index.d.ts.map +1 -0
- package/dist/esm/next-ssr/index.js +35 -0
- package/dist/esm/next-ssr/index.js.map +1 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/version.d.ts +3 -0
- package/dist/esm/version.d.ts.map +1 -0
- package/dist/esm/version.js +3 -0
- package/dist/esm/version.js.map +1 -0
- package/dist/standalone/index.js +9664 -0
- package/dist/standalone/index.umd.cjs +40 -0
- package/package.json +86 -3
- package/src/Cursors.tsx +208 -0
- package/src/InstantReactWebDatabase.ts +14 -0
- package/src/__types__/typeUtils.ts +39 -0
- package/src/__types__/typesTests.ts +90 -0
- package/src/index.ts +227 -0
- package/src/init.ts +67 -0
- package/src/next-ssr/HydrationStreamProvider.tsx +200 -0
- package/src/next-ssr/InstantNextDatabase.tsx +56 -0
- package/src/next-ssr/InstantSuspenseProvider.tsx +290 -0
- package/src/next-ssr/getUserFromInstantCookie.ts +23 -0
- package/src/next-ssr/htmlescape.ts +24 -0
- package/src/next-ssr/index.tsx +54 -0
- package/src/version.ts +3 -0
- package/tsconfig.dev.json +14 -0
- package/tsconfig.json +13 -0
- package/tsconfig.test.json +5 -0
- package/vite.config.ts +35 -0
package/src/init.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
InstantConfig,
|
|
3
|
+
InstantSchemaDef,
|
|
4
|
+
InstantUnknownSchema,
|
|
5
|
+
} from '@sidekickdb/core';
|
|
6
|
+
|
|
7
|
+
import InstantReactWebDatabase from './InstantReactWebDatabase.ts';
|
|
8
|
+
import version from './version.ts';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
*
|
|
12
|
+
* The first step: init your application!
|
|
13
|
+
*
|
|
14
|
+
* Find your `appId` in your SidekickDB dashboard.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* import { init } from "@sidekickdb/react"
|
|
18
|
+
*
|
|
19
|
+
* const db = init({ appId: "my-app-id", apiURI: "https://sidekick.example.com" })
|
|
20
|
+
*
|
|
21
|
+
* // You can also provide a schema for type safety and editor autocomplete!
|
|
22
|
+
*
|
|
23
|
+
* import { init } from "@sidekickdb/react"
|
|
24
|
+
* import schema from ""../instant.schema.ts";
|
|
25
|
+
*
|
|
26
|
+
* const db = init({ appId: "my-app-id", apiURI: "https://sidekick.example.com", schema })
|
|
27
|
+
*
|
|
28
|
+
* // To learn more: https://sidekickdb.co/docs/modeling-data
|
|
29
|
+
*/
|
|
30
|
+
export function init<
|
|
31
|
+
Schema extends InstantSchemaDef<any, any, any> = InstantUnknownSchema,
|
|
32
|
+
UseDates extends boolean = false,
|
|
33
|
+
>(
|
|
34
|
+
// Allows config with missing `useDateObjects`, but keeps `UseDates`
|
|
35
|
+
// as a non-nullable in the InstantConfig type.
|
|
36
|
+
config: Omit<InstantConfig<Schema, UseDates>, 'useDateObjects'> & {
|
|
37
|
+
useDateObjects?: UseDates;
|
|
38
|
+
},
|
|
39
|
+
): InstantReactWebDatabase<Schema, UseDates, InstantConfig<Schema, UseDates>> {
|
|
40
|
+
const configStrict = {
|
|
41
|
+
...config,
|
|
42
|
+
useDateObjects: (config.useDateObjects ?? false) as UseDates,
|
|
43
|
+
};
|
|
44
|
+
return new InstantReactWebDatabase<
|
|
45
|
+
Schema,
|
|
46
|
+
UseDates,
|
|
47
|
+
InstantConfig<Schema, UseDates>
|
|
48
|
+
>(configStrict, {
|
|
49
|
+
'@instantdb/react': version,
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* @deprecated
|
|
55
|
+
* `init_experimental` is deprecated. You can replace it with `init`.
|
|
56
|
+
*
|
|
57
|
+
* @example
|
|
58
|
+
*
|
|
59
|
+
* // Before
|
|
60
|
+
* import { init_experimental } from "@sidekickdb/react"
|
|
61
|
+
* const db = init_experimental({ ... });
|
|
62
|
+
*
|
|
63
|
+
* // After
|
|
64
|
+
* import { init } from "@sidekickdb/react"
|
|
65
|
+
* const db = init({ ... });
|
|
66
|
+
*/
|
|
67
|
+
export const init_experimental = init;
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
|
|
3
|
+
// This allows us to send serialized json from the server to the client using 'useServerInsertedHTML'
|
|
4
|
+
// We are allowed to send whatever json we want, however it must be triggered at the same time as the client is recieving new html to display
|
|
5
|
+
// after a suspsense boundary resolves
|
|
6
|
+
// We do this to send a list of triples and attrs for each query that the server made so they can be pre-filled on the client render.
|
|
7
|
+
// useServerInsertedHTML is called whenever a suspense boundary resolves, resulting in new html being streamed down to the client.
|
|
8
|
+
|
|
9
|
+
export const isServer = typeof window === 'undefined' || 'Deno' in globalThis;
|
|
10
|
+
|
|
11
|
+
import { useServerInsertedHTML } from 'next/navigation.js';
|
|
12
|
+
|
|
13
|
+
import * as React from 'react';
|
|
14
|
+
import { htmlEscapeJsonString } from './htmlescape.js';
|
|
15
|
+
|
|
16
|
+
const serializedSymbol = Symbol('serialized');
|
|
17
|
+
|
|
18
|
+
interface DataTransformer {
|
|
19
|
+
serialize: (object: any) => any;
|
|
20
|
+
deserialize: (object: any) => any;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
type Serialized<TData> = unknown & {
|
|
24
|
+
[serializedSymbol]: TData;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
interface TypedDataTransformer<TData> {
|
|
28
|
+
serialize: (obj: TData) => Serialized<TData>;
|
|
29
|
+
deserialize: (obj: Serialized<TData>) => TData;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface HydrationStreamContext<TShape> {
|
|
33
|
+
id: string;
|
|
34
|
+
stream: {
|
|
35
|
+
/**
|
|
36
|
+
* **Server method**
|
|
37
|
+
* Push a new entry to the stream
|
|
38
|
+
* Will be ignored on the client
|
|
39
|
+
*/
|
|
40
|
+
push: (...shape: Array<TShape>) => void;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface HydrationStreamProviderProps<TShape> {
|
|
45
|
+
children: React.ReactNode;
|
|
46
|
+
/**
|
|
47
|
+
* Optional transformer to serialize/deserialize the data
|
|
48
|
+
* Example devalue, superjson et al
|
|
49
|
+
*/
|
|
50
|
+
transformer?: DataTransformer;
|
|
51
|
+
/**
|
|
52
|
+
* **Client method**
|
|
53
|
+
* Called in the browser when new entries are received
|
|
54
|
+
*/
|
|
55
|
+
onEntries: (entries: Array<TShape>) => void;
|
|
56
|
+
/**
|
|
57
|
+
* **Server method**
|
|
58
|
+
* onFlush is called on the server when the cache is flushed
|
|
59
|
+
*/
|
|
60
|
+
onFlush?: () => Array<TShape>;
|
|
61
|
+
/**
|
|
62
|
+
* A nonce that'll allow the inline script to be executed when Content Security Policy is enforced
|
|
63
|
+
*/
|
|
64
|
+
nonce?: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function createHydrationStreamProvider<TShape>() {
|
|
68
|
+
const context = React.createContext<HydrationStreamContext<TShape>>(
|
|
69
|
+
null as any,
|
|
70
|
+
);
|
|
71
|
+
/**
|
|
72
|
+
|
|
73
|
+
* 1. (Happens on server): `useServerInsertedHTML()` is called **on the server** whenever a `Suspense`-boundary completes
|
|
74
|
+
* - This means that we might have some new entries in the cache that needs to be flushed
|
|
75
|
+
* - We pass these to the client by inserting a `<script>`-tag where we do `window[id].push(serializedVersionOfCache)`
|
|
76
|
+
* 2. (Happens in browser) In `useEffect()`:
|
|
77
|
+
* - We check if `window[id]` is set to an array and call `push()` on all the entries which will call `onEntries()` with the new entries
|
|
78
|
+
* - We replace `window[id]` with a `push()`-method that will be called whenever new entries are received
|
|
79
|
+
**/
|
|
80
|
+
function UseClientHydrationStreamProvider(props: {
|
|
81
|
+
children: React.ReactNode;
|
|
82
|
+
/**
|
|
83
|
+
* Optional transformer to serialize/deserialize the data
|
|
84
|
+
* Example devalue, superjson et al
|
|
85
|
+
*/
|
|
86
|
+
transformer?: DataTransformer;
|
|
87
|
+
/**
|
|
88
|
+
* **Client method**
|
|
89
|
+
* Called in the browser when new entries are received
|
|
90
|
+
*/
|
|
91
|
+
onEntries: (entries: Array<TShape>) => void;
|
|
92
|
+
/**
|
|
93
|
+
* **Server method**
|
|
94
|
+
* onFlush is called on the server when the cache is flushed
|
|
95
|
+
*/
|
|
96
|
+
onFlush?: () => Array<TShape>;
|
|
97
|
+
/**
|
|
98
|
+
* A nonce that'll allow the inline script to be executed when Content Security Policy is enforced
|
|
99
|
+
*/
|
|
100
|
+
nonce?: string;
|
|
101
|
+
}) {
|
|
102
|
+
// unique id for the cache provider
|
|
103
|
+
const id = `__RQ${React.useId()}`;
|
|
104
|
+
const idJSON = htmlEscapeJsonString(JSON.stringify(id));
|
|
105
|
+
|
|
106
|
+
const [transformer] = React.useState(
|
|
107
|
+
() =>
|
|
108
|
+
(props.transformer ?? {
|
|
109
|
+
// noop
|
|
110
|
+
serialize: (obj: any) => obj,
|
|
111
|
+
deserialize: (obj: any) => obj,
|
|
112
|
+
}) as unknown as TypedDataTransformer<TShape>,
|
|
113
|
+
);
|
|
114
|
+
|
|
115
|
+
// <server stuff>
|
|
116
|
+
const [stream] = React.useState<Array<TShape>>(() => {
|
|
117
|
+
if (!isServer) {
|
|
118
|
+
return {
|
|
119
|
+
push() {
|
|
120
|
+
// no-op on the client
|
|
121
|
+
},
|
|
122
|
+
} as unknown as Array<TShape>;
|
|
123
|
+
}
|
|
124
|
+
return [];
|
|
125
|
+
});
|
|
126
|
+
const count = React.useRef(0);
|
|
127
|
+
useServerInsertedHTML(() => {
|
|
128
|
+
// This only happens on the server
|
|
129
|
+
stream.push(...(props.onFlush?.() ?? []));
|
|
130
|
+
|
|
131
|
+
if (!stream.length) {
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const serializedCacheArgs = stream
|
|
136
|
+
.map((entry) => transformer.serialize(entry))
|
|
137
|
+
.map((entry) => JSON.stringify(entry))
|
|
138
|
+
.join(',');
|
|
139
|
+
|
|
140
|
+
// Flush stream
|
|
141
|
+
// eslint-disable-next-line react-hooks/immutability
|
|
142
|
+
stream.length = 0;
|
|
143
|
+
|
|
144
|
+
const html: Array<string> = [
|
|
145
|
+
`window[${idJSON}] = window[${idJSON}] || [];`,
|
|
146
|
+
`window[${idJSON}].push(${htmlEscapeJsonString(serializedCacheArgs)});`,
|
|
147
|
+
];
|
|
148
|
+
return (
|
|
149
|
+
<script
|
|
150
|
+
key={count.current++}
|
|
151
|
+
nonce={props.nonce}
|
|
152
|
+
dangerouslySetInnerHTML={{
|
|
153
|
+
__html: html.join(''),
|
|
154
|
+
}}
|
|
155
|
+
/>
|
|
156
|
+
);
|
|
157
|
+
});
|
|
158
|
+
// </server stuff>
|
|
159
|
+
|
|
160
|
+
// <client stuff>
|
|
161
|
+
// Setup and run the onEntries handler on the client only, but do it during
|
|
162
|
+
// the initial render so children have access to the data immediately
|
|
163
|
+
// This is important to avoid the client suspending during the initial render
|
|
164
|
+
// if the data has not yet been hydrated.
|
|
165
|
+
if (!isServer) {
|
|
166
|
+
const win = window as any;
|
|
167
|
+
if (!win[id]?.initialized) {
|
|
168
|
+
// Client: consume cache:
|
|
169
|
+
const onEntries = (...serializedEntries: Array<Serialized<TShape>>) => {
|
|
170
|
+
const entries = serializedEntries.map((serialized) =>
|
|
171
|
+
transformer.deserialize(serialized),
|
|
172
|
+
);
|
|
173
|
+
props.onEntries(entries);
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
const winStream: Array<Serialized<TShape>> = win[id] ?? [];
|
|
177
|
+
|
|
178
|
+
onEntries(...winStream);
|
|
179
|
+
|
|
180
|
+
// eslint-disable-next-line react-hooks/immutability
|
|
181
|
+
win[id] = {
|
|
182
|
+
initialized: true,
|
|
183
|
+
push: onEntries,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
// </client stuff>
|
|
188
|
+
|
|
189
|
+
return (
|
|
190
|
+
<context.Provider value={{ stream, id }}>
|
|
191
|
+
{props.children}
|
|
192
|
+
</context.Provider>
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return {
|
|
197
|
+
Provider: UseClientHydrationStreamProvider,
|
|
198
|
+
context,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AuthState,
|
|
3
|
+
InstantSchemaDef,
|
|
4
|
+
InstaQLResponse,
|
|
5
|
+
PageInfoResponse,
|
|
6
|
+
RuleParams,
|
|
7
|
+
ValidQuery,
|
|
8
|
+
} from '@sidekickdb/core';
|
|
9
|
+
import InstantReactWebDatabase from '../InstantReactWebDatabase.ts';
|
|
10
|
+
import { useContext } from 'react';
|
|
11
|
+
import { SuspsenseQueryContext } from './InstantSuspenseProvider.tsx';
|
|
12
|
+
|
|
13
|
+
export class InstantNextDatabase<
|
|
14
|
+
Schema extends InstantSchemaDef<any, any, any>,
|
|
15
|
+
UseDates extends boolean,
|
|
16
|
+
> extends InstantReactWebDatabase<Schema, UseDates> {
|
|
17
|
+
public useSuspenseQuery = <Q extends ValidQuery<Q, Schema>>(
|
|
18
|
+
q: Q,
|
|
19
|
+
opts?: {
|
|
20
|
+
ruleParams: RuleParams;
|
|
21
|
+
},
|
|
22
|
+
): {
|
|
23
|
+
data: InstaQLResponse<Schema, Q, NonNullable<UseDates>>;
|
|
24
|
+
pageInfo?: PageInfoResponse<Q>;
|
|
25
|
+
} => {
|
|
26
|
+
const ctx = useContext(SuspsenseQueryContext);
|
|
27
|
+
if (!ctx) {
|
|
28
|
+
throw new Error(
|
|
29
|
+
'useSuspenseQuery must be used within a SuspenseQueryProvider',
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
return ctx.useSuspenseQuery(q, opts) as any;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
useAuth = (): AuthState => {
|
|
36
|
+
const ctx = useContext(SuspsenseQueryContext);
|
|
37
|
+
const realAuthResult = this._useAuth();
|
|
38
|
+
if (!ctx) {
|
|
39
|
+
return realAuthResult;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const { ssrUser } = ctx;
|
|
43
|
+
if (ssrUser === undefined) {
|
|
44
|
+
return realAuthResult;
|
|
45
|
+
}
|
|
46
|
+
if (realAuthResult.isLoading) {
|
|
47
|
+
return {
|
|
48
|
+
error: undefined,
|
|
49
|
+
isLoading: false,
|
|
50
|
+
user: ssrUser ?? undefined, // null -> undefined for the response
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return realAuthResult;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
// InstantSuspenseProvider can only be used in a client context so this prevents errors from trying to use it in a server component.
|
|
3
|
+
|
|
4
|
+
import {
|
|
5
|
+
FrameworkClient,
|
|
6
|
+
InstantConfig,
|
|
7
|
+
InstantSchemaDef,
|
|
8
|
+
InstaQLResponse,
|
|
9
|
+
PageInfoResponse,
|
|
10
|
+
RuleParams,
|
|
11
|
+
User,
|
|
12
|
+
ValidQuery,
|
|
13
|
+
} from '@sidekickdb/core';
|
|
14
|
+
import InstantReactWebDatabase from '../InstantReactWebDatabase.ts';
|
|
15
|
+
import {
|
|
16
|
+
createHydrationStreamProvider,
|
|
17
|
+
isServer,
|
|
18
|
+
} from './HydrationStreamProvider.tsx';
|
|
19
|
+
import {
|
|
20
|
+
createContext,
|
|
21
|
+
useCallback,
|
|
22
|
+
useContext,
|
|
23
|
+
useMemo,
|
|
24
|
+
useRef,
|
|
25
|
+
useState,
|
|
26
|
+
useEffect,
|
|
27
|
+
} from 'react';
|
|
28
|
+
import {
|
|
29
|
+
InstantReactAbstractDatabase,
|
|
30
|
+
useQueryInternal,
|
|
31
|
+
} from '@sidekickdb/react-common';
|
|
32
|
+
|
|
33
|
+
type InstantSuspenseProviderProps<
|
|
34
|
+
Schema extends InstantSchemaDef<any, any, any>,
|
|
35
|
+
> = {
|
|
36
|
+
nonce?: string;
|
|
37
|
+
children: React.ReactNode;
|
|
38
|
+
db: InstantReactWebDatabase<Schema, any>;
|
|
39
|
+
user?: User | null;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const stream = createHydrationStreamProvider<any>();
|
|
43
|
+
|
|
44
|
+
type SuspenseQueryContextValue = {
|
|
45
|
+
useSuspenseQuery: (query: any, opts?: SuspenseQueryOpts) => any;
|
|
46
|
+
ssrUser: User | null | undefined;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export const SuspsenseQueryContext =
|
|
50
|
+
createContext<SuspenseQueryContextValue | null>(null);
|
|
51
|
+
|
|
52
|
+
// Creates a typed useSuspense hook
|
|
53
|
+
export const createUseSuspenseQuery = <
|
|
54
|
+
Schema extends InstantSchemaDef<any, any, any>,
|
|
55
|
+
UseDates extends boolean,
|
|
56
|
+
>(
|
|
57
|
+
_db: InstantReactWebDatabase<Schema, UseDates>,
|
|
58
|
+
): (<Q extends ValidQuery<Q, Schema>>(
|
|
59
|
+
q: Q,
|
|
60
|
+
opts?: {
|
|
61
|
+
ruleParams: RuleParams;
|
|
62
|
+
},
|
|
63
|
+
) => {
|
|
64
|
+
data: InstaQLResponse<Schema, Q, NonNullable<UseDates>>;
|
|
65
|
+
pageInfo?: PageInfoResponse<Q>;
|
|
66
|
+
}) => {
|
|
67
|
+
return <Q extends ValidQuery<Q, Schema>>(q: any, opts: any) => {
|
|
68
|
+
const ctx = useContext(SuspsenseQueryContext);
|
|
69
|
+
if (!ctx) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
'useSuspenseQuery must be used within a SuspenseQueryProvider',
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
return ctx.useSuspenseQuery(q, opts) as any;
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
type SuspenseQueryOpts = {
|
|
79
|
+
ruleParams: RuleParams;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
function makeUseSuspenseQueryServer(client: FrameworkClient) {
|
|
83
|
+
return function useSuspenseQueryServer(query: any, opts: SuspenseQueryOpts) {
|
|
84
|
+
let entry = client.getExistingResultForQuery(query, opts);
|
|
85
|
+
|
|
86
|
+
if (!entry) {
|
|
87
|
+
entry = client.query(query, opts);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (entry.status === 'pending') {
|
|
91
|
+
throw entry.promise;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (entry.status === 'error') {
|
|
95
|
+
throw entry.error;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (entry.status === 'success') {
|
|
99
|
+
switch (entry.type) {
|
|
100
|
+
case 'session': {
|
|
101
|
+
return entry.data;
|
|
102
|
+
}
|
|
103
|
+
case 'http': {
|
|
104
|
+
const data = entry.data;
|
|
105
|
+
const result = client.completeIsomorphic(
|
|
106
|
+
query,
|
|
107
|
+
data.triples,
|
|
108
|
+
data.attrs,
|
|
109
|
+
data.pageInfo,
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
return result;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function makeUseSuspenseQueryClient(
|
|
120
|
+
db: InstantReactAbstractDatabase<any, any>,
|
|
121
|
+
client: FrameworkClient,
|
|
122
|
+
) {
|
|
123
|
+
function getEntry(query: any, opts: SuspenseQueryOpts, allowFetch: boolean) {
|
|
124
|
+
const entry = client.getExistingResultForQuery(query, opts);
|
|
125
|
+
|
|
126
|
+
if (entry?.status === 'pending') {
|
|
127
|
+
throw entry.promise;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (entry?.status === 'error') {
|
|
131
|
+
throw entry.error;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (entry?.status === 'success') {
|
|
135
|
+
switch (entry.type) {
|
|
136
|
+
case 'session': {
|
|
137
|
+
return entry.data;
|
|
138
|
+
}
|
|
139
|
+
case 'http': {
|
|
140
|
+
const data = entry.data;
|
|
141
|
+
const result = client.completeIsomorphic(
|
|
142
|
+
query,
|
|
143
|
+
data.triples,
|
|
144
|
+
data.attrs,
|
|
145
|
+
data.pageInfo,
|
|
146
|
+
);
|
|
147
|
+
|
|
148
|
+
return result;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (allowFetch) {
|
|
154
|
+
const promise = client.queryClient(query, opts);
|
|
155
|
+
throw promise;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return function useSuspenseQueryClient(query: any, opts: SuspenseQueryOpts) {
|
|
160
|
+
const useQueryResult = useQueryInternal(
|
|
161
|
+
db.core,
|
|
162
|
+
query,
|
|
163
|
+
opts,
|
|
164
|
+
// Returns the server result for useSyncExternalStore
|
|
165
|
+
() => {
|
|
166
|
+
try {
|
|
167
|
+
const res = getEntry(query, opts, false);
|
|
168
|
+
return res;
|
|
169
|
+
} catch (throwable) {
|
|
170
|
+
return { error: throwable };
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
);
|
|
174
|
+
|
|
175
|
+
const hasData = !!useQueryResult.state.data;
|
|
176
|
+
const queryHash = useQueryResult.queryHash;
|
|
177
|
+
|
|
178
|
+
useEffect(() => {
|
|
179
|
+
if (hasData) {
|
|
180
|
+
// We have a newer result, so remove the cached SSR or suspended
|
|
181
|
+
// result from the framework client cache
|
|
182
|
+
client.removeCachedQueryResult(queryHash);
|
|
183
|
+
}
|
|
184
|
+
}, [hasData, queryHash]);
|
|
185
|
+
|
|
186
|
+
if (useQueryResult.state.data) {
|
|
187
|
+
return {
|
|
188
|
+
data: useQueryResult.state.data,
|
|
189
|
+
pageInfo: useQueryResult.state.pageInfo,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (useQueryResult.state.error) {
|
|
194
|
+
throw useQueryResult.state.error;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return getEntry(query, opts, true);
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function createFrameworkClient(
|
|
202
|
+
db: InstantReactAbstractDatabase<any, any>,
|
|
203
|
+
user: User | null | undefined,
|
|
204
|
+
) {
|
|
205
|
+
if (isServer) {
|
|
206
|
+
if (user && !user.refresh_token) {
|
|
207
|
+
throw new Error(
|
|
208
|
+
'User must have a refresh_token field. Recieved: ' +
|
|
209
|
+
JSON.stringify(user, null, 2),
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
return new FrameworkClient({
|
|
213
|
+
token: user?.refresh_token,
|
|
214
|
+
db: db.core,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// On the client, make sure we only have a single framework
|
|
219
|
+
// in case our suspense provider gets unmounted
|
|
220
|
+
const existing = db.core._reactor._frameworkClient;
|
|
221
|
+
if (existing) {
|
|
222
|
+
return existing;
|
|
223
|
+
}
|
|
224
|
+
const client = new FrameworkClient({ db: db.core });
|
|
225
|
+
db.core._reactor.setFrameworkClient(client);
|
|
226
|
+
return client;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
export const InstantSuspenseProvider = (
|
|
230
|
+
props: InstantSuspenseProviderProps<any>,
|
|
231
|
+
) => {
|
|
232
|
+
if (!props.db) {
|
|
233
|
+
throw new Error('Must provide db to InstantSuspenseProvider');
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const db = props.db;
|
|
237
|
+
|
|
238
|
+
const [trackedKeys] = useState(() => new Set<string>());
|
|
239
|
+
|
|
240
|
+
const clientRef = useRef<FrameworkClient>(
|
|
241
|
+
createFrameworkClient(props.db, props.user),
|
|
242
|
+
);
|
|
243
|
+
|
|
244
|
+
if (isServer) {
|
|
245
|
+
clientRef.current.subscribe((result) => {
|
|
246
|
+
const { queryHash } = result;
|
|
247
|
+
trackedKeys.add(queryHash);
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const useSuspenseQuery = useCallback(
|
|
252
|
+
isServer
|
|
253
|
+
? makeUseSuspenseQueryServer(clientRef.current)
|
|
254
|
+
: makeUseSuspenseQueryClient(db, clientRef.current),
|
|
255
|
+
[],
|
|
256
|
+
);
|
|
257
|
+
|
|
258
|
+
const contextValue = useMemo(() => {
|
|
259
|
+
return { useSuspenseQuery, ssrUser: props.user };
|
|
260
|
+
}, [useSuspenseQuery, props.user]);
|
|
261
|
+
|
|
262
|
+
return (
|
|
263
|
+
<SuspsenseQueryContext.Provider value={contextValue}>
|
|
264
|
+
<stream.Provider
|
|
265
|
+
nonce={props.nonce}
|
|
266
|
+
onFlush={() => {
|
|
267
|
+
const toSend: { queryKey: string; value: any }[] = [];
|
|
268
|
+
for (const [key, value] of clientRef.current!.resultMap.entries()) {
|
|
269
|
+
if (trackedKeys.has(key) && value.status === 'success') {
|
|
270
|
+
toSend.push({
|
|
271
|
+
queryKey: key,
|
|
272
|
+
value: value.data,
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
trackedKeys.clear();
|
|
278
|
+
return toSend;
|
|
279
|
+
}}
|
|
280
|
+
onEntries={(entries) => {
|
|
281
|
+
entries.forEach((entry) => {
|
|
282
|
+
clientRef.current!.addQueryResult(entry.queryKey, entry.value);
|
|
283
|
+
});
|
|
284
|
+
}}
|
|
285
|
+
>
|
|
286
|
+
{props.children}
|
|
287
|
+
</stream.Provider>
|
|
288
|
+
</SuspsenseQueryContext.Provider>
|
|
289
|
+
);
|
|
290
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { User } from '@sidekickdb/core';
|
|
2
|
+
import { cookies } from 'next/headers.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @deprecated Please use `getUnverifiedUserFromInstantCookie` instead
|
|
6
|
+
*/
|
|
7
|
+
export const getUserFromInstantCookie = async (
|
|
8
|
+
appId: string,
|
|
9
|
+
): Promise<User | null> => {
|
|
10
|
+
return getUnverifiedUserFromInstantCookie(appId);
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Parses a user object from current Next.JS request context's cookies.
|
|
15
|
+
*/
|
|
16
|
+
export const getUnverifiedUserFromInstantCookie = async (
|
|
17
|
+
appId: string,
|
|
18
|
+
): Promise<User | null> => {
|
|
19
|
+
const cookieStore = await cookies();
|
|
20
|
+
const userJSON = cookieStore.get('instant_user_' + appId);
|
|
21
|
+
const user = userJSON ? JSON.parse(decodeURIComponent(userJSON.value)) : null;
|
|
22
|
+
return user;
|
|
23
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// --------------------------------------------------------------------------------
|
|
2
|
+
//
|
|
3
|
+
// copied from
|
|
4
|
+
// https://github.com/vercel/next.js/blob/6bc07792a4462a4bf921a72ab30dc4ab2c4e1bda/packages/next/src/server/htmlescape.ts
|
|
5
|
+
// License: https://github.com/vercel/next.js/blob/6bc07792a4462a4bf921a72ab30dc4ab2c4e1bda/packages/next/license.md
|
|
6
|
+
//
|
|
7
|
+
// --------------------------------------------------------------------------------
|
|
8
|
+
|
|
9
|
+
// This utility is based on https://github.com/zertosh/htmlescape
|
|
10
|
+
// License: https://github.com/zertosh/htmlescape/blob/0527ca7156a524d256101bb310a9f970f63078ad/LICENSE
|
|
11
|
+
|
|
12
|
+
const ESCAPE_LOOKUP: Record<string, string> = {
|
|
13
|
+
'&': '\\u0026',
|
|
14
|
+
'>': '\\u003e',
|
|
15
|
+
'<': '\\u003c',
|
|
16
|
+
'\u2028': '\\u2028',
|
|
17
|
+
'\u2029': '\\u2029',
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export const ESCAPE_REGEX = /[&><\u2028\u2029]/g;
|
|
21
|
+
|
|
22
|
+
export function htmlEscapeJsonString(str: string): string {
|
|
23
|
+
return str.replace(ESCAPE_REGEX, (match) => ESCAPE_LOOKUP[match]!);
|
|
24
|
+
}
|