@sidekickdb/platform 0.0.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.tshy/build.json +8 -0
- package/.tshy/commonjs.json +16 -0
- package/.tshy/esm.json +15 -0
- package/.turbo/turbo-build.log +50 -0
- package/LICENSE.md +202 -0
- package/NOTICE +27 -0
- package/README.md +444 -2
- package/__tests__/src/apiURI.test.ts +58 -0
- package/__tests__/src/backupDownload.test.ts +427 -0
- package/__tests__/src/backups.test.ts +168 -0
- package/__tests__/src/clerk.test.ts +13 -0
- package/__tests__/src/consts.test.ts +11 -0
- package/__tests__/src/migrations.test.ts +885 -0
- package/__tests__/src/perms.test.ts +102 -0
- package/__tests__/src/rename.test.ts +126 -0
- package/__tests__/src/schema.push.e2e.test.ts +186 -0
- package/__tests__/src/schema.test.ts +644 -0
- package/__tests__/src/typescript-schema.test.ts +117 -0
- package/dist/commonjs/ProgressPromise.d.ts +18 -0
- package/dist/commonjs/ProgressPromise.d.ts.map +1 -0
- package/dist/commonjs/ProgressPromise.js +77 -0
- package/dist/commonjs/ProgressPromise.js.map +1 -0
- package/dist/commonjs/api.d.ts +480 -0
- package/dist/commonjs/api.d.ts.map +1 -0
- package/dist/commonjs/api.js +1132 -0
- package/dist/commonjs/api.js.map +1 -0
- package/dist/commonjs/backupDownload.d.ts +89 -0
- package/dist/commonjs/backupDownload.d.ts.map +1 -0
- package/dist/commonjs/backupDownload.js +357 -0
- package/dist/commonjs/backupDownload.js.map +1 -0
- package/dist/commonjs/backups.d.ts +146 -0
- package/dist/commonjs/backups.d.ts.map +1 -0
- package/dist/commonjs/backups.js +248 -0
- package/dist/commonjs/backups.js.map +1 -0
- package/dist/commonjs/clerk.d.ts +2 -0
- package/dist/commonjs/clerk.d.ts.map +1 -0
- package/dist/commonjs/clerk.js +29 -0
- package/dist/commonjs/clerk.js.map +1 -0
- package/dist/commonjs/consts.d.ts +11 -0
- package/dist/commonjs/consts.d.ts.map +1 -0
- package/dist/commonjs/consts.js +17 -0
- package/dist/commonjs/consts.js.map +1 -0
- package/dist/commonjs/crypto.d.ts +4 -0
- package/dist/commonjs/crypto.d.ts.map +1 -0
- package/dist/commonjs/crypto.js +26 -0
- package/dist/commonjs/crypto.js.map +1 -0
- package/dist/commonjs/index.d.ts +18 -0
- package/dist/commonjs/index.d.ts.map +1 -0
- package/dist/commonjs/index.js +61 -0
- package/dist/commonjs/index.js.map +1 -0
- package/dist/commonjs/migrationUtils.d.ts +4 -0
- package/dist/commonjs/migrationUtils.d.ts.map +1 -0
- package/dist/commonjs/migrationUtils.js +52 -0
- package/dist/commonjs/migrationUtils.js.map +1 -0
- package/dist/commonjs/migrations.d.ts +99 -0
- package/dist/commonjs/migrations.d.ts.map +1 -0
- package/dist/commonjs/migrations.js +597 -0
- package/dist/commonjs/migrations.js.map +1 -0
- package/dist/commonjs/oauth.d.ts +98 -0
- package/dist/commonjs/oauth.d.ts.map +1 -0
- package/dist/commonjs/oauth.js +277 -0
- package/dist/commonjs/oauth.js.map +1 -0
- package/dist/commonjs/oauthCommon.d.ts +12 -0
- package/dist/commonjs/oauthCommon.d.ts.map +1 -0
- package/dist/commonjs/oauthCommon.js +26 -0
- package/dist/commonjs/oauthCommon.js.map +1 -0
- package/dist/commonjs/package.json +3 -0
- package/dist/commonjs/perms.d.ts +3 -0
- package/dist/commonjs/perms.d.ts.map +1 -0
- package/dist/commonjs/perms.js +66 -0
- package/dist/commonjs/perms.js.map +1 -0
- package/dist/commonjs/relationships.d.ts +7 -0
- package/dist/commonjs/relationships.d.ts.map +1 -0
- package/dist/commonjs/relationships.js +46 -0
- package/dist/commonjs/relationships.js.map +1 -0
- package/dist/commonjs/schema.d.ts +161 -0
- package/dist/commonjs/schema.d.ts.map +1 -0
- package/dist/commonjs/schema.js +174 -0
- package/dist/commonjs/schema.js.map +1 -0
- package/dist/commonjs/serverOAuth.d.ts +25 -0
- package/dist/commonjs/serverOAuth.d.ts.map +1 -0
- package/dist/commonjs/serverOAuth.js +72 -0
- package/dist/commonjs/serverOAuth.js.map +1 -0
- package/dist/commonjs/typescript-schema.d.ts +17 -0
- package/dist/commonjs/typescript-schema.d.ts.map +1 -0
- package/dist/commonjs/typescript-schema.js +314 -0
- package/dist/commonjs/typescript-schema.js.map +1 -0
- package/dist/commonjs/util.d.ts +13 -0
- package/dist/commonjs/util.d.ts.map +1 -0
- package/dist/commonjs/util.js +55 -0
- package/dist/commonjs/util.js.map +1 -0
- package/dist/commonjs/version.d.ts +3 -0
- package/dist/commonjs/version.d.ts.map +1 -0
- package/dist/commonjs/version.js +5 -0
- package/dist/commonjs/version.js.map +1 -0
- package/dist/esm/ProgressPromise.d.ts +18 -0
- package/dist/esm/ProgressPromise.d.ts.map +1 -0
- package/dist/esm/ProgressPromise.js +73 -0
- package/dist/esm/ProgressPromise.js.map +1 -0
- package/dist/esm/api.d.ts +480 -0
- package/dist/esm/api.d.ts.map +1 -0
- package/dist/esm/api.js +1121 -0
- package/dist/esm/api.js.map +1 -0
- package/dist/esm/backupDownload.d.ts +89 -0
- package/dist/esm/backupDownload.d.ts.map +1 -0
- package/dist/esm/backupDownload.js +354 -0
- package/dist/esm/backupDownload.js.map +1 -0
- package/dist/esm/backups.d.ts +146 -0
- package/dist/esm/backups.d.ts.map +1 -0
- package/dist/esm/backups.js +237 -0
- package/dist/esm/backups.js.map +1 -0
- package/dist/esm/clerk.d.ts +2 -0
- package/dist/esm/clerk.d.ts.map +1 -0
- package/dist/esm/clerk.js +26 -0
- package/dist/esm/clerk.js.map +1 -0
- package/dist/esm/consts.d.ts +11 -0
- package/dist/esm/consts.d.ts.map +1 -0
- package/dist/esm/consts.js +13 -0
- package/dist/esm/consts.js.map +1 -0
- package/dist/esm/crypto.d.ts +4 -0
- package/dist/esm/crypto.d.ts.map +1 -0
- package/dist/esm/crypto.js +21 -0
- package/dist/esm/crypto.js.map +1 -0
- package/dist/esm/index.d.ts +18 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +17 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/migrationUtils.d.ts +4 -0
- package/dist/esm/migrationUtils.d.ts.map +1 -0
- package/dist/esm/migrationUtils.js +47 -0
- package/dist/esm/migrationUtils.js.map +1 -0
- package/dist/esm/migrations.d.ts +99 -0
- package/dist/esm/migrations.d.ts.map +1 -0
- package/dist/esm/migrations.js +588 -0
- package/dist/esm/migrations.js.map +1 -0
- package/dist/esm/oauth.d.ts +98 -0
- package/dist/esm/oauth.d.ts.map +1 -0
- package/dist/esm/oauth.js +268 -0
- package/dist/esm/oauth.js.map +1 -0
- package/dist/esm/oauthCommon.d.ts +12 -0
- package/dist/esm/oauthCommon.d.ts.map +1 -0
- package/dist/esm/oauthCommon.js +22 -0
- package/dist/esm/oauthCommon.js.map +1 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/perms.d.ts +3 -0
- package/dist/esm/perms.d.ts.map +1 -0
- package/dist/esm/perms.js +62 -0
- package/dist/esm/perms.js.map +1 -0
- package/dist/esm/relationships.d.ts +7 -0
- package/dist/esm/relationships.d.ts.map +1 -0
- package/dist/esm/relationships.js +43 -0
- package/dist/esm/relationships.js.map +1 -0
- package/dist/esm/schema.d.ts +161 -0
- package/dist/esm/schema.d.ts.map +1 -0
- package/dist/esm/schema.js +158 -0
- package/dist/esm/schema.js.map +1 -0
- package/dist/esm/serverOAuth.d.ts +25 -0
- package/dist/esm/serverOAuth.d.ts.map +1 -0
- package/dist/esm/serverOAuth.js +68 -0
- package/dist/esm/serverOAuth.js.map +1 -0
- package/dist/esm/typescript-schema.d.ts +17 -0
- package/dist/esm/typescript-schema.d.ts.map +1 -0
- package/dist/esm/typescript-schema.js +310 -0
- package/dist/esm/typescript-schema.js.map +1 -0
- package/dist/esm/util.d.ts +13 -0
- package/dist/esm/util.d.ts.map +1 -0
- package/dist/esm/util.js +46 -0
- package/dist/esm/util.js.map +1 -0
- package/dist/esm/version.d.ts +3 -0
- package/dist/esm/version.d.ts.map +1 -0
- package/dist/esm/version.js +3 -0
- package/dist/esm/version.js.map +1 -0
- package/dist/standalone/index.js +13747 -0
- package/dist/standalone/index.umd.cjs +72 -0
- package/package.json +69 -3
- package/src/ProgressPromise.ts +97 -0
- package/src/api.ts +1903 -0
- package/src/backupDownload.ts +519 -0
- package/src/backups.ts +342 -0
- package/src/clerk.ts +24 -0
- package/src/consts.ts +22 -0
- package/src/crypto.ts +28 -0
- package/src/index.ts +147 -0
- package/src/migrationUtils.ts +56 -0
- package/src/migrations.ts +920 -0
- package/src/oauth.ts +390 -0
- package/src/oauthCommon.ts +38 -0
- package/src/perms.ts +81 -0
- package/src/relationships.ts +57 -0
- package/src/schema.ts +497 -0
- package/src/serverOAuth.ts +119 -0
- package/src/typescript-schema.ts +439 -0
- package/src/util.ts +77 -0
- package/src/version.ts +3 -0
- package/tsconfig.dev.json +14 -0
- package/tsconfig.json +14 -0
- package/vite.config.ts +19 -0
package/src/api.ts
ADDED
|
@@ -0,0 +1,1903 @@
|
|
|
1
|
+
import {
|
|
2
|
+
InstantAPIError,
|
|
3
|
+
requireApiURI,
|
|
4
|
+
version as coreVersion,
|
|
5
|
+
InstantRules,
|
|
6
|
+
InstantSchemaDef,
|
|
7
|
+
InstantUnknownSchema,
|
|
8
|
+
EntitiesDef,
|
|
9
|
+
LinksDef,
|
|
10
|
+
RoomsDef,
|
|
11
|
+
InstantDBAttr,
|
|
12
|
+
InstantDBIdent,
|
|
13
|
+
InstantDBCheckedDataType,
|
|
14
|
+
i,
|
|
15
|
+
InstantDBInferredType,
|
|
16
|
+
DataAttrDef,
|
|
17
|
+
} from '@sidekickdb/core';
|
|
18
|
+
import { Webhooks, type WithAuth } from '@sidekickdb/webhooks';
|
|
19
|
+
import { BackupsManager } from './backups.ts';
|
|
20
|
+
import version from './version.ts';
|
|
21
|
+
import {
|
|
22
|
+
attrFwdLabel,
|
|
23
|
+
attrFwdName,
|
|
24
|
+
attrRevName,
|
|
25
|
+
collectSystemCatalogIdentNames,
|
|
26
|
+
identName,
|
|
27
|
+
InstantAPIPlatformSchema,
|
|
28
|
+
InstantAPISchemaPlanStep,
|
|
29
|
+
InstantAPISchemaPushStep,
|
|
30
|
+
validateSchema,
|
|
31
|
+
} from './schema.ts';
|
|
32
|
+
import { ProgressPromise } from './ProgressPromise.ts';
|
|
33
|
+
import {
|
|
34
|
+
capitalizeFirstLetter,
|
|
35
|
+
deriveClientType,
|
|
36
|
+
rels,
|
|
37
|
+
sortedEntries,
|
|
38
|
+
} from './util.ts';
|
|
39
|
+
import { exchangeRefreshToken } from './serverOAuth.ts';
|
|
40
|
+
import {
|
|
41
|
+
buildAutoRenameSelector,
|
|
42
|
+
convertTxSteps,
|
|
43
|
+
diffSchemas,
|
|
44
|
+
RenameCommand,
|
|
45
|
+
} from './migrations.ts';
|
|
46
|
+
|
|
47
|
+
type Simplify<T> = {
|
|
48
|
+
[K in keyof T]: T[K];
|
|
49
|
+
} & {};
|
|
50
|
+
|
|
51
|
+
type AppDataOpts = {
|
|
52
|
+
includePerms?: boolean | null | undefined;
|
|
53
|
+
includeSchema?: boolean | null | undefined;
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
type AppResponseJSON<Opts extends AppDataOpts | undefined> = Simplify<
|
|
57
|
+
{
|
|
58
|
+
id: string;
|
|
59
|
+
title: string;
|
|
60
|
+
created_at: Date;
|
|
61
|
+
org_id: string | null;
|
|
62
|
+
'admin-token'?: string;
|
|
63
|
+
} & (NonNullable<Opts>['includePerms'] extends true
|
|
64
|
+
? { perms: InstantRules }
|
|
65
|
+
: {}) &
|
|
66
|
+
(NonNullable<Opts>['includeSchema'] extends true
|
|
67
|
+
? {
|
|
68
|
+
schema: InstantAPIPlatformSchema;
|
|
69
|
+
}
|
|
70
|
+
: {})
|
|
71
|
+
>;
|
|
72
|
+
|
|
73
|
+
type OrgResponseJSON = {
|
|
74
|
+
id: string;
|
|
75
|
+
title: string;
|
|
76
|
+
created_at: Date;
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
export type InstantAPIAppDetails<Opts extends AppDataOpts | undefined> =
|
|
80
|
+
Simplify<
|
|
81
|
+
{
|
|
82
|
+
id: string;
|
|
83
|
+
title: string;
|
|
84
|
+
createdAt: Date;
|
|
85
|
+
orgId: string | null;
|
|
86
|
+
} & (NonNullable<Opts>['includePerms'] extends true
|
|
87
|
+
? { perms: InstantRules }
|
|
88
|
+
: {}) &
|
|
89
|
+
(NonNullable<Opts>['includeSchema'] extends true
|
|
90
|
+
? {
|
|
91
|
+
schema: InstantSchemaDef<
|
|
92
|
+
EntitiesDef,
|
|
93
|
+
LinksDef<EntitiesDef>,
|
|
94
|
+
RoomsDef
|
|
95
|
+
>;
|
|
96
|
+
}
|
|
97
|
+
: {})
|
|
98
|
+
>;
|
|
99
|
+
|
|
100
|
+
export type InstantAPIOrgDetails = {
|
|
101
|
+
id: string;
|
|
102
|
+
title: string;
|
|
103
|
+
createdAt: Date;
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
export type InstantAPIGetAppResponse<Opts extends AppDataOpts> = Simplify<{
|
|
107
|
+
app: InstantAPIAppDetails<Opts>;
|
|
108
|
+
}>;
|
|
109
|
+
|
|
110
|
+
export type InstantAPIListAppsResponse<Opts extends AppDataOpts | undefined> =
|
|
111
|
+
Simplify<{
|
|
112
|
+
apps: InstantAPIAppDetails<Opts>[];
|
|
113
|
+
}>;
|
|
114
|
+
|
|
115
|
+
export type InstantAPIListOrgsResponse = {
|
|
116
|
+
orgs: InstantAPIOrgDetails[];
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
export type InstantAPIGetAppSchemaResponse = {
|
|
120
|
+
schema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
export type InstantAPIGetAppPermsResponse = { perms: InstantRules };
|
|
124
|
+
|
|
125
|
+
export type InstantAPICreateAppBody = {
|
|
126
|
+
title: string;
|
|
127
|
+
schema?:
|
|
128
|
+
| InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>
|
|
129
|
+
| null
|
|
130
|
+
| undefined;
|
|
131
|
+
perms?: InstantRules | null | undefined;
|
|
132
|
+
orgId?: string | null | undefined;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
export type InstantAPICreateTemporaryAppBody = {
|
|
136
|
+
title: string;
|
|
137
|
+
schema?:
|
|
138
|
+
| InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>
|
|
139
|
+
| null
|
|
140
|
+
| undefined;
|
|
141
|
+
rules?: {
|
|
142
|
+
code: InstantRules;
|
|
143
|
+
} | null;
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
export type InstantAPICreateTemporaryAppResponse = {
|
|
147
|
+
app: Simplify<
|
|
148
|
+
InstantAPIAppDetails<{ includePerms: false; includeSchema: false }> & {
|
|
149
|
+
adminToken: string;
|
|
150
|
+
}
|
|
151
|
+
>;
|
|
152
|
+
expiresMs: number;
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
export type InstantAPICreateAppResponse = Simplify<{
|
|
156
|
+
app: InstantAPIAppDetails<{ includePerms: true; includeSchema: true }> & {
|
|
157
|
+
adminToken: string;
|
|
158
|
+
};
|
|
159
|
+
}>;
|
|
160
|
+
|
|
161
|
+
export type InstantAPIUpdateAppBody = { title: string };
|
|
162
|
+
|
|
163
|
+
export type InstantAPIUpdateAppResponse = Simplify<{
|
|
164
|
+
app: InstantAPIAppDetails<{}>;
|
|
165
|
+
}>;
|
|
166
|
+
|
|
167
|
+
export type InstantAPIDeleteAppResponse = Simplify<{
|
|
168
|
+
app: InstantAPIAppDetails<{}>;
|
|
169
|
+
}>;
|
|
170
|
+
|
|
171
|
+
export type InstantAPISchemaPushBody =
|
|
172
|
+
| {
|
|
173
|
+
schema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;
|
|
174
|
+
overwrite?: false;
|
|
175
|
+
}
|
|
176
|
+
| {
|
|
177
|
+
schema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;
|
|
178
|
+
overwrite: true;
|
|
179
|
+
renames?: RenameCommand[];
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
export type InstantAPIPushPermsBody = {
|
|
183
|
+
perms: InstantRules;
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
export type InstantAPIPushPermsResponse = {
|
|
187
|
+
perms: InstantRules;
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
export type InstantAPITokenInfoResponse = {
|
|
191
|
+
expiresAt: Date;
|
|
192
|
+
scopes: string;
|
|
193
|
+
tokenType: 'Bearer';
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
export type PlanStep =
|
|
197
|
+
| ['add-attr', InstantDBAttr]
|
|
198
|
+
| ['update-attr', Partial<InstantDBAttr>]
|
|
199
|
+
| ['index', { 'attr-id': string; 'forward-identity': InstantDBIdent }]
|
|
200
|
+
| ['remove-index', { 'attr-id': string; 'forward-identity': InstantDBIdent }]
|
|
201
|
+
| ['unique', { 'attr-id': string; 'forward-identity': InstantDBIdent }]
|
|
202
|
+
| ['remove-unique', { 'attr-id': string; 'forward-identity': InstantDBIdent }]
|
|
203
|
+
| ['required', { 'attr-id': string; 'forward-identity': InstantDBIdent }]
|
|
204
|
+
| [
|
|
205
|
+
'remove-required',
|
|
206
|
+
{ 'attr-id': string; 'forward-identity': InstantDBIdent },
|
|
207
|
+
]
|
|
208
|
+
| [
|
|
209
|
+
'check-data-type',
|
|
210
|
+
{
|
|
211
|
+
'attr-id': string;
|
|
212
|
+
'forward-identity': InstantDBIdent;
|
|
213
|
+
'checked-data-type': InstantDBCheckedDataType;
|
|
214
|
+
},
|
|
215
|
+
]
|
|
216
|
+
| [
|
|
217
|
+
'remove-data-type',
|
|
218
|
+
{ 'attr-id': string; 'forward-identity': InstantDBIdent },
|
|
219
|
+
]
|
|
220
|
+
| ['delete-attr', string];
|
|
221
|
+
|
|
222
|
+
type PlanReponseJSON = {
|
|
223
|
+
'new-schema': InstantAPIPlatformSchema;
|
|
224
|
+
'current-schema': InstantAPIPlatformSchema;
|
|
225
|
+
'current-attrs': InstantDBAttr[];
|
|
226
|
+
steps: PlanStep[];
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
// Same as PlanStep, but some background steps get a job-id
|
|
230
|
+
type StepWithJobId<T> = T extends ['add-attr', infer P]
|
|
231
|
+
? ['add-attr', P]
|
|
232
|
+
: T extends ['update-attr', infer P]
|
|
233
|
+
? ['update-attr', P]
|
|
234
|
+
: T extends [infer K, infer P]
|
|
235
|
+
? [K, P & { 'job-id': string }]
|
|
236
|
+
: never;
|
|
237
|
+
|
|
238
|
+
type PushStep = StepWithJobId<PlanStep>;
|
|
239
|
+
|
|
240
|
+
type IndexingJobJSON = {
|
|
241
|
+
id: string;
|
|
242
|
+
app_id: string;
|
|
243
|
+
group_id: string;
|
|
244
|
+
attr_id: string;
|
|
245
|
+
attr_name: string;
|
|
246
|
+
job_type:
|
|
247
|
+
| 'check-data-type'
|
|
248
|
+
| 'remove-data-type'
|
|
249
|
+
| 'index'
|
|
250
|
+
| 'remove-index'
|
|
251
|
+
| 'unique'
|
|
252
|
+
| 'remove-unique'
|
|
253
|
+
| 'required'
|
|
254
|
+
| 'remove-required';
|
|
255
|
+
job_status: 'waiting' | 'processing' | 'completed' | 'errored';
|
|
256
|
+
work_estimate: number | null;
|
|
257
|
+
work_completed: number | null;
|
|
258
|
+
error:
|
|
259
|
+
| 'invalid-triple-error'
|
|
260
|
+
| 'invalid-attr-state-error'
|
|
261
|
+
| 'triple-not-unique-error'
|
|
262
|
+
| 'triple-too-large-error'
|
|
263
|
+
| 'missing-required-error'
|
|
264
|
+
| 'unexpected-error';
|
|
265
|
+
checked_data_type?: InstantDBCheckedDataType;
|
|
266
|
+
created_at: string;
|
|
267
|
+
updated_at: string;
|
|
268
|
+
done_at: string;
|
|
269
|
+
invalid_unique_value: any;
|
|
270
|
+
invalid_triples_sample: {
|
|
271
|
+
entity_id: string;
|
|
272
|
+
value: any;
|
|
273
|
+
json_type:
|
|
274
|
+
| 'string'
|
|
275
|
+
| 'number'
|
|
276
|
+
| 'boolean'
|
|
277
|
+
| 'null'
|
|
278
|
+
| 'object'
|
|
279
|
+
| 'array'
|
|
280
|
+
| 'date';
|
|
281
|
+
}[];
|
|
282
|
+
error_data: any;
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
type SchemaPushResponseJSON = {
|
|
286
|
+
'indexing-jobs'?: {
|
|
287
|
+
'group-id': string;
|
|
288
|
+
jobs: IndexingJobJSON[];
|
|
289
|
+
} | null;
|
|
290
|
+
steps: PushStep[];
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
export type InstantAPIPlanSchemaPushResponse = {
|
|
294
|
+
newSchema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;
|
|
295
|
+
currentSchema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;
|
|
296
|
+
steps: InstantAPISchemaPlanStep[];
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
type InProgressStepsSummary = {
|
|
300
|
+
friendlyDescription: string;
|
|
301
|
+
totalCount: number;
|
|
302
|
+
inProgressCount: number;
|
|
303
|
+
completedCount: number;
|
|
304
|
+
errorCount: number;
|
|
305
|
+
steps: InstantAPISchemaPushStep[];
|
|
306
|
+
inProgressSteps: InstantAPISchemaPushStep[];
|
|
307
|
+
completedSteps: InstantAPISchemaPushStep[];
|
|
308
|
+
erroredSteps: InstantAPISchemaPushStep[];
|
|
309
|
+
};
|
|
310
|
+
|
|
311
|
+
export type InstantAPISchemaPushResponse = {
|
|
312
|
+
newSchema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;
|
|
313
|
+
steps: InstantAPISchemaPushStep[];
|
|
314
|
+
summary: InProgressStepsSummary;
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
async function jsonFetch<T>(
|
|
318
|
+
input: RequestInfo,
|
|
319
|
+
init: RequestInit | undefined,
|
|
320
|
+
): Promise<T> {
|
|
321
|
+
const headers = {
|
|
322
|
+
...(init?.headers || {}),
|
|
323
|
+
'Instant-Platform-Version': version,
|
|
324
|
+
'Instant-Core-Version': coreVersion,
|
|
325
|
+
'X-Instant-Source': 'platform-sdk',
|
|
326
|
+
'X-Instant-Version': version,
|
|
327
|
+
};
|
|
328
|
+
const res = await fetch(input, { ...init, headers });
|
|
329
|
+
if (res.status === 200) {
|
|
330
|
+
const json = await res.json();
|
|
331
|
+
return Promise.resolve(json);
|
|
332
|
+
}
|
|
333
|
+
const body = await res.text();
|
|
334
|
+
try {
|
|
335
|
+
const json = JSON.parse(body);
|
|
336
|
+
return Promise.reject(
|
|
337
|
+
new InstantAPIError({ status: res.status, body: json }),
|
|
338
|
+
);
|
|
339
|
+
} catch (_e) {
|
|
340
|
+
return Promise.reject(
|
|
341
|
+
new InstantAPIError({
|
|
342
|
+
status: res.status,
|
|
343
|
+
body: { type: undefined, message: body },
|
|
344
|
+
}),
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function attrDefForType(
|
|
350
|
+
type: InstantDBCheckedDataType | InstantDBInferredType | 'any',
|
|
351
|
+
) {
|
|
352
|
+
switch (type) {
|
|
353
|
+
case 'string':
|
|
354
|
+
return i.string();
|
|
355
|
+
case 'any':
|
|
356
|
+
return i.any();
|
|
357
|
+
case 'json':
|
|
358
|
+
return i.json();
|
|
359
|
+
case 'boolean':
|
|
360
|
+
return i.boolean();
|
|
361
|
+
case 'date':
|
|
362
|
+
return i.date();
|
|
363
|
+
case 'number':
|
|
364
|
+
return i.number();
|
|
365
|
+
default: {
|
|
366
|
+
const neverType: never = type;
|
|
367
|
+
throw new Error(`Unknown type ${neverType}.`);
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function apiSchemaAttrToDataAttrDef(attr: InstantDBAttr) {
|
|
373
|
+
const derivedType = deriveClientType(attr);
|
|
374
|
+
let i: DataAttrDef<string, boolean, boolean> = attrDefForType(
|
|
375
|
+
derivedType.type,
|
|
376
|
+
);
|
|
377
|
+
if (attr['unique?']) {
|
|
378
|
+
i = i.unique();
|
|
379
|
+
}
|
|
380
|
+
if (attr['index?']) {
|
|
381
|
+
i = i.indexed();
|
|
382
|
+
}
|
|
383
|
+
if (!attr['required?']) {
|
|
384
|
+
i = i.optional();
|
|
385
|
+
}
|
|
386
|
+
i.metadata.derivedType = derivedType;
|
|
387
|
+
return i;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function apiSchemaBlobToEntityDef(
|
|
391
|
+
attrs: InstantAPIPlatformSchema['blobs'][string],
|
|
392
|
+
) {
|
|
393
|
+
const defs: Record<string, DataAttrDef<string, boolean, boolean>> = {};
|
|
394
|
+
for (const [label, attr] of sortedEntries(attrs)) {
|
|
395
|
+
if (label === 'id') {
|
|
396
|
+
continue;
|
|
397
|
+
}
|
|
398
|
+
defs[label] = apiSchemaAttrToDataAttrDef(attr);
|
|
399
|
+
}
|
|
400
|
+
return i.entity(defs);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
function apiSchemaAttrToLinkName(attr: InstantDBAttr): string {
|
|
404
|
+
const [, fe, flabel] = attr['forward-identity'];
|
|
405
|
+
return `${fe}${capitalizeFirstLetter(flabel)}`;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function apiSchemaAttrToLinkDef(attr: InstantDBAttr) {
|
|
409
|
+
const [, fe, flabel] = attr['forward-identity'];
|
|
410
|
+
const [, re, rlabel] = attr['reverse-identity']!;
|
|
411
|
+
const [fhas, rhas] = rels[`${attr.cardinality}-${attr['unique?']}`];
|
|
412
|
+
return {
|
|
413
|
+
forward: {
|
|
414
|
+
on: fe,
|
|
415
|
+
has: fhas,
|
|
416
|
+
label: flabel,
|
|
417
|
+
required: attr['required?'] || undefined,
|
|
418
|
+
onDelete:
|
|
419
|
+
attr['on-delete'] === 'cascade' ? ('cascade' as 'cascade') : undefined,
|
|
420
|
+
},
|
|
421
|
+
reverse: {
|
|
422
|
+
on: re,
|
|
423
|
+
has: rhas,
|
|
424
|
+
label: rlabel,
|
|
425
|
+
onDelete:
|
|
426
|
+
attr['on-delete-reverse'] === 'cascade'
|
|
427
|
+
? ('cascade' as 'cascade')
|
|
428
|
+
: undefined,
|
|
429
|
+
},
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
export function apiSchemaToAttrs(
|
|
434
|
+
apiSchema: InstantAPIPlatformSchema,
|
|
435
|
+
): InstantDBAttr[] {
|
|
436
|
+
let res: InstantDBAttr[] = [];
|
|
437
|
+
for (const [_, attrs] of sortedEntries(apiSchema.blobs)) {
|
|
438
|
+
Object.values(attrs).forEach((a) => {
|
|
439
|
+
res.push(a);
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
for (const [_, a] of sortedEntries(apiSchema.refs)) {
|
|
443
|
+
res.push(a);
|
|
444
|
+
}
|
|
445
|
+
return res;
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
export function apiSchemaToInstantSchemaDef(
|
|
449
|
+
apiSchema: InstantAPIPlatformSchema,
|
|
450
|
+
): InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef> {
|
|
451
|
+
const entities: EntitiesDef = {};
|
|
452
|
+
for (const [etype, attrs] of sortedEntries(apiSchema.blobs)) {
|
|
453
|
+
entities[etype] = apiSchemaBlobToEntityDef(attrs);
|
|
454
|
+
}
|
|
455
|
+
const links: LinksDef<EntitiesDef> = {};
|
|
456
|
+
for (const [_name, attr] of sortedEntries(apiSchema.refs)) {
|
|
457
|
+
const link = apiSchemaAttrToLinkDef(attr);
|
|
458
|
+
const linkName = apiSchemaAttrToLinkName(attr);
|
|
459
|
+
links[linkName] = link;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
return i.schema({ entities, links });
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function coerceApp<Opts extends AppDataOpts>(
|
|
466
|
+
app: AppResponseJSON<Opts>,
|
|
467
|
+
): InstantAPIAppDetails<Opts> {
|
|
468
|
+
const base = {
|
|
469
|
+
id: app.id,
|
|
470
|
+
title: app.title,
|
|
471
|
+
createdAt: new Date(app.created_at),
|
|
472
|
+
orgId: app.org_id,
|
|
473
|
+
...(app['admin-token'] ? { adminToken: app['admin-token'] } : {}),
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
// `in` narrows the union, so it’s safe to read `perms` / `schema`
|
|
477
|
+
// when the property exists. :contentReference[oaicite:0]{index=0}
|
|
478
|
+
const permsPart = (
|
|
479
|
+
'perms' in app ? { perms: app.perms } : {}
|
|
480
|
+
) as InstantAPIAppDetails<Opts>;
|
|
481
|
+
|
|
482
|
+
const schemaPart = (
|
|
483
|
+
'schema' in app
|
|
484
|
+
? {
|
|
485
|
+
schema: apiSchemaToInstantSchemaDef(
|
|
486
|
+
app.schema as InstantAPIPlatformSchema,
|
|
487
|
+
),
|
|
488
|
+
}
|
|
489
|
+
: {}
|
|
490
|
+
) as InstantAPIAppDetails<Opts>;
|
|
491
|
+
|
|
492
|
+
return { ...base, ...permsPart, ...schemaPart };
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
function coerceOrg(org: OrgResponseJSON): InstantAPIOrgDetails {
|
|
496
|
+
return {
|
|
497
|
+
id: org.id,
|
|
498
|
+
title: org.title,
|
|
499
|
+
createdAt: new Date(org.created_at),
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
async function getApps<Opts extends AppDataOpts>(
|
|
504
|
+
apiURI: string,
|
|
505
|
+
token: string,
|
|
506
|
+
opts?: Opts,
|
|
507
|
+
): Promise<InstantAPIListAppsResponse<Opts>> {
|
|
508
|
+
const url = new URL(`${apiURI}/superadmin/apps`);
|
|
509
|
+
const include = [];
|
|
510
|
+
if (opts?.includePerms) {
|
|
511
|
+
include.push('perms');
|
|
512
|
+
}
|
|
513
|
+
if (opts?.includeSchema) {
|
|
514
|
+
include.push('schema');
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
if (include.length) {
|
|
518
|
+
url.searchParams.set('include', include.join(','));
|
|
519
|
+
}
|
|
520
|
+
const resp = await jsonFetch<{ apps: AppResponseJSON<typeof opts>[] }>(
|
|
521
|
+
url.toString(),
|
|
522
|
+
{
|
|
523
|
+
method: 'GET',
|
|
524
|
+
headers: {
|
|
525
|
+
Authorization: `Bearer ${token}`,
|
|
526
|
+
},
|
|
527
|
+
},
|
|
528
|
+
);
|
|
529
|
+
|
|
530
|
+
return { apps: resp.apps.map(coerceApp) };
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
async function getOrgs(
|
|
534
|
+
apiURI: string,
|
|
535
|
+
token: string,
|
|
536
|
+
): Promise<InstantAPIListOrgsResponse> {
|
|
537
|
+
const url = new URL(`${apiURI}/superadmin/orgs`);
|
|
538
|
+
|
|
539
|
+
const resp = await jsonFetch<{ orgs: OrgResponseJSON[] }>(url.toString(), {
|
|
540
|
+
method: 'GET',
|
|
541
|
+
headers: {
|
|
542
|
+
Authorization: `Bearer ${token}`,
|
|
543
|
+
},
|
|
544
|
+
});
|
|
545
|
+
|
|
546
|
+
return { orgs: resp.orgs.map(coerceOrg) };
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
async function getAppsForOrg<Opts extends AppDataOpts>(
|
|
550
|
+
apiURI: string,
|
|
551
|
+
token: string,
|
|
552
|
+
orgId: string,
|
|
553
|
+
opts?: Opts,
|
|
554
|
+
): Promise<InstantAPIListAppsResponse<Opts>> {
|
|
555
|
+
const url = new URL(`${apiURI}/superadmin/orgs/${orgId}/apps`);
|
|
556
|
+
const include = [];
|
|
557
|
+
if (opts?.includePerms) {
|
|
558
|
+
include.push('perms');
|
|
559
|
+
}
|
|
560
|
+
if (opts?.includeSchema) {
|
|
561
|
+
include.push('schema');
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
if (include.length) {
|
|
565
|
+
url.searchParams.set('include', include.join(','));
|
|
566
|
+
}
|
|
567
|
+
const resp = await jsonFetch<{ apps: AppResponseJSON<typeof opts>[] }>(
|
|
568
|
+
url.toString(),
|
|
569
|
+
{
|
|
570
|
+
method: 'GET',
|
|
571
|
+
headers: {
|
|
572
|
+
Authorization: `Bearer ${token}`,
|
|
573
|
+
},
|
|
574
|
+
},
|
|
575
|
+
);
|
|
576
|
+
|
|
577
|
+
return { apps: resp.apps.map(coerceApp) };
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
async function getAppAPISchema(
|
|
581
|
+
apiURI: string,
|
|
582
|
+
token: string,
|
|
583
|
+
appId: string,
|
|
584
|
+
): Promise<InstantAPIPlatformSchema> {
|
|
585
|
+
const { schema: apiSchema } = await jsonFetch<{
|
|
586
|
+
schema: InstantAPIPlatformSchema;
|
|
587
|
+
}>(`${apiURI}/superadmin/apps/${appId}/schema`, {
|
|
588
|
+
method: 'GET',
|
|
589
|
+
headers: {
|
|
590
|
+
Authorization: `Bearer ${token}`,
|
|
591
|
+
},
|
|
592
|
+
});
|
|
593
|
+
return apiSchema;
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
async function getAppSchema(
|
|
597
|
+
apiURI: string,
|
|
598
|
+
token: string,
|
|
599
|
+
appId: string,
|
|
600
|
+
): Promise<InstantAPIGetAppSchemaResponse> {
|
|
601
|
+
const apiSchema = await getAppAPISchema(apiURI, token, appId);
|
|
602
|
+
return { schema: apiSchemaToInstantSchemaDef(apiSchema) };
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
async function getAppPerms(
|
|
606
|
+
apiURI: string,
|
|
607
|
+
token: string,
|
|
608
|
+
appId: string,
|
|
609
|
+
): Promise<InstantAPIGetAppPermsResponse> {
|
|
610
|
+
return await jsonFetch<InstantAPIGetAppPermsResponse>(
|
|
611
|
+
`${apiURI}/superadmin/apps/${appId}/perms`,
|
|
612
|
+
{
|
|
613
|
+
method: 'GET',
|
|
614
|
+
headers: {
|
|
615
|
+
Authorization: `Bearer ${token}`,
|
|
616
|
+
},
|
|
617
|
+
},
|
|
618
|
+
);
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
async function getApp<Opts extends AppDataOpts>(
|
|
622
|
+
apiURI: string,
|
|
623
|
+
token: string,
|
|
624
|
+
appId: string,
|
|
625
|
+
opts?: Opts,
|
|
626
|
+
): Promise<Simplify<InstantAPIGetAppResponse<Opts>>> {
|
|
627
|
+
let permsPromise: null | Promise<InstantAPIGetAppPermsResponse> = null;
|
|
628
|
+
let schemaPromise: null | Promise<InstantAPIGetAppSchemaResponse> = null;
|
|
629
|
+
if (opts?.includePerms) {
|
|
630
|
+
permsPromise = getAppPerms(apiURI, token, appId);
|
|
631
|
+
}
|
|
632
|
+
if (opts?.includeSchema) {
|
|
633
|
+
schemaPromise = getAppSchema(apiURI, token, appId);
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
const { app: apiApp } = await jsonFetch<{ app: AppResponseJSON<{}> }>(
|
|
637
|
+
`${apiURI}/superadmin/apps/${appId}`,
|
|
638
|
+
{
|
|
639
|
+
method: 'GET',
|
|
640
|
+
headers: {
|
|
641
|
+
Authorization: `Bearer ${token}`,
|
|
642
|
+
},
|
|
643
|
+
},
|
|
644
|
+
);
|
|
645
|
+
|
|
646
|
+
if (!permsPromise && !schemaPromise) {
|
|
647
|
+
const app = coerceApp(apiApp) as InstantAPIAppDetails<{}>;
|
|
648
|
+
return { app } as Simplify<InstantAPIGetAppResponse<Opts>>;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
const app = {
|
|
652
|
+
...(coerceApp(apiApp) as unknown as Simplify<InstantAPIGetAppResponse<{}>>),
|
|
653
|
+
...(permsPromise ? { perms: (await permsPromise).perms } : {}),
|
|
654
|
+
...(schemaPromise ? { schema: (await schemaPromise).schema } : {}),
|
|
655
|
+
} as unknown as InstantAPIAppDetails<Opts>;
|
|
656
|
+
|
|
657
|
+
return {
|
|
658
|
+
app,
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
async function createApp(
|
|
663
|
+
apiURI: string,
|
|
664
|
+
token: string,
|
|
665
|
+
fields: InstantAPICreateAppBody,
|
|
666
|
+
): Promise<InstantAPICreateAppResponse> {
|
|
667
|
+
const apiFields: any = fields;
|
|
668
|
+
apiFields.org_id = fields.orgId;
|
|
669
|
+
|
|
670
|
+
const { app } = await jsonFetch<{
|
|
671
|
+
app: AppResponseJSON<{ includePerms: true; includeSchema: true }> & {
|
|
672
|
+
'admin-token': string;
|
|
673
|
+
};
|
|
674
|
+
}>(`${apiURI}/superadmin/apps`, {
|
|
675
|
+
method: 'POST',
|
|
676
|
+
headers: {
|
|
677
|
+
'Content-Type': 'application/json',
|
|
678
|
+
Authorization: `Bearer ${token}`,
|
|
679
|
+
},
|
|
680
|
+
body: JSON.stringify(apiFields),
|
|
681
|
+
});
|
|
682
|
+
const withAdminToken = {
|
|
683
|
+
...coerceApp<{ includePerms: true; includeSchema: true }>(app),
|
|
684
|
+
adminToken: app['admin-token'],
|
|
685
|
+
};
|
|
686
|
+
return {
|
|
687
|
+
app: withAdminToken,
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
async function createTemporaryApp(
|
|
692
|
+
apiURI: string,
|
|
693
|
+
fields: InstantAPICreateTemporaryAppBody,
|
|
694
|
+
): Promise<InstantAPICreateTemporaryAppResponse> {
|
|
695
|
+
const response = await jsonFetch<{ app: any; expires_ms: number }>(
|
|
696
|
+
`${apiURI}/dash/apps/ephemeral`,
|
|
697
|
+
{
|
|
698
|
+
method: 'POST',
|
|
699
|
+
headers: {
|
|
700
|
+
'Content-Type': 'application/json',
|
|
701
|
+
},
|
|
702
|
+
body: JSON.stringify(fields),
|
|
703
|
+
},
|
|
704
|
+
);
|
|
705
|
+
const withAdminToken = {
|
|
706
|
+
...coerceApp<{ includePerms: true; includeSchema: true }>(response.app),
|
|
707
|
+
adminToken: response.app['admin-token'],
|
|
708
|
+
};
|
|
709
|
+
return {
|
|
710
|
+
app: withAdminToken,
|
|
711
|
+
expiresMs: response.expires_ms,
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
async function updateApp(
|
|
716
|
+
apiURI: string,
|
|
717
|
+
token: string,
|
|
718
|
+
appId: string,
|
|
719
|
+
fields: InstantAPIUpdateAppBody,
|
|
720
|
+
): Promise<InstantAPIUpdateAppResponse> {
|
|
721
|
+
const { app } = await jsonFetch<{ app: AppResponseJSON<{}> }>(
|
|
722
|
+
`${apiURI}/superadmin/apps/${appId}`,
|
|
723
|
+
{
|
|
724
|
+
method: 'POST',
|
|
725
|
+
headers: {
|
|
726
|
+
'Content-Type': 'application/json',
|
|
727
|
+
Authorization: `Bearer ${token}`,
|
|
728
|
+
},
|
|
729
|
+
body: JSON.stringify(fields),
|
|
730
|
+
},
|
|
731
|
+
);
|
|
732
|
+
|
|
733
|
+
return { app: coerceApp(app) };
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
async function deleteApp(
|
|
737
|
+
apiURI: string,
|
|
738
|
+
token: string,
|
|
739
|
+
appId: string,
|
|
740
|
+
): Promise<InstantAPIDeleteAppResponse> {
|
|
741
|
+
const { app } = await jsonFetch<{ app: AppResponseJSON<{}> }>(
|
|
742
|
+
`${apiURI}/superadmin/apps/${appId}`,
|
|
743
|
+
{
|
|
744
|
+
method: 'DELETE',
|
|
745
|
+
headers: {
|
|
746
|
+
'Content-Type': 'application/json',
|
|
747
|
+
Authorization: `Bearer ${token}`,
|
|
748
|
+
},
|
|
749
|
+
},
|
|
750
|
+
);
|
|
751
|
+
return { app: coerceApp(app) };
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
function translatePlanStep(
|
|
755
|
+
apiStep: PlanStep,
|
|
756
|
+
currentAttrs: InstantDBAttr[],
|
|
757
|
+
): InstantAPISchemaPlanStep {
|
|
758
|
+
const [stepType, stepParams] = apiStep;
|
|
759
|
+
|
|
760
|
+
switch (stepType) {
|
|
761
|
+
case 'add-attr': {
|
|
762
|
+
const attr = stepParams;
|
|
763
|
+
const attrName = attrFwdName(attr);
|
|
764
|
+
const friendlyDescription =
|
|
765
|
+
attr['value-type'] === 'blob'
|
|
766
|
+
? attrFwdLabel(attr) === 'id'
|
|
767
|
+
? `Create new entity ${attrName}.`
|
|
768
|
+
: `Add attribute ${attrName}.`
|
|
769
|
+
: `Link ${attrName} to ${attrRevName(attr)}.`;
|
|
770
|
+
return { type: 'add-attr', friendlyDescription, attr };
|
|
771
|
+
}
|
|
772
|
+
case 'update-attr': {
|
|
773
|
+
const attr = stepParams as InstantDBAttr;
|
|
774
|
+
return {
|
|
775
|
+
type: 'update-attr',
|
|
776
|
+
friendlyDescription: `Update attribute ${attrFwdName(attr)}.`,
|
|
777
|
+
attr,
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
case 'index': {
|
|
781
|
+
return {
|
|
782
|
+
type: 'index',
|
|
783
|
+
friendlyDescription: `Add index to ${identName(stepParams['forward-identity'])}.`,
|
|
784
|
+
attrId: stepParams['attr-id'],
|
|
785
|
+
forwardIdentity: stepParams['forward-identity'],
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
case 'remove-index': {
|
|
789
|
+
return {
|
|
790
|
+
type: 'remove-index',
|
|
791
|
+
friendlyDescription: `Remove index from ${identName(stepParams['forward-identity'])}.`,
|
|
792
|
+
attrId: stepParams['attr-id'],
|
|
793
|
+
forwardIdentity: stepParams['forward-identity'],
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
case 'unique': {
|
|
797
|
+
return {
|
|
798
|
+
type: 'unique',
|
|
799
|
+
friendlyDescription: `Ensure that ${identName(stepParams['forward-identity'])} is unique.`,
|
|
800
|
+
attrId: stepParams['attr-id'],
|
|
801
|
+
forwardIdentity: stepParams['forward-identity'],
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
case 'remove-unique': {
|
|
805
|
+
return {
|
|
806
|
+
type: 'remove-unique',
|
|
807
|
+
friendlyDescription: `Remove uniqueness constraint from ${identName(stepParams['forward-identity'])}.`,
|
|
808
|
+
attrId: stepParams['attr-id'],
|
|
809
|
+
forwardIdentity: stepParams['forward-identity'],
|
|
810
|
+
};
|
|
811
|
+
}
|
|
812
|
+
case 'required': {
|
|
813
|
+
return {
|
|
814
|
+
type: 'required',
|
|
815
|
+
friendlyDescription: `Make ${identName(stepParams['forward-identity'])} a required attribute.`,
|
|
816
|
+
attrId: stepParams['attr-id'],
|
|
817
|
+
forwardIdentity: stepParams['forward-identity'],
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
case 'remove-required': {
|
|
821
|
+
return {
|
|
822
|
+
type: 'remove-required',
|
|
823
|
+
friendlyDescription: `Allow ${identName(stepParams['forward-identity'])} to be missing or null.`,
|
|
824
|
+
attrId: stepParams['attr-id'],
|
|
825
|
+
forwardIdentity: stepParams['forward-identity'],
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
case 'check-data-type': {
|
|
829
|
+
const forwardIdentity = stepParams['forward-identity'];
|
|
830
|
+
const dataType = stepParams['checked-data-type'];
|
|
831
|
+
return {
|
|
832
|
+
type: 'check-data-type',
|
|
833
|
+
friendlyDescription: `Enforce data type of ${identName(forwardIdentity)} as type ${dataType}.`,
|
|
834
|
+
attrId: stepParams['attr-id'],
|
|
835
|
+
forwardIdentity,
|
|
836
|
+
checkedDataType: dataType,
|
|
837
|
+
};
|
|
838
|
+
}
|
|
839
|
+
case 'remove-data-type': {
|
|
840
|
+
const forwardIdentity = stepParams['forward-identity'];
|
|
841
|
+
return {
|
|
842
|
+
type: 'remove-data-type',
|
|
843
|
+
friendlyDescription: `Stop enforcing data type of ${identName(forwardIdentity)}.`,
|
|
844
|
+
attrId: stepParams['attr-id'],
|
|
845
|
+
forwardIdentity: stepParams['forward-identity'],
|
|
846
|
+
};
|
|
847
|
+
}
|
|
848
|
+
case 'delete-attr': {
|
|
849
|
+
const attrId = stepParams;
|
|
850
|
+
const attr = currentAttrs.find((a) => a.id === attrId);
|
|
851
|
+
const friendlyName = attr ? identName(attr['forward-identity']) : attrId;
|
|
852
|
+
return {
|
|
853
|
+
type: 'delete-attr',
|
|
854
|
+
attrId: stepParams,
|
|
855
|
+
friendlyDescription: `Delete attribute ${friendlyName}.`,
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
default: {
|
|
859
|
+
// Get a type error if we ignore a case
|
|
860
|
+
const unknownType: never = stepType;
|
|
861
|
+
throw new Error(`Unknown schema operation ${unknownType}.`);
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
export function translatePlanSteps(
|
|
867
|
+
apiSteps: PlanStep[],
|
|
868
|
+
currentAttrs: InstantDBAttr[],
|
|
869
|
+
): InstantAPISchemaPlanStep[] {
|
|
870
|
+
return apiSteps.map((step) => translatePlanStep(step, currentAttrs));
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
type PushObjOf<S extends PushStep> =
|
|
874
|
+
// grab from the union the member whose discriminant matches S[0]
|
|
875
|
+
Extract<InstantAPISchemaPushStep, { type: S[0] }>;
|
|
876
|
+
|
|
877
|
+
function translatePushStep<S extends PushStep>(
|
|
878
|
+
apiStep: S,
|
|
879
|
+
jobs: IndexingJobJSON[],
|
|
880
|
+
currentAttrs: InstantDBAttr[],
|
|
881
|
+
): PushObjOf<S> {
|
|
882
|
+
const [stepType, stepParams] = apiStep;
|
|
883
|
+
if (
|
|
884
|
+
stepType === 'add-attr' ||
|
|
885
|
+
stepType === 'update-attr' ||
|
|
886
|
+
stepType === 'delete-attr'
|
|
887
|
+
) {
|
|
888
|
+
const planStep = translatePlanStep(apiStep, currentAttrs);
|
|
889
|
+
if (
|
|
890
|
+
planStep.type !== 'add-attr' &&
|
|
891
|
+
planStep.type !== 'update-attr' &&
|
|
892
|
+
planStep.type !== 'delete-attr'
|
|
893
|
+
) {
|
|
894
|
+
// This is just here for typescript
|
|
895
|
+
throw new Error('Invalid step.');
|
|
896
|
+
}
|
|
897
|
+
return planStep as PushObjOf<S>;
|
|
898
|
+
}
|
|
899
|
+
const jobId = stepParams['job-id'];
|
|
900
|
+
const job = jobs.find((j) => j.id === jobId)!;
|
|
901
|
+
const planStep = translatePlanStep(apiStep, currentAttrs);
|
|
902
|
+
const backgroundJob = formatJob(job);
|
|
903
|
+
|
|
904
|
+
if (planStep.type !== backgroundJob.type) {
|
|
905
|
+
throw new Error('Invalid type');
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
return { ...planStep, backgroundJob } as PushObjOf<S>;
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
function translatePushSteps(
|
|
912
|
+
apiSteps: PushStep[],
|
|
913
|
+
jobs: IndexingJobJSON[],
|
|
914
|
+
currentAttrs: InstantDBAttr[],
|
|
915
|
+
): InstantAPISchemaPushStep[] {
|
|
916
|
+
return apiSteps.map((step) => translatePushStep(step, jobs, currentAttrs));
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
function shouldOverwrite(body: InstantAPISchemaPushBody) {
|
|
920
|
+
if ('renames' in body && !body.overwrite) {
|
|
921
|
+
throw new Error(
|
|
922
|
+
'If you pass in `renames`, you _must_ pass in `overwrite: true`',
|
|
923
|
+
);
|
|
924
|
+
}
|
|
925
|
+
return !!body.overwrite;
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
async function planSchemaPush(
|
|
929
|
+
apiURI: string,
|
|
930
|
+
token: string,
|
|
931
|
+
appId: string,
|
|
932
|
+
body: InstantAPISchemaPushBody,
|
|
933
|
+
): Promise<InstantAPIPlanSchemaPushResponse> {
|
|
934
|
+
const resp = await jsonFetch<PlanReponseJSON>(
|
|
935
|
+
`${apiURI}/superadmin/apps/${appId}/schema/push/plan`,
|
|
936
|
+
{
|
|
937
|
+
method: 'POST',
|
|
938
|
+
headers: {
|
|
939
|
+
'Content-Type': 'application/json',
|
|
940
|
+
Authorization: `Bearer ${token}`,
|
|
941
|
+
},
|
|
942
|
+
body: JSON.stringify({
|
|
943
|
+
...body,
|
|
944
|
+
check_types: true,
|
|
945
|
+
supports_background_updates: true,
|
|
946
|
+
}),
|
|
947
|
+
},
|
|
948
|
+
);
|
|
949
|
+
const currentAttrs = resp['current-attrs'];
|
|
950
|
+
return {
|
|
951
|
+
newSchema: apiSchemaToInstantSchemaDef(resp['new-schema']),
|
|
952
|
+
currentSchema: apiSchemaToInstantSchemaDef(resp['current-schema']),
|
|
953
|
+
steps: translatePlanSteps(resp['steps'], currentAttrs),
|
|
954
|
+
};
|
|
955
|
+
}
|
|
956
|
+
|
|
957
|
+
async function planSchemaPushOverwriteInternal(
|
|
958
|
+
apiURI: string,
|
|
959
|
+
token: string,
|
|
960
|
+
appId: string,
|
|
961
|
+
body: InstantAPISchemaPushBody,
|
|
962
|
+
) {
|
|
963
|
+
const apiSchema = await getAppAPISchema(apiURI, token, appId);
|
|
964
|
+
|
|
965
|
+
const currentSchema = apiSchemaToInstantSchemaDef(apiSchema);
|
|
966
|
+
const currentAttrs = apiSchemaToAttrs(apiSchema);
|
|
967
|
+
|
|
968
|
+
const systemCatalogIdentNames = collectSystemCatalogIdentNames(currentAttrs);
|
|
969
|
+
|
|
970
|
+
const newSchema = body.schema;
|
|
971
|
+
|
|
972
|
+
validateSchema(newSchema, systemCatalogIdentNames);
|
|
973
|
+
|
|
974
|
+
const renames = ('renames' in body ? body.renames : null) || [];
|
|
975
|
+
|
|
976
|
+
const renameSelector = buildAutoRenameSelector(renames);
|
|
977
|
+
|
|
978
|
+
const diffResult = await diffSchemas(
|
|
979
|
+
currentSchema,
|
|
980
|
+
newSchema,
|
|
981
|
+
renameSelector,
|
|
982
|
+
systemCatalogIdentNames,
|
|
983
|
+
);
|
|
984
|
+
|
|
985
|
+
const txSteps = convertTxSteps(diffResult, currentAttrs);
|
|
986
|
+
|
|
987
|
+
return {
|
|
988
|
+
currentSchema,
|
|
989
|
+
currentAttrs,
|
|
990
|
+
txSteps: txSteps,
|
|
991
|
+
steps: translatePlanSteps(txSteps, currentAttrs),
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
async function planSchemaPushOverwrite(
|
|
996
|
+
apiURI: string,
|
|
997
|
+
token: string,
|
|
998
|
+
appId: string,
|
|
999
|
+
body: InstantAPISchemaPushBody,
|
|
1000
|
+
): Promise<InstantAPIPlanSchemaPushResponse> {
|
|
1001
|
+
const { currentSchema, steps } = await planSchemaPushOverwriteInternal(
|
|
1002
|
+
apiURI,
|
|
1003
|
+
token,
|
|
1004
|
+
appId,
|
|
1005
|
+
body,
|
|
1006
|
+
);
|
|
1007
|
+
|
|
1008
|
+
return {
|
|
1009
|
+
newSchema: body.schema,
|
|
1010
|
+
currentSchema: currentSchema,
|
|
1011
|
+
steps: steps,
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
function allJobsComplete(jobs: IndexingJobJSON[]): boolean {
|
|
1016
|
+
if (jobs.length === 0) {
|
|
1017
|
+
return true;
|
|
1018
|
+
}
|
|
1019
|
+
return jobs.every(
|
|
1020
|
+
(j) => j.job_status === 'completed' || j.job_status === 'errored',
|
|
1021
|
+
);
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
function latestJobUpdate(jobs: IndexingJobJSON[]): Date | null {
|
|
1025
|
+
const res = jobs.reduce((acc: Date | null, job) => {
|
|
1026
|
+
if (job.updated_at) {
|
|
1027
|
+
const d = new Date(job.updated_at);
|
|
1028
|
+
if (!acc || d > acc) {
|
|
1029
|
+
return d;
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
return acc;
|
|
1033
|
+
}, null);
|
|
1034
|
+
return res;
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
async function jobFetchLoop(
|
|
1038
|
+
apiURI: string,
|
|
1039
|
+
token: string,
|
|
1040
|
+
appId: string,
|
|
1041
|
+
groupId: string,
|
|
1042
|
+
startingJobs: IndexingJobJSON[],
|
|
1043
|
+
onFetch: (jobs: IndexingJobJSON[]) => void,
|
|
1044
|
+
): Promise<IndexingJobJSON[]> {
|
|
1045
|
+
let interval = 100;
|
|
1046
|
+
let lastJobs = startingJobs;
|
|
1047
|
+
let errorCount = 0;
|
|
1048
|
+
|
|
1049
|
+
while (!allJobsComplete(lastJobs)) {
|
|
1050
|
+
await new Promise((resolve) => setTimeout(resolve, interval));
|
|
1051
|
+
try {
|
|
1052
|
+
const nextJobs = (
|
|
1053
|
+
await jsonFetch<{ jobs: IndexingJobJSON[] }>(
|
|
1054
|
+
`${apiURI}/dash/apps/${appId}/indexing-jobs/group/${groupId}`,
|
|
1055
|
+
{
|
|
1056
|
+
method: 'GET',
|
|
1057
|
+
headers: {
|
|
1058
|
+
Authorization: `Bearer ${token}`,
|
|
1059
|
+
},
|
|
1060
|
+
},
|
|
1061
|
+
)
|
|
1062
|
+
).jobs;
|
|
1063
|
+
onFetch(nextJobs);
|
|
1064
|
+
if (allJobsComplete(nextJobs)) {
|
|
1065
|
+
return nextJobs;
|
|
1066
|
+
}
|
|
1067
|
+
errorCount = 0;
|
|
1068
|
+
const lastUpdate = latestJobUpdate(lastJobs);
|
|
1069
|
+
const thisUpdate = latestJobUpdate(nextJobs);
|
|
1070
|
+
lastJobs = nextJobs;
|
|
1071
|
+
interval =
|
|
1072
|
+
thisUpdate === null || (lastUpdate && lastUpdate >= thisUpdate)
|
|
1073
|
+
? Math.min(interval * 2, 10000)
|
|
1074
|
+
: 100;
|
|
1075
|
+
} catch (e) {
|
|
1076
|
+
if (errorCount > 3) {
|
|
1077
|
+
throw e;
|
|
1078
|
+
} else {
|
|
1079
|
+
errorCount++;
|
|
1080
|
+
interval = Math.min(interval * 2, 10000);
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
|
|
1085
|
+
return lastJobs;
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
type InstantBackgroundSchemaBaseJob = {
|
|
1089
|
+
id: string;
|
|
1090
|
+
createdAt: Date;
|
|
1091
|
+
updatedAt: Date;
|
|
1092
|
+
status: 'completed' | 'waiting' | 'processing' | 'errored';
|
|
1093
|
+
workEstimate: number | null;
|
|
1094
|
+
workCompleted: number | null;
|
|
1095
|
+
error?:
|
|
1096
|
+
| 'invalid-triple-error'
|
|
1097
|
+
| 'invalid-attr-state-error'
|
|
1098
|
+
| 'triple-not-unique-error'
|
|
1099
|
+
| 'triple-too-large-error'
|
|
1100
|
+
| 'missing-required-error'
|
|
1101
|
+
| 'unexpected-error';
|
|
1102
|
+
invalidTriplesSample?: {
|
|
1103
|
+
entityId: string;
|
|
1104
|
+
value: any;
|
|
1105
|
+
jsonType:
|
|
1106
|
+
| 'string'
|
|
1107
|
+
| 'number'
|
|
1108
|
+
| 'boolean'
|
|
1109
|
+
| 'null'
|
|
1110
|
+
| 'object'
|
|
1111
|
+
| 'array'
|
|
1112
|
+
| 'date';
|
|
1113
|
+
}[];
|
|
1114
|
+
};
|
|
1115
|
+
|
|
1116
|
+
export interface InstantBackgroundSchemaRemoveDataTypeJob
|
|
1117
|
+
extends InstantBackgroundSchemaBaseJob {
|
|
1118
|
+
type: 'remove-data-type';
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
export interface InstantBackgroundSchemaCheckDataTypeJob
|
|
1122
|
+
extends InstantBackgroundSchemaBaseJob {
|
|
1123
|
+
type: 'check-data-type';
|
|
1124
|
+
checkedDataType: InstantDBCheckedDataType;
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
export interface InstantBackgroundSchemaAddIndexJob
|
|
1128
|
+
extends InstantBackgroundSchemaBaseJob {
|
|
1129
|
+
type: 'index';
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
export interface InstantBackgroundSchemaRemoveIndexJob
|
|
1133
|
+
extends InstantBackgroundSchemaBaseJob {
|
|
1134
|
+
type: 'remove-index';
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
export interface InstantBackgroundSchemaAddUniqueJob
|
|
1138
|
+
extends InstantBackgroundSchemaBaseJob {
|
|
1139
|
+
type: 'unique';
|
|
1140
|
+
invalidUniqueValue?: any;
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
export interface InstantBackgroundSchemaRemoveUniqueJob
|
|
1144
|
+
extends InstantBackgroundSchemaBaseJob {
|
|
1145
|
+
type: 'remove-unique';
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
export interface InstantBackgroundSchemaAddRequiredJob
|
|
1149
|
+
extends InstantBackgroundSchemaBaseJob {
|
|
1150
|
+
type: 'required';
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
export interface InstantBackgroundSchemaRemoveRequiredJob
|
|
1154
|
+
extends InstantBackgroundSchemaBaseJob {
|
|
1155
|
+
type: 'remove-required';
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
export type InstantBackgroundSchemaJob =
|
|
1159
|
+
| InstantBackgroundSchemaRemoveDataTypeJob
|
|
1160
|
+
| InstantBackgroundSchemaCheckDataTypeJob
|
|
1161
|
+
| InstantBackgroundSchemaAddIndexJob
|
|
1162
|
+
| InstantBackgroundSchemaRemoveIndexJob
|
|
1163
|
+
| InstantBackgroundSchemaAddUniqueJob
|
|
1164
|
+
| InstantBackgroundSchemaRemoveUniqueJob
|
|
1165
|
+
| InstantBackgroundSchemaAddRequiredJob
|
|
1166
|
+
| InstantBackgroundSchemaRemoveRequiredJob;
|
|
1167
|
+
|
|
1168
|
+
function formatJob(job: IndexingJobJSON): InstantBackgroundSchemaJob {
|
|
1169
|
+
const baseJob: InstantBackgroundSchemaBaseJob = {
|
|
1170
|
+
id: job.id,
|
|
1171
|
+
createdAt: new Date(job.created_at),
|
|
1172
|
+
updatedAt: new Date(job.updated_at),
|
|
1173
|
+
status: job.job_status,
|
|
1174
|
+
workEstimate: job.work_estimate,
|
|
1175
|
+
workCompleted: job.work_completed,
|
|
1176
|
+
error: job.error,
|
|
1177
|
+
invalidTriplesSample: job.invalid_triples_sample?.map((s) => {
|
|
1178
|
+
return { entityId: s.entity_id, value: s.value, jsonType: s.json_type };
|
|
1179
|
+
}),
|
|
1180
|
+
};
|
|
1181
|
+
switch (job.job_type) {
|
|
1182
|
+
case 'remove-data-type':
|
|
1183
|
+
case 'index':
|
|
1184
|
+
case 'remove-index':
|
|
1185
|
+
case 'required':
|
|
1186
|
+
case 'remove-required':
|
|
1187
|
+
case 'remove-unique': {
|
|
1188
|
+
return { ...baseJob, type: job.job_type };
|
|
1189
|
+
}
|
|
1190
|
+
case 'check-data-type': {
|
|
1191
|
+
return {
|
|
1192
|
+
...baseJob,
|
|
1193
|
+
type: job.job_type,
|
|
1194
|
+
checkedDataType: job.checked_data_type!,
|
|
1195
|
+
};
|
|
1196
|
+
}
|
|
1197
|
+
case 'unique': {
|
|
1198
|
+
return {
|
|
1199
|
+
...baseJob,
|
|
1200
|
+
type: job.job_type,
|
|
1201
|
+
invalidUniqueValue: job.invalid_unique_value,
|
|
1202
|
+
};
|
|
1203
|
+
}
|
|
1204
|
+
default: {
|
|
1205
|
+
const neverType: never = job.job_type;
|
|
1206
|
+
throw new Error(`Unknown job type: ${neverType}.`);
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
function stepSummary(
|
|
1212
|
+
steps: InstantAPISchemaPushStep[],
|
|
1213
|
+
): InProgressStepsSummary {
|
|
1214
|
+
const inProgress = steps.filter(
|
|
1215
|
+
(s) =>
|
|
1216
|
+
'backgroundJob' in s &&
|
|
1217
|
+
(s.backgroundJob.status === 'processing' ||
|
|
1218
|
+
s.backgroundJob.status === 'waiting'),
|
|
1219
|
+
);
|
|
1220
|
+
const completed = steps.filter(
|
|
1221
|
+
(s) => !('backgroundJob' in s) || s.backgroundJob.status === 'completed',
|
|
1222
|
+
);
|
|
1223
|
+
const errored = steps.filter(
|
|
1224
|
+
(s) => 'backgroundJob' in s && s.backgroundJob.status === 'errored',
|
|
1225
|
+
);
|
|
1226
|
+
return {
|
|
1227
|
+
friendlyDescription: inProgress.length
|
|
1228
|
+
? `Completing ${inProgress.length} of ${steps.length} schema operations.`
|
|
1229
|
+
: `Finished ${steps.length} schema operation${steps.length === 1 ? '' : 's'}${
|
|
1230
|
+
errored.length
|
|
1231
|
+
? `, with ${errored.length} error${errored.length > 1 ? 's' : ''}`
|
|
1232
|
+
: '.'
|
|
1233
|
+
}`,
|
|
1234
|
+
totalCount: steps.length,
|
|
1235
|
+
inProgressCount: inProgress.length,
|
|
1236
|
+
completedCount: completed.length,
|
|
1237
|
+
errorCount: errored.length,
|
|
1238
|
+
steps,
|
|
1239
|
+
inProgressSteps: inProgress,
|
|
1240
|
+
completedSteps: completed,
|
|
1241
|
+
erroredSteps: errored,
|
|
1242
|
+
};
|
|
1243
|
+
}
|
|
1244
|
+
|
|
1245
|
+
function schemaPush(
|
|
1246
|
+
apiURI: string,
|
|
1247
|
+
token: string,
|
|
1248
|
+
appId: string,
|
|
1249
|
+
body: InstantAPISchemaPushBody,
|
|
1250
|
+
): ProgressPromise<InProgressStepsSummary, InstantAPISchemaPushResponse> {
|
|
1251
|
+
return new ProgressPromise(async (progress, resolve, reject) => {
|
|
1252
|
+
try {
|
|
1253
|
+
const currentAPISchema = await getAppAPISchema(apiURI, token, appId);
|
|
1254
|
+
const currentAttrs = apiSchemaToAttrs(currentAPISchema);
|
|
1255
|
+
|
|
1256
|
+
const resp = await jsonFetch<SchemaPushResponseJSON>(
|
|
1257
|
+
`${apiURI}/superadmin/apps/${appId}/schema/push/apply`,
|
|
1258
|
+
{
|
|
1259
|
+
method: 'POST',
|
|
1260
|
+
headers: {
|
|
1261
|
+
'Content-Type': 'application/json',
|
|
1262
|
+
Authorization: `Bearer ${token}`,
|
|
1263
|
+
},
|
|
1264
|
+
body: JSON.stringify({
|
|
1265
|
+
...body,
|
|
1266
|
+
check_types: true,
|
|
1267
|
+
supports_background_updates: true,
|
|
1268
|
+
}),
|
|
1269
|
+
},
|
|
1270
|
+
);
|
|
1271
|
+
|
|
1272
|
+
const indexingJobs = resp['indexing-jobs'];
|
|
1273
|
+
|
|
1274
|
+
const jobs = !indexingJobs
|
|
1275
|
+
? []
|
|
1276
|
+
: await jobFetchLoop(
|
|
1277
|
+
apiURI,
|
|
1278
|
+
token,
|
|
1279
|
+
appId,
|
|
1280
|
+
indexingJobs['group-id'],
|
|
1281
|
+
indexingJobs['jobs'],
|
|
1282
|
+
(jobs) => {
|
|
1283
|
+
progress(
|
|
1284
|
+
stepSummary(translatePushSteps(resp.steps, jobs, currentAttrs)),
|
|
1285
|
+
);
|
|
1286
|
+
},
|
|
1287
|
+
);
|
|
1288
|
+
|
|
1289
|
+
const schemaRes = await getAppSchema(apiURI, token, appId);
|
|
1290
|
+
resolve({
|
|
1291
|
+
newSchema: schemaRes.schema,
|
|
1292
|
+
steps: translatePushSteps(resp.steps, jobs, currentAttrs),
|
|
1293
|
+
summary: stepSummary(
|
|
1294
|
+
translatePushSteps(resp.steps, jobs, currentAttrs),
|
|
1295
|
+
),
|
|
1296
|
+
});
|
|
1297
|
+
} catch (e) {
|
|
1298
|
+
reject(e as Error);
|
|
1299
|
+
}
|
|
1300
|
+
});
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
function schemaPushOverwrite(
|
|
1304
|
+
apiURI: string,
|
|
1305
|
+
token: string,
|
|
1306
|
+
appId: string,
|
|
1307
|
+
body: InstantAPISchemaPushBody,
|
|
1308
|
+
): ProgressPromise<InProgressStepsSummary, InstantAPISchemaPushResponse> {
|
|
1309
|
+
return new ProgressPromise(async (progress, resolve, reject) => {
|
|
1310
|
+
try {
|
|
1311
|
+
const { currentAttrs, txSteps } = await planSchemaPushOverwriteInternal(
|
|
1312
|
+
apiURI,
|
|
1313
|
+
token,
|
|
1314
|
+
appId,
|
|
1315
|
+
body,
|
|
1316
|
+
);
|
|
1317
|
+
|
|
1318
|
+
const resp = await jsonFetch<SchemaPushResponseJSON>(
|
|
1319
|
+
`${apiURI}/dash/apps/${appId}/schema/steps/apply`,
|
|
1320
|
+
{
|
|
1321
|
+
method: 'POST',
|
|
1322
|
+
headers: {
|
|
1323
|
+
'Content-Type': 'application/json',
|
|
1324
|
+
Authorization: `Bearer ${token}`,
|
|
1325
|
+
},
|
|
1326
|
+
body: JSON.stringify({
|
|
1327
|
+
steps: txSteps,
|
|
1328
|
+
}),
|
|
1329
|
+
},
|
|
1330
|
+
);
|
|
1331
|
+
|
|
1332
|
+
const indexingJobs = resp['indexing-jobs'];
|
|
1333
|
+
|
|
1334
|
+
const jobs = !indexingJobs
|
|
1335
|
+
? []
|
|
1336
|
+
: await jobFetchLoop(
|
|
1337
|
+
apiURI,
|
|
1338
|
+
token,
|
|
1339
|
+
appId,
|
|
1340
|
+
indexingJobs['group-id'],
|
|
1341
|
+
indexingJobs['jobs'],
|
|
1342
|
+
(jobs) => {
|
|
1343
|
+
progress(
|
|
1344
|
+
stepSummary(translatePushSteps(resp.steps, jobs, currentAttrs)),
|
|
1345
|
+
);
|
|
1346
|
+
},
|
|
1347
|
+
);
|
|
1348
|
+
|
|
1349
|
+
const schemaRes = await getAppSchema(apiURI, token, appId);
|
|
1350
|
+
resolve({
|
|
1351
|
+
newSchema: schemaRes.schema,
|
|
1352
|
+
steps: translatePushSteps(resp.steps, jobs, currentAttrs),
|
|
1353
|
+
summary: stepSummary(
|
|
1354
|
+
translatePushSteps(resp.steps, jobs, currentAttrs),
|
|
1355
|
+
),
|
|
1356
|
+
});
|
|
1357
|
+
} catch (e) {
|
|
1358
|
+
reject(e as Error);
|
|
1359
|
+
}
|
|
1360
|
+
});
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
async function pushPerms(
|
|
1364
|
+
apiURI: string,
|
|
1365
|
+
token: string,
|
|
1366
|
+
appId: string,
|
|
1367
|
+
body: InstantAPIPushPermsBody,
|
|
1368
|
+
): Promise<InstantAPIPushPermsResponse> {
|
|
1369
|
+
const result = await jsonFetch<{ rules: { code: InstantRules } }>(
|
|
1370
|
+
`${apiURI}/superadmin/apps/${appId}/perms`,
|
|
1371
|
+
{
|
|
1372
|
+
method: 'POST',
|
|
1373
|
+
headers: {
|
|
1374
|
+
'Content-Type': 'application/json',
|
|
1375
|
+
Authorization: `Bearer ${token}`,
|
|
1376
|
+
},
|
|
1377
|
+
body: JSON.stringify({ code: body.perms }),
|
|
1378
|
+
},
|
|
1379
|
+
);
|
|
1380
|
+
|
|
1381
|
+
return { perms: result.rules.code };
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
async function tokenInfo(
|
|
1385
|
+
apiURI: string,
|
|
1386
|
+
token: string,
|
|
1387
|
+
): Promise<InstantAPITokenInfoResponse> {
|
|
1388
|
+
const result = await jsonFetch<{
|
|
1389
|
+
expires_in: number;
|
|
1390
|
+
scopes: string;
|
|
1391
|
+
token_type: 'Bearer';
|
|
1392
|
+
}>(`${apiURI}/platform/oauth/token-info?access_token=${token}`, {
|
|
1393
|
+
method: 'GET',
|
|
1394
|
+
});
|
|
1395
|
+
|
|
1396
|
+
return {
|
|
1397
|
+
tokenType: result.token_type,
|
|
1398
|
+
scopes: result.scopes,
|
|
1399
|
+
expiresAt: new Date(Date.now() + (result.expires_in - 60) * 1000),
|
|
1400
|
+
};
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
export type PlatformApiAuth =
|
|
1404
|
+
| {
|
|
1405
|
+
token: string;
|
|
1406
|
+
}
|
|
1407
|
+
| {
|
|
1408
|
+
accessToken: string;
|
|
1409
|
+
refreshToken: string;
|
|
1410
|
+
clientId: string;
|
|
1411
|
+
clientSecret: string;
|
|
1412
|
+
onRefresh?: (tokenInfo: {
|
|
1413
|
+
accessToken: string;
|
|
1414
|
+
expiresAt: Date;
|
|
1415
|
+
}) => Promise<void>;
|
|
1416
|
+
};
|
|
1417
|
+
|
|
1418
|
+
export type PlatformApiConfig = {
|
|
1419
|
+
auth?: PlatformApiAuth;
|
|
1420
|
+
apiURI?: string;
|
|
1421
|
+
};
|
|
1422
|
+
|
|
1423
|
+
export class PlatformApiMissingAuthError extends Error {
|
|
1424
|
+
constructor() {
|
|
1425
|
+
super('PlatformApi was not provided auth.');
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
/**
|
|
1430
|
+
* API methods for the Platform API
|
|
1431
|
+
*
|
|
1432
|
+
* Usage:
|
|
1433
|
+
*
|
|
1434
|
+
* ```ts
|
|
1435
|
+
* import { PlatformApi } from '@sidekickdb/platform';
|
|
1436
|
+
*
|
|
1437
|
+
* const api = new PlatformApi({
|
|
1438
|
+
* apiURI: 'https://sidekick.example.com',
|
|
1439
|
+
* auth: { token: 'oauth-access-token' },
|
|
1440
|
+
* });
|
|
1441
|
+
* const { apps } = await api.getApps({
|
|
1442
|
+
* includeSchema: true,
|
|
1443
|
+
* includePerms: true,
|
|
1444
|
+
* });
|
|
1445
|
+
* ```
|
|
1446
|
+
*/
|
|
1447
|
+
export class PlatformApi {
|
|
1448
|
+
#auth: PlatformApiAuth | undefined;
|
|
1449
|
+
#apiURI: string;
|
|
1450
|
+
|
|
1451
|
+
/**
|
|
1452
|
+
* @param config – Runtime configuration.
|
|
1453
|
+
* @param config.auth.token – OAuth access-token obtained via the oauth flow
|
|
1454
|
+
* or a personal access token.
|
|
1455
|
+
* @param config.apiURI – URL of your SidekickDB server. Required.
|
|
1456
|
+
* @throws {MissingApiURIError} When `apiURI` is missing.
|
|
1457
|
+
*/
|
|
1458
|
+
constructor(config?: PlatformApiConfig) {
|
|
1459
|
+
this.#auth = config?.auth;
|
|
1460
|
+
this.#apiURI = requireApiURI(config?.apiURI, {
|
|
1461
|
+
target: 'new PlatformApi()',
|
|
1462
|
+
});
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
token(): string {
|
|
1466
|
+
if (!this.#auth) {
|
|
1467
|
+
throw new PlatformApiMissingAuthError();
|
|
1468
|
+
}
|
|
1469
|
+
if ('token' in this.#auth) {
|
|
1470
|
+
return this.#auth.token;
|
|
1471
|
+
}
|
|
1472
|
+
return this.#auth.accessToken;
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
canRefreshToken(): boolean {
|
|
1476
|
+
if (!this.#auth) {
|
|
1477
|
+
throw new PlatformApiMissingAuthError();
|
|
1478
|
+
}
|
|
1479
|
+
return (
|
|
1480
|
+
'refreshToken' in this.#auth &&
|
|
1481
|
+
'clientId' in this.#auth &&
|
|
1482
|
+
'clientSecret' in this.#auth &&
|
|
1483
|
+
this.#auth.refreshToken != null &&
|
|
1484
|
+
this.#auth.clientId != null &&
|
|
1485
|
+
this.#auth.clientSecret != null
|
|
1486
|
+
);
|
|
1487
|
+
}
|
|
1488
|
+
|
|
1489
|
+
async refreshToken(): Promise<null | {
|
|
1490
|
+
accessToken: string;
|
|
1491
|
+
expiresAt: Date;
|
|
1492
|
+
}> {
|
|
1493
|
+
if (!this.#auth) {
|
|
1494
|
+
throw new PlatformApiMissingAuthError();
|
|
1495
|
+
}
|
|
1496
|
+
if (
|
|
1497
|
+
!this.canRefreshToken() ||
|
|
1498
|
+
// Checked in canRefreshToken, but this lets
|
|
1499
|
+
// typescript refine this.#auth here
|
|
1500
|
+
!('clientId' in this.#auth)
|
|
1501
|
+
) {
|
|
1502
|
+
return null;
|
|
1503
|
+
}
|
|
1504
|
+
const token = await exchangeRefreshToken({
|
|
1505
|
+
apiURI: this.#apiURI,
|
|
1506
|
+
clientId: this.#auth.clientId,
|
|
1507
|
+
clientSecret: this.#auth.clientSecret,
|
|
1508
|
+
refreshToken: this.#auth.refreshToken,
|
|
1509
|
+
});
|
|
1510
|
+
this.#auth.accessToken = token.accessToken;
|
|
1511
|
+
if (this.#auth.onRefresh) {
|
|
1512
|
+
await this.#auth.onRefresh(token);
|
|
1513
|
+
}
|
|
1514
|
+
return token;
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
async withRetry<F extends (...args: any[]) => any>(
|
|
1518
|
+
f: F,
|
|
1519
|
+
args: Parameters<F>,
|
|
1520
|
+
) {
|
|
1521
|
+
let attempt = 0;
|
|
1522
|
+
const [apiURI, tokenInArg, ...restArgs] = args;
|
|
1523
|
+
let token = tokenInArg;
|
|
1524
|
+
while (attempt < 2) {
|
|
1525
|
+
try {
|
|
1526
|
+
return await f(apiURI, token, ...restArgs);
|
|
1527
|
+
} catch (e) {
|
|
1528
|
+
if (
|
|
1529
|
+
e instanceof InstantAPIError &&
|
|
1530
|
+
(e.status === 401 ||
|
|
1531
|
+
e.body?.type === 'record-expired' ||
|
|
1532
|
+
(e.body?.type === 'record-not-found' &&
|
|
1533
|
+
e.body.hint['record-type'].match(/token/i))) &&
|
|
1534
|
+
this.canRefreshToken()
|
|
1535
|
+
) {
|
|
1536
|
+
const refreshedToken = await this.refreshToken();
|
|
1537
|
+
if (refreshedToken) {
|
|
1538
|
+
token = refreshedToken.accessToken;
|
|
1539
|
+
attempt++;
|
|
1540
|
+
continue;
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
throw e;
|
|
1544
|
+
}
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
/**
|
|
1549
|
+
* Fetch a single app by its id.
|
|
1550
|
+
*
|
|
1551
|
+
* ```ts
|
|
1552
|
+
* const { app } = await api.getApp('MY_APP_ID', {
|
|
1553
|
+
* includeSchema: true,
|
|
1554
|
+
* includePerms: true,
|
|
1555
|
+
* });
|
|
1556
|
+
* ```
|
|
1557
|
+
*
|
|
1558
|
+
* @template Opts – Narrow the shape of the response via the
|
|
1559
|
+
* {@link AppDataOpts} flags.
|
|
1560
|
+
* @param appId – UUID of the app.
|
|
1561
|
+
* @param opts – `{ includeSchema?: boolean; includePerms?: boolean }`
|
|
1562
|
+
* @returns A typed wrapper containing the app, whose shape is expanded
|
|
1563
|
+
* according to `Opts`.
|
|
1564
|
+
*/
|
|
1565
|
+
async getApp<Opts extends AppDataOpts>(
|
|
1566
|
+
appId: string,
|
|
1567
|
+
opts?: Opts,
|
|
1568
|
+
): Promise<InstantAPIGetAppResponse<Opts>> {
|
|
1569
|
+
return this.withRetry(getApp, [this.#apiURI, this.token(), appId, opts]);
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
/**
|
|
1573
|
+
* List **all apps** owned by the auth owner.
|
|
1574
|
+
*
|
|
1575
|
+
* ```ts
|
|
1576
|
+
* const { apps } = await api.getApps({
|
|
1577
|
+
* includeSchema: true,
|
|
1578
|
+
* includePerms: true,
|
|
1579
|
+
* });
|
|
1580
|
+
* ```
|
|
1581
|
+
*
|
|
1582
|
+
* @template Opts – Same as {@link getApp}.
|
|
1583
|
+
* @param opts – `{ includeSchema?: boolean; includePerms?: boolean }`
|
|
1584
|
+
* @returns An array wrapper; each element’s shape follows `Opts`.
|
|
1585
|
+
*/
|
|
1586
|
+
async getApps<Opts extends AppDataOpts>(
|
|
1587
|
+
opts?: Opts,
|
|
1588
|
+
): Promise<InstantAPIListAppsResponse<Opts>> {
|
|
1589
|
+
return this.withRetry(getApps, [this.#apiURI, this.token(), opts]);
|
|
1590
|
+
}
|
|
1591
|
+
|
|
1592
|
+
/**
|
|
1593
|
+
* List **all orgs** that the auth owner is a member of.
|
|
1594
|
+
*
|
|
1595
|
+
* ```ts
|
|
1596
|
+
* const { orgs } = await api.getOrgs();
|
|
1597
|
+
* ```
|
|
1598
|
+
*
|
|
1599
|
+
* @returns An array of orgs
|
|
1600
|
+
*/
|
|
1601
|
+
async getOrgs(): Promise<InstantAPIListOrgsResponse> {
|
|
1602
|
+
return this.withRetry(getOrgs, [this.#apiURI, this.token()]);
|
|
1603
|
+
}
|
|
1604
|
+
|
|
1605
|
+
/**
|
|
1606
|
+
* List **all apps** owned by the auth owner.
|
|
1607
|
+
*
|
|
1608
|
+
* ```ts
|
|
1609
|
+
* const { apps } = await api.getApps({
|
|
1610
|
+
* includeSchema: true,
|
|
1611
|
+
* includePerms: true,
|
|
1612
|
+
* });
|
|
1613
|
+
* ```
|
|
1614
|
+
*
|
|
1615
|
+
* @template Opts – Same as {@link getApp}.
|
|
1616
|
+
* @param opts – `{ includeSchema?: boolean; includePerms?: boolean }`
|
|
1617
|
+
* @returns An array wrapper; each element’s shape follows `Opts`.
|
|
1618
|
+
*/
|
|
1619
|
+
async getAppsForOrg<Opts extends AppDataOpts>(
|
|
1620
|
+
orgId: string,
|
|
1621
|
+
opts?: Opts,
|
|
1622
|
+
): Promise<InstantAPIListAppsResponse<Opts>> {
|
|
1623
|
+
return this.withRetry(getAppsForOrg, [
|
|
1624
|
+
this.#apiURI,
|
|
1625
|
+
this.token(),
|
|
1626
|
+
orgId,
|
|
1627
|
+
opts,
|
|
1628
|
+
]);
|
|
1629
|
+
}
|
|
1630
|
+
|
|
1631
|
+
/**
|
|
1632
|
+
* Gets the schema for an app by its id.
|
|
1633
|
+
*
|
|
1634
|
+
* ```ts
|
|
1635
|
+
* const { schema } = await api.getSchema('MY_APP_ID');
|
|
1636
|
+
* ```
|
|
1637
|
+
*
|
|
1638
|
+
* @param appId -- UUID of the app
|
|
1639
|
+
*/
|
|
1640
|
+
async getSchema(appId: string): Promise<InstantAPIGetAppSchemaResponse> {
|
|
1641
|
+
return this.withRetry(getAppSchema, [this.#apiURI, this.token(), appId]);
|
|
1642
|
+
}
|
|
1643
|
+
|
|
1644
|
+
/**
|
|
1645
|
+
* Gets the permissions for an app by its id.
|
|
1646
|
+
*
|
|
1647
|
+
* ```ts
|
|
1648
|
+
* const { perms } = await api.getPerms('MY_APP_ID');
|
|
1649
|
+
* ```
|
|
1650
|
+
*
|
|
1651
|
+
* @param appId -- UUID of the app
|
|
1652
|
+
*/
|
|
1653
|
+
async getPerms(appId: string): Promise<InstantAPIGetAppPermsResponse> {
|
|
1654
|
+
return this.withRetry(getAppPerms, [this.#apiURI, this.token(), appId]);
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1657
|
+
/**
|
|
1658
|
+
* Create a new app.
|
|
1659
|
+
*
|
|
1660
|
+
* The app will be placed in the authenticated user's account
|
|
1661
|
+
* if no orgId is provided.
|
|
1662
|
+
*
|
|
1663
|
+
* Optionally set permissions and schema.
|
|
1664
|
+
*
|
|
1665
|
+
* ```ts
|
|
1666
|
+
* const { app } = await api.createApp({
|
|
1667
|
+
* title: 'My new app',
|
|
1668
|
+
* // Optional permissions
|
|
1669
|
+
* perms: { $default: { allow: { $default: 'false' } } },
|
|
1670
|
+
* // Optional schema
|
|
1671
|
+
* schema: i.schema({
|
|
1672
|
+
* entities: { books: i.entity({ title: i.string() }) },
|
|
1673
|
+
* }),
|
|
1674
|
+
* });
|
|
1675
|
+
* ```
|
|
1676
|
+
*
|
|
1677
|
+
* @param fields
|
|
1678
|
+
* @param fields.title -- Title for app
|
|
1679
|
+
* @param fields.schema -- Optional schema for the app
|
|
1680
|
+
* @param fields.perms -- Optional permissions for the app
|
|
1681
|
+
* @param fields.orgId -- Optional id of the org that the app will be placed in
|
|
1682
|
+
*/
|
|
1683
|
+
async createApp(
|
|
1684
|
+
fields: InstantAPICreateAppBody,
|
|
1685
|
+
): Promise<InstantAPICreateAppResponse> {
|
|
1686
|
+
return this.withRetry(createApp, [this.#apiURI, this.token(), fields]);
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
/**
|
|
1690
|
+
* Create a new temporary app.
|
|
1691
|
+
*
|
|
1692
|
+
* Optionally set permissions and schema.
|
|
1693
|
+
*
|
|
1694
|
+
* ```ts
|
|
1695
|
+
* const { app } = await api.createTemporaryApp({
|
|
1696
|
+
* title: 'My new app',
|
|
1697
|
+
* // Optional permissions
|
|
1698
|
+
* perms: { $default: { allow: { $default: 'false' } } },
|
|
1699
|
+
* // Optional schema
|
|
1700
|
+
* schema: i.schema({
|
|
1701
|
+
* entities: { books: i.entity({ title: i.string() }) },
|
|
1702
|
+
* }),
|
|
1703
|
+
* });
|
|
1704
|
+
* ```
|
|
1705
|
+
*
|
|
1706
|
+
* @param fields
|
|
1707
|
+
* @param fields.title -- Title for app
|
|
1708
|
+
* @param fields.schema -- Optional schema for the app
|
|
1709
|
+
* @param fields.perms -- Optional permissions for the app
|
|
1710
|
+
*/
|
|
1711
|
+
async createTemporaryApp(fields: InstantAPICreateTemporaryAppBody) {
|
|
1712
|
+
return createTemporaryApp(this.#apiURI, fields);
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1715
|
+
/**
|
|
1716
|
+
* Update the title of an app by its id.
|
|
1717
|
+
*
|
|
1718
|
+
* ```ts
|
|
1719
|
+
* const { app } = await api.updateApp('MY_APP_ID', {
|
|
1720
|
+
* title: 'New title',
|
|
1721
|
+
* });
|
|
1722
|
+
* ```
|
|
1723
|
+
*
|
|
1724
|
+
* @param appId -- UUID of the app
|
|
1725
|
+
* @param fields.title -- New title for the app
|
|
1726
|
+
*/
|
|
1727
|
+
async updateApp(
|
|
1728
|
+
appId: string,
|
|
1729
|
+
fields: InstantAPIUpdateAppBody,
|
|
1730
|
+
): Promise<InstantAPIUpdateAppResponse> {
|
|
1731
|
+
return this.withRetry(updateApp, [
|
|
1732
|
+
this.#apiURI,
|
|
1733
|
+
this.token(),
|
|
1734
|
+
appId,
|
|
1735
|
+
fields,
|
|
1736
|
+
]);
|
|
1737
|
+
}
|
|
1738
|
+
|
|
1739
|
+
/**
|
|
1740
|
+
* Delete an app by its id.
|
|
1741
|
+
*
|
|
1742
|
+
* ```ts
|
|
1743
|
+
* const { app } = await api.deleteApp('MY_APP_ID');
|
|
1744
|
+
* ```
|
|
1745
|
+
*
|
|
1746
|
+
* @param appId -- UUID of the app
|
|
1747
|
+
*/
|
|
1748
|
+
async deleteApp(appId: string): Promise<InstantAPIDeleteAppResponse> {
|
|
1749
|
+
return this.withRetry(deleteApp, [this.#apiURI, this.token(), appId]);
|
|
1750
|
+
}
|
|
1751
|
+
|
|
1752
|
+
/**
|
|
1753
|
+
* Dry-run a **schema push** and receive a _plan_ of steps the server would
|
|
1754
|
+
* execute.
|
|
1755
|
+
*
|
|
1756
|
+
* ```ts
|
|
1757
|
+
* const { steps } = await api.planSchemaPush(appId, body);
|
|
1758
|
+
* ```
|
|
1759
|
+
*/
|
|
1760
|
+
async planSchemaPush(
|
|
1761
|
+
appId: string,
|
|
1762
|
+
body: InstantAPISchemaPushBody,
|
|
1763
|
+
): Promise<InstantAPIPlanSchemaPushResponse> {
|
|
1764
|
+
const useOverwrite = shouldOverwrite(body);
|
|
1765
|
+
return this.withRetry(
|
|
1766
|
+
useOverwrite ? planSchemaPushOverwrite : planSchemaPush,
|
|
1767
|
+
[this.#apiURI, this.token(), appId, body],
|
|
1768
|
+
);
|
|
1769
|
+
}
|
|
1770
|
+
|
|
1771
|
+
/**
|
|
1772
|
+
* Execute a **schema push**. The server returns a long-running job
|
|
1773
|
+
* represented as a {@link ProgressPromise}: you can both `await` the final
|
|
1774
|
+
* result **or** subscribe to intermediate status updates.
|
|
1775
|
+
*
|
|
1776
|
+
* ```ts
|
|
1777
|
+
* // 1) Subscribe to progress
|
|
1778
|
+
* const schema = i.schema({
|
|
1779
|
+
* entities: {
|
|
1780
|
+
* books: i.entity({
|
|
1781
|
+
* title: i.string().indexed(),
|
|
1782
|
+
* }),
|
|
1783
|
+
* },
|
|
1784
|
+
* });
|
|
1785
|
+
* const job = api.schemaPush(appId, { overwrite: true, schema: schema });
|
|
1786
|
+
* job
|
|
1787
|
+
* .then(({ summary }) => console.log('done!', summary))
|
|
1788
|
+
* .catch((e) => console.error(e));
|
|
1789
|
+
* job.subscribe({
|
|
1790
|
+
* next: (status) => renderProgress(status),
|
|
1791
|
+
* });
|
|
1792
|
+
*
|
|
1793
|
+
* // 2) Or just await it
|
|
1794
|
+
* const result = await api.schemaPush(appId, { schema: schema });
|
|
1795
|
+
* ```
|
|
1796
|
+
*/
|
|
1797
|
+
schemaPush(
|
|
1798
|
+
appId: string,
|
|
1799
|
+
body: InstantAPISchemaPushBody,
|
|
1800
|
+
): ProgressPromise<InProgressStepsSummary, InstantAPISchemaPushResponse> {
|
|
1801
|
+
if (!this.#auth) {
|
|
1802
|
+
throw new PlatformApiMissingAuthError();
|
|
1803
|
+
}
|
|
1804
|
+
return new ProgressPromise(async (progress, resolve, reject) => {
|
|
1805
|
+
try {
|
|
1806
|
+
const useOverwrite = shouldOverwrite(body);
|
|
1807
|
+
const pushFn = useOverwrite ? schemaPushOverwrite : schemaPush;
|
|
1808
|
+
|
|
1809
|
+
// It's tricky to add withRetry to the background process that fetches the jobs,
|
|
1810
|
+
// so we'll just refresh the token at the start.
|
|
1811
|
+
if (this.canRefreshToken()) {
|
|
1812
|
+
try {
|
|
1813
|
+
await this.refreshToken();
|
|
1814
|
+
} catch (_e) {}
|
|
1815
|
+
}
|
|
1816
|
+
pushFn(this.#apiURI, this.token(), appId, body).subscribe({
|
|
1817
|
+
complete(v) {
|
|
1818
|
+
resolve(v);
|
|
1819
|
+
},
|
|
1820
|
+
error(e) {
|
|
1821
|
+
reject(e);
|
|
1822
|
+
},
|
|
1823
|
+
next(v) {
|
|
1824
|
+
progress(v);
|
|
1825
|
+
},
|
|
1826
|
+
});
|
|
1827
|
+
} catch (e) {
|
|
1828
|
+
reject(e as Error);
|
|
1829
|
+
}
|
|
1830
|
+
});
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1833
|
+
/**
|
|
1834
|
+
* Update permission rules for an app by its id.
|
|
1835
|
+
*
|
|
1836
|
+
* Completely replaces the current rule set.
|
|
1837
|
+
*
|
|
1838
|
+
* ```ts
|
|
1839
|
+
* const { steps } = await api.pushPerms(appId, {
|
|
1840
|
+
* perms: {
|
|
1841
|
+
* $default: { allow: { $default: 'false' } },
|
|
1842
|
+
* books: { allow: { view: 'true', $default: 'false' } },
|
|
1843
|
+
* },
|
|
1844
|
+
* });
|
|
1845
|
+
* ```
|
|
1846
|
+
*/
|
|
1847
|
+
async pushPerms(
|
|
1848
|
+
appId: string,
|
|
1849
|
+
body: InstantAPIPushPermsBody,
|
|
1850
|
+
): Promise<InstantAPIPushPermsResponse> {
|
|
1851
|
+
if (!this.#auth) {
|
|
1852
|
+
throw new PlatformApiMissingAuthError();
|
|
1853
|
+
}
|
|
1854
|
+
return this.withRetry(pushPerms, [this.#apiURI, this.token(), appId, body]);
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
async tokenInfo(): Promise<InstantAPITokenInfoResponse> {
|
|
1858
|
+
if (!this.#auth) {
|
|
1859
|
+
throw new PlatformApiMissingAuthError();
|
|
1860
|
+
}
|
|
1861
|
+
return this.withRetry(tokenInfo, [this.#apiURI, this.token()]);
|
|
1862
|
+
}
|
|
1863
|
+
|
|
1864
|
+
/**
|
|
1865
|
+
* Returns a {@link Webhooks} instance scoped to `appId`. You don't need
|
|
1866
|
+
* auth on this PlatformApi to verify signatures or process incoming
|
|
1867
|
+
* deliveries — only `webhooks(appId).manager.*` requires it, and those
|
|
1868
|
+
* calls are routed through {@link withRetry}, so an expired access token
|
|
1869
|
+
* is transparently refreshed.
|
|
1870
|
+
*
|
|
1871
|
+
* Pass `schema` (e.g. from {@link apiSchemaToInstantSchemaDef}) for typed
|
|
1872
|
+
* handler records and typed `namespaces` on `manager.create`/`update`.
|
|
1873
|
+
*/
|
|
1874
|
+
webhooks<
|
|
1875
|
+
Schema extends InstantSchemaDef<any, any, any> = InstantUnknownSchema,
|
|
1876
|
+
>(appId: string, opts?: { schema?: Schema }): Webhooks<Schema> {
|
|
1877
|
+
const withAuth: WithAuth = (operation) =>
|
|
1878
|
+
this.withRetry(
|
|
1879
|
+
(_apiURI: string, token: string) => operation(token),
|
|
1880
|
+
[this.#apiURI, this.token()],
|
|
1881
|
+
);
|
|
1882
|
+
return new Webhooks<Schema>({
|
|
1883
|
+
appId,
|
|
1884
|
+
apiURI: this.#apiURI,
|
|
1885
|
+
schema: opts?.schema,
|
|
1886
|
+
withAuth,
|
|
1887
|
+
});
|
|
1888
|
+
}
|
|
1889
|
+
|
|
1890
|
+
/**
|
|
1891
|
+
* Returns a {@link BackupsManager} scoped to `appId` for listing an app's
|
|
1892
|
+
* backups and downloading their contents. Calls are routed through
|
|
1893
|
+
* {@link withRetry}, so an expired access token is transparently refreshed.
|
|
1894
|
+
*/
|
|
1895
|
+
backups(appId: string): BackupsManager {
|
|
1896
|
+
const withAuth: WithAuth = (operation) =>
|
|
1897
|
+
this.withRetry(
|
|
1898
|
+
(_apiURI: string, token: string) => operation(token),
|
|
1899
|
+
[this.#apiURI, this.token()],
|
|
1900
|
+
);
|
|
1901
|
+
return new BackupsManager({ appId, apiURI: this.#apiURI, withAuth });
|
|
1902
|
+
}
|
|
1903
|
+
}
|