@sidekickdb/platform 0.0.0 → 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 +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
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backupDownload.js","sourceRoot":"","sources":["../../src/backupDownload.ts"],"names":[],"mappings":"AA4FA,MAAM,sBAAsB,GAAG,CAAC,CAAC;AACjC,MAAM,sBAAsB,GAAG,GAAG,CA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,IAAI,EAAE,CAAC;QACP,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAE,KAAK,EAAE,cAAc,EAAE,QAAQ,EAAE,CAAC;IAC1E,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,sEAAsE;QACtE,oEAAoE;QACpE,6BAA6B;QAC7B,eAAe,CAAC,KAAK,EAAE,CAAC;QACxB,MAAM,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAC1C,MAAM,CAAC,CAAC;IACV,CAAC;AACH,CAAC","sourcesContent":["import type {\n AppBackup,\n AppBackupStorageFile,\n BackupsManager,\n} from './backups.ts';\n\nexport type BackupDownloadProgress = {\n entitiesCompleted: number;\n entitiesTotal: number | null;\n filesCompleted: number;\n filesTotal: number | null;\n // Compressed bytes written to the sink so far (the zip's on-disk size).\n zipBytes: number;\n // Uncompressed bytes read from source bodies, and the backup's known\n // uncompressed total — the numerator/denominator for a progress bar.\n // bytesTotal is null when the backup row carries no sizes.\n bytesRead: number;\n bytesTotal: number | null;\n // The entry currently being fetched in each phase; empty while that phase\n // isn't actively fetching, so a finished phase stops claiming a file.\n currentEntity: string;\n currentFile: string;\n};\n\nexport type BackupDownloadResult = {\n entities: number;\n files: number;\n zipBytes: number;\n};\n\n/**\n * The archive encoder {@link downloadBackupArchive} writes entries through,\n * supplied by the caller so this package doesn't depend on a zip\n * implementation. zip.js's `ZipWriter` satisfies it structurally, so\n * `new ZipWriter(sink, { zip64: true, signal })` works without an adapter.\n *\n * Implementations must handle archives past 4GB — for zip that means zip64,\n * without which the central-directory offsets wrap and the archive is\n * silently unreadable.\n */\nexport type BackupArchiveWriter = {\n add(\n name: string,\n input: ReadableStream<Uint8Array>,\n opts: { lastModDate: Date },\n ): Promise<unknown>;\n close(): Promise<unknown>;\n};\n\nexport type DownloadBackupArchiveOpts = {\n backup: AppBackup;\n /**\n * Fetches a presigned URL, resolving with the response body and rejecting\n * on a non-200 status. Put the status in the message (e.g. `HTTP 403`) —\n * it's surfaced to the user alongside the failing entry's name. The entity\n * files are served with `Content-Encoding: zstd`; browser fetch decodes\n * that transparently, other runtimes must decompress explicitly.\n */\n fetchBody: (\n url: string,\n signal: AbortSignal,\n ) => Promise<ReadableStream<Uint8Array>>;\n /**\n * Where the archive's bytes go. Closed after the last entry is written;\n * aborted when the download fails or is cancelled, so the caller can\n * discard partial output.\n */\n sink: WritableStream<Uint8Array>;\n /**\n * Builds the archive encoder over a sink that already counts progress and\n * carries the caller's sink's backpressure.\n */\n createWriter: (\n sink: WritableStream<Uint8Array>,\n signal: AbortSignal,\n ) => Promise<BackupArchiveWriter>;\n signal?: AbortSignal;\n onProgress?: (progress: BackupDownloadProgress) => void;\n /**\n * Retry policy for *opening* an entry's body (fetching its presigned URL and\n * getting a live response).\n * `attempts` is the total number of tries (default {@link DEFAULT_FETCH_ATTEMPTS});\n * `delayMs` is the base for exponential backoff (default {@link DEFAULT_RETRY_DELAY_MS}).\n *\n * This only covers failures before the writer starts consuming the body.\n * Once bytes have been written into the archive entry there's no way to\n * restart it without HTTP range/resume support, so a mid-stream failure\n * still fails the download.\n */\n retry?: { attempts?: number; delayMs?: number };\n};\n\nconst DEFAULT_FETCH_ATTEMPTS = 3;\nconst DEFAULT_RETRY_DELAY_MS = 500;\nconst MAX_RETRY_DELAY_MS = 5000;\n\n// Normalize caller-supplied numeric options so NaN/Infinity/non-integers can't\n// alter retry counts or pipeline bounds — fall back to the default instead.\nconst finitePositiveInt = (v: number | undefined, fallback: number): number =>\n v != null && Number.isInteger(v) && v > 0 ? v : fallback;\nconst finiteNonNegative = (v: number | undefined, fallback: number): number =>\n v != null && Number.isFinite(v) && v >= 0 ? v : fallback;\n\nconst isAbortError = (e: unknown): boolean =>\n (e as { name?: string })?.name === 'AbortError';\n\nconst errorMessage = (e: unknown): string =>\n e instanceof Error ? e.message : String(e);\n\n// A cancellable sleep: resolves after `ms`, or rejects if the signal aborts\n// first so backoff between retries doesn't outlive a cancelled download.\nconst delay = (ms: number, signal: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));\n };\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal.addEventListener('abort', onAbort, { once: true });\n });\n\n// Re-emits an already-read first chunk, then streams the rest from `reader`.\n// Past that first chunk read errors propagate to the consumer unchanged — by\n// then bytes are in the archive entry and it can't be restarted.\nfunction replayFrom(\n first: ReadableStreamReadResult<Uint8Array>,\n reader: ReadableStreamDefaultReader<Uint8Array>,\n): ReadableStream<Uint8Array> {\n let replayed = false;\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n if (!replayed) {\n replayed = true;\n if (first.done) {\n controller.close();\n return;\n }\n controller.enqueue(first.value);\n return;\n }\n const { done, value } = await reader.read();\n if (done) controller.close();\n else controller.enqueue(value);\n },\n async cancel(reason) {\n await reader.cancel(reason);\n },\n });\n}\n\n/**\n * Opens a body via `open`, retrying on transient failure with abortable\n * exponential backoff. `open` is re-invoked from scratch each attempt, so an\n * entity file re-mints its presigned URL. An abort propagates immediately; any\n * other final failure is wrapped by `describe` into a user-facing message\n * naming the entry.\n *\n * The first chunk is read inside the retry scope, so a body that connects but\n * fails on its first read is re-fetched too, since nothing has been written\n * to the archive yet. Only failures once bytes are flowing are treated as\n * unrecoverable.\n */\nasync function openWithRetry(\n open: () => Promise<ReadableStream<Uint8Array>>,\n opts: {\n signal: AbortSignal;\n attempts: number;\n delayMs: number;\n describe: (e: unknown) => string;\n },\n): Promise<ReadableStream<Uint8Array>> {\n let lastError: unknown;\n for (let attempt = 1; attempt <= opts.attempts; attempt++) {\n opts.signal.throwIfAborted();\n let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;\n try {\n const body = await open();\n reader = body.getReader();\n const first = await reader.read();\n return replayFrom(first, reader);\n } catch (e) {\n // Release the failed connection before retrying (or giving up).\n if (reader) reader.cancel().catch(() => {});\n if (isAbortError(e)) throw e;\n lastError = e;\n if (attempt < opts.attempts) {\n const backoff = Math.min(\n opts.delayMs * 2 ** (attempt - 1),\n MAX_RETRY_DELAY_MS,\n );\n await delay(backoff, opts.signal);\n }\n }\n }\n throw new Error(opts.describe(lastError));\n}\n\n/**\n * One archive entry whose body fetch has been started. `onWriting` runs when\n * the encoder begins consuming it (so progress reflects the entry actually\n * streaming); `onAdded` runs once it's fully written.\n */\ntype PreparedEntry = {\n name: string;\n input: ReadableStream<Uint8Array>;\n onWriting: () => void;\n onAdded: () => void;\n};\n\n/**\n * A thunk that fetches one entry (presigned URL + body) and resolves once the\n * body stream is available — not once it's fully downloaded. Called only when\n * the entry is about to be written, so its body never downloads ahead.\n */\ntype EntryThunk = () => Promise<PreparedEntry>;\n\n/**\n * Downloads a backup into a single archive written to `opts.sink`: entries\n * in the canonical restore order (`config.json`, then the\n * `entities/<etype>.jsonl` shards, then `files/<locationId>` storage blobs —\n * all entity files before any storage file), with the encoder writing\n * through a counting sink that awaits the caller's sink, so a fast source\n * can't outrun it and balloon memory.\n *\n * The runtime-specific pieces are injected: how to fetch a presigned URL\n * (`fetchBody`), where the bytes go (`sink`), and the archive encoder\n * (`createWriter`). Most callers reach this via\n * {@link BackupsManager.downloadArchive}.\n */\nexport async function downloadBackupArchive(\n opts: DownloadBackupArchiveOpts & {\n manager: Pick<\n BackupsManager,\n 'listFiles' | 'getFileUrl' | 'streamStorageFiles'\n >;\n },\n): Promise<BackupDownloadResult> {\n const { manager, backup, fetchBody, createWriter, onProgress } = opts;\n\n // Internal controller so a pipeline failure also tears down the\n // storage-files discovery stream and any in-flight body fetches.\n const abortController = new AbortController();\n if (opts.signal?.aborted) {\n abortController.abort();\n } else {\n opts.signal?.addEventListener('abort', () => abortController.abort(), {\n once: true,\n });\n }\n const signal = abortController.signal;\n\n let entitiesCompleted = 0;\n let entitiesTotal: number | null = null;\n let filesCompleted = 0;\n let filesTotal: number | null = null;\n let zipBytes = 0;\n let bytesRead = 0;\n let currentEntity = '';\n let currentFile = '';\n const bytesTotal =\n backup.uncompressedSize != null\n ? backup.uncompressedSize + (backup.filesSize ?? 0)\n : null;\n\n const retryAttempts = finitePositiveInt(\n opts.retry?.attempts,\n DEFAULT_FETCH_ATTEMPTS,\n );\n const retryDelayMs = finiteNonNegative(\n opts.retry?.delayMs,\n DEFAULT_RETRY_DELAY_MS,\n );\n\n const tick = () =>\n onProgress?.({\n entitiesCompleted,\n entitiesTotal,\n filesCompleted,\n filesTotal,\n zipBytes,\n bytesRead,\n bytesTotal,\n currentEntity,\n currentFile,\n });\n\n // Throttle by time: a large backup pushes many small chunks and ticking on\n // every one is wasted work. Phase changes tick() directly so they're still\n // immediate.\n const TICK_INTERVAL_MS = 100;\n let lastTickAt = 0;\n const throttledTick = () => {\n const now = Date.now();\n if (now - lastTickAt >= TICK_INTERVAL_MS) {\n lastTickAt = now;\n tick();\n }\n };\n\n // Count the uncompressed bytes of a source body for progress as it streams\n // into the archive.\n const countBytes = (\n body: ReadableStream<Uint8Array>,\n ): ReadableStream<Uint8Array> =>\n body.pipeThrough(\n new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n bytesRead += chunk.byteLength;\n throttledTick();\n controller.enqueue(chunk);\n },\n }),\n );\n\n // Storage-files discovery runs concurrently with the entity phase and is\n // drained eagerly into a queue. That isn't just overlap: it closes the\n // NDJSON connection quickly instead of holding it open (and at the mercy of\n // idle timeouts) while multi-GB blobs download. `queueHead` walks the array\n // in place, freeing each slot as it's consumed.\n const queue: (AppBackupStorageFile | undefined)[] = [];\n let queueHead = 0;\n let storageDone = false;\n let storageError: Error | null = null;\n let waitResolve: (() => void) | null = null;\n const notify = () => {\n const w = waitResolve;\n waitResolve = null;\n w?.();\n };\n\n // Never rejects: failures land in storageError for the drain loop to throw.\n const discovery = (async () => {\n let discoveryComplete = false;\n try {\n for await (const file of manager.streamStorageFiles(backup.id, {\n signal,\n })) {\n queue.push(file);\n filesTotal = (filesTotal ?? 0) + 1;\n throttledTick();\n notify();\n }\n discoveryComplete = true;\n } catch (e) {\n // The abort path is expected when the pipeline failed and we tore the\n // discovery down.\n if (!isAbortError(e)) {\n storageError = e as Error;\n }\n } finally {\n // A failed listing keeps the total unknown rather than reading as an\n // empty-but-complete storage phase.\n if (discoveryComplete && filesTotal == null) filesTotal = 0;\n storageDone = true;\n tick();\n notify();\n }\n })();\n\n // Entry write order is significant for restore: config.json first, then the\n // entities/*.jsonl shards, then files/<locationId>. In particular ALL entity\n // files must be written before ANY storage file. listFiles returns the\n // entity files in write order; this generator yields thunks for them in\n // order, then drains the storage queue. The consumer calls each thunk in turn\n // and writes it to completion before the next, so bodies download one at a\n // time and never ahead of the encoder.\n const thunks = (async function* (): AsyncGenerator<EntryThunk> {\n const files = await manager.listFiles(backup.id, { signal });\n if (files.length === 0) {\n throw new Error('No files found for this backup.');\n }\n // We write entries in the order the server returns them, and restore\n // requires config.json to be the first entry. Fail loudly rather than\n // build a zip that can't be restored.\n if (files[0].name !== 'config.json') {\n throw new Error(\n `Backup files came back in an unexpected order (expected config.json first, got \"${files[0].name}\").`,\n );\n }\n // config.json isn't a namespace — count only the entities/*.jsonl shards.\n entitiesTotal = files.filter((f) => f.name !== 'config.json').length;\n tick();\n\n for (const f of files) {\n yield async () => {\n const body = await openWithRetry(\n async () => {\n const url = await manager.getFileUrl(backup.id, f.name, { signal });\n return fetchBody(url, signal);\n },\n {\n signal,\n attempts: retryAttempts,\n delayMs: retryDelayMs,\n describe: (e) => `Failed to fetch ${f.name}: ${errorMessage(e)}.`,\n },\n );\n return {\n name: f.name,\n input: countBytes(body),\n onWriting: () => {\n currentEntity = f.name;\n currentFile = '';\n tick();\n },\n onAdded: () => {\n if (f.name !== 'config.json') entitiesCompleted++;\n tick();\n },\n };\n };\n }\n\n while (true) {\n if (storageError) throw storageError;\n // A caller abort while no fetch is in flight surfaces only in the\n // discovery stream, which swallows it as expected teardown — check\n // explicitly so a cancellation can't read as a complete storage phase\n // with files still undiscovered.\n signal.throwIfAborted();\n let file: AppBackupStorageFile | undefined;\n if (queueHead < queue.length) {\n file = queue[queueHead];\n queue[queueHead] = undefined;\n queueHead++;\n }\n if (file) {\n const storageFile = file;\n const label = storageFile.path || storageFile.locationId;\n yield async () => {\n const body = await openWithRetry(\n () => fetchBody(storageFile.url, signal),\n {\n signal,\n attempts: retryAttempts,\n delayMs: retryDelayMs,\n describe: (e) =>\n `Couldn't download storage file \"${label}\" (${errorMessage(e)}).`,\n },\n );\n return {\n name: `files/${storageFile.locationId}`,\n input: countBytes(body),\n onWriting: () => {\n currentEntity = '';\n currentFile = label;\n tick();\n },\n onAdded: () => {\n filesCompleted++;\n tick();\n },\n };\n };\n } else if (storageDone) {\n break;\n } else {\n await new Promise<void>((resolve) => {\n waitResolve = resolve;\n });\n }\n }\n\n if (storageError) throw storageError;\n })();\n\n const sinkWriter = opts.sink.getWriter();\n try {\n // Sink the archive encoder writes into: it tallies the encoded size for\n // progress, then forwards to the caller's sink. Awaiting the downstream\n // write propagates backpressure up into the encoder, so a fast source\n // can't outrun the sink and balloon memory.\n const countingSink = new WritableStream<Uint8Array>({\n async write(chunk) {\n zipBytes += chunk.byteLength;\n throttledTick();\n await sinkWriter.write(chunk);\n },\n async close() {\n await sinkWriter.close();\n tick();\n },\n async abort(reason) {\n await sinkWriter.abort(reason);\n },\n });\n\n const writer = await createWriter(countingSink, signal);\n\n for await (const thunk of thunks) {\n const entry = await thunk();\n entry.onWriting();\n await writer.add(entry.name, entry.input, {\n lastModDate: backup.backupAt,\n });\n entry.onAdded();\n }\n currentEntity = '';\n currentFile = '';\n tick();\n // A caller abort that lands after the last entry lets the generator\n // finish cleanly; don't close and return a complete-looking archive.\n signal.throwIfAborted();\n await writer.close();\n await discovery;\n tick();\n return { entities: entitiesCompleted, files: filesCompleted, zipBytes };\n } catch (e) {\n // Tear down the discovery stream and any in-flight body fetches so we\n // don't keep pulling from S3, and abort the caller's sink so it can\n // discard whatever it wrote.\n abortController.abort();\n await sinkWriter.abort(e).catch(() => {});\n throw e;\n }\n}\n"]}
@@ -0,0 +1,146 @@
1
+ import type { WithAuth } from '@sidekickdb/webhooks';
2
+ import { type BackupDownloadResult, type DownloadBackupArchiveOpts } from './backupDownload.ts';
3
+ /** A point-in-time snapshot of an app. */
4
+ export type AppBackup = {
5
+ /** Unique identifier for the backup. */
6
+ id: string;
7
+ /** Instant sequence number the snapshot was taken at. */
8
+ isn: string;
9
+ /** When the snapshot was taken. */
10
+ backupAt: Date;
11
+ /** Total size in bytes of the app's storage files at backup time, if known. */
12
+ filesSize: number | null;
13
+ /** Size in bytes of the app's database at backup time, if known. */
14
+ dbSize: number | null;
15
+ /**
16
+ * Total uncompressed size in bytes of the backup's entity files (what they
17
+ * take up unpacked on disk), if known.
18
+ */
19
+ uncompressedSize: number | null;
20
+ /** Human-readable label, e.g. "Automated Daily Snapshot". */
21
+ description: string | null;
22
+ /** When the backup stops being available for download. */
23
+ expiresAt: Date | null;
24
+ };
25
+ /**
26
+ * A file that makes up the backup payload: `config.json` or an
27
+ * `entities/<etype>.jsonl` shard.
28
+ */
29
+ export type AppBackupFile = {
30
+ name: string;
31
+ /** Size in bytes as stored (the entity shards are stored compressed). */
32
+ size: number;
33
+ };
34
+ /** A storage file captured in a backup, with a presigned download URL. */
35
+ export type AppBackupStorageFile = {
36
+ /**
37
+ * Stable id of the file's blob. A backup archive stores the blob at
38
+ * `files/<locationId>`.
39
+ */
40
+ locationId: string;
41
+ /** The path the user uploaded the file to. */
42
+ path: string | null;
43
+ /** Presigned URL for the file's contents. Expires after 12 hours. */
44
+ url: string;
45
+ };
46
+ type AppBackupResponse = {
47
+ id: string;
48
+ isn: string;
49
+ backup_at: string;
50
+ files_size: number | null;
51
+ db_size: number | null;
52
+ uncompressed_size: number | null;
53
+ description: string | null;
54
+ expires_at: string | null;
55
+ };
56
+ /** Converts a backup row as the server sends it into an {@link AppBackup}. */
57
+ export declare function toAppBackup(row: AppBackupResponse): AppBackup;
58
+ /** Suggested filename for a backup archive. */
59
+ export declare function backupZipName(backup: AppBackup): string;
60
+ /**
61
+ * Formats a byte count the way macOS/Finder reports file sizes: decimal
62
+ * (1000-based) units with SI labels, so the number lines up with what lands
63
+ * on disk.
64
+ */
65
+ export declare function formatFileSize(n: number): string;
66
+ /**
67
+ * Estimated size range for a backup's zip archive, or null when the backup
68
+ * row carries no sizes. Upper bound: everything stored uncompressed (STORE
69
+ * mode and/or files that don't compress). Lower bound: everything compressed
70
+ * at a ~4x DEFLATE ratio, best case for text/JSON, but storage files vary
71
+ * wildly (raw text compresses well, already-compressed images/videos don't).
72
+ * The same divisor applies to both since the file types aren't visible from
73
+ * here; the actual zip lands somewhere inside the range.
74
+ */
75
+ export declare function estimateZipSize(backup: AppBackup): {
76
+ min: number;
77
+ max: number;
78
+ } | null;
79
+ /**
80
+ * Read-only API for an app's backups.
81
+ *
82
+ * A backup archive has a canonical entry order that restore relies on:
83
+ * `config.json` first, then every `entities/<etype>.jsonl` shard, then the
84
+ * `files/<locationId>` storage blobs. In particular ALL entity files must
85
+ * come before ANY storage file, so a restore can process the archive in a
86
+ * single streaming pass: `config.json` sets up the schema, the `$files`
87
+ * entities register file metadata, and only then can each blob be matched
88
+ * to its entity. {@link downloadArchive} implements that order end to end;
89
+ * {@link listFiles} (which returns the entity files already in write order)
90
+ * and {@link streamStorageFiles} are the pieces for building a custom
91
+ * pipeline.
92
+ */
93
+ export declare class BackupsManager {
94
+ #private;
95
+ constructor(opts: {
96
+ appId: string;
97
+ apiURI: string;
98
+ withAuth: WithAuth;
99
+ });
100
+ /**
101
+ * Returns the app's downloadable (non-expired) backups, newest first.
102
+ */
103
+ list(opts?: {
104
+ signal?: AbortSignal;
105
+ }): Promise<AppBackup[]>;
106
+ /**
107
+ * Returns the backup's entity files (`config.json` and the
108
+ * `entities/<etype>.jsonl` shards) in archive write order. Storage blobs
109
+ * are not included; discover those with {@link streamStorageFiles}.
110
+ */
111
+ listFiles(backupId: string, opts?: {
112
+ signal?: AbortSignal;
113
+ }): Promise<AppBackupFile[]>;
114
+ /**
115
+ * Returns a presigned download URL for one of the backup's entity files.
116
+ * The URL expires after 1 hour, so fetch it right before downloading.
117
+ *
118
+ * The entity files are stored zstd-compressed (the response carries
119
+ * `Content-Encoding: zstd`); decompress to get the raw JSON/JSONL.
120
+ */
121
+ getFileUrl(backupId: string, name: string, opts?: {
122
+ signal?: AbortSignal;
123
+ }): Promise<string>;
124
+ /**
125
+ * Streams every storage file captured in the backup, each with a presigned
126
+ * download URL. Completes without yielding anything when the app has no
127
+ * storage files.
128
+ *
129
+ * The server ends a healthy stream with a terminal sentinel; if the stream
130
+ * closes without it (a server-side failure truncated the listing), this
131
+ * throws instead of silently under-reporting files.
132
+ */
133
+ streamStorageFiles(backupId: string, opts?: {
134
+ signal?: AbortSignal;
135
+ }): AsyncGenerator<AppBackupStorageFile, void, void>;
136
+ /**
137
+ * Downloads the backup into a single zip archive written to `opts.sink`,
138
+ * entries in the canonical restore order described above. The caller
139
+ * supplies the runtime-specific pieces — how to fetch a presigned URL,
140
+ * where the bytes go, and the archive encoder (e.g. zip.js's `ZipWriter`);
141
+ * see {@link DownloadBackupArchiveOpts}.
142
+ */
143
+ downloadArchive(opts: DownloadBackupArchiveOpts): Promise<BackupDownloadResult>;
144
+ }
145
+ export {};
146
+ //# sourceMappingURL=backups.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backups.d.ts","sourceRoot":"","sources":["../../src/backups.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAErD,OAAO,EAEL,KAAK,oBAAoB,EACzB,KAAK,yBAAyB,EAC/B,MAAM,qBAAqB,CAAC;AAE7B,0CAA0C;AAC1C,MAAM,MAAM,SAAS,GAAG;IACtB,wCAAwC;IACxC,EAAE,EAAE,MAAM,CAAC;IACX,yDAAyD;IACzD,GAAG,EAAE,MAAM,CAAC;IACZ,mCAAmC;I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AAM,CAkBhD;AAED;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,SAAS,GAChB;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAKrC;AAuDD;;;;;;;;;;;;;GAaG;AACH,qBAAa,cAAc;;gBAKb,IAAI,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,QAAQ,CAAA;KAAE;IAmBvE;;OAEG;IACG,IAAI,CAAC,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAAG,OAAO,CAAC,SAAS,EAAE,CAAC;IAQjE;;;;OAIG;IACG,SAAS,CACb,QAAQ,EAAE,MAAM,EAChB,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAC9B,OAAO,CAAC,aAAa,EAAE,CAAC;IAQ3B;;;;;;OAMG;IACG,UAAU,CACd,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAC9B,OAAO,CAAC,MAAM,CAAC;IAQlB;;;;;;;;OAQG;IACI,kBAAkB,CACvB,QAAQ,EAAE,MAAM,EAChB,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAC9B,cAAc,CAAC,oBAAoB,EAAE,IAAI,EAAE,IAAI,CAAC;IAmDnD;;;;;;OAMG;IACH,eAAe,CACb,IAAI,EAAE,yBAAyB,GAC9B,OAAO,CAAC,oBAAoB,CAAC;CAGjC"}
@@ -0,0 +1,237 @@
1
+ import { InstantAPIError, version as coreVersion } from '@sidekickdb/core';
2
+ import version from "./version.js";
3
+ import { downloadBackupArchive, } from "./backupDownload.js";
4
+ /** Converts a backup row as the server sends it into an {@link AppBackup}. */
5
+ export function toAppBackup(row) {
6
+ return {
7
+ id: row.id,
8
+ isn: row.isn,
9
+ backupAt: new Date(row.backup_at),
10
+ filesSize: row.files_size,
11
+ dbSize: row.db_size,
12
+ uncompressedSize: row.uncompressed_size,
13
+ description: row.description,
14
+ expiresAt: row.expires_at ? new Date(row.expires_at) : null,
15
+ };
16
+ }
17
+ /** Suggested filename for a backup archive. */
18
+ export function backupZipName(backup) {
19
+ const safe = backup.backupAt.toISOString().replace(/[:.]/g, '-');
20
+ return `instant-backup-${safe}.zip`;
21
+ }
22
+ /**
23
+ * Formats a byte count the way macOS/Finder reports file sizes: decimal
24
+ * (1000-based) units with SI labels, so the number lines up with what lands
25
+ * on disk.
26
+ */
27
+ export function formatFileSize(n) {
28
+ if (n < 1000)
29
+ return `${n} B`;
30
+ const units = ['KB', 'MB', 'GB', 'TB'];
31
+ let i = -1;
32
+ let v = n;
33
+ do {
34
+ v /= 1000;
35
+ i++;
36
+ } while (v >= 1000 && i < units.length - 1);
37
+ let digits = v < 10 ? 2 : v < 100 ? 1 : 0;
38
+ // Rounding can cross a unit boundary (999,500 would read "1000 KB");
39
+ // promote to the next unit instead.
40
+ if (Number(v.toFixed(digits)) >= 1000 && i < units.length - 1) {
41
+ v /= 1000;
42
+ i++;
43
+ digits = 2;
44
+ }
45
+ return `${v.toFixed(digits)} ${units[i]}`;
46
+ }
47
+ /**
48
+ * Estimated size range for a backup's zip archive, or null when the backup
49
+ * row carries no sizes. Upper bound: everything stored uncompressed (STORE
50
+ * mode and/or files that don't compress). Lower bound: everything compressed
51
+ * at a ~4x DEFLATE ratio, best case for text/JSON, but storage files vary
52
+ * wildly (raw text compresses well, already-compressed images/videos don't).
53
+ * The same divisor applies to both since the file types aren't visible from
54
+ * here; the actual zip lands somewhere inside the range.
55
+ */
56
+ export function estimateZipSize(backup) {
57
+ const backupBytes = backup.uncompressedSize ?? backup.dbSize;
58
+ if (backupBytes == null || backup.filesSize == null)
59
+ return null;
60
+ const max = backupBytes + backup.filesSize;
61
+ return { min: Math.round(max / 4), max };
62
+ }
63
+ function authHeaders(token) {
64
+ return {
65
+ authorization: `Bearer ${token}`,
66
+ 'Instant-Platform-Version': version,
67
+ 'Instant-Core-Version': coreVersion,
68
+ 'X-Instant-Source': 'platform-sdk',
69
+ 'X-Instant-Version': version,
70
+ };
71
+ }
72
+ async function apiError(res) {
73
+ const body = await res.text();
74
+ try {
75
+ return new InstantAPIError({ status: res.status, body: JSON.parse(body) });
76
+ }
77
+ catch (_e) {
78
+ return new InstantAPIError({
79
+ status: res.status,
80
+ body: { type: undefined, message: body },
81
+ });
82
+ }
83
+ }
84
+ async function* ndjsonLines(body) {
85
+ const reader = body.getReader();
86
+ try {
87
+ const decoder = new TextDecoder();
88
+ let buf = '';
89
+ while (true) {
90
+ const { done, value } = await reader.read();
91
+ if (done)
92
+ break;
93
+ buf += decoder.decode(value, { stream: true });
94
+ let nl = buf.indexOf('\n');
95
+ while (nl !== -1) {
96
+ const line = buf.slice(0, nl).trim();
97
+ buf = buf.slice(nl + 1);
98
+ if (line.length > 0) {
99
+ yield JSON.parse(line);
100
+ }
101
+ nl = buf.indexOf('\n');
102
+ }
103
+ }
104
+ const line = buf.trim();
105
+ if (line.length > 0) {
106
+ yield JSON.parse(line);
107
+ }
108
+ }
109
+ finally {
110
+ // Also releases the connection when the consumer stops iterating early.
111
+ await reader.cancel().catch(() => { });
112
+ }
113
+ }
114
+ /**
115
+ * Read-only API for an app's backups.
116
+ *
117
+ * A backup archive has a canonical entry order that restore relies on:
118
+ * `config.json` first, then every `entities/<etype>.jsonl` shard, then the
119
+ * `files/<locationId>` storage blobs. In particular ALL entity files must
120
+ * come before ANY storage file, so a restore can process the archive in a
121
+ * single streaming pass: `config.json` sets up the schema, the `$files`
122
+ * entities register file metadata, and only then can each blob be matched
123
+ * to its entity. {@link downloadArchive} implements that order end to end;
124
+ * {@link listFiles} (which returns the entity files already in write order)
125
+ * and {@link streamStorageFiles} are the pieces for building a custom
126
+ * pipeline.
127
+ */
128
+ export class BackupsManager {
129
+ #appId;
130
+ #apiURI;
131
+ #withAuth;
132
+ constructor(opts) {
133
+ this.#appId = opts.appId;
134
+ this.#apiURI = opts.apiURI;
135
+ this.#withAuth = opts.withAuth;
136
+ }
137
+ #getJson(path, signal) {
138
+ return this.#withAuth(async (token) => {
139
+ const res = await fetch(`${this.#apiURI}${path}`, {
140
+ headers: authHeaders(token),
141
+ signal,
142
+ });
143
+ if (res.status !== 200) {
144
+ throw await apiError(res);
145
+ }
146
+ return res.json();
147
+ });
148
+ }
149
+ /**
150
+ * Returns the app's downloadable (non-expired) backups, newest first.
151
+ */
152
+ async list(opts) {
153
+ const res = await this.#getJson(`/dash/apps/${this.#appId}/backups`, opts?.signal);
154
+ return (res.backups || []).map(toAppBackup);
155
+ }
156
+ /**
157
+ * Returns the backup's entity files (`config.json` and the
158
+ * `entities/<etype>.jsonl` shards) in archive write order. Storage blobs
159
+ * are not included; discover those with {@link streamStorageFiles}.
160
+ */
161
+ async listFiles(backupId, opts) {
162
+ const res = await this.#getJson(`/dash/apps/${this.#appId}/backups/${backupId}/files`, opts?.signal);
163
+ return (res.files || []);
164
+ }
165
+ /**
166
+ * Returns a presigned download URL for one of the backup's entity files.
167
+ * The URL expires after 1 hour, so fetch it right before downloading.
168
+ *
169
+ * The entity files are stored zstd-compressed (the response carries
170
+ * `Content-Encoding: zstd`); decompress to get the raw JSON/JSONL.
171
+ */
172
+ async getFileUrl(backupId, name, opts) {
173
+ const res = await this.#getJson(`/dash/apps/${this.#appId}/backups/${backupId}/file-url?name=${encodeURIComponent(name)}`, opts?.signal);
174
+ return res.url;
175
+ }
176
+ /**
177
+ * Streams every storage file captured in the backup, each with a presigned
178
+ * download URL. Completes without yielding anything when the app has no
179
+ * storage files.
180
+ *
181
+ * The server ends a healthy stream with a terminal sentinel; if the stream
182
+ * closes without it (a server-side failure truncated the listing), this
183
+ * throws instead of silently under-reporting files.
184
+ */
185
+ async *streamStorageFiles(backupId, opts) {
186
+ const res = await this.#withAuth(async (token) => {
187
+ const res = await fetch(`${this.#apiURI}/dash/apps/${this.#appId}/backups/${backupId}/storage-files`, { headers: authHeaders(token), signal: opts?.signal });
188
+ if (res.status !== 200) {
189
+ throw await apiError(res);
190
+ }
191
+ return res;
192
+ });
193
+ if (!res.body) {
194
+ throw new Error('Storage file listing returned no body.');
195
+ }
196
+ let complete = false;
197
+ for await (const line of ndjsonLines(res.body)) {
198
+ if (line.done === true) {
199
+ complete = true;
200
+ break;
201
+ }
202
+ // A file record always carries a locationId and url; anything else is
203
+ // corruption, and skipping it would silently omit a file from the
204
+ // archive.
205
+ if (typeof line.locationId !== 'string' ||
206
+ line.locationId.length === 0 ||
207
+ // The locationId becomes the archive entry path `files/<locationId>`;
208
+ // reject separators and control characters that could escape it.
209
+ /[/\\\u0000-\u001f\u007f]/.test(line.locationId) ||
210
+ line.locationId === '.' ||
211
+ line.locationId === '..' ||
212
+ typeof line.url !== 'string' ||
213
+ line.url.length === 0) {
214
+ throw new Error('Storage file listing returned a malformed record. Please retry the download.');
215
+ }
216
+ yield {
217
+ locationId: line.locationId,
218
+ path: line.path ?? null,
219
+ url: line.url,
220
+ };
221
+ }
222
+ if (!complete) {
223
+ throw new Error('Storage file listing ended before it finished. Please retry the download.');
224
+ }
225
+ }
226
+ /**
227
+ * Downloads the backup into a single zip archive written to `opts.sink`,
228
+ * entries in the canonical restore order described above. The caller
229
+ * supplies the runtime-specific pieces — how to fetch a presigned URL,
230
+ * where the bytes go, and the archive encoder (e.g. zip.js's `ZipWriter`);
231
+ * see {@link DownloadBackupArchiveOpts}.
232
+ */
233
+ downloadArchive(opts) {
234
+ return downloadBackupArchive({ manager: this, ...opts });
235
+ }
236
+ }
237
+ //# sourceMappingURL=backups.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"backups.js","sourceRoot":"","sources":["../../src/backups.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,OAAO,IAAI,WAAW,EAAE,MAAM,kBAAkB,C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O,qBAAqB,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,IAAI,EAAE,CAAC,CAAC;IAC3D,CAAC;CACF","sourcesContent":["import { InstantAPIError, version as coreVersion } from '@sidekickdb/core';\nimport type { WithAuth } from '@sidekickdb/webhooks';\nimport version from './version.ts';\nimport {\n downloadBackupArchive,\n type BackupDownloadResult,\n type DownloadBackupArchiveOpts,\n} from './backupDownload.ts';\n\n/** A point-in-time snapshot of an app. */\nexport type AppBackup = {\n /** Unique identifier for the backup. */\n id: string;\n /** Instant sequence number the snapshot was taken at. */\n isn: string;\n /** When the snapshot was taken. */\n backupAt: Date;\n /** Total size in bytes of the app's storage files at backup time, if known. */\n filesSize: number | null;\n /** Size in bytes of the app's database at backup time, if known. */\n dbSize: number | null;\n /**\n * Total uncompressed size in bytes of the backup's entity files (what they\n * take up unpacked on disk), if known.\n */\n uncompressedSize: number | null;\n /** Human-readable label, e.g. \"Automated Daily Snapshot\". */\n description: string | null;\n /** When the backup stops being available for download. */\n expiresAt: Date | null;\n};\n\n/**\n * A file that makes up the backup payload: `config.json` or an\n * `entities/<etype>.jsonl` shard.\n */\nexport type AppBackupFile = {\n name: string;\n /** Size in bytes as stored (the entity shards are stored compressed). */\n size: number;\n};\n\n/** A storage file captured in a backup, with a presigned download URL. */\nexport type AppBackupStorageFile = {\n /**\n * Stable id of the file's blob. A backup archive stores the blob at\n * `files/<locationId>`.\n */\n locationId: string;\n /** The path the user uploaded the file to. */\n path: string | null;\n /** Presigned URL for the file's contents. Expires after 12 hours. */\n url: string;\n};\n\ntype AppBackupResponse = {\n id: string;\n isn: string;\n backup_at: string;\n files_size: number | null;\n db_size: number | null;\n uncompressed_size: number | null;\n description: string | null;\n expires_at: string | null;\n};\n\n/** Converts a backup row as the server sends it into an {@link AppBackup}. */\nexport function toAppBackup(row: AppBackupResponse): AppBackup {\n return {\n id: row.id,\n isn: row.isn,\n backupAt: new Date(row.backup_at),\n filesSize: row.files_size,\n dbSize: row.db_size,\n uncompressedSize: row.uncompressed_size,\n description: row.description,\n expiresAt: row.expires_at ? new Date(row.expires_at) : null,\n };\n}\n\n/** Suggested filename for a backup archive. */\nexport function backupZipName(backup: AppBackup): string {\n const safe = backup.backupAt.toISOString().replace(/[:.]/g, '-');\n return `instant-backup-${safe}.zip`;\n}\n\n/**\n * Formats a byte count the way macOS/Finder reports file sizes: decimal\n * (1000-based) units with SI labels, so the number lines up with what lands\n * on disk.\n */\nexport function formatFileSize(n: number): string {\n if (n < 1000) return `${n} B`;\n const units = ['KB', 'MB', 'GB', 'TB'];\n let i = -1;\n let v = n;\n do {\n v /= 1000;\n i++;\n } while (v >= 1000 && i < units.length - 1);\n let digits = v < 10 ? 2 : v < 100 ? 1 : 0;\n // Rounding can cross a unit boundary (999,500 would read \"1000 KB\");\n // promote to the next unit instead.\n if (Number(v.toFixed(digits)) >= 1000 && i < units.length - 1) {\n v /= 1000;\n i++;\n digits = 2;\n }\n return `${v.toFixed(digits)} ${units[i]}`;\n}\n\n/**\n * Estimated size range for a backup's zip archive, or null when the backup\n * row carries no sizes. Upper bound: everything stored uncompressed (STORE\n * mode and/or files that don't compress). Lower bound: everything compressed\n * at a ~4x DEFLATE ratio, best case for text/JSON, but storage files vary\n * wildly (raw text compresses well, already-compressed images/videos don't).\n * The same divisor applies to both since the file types aren't visible from\n * here; the actual zip lands somewhere inside the range.\n */\nexport function estimateZipSize(\n backup: AppBackup,\n): { min: number; max: number } | null {\n const backupBytes = backup.uncompressedSize ?? backup.dbSize;\n if (backupBytes == null || backup.filesSize == null) return null;\n const max = backupBytes + backup.filesSize;\n return { min: Math.round(max / 4), max };\n}\n\nfunction authHeaders(token: string): Record<string, string> {\n return {\n authorization: `Bearer ${token}`,\n 'Instant-Platform-Version': version,\n 'Instant-Core-Version': coreVersion,\n 'X-Instant-Source': 'platform-sdk',\n 'X-Instant-Version': version,\n };\n}\n\nasync function apiError(res: Response): Promise<InstantAPIError> {\n const body = await res.text();\n try {\n return new InstantAPIError({ status: res.status, body: JSON.parse(body) });\n } catch (_e) {\n return new InstantAPIError({\n status: res.status,\n body: { type: undefined, message: body },\n });\n }\n}\n\nasync function* ndjsonLines(\n body: ReadableStream<Uint8Array>,\n): AsyncGenerator<any, void, void> {\n const reader = body.getReader();\n try {\n const decoder = new TextDecoder();\n let buf = '';\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buf += decoder.decode(value, { stream: true });\n let nl = buf.indexOf('\\n');\n while (nl !== -1) {\n const line = buf.slice(0, nl).trim();\n buf = buf.slice(nl + 1);\n if (line.length > 0) {\n yield JSON.parse(line);\n }\n nl = buf.indexOf('\\n');\n }\n }\n const line = buf.trim();\n if (line.length > 0) {\n yield JSON.parse(line);\n }\n } finally {\n // Also releases the connection when the consumer stops iterating early.\n await reader.cancel().catch(() => {});\n }\n}\n\n/**\n * Read-only API for an app's backups.\n *\n * A backup archive has a canonical entry order that restore relies on:\n * `config.json` first, then every `entities/<etype>.jsonl` shard, then the\n * `files/<locationId>` storage blobs. In particular ALL entity files must\n * come before ANY storage file, so a restore can process the archive in a\n * single streaming pass: `config.json` sets up the schema, the `$files`\n * entities register file metadata, and only then can each blob be matched\n * to its entity. {@link downloadArchive} implements that order end to end;\n * {@link listFiles} (which returns the entity files already in write order)\n * and {@link streamStorageFiles} are the pieces for building a custom\n * pipeline.\n */\nexport class BackupsManager {\n #appId: string;\n #apiURI: string;\n #withAuth: WithAuth;\n\n constructor(opts: { appId: string; apiURI: string; withAuth: WithAuth }) {\n this.#appId = opts.appId;\n this.#apiURI = opts.apiURI;\n this.#withAuth = opts.withAuth;\n }\n\n #getJson(path: string, signal?: AbortSignal): Promise<any> {\n return this.#withAuth(async (token) => {\n const res = await fetch(`${this.#apiURI}${path}`, {\n headers: authHeaders(token),\n signal,\n });\n if (res.status !== 200) {\n throw await apiError(res);\n }\n return res.json();\n });\n }\n\n /**\n * Returns the app's downloadable (non-expired) backups, newest first.\n */\n async list(opts?: { signal?: AbortSignal }): Promise<AppBackup[]> {\n const res = await this.#getJson(\n `/dash/apps/${this.#appId}/backups`,\n opts?.signal,\n );\n return ((res.backups || []) as AppBackupResponse[]).map(toAppBackup);\n }\n\n /**\n * Returns the backup's entity files (`config.json` and the\n * `entities/<etype>.jsonl` shards) in archive write order. Storage blobs\n * are not included; discover those with {@link streamStorageFiles}.\n */\n async listFiles(\n backupId: string,\n opts?: { signal?: AbortSignal },\n ): Promise<AppBackupFile[]> {\n const res = await this.#getJson(\n `/dash/apps/${this.#appId}/backups/${backupId}/files`,\n opts?.signal,\n );\n return (res.files || []) as AppBackupFile[];\n }\n\n /**\n * Returns a presigned download URL for one of the backup's entity files.\n * The URL expires after 1 hour, so fetch it right before downloading.\n *\n * The entity files are stored zstd-compressed (the response carries\n * `Content-Encoding: zstd`); decompress to get the raw JSON/JSONL.\n */\n async getFileUrl(\n backupId: string,\n name: string,\n opts?: { signal?: AbortSignal },\n ): Promise<string> {\n const res = await this.#getJson(\n `/dash/apps/${this.#appId}/backups/${backupId}/file-url?name=${encodeURIComponent(name)}`,\n opts?.signal,\n );\n return res.url as string;\n }\n\n /**\n * Streams every storage file captured in the backup, each with a presigned\n * download URL. Completes without yielding anything when the app has no\n * storage files.\n *\n * The server ends a healthy stream with a terminal sentinel; if the stream\n * closes without it (a server-side failure truncated the listing), this\n * throws instead of silently under-reporting files.\n */\n async *streamStorageFiles(\n backupId: string,\n opts?: { signal?: AbortSignal },\n ): AsyncGenerator<AppBackupStorageFile, void, void> {\n const res = await this.#withAuth(async (token) => {\n const res = await fetch(\n `${this.#apiURI}/dash/apps/${this.#appId}/backups/${backupId}/storage-files`,\n { headers: authHeaders(token), signal: opts?.signal },\n );\n if (res.status !== 200) {\n throw await apiError(res);\n }\n return res;\n });\n if (!res.body) {\n throw new Error('Storage file listing returned no body.');\n }\n let complete = false;\n for await (const line of ndjsonLines(res.body)) {\n if (line.done === true) {\n complete = true;\n break;\n }\n // A file record always carries a locationId and url; anything else is\n // corruption, and skipping it would silently omit a file from the\n // archive.\n if (\n typeof line.locationId !== 'string' ||\n line.locationId.length === 0 ||\n // The locationId becomes the archive entry path `files/<locationId>`;\n // reject separators and control characters that could escape it.\n /[/\\\\\\u0000-\\u001f\\u007f]/.test(line.locationId) ||\n line.locationId === '.' ||\n line.locationId === '..' ||\n typeof line.url !== 'string' ||\n line.url.length === 0\n ) {\n throw new Error(\n 'Storage file listing returned a malformed record. Please retry the download.',\n );\n }\n yield {\n locationId: line.locationId,\n path: line.path ?? null,\n url: line.url,\n };\n }\n if (!complete) {\n throw new Error(\n 'Storage file listing ended before it finished. Please retry the download.',\n );\n }\n }\n\n /**\n * Downloads the backup into a single zip archive written to `opts.sink`,\n * entries in the canonical restore order described above. The caller\n * supplies the runtime-specific pieces — how to fetch a presigned URL,\n * where the bytes go, and the archive encoder (e.g. zip.js's `ZipWriter`);\n * see {@link DownloadBackupArchiveOpts}.\n */\n downloadArchive(\n opts: DownloadBackupArchiveOpts,\n ): Promise<BackupDownloadResult> {\n return downloadBackupArchive({ manager: this, ...opts });\n }\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export declare function clerkDomainFromPublishableKey(key: string): string | null;
2
+ //# sourceMappingURL=clerk.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clerk.d.ts","sourceRoot":"","sources":["../../src/clerk.ts"],"names":[],"mappings":"AAaA,wBAAgB,6BAA6B,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAUxE"}
@@ -0,0 +1,26 @@
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) {
7
+ try {
8
+ return Buffer.from(s, 'base64').toString('utf-8');
9
+ }
10
+ catch (e) {
11
+ return Buffer.from(s, 'base64url').toString('utf-8');
12
+ }
13
+ }
14
+ export function clerkDomainFromPublishableKey(key) {
15
+ try {
16
+ const parts = key.split('_');
17
+ const domainPartB64 = parts[parts.length - 1];
18
+ const domainPart = base64Decode(domainPartB64);
19
+ return domainPart.replace('$', '');
20
+ }
21
+ catch (e) {
22
+ console.error('Error getting domain from clerk key', e);
23
+ return null;
24
+ }
25
+ }
26
+ //# sourceMappingURL=clerk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clerk.js","sourceRoot":"","sources":["../../src/clerk.ts"],"names":[],"mappings":"AAAA,iEAAiE;AACjE,mEAAmE;AACnE,iEAAiE;AACjE,iEAAiE;AACjE,0DAA0D;AAC1D,SAAS,YAAY,CAAC,CAAS;IAC7B,IAAI,CAAC;QACH,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,QAAQ,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACpD,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;IACvD,CAAC;AACH,CAAC;AAED,MAAM,UAAU,6BAA6B,CAAC,GAAW;IACvD,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QAC7B,MAAM,aAAa,GAAG,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;QAC9C,MAAM,UAAU,GAAG,YAAY,CAAC,aAAa,CAAC,CAAC;QAC/C,OAAO,UAAU,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACrC,CAAC;IAAC,OAAO,CAAC,EAAE,CAAC;QACX,OAAO,CAAC,KAAK,CAAC,qCAAqC,EAAE,CAAC,CAAC,CAAC;QACxD,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["// Base64 decode, switching to url-safe decode if we hit an error\n// Can't be sure which method Clerk uses because you can't generate\n// `+` or `/` with characters that go in a normal host. Urls with\n// chinese characters exist, they might encode to `+` or `/`, and\n// Clerk might support them, so we'll be safe and do both.\nfunction base64Decode(s: string) {\n try {\n return Buffer.from(s, 'base64').toString('utf-8');\n } catch (e) {\n return Buffer.from(s, 'base64url').toString('utf-8');\n }\n}\n\nexport function clerkDomainFromPublishableKey(key: string): string | null {\n try {\n const parts = key.split('_');\n const domainPartB64 = parts[parts.length - 1];\n const domainPart = base64Decode(domainPartB64);\n return domainPart.replace('$', '');\n } catch (e) {\n console.error('Error getting domain from clerk key', e);\n return null;\n }\n}\n"]}
@@ -0,0 +1,11 @@
1
+ export declare function oauthCallbackURL(apiURI: string): string;
2
+ export declare const GOOGLE_AUTHORIZATION_ENDPOINT = "https://accounts.google.com/o/oauth2/v2/auth";
3
+ export declare const GOOGLE_TOKEN_ENDPOINT = "https://oauth2.googleapis.com/token";
4
+ export declare const GOOGLE_DISCOVERY_ENDPOINT = "https://accounts.google.com/.well-known/openid-configuration";
5
+ export declare const APPLE_AUTHORIZATION_ENDPOINT = "https://appleid.apple.com/auth/authorize";
6
+ export declare const APPLE_TOKEN_ENDPOINT = "https://appleid.apple.com/auth/token";
7
+ export declare const APPLE_DISCOVERY_ENDPOINT = "https://appleid.apple.com/.well-known/openid-configuration";
8
+ export declare const LINKEDIN_AUTHORIZATION_ENDPOINT = "https://www.linkedin.com/oauth/v2/authorization";
9
+ export declare const LINKEDIN_TOKEN_ENDPOINT = "https://www.linkedin.com/oauth/v2/accessToken";
10
+ export declare const LINKEDIN_DISCOVERY_ENDPOINT = "https://www.linkedin.com/oauth/.well-known/openid-configuration";
11
+ //# sourceMappingURL=consts.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"consts.d.ts","sourceRoot":"","sources":["../../src/consts.ts"],"names":[],"mappings":"AAAA,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,MAAM,UAE9C;AAED,eAAO,MAAM,6BAA6B,iDACM,CAAC;AACjD,eAAO,MAAM,qBAAqB,wCAAwC,CAAC;AAC3E,eAAO,MAAM,yBAAyB,iEAC0B,CAAC;AAEjE,eAAO,MAAM,4BAA4B,6CACG,CAAC;AAC7C,eAAO,MAAM,oBAAoB,yCAAyC,CAAC;AAC3E,eAAO,MAAM,wBAAwB,+DACyB,CAAC;AAE/D,eAAO,MAAM,+BAA+B,oDACO,CAAC;AACpD,eAAO,MAAM,uBAAuB,kDACa,CAAC;AAClD,eAAO,MAAM,2BAA2B,oEAC2B,CAAC"}
@@ -0,0 +1,13 @@
1
+ export function oauthCallbackURL(apiURI) {
2
+ return `${apiURI.replace(/\/+$/, '')}/runtime/oauth/callback`;
3
+ }
4
+ export const GOOGLE_AUTHORIZATION_ENDPOINT = 'https://accounts.google.com/o/oauth2/v2/auth';
5
+ export const GOOGLE_TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token';
6
+ export const GOOGLE_DISCOVERY_ENDPOINT = 'https://accounts.google.com/.well-known/openid-configuration';
7
+ export const APPLE_AUTHORIZATION_ENDPOINT = 'https://appleid.apple.com/auth/authorize';
8
+ export const APPLE_TOKEN_ENDPOINT = 'https://appleid.apple.com/auth/token';
9
+ export const APPLE_DISCOVERY_ENDPOINT = 'https://appleid.apple.com/.well-known/openid-configuration';
10
+ export const LINKEDIN_AUTHORIZATION_ENDPOINT = 'https://www.linkedin.com/oauth/v2/authorization';
11
+ export const LINKEDIN_TOKEN_ENDPOINT = 'https://www.linkedin.com/oauth/v2/accessToken';
12
+ export const LINKEDIN_DISCOVERY_ENDPOINT = 'https://www.linkedin.com/oauth/.well-known/openid-configuration';
13
+ //# sourceMappingURL=consts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"consts.js","sourceRoot":"","sources":["../../src/consts.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,gBAAgB,CAAC,MAAc;IAC7C,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,yBAAyB,CAAC;AAChE,CAAC;AAED,MAAM,CAAC,MAAM,6BAA6B,GACxC,8CAA8C,CAAC;AACjD,MAAM,CAAC,MAAM,qBAAqB,GAAG,qCAAqC,CAAC;AAC3E,MAAM,CAAC,MAAM,yBAAyB,GACpC,8DAA8D,CAAC;AAEjE,MAAM,CAAC,MAAM,4BAA4B,GACvC,0CAA0C,CAAC;AAC7C,MAAM,CAAC,MAAM,oBAAoB,GAAG,sCAAsC,CAAC;AAC3E,MAAM,CAAC,MAAM,wBAAwB,GACnC,4DAA4D,CAAC;AAE/D,MAAM,CAAC,MAAM,+BAA+B,GAC1C,iDAAiD,CAAC;AACpD,MAAM,CAAC,MAAM,uBAAuB,GAClC,+CAA+C,CAAC;AAClD,MAAM,CAAC,MAAM,2BAA2B,GACtC,iEAAiE,CAAC","sourcesContent":["export function oauthCallbackURL(apiURI: string) {\n return `${apiURI.replace(/\\/+$/, '')}/runtime/oauth/callback`;\n}\n\nexport const GOOGLE_AUTHORIZATION_ENDPOINT =\n 'https://accounts.google.com/o/oauth2/v2/auth';\nexport const GOOGLE_TOKEN_ENDPOINT = 'https://oauth2.googleapis.com/token';\nexport const GOOGLE_DISCOVERY_ENDPOINT =\n 'https://accounts.google.com/.well-known/openid-configuration';\n\nexport const APPLE_AUTHORIZATION_ENDPOINT =\n 'https://appleid.apple.com/auth/authorize';\nexport const APPLE_TOKEN_ENDPOINT = 'https://appleid.apple.com/auth/token';\nexport const APPLE_DISCOVERY_ENDPOINT =\n 'https://appleid.apple.com/.well-known/openid-configuration';\n\nexport const LINKEDIN_AUTHORIZATION_ENDPOINT =\n 'https://www.linkedin.com/oauth/v2/authorization';\nexport const LINKEDIN_TOKEN_ENDPOINT =\n 'https://www.linkedin.com/oauth/v2/accessToken';\nexport const LINKEDIN_DISCOVERY_ENDPOINT =\n 'https://www.linkedin.com/oauth/.well-known/openid-configuration';\n"]}
@@ -0,0 +1,4 @@
1
+ export declare function pkceVerifier(): string;
2
+ export declare function sha256(s: string): Promise<ArrayBuffer>;
3
+ export declare function pkceCodeChallengeOfVerifier(verifier: string): Promise<string>;
4
+ //# sourceMappingURL=crypto.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../../src/crypto.ts"],"names":[],"mappings":"AACA,wBAAgB,YAAY,IAAI,MAAM,CAUrC;AAED,wBAAgB,MAAM,CAAC,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,CAAC,CAEtD;AAMD,wBAAgB,2BAA2B,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAM7E"}
@@ -0,0 +1,21 @@
1
+ // https://tools.ietf.org/html/rfc7636#section-4.1
2
+ export function pkceVerifier() {
3
+ const chars = '0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz-._~';
4
+ let s = '';
5
+ for (const value of crypto.getRandomValues(new Uint8Array(64))) {
6
+ s = s + chars[value % chars.length];
7
+ }
8
+ return s;
9
+ }
10
+ export function sha256(s) {
11
+ return crypto.subtle.digest({ name: 'SHA-256' }, new TextEncoder().encode(s));
12
+ }
13
+ function urlSafeBase64(s) {
14
+ return s.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
15
+ }
16
+ export function pkceCodeChallengeOfVerifier(verifier) {
17
+ return sha256(verifier).then((s) => {
18
+ return urlSafeBase64(btoa(String.fromCharCode(...Array.from(new Uint8Array(s)))));
19
+ });
20
+ }
21
+ //# sourceMappingURL=crypto.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crypto.js","sourceRoot":"","sources":["../../src/crypto.ts"],"names":[],"mappings":"AAAA,kDAAkD;AAClD,MAAM,UAAU,YAAY;IAC1B,MAAM,KAAK,GACT,oEAAoE,CAAC;IACvE,IAAI,CAAC,GAAG,EAAE,CAAC;IAEX,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,eAAe,CAAC,IAAI,UAAU,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;QAC/D,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC;IACtC,CAAC;IAED,OAAO,CAAC,CAAC;AACX,CAAC;AAED,MAAM,UAAU,MAAM,CAAC,CAAS;IAC9B,OAAO,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,EAAE,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;AAChF,CAAC;AAED,SAAS,aAAa,CAAC,CAAS;IAC9B,OAAO,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;AACrE,CAAC;AAED,MAAM,UAAU,2BAA2B,CAAC,QAAgB;IAC1D,OAAO,MAAM,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE;QACjC,OAAO,aAAa,CAClB,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAC5D,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["// https://tools.ietf.org/html/rfc7636#section-4.1\nexport function pkceVerifier(): string {\n const chars =\n '0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz-._~';\n let s = '';\n\n for (const value of crypto.getRandomValues(new Uint8Array(64))) {\n s = s + chars[value % chars.length];\n }\n\n return s;\n}\n\nexport function sha256(s: string): Promise<ArrayBuffer> {\n return crypto.subtle.digest({ name: 'SHA-256' }, new TextEncoder().encode(s));\n}\n\nfunction urlSafeBase64(s: string): string {\n return s.replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n}\n\nexport function pkceCodeChallengeOfVerifier(verifier: string): Promise<string> {\n return sha256(verifier).then((s) => {\n return urlSafeBase64(\n btoa(String.fromCharCode(...Array.from(new Uint8Array(s)))),\n );\n });\n}\n"]}