@sidekickdb/platform 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.
Files changed (197) hide show
  1. package/.tshy/build.json +8 -0
  2. package/.tshy/commonjs.json +16 -0
  3. package/.tshy/esm.json +15 -0
  4. package/.turbo/turbo-build.log +50 -0
  5. package/LICENSE.md +202 -0
  6. package/NOTICE +27 -0
  7. package/README.md +445 -2
  8. package/__tests__/src/apiURI.test.ts +58 -0
  9. package/__tests__/src/backupDownload.test.ts +427 -0
  10. package/__tests__/src/backups.test.ts +168 -0
  11. package/__tests__/src/clerk.test.ts +13 -0
  12. package/__tests__/src/consts.test.ts +11 -0
  13. package/__tests__/src/migrations.test.ts +885 -0
  14. package/__tests__/src/perms.test.ts +102 -0
  15. package/__tests__/src/rename.test.ts +126 -0
  16. package/__tests__/src/schema.push.e2e.test.ts +186 -0
  17. package/__tests__/src/schema.test.ts +644 -0
  18. package/__tests__/src/typescript-schema.test.ts +117 -0
  19. package/dist/commonjs/ProgressPromise.d.ts +18 -0
  20. package/dist/commonjs/ProgressPromise.d.ts.map +1 -0
  21. package/dist/commonjs/ProgressPromise.js +77 -0
  22. package/dist/commonjs/ProgressPromise.js.map +1 -0
  23. package/dist/commonjs/api.d.ts +480 -0
  24. package/dist/commonjs/api.d.ts.map +1 -0
  25. package/dist/commonjs/api.js +1132 -0
  26. package/dist/commonjs/api.js.map +1 -0
  27. package/dist/commonjs/backupDownload.d.ts +89 -0
  28. package/dist/commonjs/backupDownload.d.ts.map +1 -0
  29. package/dist/commonjs/backupDownload.js +357 -0
  30. package/dist/commonjs/backupDownload.js.map +1 -0
  31. package/dist/commonjs/backups.d.ts +146 -0
  32. package/dist/commonjs/backups.d.ts.map +1 -0
  33. package/dist/commonjs/backups.js +248 -0
  34. package/dist/commonjs/backups.js.map +1 -0
  35. package/dist/commonjs/clerk.d.ts +2 -0
  36. package/dist/commonjs/clerk.d.ts.map +1 -0
  37. package/dist/commonjs/clerk.js +29 -0
  38. package/dist/commonjs/clerk.js.map +1 -0
  39. package/dist/commonjs/consts.d.ts +11 -0
  40. package/dist/commonjs/consts.d.ts.map +1 -0
  41. package/dist/commonjs/consts.js +17 -0
  42. package/dist/commonjs/consts.js.map +1 -0
  43. package/dist/commonjs/crypto.d.ts +4 -0
  44. package/dist/commonjs/crypto.d.ts.map +1 -0
  45. package/dist/commonjs/crypto.js +26 -0
  46. package/dist/commonjs/crypto.js.map +1 -0
  47. package/dist/commonjs/index.d.ts +18 -0
  48. package/dist/commonjs/index.d.ts.map +1 -0
  49. package/dist/commonjs/index.js +61 -0
  50. package/dist/commonjs/index.js.map +1 -0
  51. package/dist/commonjs/migrationUtils.d.ts +4 -0
  52. package/dist/commonjs/migrationUtils.d.ts.map +1 -0
  53. package/dist/commonjs/migrationUtils.js +52 -0
  54. package/dist/commonjs/migrationUtils.js.map +1 -0
  55. package/dist/commonjs/migrations.d.ts +99 -0
  56. package/dist/commonjs/migrations.d.ts.map +1 -0
  57. package/dist/commonjs/migrations.js +597 -0
  58. package/dist/commonjs/migrations.js.map +1 -0
  59. package/dist/commonjs/oauth.d.ts +98 -0
  60. package/dist/commonjs/oauth.d.ts.map +1 -0
  61. package/dist/commonjs/oauth.js +277 -0
  62. package/dist/commonjs/oauth.js.map +1 -0
  63. package/dist/commonjs/oauthCommon.d.ts +12 -0
  64. package/dist/commonjs/oauthCommon.d.ts.map +1 -0
  65. package/dist/commonjs/oauthCommon.js +26 -0
  66. package/dist/commonjs/oauthCommon.js.map +1 -0
  67. package/dist/commonjs/package.json +3 -0
  68. package/dist/commonjs/perms.d.ts +3 -0
  69. package/dist/commonjs/perms.d.ts.map +1 -0
  70. package/dist/commonjs/perms.js +66 -0
  71. package/dist/commonjs/perms.js.map +1 -0
  72. package/dist/commonjs/relationships.d.ts +7 -0
  73. package/dist/commonjs/relationships.d.ts.map +1 -0
  74. package/dist/commonjs/relationships.js +46 -0
  75. package/dist/commonjs/relationships.js.map +1 -0
  76. package/dist/commonjs/schema.d.ts +161 -0
  77. package/dist/commonjs/schema.d.ts.map +1 -0
  78. package/dist/commonjs/schema.js +174 -0
  79. package/dist/commonjs/schema.js.map +1 -0
  80. package/dist/commonjs/serverOAuth.d.ts +25 -0
  81. package/dist/commonjs/serverOAuth.d.ts.map +1 -0
  82. package/dist/commonjs/serverOAuth.js +72 -0
  83. package/dist/commonjs/serverOAuth.js.map +1 -0
  84. package/dist/commonjs/typescript-schema.d.ts +17 -0
  85. package/dist/commonjs/typescript-schema.d.ts.map +1 -0
  86. package/dist/commonjs/typescript-schema.js +314 -0
  87. package/dist/commonjs/typescript-schema.js.map +1 -0
  88. package/dist/commonjs/util.d.ts +13 -0
  89. package/dist/commonjs/util.d.ts.map +1 -0
  90. package/dist/commonjs/util.js +55 -0
  91. package/dist/commonjs/util.js.map +1 -0
  92. package/dist/commonjs/version.d.ts +3 -0
  93. package/dist/commonjs/version.d.ts.map +1 -0
  94. package/dist/commonjs/version.js +5 -0
  95. package/dist/commonjs/version.js.map +1 -0
  96. package/dist/esm/ProgressPromise.d.ts +18 -0
  97. package/dist/esm/ProgressPromise.d.ts.map +1 -0
  98. package/dist/esm/ProgressPromise.js +73 -0
  99. package/dist/esm/ProgressPromise.js.map +1 -0
  100. package/dist/esm/api.d.ts +480 -0
  101. package/dist/esm/api.d.ts.map +1 -0
  102. package/dist/esm/api.js +1121 -0
  103. package/dist/esm/api.js.map +1 -0
  104. package/dist/esm/backupDownload.d.ts +89 -0
  105. package/dist/esm/backupDownload.d.ts.map +1 -0
  106. package/dist/esm/backupDownload.js +354 -0
  107. package/dist/esm/backupDownload.js.map +1 -0
  108. package/dist/esm/backups.d.ts +146 -0
  109. package/dist/esm/backups.d.ts.map +1 -0
  110. package/dist/esm/backups.js +237 -0
  111. package/dist/esm/backups.js.map +1 -0
  112. package/dist/esm/clerk.d.ts +2 -0
  113. package/dist/esm/clerk.d.ts.map +1 -0
  114. package/dist/esm/clerk.js +26 -0
  115. package/dist/esm/clerk.js.map +1 -0
  116. package/dist/esm/consts.d.ts +11 -0
  117. package/dist/esm/consts.d.ts.map +1 -0
  118. package/dist/esm/consts.js +13 -0
  119. package/dist/esm/consts.js.map +1 -0
  120. package/dist/esm/crypto.d.ts +4 -0
  121. package/dist/esm/crypto.d.ts.map +1 -0
  122. package/dist/esm/crypto.js +21 -0
  123. package/dist/esm/crypto.js.map +1 -0
  124. package/dist/esm/index.d.ts +18 -0
  125. package/dist/esm/index.d.ts.map +1 -0
  126. package/dist/esm/index.js +17 -0
  127. package/dist/esm/index.js.map +1 -0
  128. package/dist/esm/migrationUtils.d.ts +4 -0
  129. package/dist/esm/migrationUtils.d.ts.map +1 -0
  130. package/dist/esm/migrationUtils.js +47 -0
  131. package/dist/esm/migrationUtils.js.map +1 -0
  132. package/dist/esm/migrations.d.ts +99 -0
  133. package/dist/esm/migrations.d.ts.map +1 -0
  134. package/dist/esm/migrations.js +588 -0
  135. package/dist/esm/migrations.js.map +1 -0
  136. package/dist/esm/oauth.d.ts +98 -0
  137. package/dist/esm/oauth.d.ts.map +1 -0
  138. package/dist/esm/oauth.js +268 -0
  139. package/dist/esm/oauth.js.map +1 -0
  140. package/dist/esm/oauthCommon.d.ts +12 -0
  141. package/dist/esm/oauthCommon.d.ts.map +1 -0
  142. package/dist/esm/oauthCommon.js +22 -0
  143. package/dist/esm/oauthCommon.js.map +1 -0
  144. package/dist/esm/package.json +3 -0
  145. package/dist/esm/perms.d.ts +3 -0
  146. package/dist/esm/perms.d.ts.map +1 -0
  147. package/dist/esm/perms.js +62 -0
  148. package/dist/esm/perms.js.map +1 -0
  149. package/dist/esm/relationships.d.ts +7 -0
  150. package/dist/esm/relationships.d.ts.map +1 -0
  151. package/dist/esm/relationships.js +43 -0
  152. package/dist/esm/relationships.js.map +1 -0
  153. package/dist/esm/schema.d.ts +161 -0
  154. package/dist/esm/schema.d.ts.map +1 -0
  155. package/dist/esm/schema.js +158 -0
  156. package/dist/esm/schema.js.map +1 -0
  157. package/dist/esm/serverOAuth.d.ts +25 -0
  158. package/dist/esm/serverOAuth.d.ts.map +1 -0
  159. package/dist/esm/serverOAuth.js +68 -0
  160. package/dist/esm/serverOAuth.js.map +1 -0
  161. package/dist/esm/typescript-schema.d.ts +17 -0
  162. package/dist/esm/typescript-schema.d.ts.map +1 -0
  163. package/dist/esm/typescript-schema.js +310 -0
  164. package/dist/esm/typescript-schema.js.map +1 -0
  165. package/dist/esm/util.d.ts +13 -0
  166. package/dist/esm/util.d.ts.map +1 -0
  167. package/dist/esm/util.js +46 -0
  168. package/dist/esm/util.js.map +1 -0
  169. package/dist/esm/version.d.ts +3 -0
  170. package/dist/esm/version.d.ts.map +1 -0
  171. package/dist/esm/version.js +3 -0
  172. package/dist/esm/version.js.map +1 -0
  173. package/dist/standalone/index.js +13747 -0
  174. package/dist/standalone/index.umd.cjs +72 -0
  175. package/package.json +74 -3
  176. package/src/ProgressPromise.ts +97 -0
  177. package/src/api.ts +1903 -0
  178. package/src/backupDownload.ts +519 -0
  179. package/src/backups.ts +342 -0
  180. package/src/clerk.ts +24 -0
  181. package/src/consts.ts +22 -0
  182. package/src/crypto.ts +28 -0
  183. package/src/index.ts +147 -0
  184. package/src/migrationUtils.ts +56 -0
  185. package/src/migrations.ts +920 -0
  186. package/src/oauth.ts +390 -0
  187. package/src/oauthCommon.ts +38 -0
  188. package/src/perms.ts +81 -0
  189. package/src/relationships.ts +57 -0
  190. package/src/schema.ts +497 -0
  191. package/src/serverOAuth.ts +119 -0
  192. package/src/typescript-schema.ts +439 -0
  193. package/src/util.ts +77 -0
  194. package/src/version.ts +3 -0
  195. package/tsconfig.dev.json +14 -0
  196. package/tsconfig.json +14 -0
  197. package/vite.config.ts +19 -0
package/src/oauth.ts ADDED
@@ -0,0 +1,390 @@
1
+ import { requireApiURI, version as coreVersion } from '@sidekickdb/core';
2
+ import { pkceVerifier, pkceCodeChallengeOfVerifier } from './crypto.ts';
3
+ import { InstantOAuthError, OAuthScope } from './oauthCommon.ts';
4
+ import version from './version.ts';
5
+
6
+ export type InstantDBOAuthAccessToken = {
7
+ /**
8
+ * Token that can be used to access the Instant platform API on behalf of a user
9
+ */
10
+ token: string;
11
+ /**
12
+ * The date when the token expires (2 weeks from when it was issued by default)
13
+ */
14
+ expiresAt: Date;
15
+ };
16
+
17
+ function getWindowOpts(): string {
18
+ const windowWidth = Math.min(800, Math.floor(window.outerWidth * 0.8));
19
+ const windowHeight = Math.min(630, Math.floor(window.outerHeight * 0.5));
20
+ const windowArea = {
21
+ width: windowWidth,
22
+ height: windowHeight,
23
+ left: Math.round(window.screenX + (window.outerWidth - windowWidth) / 2),
24
+ top: Math.round(window.screenY + (window.outerHeight - windowHeight) / 8),
25
+ };
26
+
27
+ const opts: Record<string, number | string> = {
28
+ width: windowArea.width,
29
+ height: windowArea.height,
30
+ left: windowArea.left,
31
+ top: windowArea.top,
32
+ toolbar: 0,
33
+ scrollbars: 1,
34
+ status: 1,
35
+ resizable: 1,
36
+ menuBar: 0,
37
+ rel: 'opener',
38
+ };
39
+
40
+ return Object.keys(opts)
41
+ .map((k) => `${k}=${opts[k]}`)
42
+ .join(',');
43
+ }
44
+
45
+ let AUTH_WINDOW: null | Window = null;
46
+
47
+ function oAuthStartUrl({
48
+ clientId,
49
+ state,
50
+ codeChallenge,
51
+ apiURI,
52
+ redirectUri,
53
+ scopes,
54
+ }: {
55
+ clientId: string;
56
+ state: string;
57
+ codeChallenge: string;
58
+ apiURI: string;
59
+ redirectUri: string;
60
+ scopes: string[];
61
+ }): string {
62
+ const oauthUrl = new URL(`${apiURI}/platform/oauth/start`);
63
+ oauthUrl.searchParams.set('client_id', clientId);
64
+ oauthUrl.searchParams.set('redirect_uri', redirectUri);
65
+ oauthUrl.searchParams.set('scope', scopes.join(' '));
66
+ oauthUrl.searchParams.set('state', state);
67
+ oauthUrl.searchParams.set('response_type', 'code');
68
+ oauthUrl.searchParams.set('code_challenge', codeChallenge);
69
+ oauthUrl.searchParams.set('code_challenge_method', 'S256');
70
+
71
+ return oauthUrl.toString();
72
+ }
73
+
74
+ async function exchangeCodeForToken({
75
+ code,
76
+ clientId,
77
+ verifier,
78
+ apiURI,
79
+ redirectUri,
80
+ }: {
81
+ code: string;
82
+ clientId: string;
83
+ verifier: string;
84
+ apiURI: string;
85
+ redirectUri: string;
86
+ }): Promise<InstantDBOAuthAccessToken> {
87
+ const res = await fetch(`${apiURI}/platform/oauth/token`, {
88
+ method: 'POST',
89
+ headers: {
90
+ 'Content-type': 'application/json',
91
+ 'Instant-Platform-Version': version,
92
+ 'Instant-Core-Version': coreVersion,
93
+ },
94
+ body: JSON.stringify({
95
+ grant_type: 'authorization_code',
96
+ code,
97
+ redirect_uri: redirectUri,
98
+ client_id: clientId,
99
+ code_verifier: verifier,
100
+ }),
101
+ });
102
+
103
+ if (!res.ok) {
104
+ const text = await res.text();
105
+ let error;
106
+
107
+ try {
108
+ const json = JSON.parse(text);
109
+ error = {
110
+ error: json.error,
111
+ errorDescription: json.error_description,
112
+ message: `OAuth error: ${json.error || 'server_error'}`,
113
+ };
114
+ } catch (e) {
115
+ error = {
116
+ error: 'server_error',
117
+ message: 'OAuth error: server_error',
118
+ };
119
+ }
120
+
121
+ throw new InstantOAuthError(error);
122
+ }
123
+
124
+ const json = (await res.json()) as {
125
+ access_token: string;
126
+ expires_in: number;
127
+ };
128
+
129
+ return {
130
+ token: json.access_token,
131
+ expiresAt: new Date(Date.now() + (json.expires_in - 30) * 1000),
132
+ };
133
+ }
134
+
135
+ export function handleClientRedirect() {
136
+ if (typeof window === 'undefined') {
137
+ throw new Error('This function may only be used in a browser context.');
138
+ }
139
+
140
+ const searchParams = new URL(window.location.href).searchParams;
141
+
142
+ const state = searchParams.get('state');
143
+ const error = searchParams.get('error');
144
+ const errorDescription = searchParams.get('error_description');
145
+ const code = searchParams.get('code');
146
+
147
+ if (!state) {
148
+ throw new Error('Invalid redirect. The state param is missing.');
149
+ }
150
+
151
+ const channel = new BroadcastChannel(state);
152
+ channel.addEventListener('message', (event) => {
153
+ if (event.data.type === 'oauth-redirect-window-done') {
154
+ window.close();
155
+ }
156
+ });
157
+ channel.postMessage({
158
+ type: 'oauth-redirect',
159
+ state,
160
+ error,
161
+ errorDescription,
162
+ code,
163
+ });
164
+
165
+ return () => {
166
+ channel.close();
167
+ };
168
+ }
169
+
170
+ export function startInstantOAuthClientOnlyFlow({
171
+ clientId,
172
+ apiURI,
173
+ redirectUri,
174
+ scopes,
175
+ }: {
176
+ clientId: string;
177
+ apiURI: string;
178
+ redirectUri: string;
179
+ scopes: OAuthScope[];
180
+ }): Promise<InstantDBOAuthAccessToken> {
181
+ if (typeof window === 'undefined') {
182
+ throw new Error('OAuth flow can only be started on the client.');
183
+ }
184
+
185
+ const existingAuthWindow = AUTH_WINDOW;
186
+
187
+ if (existingAuthWindow) {
188
+ existingAuthWindow.close();
189
+ }
190
+
191
+ const state = crypto.randomUUID();
192
+
193
+ const verifier = pkceVerifier();
194
+
195
+ const channel = new BroadcastChannel(state);
196
+
197
+ const flowCompletePromise: Promise<InstantDBOAuthAccessToken> = new Promise(
198
+ (resolve, reject) => {
199
+ channel.addEventListener('message', async (event) => {
200
+ if (event.data.type !== 'oauth-redirect') {
201
+ return;
202
+ }
203
+
204
+ const {
205
+ state: redirectState,
206
+ error,
207
+ code,
208
+ errorDescription,
209
+ } = event.data;
210
+
211
+ if (!redirectState || redirectState !== state) {
212
+ return;
213
+ }
214
+
215
+ if (code) {
216
+ try {
217
+ const token = await exchangeCodeForToken({
218
+ clientId,
219
+ code,
220
+ verifier,
221
+ apiURI,
222
+ redirectUri,
223
+ });
224
+ resolve(token);
225
+ } catch (e) {
226
+ if (e instanceof InstantOAuthError) {
227
+ reject(e);
228
+ }
229
+ reject(
230
+ new InstantOAuthError({
231
+ error: 'server_error',
232
+ message: 'OAuth error exchanging code for token',
233
+ }),
234
+ );
235
+ }
236
+ } else if (typeof error === 'string') {
237
+ reject(
238
+ new InstantOAuthError({
239
+ error,
240
+ errorDescription,
241
+ message: `OAuth error: ${error}`,
242
+ }),
243
+ );
244
+ } else {
245
+ reject(
246
+ new InstantOAuthError({
247
+ error: 'server_error',
248
+ message: 'OAuth error: server_error',
249
+ }),
250
+ );
251
+ }
252
+
253
+ channel.postMessage({ type: 'oauth-redirect-window-done' });
254
+ });
255
+ },
256
+ );
257
+
258
+ const w = window.open(
259
+ // Open window synchronously to prevent popup blocker
260
+ '',
261
+ // A unqiue name prevents orphaned popups from stealing our window.open
262
+ `instantdb_oauth_${Math.random()}`.replace('.', ''),
263
+ getWindowOpts(),
264
+ );
265
+
266
+ if (!w) {
267
+ return Promise.reject({ error: 'Could not open Auth window' });
268
+ }
269
+
270
+ AUTH_WINDOW = w;
271
+
272
+ pkceCodeChallengeOfVerifier(verifier).then((codeChallenge) => {
273
+ const oauthUrl = oAuthStartUrl({
274
+ clientId,
275
+ state,
276
+ codeChallenge,
277
+ apiURI,
278
+ redirectUri,
279
+ scopes,
280
+ });
281
+ w.location.href = oauthUrl;
282
+ });
283
+
284
+ return flowCompletePromise.finally(() => channel.close());
285
+ }
286
+
287
+ /**
288
+ * Configuration for {@link OAuthHandler}.
289
+ */
290
+ export interface OAuthHandlerConfig {
291
+ /**
292
+ * Must exactly match one of the **Authorized Redirect URIs** in your OAuth
293
+ * client settings on the Instant dashboard.
294
+ */
295
+ redirectUri: string;
296
+
297
+ /** OAuth client ID from the Instant dashboard. */
298
+ clientId: string;
299
+
300
+ /**
301
+ * URL of your SidekickDB server, e.g. `https://sidekick.example.com`.
302
+ * Required: there is no default server.
303
+ */
304
+ apiURI?: string | null;
305
+ }
306
+
307
+ /**
308
+ * Thin wrapper that drives InstantDB’s browser-only OAuth flow.
309
+ */
310
+ export class OAuthHandler {
311
+ /** Redirect URI that the provider will call back into. */
312
+ readonly redirectUri: string;
313
+
314
+ /** OAuth client ID. */
315
+ readonly clientId: string;
316
+
317
+ /**
318
+ * Base URL of your SidekickDB server's REST API.
319
+ */
320
+ readonly apiURI: string;
321
+
322
+ constructor(config: OAuthHandlerConfig) {
323
+ this.redirectUri = config.redirectUri;
324
+ this.apiURI = requireApiURI(config.apiURI, {
325
+ target: 'new OAuthHandler()',
326
+ });
327
+ this.clientId = config.clientId;
328
+ }
329
+
330
+ /**
331
+ * **Client-only flow** using PKCE (no client-secret required).
332
+ * Opens a popup to start the OAuth flow.
333
+ * Returns an {@link InstantDBOAuthAccessToken}.
334
+ * *Refresh tokens are **not** available in this flow.*
335
+ *
336
+ * @example
337
+ * const oauthHandler = new OAuthHandler({
338
+ * clientId: YOUR_CLIENT_ID,
339
+ * redirectUri: YOUR_REDIRECT_URI,
340
+ * apiURI: 'https://sidekick.example.com',
341
+ * });
342
+ *
343
+ * function ConnectToInstant() {
344
+ * const handleConnect = async () => {
345
+ * try {
346
+ * const token = await oauthHandler.startClientOnlyFlow(['apps-write']);
347
+ * console.log('success!', token)
348
+ * } catch (e) {
349
+ * console.log('OAuth flow failed', e);
350
+ * }
351
+ * }
352
+ * return <button onClick={handleConnect}>Connect to Instant</button>
353
+ * }
354
+ */
355
+ startClientOnlyFlow(
356
+ scopes: OAuthScope[],
357
+ ): Promise<InstantDBOAuthAccessToken> {
358
+ return startInstantOAuthClientOnlyFlow({
359
+ clientId: this.clientId,
360
+ apiURI: this.apiURI,
361
+ redirectUri: this.redirectUri,
362
+ scopes,
363
+ });
364
+ }
365
+
366
+ /**
367
+ * Call from the page served at {@link OAuthHandlerConfig.redirectUri}.
368
+ * Parses `state` & `code` from the URL, exchanges them for an access token,
369
+ * then automatically closes the popup/window.
370
+ *
371
+ * @example
372
+ * ```tsx
373
+ * const oauthHandler = new OAuthHandler({
374
+ * clientId: YOUR_CLIENT_ID,
375
+ * redirectUri: YOUR_REDIRECT_URI,
376
+ * apiURI: 'https://sidekick.example.com',
377
+ * })
378
+ *
379
+ * function RedirectPage() {
380
+ * useEffect(() => {
381
+ * return oauthHandler.handleClientRedirect();
382
+ * }, []);
383
+ * return <div>Loading…</div>;
384
+ * }
385
+ * ```
386
+ */
387
+ handleClientRedirect(): () => void {
388
+ return handleClientRedirect();
389
+ }
390
+ }
@@ -0,0 +1,38 @@
1
+ export type OAuthScope =
2
+ | 'apps-read'
3
+ | 'apps-write'
4
+ | 'data-read'
5
+ | 'data-write'
6
+ | 'storage-read'
7
+ | 'storage-write';
8
+
9
+ export class InstantOAuthError extends Error {
10
+ error: string;
11
+ errorDescription: string | null | undefined;
12
+
13
+ constructor(config: {
14
+ message: string;
15
+ error: string;
16
+ errorDescription?: string | null | undefined;
17
+ }) {
18
+ super(config.message);
19
+
20
+ const actualProto = new.target.prototype;
21
+ if (Object.setPrototypeOf) {
22
+ Object.setPrototypeOf(this, actualProto);
23
+ }
24
+
25
+ // Maintain proper stack trace for where our error was thrown
26
+ if (Error.captureStackTrace) {
27
+ Error.captureStackTrace(this, InstantOAuthError);
28
+ }
29
+
30
+ this.name = 'InstantOAuthError';
31
+ this.error = config.error;
32
+ this.errorDescription = config.errorDescription;
33
+ }
34
+
35
+ get [Symbol.toStringTag]() {
36
+ return 'InstantOAuthError';
37
+ }
38
+ }
package/src/perms.ts ADDED
@@ -0,0 +1,81 @@
1
+ import { parse, type ParseResult, type File } from '@babel/parser';
2
+ import { astToJson } from './typescript-schema.ts';
3
+
4
+ export function generatePermsTypescriptFile(
5
+ permsCode: null | Record<string, any>,
6
+ instantModuleName: string,
7
+ ) {
8
+ const rulesTxt =
9
+ permsCode && Object.keys(permsCode).length
10
+ ? JSON.stringify(permsCode, null, 2)
11
+ : `{
12
+ /**
13
+ * Welcome to SidekickDB's permission system!
14
+ * Right now your rules are empty. To start filling them in, check out the docs:
15
+ * https://sidekickdb.co/docs/permissions
16
+ *
17
+ * Here's an example to give you a feel:
18
+ * posts: {
19
+ * allow: {
20
+ * view: "true",
21
+ * create: "isOwner",
22
+ * update: "isOwner",
23
+ * delete: "isOwner",
24
+ * },
25
+ * bind: {"isOwner": "auth.id != null && auth.id == data.ownerId"},
26
+ * },
27
+ */
28
+ }
29
+ `.trim();
30
+
31
+ return `// Docs: https://sidekickdb.co/docs/permissions
32
+
33
+ import type { InstantRules } from "${instantModuleName ?? '@sidekickdb/core'}";
34
+
35
+ const rules = ${rulesTxt} satisfies InstantRules;
36
+
37
+ export default rules;
38
+ `;
39
+ }
40
+
41
+ function astToPermsCode(ast: ParseResult<File>): Record<string, any> {
42
+ for (const n of ast.program.body) {
43
+ if (
44
+ n.type !== 'VariableDeclaration' ||
45
+ n.declarations.length !== 1 ||
46
+ n.declarations[0].id.type !== 'Identifier' ||
47
+ n.declarations[0].id.name !== 'rules'
48
+ ) {
49
+ continue;
50
+ }
51
+
52
+ const node = n.declarations[0];
53
+
54
+ if (!node.init || node.init.type !== 'TSSatisfiesExpression') {
55
+ throw new Error(`Could not extract rules`);
56
+ }
57
+
58
+ return astToJson(node.init.expression) as Record<string, any>;
59
+ }
60
+
61
+ throw new Error(
62
+ 'Could not extract rules, did not find the rules variable declaration.',
63
+ );
64
+ }
65
+
66
+ export function permsTypescriptFileToCode(
67
+ content: string,
68
+ sourceFilename: string,
69
+ ) {
70
+ const ast = parse(content, {
71
+ sourceFilename,
72
+ sourceType: 'module',
73
+ errorRecovery: false,
74
+ plugins: ['typescript'],
75
+ });
76
+ if (ast.errors?.length) {
77
+ throw new Error(`Could not parse perms file. ${ast.errors[0].reasonCode}.`);
78
+ }
79
+
80
+ return astToPermsCode(ast);
81
+ }
@@ -0,0 +1,57 @@
1
+ // Copied from www/lib/relationships.ts
2
+ export type RelationshipKinds =
3
+ | `many-many`
4
+ | 'one-one'
5
+ | 'one-many'
6
+ | 'many-one';
7
+
8
+ export const relationshipConstraints: Record<
9
+ RelationshipKinds,
10
+ { cardinality: 'one' | 'many'; 'unique?': boolean }
11
+ > = {
12
+ /**
13
+ * users has_many tags
14
+ * tags has_many users
15
+ */
16
+ 'many-many': {
17
+ cardinality: 'many',
18
+ 'unique?': false,
19
+ },
20
+ /**
21
+ * users has_one profile
22
+ * profiles has_one owner
23
+ */
24
+ 'one-one': {
25
+ cardinality: 'one',
26
+ 'unique?': true,
27
+ },
28
+ /**
29
+ * users has_many posts
30
+ * posts has_one author
31
+ * [?users :users/posts ?posts]
32
+ * <---------------> unique!
33
+ */
34
+ 'many-one': {
35
+ cardinality: 'many',
36
+ 'unique?': true,
37
+ },
38
+
39
+ /**
40
+ * posts has_one owner
41
+ * users has_many owned_posts
42
+ * [?posts :posts/user ?users]
43
+ * <---------------> unique!
44
+ */
45
+ 'one-many': {
46
+ cardinality: 'one',
47
+ 'unique?': false,
48
+ },
49
+ };
50
+
51
+ export const relationshipConstraintsInverse: Record<string, RelationshipKinds> =
52
+ Object.fromEntries(
53
+ Object.entries(relationshipConstraints).map(([k, v]) => [
54
+ `${v.cardinality}-${v['unique?']}`,
55
+ k as RelationshipKinds,
56
+ ]),
57
+ );