@sidekickdb/platform 0.0.0 → 2.0.1

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 +444 -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 +69 -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/backups.ts ADDED
@@ -0,0 +1,342 @@
1
+ import { InstantAPIError, version as coreVersion } from '@sidekickdb/core';
2
+ import type { WithAuth } from '@sidekickdb/webhooks';
3
+ import version from './version.ts';
4
+ import {
5
+ downloadBackupArchive,
6
+ type BackupDownloadResult,
7
+ type DownloadBackupArchiveOpts,
8
+ } from './backupDownload.ts';
9
+
10
+ /** A point-in-time snapshot of an app. */
11
+ export type AppBackup = {
12
+ /** Unique identifier for the backup. */
13
+ id: string;
14
+ /** Instant sequence number the snapshot was taken at. */
15
+ isn: string;
16
+ /** When the snapshot was taken. */
17
+ backupAt: Date;
18
+ /** Total size in bytes of the app's storage files at backup time, if known. */
19
+ filesSize: number | null;
20
+ /** Size in bytes of the app's database at backup time, if known. */
21
+ dbSize: number | null;
22
+ /**
23
+ * Total uncompressed size in bytes of the backup's entity files (what they
24
+ * take up unpacked on disk), if known.
25
+ */
26
+ uncompressedSize: number | null;
27
+ /** Human-readable label, e.g. "Automated Daily Snapshot". */
28
+ description: string | null;
29
+ /** When the backup stops being available for download. */
30
+ expiresAt: Date | null;
31
+ };
32
+
33
+ /**
34
+ * A file that makes up the backup payload: `config.json` or an
35
+ * `entities/<etype>.jsonl` shard.
36
+ */
37
+ export type AppBackupFile = {
38
+ name: string;
39
+ /** Size in bytes as stored (the entity shards are stored compressed). */
40
+ size: number;
41
+ };
42
+
43
+ /** A storage file captured in a backup, with a presigned download URL. */
44
+ export type AppBackupStorageFile = {
45
+ /**
46
+ * Stable id of the file's blob. A backup archive stores the blob at
47
+ * `files/<locationId>`.
48
+ */
49
+ locationId: string;
50
+ /** The path the user uploaded the file to. */
51
+ path: string | null;
52
+ /** Presigned URL for the file's contents. Expires after 12 hours. */
53
+ url: string;
54
+ };
55
+
56
+ type AppBackupResponse = {
57
+ id: string;
58
+ isn: string;
59
+ backup_at: string;
60
+ files_size: number | null;
61
+ db_size: number | null;
62
+ uncompressed_size: number | null;
63
+ description: string | null;
64
+ expires_at: string | null;
65
+ };
66
+
67
+ /** Converts a backup row as the server sends it into an {@link AppBackup}. */
68
+ export function toAppBackup(row: AppBackupResponse): AppBackup {
69
+ return {
70
+ id: row.id,
71
+ isn: row.isn,
72
+ backupAt: new Date(row.backup_at),
73
+ filesSize: row.files_size,
74
+ dbSize: row.db_size,
75
+ uncompressedSize: row.uncompressed_size,
76
+ description: row.description,
77
+ expiresAt: row.expires_at ? new Date(row.expires_at) : null,
78
+ };
79
+ }
80
+
81
+ /** Suggested filename for a backup archive. */
82
+ export function backupZipName(backup: AppBackup): string {
83
+ const safe = backup.backupAt.toISOString().replace(/[:.]/g, '-');
84
+ return `instant-backup-${safe}.zip`;
85
+ }
86
+
87
+ /**
88
+ * Formats a byte count the way macOS/Finder reports file sizes: decimal
89
+ * (1000-based) units with SI labels, so the number lines up with what lands
90
+ * on disk.
91
+ */
92
+ export function formatFileSize(n: number): string {
93
+ if (n < 1000) return `${n} B`;
94
+ const units = ['KB', 'MB', 'GB', 'TB'];
95
+ let i = -1;
96
+ let v = n;
97
+ do {
98
+ v /= 1000;
99
+ i++;
100
+ } while (v >= 1000 && i < units.length - 1);
101
+ let digits = v < 10 ? 2 : v < 100 ? 1 : 0;
102
+ // Rounding can cross a unit boundary (999,500 would read "1000 KB");
103
+ // promote to the next unit instead.
104
+ if (Number(v.toFixed(digits)) >= 1000 && i < units.length - 1) {
105
+ v /= 1000;
106
+ i++;
107
+ digits = 2;
108
+ }
109
+ return `${v.toFixed(digits)} ${units[i]}`;
110
+ }
111
+
112
+ /**
113
+ * Estimated size range for a backup's zip archive, or null when the backup
114
+ * row carries no sizes. Upper bound: everything stored uncompressed (STORE
115
+ * mode and/or files that don't compress). Lower bound: everything compressed
116
+ * at a ~4x DEFLATE ratio, best case for text/JSON, but storage files vary
117
+ * wildly (raw text compresses well, already-compressed images/videos don't).
118
+ * The same divisor applies to both since the file types aren't visible from
119
+ * here; the actual zip lands somewhere inside the range.
120
+ */
121
+ export function estimateZipSize(
122
+ backup: AppBackup,
123
+ ): { min: number; max: number } | null {
124
+ const backupBytes = backup.uncompressedSize ?? backup.dbSize;
125
+ if (backupBytes == null || backup.filesSize == null) return null;
126
+ const max = backupBytes + backup.filesSize;
127
+ return { min: Math.round(max / 4), max };
128
+ }
129
+
130
+ function authHeaders(token: string): Record<string, string> {
131
+ return {
132
+ authorization: `Bearer ${token}`,
133
+ 'Instant-Platform-Version': version,
134
+ 'Instant-Core-Version': coreVersion,
135
+ 'X-Instant-Source': 'platform-sdk',
136
+ 'X-Instant-Version': version,
137
+ };
138
+ }
139
+
140
+ async function apiError(res: Response): Promise<InstantAPIError> {
141
+ const body = await res.text();
142
+ try {
143
+ return new InstantAPIError({ status: res.status, body: JSON.parse(body) });
144
+ } catch (_e) {
145
+ return new InstantAPIError({
146
+ status: res.status,
147
+ body: { type: undefined, message: body },
148
+ });
149
+ }
150
+ }
151
+
152
+ async function* ndjsonLines(
153
+ body: ReadableStream<Uint8Array>,
154
+ ): AsyncGenerator<any, void, void> {
155
+ const reader = body.getReader();
156
+ try {
157
+ const decoder = new TextDecoder();
158
+ let buf = '';
159
+ while (true) {
160
+ const { done, value } = await reader.read();
161
+ if (done) break;
162
+ buf += decoder.decode(value, { stream: true });
163
+ let nl = buf.indexOf('\n');
164
+ while (nl !== -1) {
165
+ const line = buf.slice(0, nl).trim();
166
+ buf = buf.slice(nl + 1);
167
+ if (line.length > 0) {
168
+ yield JSON.parse(line);
169
+ }
170
+ nl = buf.indexOf('\n');
171
+ }
172
+ }
173
+ const line = buf.trim();
174
+ if (line.length > 0) {
175
+ yield JSON.parse(line);
176
+ }
177
+ } finally {
178
+ // Also releases the connection when the consumer stops iterating early.
179
+ await reader.cancel().catch(() => {});
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Read-only API for an app's backups.
185
+ *
186
+ * A backup archive has a canonical entry order that restore relies on:
187
+ * `config.json` first, then every `entities/<etype>.jsonl` shard, then the
188
+ * `files/<locationId>` storage blobs. In particular ALL entity files must
189
+ * come before ANY storage file, so a restore can process the archive in a
190
+ * single streaming pass: `config.json` sets up the schema, the `$files`
191
+ * entities register file metadata, and only then can each blob be matched
192
+ * to its entity. {@link downloadArchive} implements that order end to end;
193
+ * {@link listFiles} (which returns the entity files already in write order)
194
+ * and {@link streamStorageFiles} are the pieces for building a custom
195
+ * pipeline.
196
+ */
197
+ export class BackupsManager {
198
+ #appId: string;
199
+ #apiURI: string;
200
+ #withAuth: WithAuth;
201
+
202
+ constructor(opts: { appId: string; apiURI: string; withAuth: WithAuth }) {
203
+ this.#appId = opts.appId;
204
+ this.#apiURI = opts.apiURI;
205
+ this.#withAuth = opts.withAuth;
206
+ }
207
+
208
+ #getJson(path: string, signal?: AbortSignal): Promise<any> {
209
+ return this.#withAuth(async (token) => {
210
+ const res = await fetch(`${this.#apiURI}${path}`, {
211
+ headers: authHeaders(token),
212
+ signal,
213
+ });
214
+ if (res.status !== 200) {
215
+ throw await apiError(res);
216
+ }
217
+ return res.json();
218
+ });
219
+ }
220
+
221
+ /**
222
+ * Returns the app's downloadable (non-expired) backups, newest first.
223
+ */
224
+ async list(opts?: { signal?: AbortSignal }): Promise<AppBackup[]> {
225
+ const res = await this.#getJson(
226
+ `/dash/apps/${this.#appId}/backups`,
227
+ opts?.signal,
228
+ );
229
+ return ((res.backups || []) as AppBackupResponse[]).map(toAppBackup);
230
+ }
231
+
232
+ /**
233
+ * Returns the backup's entity files (`config.json` and the
234
+ * `entities/<etype>.jsonl` shards) in archive write order. Storage blobs
235
+ * are not included; discover those with {@link streamStorageFiles}.
236
+ */
237
+ async listFiles(
238
+ backupId: string,
239
+ opts?: { signal?: AbortSignal },
240
+ ): Promise<AppBackupFile[]> {
241
+ const res = await this.#getJson(
242
+ `/dash/apps/${this.#appId}/backups/${backupId}/files`,
243
+ opts?.signal,
244
+ );
245
+ return (res.files || []) as AppBackupFile[];
246
+ }
247
+
248
+ /**
249
+ * Returns a presigned download URL for one of the backup's entity files.
250
+ * The URL expires after 1 hour, so fetch it right before downloading.
251
+ *
252
+ * The entity files are stored zstd-compressed (the response carries
253
+ * `Content-Encoding: zstd`); decompress to get the raw JSON/JSONL.
254
+ */
255
+ async getFileUrl(
256
+ backupId: string,
257
+ name: string,
258
+ opts?: { signal?: AbortSignal },
259
+ ): Promise<string> {
260
+ const res = await this.#getJson(
261
+ `/dash/apps/${this.#appId}/backups/${backupId}/file-url?name=${encodeURIComponent(name)}`,
262
+ opts?.signal,
263
+ );
264
+ return res.url as string;
265
+ }
266
+
267
+ /**
268
+ * Streams every storage file captured in the backup, each with a presigned
269
+ * download URL. Completes without yielding anything when the app has no
270
+ * storage files.
271
+ *
272
+ * The server ends a healthy stream with a terminal sentinel; if the stream
273
+ * closes without it (a server-side failure truncated the listing), this
274
+ * throws instead of silently under-reporting files.
275
+ */
276
+ async *streamStorageFiles(
277
+ backupId: string,
278
+ opts?: { signal?: AbortSignal },
279
+ ): AsyncGenerator<AppBackupStorageFile, void, void> {
280
+ const res = await this.#withAuth(async (token) => {
281
+ const res = await fetch(
282
+ `${this.#apiURI}/dash/apps/${this.#appId}/backups/${backupId}/storage-files`,
283
+ { headers: authHeaders(token), signal: opts?.signal },
284
+ );
285
+ if (res.status !== 200) {
286
+ throw await apiError(res);
287
+ }
288
+ return res;
289
+ });
290
+ if (!res.body) {
291
+ throw new Error('Storage file listing returned no body.');
292
+ }
293
+ let complete = false;
294
+ for await (const line of ndjsonLines(res.body)) {
295
+ if (line.done === true) {
296
+ complete = true;
297
+ break;
298
+ }
299
+ // A file record always carries a locationId and url; anything else is
300
+ // corruption, and skipping it would silently omit a file from the
301
+ // archive.
302
+ if (
303
+ typeof line.locationId !== 'string' ||
304
+ line.locationId.length === 0 ||
305
+ // The locationId becomes the archive entry path `files/<locationId>`;
306
+ // reject separators and control characters that could escape it.
307
+ /[/\\\u0000-\u001f\u007f]/.test(line.locationId) ||
308
+ line.locationId === '.' ||
309
+ line.locationId === '..' ||
310
+ typeof line.url !== 'string' ||
311
+ line.url.length === 0
312
+ ) {
313
+ throw new Error(
314
+ 'Storage file listing returned a malformed record. Please retry the download.',
315
+ );
316
+ }
317
+ yield {
318
+ locationId: line.locationId,
319
+ path: line.path ?? null,
320
+ url: line.url,
321
+ };
322
+ }
323
+ if (!complete) {
324
+ throw new Error(
325
+ 'Storage file listing ended before it finished. Please retry the download.',
326
+ );
327
+ }
328
+ }
329
+
330
+ /**
331
+ * Downloads the backup into a single zip archive written to `opts.sink`,
332
+ * entries in the canonical restore order described above. The caller
333
+ * supplies the runtime-specific pieces — how to fetch a presigned URL,
334
+ * where the bytes go, and the archive encoder (e.g. zip.js's `ZipWriter`);
335
+ * see {@link DownloadBackupArchiveOpts}.
336
+ */
337
+ downloadArchive(
338
+ opts: DownloadBackupArchiveOpts,
339
+ ): Promise<BackupDownloadResult> {
340
+ return downloadBackupArchive({ manager: this, ...opts });
341
+ }
342
+ }
package/src/clerk.ts ADDED
@@ -0,0 +1,24 @@
1
+ // Base64 decode, switching to url-safe decode if we hit an error
2
+ // Can't be sure which method Clerk uses because you can't generate
3
+ // `+` or `/` with characters that go in a normal host. Urls with
4
+ // chinese characters exist, they might encode to `+` or `/`, and
5
+ // Clerk might support them, so we'll be safe and do both.
6
+ function base64Decode(s: string) {
7
+ try {
8
+ return Buffer.from(s, 'base64').toString('utf-8');
9
+ } catch (e) {
10
+ return Buffer.from(s, 'base64url').toString('utf-8');
11
+ }
12
+ }
13
+
14
+ export function clerkDomainFromPublishableKey(key: string): string | null {
15
+ try {
16
+ const parts = key.split('_');
17
+ const domainPartB64 = parts[parts.length - 1];
18
+ const domainPart = base64Decode(domainPartB64);
19
+ return domainPart.replace('$', '');
20
+ } catch (e) {
21
+ console.error('Error getting domain from clerk key', e);
22
+ return null;
23
+ }
24
+ }
package/src/consts.ts ADDED
@@ -0,0 +1,22 @@
1
+ export function oauthCallbackURL(apiURI: string) {
2
+ return `${apiURI.replace(/\/+$/, '')}/runtime/oauth/callback`;
3
+ }
4
+
5
+ export const GOOGLE_AUTHORIZATION_ENDPOINT =
6
+ 'https://accounts.google.com/o/oauth2/v2/auth';
7
+ export const GOOGLE_TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token';
8
+ export const GOOGLE_DISCOVERY_ENDPOINT =
9
+ 'https://accounts.google.com/.well-known/openid-configuration';
10
+
11
+ export const APPLE_AUTHORIZATION_ENDPOINT =
12
+ 'https://appleid.apple.com/auth/authorize';
13
+ export const APPLE_TOKEN_ENDPOINT = 'https://appleid.apple.com/auth/token';
14
+ export const APPLE_DISCOVERY_ENDPOINT =
15
+ 'https://appleid.apple.com/.well-known/openid-configuration';
16
+
17
+ export const LINKEDIN_AUTHORIZATION_ENDPOINT =
18
+ 'https://www.linkedin.com/oauth/v2/authorization';
19
+ export const LINKEDIN_TOKEN_ENDPOINT =
20
+ 'https://www.linkedin.com/oauth/v2/accessToken';
21
+ export const LINKEDIN_DISCOVERY_ENDPOINT =
22
+ 'https://www.linkedin.com/oauth/.well-known/openid-configuration';
package/src/crypto.ts ADDED
@@ -0,0 +1,28 @@
1
+ // https://tools.ietf.org/html/rfc7636#section-4.1
2
+ export function pkceVerifier(): string {
3
+ const chars =
4
+ '0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz-._~';
5
+ let s = '';
6
+
7
+ for (const value of crypto.getRandomValues(new Uint8Array(64))) {
8
+ s = s + chars[value % chars.length];
9
+ }
10
+
11
+ return s;
12
+ }
13
+
14
+ export function sha256(s: string): Promise<ArrayBuffer> {
15
+ return crypto.subtle.digest({ name: 'SHA-256' }, new TextEncoder().encode(s));
16
+ }
17
+
18
+ function urlSafeBase64(s: string): string {
19
+ return s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
20
+ }
21
+
22
+ export function pkceCodeChallengeOfVerifier(verifier: string): Promise<string> {
23
+ return sha256(verifier).then((s) => {
24
+ return urlSafeBase64(
25
+ btoa(String.fromCharCode(...Array.from(new Uint8Array(s)))),
26
+ );
27
+ });
28
+ }
package/src/index.ts ADDED
@@ -0,0 +1,147 @@
1
+ import { InstantOAuthError, type OAuthScope } from './oauthCommon.ts';
2
+ import {
3
+ type InstantDBOAuthAccessToken,
4
+ type OAuthHandlerConfig,
5
+ OAuthHandler,
6
+ } from './oauth.ts';
7
+ import {
8
+ generatePermsTypescriptFile,
9
+ permsTypescriptFileToCode,
10
+ } from './perms.ts';
11
+ import {
12
+ type InstantAPIPlatformSchema,
13
+ generateSchemaTypescriptFile,
14
+ collectSystemCatalogIdentNames,
15
+ validateSchema,
16
+ SchemaValidationError,
17
+ } from './schema.ts';
18
+ import {
19
+ apiSchemaToInstantSchemaDef,
20
+ PlatformApi,
21
+ translatePlanSteps,
22
+ } from './api.ts';
23
+ import { schemaTypescriptFileToInstantSchema } from './typescript-schema.ts';
24
+
25
+ import version from './version.ts';
26
+ import { ProgressPromise } from './ProgressPromise.ts';
27
+ import {
28
+ i,
29
+ type InstantRules,
30
+ type InstantRouteHandlerPayloadByType,
31
+ type InstantRouteHandlerType,
32
+ type InstantRouteHandlerBody,
33
+ } from '@sidekickdb/core';
34
+ import { exchangeCodeForToken, exchangeRefreshToken } from './serverOAuth.ts';
35
+ import { clerkDomainFromPublishableKey } from './clerk.ts';
36
+ import {
37
+ Webhooks,
38
+ type WebhookAction,
39
+ type WebhookStatus,
40
+ type WebhookEventStatus,
41
+ type WebhookInfo,
42
+ type WebhookAttempt,
43
+ type WebhookEventInfo,
44
+ type WebhookEventsPage,
45
+ type WebhookBody,
46
+ type WebhookEntity,
47
+ type WebhookPayload,
48
+ type WebhookPayloadRecord,
49
+ type WebhookPayloadRecordFor,
50
+ type WebhookHandlerFn,
51
+ type WebhookHandlers,
52
+ type WebhookHelpers,
53
+ type CreateWebhookParams,
54
+ type UpdateWebhookParams,
55
+ WebhooksManager,
56
+ } from '@sidekickdb/webhooks';
57
+
58
+ export {
59
+ type InstantAPIPlatformSchema,
60
+ type InstantDBOAuthAccessToken,
61
+ type OAuthHandlerConfig,
62
+ type OAuthScope,
63
+ type InstantRules,
64
+ type InstantRouteHandlerPayloadByType,
65
+ type InstantRouteHandlerType,
66
+ type InstantRouteHandlerBody,
67
+ OAuthHandler,
68
+ InstantOAuthError,
69
+ generateSchemaTypescriptFile,
70
+ collectSystemCatalogIdentNames,
71
+ validateSchema,
72
+ SchemaValidationError,
73
+ generatePermsTypescriptFile,
74
+ permsTypescriptFileToCode,
75
+ apiSchemaToInstantSchemaDef,
76
+ schemaTypescriptFileToInstantSchema,
77
+ version,
78
+ translatePlanSteps,
79
+ PlatformApi,
80
+ ProgressPromise,
81
+ exchangeCodeForToken,
82
+ exchangeRefreshToken,
83
+ clerkDomainFromPublishableKey,
84
+ i,
85
+ Webhooks,
86
+ WebhooksManager,
87
+ type WebhookAction,
88
+ type WebhookStatus,
89
+ type WebhookEventStatus,
90
+ type WebhookInfo,
91
+ type WebhookAttempt,
92
+ type WebhookEventInfo,
93
+ type WebhookEventsPage,
94
+ type WebhookBody,
95
+ type WebhookEntity,
96
+ type WebhookPayload,
97
+ type WebhookPayloadRecord,
98
+ type WebhookPayloadRecordFor,
99
+ type WebhookHandlerFn,
100
+ type WebhookHandlers,
101
+ type WebhookHelpers,
102
+ type CreateWebhookParams,
103
+ type UpdateWebhookParams,
104
+ };
105
+
106
+ export {
107
+ diffSchemas,
108
+ convertTxSteps,
109
+ isRenamePromptItem,
110
+ buildAutoRenameSelector,
111
+ type RenameResolveFn,
112
+ type MigrationTx,
113
+ type MigrationTxSpecific,
114
+ type MigrationTxTypes,
115
+ type Identifier,
116
+ } from './migrations.ts';
117
+
118
+ export {
119
+ BackupsManager,
120
+ backupZipName,
121
+ estimateZipSize,
122
+ formatFileSize,
123
+ toAppBackup,
124
+ type AppBackup,
125
+ type AppBackupFile,
126
+ type AppBackupStorageFile,
127
+ } from './backups.ts';
128
+
129
+ export {
130
+ type DownloadBackupArchiveOpts,
131
+ type BackupArchiveWriter,
132
+ type BackupDownloadProgress,
133
+ type BackupDownloadResult,
134
+ } from './backupDownload.ts';
135
+
136
+ export {
137
+ oauthCallbackURL,
138
+ GOOGLE_AUTHORIZATION_ENDPOINT,
139
+ GOOGLE_DISCOVERY_ENDPOINT,
140
+ GOOGLE_TOKEN_ENDPOINT,
141
+ APPLE_AUTHORIZATION_ENDPOINT,
142
+ APPLE_DISCOVERY_ENDPOINT,
143
+ APPLE_TOKEN_ENDPOINT,
144
+ LINKEDIN_AUTHORIZATION_ENDPOINT,
145
+ LINKEDIN_DISCOVERY_ENDPOINT,
146
+ LINKEDIN_TOKEN_ENDPOINT,
147
+ } from './consts.ts';
@@ -0,0 +1,56 @@
1
+ import { AnyBlob, AnyLink, MigrationTx } from './migrations.ts';
2
+ import { relationshipConstraints, RelationshipKinds } from './relationships.ts';
3
+
4
+ export const attrDefToNewAttrTx = (
5
+ attrInSchema: AnyBlob,
6
+ entityName: string,
7
+ createdName: string,
8
+ ): MigrationTx => {
9
+ return {
10
+ type: 'add-attr',
11
+ 'unique?': attrInSchema.config.unique,
12
+ 'value-type': 'blob',
13
+ cardinality: 'one',
14
+ identifier: {
15
+ namespace: entityName,
16
+ attrName: createdName,
17
+ },
18
+ 'required?': attrInSchema.required,
19
+ 'forward-identity': {
20
+ attrName: createdName,
21
+ namespace: entityName,
22
+ },
23
+ 'index?': attrInSchema.config.indexed,
24
+ 'checked-data-type':
25
+ attrInSchema.valueType !== 'json' ? attrInSchema.valueType : null,
26
+ };
27
+ };
28
+
29
+ export const linkDefToNewAttrTx = (link: AnyLink): MigrationTx => {
30
+ const relationship =
31
+ `${link.forward.has}-${link.reverse.has}` as RelationshipKinds;
32
+ const uniqueAndCardinality = relationshipConstraints[relationship];
33
+
34
+ return {
35
+ 'checked-data-type': null,
36
+ 'index?': false,
37
+ ...uniqueAndCardinality,
38
+ 'required?': !!link.forward.required,
39
+ identifier: {
40
+ attrName: link.forward.label,
41
+ namespace: link.forward.on,
42
+ },
43
+ 'value-type': 'ref',
44
+ type: 'add-attr',
45
+ 'forward-identity': {
46
+ attrName: link.forward.label,
47
+ namespace: link.forward.on,
48
+ },
49
+ 'on-delete': link.forward.onDelete,
50
+ 'on-delete-reverse': link.reverse.onDelete,
51
+ 'reverse-identity': {
52
+ attrName: link.reverse.label,
53
+ namespace: link.reverse.on,
54
+ },
55
+ };
56
+ };