@sidekickdb/platform 0.0.0-stage → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (197) hide show
  1. package/.tshy/build.json +8 -0
  2. package/.tshy/commonjs.json +16 -0
  3. package/.tshy/esm.json +15 -0
  4. package/.turbo/turbo-build.log +50 -0
  5. package/LICENSE.md +202 -0
  6. package/NOTICE +27 -0
  7. package/README.md +445 -2
  8. package/__tests__/src/apiURI.test.ts +58 -0
  9. package/__tests__/src/backupDownload.test.ts +427 -0
  10. package/__tests__/src/backups.test.ts +168 -0
  11. package/__tests__/src/clerk.test.ts +13 -0
  12. package/__tests__/src/consts.test.ts +11 -0
  13. package/__tests__/src/migrations.test.ts +885 -0
  14. package/__tests__/src/perms.test.ts +102 -0
  15. package/__tests__/src/rename.test.ts +126 -0
  16. package/__tests__/src/schema.push.e2e.test.ts +186 -0
  17. package/__tests__/src/schema.test.ts +644 -0
  18. package/__tests__/src/typescript-schema.test.ts +117 -0
  19. package/dist/commonjs/ProgressPromise.d.ts +18 -0
  20. package/dist/commonjs/ProgressPromise.d.ts.map +1 -0
  21. package/dist/commonjs/ProgressPromise.js +77 -0
  22. package/dist/commonjs/ProgressPromise.js.map +1 -0
  23. package/dist/commonjs/api.d.ts +480 -0
  24. package/dist/commonjs/api.d.ts.map +1 -0
  25. package/dist/commonjs/api.js +1132 -0
  26. package/dist/commonjs/api.js.map +1 -0
  27. package/dist/commonjs/backupDownload.d.ts +89 -0
  28. package/dist/commonjs/backupDownload.d.ts.map +1 -0
  29. package/dist/commonjs/backupDownload.js +357 -0
  30. package/dist/commonjs/backupDownload.js.map +1 -0
  31. package/dist/commonjs/backups.d.ts +146 -0
  32. package/dist/commonjs/backups.d.ts.map +1 -0
  33. package/dist/commonjs/backups.js +248 -0
  34. package/dist/commonjs/backups.js.map +1 -0
  35. package/dist/commonjs/clerk.d.ts +2 -0
  36. package/dist/commonjs/clerk.d.ts.map +1 -0
  37. package/dist/commonjs/clerk.js +29 -0
  38. package/dist/commonjs/clerk.js.map +1 -0
  39. package/dist/commonjs/consts.d.ts +11 -0
  40. package/dist/commonjs/consts.d.ts.map +1 -0
  41. package/dist/commonjs/consts.js +17 -0
  42. package/dist/commonjs/consts.js.map +1 -0
  43. package/dist/commonjs/crypto.d.ts +4 -0
  44. package/dist/commonjs/crypto.d.ts.map +1 -0
  45. package/dist/commonjs/crypto.js +26 -0
  46. package/dist/commonjs/crypto.js.map +1 -0
  47. package/dist/commonjs/index.d.ts +18 -0
  48. package/dist/commonjs/index.d.ts.map +1 -0
  49. package/dist/commonjs/index.js +61 -0
  50. package/dist/commonjs/index.js.map +1 -0
  51. package/dist/commonjs/migrationUtils.d.ts +4 -0
  52. package/dist/commonjs/migrationUtils.d.ts.map +1 -0
  53. package/dist/commonjs/migrationUtils.js +52 -0
  54. package/dist/commonjs/migrationUtils.js.map +1 -0
  55. package/dist/commonjs/migrations.d.ts +99 -0
  56. package/dist/commonjs/migrations.d.ts.map +1 -0
  57. package/dist/commonjs/migrations.js +597 -0
  58. package/dist/commonjs/migrations.js.map +1 -0
  59. package/dist/commonjs/oauth.d.ts +98 -0
  60. package/dist/commonjs/oauth.d.ts.map +1 -0
  61. package/dist/commonjs/oauth.js +277 -0
  62. package/dist/commonjs/oauth.js.map +1 -0
  63. package/dist/commonjs/oauthCommon.d.ts +12 -0
  64. package/dist/commonjs/oauthCommon.d.ts.map +1 -0
  65. package/dist/commonjs/oauthCommon.js +26 -0
  66. package/dist/commonjs/oauthCommon.js.map +1 -0
  67. package/dist/commonjs/package.json +3 -0
  68. package/dist/commonjs/perms.d.ts +3 -0
  69. package/dist/commonjs/perms.d.ts.map +1 -0
  70. package/dist/commonjs/perms.js +66 -0
  71. package/dist/commonjs/perms.js.map +1 -0
  72. package/dist/commonjs/relationships.d.ts +7 -0
  73. package/dist/commonjs/relationships.d.ts.map +1 -0
  74. package/dist/commonjs/relationships.js +46 -0
  75. package/dist/commonjs/relationships.js.map +1 -0
  76. package/dist/commonjs/schema.d.ts +161 -0
  77. package/dist/commonjs/schema.d.ts.map +1 -0
  78. package/dist/commonjs/schema.js +174 -0
  79. package/dist/commonjs/schema.js.map +1 -0
  80. package/dist/commonjs/serverOAuth.d.ts +25 -0
  81. package/dist/commonjs/serverOAuth.d.ts.map +1 -0
  82. package/dist/commonjs/serverOAuth.js +72 -0
  83. package/dist/commonjs/serverOAuth.js.map +1 -0
  84. package/dist/commonjs/typescript-schema.d.ts +17 -0
  85. package/dist/commonjs/typescript-schema.d.ts.map +1 -0
  86. package/dist/commonjs/typescript-schema.js +314 -0
  87. package/dist/commonjs/typescript-schema.js.map +1 -0
  88. package/dist/commonjs/util.d.ts +13 -0
  89. package/dist/commonjs/util.d.ts.map +1 -0
  90. package/dist/commonjs/util.js +55 -0
  91. package/dist/commonjs/util.js.map +1 -0
  92. package/dist/commonjs/version.d.ts +3 -0
  93. package/dist/commonjs/version.d.ts.map +1 -0
  94. package/dist/commonjs/version.js +5 -0
  95. package/dist/commonjs/version.js.map +1 -0
  96. package/dist/esm/ProgressPromise.d.ts +18 -0
  97. package/dist/esm/ProgressPromise.d.ts.map +1 -0
  98. package/dist/esm/ProgressPromise.js +73 -0
  99. package/dist/esm/ProgressPromise.js.map +1 -0
  100. package/dist/esm/api.d.ts +480 -0
  101. package/dist/esm/api.d.ts.map +1 -0
  102. package/dist/esm/api.js +1121 -0
  103. package/dist/esm/api.js.map +1 -0
  104. package/dist/esm/backupDownload.d.ts +89 -0
  105. package/dist/esm/backupDownload.d.ts.map +1 -0
  106. package/dist/esm/backupDownload.js +354 -0
  107. package/dist/esm/backupDownload.js.map +1 -0
  108. package/dist/esm/backups.d.ts +146 -0
  109. package/dist/esm/backups.d.ts.map +1 -0
  110. package/dist/esm/backups.js +237 -0
  111. package/dist/esm/backups.js.map +1 -0
  112. package/dist/esm/clerk.d.ts +2 -0
  113. package/dist/esm/clerk.d.ts.map +1 -0
  114. package/dist/esm/clerk.js +26 -0
  115. package/dist/esm/clerk.js.map +1 -0
  116. package/dist/esm/consts.d.ts +11 -0
  117. package/dist/esm/consts.d.ts.map +1 -0
  118. package/dist/esm/consts.js +13 -0
  119. package/dist/esm/consts.js.map +1 -0
  120. package/dist/esm/crypto.d.ts +4 -0
  121. package/dist/esm/crypto.d.ts.map +1 -0
  122. package/dist/esm/crypto.js +21 -0
  123. package/dist/esm/crypto.js.map +1 -0
  124. package/dist/esm/index.d.ts +18 -0
  125. package/dist/esm/index.d.ts.map +1 -0
  126. package/dist/esm/index.js +17 -0
  127. package/dist/esm/index.js.map +1 -0
  128. package/dist/esm/migrationUtils.d.ts +4 -0
  129. package/dist/esm/migrationUtils.d.ts.map +1 -0
  130. package/dist/esm/migrationUtils.js +47 -0
  131. package/dist/esm/migrationUtils.js.map +1 -0
  132. package/dist/esm/migrations.d.ts +99 -0
  133. package/dist/esm/migrations.d.ts.map +1 -0
  134. package/dist/esm/migrations.js +588 -0
  135. package/dist/esm/migrations.js.map +1 -0
  136. package/dist/esm/oauth.d.ts +98 -0
  137. package/dist/esm/oauth.d.ts.map +1 -0
  138. package/dist/esm/oauth.js +268 -0
  139. package/dist/esm/oauth.js.map +1 -0
  140. package/dist/esm/oauthCommon.d.ts +12 -0
  141. package/dist/esm/oauthCommon.d.ts.map +1 -0
  142. package/dist/esm/oauthCommon.js +22 -0
  143. package/dist/esm/oauthCommon.js.map +1 -0
  144. package/dist/esm/package.json +3 -0
  145. package/dist/esm/perms.d.ts +3 -0
  146. package/dist/esm/perms.d.ts.map +1 -0
  147. package/dist/esm/perms.js +62 -0
  148. package/dist/esm/perms.js.map +1 -0
  149. package/dist/esm/relationships.d.ts +7 -0
  150. package/dist/esm/relationships.d.ts.map +1 -0
  151. package/dist/esm/relationships.js +43 -0
  152. package/dist/esm/relationships.js.map +1 -0
  153. package/dist/esm/schema.d.ts +161 -0
  154. package/dist/esm/schema.d.ts.map +1 -0
  155. package/dist/esm/schema.js +158 -0
  156. package/dist/esm/schema.js.map +1 -0
  157. package/dist/esm/serverOAuth.d.ts +25 -0
  158. package/dist/esm/serverOAuth.d.ts.map +1 -0
  159. package/dist/esm/serverOAuth.js +68 -0
  160. package/dist/esm/serverOAuth.js.map +1 -0
  161. package/dist/esm/typescript-schema.d.ts +17 -0
  162. package/dist/esm/typescript-schema.d.ts.map +1 -0
  163. package/dist/esm/typescript-schema.js +310 -0
  164. package/dist/esm/typescript-schema.js.map +1 -0
  165. package/dist/esm/util.d.ts +13 -0
  166. package/dist/esm/util.d.ts.map +1 -0
  167. package/dist/esm/util.js +46 -0
  168. package/dist/esm/util.js.map +1 -0
  169. package/dist/esm/version.d.ts +3 -0
  170. package/dist/esm/version.d.ts.map +1 -0
  171. package/dist/esm/version.js +3 -0
  172. package/dist/esm/version.js.map +1 -0
  173. package/dist/standalone/index.js +13747 -0
  174. package/dist/standalone/index.umd.cjs +72 -0
  175. package/package.json +74 -3
  176. package/src/ProgressPromise.ts +97 -0
  177. package/src/api.ts +1903 -0
  178. package/src/backupDownload.ts +519 -0
  179. package/src/backups.ts +342 -0
  180. package/src/clerk.ts +24 -0
  181. package/src/consts.ts +22 -0
  182. package/src/crypto.ts +28 -0
  183. package/src/index.ts +147 -0
  184. package/src/migrationUtils.ts +56 -0
  185. package/src/migrations.ts +920 -0
  186. package/src/oauth.ts +390 -0
  187. package/src/oauthCommon.ts +38 -0
  188. package/src/perms.ts +81 -0
  189. package/src/relationships.ts +57 -0
  190. package/src/schema.ts +497 -0
  191. package/src/serverOAuth.ts +119 -0
  192. package/src/typescript-schema.ts +439 -0
  193. package/src/util.ts +77 -0
  194. package/src/version.ts +3 -0
  195. package/tsconfig.dev.json +14 -0
  196. package/tsconfig.json +14 -0
  197. package/vite.config.ts +19 -0
@@ -0,0 +1,1121 @@
1
+ import { InstantAPIError, requireApiURI, version as coreVersion, i, } from '@sidekickdb/core';
2
+ import { Webhooks } from '@sidekickdb/webhooks';
3
+ import { BackupsManager } from "./backups.js";
4
+ import version from "./version.js";
5
+ import { attrFwdLabel, attrFwdName, attrRevName, collectSystemCatalogIdentNames, identName, validateSchema, } from "./schema.js";
6
+ import { ProgressPromise } from "./ProgressPromise.js";
7
+ import { capitalizeFirstLetter, deriveClientType, rels, sortedEntries, } from "./util.js";
8
+ import { exchangeRefreshToken } from "./serverOAuth.js";
9
+ import { buildAutoRenameSelector, convertTxSteps, diffSchemas, } from "./migrations.js";
10
+ async function jsonFetch(input, init) {
11
+ const headers = {
12
+ ...(init?.headers || {}),
13
+ 'Instant-Platform-Version': version,
14
+ 'Instant-Core-Version': coreVersion,
15
+ 'X-Instant-Source': 'platform-sdk',
16
+ 'X-Instant-Version': version,
17
+ };
18
+ const res = await fetch(input, { ...init, headers });
19
+ if (res.status === 200) {
20
+ const json = await res.json();
21
+ return Promise.resolve(json);
22
+ }
23
+ const body = await res.text();
24
+ try {
25
+ const json = JSON.parse(body);
26
+ return Promise.reject(new InstantAPIError({ status: res.status, body: json }));
27
+ }
28
+ catch (_e) {
29
+ return Promise.reject(new InstantAPIError({
30
+ status: res.status,
31
+ body: { type: undefined, message: body },
32
+ }));
33
+ }
34
+ }
35
+ function attrDefForType(type) {
36
+ switch (type) {
37
+ case 'string':
38
+ return i.string();
39
+ case 'any':
40
+ return i.any();
41
+ case 'json':
42
+ return i.json();
43
+ case 'boolean':
44
+ return i.boolean();
45
+ case 'date':
46
+ return i.date();
47
+ case 'number':
48
+ return i.number();
49
+ default: {
50
+ const neverType = type;
51
+ throw new Error(`Unknown type ${neverType}.`);
52
+ }
53
+ }
54
+ }
55
+ function apiSchemaAttrToDataAttrDef(attr) {
56
+ const derivedType = deriveClientType(attr);
57
+ let i = attrDefForType(derivedType.type);
58
+ if (attr['unique?']) {
59
+ i = i.unique();
60
+ }
61
+ if (attr['index?']) {
62
+ i = i.indexed();
63
+ }
64
+ if (!attr['required?']) {
65
+ i = i.optional();
66
+ }
67
+ i.metadata.derivedType = derivedType;
68
+ return i;
69
+ }
70
+ function apiSchemaBlobToEntityDef(attrs) {
71
+ const defs = {};
72
+ for (const [label, attr] of sortedEntries(attrs)) {
73
+ if (label === 'id') {
74
+ continue;
75
+ }
76
+ defs[label] = apiSchemaAttrToDataAttrDef(attr);
77
+ }
78
+ return i.entity(defs);
79
+ }
80
+ function apiSchemaAttrToLinkName(attr) {
81
+ const [, fe, flabel] = attr['forward-identity'];
82
+ return `${fe}${capitalizeFirstLetter(flabel)}`;
83
+ }
84
+ function apiSchemaAttrToLinkDef(attr) {
85
+ const [, fe, flabel] = attr['forward-identity'];
86
+ const [, re, rlabel] = attr['reverse-identity'];
87
+ const [fhas, rhas] = rels[`${attr.cardinality}-${attr['unique?']}`];
88
+ return {
89
+ forward: {
90
+ on: fe,
91
+ has: fhas,
92
+ label: flabel,
93
+ required: attr['required?'] || undefined,
94
+ onDelete: attr['on-delete'] === 'cascade' ? 'cascade' : undefined,
95
+ },
96
+ reverse: {
97
+ on: re,
98
+ has: rhas,
99
+ label: rlabel,
100
+ onDelete: attr['on-delete-reverse'] === 'cascade'
101
+ ? 'cascade'
102
+ : undefined,
103
+ },
104
+ };
105
+ }
106
+ export function apiSchemaToAttrs(apiSchema) {
107
+ let res = [];
108
+ for (const [_, attrs] of sortedEntries(apiSchema.blobs)) {
109
+ Object.values(attrs).forEach((a) => {
110
+ res.push(a);
111
+ });
112
+ }
113
+ for (const [_, a] of sortedEntries(apiSchema.refs)) {
114
+ res.push(a);
115
+ }
116
+ return res;
117
+ }
118
+ export function apiSchemaToInstantSchemaDef(apiSchema) {
119
+ const entities = {};
120
+ for (const [etype, attrs] of sortedEntries(apiSchema.blobs)) {
121
+ entities[etype] = apiSchemaBlobToEntityDef(attrs);
122
+ }
123
+ const links = {};
124
+ for (const [_name, attr] of sortedEntries(apiSchema.refs)) {
125
+ const link = apiSchemaAttrToLinkDef(attr);
126
+ const linkName = apiSchemaAttrToLinkName(attr);
127
+ links[linkName] = link;
128
+ }
129
+ return i.schema({ entities, links });
130
+ }
131
+ function coerceApp(app) {
132
+ const base = {
133
+ id: app.id,
134
+ title: app.title,
135
+ createdAt: new Date(app.created_at),
136
+ orgId: app.org_id,
137
+ ...(app['admin-token'] ? { adminToken: app['admin-token'] } : {}),
138
+ };
139
+ // `in` narrows the union, so it’s safe to read `perms` / `schema`
140
+ // when the property exists. :contentReference[oaicite:0]{index=0}
141
+ const permsPart = ('perms' in app ? { perms: app.perms } : {});
142
+ const schemaPart = ('schema' in app
143
+ ? {
144
+ schema: apiSchemaToInstantSchemaDef(app.schema),
145
+ }
146
+ : {});
147
+ return { ...base, ...permsPart, ...schemaPart };
148
+ }
149
+ function coerceOrg(org) {
150
+ return {
151
+ id: org.id,
152
+ title: org.title,
153
+ createdAt: new Date(org.created_at),
154
+ };
155
+ }
156
+ async function getApps(apiURI, token, opts) {
157
+ const url = new URL(`${apiURI}/superadmin/apps`);
158
+ const include = [];
159
+ if (opts?.includePerms) {
160
+ include.push('perms');
161
+ }
162
+ if (opts?.includeSchema) {
163
+ include.push('schema');
164
+ }
165
+ if (include.length) {
166
+ url.searchParams.set('include', include.join(','));
167
+ }
168
+ const resp = await jsonFetch(url.toString(), {
169
+ method: 'GET',
170
+ headers: {
171
+ Authorization: `Bearer ${token}`,
172
+ },
173
+ });
174
+ return { apps: resp.apps.map(coerceApp) };
175
+ }
176
+ async function getOrgs(apiURI, token) {
177
+ const url = new URL(`${apiURI}/superadmin/orgs`);
178
+ const resp = await jsonFetch(url.toString(), {
179
+ method: 'GET',
180
+ headers: {
181
+ Authorization: `Bearer ${token}`,
182
+ },
183
+ });
184
+ return { orgs: resp.orgs.map(coerceOrg) };
185
+ }
186
+ async function getAppsForOrg(apiURI, token, orgId, opts) {
187
+ const url = new URL(`${apiURI}/superadmin/orgs/${orgId}/apps`);
188
+ const include = [];
189
+ if (opts?.includePerms) {
190
+ include.push('perms');
191
+ }
192
+ if (opts?.includeSchema) {
193
+ include.push('schema');
194
+ }
195
+ if (include.length) {
196
+ url.searchParams.set('include', include.join(','));
197
+ }
198
+ const resp = await jsonFetch(url.toString(), {
199
+ method: 'GET',
200
+ headers: {
201
+ Authorization: `Bearer ${token}`,
202
+ },
203
+ });
204
+ return { apps: resp.apps.map(coerceApp) };
205
+ }
206
+ async function getAppAPISchema(apiURI, token, appId) {
207
+ const { schema: apiSchema } = await jsonFetch(`${apiURI}/superadmin/apps/${appId}/schema`, {
208
+ method: 'GET',
209
+ headers: {
210
+ Authorization: `Bearer ${token}`,
211
+ },
212
+ });
213
+ return apiSchema;
214
+ }
215
+ async function getAppSchema(apiURI, token, appId) {
216
+ const apiSchema = await getAppAPISchema(apiURI, token, appId);
217
+ return { schema: apiSchemaToInstantSchemaDef(apiSchema) };
218
+ }
219
+ async function getAppPerms(apiURI, token, appId) {
220
+ return await jsonFetch(`${apiURI}/superadmin/apps/${appId}/perms`, {
221
+ method: 'GET',
222
+ headers: {
223
+ Authorization: `Bearer ${token}`,
224
+ },
225
+ });
226
+ }
227
+ async function getApp(apiURI, token, appId, opts) {
228
+ let permsPromise = null;
229
+ let schemaPromise = null;
230
+ if (opts?.includePerms) {
231
+ permsPromise = getAppPerms(apiURI, token, appId);
232
+ }
233
+ if (opts?.includeSchema) {
234
+ schemaPromise = getAppSchema(apiURI, token, appId);
235
+ }
236
+ const { app: apiApp } = await jsonFetch(`${apiURI}/superadmin/apps/${appId}`, {
237
+ method: 'GET',
238
+ headers: {
239
+ Authorization: `Bearer ${token}`,
240
+ },
241
+ });
242
+ if (!permsPromise && !schemaPromise) {
243
+ const app = coerceApp(apiApp);
244
+ return { app };
245
+ }
246
+ const app = {
247
+ ...coerceApp(apiApp),
248
+ ...(permsPromise ? { perms: (await permsPromise).perms } : {}),
249
+ ...(schemaPromise ? { schema: (await schemaPromise).schema } : {}),
250
+ };
251
+ return {
252
+ app,
253
+ };
254
+ }
255
+ async function createApp(apiURI, token, fields) {
256
+ const apiFields = fields;
257
+ apiFields.org_id = fields.orgId;
258
+ const { app } = await jsonFetch(`${apiURI}/superadmin/apps`, {
259
+ method: 'POST',
260
+ headers: {
261
+ 'Content-Type': 'application/json',
262
+ Authorization: `Bearer ${token}`,
263
+ },
264
+ body: JSON.stringify(apiFields),
265
+ });
266
+ const withAdminToken = {
267
+ ...coerceApp(app),
268
+ adminToken: app['admin-token'],
269
+ };
270
+ return {
271
+ app: withAdminToken,
272
+ };
273
+ }
274
+ async function createTemporaryApp(apiURI, fields) {
275
+ const response = await jsonFetch(`${apiURI}/dash/apps/ephemeral`, {
276
+ method: 'POST',
277
+ headers: {
278
+ 'Content-Type': 'application/json',
279
+ },
280
+ body: JSON.stringify(fields),
281
+ });
282
+ const withAdminToken = {
283
+ ...coerceApp(response.app),
284
+ adminToken: response.app['admin-token'],
285
+ };
286
+ return {
287
+ app: withAdminToken,
288
+ expiresMs: response.expires_ms,
289
+ };
290
+ }
291
+ async function updateApp(apiURI, token, appId, fields) {
292
+ const { app } = await jsonFetch(`${apiURI}/superadmin/apps/${appId}`, {
293
+ method: 'POST',
294
+ headers: {
295
+ 'Content-Type': 'application/json',
296
+ Authorization: `Bearer ${token}`,
297
+ },
298
+ body: JSON.stringify(fields),
299
+ });
300
+ return { app: coerceApp(app) };
301
+ }
302
+ async function deleteApp(apiURI, token, appId) {
303
+ const { app } = await jsonFetch(`${apiURI}/superadmin/apps/${appId}`, {
304
+ method: 'DELETE',
305
+ headers: {
306
+ 'Content-Type': 'application/json',
307
+ Authorization: `Bearer ${token}`,
308
+ },
309
+ });
310
+ return { app: coerceApp(app) };
311
+ }
312
+ function translatePlanStep(apiStep, currentAttrs) {
313
+ const [stepType, stepParams] = apiStep;
314
+ switch (stepType) {
315
+ case 'add-attr': {
316
+ const attr = stepParams;
317
+ const attrName = attrFwdName(attr);
318
+ const friendlyDescription = attr['value-type'] === 'blob'
319
+ ? attrFwdLabel(attr) === 'id'
320
+ ? `Create new entity ${attrName}.`
321
+ : `Add attribute ${attrName}.`
322
+ : `Link ${attrName} to ${attrRevName(attr)}.`;
323
+ return { type: 'add-attr', friendlyDescription, attr };
324
+ }
325
+ case 'update-attr': {
326
+ const attr = stepParams;
327
+ return {
328
+ type: 'update-attr',
329
+ friendlyDescription: `Update attribute ${attrFwdName(attr)}.`,
330
+ attr,
331
+ };
332
+ }
333
+ case 'index': {
334
+ return {
335
+ type: 'index',
336
+ friendlyDescription: `Add index to ${identName(stepParams['forward-identity'])}.`,
337
+ attrId: stepParams['attr-id'],
338
+ forwardIdentity: stepParams['forward-identity'],
339
+ };
340
+ }
341
+ case 'remove-index': {
342
+ return {
343
+ type: 'remove-index',
344
+ friendlyDescription: `Remove index from ${identName(stepParams['forward-identity'])}.`,
345
+ attrId: stepParams['attr-id'],
346
+ forwardIdentity: stepParams['forward-identity'],
347
+ };
348
+ }
349
+ case 'unique': {
350
+ return {
351
+ type: 'unique',
352
+ friendlyDescription: `Ensure that ${identName(stepParams['forward-identity'])} is unique.`,
353
+ attrId: stepParams['attr-id'],
354
+ forwardIdentity: stepParams['forward-identity'],
355
+ };
356
+ }
357
+ case 'remove-unique': {
358
+ return {
359
+ type: 'remove-unique',
360
+ friendlyDescription: `Remove uniqueness constraint from ${identName(stepParams['forward-identity'])}.`,
361
+ attrId: stepParams['attr-id'],
362
+ forwardIdentity: stepParams['forward-identity'],
363
+ };
364
+ }
365
+ case 'required': {
366
+ return {
367
+ type: 'required',
368
+ friendlyDescription: `Make ${identName(stepParams['forward-identity'])} a required attribute.`,
369
+ attrId: stepParams['attr-id'],
370
+ forwardIdentity: stepParams['forward-identity'],
371
+ };
372
+ }
373
+ case 'remove-required': {
374
+ return {
375
+ type: 'remove-required',
376
+ friendlyDescription: `Allow ${identName(stepParams['forward-identity'])} to be missing or null.`,
377
+ attrId: stepParams['attr-id'],
378
+ forwardIdentity: stepParams['forward-identity'],
379
+ };
380
+ }
381
+ case 'check-data-type': {
382
+ const forwardIdentity = stepParams['forward-identity'];
383
+ const dataType = stepParams['checked-data-type'];
384
+ return {
385
+ type: 'check-data-type',
386
+ friendlyDescription: `Enforce data type of ${identName(forwardIdentity)} as type ${dataType}.`,
387
+ attrId: stepParams['attr-id'],
388
+ forwardIdentity,
389
+ checkedDataType: dataType,
390
+ };
391
+ }
392
+ case 'remove-data-type': {
393
+ const forwardIdentity = stepParams['forward-identity'];
394
+ return {
395
+ type: 'remove-data-type',
396
+ friendlyDescription: `Stop enforcing data type of ${identName(forwardIdentity)}.`,
397
+ attrId: stepParams['attr-id'],
398
+ forwardIdentity: stepParams['forward-identity'],
399
+ };
400
+ }
401
+ case 'delete-attr': {
402
+ const attrId = stepParams;
403
+ const attr = currentAttrs.find((a) => a.id === attrId);
404
+ const friendlyName = attr ? identName(attr['forward-identity']) : attrId;
405
+ return {
406
+ type: 'delete-attr',
407
+ attrId: stepParams,
408
+ friendlyDescription: `Delete attribute ${friendlyName}.`,
409
+ };
410
+ }
411
+ default: {
412
+ // Get a type error if we ignore a case
413
+ const unknownType = stepType;
414
+ throw new Error(`Unknown schema operation ${unknownType}.`);
415
+ }
416
+ }
417
+ }
418
+ export function translatePlanSteps(apiSteps, currentAttrs) {
419
+ return apiSteps.map((step) => translatePlanStep(step, currentAttrs));
420
+ }
421
+ function translatePushStep(apiStep, jobs, currentAttrs) {
422
+ const [stepType, stepParams] = apiStep;
423
+ if (stepType === 'add-attr' ||
424
+ stepType === 'update-attr' ||
425
+ stepType === 'delete-attr') {
426
+ const planStep = translatePlanStep(apiStep, currentAttrs);
427
+ if (planStep.type !== 'add-attr' &&
428
+ planStep.type !== 'update-attr' &&
429
+ planStep.type !== 'delete-attr') {
430
+ // This is just here for typescript
431
+ throw new Error('Invalid step.');
432
+ }
433
+ return planStep;
434
+ }
435
+ const jobId = stepParams['job-id'];
436
+ const job = jobs.find((j) => j.id === jobId);
437
+ const planStep = translatePlanStep(apiStep, currentAttrs);
438
+ const backgroundJob = formatJob(job);
439
+ if (planStep.type !== backgroundJob.type) {
440
+ throw new Error('Invalid type');
441
+ }
442
+ return { ...planStep, backgroundJob };
443
+ }
444
+ function translatePushSteps(apiSteps, jobs, currentAttrs) {
445
+ return apiSteps.map((step) => translatePushStep(step, jobs, currentAttrs));
446
+ }
447
+ function shouldOverwrite(body) {
448
+ if ('renames' in body && !body.overwrite) {
449
+ throw new Error('If you pass in `renames`, you _must_ pass in `overwrite: true`');
450
+ }
451
+ return !!body.overwrite;
452
+ }
453
+ async function planSchemaPush(apiURI, token, appId, body) {
454
+ const resp = await jsonFetch(`${apiURI}/superadmin/apps/${appId}/schema/push/plan`, {
455
+ method: 'POST',
456
+ headers: {
457
+ 'Content-Type': 'application/json',
458
+ Authorization: `Bearer ${token}`,
459
+ },
460
+ body: JSON.stringify({
461
+ ...body,
462
+ check_types: true,
463
+ supports_background_updates: true,
464
+ }),
465
+ });
466
+ const currentAttrs = resp['current-attrs'];
467
+ return {
468
+ newSchema: apiSchemaToInstantSchemaDef(resp['new-schema']),
469
+ currentSchema: apiSchemaToInstantSchemaDef(resp['current-schema']),
470
+ steps: translatePlanSteps(resp['steps'], currentAttrs),
471
+ };
472
+ }
473
+ async function planSchemaPushOverwriteInternal(apiURI, token, appId, body) {
474
+ const apiSchema = await getAppAPISchema(apiURI, token, appId);
475
+ const currentSchema = apiSchemaToInstantSchemaDef(apiSchema);
476
+ const currentAttrs = apiSchemaToAttrs(apiSchema);
477
+ const systemCatalogIdentNames = collectSystemCatalogIdentNames(currentAttrs);
478
+ const newSchema = body.schema;
479
+ validateSchema(newSchema, systemCatalogIdentNames);
480
+ const renames = ('renames' in body ? body.renames : null) || [];
481
+ const renameSelector = buildAutoRenameSelector(renames);
482
+ const diffResult = await diffSchemas(currentSchema, newSchema, renameSelector, systemCatalogIdentNames);
483
+ const txSteps = convertTxSteps(diffResult, currentAttrs);
484
+ return {
485
+ currentSchema,
486
+ currentAttrs,
487
+ txSteps: txSteps,
488
+ steps: translatePlanSteps(txSteps, currentAttrs),
489
+ };
490
+ }
491
+ async function planSchemaPushOverwrite(apiURI, token, appId, body) {
492
+ const { currentSchema, steps } = await planSchemaPushOverwriteInternal(apiURI, token, appId, body);
493
+ return {
494
+ newSchema: body.schema,
495
+ currentSchema: currentSchema,
496
+ steps: steps,
497
+ };
498
+ }
499
+ function allJobsComplete(jobs) {
500
+ if (jobs.length === 0) {
501
+ return true;
502
+ }
503
+ return jobs.every((j) => j.job_status === 'completed' || j.job_status === 'errored');
504
+ }
505
+ function latestJobUpdate(jobs) {
506
+ const res = jobs.reduce((acc, job) => {
507
+ if (job.updated_at) {
508
+ const d = new Date(job.updated_at);
509
+ if (!acc || d > acc) {
510
+ return d;
511
+ }
512
+ }
513
+ return acc;
514
+ }, null);
515
+ return res;
516
+ }
517
+ async function jobFetchLoop(apiURI, token, appId, groupId, startingJobs, onFetch) {
518
+ let interval = 100;
519
+ let lastJobs = startingJobs;
520
+ let errorCount = 0;
521
+ while (!allJobsComplete(lastJobs)) {
522
+ await new Promise((resolve) => setTimeout(resolve, interval));
523
+ try {
524
+ const nextJobs = (await jsonFetch(`${apiURI}/dash/apps/${appId}/indexing-jobs/group/${groupId}`, {
525
+ method: 'GET',
526
+ headers: {
527
+ Authorization: `Bearer ${token}`,
528
+ },
529
+ })).jobs;
530
+ onFetch(nextJobs);
531
+ if (allJobsComplete(nextJobs)) {
532
+ return nextJobs;
533
+ }
534
+ errorCount = 0;
535
+ const lastUpdate = latestJobUpdate(lastJobs);
536
+ const thisUpdate = latestJobUpdate(nextJobs);
537
+ lastJobs = nextJobs;
538
+ interval =
539
+ thisUpdate === null || (lastUpdate && lastUpdate >= thisUpdate)
540
+ ? Math.min(interval * 2, 10000)
541
+ : 100;
542
+ }
543
+ catch (e) {
544
+ if (errorCount > 3) {
545
+ throw e;
546
+ }
547
+ else {
548
+ errorCount++;
549
+ interval = Math.min(interval * 2, 10000);
550
+ }
551
+ }
552
+ }
553
+ return lastJobs;
554
+ }
555
+ function formatJob(job) {
556
+ const baseJob = {
557
+ id: job.id,
558
+ createdAt: new Date(job.created_at),
559
+ updatedAt: new Date(job.updated_at),
560
+ status: job.job_status,
561
+ workEstimate: job.work_estimate,
562
+ workCompleted: job.work_completed,
563
+ error: job.error,
564
+ invalidTriplesSample: job.invalid_triples_sample?.map((s) => {
565
+ return { entityId: s.entity_id, value: s.value, jsonType: s.json_type };
566
+ }),
567
+ };
568
+ switch (job.job_type) {
569
+ case 'remove-data-type':
570
+ case 'index':
571
+ case 'remove-index':
572
+ case 'required':
573
+ case 'remove-required':
574
+ case 'remove-unique': {
575
+ return { ...baseJob, type: job.job_type };
576
+ }
577
+ case 'check-data-type': {
578
+ return {
579
+ ...baseJob,
580
+ type: job.job_type,
581
+ checkedDataType: job.checked_data_type,
582
+ };
583
+ }
584
+ case 'unique': {
585
+ return {
586
+ ...baseJob,
587
+ type: job.job_type,
588
+ invalidUniqueValue: job.invalid_unique_value,
589
+ };
590
+ }
591
+ default: {
592
+ const neverType = job.job_type;
593
+ throw new Error(`Unknown job type: ${neverType}.`);
594
+ }
595
+ }
596
+ }
597
+ function stepSummary(steps) {
598
+ const inProgress = steps.filter((s) => 'backgroundJob' in s &&
599
+ (s.backgroundJob.status === 'processing' ||
600
+ s.backgroundJob.status === 'waiting'));
601
+ const completed = steps.filter((s) => !('backgroundJob' in s) || s.backgroundJob.status === 'completed');
602
+ const errored = steps.filter((s) => 'backgroundJob' in s && s.backgroundJob.status === 'errored');
603
+ return {
604
+ friendlyDescription: inProgress.length
605
+ ? `Completing ${inProgress.length} of ${steps.length} schema operations.`
606
+ : `Finished ${steps.length} schema operation${steps.length === 1 ? '' : 's'}${errored.length
607
+ ? `, with ${errored.length} error${errored.length > 1 ? 's' : ''}`
608
+ : '.'}`,
609
+ totalCount: steps.length,
610
+ inProgressCount: inProgress.length,
611
+ completedCount: completed.length,
612
+ errorCount: errored.length,
613
+ steps,
614
+ inProgressSteps: inProgress,
615
+ completedSteps: completed,
616
+ erroredSteps: errored,
617
+ };
618
+ }
619
+ function schemaPush(apiURI, token, appId, body) {
620
+ return new ProgressPromise(async (progress, resolve, reject) => {
621
+ try {
622
+ const currentAPISchema = await getAppAPISchema(apiURI, token, appId);
623
+ const currentAttrs = apiSchemaToAttrs(currentAPISchema);
624
+ const resp = await jsonFetch(`${apiURI}/superadmin/apps/${appId}/schema/push/apply`, {
625
+ method: 'POST',
626
+ headers: {
627
+ 'Content-Type': 'application/json',
628
+ Authorization: `Bearer ${token}`,
629
+ },
630
+ body: JSON.stringify({
631
+ ...body,
632
+ check_types: true,
633
+ supports_background_updates: true,
634
+ }),
635
+ });
636
+ const indexingJobs = resp['indexing-jobs'];
637
+ const jobs = !indexingJobs
638
+ ? []
639
+ : await jobFetchLoop(apiURI, token, appId, indexingJobs['group-id'], indexingJobs['jobs'], (jobs) => {
640
+ progress(stepSummary(translatePushSteps(resp.steps, jobs, currentAttrs)));
641
+ });
642
+ const schemaRes = await getAppSchema(apiURI, token, appId);
643
+ resolve({
644
+ newSchema: schemaRes.schema,
645
+ steps: translatePushSteps(resp.steps, jobs, currentAttrs),
646
+ summary: stepSummary(translatePushSteps(resp.steps, jobs, currentAttrs)),
647
+ });
648
+ }
649
+ catch (e) {
650
+ reject(e);
651
+ }
652
+ });
653
+ }
654
+ function schemaPushOverwrite(apiURI, token, appId, body) {
655
+ return new ProgressPromise(async (progress, resolve, reject) => {
656
+ try {
657
+ const { currentAttrs, txSteps } = await planSchemaPushOverwriteInternal(apiURI, token, appId, body);
658
+ const resp = await jsonFetch(`${apiURI}/dash/apps/${appId}/schema/steps/apply`, {
659
+ method: 'POST',
660
+ headers: {
661
+ 'Content-Type': 'application/json',
662
+ Authorization: `Bearer ${token}`,
663
+ },
664
+ body: JSON.stringify({
665
+ steps: txSteps,
666
+ }),
667
+ });
668
+ const indexingJobs = resp['indexing-jobs'];
669
+ const jobs = !indexingJobs
670
+ ? []
671
+ : await jobFetchLoop(apiURI, token, appId, indexingJobs['group-id'], indexingJobs['jobs'], (jobs) => {
672
+ progress(stepSummary(translatePushSteps(resp.steps, jobs, currentAttrs)));
673
+ });
674
+ const schemaRes = await getAppSchema(apiURI, token, appId);
675
+ resolve({
676
+ newSchema: schemaRes.schema,
677
+ steps: translatePushSteps(resp.steps, jobs, currentAttrs),
678
+ summary: stepSummary(translatePushSteps(resp.steps, jobs, currentAttrs)),
679
+ });
680
+ }
681
+ catch (e) {
682
+ reject(e);
683
+ }
684
+ });
685
+ }
686
+ async function pushPerms(apiURI, token, appId, body) {
687
+ const result = await jsonFetch(`${apiURI}/superadmin/apps/${appId}/perms`, {
688
+ method: 'POST',
689
+ headers: {
690
+ 'Content-Type': 'application/json',
691
+ Authorization: `Bearer ${token}`,
692
+ },
693
+ body: JSON.stringify({ code: body.perms }),
694
+ });
695
+ return { perms: result.rules.code };
696
+ }
697
+ async function tokenInfo(apiURI, token) {
698
+ const result = await jsonFetch(`${apiURI}/platform/oauth/token-info?access_token=${token}`, {
699
+ method: 'GET',
700
+ });
701
+ return {
702
+ tokenType: result.token_type,
703
+ scopes: result.scopes,
704
+ expiresAt: new Date(Date.now() + (result.expires_in - 60) * 1000),
705
+ };
706
+ }
707
+ export class PlatformApiMissingAuthError extends Error {
708
+ constructor() {
709
+ super('PlatformApi was not provided auth.');
710
+ }
711
+ }
712
+ /**
713
+ * API methods for the Platform API
714
+ *
715
+ * Usage:
716
+ *
717
+ * ```ts
718
+ * import { PlatformApi } from '@sidekickdb/platform';
719
+ *
720
+ * const api = new PlatformApi({
721
+ * apiURI: 'https://sidekick.example.com',
722
+ * auth: { token: 'oauth-access-token' },
723
+ * });
724
+ * const { apps } = await api.getApps({
725
+ * includeSchema: true,
726
+ * includePerms: true,
727
+ * });
728
+ * ```
729
+ */
730
+ export class PlatformApi {
731
+ #auth;
732
+ #apiURI;
733
+ /**
734
+ * @param config – Runtime configuration.
735
+ * @param config.auth.token – OAuth access-token obtained via the oauth flow
736
+ * or a personal access token.
737
+ * @param config.apiURI – URL of your SidekickDB server. Required.
738
+ * @throws {MissingApiURIError} When `apiURI` is missing.
739
+ */
740
+ constructor(config) {
741
+ this.#auth = config?.auth;
742
+ this.#apiURI = requireApiURI(config?.apiURI, {
743
+ target: 'new PlatformApi()',
744
+ });
745
+ }
746
+ token() {
747
+ if (!this.#auth) {
748
+ throw new PlatformApiMissingAuthError();
749
+ }
750
+ if ('token' in this.#auth) {
751
+ return this.#auth.token;
752
+ }
753
+ return this.#auth.accessToken;
754
+ }
755
+ canRefreshToken() {
756
+ if (!this.#auth) {
757
+ throw new PlatformApiMissingAuthError();
758
+ }
759
+ return ('refreshToken' in this.#auth &&
760
+ 'clientId' in this.#auth &&
761
+ 'clientSecret' in this.#auth &&
762
+ this.#auth.refreshToken != null &&
763
+ this.#auth.clientId != null &&
764
+ this.#auth.clientSecret != null);
765
+ }
766
+ async refreshToken() {
767
+ if (!this.#auth) {
768
+ throw new PlatformApiMissingAuthError();
769
+ }
770
+ if (!this.canRefreshToken() ||
771
+ // Checked in canRefreshToken, but this lets
772
+ // typescript refine this.#auth here
773
+ !('clientId' in this.#auth)) {
774
+ return null;
775
+ }
776
+ const token = await exchangeRefreshToken({
777
+ apiURI: this.#apiURI,
778
+ clientId: this.#auth.clientId,
779
+ clientSecret: this.#auth.clientSecret,
780
+ refreshToken: this.#auth.refreshToken,
781
+ });
782
+ this.#auth.accessToken = token.accessToken;
783
+ if (this.#auth.onRefresh) {
784
+ await this.#auth.onRefresh(token);
785
+ }
786
+ return token;
787
+ }
788
+ async withRetry(f, args) {
789
+ let attempt = 0;
790
+ const [apiURI, tokenInArg, ...restArgs] = args;
791
+ let token = tokenInArg;
792
+ while (attempt < 2) {
793
+ try {
794
+ return await f(apiURI, token, ...restArgs);
795
+ }
796
+ catch (e) {
797
+ if (e instanceof InstantAPIError &&
798
+ (e.status === 401 ||
799
+ e.body?.type === 'record-expired' ||
800
+ (e.body?.type === 'record-not-found' &&
801
+ e.body.hint['record-type'].match(/token/i))) &&
802
+ this.canRefreshToken()) {
803
+ const refreshedToken = await this.refreshToken();
804
+ if (refreshedToken) {
805
+ token = refreshedToken.accessToken;
806
+ attempt++;
807
+ continue;
808
+ }
809
+ }
810
+ throw e;
811
+ }
812
+ }
813
+ }
814
+ /**
815
+ * Fetch a single app by its id.
816
+ *
817
+ * ```ts
818
+ * const { app } = await api.getApp('MY_APP_ID', {
819
+ * includeSchema: true,
820
+ * includePerms: true,
821
+ * });
822
+ * ```
823
+ *
824
+ * @template Opts – Narrow the shape of the response via the
825
+ * {@link AppDataOpts} flags.
826
+ * @param appId – UUID of the app.
827
+ * @param opts – `{ includeSchema?: boolean; includePerms?: boolean }`
828
+ * @returns A typed wrapper containing the app, whose shape is expanded
829
+ * according to `Opts`.
830
+ */
831
+ async getApp(appId, opts) {
832
+ return this.withRetry(getApp, [this.#apiURI, this.token(), appId, opts]);
833
+ }
834
+ /**
835
+ * List **all apps** owned by the auth owner.
836
+ *
837
+ * ```ts
838
+ * const { apps } = await api.getApps({
839
+ * includeSchema: true,
840
+ * includePerms: true,
841
+ * });
842
+ * ```
843
+ *
844
+ * @template Opts – Same as {@link getApp}.
845
+ * @param opts – `{ includeSchema?: boolean; includePerms?: boolean }`
846
+ * @returns An array wrapper; each element’s shape follows `Opts`.
847
+ */
848
+ async getApps(opts) {
849
+ return this.withRetry(getApps, [this.#apiURI, this.token(), opts]);
850
+ }
851
+ /**
852
+ * List **all orgs** that the auth owner is a member of.
853
+ *
854
+ * ```ts
855
+ * const { orgs } = await api.getOrgs();
856
+ * ```
857
+ *
858
+ * @returns An array of orgs
859
+ */
860
+ async getOrgs() {
861
+ return this.withRetry(getOrgs, [this.#apiURI, this.token()]);
862
+ }
863
+ /**
864
+ * List **all apps** owned by the auth owner.
865
+ *
866
+ * ```ts
867
+ * const { apps } = await api.getApps({
868
+ * includeSchema: true,
869
+ * includePerms: true,
870
+ * });
871
+ * ```
872
+ *
873
+ * @template Opts – Same as {@link getApp}.
874
+ * @param opts – `{ includeSchema?: boolean; includePerms?: boolean }`
875
+ * @returns An array wrapper; each element’s shape follows `Opts`.
876
+ */
877
+ async getAppsForOrg(orgId, opts) {
878
+ return this.withRetry(getAppsForOrg, [
879
+ this.#apiURI,
880
+ this.token(),
881
+ orgId,
882
+ opts,
883
+ ]);
884
+ }
885
+ /**
886
+ * Gets the schema for an app by its id.
887
+ *
888
+ * ```ts
889
+ * const { schema } = await api.getSchema('MY_APP_ID');
890
+ * ```
891
+ *
892
+ * @param appId -- UUID of the app
893
+ */
894
+ async getSchema(appId) {
895
+ return this.withRetry(getAppSchema, [this.#apiURI, this.token(), appId]);
896
+ }
897
+ /**
898
+ * Gets the permissions for an app by its id.
899
+ *
900
+ * ```ts
901
+ * const { perms } = await api.getPerms('MY_APP_ID');
902
+ * ```
903
+ *
904
+ * @param appId -- UUID of the app
905
+ */
906
+ async getPerms(appId) {
907
+ return this.withRetry(getAppPerms, [this.#apiURI, this.token(), appId]);
908
+ }
909
+ /**
910
+ * Create a new app.
911
+ *
912
+ * The app will be placed in the authenticated user's account
913
+ * if no orgId is provided.
914
+ *
915
+ * Optionally set permissions and schema.
916
+ *
917
+ * ```ts
918
+ * const { app } = await api.createApp({
919
+ * title: 'My new app',
920
+ * // Optional permissions
921
+ * perms: { $default: { allow: { $default: 'false' } } },
922
+ * // Optional schema
923
+ * schema: i.schema({
924
+ * entities: { books: i.entity({ title: i.string() }) },
925
+ * }),
926
+ * });
927
+ * ```
928
+ *
929
+ * @param fields
930
+ * @param fields.title -- Title for app
931
+ * @param fields.schema -- Optional schema for the app
932
+ * @param fields.perms -- Optional permissions for the app
933
+ * @param fields.orgId -- Optional id of the org that the app will be placed in
934
+ */
935
+ async createApp(fields) {
936
+ return this.withRetry(createApp, [this.#apiURI, this.token(), fields]);
937
+ }
938
+ /**
939
+ * Create a new temporary app.
940
+ *
941
+ * Optionally set permissions and schema.
942
+ *
943
+ * ```ts
944
+ * const { app } = await api.createTemporaryApp({
945
+ * title: 'My new app',
946
+ * // Optional permissions
947
+ * perms: { $default: { allow: { $default: 'false' } } },
948
+ * // Optional schema
949
+ * schema: i.schema({
950
+ * entities: { books: i.entity({ title: i.string() }) },
951
+ * }),
952
+ * });
953
+ * ```
954
+ *
955
+ * @param fields
956
+ * @param fields.title -- Title for app
957
+ * @param fields.schema -- Optional schema for the app
958
+ * @param fields.perms -- Optional permissions for the app
959
+ */
960
+ async createTemporaryApp(fields) {
961
+ return createTemporaryApp(this.#apiURI, fields);
962
+ }
963
+ /**
964
+ * Update the title of an app by its id.
965
+ *
966
+ * ```ts
967
+ * const { app } = await api.updateApp('MY_APP_ID', {
968
+ * title: 'New title',
969
+ * });
970
+ * ```
971
+ *
972
+ * @param appId -- UUID of the app
973
+ * @param fields.title -- New title for the app
974
+ */
975
+ async updateApp(appId, fields) {
976
+ return this.withRetry(updateApp, [
977
+ this.#apiURI,
978
+ this.token(),
979
+ appId,
980
+ fields,
981
+ ]);
982
+ }
983
+ /**
984
+ * Delete an app by its id.
985
+ *
986
+ * ```ts
987
+ * const { app } = await api.deleteApp('MY_APP_ID');
988
+ * ```
989
+ *
990
+ * @param appId -- UUID of the app
991
+ */
992
+ async deleteApp(appId) {
993
+ return this.withRetry(deleteApp, [this.#apiURI, this.token(), appId]);
994
+ }
995
+ /**
996
+ * Dry-run a **schema push** and receive a _plan_ of steps the server would
997
+ * execute.
998
+ *
999
+ * ```ts
1000
+ * const { steps } = await api.planSchemaPush(appId, body);
1001
+ * ```
1002
+ */
1003
+ async planSchemaPush(appId, body) {
1004
+ const useOverwrite = shouldOverwrite(body);
1005
+ return this.withRetry(useOverwrite ? planSchemaPushOverwrite : planSchemaPush, [this.#apiURI, this.token(), appId, body]);
1006
+ }
1007
+ /**
1008
+ * Execute a **schema push**. The server returns a long-running job
1009
+ * represented as a {@link ProgressPromise}: you can both `await` the final
1010
+ * result **or** subscribe to intermediate status updates.
1011
+ *
1012
+ * ```ts
1013
+ * // 1) Subscribe to progress
1014
+ * const schema = i.schema({
1015
+ * entities: {
1016
+ * books: i.entity({
1017
+ * title: i.string().indexed(),
1018
+ * }),
1019
+ * },
1020
+ * });
1021
+ * const job = api.schemaPush(appId, { overwrite: true, schema: schema });
1022
+ * job
1023
+ * .then(({ summary }) => console.log('done!', summary))
1024
+ * .catch((e) => console.error(e));
1025
+ * job.subscribe({
1026
+ * next: (status) => renderProgress(status),
1027
+ * });
1028
+ *
1029
+ * // 2) Or just await it
1030
+ * const result = await api.schemaPush(appId, { schema: schema });
1031
+ * ```
1032
+ */
1033
+ schemaPush(appId, body) {
1034
+ if (!this.#auth) {
1035
+ throw new PlatformApiMissingAuthError();
1036
+ }
1037
+ return new ProgressPromise(async (progress, resolve, reject) => {
1038
+ try {
1039
+ const useOverwrite = shouldOverwrite(body);
1040
+ const pushFn = useOverwrite ? schemaPushOverwrite : schemaPush;
1041
+ // It's tricky to add withRetry to the background process that fetches the jobs,
1042
+ // so we'll just refresh the token at the start.
1043
+ if (this.canRefreshToken()) {
1044
+ try {
1045
+ await this.refreshToken();
1046
+ }
1047
+ catch (_e) { }
1048
+ }
1049
+ pushFn(this.#apiURI, this.token(), appId, body).subscribe({
1050
+ complete(v) {
1051
+ resolve(v);
1052
+ },
1053
+ error(e) {
1054
+ reject(e);
1055
+ },
1056
+ next(v) {
1057
+ progress(v);
1058
+ },
1059
+ });
1060
+ }
1061
+ catch (e) {
1062
+ reject(e);
1063
+ }
1064
+ });
1065
+ }
1066
+ /**
1067
+ * Update permission rules for an app by its id.
1068
+ *
1069
+ * Completely replaces the current rule set.
1070
+ *
1071
+ * ```ts
1072
+ * const { steps } = await api.pushPerms(appId, {
1073
+ * perms: {
1074
+ * $default: { allow: { $default: 'false' } },
1075
+ * books: { allow: { view: 'true', $default: 'false' } },
1076
+ * },
1077
+ * });
1078
+ * ```
1079
+ */
1080
+ async pushPerms(appId, body) {
1081
+ if (!this.#auth) {
1082
+ throw new PlatformApiMissingAuthError();
1083
+ }
1084
+ return this.withRetry(pushPerms, [this.#apiURI, this.token(), appId, body]);
1085
+ }
1086
+ async tokenInfo() {
1087
+ if (!this.#auth) {
1088
+ throw new PlatformApiMissingAuthError();
1089
+ }
1090
+ return this.withRetry(tokenInfo, [this.#apiURI, this.token()]);
1091
+ }
1092
+ /**
1093
+ * Returns a {@link Webhooks} instance scoped to `appId`. You don't need
1094
+ * auth on this PlatformApi to verify signatures or process incoming
1095
+ * deliveries — only `webhooks(appId).manager.*` requires it, and those
1096
+ * calls are routed through {@link withRetry}, so an expired access token
1097
+ * is transparently refreshed.
1098
+ *
1099
+ * Pass `schema` (e.g. from {@link apiSchemaToInstantSchemaDef}) for typed
1100
+ * handler records and typed `namespaces` on `manager.create`/`update`.
1101
+ */
1102
+ webhooks(appId, opts) {
1103
+ const withAuth = (operation) => this.withRetry((_apiURI, token) => operation(token), [this.#apiURI, this.token()]);
1104
+ return new Webhooks({
1105
+ appId,
1106
+ apiURI: this.#apiURI,
1107
+ schema: opts?.schema,
1108
+ withAuth,
1109
+ });
1110
+ }
1111
+ /**
1112
+ * Returns a {@link BackupsManager} scoped to `appId` for listing an app's
1113
+ * backups and downloading their contents. Calls are routed through
1114
+ * {@link withRetry}, so an expired access token is transparently refreshed.
1115
+ */
1116
+ backups(appId) {
1117
+ const withAuth = (operation) => this.withRetry((_apiURI, token) => operation(token), [this.#apiURI, this.token()]);
1118
+ return new BackupsManager({ appId, apiURI: this.#apiURI, withAuth });
1119
+ }
1120
+ }
1121
+ //# sourceMappingURL=api.js.map