@instantdb/platform 0.22.99-experimental.add-user-perm-rules.20792844601.1 → 0.22.99
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/.turbo/turbo-build.log +8 -8
- package/dist/commonjs/ProgressPromise.js +45 -58
- package/dist/commonjs/ProgressPromise.js.map +1 -1
- package/dist/commonjs/api.js +366 -412
- package/dist/commonjs/api.js.map +1 -1
- package/dist/commonjs/migrationUtils.js +16 -4
- package/dist/commonjs/migrationUtils.js.map +1 -1
- package/dist/commonjs/migrations.js +10 -21
- package/dist/commonjs/migrations.js.map +1 -1
- package/dist/commonjs/oauth.js +52 -55
- package/dist/commonjs/oauth.js.map +1 -1
- package/dist/commonjs/oauthCommon.js +2 -0
- package/dist/commonjs/oauthCommon.js.map +1 -1
- package/dist/commonjs/perms.js +1 -1
- package/dist/commonjs/perms.js.map +1 -1
- package/dist/commonjs/schema.js +8 -14
- package/dist/commonjs/schema.js.map +1 -1
- package/dist/commonjs/serverOAuth.js +55 -68
- package/dist/commonjs/serverOAuth.js.map +1 -1
- package/dist/commonjs/typescript-schema.js +1 -2
- package/dist/commonjs/typescript-schema.js.map +1 -1
- package/dist/commonjs/util.js +1 -1
- package/dist/commonjs/util.js.map +1 -1
- package/dist/esm/ProgressPromise.js +45 -58
- package/dist/esm/ProgressPromise.js.map +1 -1
- package/dist/esm/api.js +366 -412
- package/dist/esm/api.js.map +1 -1
- package/dist/esm/migrationUtils.js +16 -4
- package/dist/esm/migrationUtils.js.map +1 -1
- package/dist/esm/migrations.js +10 -21
- package/dist/esm/migrations.js.map +1 -1
- package/dist/esm/oauth.js +52 -55
- package/dist/esm/oauth.js.map +1 -1
- package/dist/esm/oauthCommon.js +2 -0
- package/dist/esm/oauthCommon.js.map +1 -1
- package/dist/esm/perms.js +1 -1
- package/dist/esm/perms.js.map +1 -1
- package/dist/esm/schema.js +8 -14
- package/dist/esm/schema.js.map +1 -1
- package/dist/esm/serverOAuth.js +55 -68
- package/dist/esm/serverOAuth.js.map +1 -1
- package/dist/esm/typescript-schema.js +1 -2
- package/dist/esm/typescript-schema.js.map +1 -1
- package/dist/esm/util.js +1 -1
- package/dist/esm/util.js.map +1 -1
- package/dist/standalone/index.js +690 -660
- package/dist/standalone/index.umd.cjs +16 -16
- package/package.json +3 -3
package/dist/commonjs/api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/api.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAqaA,kEAgBC;AAsYD,gDAIC;AA/zBD,0CAcyB;AACzB,8DAAmC;AACnC,2CAQqB;AACrB,6DAAuD;AACvD,uCAKmB;AACnB,qDAAwD;AAyQxD,SAAe,SAAS,CACtB,KAAkB,EAClB,IAA6B;;QAE7B,MAAM,OAAO,mCACR,CAAC,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,OAAO,KAAI,EAAE,CAAC,KACxB,0BAA0B,EAAE,oBAAO,EACnC,sBAAsB,EAAE,cAAW,EACnC,kBAAkB,EAAE,cAAc,EAClC,mBAAmB,EAAE,oBAAO,GAC7B,CAAC;QACF,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,KAAK,kCAAO,IAAI,KAAE,OAAO,IAAG,CAAC;QACrD,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;YACvB,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;YAC9B,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QAC/B,CAAC;QACD,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;QAC9B,IAAI,CAAC;YACH,MAAM,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YAC9B,OAAO,OAAO,CAAC,MAAM,CACnB,IAAI,sBAAe,CAAC,EAAE,MAAM,EAAE,GA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Q,EAAE,IAAI,CAAC,KAAK,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,SAAS,CAAC;gBAC5D,QAAQ,CAAC,CAAC;oBACR,OAAO,CAAC,CAAC,CAAC,CAAC;gBACb,CAAC;gBACD,KAAK,CAAC,CAAC;oBACL,MAAM,CAAC,CAAC,CAAC,CAAC;gBACZ,CAAC;gBACD,IAAI,CAAC,CAAC;oBACJ,QAAQ,CAAC,CAAC,CAAC,CAAC;gBACd,CAAC;aACF,CAAC,CAAC;QACL,CAAC,CAAA,CAAC,CAAC;IACL,CAAC;IAED;;;;;;;;;;;;;OAaG;IACG,SAAS,CACb,KAAa,EACb,IAA6B;;YAE7B,IAAI,CAAC,uBAAA,IAAI,yBAAM,EAAE,CAAC;gBAChB,MAAM,IAAI,2BAA2B,EAAE,CAAC;YAC1C,CAAC;YACD,OAAO,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE,CAAC,uBAAA,IAAI,2BAAQ,EAAE,IAAI,CAAC,KAAK,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC;QAC9E,CAAC;KAAA;IAEK,SAAS;;YACb,IAAI,CAAC,uBAAA,IAAI,yBAAM,EAAE,CAAC;gBAChB,MAAM,IAAI,2BAA2B,EAAE,CAAC;YAC1C,CAAC;YACD,OAAO,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE,CAAC,uBAAA,IAAI,2BAAQ,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;QACjE,CAAC;KAAA;CACF;AAvZD,kCAuZC","sourcesContent":["import {\n InstantAPIError,\n version as coreVersion,\n InstantRules,\n InstantSchemaDef,\n EntitiesDef,\n LinksDef,\n RoomsDef,\n InstantDBAttr,\n InstantDBIdent,\n InstantDBCheckedDataType,\n i,\n InstantDBInferredType,\n DataAttrDef,\n} from '@instantdb/core';\nimport version from './version.ts';\nimport {\n attrFwdLabel,\n attrFwdName,\n attrRevName,\n identName,\n InstantAPIPlatformSchema,\n InstantAPISchemaPlanStep,\n InstantAPISchemaPushStep,\n} from './schema.ts';\nimport { ProgressPromise } from './ProgressPromise.ts';\nimport {\n capitalizeFirstLetter,\n deriveClientType,\n rels,\n sortedEntries,\n} from './util.ts';\nimport { exchangeRefreshToken } from './serverOAuth.ts';\n\ntype Simplify<T> = {\n [K in keyof T]: T[K];\n} & {};\n\ntype AppDataOpts = {\n includePerms?: boolean | null | undefined;\n includeSchema?: boolean | null | undefined;\n};\n\ntype AppResponseJSON<Opts extends AppDataOpts | undefined> = Simplify<\n {\n id: string;\n title: string;\n created_at: Date;\n org_id: string | null;\n 'admin-token'?: string;\n } & (NonNullable<Opts>['includePerms'] extends true\n ? { perms: InstantRules }\n : {}) &\n (NonNullable<Opts>['includeSchema'] extends true\n ? {\n schema: InstantAPIPlatformSchema;\n }\n : {})\n>;\n\ntype OrgResponseJSON = {\n id: string;\n title: string;\n created_at: Date;\n};\n\nexport type InstantAPIAppDetails<Opts extends AppDataOpts | undefined> =\n Simplify<\n {\n id: string;\n title: string;\n createdAt: Date;\n orgId: string | null;\n } & (NonNullable<Opts>['includePerms'] extends true\n ? { perms: InstantRules }\n : {}) &\n (NonNullable<Opts>['includeSchema'] extends true\n ? {\n schema: InstantSchemaDef<\n EntitiesDef,\n LinksDef<EntitiesDef>,\n RoomsDef\n >;\n }\n : {})\n >;\n\nexport type InstantAPIOrgDetails = {\n id: string;\n title: string;\n createdAt: Date;\n};\n\nexport type InstantAPIGetAppResponse<Opts extends AppDataOpts> = Simplify<{\n app: InstantAPIAppDetails<Opts>;\n}>;\n\nexport type InstantAPIListAppsResponse<Opts extends AppDataOpts | undefined> =\n Simplify<{\n apps: InstantAPIAppDetails<Opts>[];\n }>;\n\nexport type InstantAPIListOrgsResponse = {\n orgs: InstantAPIOrgDetails[];\n};\n\nexport type InstantAPIGetAppSchemaResponse = {\n schema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;\n};\n\nexport type InstantAPIGetAppPermsResponse = { perms: InstantRules };\n\nexport type InstantAPICreateAppBody = {\n title: string;\n schema?:\n | InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>\n | null\n | undefined;\n perms?: InstantRules | null | undefined;\n orgId?: string | null | undefined;\n};\n\nexport type InstantAPICreateTemporaryAppBody = {\n title: string;\n schema?:\n | InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>\n | null\n | undefined;\n rules?: {\n code: InstantRules;\n } | null;\n};\n\nexport type InstantAPICreateTemporaryAppResponse = {\n app: Simplify<\n InstantAPIAppDetails<{ includePerms: false; includeSchema: false }> & {\n adminToken: string;\n }\n >;\n expiresMs: number;\n};\n\nexport type InstantAPICreateAppResponse = Simplify<{\n app: InstantAPIAppDetails<{ includePerms: true; includeSchema: true }> & {\n adminToken: string;\n };\n}>;\n\nexport type InstantAPIUpdateAppBody = { title: string };\n\nexport type InstantAPIUpdateAppResponse = Simplify<{\n app: InstantAPIAppDetails<{}>;\n}>;\n\nexport type InstantAPIDeleteAppResponse = Simplify<{\n app: InstantAPIAppDetails<{}>;\n}>;\n\nexport type InstantAPISchemaPushBody = {\n schema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;\n};\n\nexport type InstantAPIPushPermsBody = {\n perms: InstantRules;\n};\n\nexport type InstantAPIPushPermsResponse = {\n perms: InstantRules;\n};\n\nexport type InstantAPITokenInfoResponse = {\n expiresAt: Date;\n scopes: string;\n tokenType: 'Bearer';\n};\n\nexport type PlanStep =\n | ['add-attr', InstantDBAttr]\n | ['update-attr', Partial<InstantDBAttr>]\n | ['index', { 'attr-id': string; 'forward-identity': InstantDBIdent }]\n | ['remove-index', { 'attr-id': string; 'forward-identity': InstantDBIdent }]\n | ['unique', { 'attr-id': string; 'forward-identity': InstantDBIdent }]\n | ['remove-unique', { 'attr-id': string; 'forward-identity': InstantDBIdent }]\n | ['required', { 'attr-id': string; 'forward-identity': InstantDBIdent }]\n | [\n 'remove-required',\n { 'attr-id': string; 'forward-identity': InstantDBIdent },\n ]\n | [\n 'check-data-type',\n {\n 'attr-id': string;\n 'forward-identity': InstantDBIdent;\n 'checked-data-type': InstantDBCheckedDataType;\n },\n ]\n | [\n 'remove-data-type',\n { 'attr-id': string; 'forward-identity': InstantDBIdent },\n ]\n | ['delete-attr', string];\n\ntype PlanReponseJSON = {\n 'new-schema': InstantAPIPlatformSchema;\n 'current-schema': InstantAPIPlatformSchema;\n 'current-attrs': InstantDBAttr[];\n steps: PlanStep[];\n};\n\n// Same as PlanStep, but some background steps get a job-id\ntype StepWithJobId<T> = T extends ['add-attr', infer P]\n ? ['add-attr', P]\n : T extends ['update-attr', infer P]\n ? ['update-attr', P]\n : T extends [infer K, infer P]\n ? [K, P & { 'job-id': string }]\n : never;\n\ntype PushStep = StepWithJobId<PlanStep>;\n\ntype IndexingJobJSON = {\n id: string;\n app_id: string;\n group_id: string;\n attr_id: string;\n attr_name: string;\n job_type:\n | 'check-data-type'\n | 'remove-data-type'\n | 'index'\n | 'remove-index'\n | 'unique'\n | 'remove-unique'\n | 'required'\n | 'remove-required';\n job_status: 'waiting' | 'processing' | 'completed' | 'errored';\n work_estimate: number | null;\n work_completed: number | null;\n error:\n | 'invalid-triple-error'\n | 'invalid-attr-state-error'\n | 'triple-not-unique-error'\n | 'triple-too-large-error'\n | 'missing-required-error'\n | 'unexpected-error';\n checked_data_type?: InstantDBCheckedDataType;\n created_at: string;\n updated_at: string;\n done_at: string;\n invalid_unique_value: any;\n invalid_triples_sample: {\n entity_id: string;\n value: any;\n json_type:\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'object'\n | 'array'\n | 'date';\n }[];\n error_data: any;\n};\n\ntype SchemaPushResponseJSON = {\n 'indexing-jobs'?: {\n 'group-id': string;\n jobs: IndexingJobJSON[];\n } | null;\n steps: PushStep[];\n};\n\nexport type InstantAPIPlanSchemaPushResponse = {\n newSchema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;\n currentSchema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;\n steps: InstantAPISchemaPlanStep[];\n};\n\ntype InProgressStepsSummary = {\n friendlyDescription: string;\n totalCount: number;\n inProgressCount: number;\n completedCount: number;\n errorCount: number;\n steps: InstantAPISchemaPushStep[];\n inProgressSteps: InstantAPISchemaPushStep[];\n completedSteps: InstantAPISchemaPushStep[];\n erroredSteps: InstantAPISchemaPushStep[];\n};\n\nexport type InstantAPISchemaPushResponse = {\n newSchema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;\n steps: InstantAPISchemaPushStep[];\n summary: InProgressStepsSummary;\n};\n\nasync function jsonFetch<T>(\n input: RequestInfo,\n init: RequestInit | undefined,\n): Promise<T> {\n const headers = {\n ...(init?.headers || {}),\n 'Instant-Platform-Version': version,\n 'Instant-Core-Version': coreVersion,\n 'X-Instant-Source': 'platform-sdk',\n 'X-Instant-Version': version,\n };\n const res = await fetch(input, { ...init, headers });\n if (res.status === 200) {\n const json = await res.json();\n return Promise.resolve(json);\n }\n const body = await res.text();\n try {\n const json = JSON.parse(body);\n return Promise.reject(\n new InstantAPIError({ status: res.status, body: json }),\n );\n } catch (_e) {\n return Promise.reject(\n new InstantAPIError({\n status: res.status,\n body: { type: undefined, message: body },\n }),\n );\n }\n}\n\nfunction attrDefForType(\n type: InstantDBCheckedDataType | InstantDBInferredType | 'any',\n) {\n switch (type) {\n case 'string':\n return i.string();\n case 'any':\n return i.any();\n case 'json':\n return i.json();\n case 'boolean':\n return i.boolean();\n case 'date':\n return i.date();\n case 'number':\n return i.number();\n default: {\n const neverType: never = type;\n throw new Error(`Unknown type ${neverType}.`);\n }\n }\n}\n\ntype APISchemaConversionOpts = {\n disableTypeInference: boolean;\n};\n\nfunction apiSchemaAttrToDataAttrDef(\n attr: InstantDBAttr,\n opts?: APISchemaConversionOpts,\n) {\n const derivedType = deriveClientType(attr, opts?.disableTypeInference);\n let i: DataAttrDef<string, boolean, boolean> = attrDefForType(\n derivedType.type,\n );\n if (attr['unique?']) {\n i = i.unique();\n }\n if (attr['index?']) {\n i = i.indexed();\n }\n if (!attr['required?']) {\n i = i.optional();\n }\n i.metadata.derivedType = derivedType;\n return i;\n}\n\nfunction apiSchemaBlobToEntityDef(\n attrs: InstantAPIPlatformSchema['blobs'][string],\n opts?: APISchemaConversionOpts,\n) {\n const defs: Record<string, DataAttrDef<string, boolean, boolean>> = {};\n for (const [label, attr] of sortedEntries(attrs)) {\n if (label === 'id') {\n continue;\n }\n defs[label] = apiSchemaAttrToDataAttrDef(attr, opts);\n }\n return i.entity(defs);\n}\n\nfunction apiSchemaAttrToLinkName(attr: InstantDBAttr): string {\n const [, fe, flabel] = attr['forward-identity'];\n return `${fe}${capitalizeFirstLetter(flabel)}`;\n}\n\nfunction apiSchemaAttrToLinkDef(attr: InstantDBAttr) {\n const [, fe, flabel] = attr['forward-identity'];\n const [, re, rlabel] = attr['reverse-identity']!;\n const [fhas, rhas] = rels[`${attr.cardinality}-${attr['unique?']}`];\n return {\n forward: {\n on: fe,\n has: fhas,\n label: flabel,\n required: attr['required?'] || undefined,\n onDelete:\n attr['on-delete'] === 'cascade' ? ('cascade' as 'cascade') : undefined,\n },\n reverse: {\n on: re,\n has: rhas,\n label: rlabel,\n onDelete:\n attr['on-delete-reverse'] === 'cascade'\n ? ('cascade' as 'cascade')\n : undefined,\n },\n };\n}\n\nexport function apiSchemaToInstantSchemaDef(\n apiSchema: InstantAPIPlatformSchema,\n opts?: { disableTypeInference: boolean },\n): InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef> {\n const entities: EntitiesDef = {};\n for (const [etype, attrs] of sortedEntries(apiSchema.blobs)) {\n entities[etype] = apiSchemaBlobToEntityDef(attrs, opts);\n }\n const links: LinksDef<EntitiesDef> = {};\n for (const [_name, attr] of sortedEntries(apiSchema.refs)) {\n const link = apiSchemaAttrToLinkDef(attr);\n const linkName = apiSchemaAttrToLinkName(attr);\n links[linkName] = link;\n }\n\n return i.schema({ entities, links });\n}\n\nfunction coerceApp<Opts extends AppDataOpts>(\n app: AppResponseJSON<Opts>,\n): InstantAPIAppDetails<Opts> {\n const base = {\n id: app.id,\n title: app.title,\n createdAt: new Date(app.created_at),\n orgId: app.org_id,\n ...(app['admin-token'] ? { adminToken: app['admin-token'] } : {}),\n };\n\n // `in` narrows the union, so it’s safe to read `perms` / `schema`\n // when the property exists. :contentReference[oaicite:0]{index=0}\n const permsPart = (\n 'perms' in app ? { perms: app.perms } : {}\n ) as InstantAPIAppDetails<Opts>;\n\n const schemaPart = (\n 'schema' in app\n ? {\n schema: apiSchemaToInstantSchemaDef(\n app.schema as InstantAPIPlatformSchema,\n ),\n }\n : {}\n ) as InstantAPIAppDetails<Opts>;\n\n return { ...base, ...permsPart, ...schemaPart };\n}\n\nfunction coerceOrg(org: OrgResponseJSON): InstantAPIOrgDetails {\n return {\n id: org.id,\n title: org.title,\n createdAt: new Date(org.created_at),\n };\n}\n\nasync function getApps<Opts extends AppDataOpts>(\n apiURI: string,\n token: string,\n opts?: Opts,\n): Promise<InstantAPIListAppsResponse<Opts>> {\n const url = new URL(`${apiURI}/superadmin/apps`);\n const include = [];\n if (opts?.includePerms) {\n include.push('perms');\n }\n if (opts?.includeSchema) {\n include.push('schema');\n }\n\n if (include.length) {\n url.searchParams.set('include', include.join(','));\n }\n const resp = await jsonFetch<{ apps: AppResponseJSON<typeof opts>[] }>(\n url.toString(),\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n },\n );\n\n return { apps: resp.apps.map(coerceApp) };\n}\n\nasync function getOrgs(\n apiURI: string,\n token: string,\n): Promise<InstantAPIListOrgsResponse> {\n const url = new URL(`${apiURI}/superadmin/orgs`);\n\n const resp = await jsonFetch<{ orgs: OrgResponseJSON[] }>(url.toString(), {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n });\n\n return { orgs: resp.orgs.map(coerceOrg) };\n}\n\nasync function getAppsForOrg<Opts extends AppDataOpts>(\n apiURI: string,\n token: string,\n orgId: string,\n opts?: Opts,\n): Promise<InstantAPIListAppsResponse<Opts>> {\n const url = new URL(`${apiURI}/superadmin/orgs/${orgId}/apps`);\n const include = [];\n if (opts?.includePerms) {\n include.push('perms');\n }\n if (opts?.includeSchema) {\n include.push('schema');\n }\n\n if (include.length) {\n url.searchParams.set('include', include.join(','));\n }\n const resp = await jsonFetch<{ apps: AppResponseJSON<typeof opts>[] }>(\n url.toString(),\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n },\n );\n\n return { apps: resp.apps.map(coerceApp) };\n}\n\nasync function getAppSchema(\n apiURI: string,\n token: string,\n appId: string,\n): Promise<InstantAPIGetAppSchemaResponse> {\n const { schema } = await jsonFetch<{ schema: InstantAPIPlatformSchema }>(\n `${apiURI}/superadmin/apps/${appId}/schema`,\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n },\n );\n return { schema: apiSchemaToInstantSchemaDef(schema) };\n}\n\nasync function getAppPerms(\n apiURI: string,\n token: string,\n appId: string,\n): Promise<InstantAPIGetAppPermsResponse> {\n return await jsonFetch<InstantAPIGetAppPermsResponse>(\n `${apiURI}/superadmin/apps/${appId}/perms`,\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n },\n );\n}\n\nasync function getApp<Opts extends AppDataOpts>(\n apiURI: string,\n token: string,\n appId: string,\n opts?: Opts,\n): Promise<Simplify<InstantAPIGetAppResponse<Opts>>> {\n let permsPromise: null | Promise<InstantAPIGetAppPermsResponse> = null;\n let schemaPromise: null | Promise<InstantAPIGetAppSchemaResponse> = null;\n if (opts?.includePerms) {\n permsPromise = getAppPerms(apiURI, token, appId);\n }\n if (opts?.includeSchema) {\n schemaPromise = getAppSchema(apiURI, token, appId);\n }\n\n const { app: apiApp } = await jsonFetch<{ app: AppResponseJSON<{}> }>(\n `${apiURI}/superadmin/apps/${appId}`,\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n },\n );\n\n if (!permsPromise && !schemaPromise) {\n const app = coerceApp(apiApp) as InstantAPIAppDetails<{}>;\n return { app } as Simplify<InstantAPIGetAppResponse<Opts>>;\n }\n\n const app = {\n ...(coerceApp(apiApp) as unknown as Simplify<InstantAPIGetAppResponse<{}>>),\n ...(permsPromise ? { perms: (await permsPromise).perms } : {}),\n ...(schemaPromise ? { schema: (await schemaPromise).schema } : {}),\n } as unknown as InstantAPIAppDetails<Opts>;\n\n return {\n app,\n };\n}\n\nasync function createApp(\n apiURI: string,\n token: string,\n fields: InstantAPICreateAppBody,\n): Promise<InstantAPICreateAppResponse> {\n const apiFields: any = fields;\n apiFields.org_id = fields.orgId;\n\n const { app } = await jsonFetch<{\n app: AppResponseJSON<{ includePerms: true; includeSchema: true }> & {\n 'admin-token': string;\n };\n }>(`${apiURI}/superadmin/apps`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(apiFields),\n });\n const withAdminToken = {\n ...coerceApp<{ includePerms: true; includeSchema: true }>(app),\n adminToken: app['admin-token'],\n };\n return {\n app: withAdminToken,\n };\n}\n\nasync function createTemporaryApp(\n apiURI: string,\n fields: InstantAPICreateTemporaryAppBody,\n): Promise<InstantAPICreateTemporaryAppResponse> {\n const response = await jsonFetch<{ app: any; expires_ms: number }>(\n `${apiURI}/dash/apps/ephemeral`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(fields),\n },\n );\n const withAdminToken = {\n ...coerceApp<{ includePerms: true; includeSchema: true }>(response.app),\n adminToken: response.app['admin-token'],\n };\n return {\n app: withAdminToken,\n expiresMs: response.expires_ms,\n };\n}\n\nasync function updateApp(\n apiURI: string,\n token: string,\n appId: string,\n fields: InstantAPIUpdateAppBody,\n): Promise<InstantAPIUpdateAppResponse> {\n const { app } = await jsonFetch<{ app: AppResponseJSON<{}> }>(\n `${apiURI}/superadmin/apps/${appId}`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(fields),\n },\n );\n\n return { app: coerceApp(app) };\n}\n\nasync function deleteApp(\n apiURI: string,\n token: string,\n appId: string,\n): Promise<InstantAPIDeleteAppResponse> {\n const { app } = await jsonFetch<{ app: AppResponseJSON<{}> }>(\n `${apiURI}/superadmin/apps/${appId}`,\n {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n },\n );\n return { app: coerceApp(app) };\n}\n\nfunction translatePlanStep(apiStep: PlanStep): InstantAPISchemaPlanStep {\n const [stepType, stepParams] = apiStep;\n\n switch (stepType) {\n case 'add-attr': {\n const attr = stepParams;\n const attrName = attrFwdName(attr);\n const friendlyDescription =\n attr['value-type'] === 'blob'\n ? attrFwdLabel(attr) === 'id'\n ? `Create new entity ${attrName}.`\n : `Add attribute ${attrName}.`\n : `Link ${attrName} to ${attrRevName(attr)}.`;\n return { type: 'add-attr', friendlyDescription, attr };\n }\n case 'update-attr': {\n const attr = stepParams as InstantDBAttr;\n return {\n type: 'update-attr',\n friendlyDescription: `Update attribute ${attrFwdName(attr)}.`,\n attr,\n };\n }\n case 'index': {\n return {\n type: 'index',\n friendlyDescription: `Add index to ${identName(stepParams['forward-identity'])}.`,\n attrId: stepParams['attr-id'],\n forwardIdentity: stepParams['forward-identity'],\n };\n }\n case 'remove-index': {\n return {\n type: 'remove-index',\n friendlyDescription: `Remove index from ${identName(stepParams['forward-identity'])}.`,\n attrId: stepParams['attr-id'],\n forwardIdentity: stepParams['forward-identity'],\n };\n }\n case 'unique': {\n return {\n type: 'unique',\n friendlyDescription: `Ensure that ${identName(stepParams['forward-identity'])} is unique.`,\n attrId: stepParams['attr-id'],\n forwardIdentity: stepParams['forward-identity'],\n };\n }\n case 'remove-unique': {\n return {\n type: 'remove-unique',\n friendlyDescription: `Remove uniqueness constarint from ${identName(stepParams['forward-identity'])}.`,\n attrId: stepParams['attr-id'],\n forwardIdentity: stepParams['forward-identity'],\n };\n }\n case 'required': {\n return {\n type: 'required',\n friendlyDescription: `Make ${identName(stepParams['forward-identity'])} a required attribute.`,\n attrId: stepParams['attr-id'],\n forwardIdentity: stepParams['forward-identity'],\n };\n }\n case 'remove-required': {\n return {\n type: 'remove-required',\n friendlyDescription: `Allow ${identName(stepParams['forward-identity'])} to be missing or null.`,\n attrId: stepParams['attr-id'],\n forwardIdentity: stepParams['forward-identity'],\n };\n }\n case 'check-data-type': {\n const forwardIdentity = stepParams['forward-identity'];\n const dataType = stepParams['checked-data-type'];\n return {\n type: 'check-data-type',\n friendlyDescription: `Enforce data type of ${identName(forwardIdentity)} as type ${dataType}.`,\n attrId: stepParams['attr-id'],\n forwardIdentity,\n checkedDataType: dataType,\n };\n }\n case 'remove-data-type': {\n const forwardIdentity = stepParams['forward-identity'];\n return {\n type: 'remove-data-type',\n friendlyDescription: `Stop enforcing data type of ${identName(forwardIdentity)}.`,\n attrId: stepParams['attr-id'],\n forwardIdentity: stepParams['forward-identity'],\n };\n }\n // This case will never actually run because /schema/push/plan doesn't detect deleted attrs\n case 'delete-attr': {\n return {\n type: 'delete-attr',\n attrId: stepParams,\n friendlyDescription: `Delete attribute ${stepParams}.`,\n };\n }\n default: {\n // Get a type error if we ignore a case\n const unknownType: never = stepType;\n throw new Error(`Uknown schema operation ${unknownType}.`);\n }\n }\n}\n\nexport function translatePlanSteps(\n apiSteps: PlanStep[],\n): InstantAPISchemaPlanStep[] {\n return apiSteps.map((step) => translatePlanStep(step));\n}\n\ntype PushObjOf<S extends PushStep> =\n // grab from the union the member whose discriminant matches S[0]\n Extract<InstantAPISchemaPushStep, { type: S[0] }>;\n\nfunction translatePushStep<S extends PushStep>(\n apiStep: S,\n jobs: IndexingJobJSON[],\n): PushObjOf<S> {\n const [stepType, stepParams] = apiStep;\n if (stepType === 'add-attr' || stepType === 'update-attr') {\n const planStep = translatePlanStep(apiStep);\n if (planStep.type !== 'add-attr' && planStep.type !== 'update-attr') {\n // This is just here for typescript\n throw new Error('Invalid step.');\n }\n return planStep as PushObjOf<S>;\n }\n const jobId = stepParams['job-id'];\n const job = jobs.find((j) => j.id === jobId)!;\n const planStep = translatePlanStep(apiStep);\n const backgroundJob = formatJob(job);\n\n if (planStep.type !== backgroundJob.type) {\n throw new Error('Invalid type');\n }\n\n return { ...planStep, backgroundJob } as PushObjOf<S>;\n}\n\nfunction translatePushSteps(\n apiSteps: PushStep[],\n jobs: IndexingJobJSON[],\n): InstantAPISchemaPushStep[] {\n return apiSteps.map((step) => translatePushStep(step, jobs));\n}\n\nasync function planSchemaPush(\n apiURI: string,\n token: string,\n appId: string,\n body: InstantAPISchemaPushBody,\n): Promise<InstantAPIPlanSchemaPushResponse> {\n const resp = await jsonFetch<PlanReponseJSON>(\n `${apiURI}/superadmin/apps/${appId}/schema/push/plan`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n ...body,\n check_types: true,\n supports_background_updates: true,\n }),\n },\n );\n\n return {\n newSchema: apiSchemaToInstantSchemaDef(resp['new-schema']),\n currentSchema: apiSchemaToInstantSchemaDef(resp['current-schema']),\n steps: translatePlanSteps(resp['steps']),\n };\n}\n\nfunction allJobsComplete(jobs: IndexingJobJSON[]): boolean {\n return !!jobs.find(\n (j) => j.job_status === 'completed' || j.job_status === 'errored',\n );\n}\n\nfunction latestJobUpdate(jobs: IndexingJobJSON[]): Date | null {\n const res = jobs.reduce((acc: Date | null, job) => {\n if (job.updated_at) {\n const d = new Date(job.updated_at);\n if (!acc || d > acc) {\n return d;\n }\n }\n return acc;\n }, null);\n return res;\n}\n\nasync function jobFetchLoop(\n apiURI: string,\n token: string,\n appId: string,\n groupId: string,\n startingJobs: IndexingJobJSON[],\n onFetch: (jobs: IndexingJobJSON[]) => void,\n): Promise<IndexingJobJSON[]> {\n let interval = 100;\n let lastJobs = startingJobs;\n let errorCount = 0;\n\n while (!allJobsComplete(lastJobs)) {\n await new Promise((resolve) => setTimeout(resolve, interval));\n try {\n const nextJobs = (\n await jsonFetch<{ jobs: IndexingJobJSON[] }>(\n `${apiURI}/dash/apps/${appId}/indexing-jobs/group/${groupId}`,\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n },\n )\n ).jobs;\n onFetch(nextJobs);\n if (allJobsComplete(nextJobs)) {\n return nextJobs;\n }\n errorCount = 0;\n const lastUpdate = latestJobUpdate(lastJobs);\n const thisUpdate = latestJobUpdate(nextJobs);\n interval =\n thisUpdate === null || (lastUpdate && lastUpdate >= thisUpdate)\n ? Math.min(interval * 2, 10000)\n : 100;\n } catch (e) {\n if (errorCount > 3) {\n throw e;\n } else {\n errorCount++;\n interval = Math.min(interval * 2, 10000);\n }\n }\n }\n\n return lastJobs;\n}\n\ntype InstantBackgroundSchemaBaseJob = {\n id: string;\n createdAt: Date;\n updatedAt: Date;\n status: 'completed' | 'waiting' | 'processing' | 'errored';\n workEstimate: number | null;\n workCompleted: number | null;\n error?:\n | 'invalid-triple-error'\n | 'invalid-attr-state-error'\n | 'triple-not-unique-error'\n | 'triple-too-large-error'\n | 'missing-required-error'\n | 'unexpected-error';\n invalidTriplesSample?: {\n entityId: string;\n value: any;\n jsonType:\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'object'\n | 'array'\n | 'date';\n }[];\n};\n\nexport interface InstantBackgroundSchemaRemoveDataTypeJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-data-type';\n}\n\nexport interface InstantBackgroundSchemaCheckDataTypeJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'check-data-type';\n checkedDataType: InstantDBCheckedDataType;\n}\n\nexport interface InstantBackgroundSchemaAddIndexJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'index';\n}\n\nexport interface InstantBackgroundSchemaRemoveIndexJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-index';\n}\n\nexport interface InstantBackgroundSchemaAddUniqueJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'unique';\n invalidUniqueValue?: any;\n}\n\nexport interface InstantBackgroundSchemaRemoveUniqueJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-unique';\n}\n\nexport interface InstantBackgroundSchemaAddRequiredJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'required';\n}\n\nexport interface InstantBackgroundSchemaRemoveRequiredJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-required';\n}\n\nexport type InstantBackgroundSchemaJob =\n | InstantBackgroundSchemaRemoveDataTypeJob\n | InstantBackgroundSchemaCheckDataTypeJob\n | InstantBackgroundSchemaAddIndexJob\n | InstantBackgroundSchemaRemoveIndexJob\n | InstantBackgroundSchemaAddUniqueJob\n | InstantBackgroundSchemaRemoveUniqueJob\n | InstantBackgroundSchemaAddRequiredJob\n | InstantBackgroundSchemaRemoveRequiredJob;\n\nfunction formatJob(job: IndexingJobJSON): InstantBackgroundSchemaJob {\n const baseJob: InstantBackgroundSchemaBaseJob = {\n id: job.id,\n createdAt: new Date(job.created_at),\n updatedAt: new Date(job.updated_at),\n status: job.job_status,\n workEstimate: job.work_estimate,\n workCompleted: job.work_completed,\n error: job.error,\n invalidTriplesSample: job.invalid_triples_sample?.map((s) => {\n return { entityId: s.entity_id, value: s.value, jsonType: s.json_type };\n }),\n };\n switch (job.job_type) {\n case 'remove-data-type':\n case 'index':\n case 'remove-index':\n case 'required':\n case 'remove-required':\n case 'remove-unique': {\n return { ...baseJob, type: job.job_type };\n }\n case 'check-data-type': {\n return {\n ...baseJob,\n type: job.job_type,\n checkedDataType: job.checked_data_type!,\n };\n }\n case 'unique': {\n return {\n ...baseJob,\n type: job.job_type,\n invalidUniqueValue: job.invalid_unique_value,\n };\n }\n default: {\n const neverType: never = job.job_type;\n throw new Error(`Unknown job type: ${neverType}.`);\n }\n }\n}\n\nfunction stepSummary(\n steps: InstantAPISchemaPushStep[],\n): InProgressStepsSummary {\n const inProgress = steps.filter(\n (s) =>\n 'backgroundJob' in s &&\n (s.backgroundJob.status === 'processing' ||\n s.backgroundJob.status === 'waiting'),\n );\n const completed = steps.filter(\n (s) => !('backgroundJob' in s) || s.backgroundJob.status === 'completed',\n );\n const errored = steps.filter(\n (s) => 'backgroundJob' in s && s.backgroundJob.status === 'errored',\n );\n return {\n friendlyDescription: inProgress.length\n ? `Completing ${inProgress.length} of ${steps.length} schema operations.`\n : `Finished ${steps.length} schema operation${steps.length === 1 ? '' : 's'}${\n errored.length\n ? `, with ${errored.length} error${errored.length > 1 ? 's' : ''}`\n : '.'\n }`,\n totalCount: steps.length,\n inProgressCount: inProgress.length,\n completedCount: completed.length,\n errorCount: errored.length,\n steps,\n inProgressSteps: inProgress,\n completedSteps: completed,\n erroredSteps: errored,\n };\n}\n\nfunction schemaPush(\n apiURI: string,\n token: string,\n appId: string,\n body: InstantAPISchemaPushBody,\n): ProgressPromise<InProgressStepsSummary, InstantAPISchemaPushResponse> {\n return new ProgressPromise(async (progress, resolve, reject) => {\n try {\n const resp = await jsonFetch<SchemaPushResponseJSON>(\n `${apiURI}/superadmin/apps/${appId}/schema/push/apply`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n ...body,\n check_types: true,\n supports_background_updates: true,\n }),\n },\n );\n\n const indexingJobs = resp['indexing-jobs'];\n\n const jobs = !indexingJobs\n ? []\n : await jobFetchLoop(\n apiURI,\n token,\n appId,\n indexingJobs['group-id'],\n indexingJobs['jobs'],\n (jobs) => {\n progress(stepSummary(translatePushSteps(resp.steps, jobs)));\n },\n );\n\n const schemaRes = await getAppSchema(apiURI, token, appId);\n resolve({\n newSchema: schemaRes.schema,\n steps: translatePushSteps(resp.steps, jobs),\n summary: stepSummary(translatePushSteps(resp.steps, jobs)),\n });\n } catch (e) {\n reject(e as Error);\n }\n });\n}\n\nasync function pushPerms(\n apiURI: string,\n token: string,\n appId: string,\n body: InstantAPIPushPermsBody,\n): Promise<InstantAPIPushPermsResponse> {\n const result = await jsonFetch<{ rules: { code: InstantRules } }>(\n `${apiURI}/superadmin/apps/${appId}/perms`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({ code: body.perms }),\n },\n );\n\n return { perms: result.rules.code };\n}\n\nasync function tokenInfo(\n apiURI: string,\n token: string,\n): Promise<InstantAPITokenInfoResponse> {\n const result = await jsonFetch<{\n expires_in: number;\n scopes: string;\n token_type: 'Bearer';\n }>(`${apiURI}/platform/oauth/token-info?access_token=${token}`, {\n method: 'GET',\n });\n\n return {\n tokenType: result.token_type,\n scopes: result.scopes,\n expiresAt: new Date(Date.now() + (result.expires_in - 60) * 1000),\n };\n}\n\nexport type PlatformApiAuth =\n | {\n token: string;\n }\n | {\n accessToken: string;\n refreshToken: string;\n clientId: string;\n clientSecret: string;\n onRefresh?: (tokenInfo: {\n accessToken: string;\n expiresAt: Date;\n }) => Promise<void>;\n };\n\nexport type PlatformApiConfig = {\n auth?: PlatformApiAuth;\n apiURI?: string;\n};\n\nexport class PlatformApiMissingAuthError extends Error {\n constructor() {\n super('PlatformApi was not provided auth.');\n }\n}\n\n/**\n * API methods for the Platform API\n *\n * Usage:\n *\n * ```ts\n * import { PlatformApi } from '@instantdb/platform';\n *\n * const api = new PlatformApi({ auth: { token: 'oauth-access-token' } });\n * const { apps } = await api.getApps({\n * includeSchema: true,\n * includePerms: true,\n * });\n * ```\n */\nexport class PlatformApi {\n #auth: PlatformApiAuth | undefined;\n #apiURI: string;\n\n /**\n * @param config – Runtime configuration.\n * @param config.auth.token – OAuth access-token obtained via the oauth flow\n * or a personal access token.\n * @throws {Error} When `token` is missing.\n */\n constructor(config?: PlatformApiConfig) {\n this.#auth = config?.auth;\n this.#apiURI = config?.apiURI || 'https://api.instantdb.com';\n }\n\n token(): string {\n if (!this.#auth) {\n throw new PlatformApiMissingAuthError();\n }\n if ('token' in this.#auth) {\n return this.#auth.token;\n }\n return this.#auth.accessToken;\n }\n\n canRefreshToken(): boolean {\n if (!this.#auth) {\n throw new PlatformApiMissingAuthError();\n }\n return (\n 'refreshToken' in this.#auth &&\n 'clientId' in this.#auth &&\n 'clientSecret' in this.#auth &&\n this.#auth.refreshToken != null &&\n this.#auth.clientId != null &&\n this.#auth.clientSecret != null\n );\n }\n\n async refreshToken(): Promise<null | {\n accessToken: string;\n expiresAt: Date;\n }> {\n if (!this.#auth) {\n throw new PlatformApiMissingAuthError();\n }\n if (\n !this.canRefreshToken() ||\n // Checked in canRefreshToken, but this lets\n // typescript refine this.#auth here\n !('clientId' in this.#auth)\n ) {\n return null;\n }\n const token = await exchangeRefreshToken({\n apiURI: this.#apiURI,\n clientId: this.#auth.clientId,\n clientSecret: this.#auth.clientSecret,\n refreshToken: this.#auth.refreshToken,\n });\n this.#auth.accessToken = token.accessToken;\n if (this.#auth.onRefresh) {\n await this.#auth.onRefresh(token);\n }\n return token;\n }\n\n async withRetry<F extends (...args: any[]) => any>(\n f: F,\n args: Parameters<F>,\n ) {\n let attempt = 0;\n const [apiURI, tokenInArg, ...restArgs] = args;\n let token = tokenInArg;\n while (attempt < 2) {\n try {\n return await f(apiURI, token, ...restArgs);\n } catch (e) {\n if (\n e instanceof InstantAPIError &&\n (e.status === 401 ||\n e.body?.type === 'record-expired' ||\n (e.body?.type === 'record-not-found' &&\n e.body.hint['record-type'].match(/token/i))) &&\n this.canRefreshToken()\n ) {\n const refreshedToken = await this.refreshToken();\n if (refreshedToken) {\n token = refreshedToken.accessToken;\n attempt++;\n continue;\n }\n }\n throw e;\n }\n }\n }\n\n /**\n * Fetch a single app by its id.\n *\n * ```ts\n * const { app } = await api.getApp('MY_APP_ID', {\n * includeSchema: true,\n * includePerms: true,\n * });\n * ```\n *\n * @template Opts – Narrow the shape of the response via the\n * {@link AppDataOpts} flags.\n * @param appId – UUID of the app.\n * @param opts – `{ includeSchema?: boolean; includePerms?: boolean }`\n * @returns A typed wrapper containing the app, whose shape is expanded\n * according to `Opts`.\n */\n async getApp<Opts extends AppDataOpts>(\n appId: string,\n opts?: Opts,\n ): Promise<InstantAPIGetAppResponse<Opts>> {\n return this.withRetry(getApp, [this.#apiURI, this.token(), appId, opts]);\n }\n\n /**\n * List **all apps** owned by the auth owner.\n *\n * ```ts\n * const { apps } = await api.getApps({\n * includeSchema: true,\n * includePerms: true,\n * });\n * ```\n *\n * @template Opts – Same as {@link getApp}.\n * @param opts – `{ includeSchema?: boolean; includePerms?: boolean }`\n * @returns An array wrapper; each element’s shape follows `Opts`.\n */\n async getApps<Opts extends AppDataOpts>(\n opts?: Opts,\n ): Promise<InstantAPIListAppsResponse<Opts>> {\n return this.withRetry(getApps, [this.#apiURI, this.token(), opts]);\n }\n\n /**\n * List **all orgs** that the auth owner is a member of.\n *\n * ```ts\n * const { orgs } = await api.getOrgs();\n * ```\n *\n * @returns An array of orgs\n */\n async getOrgs(): Promise<InstantAPIListOrgsResponse> {\n return this.withRetry(getOrgs, [this.#apiURI, this.token()]);\n }\n\n /**\n * List **all apps** owned by the auth owner.\n *\n * ```ts\n * const { apps } = await api.getApps({\n * includeSchema: true,\n * includePerms: true,\n * });\n * ```\n *\n * @template Opts – Same as {@link getApp}.\n * @param opts – `{ includeSchema?: boolean; includePerms?: boolean }`\n * @returns An array wrapper; each element’s shape follows `Opts`.\n */\n async getAppsForOrg<Opts extends AppDataOpts>(\n orgId: string,\n opts?: Opts,\n ): Promise<InstantAPIListAppsResponse<Opts>> {\n return this.withRetry(getAppsForOrg, [\n this.#apiURI,\n this.token(),\n orgId,\n opts,\n ]);\n }\n\n /**\n * Gets the schema for an app by its id.\n *\n * ```ts\n * const { schema } = await api.getSchema('MY_APP_ID');\n * ```\n *\n * @param appId -- UUID of the app\n */\n async getSchema(appId: string): Promise<InstantAPIGetAppSchemaResponse> {\n return this.withRetry(getAppSchema, [this.#apiURI, this.token(), appId]);\n }\n\n /**\n * Gets the permissions for an app by its id.\n *\n * ```ts\n * const { perms } = await api.getPerms('MY_APP_ID');\n * ```\n *\n * @param appId -- UUID of the app\n */\n async getPerms(appId: string): Promise<InstantAPIGetAppPermsResponse> {\n return this.withRetry(getAppPerms, [this.#apiURI, this.token(), appId]);\n }\n\n /**\n * Create a new app.\n *\n * The app will be placed in the authenticated user's account\n * if no orgId is provided.\n *\n * Optionally set permissions and schema.\n *\n * ```ts\n * const { app } = await api.createApp({\n * title: 'My new app',\n * // Optional permissions\n * perms: { $default: { allow: { $default: 'false' } } },\n * // Optional schema\n * schema: i.schema({\n * entities: { books: i.entity({ title: i.string() }) },\n * }),\n * });\n * ```\n *\n * @param fields\n * @param fields.title -- Title for app\n * @param fields.schema -- Optional schema for the app\n * @param fields.perms -- Optional permissions for the app\n * @param fields.orgId -- Optional id of the org that the app will be placed in\n */\n async createApp(\n fields: InstantAPICreateAppBody,\n ): Promise<InstantAPICreateAppResponse> {\n return this.withRetry(createApp, [this.#apiURI, this.token(), fields]);\n }\n\n /**\n * Create a new temporary app.\n *\n * Optionally set permissions and schema.\n *\n * ```ts\n * const { app } = await api.createTemporaryApp({\n * title: 'My new app',\n * // Optional permissions\n * perms: { $default: { allow: { $default: 'false' } } },\n * // Optional schema\n * schema: i.schema({\n * entities: { books: i.entity({ title: i.string() }) },\n * }),\n * });\n * ```\n *\n * @param fields\n * @param fields.title -- Title for app\n * @param fields.schema -- Optional schema for the app\n * @param fields.perms -- Optional permissions for the app\n */\n async createTemporaryApp(fields: InstantAPICreateTemporaryAppBody) {\n return createTemporaryApp(this.#apiURI, fields);\n }\n\n /**\n * Update the title of an app by its id.\n *\n * ```ts\n * const { app } = await api.updateApp('MY_APP_ID', {\n * title: 'New title',\n * });\n * ```\n *\n * @param appId -- UUID of the app\n * @param fields.title -- New title for the app\n */\n async updateApp(\n appId: string,\n fields: InstantAPIUpdateAppBody,\n ): Promise<InstantAPIUpdateAppResponse> {\n return this.withRetry(updateApp, [\n this.#apiURI,\n this.token(),\n appId,\n fields,\n ]);\n }\n\n /**\n * Delete an app by its id.\n *\n * ```ts\n * const { app } = await api.deleteApp('MY_APP_ID');\n * ```\n *\n * @param appId -- UUID of the app\n */\n async deleteApp(appId: string): Promise<InstantAPIDeleteAppResponse> {\n return this.withRetry(deleteApp, [this.#apiURI, this.token(), appId]);\n }\n\n /**\n * Dry-run a **schema push** and receive a _plan_ of steps the server would\n * execute.\n *\n * ```ts\n * const { steps } = await api.planSchemaPush(appId, body);\n * ```\n */\n async planSchemaPush(\n appId: string,\n body: InstantAPISchemaPushBody,\n ): Promise<InstantAPIPlanSchemaPushResponse> {\n return this.withRetry(planSchemaPush, [\n this.#apiURI,\n this.token(),\n appId,\n body,\n ]);\n }\n\n /**\n * Execute a **schema push**. The server returns a long-running job\n * represented as a {@link ProgressPromise}: you can both `await` the final\n * result **or** subscribe to intermediate status updates.\n *\n * ```ts\n * // 1) Subscribe to progress\n * const schema = i.schema({\n * entities: {\n * books: i.entity({\n * title: i.string().indexed(),\n * }),\n * },\n * });\n * const job = api.schemaPush(appId, { schema: schema });\n * job\n * .then(({ summary }) => console.log('done!', summary))\n * .catch((e) => console.error(e));\n * job.subscribe({\n * next: (status) => renderProgress(status),\n * });\n *\n * // 2) Or just await it\n * const result = await api.schemaPush(appId, { schema: schema });\n * ```\n */\n schemaPush(\n appId: string,\n body: InstantAPISchemaPushBody,\n ): ProgressPromise<InProgressStepsSummary, InstantAPISchemaPushResponse> {\n if (!this.#auth) {\n throw new PlatformApiMissingAuthError();\n }\n return new ProgressPromise(async (progress, resolve, reject) => {\n // It's tricky to add withRetry to the background process that fetches the jobs,\n // so we'll just refresh the token at the start.\n if (this.canRefreshToken()) {\n try {\n await this.refreshToken();\n } catch (_e) {}\n }\n schemaPush(this.#apiURI, this.token(), appId, body).subscribe({\n complete(v) {\n resolve(v);\n },\n error(e) {\n reject(e);\n },\n next(v) {\n progress(v);\n },\n });\n });\n }\n\n /**\n * Update permission rules for an app by its id.\n *\n * Completely replaces the current rule set.\n *\n * ```ts\n * const { steps } = await api.pushPerms(appId, {\n * perms: {\n * $default: { allow: { $default: 'false' } },\n * books: { allow: { view: 'true', $default: 'false' } },\n * },\n * });\n * ```\n */\n async pushPerms(\n appId: string,\n body: InstantAPIPushPermsBody,\n ): Promise<InstantAPIPushPermsResponse> {\n if (!this.#auth) {\n throw new PlatformApiMissingAuthError();\n }\n return this.withRetry(pushPerms, [this.#apiURI, this.token(), appId, body]);\n }\n\n async tokenInfo(): Promise<InstantAPITokenInfoResponse> {\n if (!this.#auth) {\n throw new PlatformApiMissingAuthError();\n }\n return this.withRetry(tokenInfo, [this.#apiURI, this.token()]);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/api.ts"],"names":[],"mappings":";;;;;;AAqaA,kEAgBC;AAsYD,gDAIC;AA/zBD,0CAcyB;AACzB,8DAAmC;AACnC,2CAQqB;AACrB,6DAAuD;AACvD,uCAKmB;AACnB,qDAAwD;AAyQxD,KAAK,UAAU,SAAS,CACtB,KAAkB,EAClB,IAA6B;IAE7B,MAAM,OAAO,GAAG;QACd,GAAG,CAAC,IAAI,EAAE,OAAO,IAAI,EAAE,CAAC;QACxB,0BAA0B,EAAE,oBAAO;QACnC,sBAAsB,EAAE,cAAW;QACnC,kBAAkB,EAAE,cAAc;QAClC,mBAAmB,EAAE,oBAAO;KAC7B,CAAC;IACF,MAAM,GAAG,GAAG,MAAM,KAAK,CAAC,KAAK,EAAE,EAAE,GAAG,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC;IACrD,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,EAAE,CAAC;QACvB,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;QAC9B,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IAC/B,CAAC;IACD,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;IAC9B,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,IAAI,CAAC,K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;oBACR,OAAO,CAAC,CAAC,CAAC,CAAC;gBACb,CAAC;gBACD,KAAK,CAAC,CAAC;oBACL,MAAM,CAAC,CAAC,CAAC,CAAC;gBACZ,CAAC;gBACD,IAAI,CAAC,CAAC;oBACJ,QAAQ,CAAC,CAAC,CAAC,CAAC;gBACd,CAAC;aACF,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;IAED;;;;;;;;;;;;;OAaG;IACH,KAAK,CAAC,SAAS,CACb,KAAa,EACb,IAA6B;QAE7B,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;YAChB,MAAM,IAAI,2BAA2B,EAAE,CAAC;QAC1C,CAAC;QACD,OAAO,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC;IAC9E,CAAC;IAED,KAAK,CAAC,SAAS;QACb,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC;YAChB,MAAM,IAAI,2BAA2B,EAAE,CAAC;QAC1C,CAAC;QACD,OAAO,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;IACjE,CAAC;CACF;AAvZD,kCAuZC","sourcesContent":["import {\n InstantAPIError,\n version as coreVersion,\n InstantRules,\n InstantSchemaDef,\n EntitiesDef,\n LinksDef,\n RoomsDef,\n InstantDBAttr,\n InstantDBIdent,\n InstantDBCheckedDataType,\n i,\n InstantDBInferredType,\n DataAttrDef,\n} from '@instantdb/core';\nimport version from './version.ts';\nimport {\n attrFwdLabel,\n attrFwdName,\n attrRevName,\n identName,\n InstantAPIPlatformSchema,\n InstantAPISchemaPlanStep,\n InstantAPISchemaPushStep,\n} from './schema.ts';\nimport { ProgressPromise } from './ProgressPromise.ts';\nimport {\n capitalizeFirstLetter,\n deriveClientType,\n rels,\n sortedEntries,\n} from './util.ts';\nimport { exchangeRefreshToken } from './serverOAuth.ts';\n\ntype Simplify<T> = {\n [K in keyof T]: T[K];\n} & {};\n\ntype AppDataOpts = {\n includePerms?: boolean | null | undefined;\n includeSchema?: boolean | null | undefined;\n};\n\ntype AppResponseJSON<Opts extends AppDataOpts | undefined> = Simplify<\n {\n id: string;\n title: string;\n created_at: Date;\n org_id: string | null;\n 'admin-token'?: string;\n } & (NonNullable<Opts>['includePerms'] extends true\n ? { perms: InstantRules }\n : {}) &\n (NonNullable<Opts>['includeSchema'] extends true\n ? {\n schema: InstantAPIPlatformSchema;\n }\n : {})\n>;\n\ntype OrgResponseJSON = {\n id: string;\n title: string;\n created_at: Date;\n};\n\nexport type InstantAPIAppDetails<Opts extends AppDataOpts | undefined> =\n Simplify<\n {\n id: string;\n title: string;\n createdAt: Date;\n orgId: string | null;\n } & (NonNullable<Opts>['includePerms'] extends true\n ? { perms: InstantRules }\n : {}) &\n (NonNullable<Opts>['includeSchema'] extends true\n ? {\n schema: InstantSchemaDef<\n EntitiesDef,\n LinksDef<EntitiesDef>,\n RoomsDef\n >;\n }\n : {})\n >;\n\nexport type InstantAPIOrgDetails = {\n id: string;\n title: string;\n createdAt: Date;\n};\n\nexport type InstantAPIGetAppResponse<Opts extends AppDataOpts> = Simplify<{\n app: InstantAPIAppDetails<Opts>;\n}>;\n\nexport type InstantAPIListAppsResponse<Opts extends AppDataOpts | undefined> =\n Simplify<{\n apps: InstantAPIAppDetails<Opts>[];\n }>;\n\nexport type InstantAPIListOrgsResponse = {\n orgs: InstantAPIOrgDetails[];\n};\n\nexport type InstantAPIGetAppSchemaResponse = {\n schema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;\n};\n\nexport type InstantAPIGetAppPermsResponse = { perms: InstantRules };\n\nexport type InstantAPICreateAppBody = {\n title: string;\n schema?:\n | InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>\n | null\n | undefined;\n perms?: InstantRules | null | undefined;\n orgId?: string | null | undefined;\n};\n\nexport type InstantAPICreateTemporaryAppBody = {\n title: string;\n schema?:\n | InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>\n | null\n | undefined;\n rules?: {\n code: InstantRules;\n } | null;\n};\n\nexport type InstantAPICreateTemporaryAppResponse = {\n app: Simplify<\n InstantAPIAppDetails<{ includePerms: false; includeSchema: false }> & {\n adminToken: string;\n }\n >;\n expiresMs: number;\n};\n\nexport type InstantAPICreateAppResponse = Simplify<{\n app: InstantAPIAppDetails<{ includePerms: true; includeSchema: true }> & {\n adminToken: string;\n };\n}>;\n\nexport type InstantAPIUpdateAppBody = { title: string };\n\nexport type InstantAPIUpdateAppResponse = Simplify<{\n app: InstantAPIAppDetails<{}>;\n}>;\n\nexport type InstantAPIDeleteAppResponse = Simplify<{\n app: InstantAPIAppDetails<{}>;\n}>;\n\nexport type InstantAPISchemaPushBody = {\n schema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;\n};\n\nexport type InstantAPIPushPermsBody = {\n perms: InstantRules;\n};\n\nexport type InstantAPIPushPermsResponse = {\n perms: InstantRules;\n};\n\nexport type InstantAPITokenInfoResponse = {\n expiresAt: Date;\n scopes: string;\n tokenType: 'Bearer';\n};\n\nexport type PlanStep =\n | ['add-attr', InstantDBAttr]\n | ['update-attr', Partial<InstantDBAttr>]\n | ['index', { 'attr-id': string; 'forward-identity': InstantDBIdent }]\n | ['remove-index', { 'attr-id': string; 'forward-identity': InstantDBIdent }]\n | ['unique', { 'attr-id': string; 'forward-identity': InstantDBIdent }]\n | ['remove-unique', { 'attr-id': string; 'forward-identity': InstantDBIdent }]\n | ['required', { 'attr-id': string; 'forward-identity': InstantDBIdent }]\n | [\n 'remove-required',\n { 'attr-id': string; 'forward-identity': InstantDBIdent },\n ]\n | [\n 'check-data-type',\n {\n 'attr-id': string;\n 'forward-identity': InstantDBIdent;\n 'checked-data-type': InstantDBCheckedDataType;\n },\n ]\n | [\n 'remove-data-type',\n { 'attr-id': string; 'forward-identity': InstantDBIdent },\n ]\n | ['delete-attr', string];\n\ntype PlanReponseJSON = {\n 'new-schema': InstantAPIPlatformSchema;\n 'current-schema': InstantAPIPlatformSchema;\n 'current-attrs': InstantDBAttr[];\n steps: PlanStep[];\n};\n\n// Same as PlanStep, but some background steps get a job-id\ntype StepWithJobId<T> = T extends ['add-attr', infer P]\n ? ['add-attr', P]\n : T extends ['update-attr', infer P]\n ? ['update-attr', P]\n : T extends [infer K, infer P]\n ? [K, P & { 'job-id': string }]\n : never;\n\ntype PushStep = StepWithJobId<PlanStep>;\n\ntype IndexingJobJSON = {\n id: string;\n app_id: string;\n group_id: string;\n attr_id: string;\n attr_name: string;\n job_type:\n | 'check-data-type'\n | 'remove-data-type'\n | 'index'\n | 'remove-index'\n | 'unique'\n | 'remove-unique'\n | 'required'\n | 'remove-required';\n job_status: 'waiting' | 'processing' | 'completed' | 'errored';\n work_estimate: number | null;\n work_completed: number | null;\n error:\n | 'invalid-triple-error'\n | 'invalid-attr-state-error'\n | 'triple-not-unique-error'\n | 'triple-too-large-error'\n | 'missing-required-error'\n | 'unexpected-error';\n checked_data_type?: InstantDBCheckedDataType;\n created_at: string;\n updated_at: string;\n done_at: string;\n invalid_unique_value: any;\n invalid_triples_sample: {\n entity_id: string;\n value: any;\n json_type:\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'object'\n | 'array'\n | 'date';\n }[];\n error_data: any;\n};\n\ntype SchemaPushResponseJSON = {\n 'indexing-jobs'?: {\n 'group-id': string;\n jobs: IndexingJobJSON[];\n } | null;\n steps: PushStep[];\n};\n\nexport type InstantAPIPlanSchemaPushResponse = {\n newSchema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;\n currentSchema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;\n steps: InstantAPISchemaPlanStep[];\n};\n\ntype InProgressStepsSummary = {\n friendlyDescription: string;\n totalCount: number;\n inProgressCount: number;\n completedCount: number;\n errorCount: number;\n steps: InstantAPISchemaPushStep[];\n inProgressSteps: InstantAPISchemaPushStep[];\n completedSteps: InstantAPISchemaPushStep[];\n erroredSteps: InstantAPISchemaPushStep[];\n};\n\nexport type InstantAPISchemaPushResponse = {\n newSchema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;\n steps: InstantAPISchemaPushStep[];\n summary: InProgressStepsSummary;\n};\n\nasync function jsonFetch<T>(\n input: RequestInfo,\n init: RequestInit | undefined,\n): Promise<T> {\n const headers = {\n ...(init?.headers || {}),\n 'Instant-Platform-Version': version,\n 'Instant-Core-Version': coreVersion,\n 'X-Instant-Source': 'platform-sdk',\n 'X-Instant-Version': version,\n };\n const res = await fetch(input, { ...init, headers });\n if (res.status === 200) {\n const json = await res.json();\n return Promise.resolve(json);\n }\n const body = await res.text();\n try {\n const json = JSON.parse(body);\n return Promise.reject(\n new InstantAPIError({ status: res.status, body: json }),\n );\n } catch (_e) {\n return Promise.reject(\n new InstantAPIError({\n status: res.status,\n body: { type: undefined, message: body },\n }),\n );\n }\n}\n\nfunction attrDefForType(\n type: InstantDBCheckedDataType | InstantDBInferredType | 'any',\n) {\n switch (type) {\n case 'string':\n return i.string();\n case 'any':\n return i.any();\n case 'json':\n return i.json();\n case 'boolean':\n return i.boolean();\n case 'date':\n return i.date();\n case 'number':\n return i.number();\n default: {\n const neverType: never = type;\n throw new Error(`Unknown type ${neverType}.`);\n }\n }\n}\n\ntype APISchemaConversionOpts = {\n disableTypeInference: boolean;\n};\n\nfunction apiSchemaAttrToDataAttrDef(\n attr: InstantDBAttr,\n opts?: APISchemaConversionOpts,\n) {\n const derivedType = deriveClientType(attr, opts?.disableTypeInference);\n let i: DataAttrDef<string, boolean, boolean> = attrDefForType(\n derivedType.type,\n );\n if (attr['unique?']) {\n i = i.unique();\n }\n if (attr['index?']) {\n i = i.indexed();\n }\n if (!attr['required?']) {\n i = i.optional();\n }\n i.metadata.derivedType = derivedType;\n return i;\n}\n\nfunction apiSchemaBlobToEntityDef(\n attrs: InstantAPIPlatformSchema['blobs'][string],\n opts?: APISchemaConversionOpts,\n) {\n const defs: Record<string, DataAttrDef<string, boolean, boolean>> = {};\n for (const [label, attr] of sortedEntries(attrs)) {\n if (label === 'id') {\n continue;\n }\n defs[label] = apiSchemaAttrToDataAttrDef(attr, opts);\n }\n return i.entity(defs);\n}\n\nfunction apiSchemaAttrToLinkName(attr: InstantDBAttr): string {\n const [, fe, flabel] = attr['forward-identity'];\n return `${fe}${capitalizeFirstLetter(flabel)}`;\n}\n\nfunction apiSchemaAttrToLinkDef(attr: InstantDBAttr) {\n const [, fe, flabel] = attr['forward-identity'];\n const [, re, rlabel] = attr['reverse-identity']!;\n const [fhas, rhas] = rels[`${attr.cardinality}-${attr['unique?']}`];\n return {\n forward: {\n on: fe,\n has: fhas,\n label: flabel,\n required: attr['required?'] || undefined,\n onDelete:\n attr['on-delete'] === 'cascade' ? ('cascade' as 'cascade') : undefined,\n },\n reverse: {\n on: re,\n has: rhas,\n label: rlabel,\n onDelete:\n attr['on-delete-reverse'] === 'cascade'\n ? ('cascade' as 'cascade')\n : undefined,\n },\n };\n}\n\nexport function apiSchemaToInstantSchemaDef(\n apiSchema: InstantAPIPlatformSchema,\n opts?: { disableTypeInference: boolean },\n): InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef> {\n const entities: EntitiesDef = {};\n for (const [etype, attrs] of sortedEntries(apiSchema.blobs)) {\n entities[etype] = apiSchemaBlobToEntityDef(attrs, opts);\n }\n const links: LinksDef<EntitiesDef> = {};\n for (const [_name, attr] of sortedEntries(apiSchema.refs)) {\n const link = apiSchemaAttrToLinkDef(attr);\n const linkName = apiSchemaAttrToLinkName(attr);\n links[linkName] = link;\n }\n\n return i.schema({ entities, links });\n}\n\nfunction coerceApp<Opts extends AppDataOpts>(\n app: AppResponseJSON<Opts>,\n): InstantAPIAppDetails<Opts> {\n const base = {\n id: app.id,\n title: app.title,\n createdAt: new Date(app.created_at),\n orgId: app.org_id,\n ...(app['admin-token'] ? { adminToken: app['admin-token'] } : {}),\n };\n\n // `in` narrows the union, so it’s safe to read `perms` / `schema`\n // when the property exists. :contentReference[oaicite:0]{index=0}\n const permsPart = (\n 'perms' in app ? { perms: app.perms } : {}\n ) as InstantAPIAppDetails<Opts>;\n\n const schemaPart = (\n 'schema' in app\n ? {\n schema: apiSchemaToInstantSchemaDef(\n app.schema as InstantAPIPlatformSchema,\n ),\n }\n : {}\n ) as InstantAPIAppDetails<Opts>;\n\n return { ...base, ...permsPart, ...schemaPart };\n}\n\nfunction coerceOrg(org: OrgResponseJSON): InstantAPIOrgDetails {\n return {\n id: org.id,\n title: org.title,\n createdAt: new Date(org.created_at),\n };\n}\n\nasync function getApps<Opts extends AppDataOpts>(\n apiURI: string,\n token: string,\n opts?: Opts,\n): Promise<InstantAPIListAppsResponse<Opts>> {\n const url = new URL(`${apiURI}/superadmin/apps`);\n const include = [];\n if (opts?.includePerms) {\n include.push('perms');\n }\n if (opts?.includeSchema) {\n include.push('schema');\n }\n\n if (include.length) {\n url.searchParams.set('include', include.join(','));\n }\n const resp = await jsonFetch<{ apps: AppResponseJSON<typeof opts>[] }>(\n url.toString(),\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n },\n );\n\n return { apps: resp.apps.map(coerceApp) };\n}\n\nasync function getOrgs(\n apiURI: string,\n token: string,\n): Promise<InstantAPIListOrgsResponse> {\n const url = new URL(`${apiURI}/superadmin/orgs`);\n\n const resp = await jsonFetch<{ orgs: OrgResponseJSON[] }>(url.toString(), {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n });\n\n return { orgs: resp.orgs.map(coerceOrg) };\n}\n\nasync function getAppsForOrg<Opts extends AppDataOpts>(\n apiURI: string,\n token: string,\n orgId: string,\n opts?: Opts,\n): Promise<InstantAPIListAppsResponse<Opts>> {\n const url = new URL(`${apiURI}/superadmin/orgs/${orgId}/apps`);\n const include = [];\n if (opts?.includePerms) {\n include.push('perms');\n }\n if (opts?.includeSchema) {\n include.push('schema');\n }\n\n if (include.length) {\n url.searchParams.set('include', include.join(','));\n }\n const resp = await jsonFetch<{ apps: AppResponseJSON<typeof opts>[] }>(\n url.toString(),\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n },\n );\n\n return { apps: resp.apps.map(coerceApp) };\n}\n\nasync function getAppSchema(\n apiURI: string,\n token: string,\n appId: string,\n): Promise<InstantAPIGetAppSchemaResponse> {\n const { schema } = await jsonFetch<{ schema: InstantAPIPlatformSchema }>(\n `${apiURI}/superadmin/apps/${appId}/schema`,\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n },\n );\n return { schema: apiSchemaToInstantSchemaDef(schema) };\n}\n\nasync function getAppPerms(\n apiURI: string,\n token: string,\n appId: string,\n): Promise<InstantAPIGetAppPermsResponse> {\n return await jsonFetch<InstantAPIGetAppPermsResponse>(\n `${apiURI}/superadmin/apps/${appId}/perms`,\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n },\n );\n}\n\nasync function getApp<Opts extends AppDataOpts>(\n apiURI: string,\n token: string,\n appId: string,\n opts?: Opts,\n): Promise<Simplify<InstantAPIGetAppResponse<Opts>>> {\n let permsPromise: null | Promise<InstantAPIGetAppPermsResponse> = null;\n let schemaPromise: null | Promise<InstantAPIGetAppSchemaResponse> = null;\n if (opts?.includePerms) {\n permsPromise = getAppPerms(apiURI, token, appId);\n }\n if (opts?.includeSchema) {\n schemaPromise = getAppSchema(apiURI, token, appId);\n }\n\n const { app: apiApp } = await jsonFetch<{ app: AppResponseJSON<{}> }>(\n `${apiURI}/superadmin/apps/${appId}`,\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n },\n );\n\n if (!permsPromise && !schemaPromise) {\n const app = coerceApp(apiApp) as InstantAPIAppDetails<{}>;\n return { app } as Simplify<InstantAPIGetAppResponse<Opts>>;\n }\n\n const app = {\n ...(coerceApp(apiApp) as unknown as Simplify<InstantAPIGetAppResponse<{}>>),\n ...(permsPromise ? { perms: (await permsPromise).perms } : {}),\n ...(schemaPromise ? { schema: (await schemaPromise).schema } : {}),\n } as unknown as InstantAPIAppDetails<Opts>;\n\n return {\n app,\n };\n}\n\nasync function createApp(\n apiURI: string,\n token: string,\n fields: InstantAPICreateAppBody,\n): Promise<InstantAPICreateAppResponse> {\n const apiFields: any = fields;\n apiFields.org_id = fields.orgId;\n\n const { app } = await jsonFetch<{\n app: AppResponseJSON<{ includePerms: true; includeSchema: true }> & {\n 'admin-token': string;\n };\n }>(`${apiURI}/superadmin/apps`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(apiFields),\n });\n const withAdminToken = {\n ...coerceApp<{ includePerms: true; includeSchema: true }>(app),\n adminToken: app['admin-token'],\n };\n return {\n app: withAdminToken,\n };\n}\n\nasync function createTemporaryApp(\n apiURI: string,\n fields: InstantAPICreateTemporaryAppBody,\n): Promise<InstantAPICreateTemporaryAppResponse> {\n const response = await jsonFetch<{ app: any; expires_ms: number }>(\n `${apiURI}/dash/apps/ephemeral`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(fields),\n },\n );\n const withAdminToken = {\n ...coerceApp<{ includePerms: true; includeSchema: true }>(response.app),\n adminToken: response.app['admin-token'],\n };\n return {\n app: withAdminToken,\n expiresMs: response.expires_ms,\n };\n}\n\nasync function updateApp(\n apiURI: string,\n token: string,\n appId: string,\n fields: InstantAPIUpdateAppBody,\n): Promise<InstantAPIUpdateAppResponse> {\n const { app } = await jsonFetch<{ app: AppResponseJSON<{}> }>(\n `${apiURI}/superadmin/apps/${appId}`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify(fields),\n },\n );\n\n return { app: coerceApp(app) };\n}\n\nasync function deleteApp(\n apiURI: string,\n token: string,\n appId: string,\n): Promise<InstantAPIDeleteAppResponse> {\n const { app } = await jsonFetch<{ app: AppResponseJSON<{}> }>(\n `${apiURI}/superadmin/apps/${appId}`,\n {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n },\n );\n return { app: coerceApp(app) };\n}\n\nfunction translatePlanStep(apiStep: PlanStep): InstantAPISchemaPlanStep {\n const [stepType, stepParams] = apiStep;\n\n switch (stepType) {\n case 'add-attr': {\n const attr = stepParams;\n const attrName = attrFwdName(attr);\n const friendlyDescription =\n attr['value-type'] === 'blob'\n ? attrFwdLabel(attr) === 'id'\n ? `Create new entity ${attrName}.`\n : `Add attribute ${attrName}.`\n : `Link ${attrName} to ${attrRevName(attr)}.`;\n return { type: 'add-attr', friendlyDescription, attr };\n }\n case 'update-attr': {\n const attr = stepParams as InstantDBAttr;\n return {\n type: 'update-attr',\n friendlyDescription: `Update attribute ${attrFwdName(attr)}.`,\n attr,\n };\n }\n case 'index': {\n return {\n type: 'index',\n friendlyDescription: `Add index to ${identName(stepParams['forward-identity'])}.`,\n attrId: stepParams['attr-id'],\n forwardIdentity: stepParams['forward-identity'],\n };\n }\n case 'remove-index': {\n return {\n type: 'remove-index',\n friendlyDescription: `Remove index from ${identName(stepParams['forward-identity'])}.`,\n attrId: stepParams['attr-id'],\n forwardIdentity: stepParams['forward-identity'],\n };\n }\n case 'unique': {\n return {\n type: 'unique',\n friendlyDescription: `Ensure that ${identName(stepParams['forward-identity'])} is unique.`,\n attrId: stepParams['attr-id'],\n forwardIdentity: stepParams['forward-identity'],\n };\n }\n case 'remove-unique': {\n return {\n type: 'remove-unique',\n friendlyDescription: `Remove uniqueness constarint from ${identName(stepParams['forward-identity'])}.`,\n attrId: stepParams['attr-id'],\n forwardIdentity: stepParams['forward-identity'],\n };\n }\n case 'required': {\n return {\n type: 'required',\n friendlyDescription: `Make ${identName(stepParams['forward-identity'])} a required attribute.`,\n attrId: stepParams['attr-id'],\n forwardIdentity: stepParams['forward-identity'],\n };\n }\n case 'remove-required': {\n return {\n type: 'remove-required',\n friendlyDescription: `Allow ${identName(stepParams['forward-identity'])} to be missing or null.`,\n attrId: stepParams['attr-id'],\n forwardIdentity: stepParams['forward-identity'],\n };\n }\n case 'check-data-type': {\n const forwardIdentity = stepParams['forward-identity'];\n const dataType = stepParams['checked-data-type'];\n return {\n type: 'check-data-type',\n friendlyDescription: `Enforce data type of ${identName(forwardIdentity)} as type ${dataType}.`,\n attrId: stepParams['attr-id'],\n forwardIdentity,\n checkedDataType: dataType,\n };\n }\n case 'remove-data-type': {\n const forwardIdentity = stepParams['forward-identity'];\n return {\n type: 'remove-data-type',\n friendlyDescription: `Stop enforcing data type of ${identName(forwardIdentity)}.`,\n attrId: stepParams['attr-id'],\n forwardIdentity: stepParams['forward-identity'],\n };\n }\n // This case will never actually run because /schema/push/plan doesn't detect deleted attrs\n case 'delete-attr': {\n return {\n type: 'delete-attr',\n attrId: stepParams,\n friendlyDescription: `Delete attribute ${stepParams}.`,\n };\n }\n default: {\n // Get a type error if we ignore a case\n const unknownType: never = stepType;\n throw new Error(`Uknown schema operation ${unknownType}.`);\n }\n }\n}\n\nexport function translatePlanSteps(\n apiSteps: PlanStep[],\n): InstantAPISchemaPlanStep[] {\n return apiSteps.map((step) => translatePlanStep(step));\n}\n\ntype PushObjOf<S extends PushStep> =\n // grab from the union the member whose discriminant matches S[0]\n Extract<InstantAPISchemaPushStep, { type: S[0] }>;\n\nfunction translatePushStep<S extends PushStep>(\n apiStep: S,\n jobs: IndexingJobJSON[],\n): PushObjOf<S> {\n const [stepType, stepParams] = apiStep;\n if (stepType === 'add-attr' || stepType === 'update-attr') {\n const planStep = translatePlanStep(apiStep);\n if (planStep.type !== 'add-attr' && planStep.type !== 'update-attr') {\n // This is just here for typescript\n throw new Error('Invalid step.');\n }\n return planStep as PushObjOf<S>;\n }\n const jobId = stepParams['job-id'];\n const job = jobs.find((j) => j.id === jobId)!;\n const planStep = translatePlanStep(apiStep);\n const backgroundJob = formatJob(job);\n\n if (planStep.type !== backgroundJob.type) {\n throw new Error('Invalid type');\n }\n\n return { ...planStep, backgroundJob } as PushObjOf<S>;\n}\n\nfunction translatePushSteps(\n apiSteps: PushStep[],\n jobs: IndexingJobJSON[],\n): InstantAPISchemaPushStep[] {\n return apiSteps.map((step) => translatePushStep(step, jobs));\n}\n\nasync function planSchemaPush(\n apiURI: string,\n token: string,\n appId: string,\n body: InstantAPISchemaPushBody,\n): Promise<InstantAPIPlanSchemaPushResponse> {\n const resp = await jsonFetch<PlanReponseJSON>(\n `${apiURI}/superadmin/apps/${appId}/schema/push/plan`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n ...body,\n check_types: true,\n supports_background_updates: true,\n }),\n },\n );\n\n return {\n newSchema: apiSchemaToInstantSchemaDef(resp['new-schema']),\n currentSchema: apiSchemaToInstantSchemaDef(resp['current-schema']),\n steps: translatePlanSteps(resp['steps']),\n };\n}\n\nfunction allJobsComplete(jobs: IndexingJobJSON[]): boolean {\n return !!jobs.find(\n (j) => j.job_status === 'completed' || j.job_status === 'errored',\n );\n}\n\nfunction latestJobUpdate(jobs: IndexingJobJSON[]): Date | null {\n const res = jobs.reduce((acc: Date | null, job) => {\n if (job.updated_at) {\n const d = new Date(job.updated_at);\n if (!acc || d > acc) {\n return d;\n }\n }\n return acc;\n }, null);\n return res;\n}\n\nasync function jobFetchLoop(\n apiURI: string,\n token: string,\n appId: string,\n groupId: string,\n startingJobs: IndexingJobJSON[],\n onFetch: (jobs: IndexingJobJSON[]) => void,\n): Promise<IndexingJobJSON[]> {\n let interval = 100;\n let lastJobs = startingJobs;\n let errorCount = 0;\n\n while (!allJobsComplete(lastJobs)) {\n await new Promise((resolve) => setTimeout(resolve, interval));\n try {\n const nextJobs = (\n await jsonFetch<{ jobs: IndexingJobJSON[] }>(\n `${apiURI}/dash/apps/${appId}/indexing-jobs/group/${groupId}`,\n {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n },\n )\n ).jobs;\n onFetch(nextJobs);\n if (allJobsComplete(nextJobs)) {\n return nextJobs;\n }\n errorCount = 0;\n const lastUpdate = latestJobUpdate(lastJobs);\n const thisUpdate = latestJobUpdate(nextJobs);\n interval =\n thisUpdate === null || (lastUpdate && lastUpdate >= thisUpdate)\n ? Math.min(interval * 2, 10000)\n : 100;\n } catch (e) {\n if (errorCount > 3) {\n throw e;\n } else {\n errorCount++;\n interval = Math.min(interval * 2, 10000);\n }\n }\n }\n\n return lastJobs;\n}\n\ntype InstantBackgroundSchemaBaseJob = {\n id: string;\n createdAt: Date;\n updatedAt: Date;\n status: 'completed' | 'waiting' | 'processing' | 'errored';\n workEstimate: number | null;\n workCompleted: number | null;\n error?:\n | 'invalid-triple-error'\n | 'invalid-attr-state-error'\n | 'triple-not-unique-error'\n | 'triple-too-large-error'\n | 'missing-required-error'\n | 'unexpected-error';\n invalidTriplesSample?: {\n entityId: string;\n value: any;\n jsonType:\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'object'\n | 'array'\n | 'date';\n }[];\n};\n\nexport interface InstantBackgroundSchemaRemoveDataTypeJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-data-type';\n}\n\nexport interface InstantBackgroundSchemaCheckDataTypeJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'check-data-type';\n checkedDataType: InstantDBCheckedDataType;\n}\n\nexport interface InstantBackgroundSchemaAddIndexJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'index';\n}\n\nexport interface InstantBackgroundSchemaRemoveIndexJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-index';\n}\n\nexport interface InstantBackgroundSchemaAddUniqueJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'unique';\n invalidUniqueValue?: any;\n}\n\nexport interface InstantBackgroundSchemaRemoveUniqueJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-unique';\n}\n\nexport interface InstantBackgroundSchemaAddRequiredJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'required';\n}\n\nexport interface InstantBackgroundSchemaRemoveRequiredJob\n extends InstantBackgroundSchemaBaseJob {\n type: 'remove-required';\n}\n\nexport type InstantBackgroundSchemaJob =\n | InstantBackgroundSchemaRemoveDataTypeJob\n | InstantBackgroundSchemaCheckDataTypeJob\n | InstantBackgroundSchemaAddIndexJob\n | InstantBackgroundSchemaRemoveIndexJob\n | InstantBackgroundSchemaAddUniqueJob\n | InstantBackgroundSchemaRemoveUniqueJob\n | InstantBackgroundSchemaAddRequiredJob\n | InstantBackgroundSchemaRemoveRequiredJob;\n\nfunction formatJob(job: IndexingJobJSON): InstantBackgroundSchemaJob {\n const baseJob: InstantBackgroundSchemaBaseJob = {\n id: job.id,\n createdAt: new Date(job.created_at),\n updatedAt: new Date(job.updated_at),\n status: job.job_status,\n workEstimate: job.work_estimate,\n workCompleted: job.work_completed,\n error: job.error,\n invalidTriplesSample: job.invalid_triples_sample?.map((s) => {\n return { entityId: s.entity_id, value: s.value, jsonType: s.json_type };\n }),\n };\n switch (job.job_type) {\n case 'remove-data-type':\n case 'index':\n case 'remove-index':\n case 'required':\n case 'remove-required':\n case 'remove-unique': {\n return { ...baseJob, type: job.job_type };\n }\n case 'check-data-type': {\n return {\n ...baseJob,\n type: job.job_type,\n checkedDataType: job.checked_data_type!,\n };\n }\n case 'unique': {\n return {\n ...baseJob,\n type: job.job_type,\n invalidUniqueValue: job.invalid_unique_value,\n };\n }\n default: {\n const neverType: never = job.job_type;\n throw new Error(`Unknown job type: ${neverType}.`);\n }\n }\n}\n\nfunction stepSummary(\n steps: InstantAPISchemaPushStep[],\n): InProgressStepsSummary {\n const inProgress = steps.filter(\n (s) =>\n 'backgroundJob' in s &&\n (s.backgroundJob.status === 'processing' ||\n s.backgroundJob.status === 'waiting'),\n );\n const completed = steps.filter(\n (s) => !('backgroundJob' in s) || s.backgroundJob.status === 'completed',\n );\n const errored = steps.filter(\n (s) => 'backgroundJob' in s && s.backgroundJob.status === 'errored',\n );\n return {\n friendlyDescription: inProgress.length\n ? `Completing ${inProgress.length} of ${steps.length} schema operations.`\n : `Finished ${steps.length} schema operation${steps.length === 1 ? '' : 's'}${\n errored.length\n ? `, with ${errored.length} error${errored.length > 1 ? 's' : ''}`\n : '.'\n }`,\n totalCount: steps.length,\n inProgressCount: inProgress.length,\n completedCount: completed.length,\n errorCount: errored.length,\n steps,\n inProgressSteps: inProgress,\n completedSteps: completed,\n erroredSteps: errored,\n };\n}\n\nfunction schemaPush(\n apiURI: string,\n token: string,\n appId: string,\n body: InstantAPISchemaPushBody,\n): ProgressPromise<InProgressStepsSummary, InstantAPISchemaPushResponse> {\n return new ProgressPromise(async (progress, resolve, reject) => {\n try {\n const resp = await jsonFetch<SchemaPushResponseJSON>(\n `${apiURI}/superadmin/apps/${appId}/schema/push/apply`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n ...body,\n check_types: true,\n supports_background_updates: true,\n }),\n },\n );\n\n const indexingJobs = resp['indexing-jobs'];\n\n const jobs = !indexingJobs\n ? []\n : await jobFetchLoop(\n apiURI,\n token,\n appId,\n indexingJobs['group-id'],\n indexingJobs['jobs'],\n (jobs) => {\n progress(stepSummary(translatePushSteps(resp.steps, jobs)));\n },\n );\n\n const schemaRes = await getAppSchema(apiURI, token, appId);\n resolve({\n newSchema: schemaRes.schema,\n steps: translatePushSteps(resp.steps, jobs),\n summary: stepSummary(translatePushSteps(resp.steps, jobs)),\n });\n } catch (e) {\n reject(e as Error);\n }\n });\n}\n\nasync function pushPerms(\n apiURI: string,\n token: string,\n appId: string,\n body: InstantAPIPushPermsBody,\n): Promise<InstantAPIPushPermsResponse> {\n const result = await jsonFetch<{ rules: { code: InstantRules } }>(\n `${apiURI}/superadmin/apps/${appId}/perms`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({ code: body.perms }),\n },\n );\n\n return { perms: result.rules.code };\n}\n\nasync function tokenInfo(\n apiURI: string,\n token: string,\n): Promise<InstantAPITokenInfoResponse> {\n const result = await jsonFetch<{\n expires_in: number;\n scopes: string;\n token_type: 'Bearer';\n }>(`${apiURI}/platform/oauth/token-info?access_token=${token}`, {\n method: 'GET',\n });\n\n return {\n tokenType: result.token_type,\n scopes: result.scopes,\n expiresAt: new Date(Date.now() + (result.expires_in - 60) * 1000),\n };\n}\n\nexport type PlatformApiAuth =\n | {\n token: string;\n }\n | {\n accessToken: string;\n refreshToken: string;\n clientId: string;\n clientSecret: string;\n onRefresh?: (tokenInfo: {\n accessToken: string;\n expiresAt: Date;\n }) => Promise<void>;\n };\n\nexport type PlatformApiConfig = {\n auth?: PlatformApiAuth;\n apiURI?: string;\n};\n\nexport class PlatformApiMissingAuthError extends Error {\n constructor() {\n super('PlatformApi was not provided auth.');\n }\n}\n\n/**\n * API methods for the Platform API\n *\n * Usage:\n *\n * ```ts\n * import { PlatformApi } from '@instantdb/platform';\n *\n * const api = new PlatformApi({ auth: { token: 'oauth-access-token' } });\n * const { apps } = await api.getApps({\n * includeSchema: true,\n * includePerms: true,\n * });\n * ```\n */\nexport class PlatformApi {\n #auth: PlatformApiAuth | undefined;\n #apiURI: string;\n\n /**\n * @param config – Runtime configuration.\n * @param config.auth.token – OAuth access-token obtained via the oauth flow\n * or a personal access token.\n * @throws {Error} When `token` is missing.\n */\n constructor(config?: PlatformApiConfig) {\n this.#auth = config?.auth;\n this.#apiURI = config?.apiURI || 'https://api.instantdb.com';\n }\n\n token(): string {\n if (!this.#auth) {\n throw new PlatformApiMissingAuthError();\n }\n if ('token' in this.#auth) {\n return this.#auth.token;\n }\n return this.#auth.accessToken;\n }\n\n canRefreshToken(): boolean {\n if (!this.#auth) {\n throw new PlatformApiMissingAuthError();\n }\n return (\n 'refreshToken' in this.#auth &&\n 'clientId' in this.#auth &&\n 'clientSecret' in this.#auth &&\n this.#auth.refreshToken != null &&\n this.#auth.clientId != null &&\n this.#auth.clientSecret != null\n );\n }\n\n async refreshToken(): Promise<null | {\n accessToken: string;\n expiresAt: Date;\n }> {\n if (!this.#auth) {\n throw new PlatformApiMissingAuthError();\n }\n if (\n !this.canRefreshToken() ||\n // Checked in canRefreshToken, but this lets\n // typescript refine this.#auth here\n !('clientId' in this.#auth)\n ) {\n return null;\n }\n const token = await exchangeRefreshToken({\n apiURI: this.#apiURI,\n clientId: this.#auth.clientId,\n clientSecret: this.#auth.clientSecret,\n refreshToken: this.#auth.refreshToken,\n });\n this.#auth.accessToken = token.accessToken;\n if (this.#auth.onRefresh) {\n await this.#auth.onRefresh(token);\n }\n return token;\n }\n\n async withRetry<F extends (...args: any[]) => any>(\n f: F,\n args: Parameters<F>,\n ) {\n let attempt = 0;\n const [apiURI, tokenInArg, ...restArgs] = args;\n let token = tokenInArg;\n while (attempt < 2) {\n try {\n return await f(apiURI, token, ...restArgs);\n } catch (e) {\n if (\n e instanceof InstantAPIError &&\n (e.status === 401 ||\n e.body?.type === 'record-expired' ||\n (e.body?.type === 'record-not-found' &&\n e.body.hint['record-type'].match(/token/i))) &&\n this.canRefreshToken()\n ) {\n const refreshedToken = await this.refreshToken();\n if (refreshedToken) {\n token = refreshedToken.accessToken;\n attempt++;\n continue;\n }\n }\n throw e;\n }\n }\n }\n\n /**\n * Fetch a single app by its id.\n *\n * ```ts\n * const { app } = await api.getApp('MY_APP_ID', {\n * includeSchema: true,\n * includePerms: true,\n * });\n * ```\n *\n * @template Opts – Narrow the shape of the response via the\n * {@link AppDataOpts} flags.\n * @param appId – UUID of the app.\n * @param opts – `{ includeSchema?: boolean; includePerms?: boolean }`\n * @returns A typed wrapper containing the app, whose shape is expanded\n * according to `Opts`.\n */\n async getApp<Opts extends AppDataOpts>(\n appId: string,\n opts?: Opts,\n ): Promise<InstantAPIGetAppResponse<Opts>> {\n return this.withRetry(getApp, [this.#apiURI, this.token(), appId, opts]);\n }\n\n /**\n * List **all apps** owned by the auth owner.\n *\n * ```ts\n * const { apps } = await api.getApps({\n * includeSchema: true,\n * includePerms: true,\n * });\n * ```\n *\n * @template Opts – Same as {@link getApp}.\n * @param opts – `{ includeSchema?: boolean; includePerms?: boolean }`\n * @returns An array wrapper; each element’s shape follows `Opts`.\n */\n async getApps<Opts extends AppDataOpts>(\n opts?: Opts,\n ): Promise<InstantAPIListAppsResponse<Opts>> {\n return this.withRetry(getApps, [this.#apiURI, this.token(), opts]);\n }\n\n /**\n * List **all orgs** that the auth owner is a member of.\n *\n * ```ts\n * const { orgs } = await api.getOrgs();\n * ```\n *\n * @returns An array of orgs\n */\n async getOrgs(): Promise<InstantAPIListOrgsResponse> {\n return this.withRetry(getOrgs, [this.#apiURI, this.token()]);\n }\n\n /**\n * List **all apps** owned by the auth owner.\n *\n * ```ts\n * const { apps } = await api.getApps({\n * includeSchema: true,\n * includePerms: true,\n * });\n * ```\n *\n * @template Opts – Same as {@link getApp}.\n * @param opts – `{ includeSchema?: boolean; includePerms?: boolean }`\n * @returns An array wrapper; each element’s shape follows `Opts`.\n */\n async getAppsForOrg<Opts extends AppDataOpts>(\n orgId: string,\n opts?: Opts,\n ): Promise<InstantAPIListAppsResponse<Opts>> {\n return this.withRetry(getAppsForOrg, [\n this.#apiURI,\n this.token(),\n orgId,\n opts,\n ]);\n }\n\n /**\n * Gets the schema for an app by its id.\n *\n * ```ts\n * const { schema } = await api.getSchema('MY_APP_ID');\n * ```\n *\n * @param appId -- UUID of the app\n */\n async getSchema(appId: string): Promise<InstantAPIGetAppSchemaResponse> {\n return this.withRetry(getAppSchema, [this.#apiURI, this.token(), appId]);\n }\n\n /**\n * Gets the permissions for an app by its id.\n *\n * ```ts\n * const { perms } = await api.getPerms('MY_APP_ID');\n * ```\n *\n * @param appId -- UUID of the app\n */\n async getPerms(appId: string): Promise<InstantAPIGetAppPermsResponse> {\n return this.withRetry(getAppPerms, [this.#apiURI, this.token(), appId]);\n }\n\n /**\n * Create a new app.\n *\n * The app will be placed in the authenticated user's account\n * if no orgId is provided.\n *\n * Optionally set permissions and schema.\n *\n * ```ts\n * const { app } = await api.createApp({\n * title: 'My new app',\n * // Optional permissions\n * perms: { $default: { allow: { $default: 'false' } } },\n * // Optional schema\n * schema: i.schema({\n * entities: { books: i.entity({ title: i.string() }) },\n * }),\n * });\n * ```\n *\n * @param fields\n * @param fields.title -- Title for app\n * @param fields.schema -- Optional schema for the app\n * @param fields.perms -- Optional permissions for the app\n * @param fields.orgId -- Optional id of the org that the app will be placed in\n */\n async createApp(\n fields: InstantAPICreateAppBody,\n ): Promise<InstantAPICreateAppResponse> {\n return this.withRetry(createApp, [this.#apiURI, this.token(), fields]);\n }\n\n /**\n * Create a new temporary app.\n *\n * Optionally set permissions and schema.\n *\n * ```ts\n * const { app } = await api.createTemporaryApp({\n * title: 'My new app',\n * // Optional permissions\n * perms: { $default: { allow: { $default: 'false' } } },\n * // Optional schema\n * schema: i.schema({\n * entities: { books: i.entity({ title: i.string() }) },\n * }),\n * });\n * ```\n *\n * @param fields\n * @param fields.title -- Title for app\n * @param fields.schema -- Optional schema for the app\n * @param fields.perms -- Optional permissions for the app\n */\n async createTemporaryApp(fields: InstantAPICreateTemporaryAppBody) {\n return createTemporaryApp(this.#apiURI, fields);\n }\n\n /**\n * Update the title of an app by its id.\n *\n * ```ts\n * const { app } = await api.updateApp('MY_APP_ID', {\n * title: 'New title',\n * });\n * ```\n *\n * @param appId -- UUID of the app\n * @param fields.title -- New title for the app\n */\n async updateApp(\n appId: string,\n fields: InstantAPIUpdateAppBody,\n ): Promise<InstantAPIUpdateAppResponse> {\n return this.withRetry(updateApp, [\n this.#apiURI,\n this.token(),\n appId,\n fields,\n ]);\n }\n\n /**\n * Delete an app by its id.\n *\n * ```ts\n * const { app } = await api.deleteApp('MY_APP_ID');\n * ```\n *\n * @param appId -- UUID of the app\n */\n async deleteApp(appId: string): Promise<InstantAPIDeleteAppResponse> {\n return this.withRetry(deleteApp, [this.#apiURI, this.token(), appId]);\n }\n\n /**\n * Dry-run a **schema push** and receive a _plan_ of steps the server would\n * execute.\n *\n * ```ts\n * const { steps } = await api.planSchemaPush(appId, body);\n * ```\n */\n async planSchemaPush(\n appId: string,\n body: InstantAPISchemaPushBody,\n ): Promise<InstantAPIPlanSchemaPushResponse> {\n return this.withRetry(planSchemaPush, [\n this.#apiURI,\n this.token(),\n appId,\n body,\n ]);\n }\n\n /**\n * Execute a **schema push**. The server returns a long-running job\n * represented as a {@link ProgressPromise}: you can both `await` the final\n * result **or** subscribe to intermediate status updates.\n *\n * ```ts\n * // 1) Subscribe to progress\n * const schema = i.schema({\n * entities: {\n * books: i.entity({\n * title: i.string().indexed(),\n * }),\n * },\n * });\n * const job = api.schemaPush(appId, { schema: schema });\n * job\n * .then(({ summary }) => console.log('done!', summary))\n * .catch((e) => console.error(e));\n * job.subscribe({\n * next: (status) => renderProgress(status),\n * });\n *\n * // 2) Or just await it\n * const result = await api.schemaPush(appId, { schema: schema });\n * ```\n */\n schemaPush(\n appId: string,\n body: InstantAPISchemaPushBody,\n ): ProgressPromise<InProgressStepsSummary, InstantAPISchemaPushResponse> {\n if (!this.#auth) {\n throw new PlatformApiMissingAuthError();\n }\n return new ProgressPromise(async (progress, resolve, reject) => {\n // It's tricky to add withRetry to the background process that fetches the jobs,\n // so we'll just refresh the token at the start.\n if (this.canRefreshToken()) {\n try {\n await this.refreshToken();\n } catch (_e) {}\n }\n schemaPush(this.#apiURI, this.token(), appId, body).subscribe({\n complete(v) {\n resolve(v);\n },\n error(e) {\n reject(e);\n },\n next(v) {\n progress(v);\n },\n });\n });\n }\n\n /**\n * Update permission rules for an app by its id.\n *\n * Completely replaces the current rule set.\n *\n * ```ts\n * const { steps } = await api.pushPerms(appId, {\n * perms: {\n * $default: { allow: { $default: 'false' } },\n * books: { allow: { view: 'true', $default: 'false' } },\n * },\n * });\n * ```\n */\n async pushPerms(\n appId: string,\n body: InstantAPIPushPermsBody,\n ): Promise<InstantAPIPushPermsResponse> {\n if (!this.#auth) {\n throw new PlatformApiMissingAuthError();\n }\n return this.withRetry(pushPerms, [this.#apiURI, this.token(), appId, body]);\n }\n\n async tokenInfo(): Promise<InstantAPITokenInfoResponse> {\n if (!this.#auth) {\n throw new PlatformApiMissingAuthError();\n }\n return this.withRetry(tokenInfo, [this.#apiURI, this.token()]);\n }\n}\n"]}
|
|
@@ -25,16 +25,28 @@ exports.attrDefToNewAttrTx = attrDefToNewAttrTx;
|
|
|
25
25
|
const linkDefToNewAttrTx = (link) => {
|
|
26
26
|
const relationship = `${link.forward.has}-${link.reverse.has}`;
|
|
27
27
|
const uniqueAndCardinality = relationships_ts_1.relationshipConstraints[relationship];
|
|
28
|
-
return
|
|
28
|
+
return {
|
|
29
|
+
'checked-data-type': null,
|
|
30
|
+
'index?': false,
|
|
31
|
+
...uniqueAndCardinality,
|
|
32
|
+
'required?': false,
|
|
33
|
+
identifier: {
|
|
29
34
|
attrName: link.forward.label,
|
|
30
35
|
namespace: link.forward.on,
|
|
31
|
-
},
|
|
36
|
+
},
|
|
37
|
+
'value-type': 'ref',
|
|
38
|
+
type: 'add-attr',
|
|
39
|
+
'forward-identity': {
|
|
32
40
|
attrName: link.forward.label,
|
|
33
41
|
namespace: link.forward.on,
|
|
34
|
-
},
|
|
42
|
+
},
|
|
43
|
+
'on-delete': link.forward.onDelete,
|
|
44
|
+
'on-delete-reverse': link.reverse.onDelete,
|
|
45
|
+
'reverse-identity': {
|
|
35
46
|
attrName: link.reverse.label,
|
|
36
47
|
namespace: link.reverse.on,
|
|
37
|
-
}
|
|
48
|
+
},
|
|
49
|
+
};
|
|
38
50
|
};
|
|
39
51
|
exports.linkDefToNewAttrTx = linkDefToNewAttrTx;
|
|
40
52
|
//# sourceMappingURL=migrationUtils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrationUtils.js","sourceRoot":"","sources":["../../src/migrationUtils.ts"],"names":[],"mappings":";;;AACA,yDAAgF;AAEzE,MAAM,kBAAkB,GAAG,CAChC,YAAqB,EACrB,UAAkB,EAClB,WAAmB,EACN,EAAE;IACf,OAAO;QACL,IAAI,EAAE,UAAU;QAChB,SAAS,EAAE,YAAY,CAAC,MAAM,CAAC,MAAM;QACrC,YAAY,EAAE,MAAM;QACpB,WAAW,EAAE,KAAK;QAClB,UAAU,EAAE;YACV,SAAS,EAAE,UAAU;YACrB,QAAQ,EAAE,WAAW;SACtB;QACD,WAAW,EAAE,YAAY,CAAC,QAAQ;QAClC,kBAAkB,EAAE;YAClB,QAAQ,EAAE,WAAW;YACrB,SAAS,EAAE,UAAU;SACtB;QACD,QAAQ,EAAE,YAAY,CAAC,MAAM,CAAC,OAAO;QACrC,mBAAmB,EACjB,YAAY,CAAC,SAAS,KAAK,MAAM,CAAC,CAAC,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI;KACpE,CAAC;AACJ,CAAC,CAAC;AAvBW,QAAA,kBAAkB,sBAuB7B;AAEK,MAAM,kBAAkB,GAAG,CAAC,IAAa,EAAe,EAAE;IAC/D,MAAM,YAAY,GAChB,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,EAAuB,CAAC;IACjE,MAAM,oBAAoB,GAAG,0CAAuB,CAAC,YAAY,CAAC,CAAC;IAEnE,
|
|
1
|
+
{"version":3,"file":"migrationUtils.js","sourceRoot":"","sources":["../../src/migrationUtils.ts"],"names":[],"mappings":";;;AACA,yDAAgF;AAEzE,MAAM,kBAAkB,GAAG,CAChC,YAAqB,EACrB,UAAkB,EAClB,WAAmB,EACN,EAAE;IACf,OAAO;QACL,IAAI,EAAE,UAAU;QAChB,SAAS,EAAE,YAAY,CAAC,MAAM,CAAC,MAAM;QACrC,YAAY,EAAE,MAAM;QACpB,WAAW,EAAE,KAAK;QAClB,UAAU,EAAE;YACV,SAAS,EAAE,UAAU;YACrB,QAAQ,EAAE,W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AA,kBAAkB,sBA2B7B","sourcesContent":["import { AnyBlob, AnyLink, MigrationTx } from './migrations.ts';\nimport { relationshipConstraints, RelationshipKinds } from './relationships.ts';\n\nexport const attrDefToNewAttrTx = (\n attrInSchema: AnyBlob,\n entityName: string,\n createdName: string,\n): MigrationTx => {\n return {\n type: 'add-attr',\n 'unique?': attrInSchema.config.unique,\n 'value-type': 'blob',\n cardinality: 'one',\n identifier: {\n namespace: entityName,\n attrName: createdName,\n },\n 'required?': attrInSchema.required,\n 'forward-identity': {\n attrName: createdName,\n namespace: entityName,\n },\n 'index?': attrInSchema.config.indexed,\n 'checked-data-type':\n attrInSchema.valueType !== 'json' ? attrInSchema.valueType : null,\n };\n};\n\nexport const linkDefToNewAttrTx = (link: AnyLink): MigrationTx => {\n const relationship =\n `${link.forward.has}-${link.reverse.has}` as RelationshipKinds;\n const uniqueAndCardinality = relationshipConstraints[relationship];\n\n return {\n 'checked-data-type': null,\n 'index?': false,\n ...uniqueAndCardinality,\n 'required?': false,\n identifier: {\n attrName: link.forward.label,\n namespace: link.forward.on,\n },\n 'value-type': 'ref',\n type: 'add-attr',\n 'forward-identity': {\n attrName: link.forward.label,\n namespace: link.forward.on,\n },\n 'on-delete': link.forward.onDelete,\n 'on-delete-reverse': link.reverse.onDelete,\n 'reverse-identity': {\n attrName: link.reverse.label,\n namespace: link.reverse.on,\n },\n };\n};\n"]}
|
|
@@ -1,13 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
3
|
exports.isRenamePromptItem = exports.compareLinks = exports.compareBlobs = exports.diffSchemas = exports.convertTxSteps = void 0;
|
|
13
4
|
const core_1 = require("@instantdb/core");
|
|
@@ -146,8 +137,7 @@ const CONVERTERS = {
|
|
|
146
137
|
},
|
|
147
138
|
};
|
|
148
139
|
function isSystemCatalogAttr(systemCatalogIdentNames, entityName, attrName) {
|
|
149
|
-
|
|
150
|
-
return !!((_a = systemCatalogIdentNames[entityName]) === null || _a === void 0 ? void 0 : _a.has(attrName));
|
|
140
|
+
return !!systemCatalogIdentNames[entityName]?.has(attrName);
|
|
151
141
|
}
|
|
152
142
|
const convertTxSteps = (txs, existingAttrs) => {
|
|
153
143
|
if (!existingAttrs) {
|
|
@@ -170,8 +160,7 @@ const convertTxSteps = (txs, existingAttrs) => {
|
|
|
170
160
|
return result;
|
|
171
161
|
};
|
|
172
162
|
exports.convertTxSteps = convertTxSteps;
|
|
173
|
-
const diffSchemas = (oldSchema, newSchema, resolveFn, systemCatalogIdentNames) =>
|
|
174
|
-
var _a, _b;
|
|
163
|
+
const diffSchemas = async (oldSchema, newSchema, resolveFn, systemCatalogIdentNames) => {
|
|
175
164
|
const transactions = [];
|
|
176
165
|
const oldEntities = oldSchema.entities;
|
|
177
166
|
const newEntities = newSchema.entities;
|
|
@@ -244,7 +233,7 @@ const diffSchemas = (oldSchema, newSchema, resolveFn, systemCatalogIdentNames) =
|
|
|
244
233
|
const newEntityHasIt = Object.keys(newEntities[entityName].attrs).includes(field);
|
|
245
234
|
return !newEntityHasIt;
|
|
246
235
|
});
|
|
247
|
-
const resolved =
|
|
236
|
+
const resolved = await resolveRenames(addedFields, removedFields, resolveFn, {
|
|
248
237
|
type: 'attribute',
|
|
249
238
|
entityName: entityName,
|
|
250
239
|
});
|
|
@@ -334,10 +323,10 @@ const diffSchemas = (oldSchema, newSchema, resolveFn, systemCatalogIdentNames) =
|
|
|
334
323
|
attrName: oldLink.forward.label,
|
|
335
324
|
}, oldLink, newLink));
|
|
336
325
|
});
|
|
337
|
-
const resolved =
|
|
326
|
+
const resolved = await resolveRenames(addedIdentities, removedIdentities, resolveFn, {
|
|
338
327
|
type: 'link',
|
|
339
|
-
forwardEntityName:
|
|
340
|
-
reverseEntityName:
|
|
328
|
+
forwardEntityName: oldLinksInGroup[0]?.forward.on,
|
|
329
|
+
reverseEntityName: oldLinksInGroup[0]?.reverse.on,
|
|
341
330
|
});
|
|
342
331
|
resolved.deleted.forEach((identity) => {
|
|
343
332
|
const link = oldLinksInGroup.find((l) => createLinkIdentity(l) === identity);
|
|
@@ -388,7 +377,7 @@ const diffSchemas = (oldSchema, newSchema, resolveFn, systemCatalogIdentNames) =
|
|
|
388
377
|
});
|
|
389
378
|
}
|
|
390
379
|
return transactions;
|
|
391
|
-
}
|
|
380
|
+
};
|
|
392
381
|
exports.diffSchemas = diffSchemas;
|
|
393
382
|
const compareBlobs = (identity, oldBlob, newBlob) => {
|
|
394
383
|
const results = [];
|
|
@@ -475,7 +464,7 @@ const isRenamePromptItem = (item) => {
|
|
|
475
464
|
return false;
|
|
476
465
|
};
|
|
477
466
|
exports.isRenamePromptItem = isRenamePromptItem;
|
|
478
|
-
const resolveRenames = (newItems, missingItems, resolveFn, extraInfo) =>
|
|
467
|
+
const resolveRenames = async (newItems, missingItems, resolveFn, extraInfo) => {
|
|
479
468
|
if (missingItems.length === 0 || newItems.length === 0) {
|
|
480
469
|
return {
|
|
481
470
|
created: newItems,
|
|
@@ -492,7 +481,7 @@ const resolveRenames = (newItems, missingItems, resolveFn, extraInfo) => __await
|
|
|
492
481
|
return { from: it, to: created };
|
|
493
482
|
});
|
|
494
483
|
const promptData = [created, ...renames];
|
|
495
|
-
const data =
|
|
484
|
+
const data = await resolveFn(created, promptData, extraInfo);
|
|
496
485
|
if ((0, exports.isRenamePromptItem)(data)) {
|
|
497
486
|
if (data.from !== data.to) {
|
|
498
487
|
result.renamed.push(data);
|
|
@@ -507,5 +496,5 @@ const resolveRenames = (newItems, missingItems, resolveFn, extraInfo) => __await
|
|
|
507
496
|
} while (index < newItems.length);
|
|
508
497
|
result.deleted.push(...leftMissing);
|
|
509
498
|
return result;
|
|
510
|
-
}
|
|
499
|
+
};
|
|
511
500
|
//# sourceMappingURL=migrations.js.map
|