@instantdb/platform 0.22.141 → 0.22.142-experimental.button-on-admin.22246088935.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,17 @@
1
1
 
2
- > @instantdb/platform@0.22.141 build /home/runner/work/instant/instant/client/packages/platform
2
+ > @instantdb/platform@0.22.142-experimental.button-on-admin.22246088935.1 build /home/runner/work/instant/instant/client/packages/platform
3
3
  > rm -rf dist; npm run build:tshy && npm run build:standalone && npm run check-exports
4
4
 
5
5
  npm warn Unknown env config "verify-deps-before-run". This will stop working in the next major version of npm.
6
6
  npm warn Unknown user config "always-auth". This will stop working in the next major version of npm.
7
7
 
8
- > @instantdb/platform@0.22.141 build:tshy
8
+ > @instantdb/platform@0.22.142-experimental.button-on-admin.22246088935.1 build:tshy
9
9
  > tshy
10
10
 
11
11
  npm warn Unknown env config "verify-deps-before-run". This will stop working in the next major version of npm.
12
12
  npm warn Unknown user config "always-auth". This will stop working in the next major version of npm.
13
13
 
14
- > @instantdb/platform@0.22.141 build:standalone
14
+ > @instantdb/platform@0.22.142-experimental.button-on-admin.22246088935.1 build:standalone
15
15
  > vite build
16
16
 
17
17
  vite v5.4.14 building for production...
@@ -19,17 +19,17 @@ transforming...
19
19
  ✓ 80 modules transformed.
20
20
  rendering chunks...
21
21
  computing gzip size...
22
- dist/standalone/index.umd.cjs 353.83 kB │ gzip: 96.24 kB
23
- dist/standalone/index.js 462.04 kB │ gzip: 108.59 kB
24
- ✓ built in 3.06s
22
+ dist/standalone/index.umd.cjs 353.87 kB │ gzip: 96.29 kB
23
+ dist/standalone/index.js 462.08 kB │ gzip: 108.62 kB
24
+ ✓ built in 3.07s
25
25
  npm warn Unknown env config "verify-deps-before-run". This will stop working in the next major version of npm.
26
26
  npm warn Unknown user config "always-auth". This will stop working in the next major version of npm.
27
27
 
28
- > @instantdb/platform@0.22.141 check-exports
28
+ > @instantdb/platform@0.22.142-experimental.button-on-admin.22246088935.1 check-exports
29
29
  > attw --pack .
30
30
 
31
31
 
32
- @instantdb/platform v0.22.141
32
+ @instantdb/platform v0.22.142-experimental.button-on-admin.22246088935.1
33
33
 
34
34
  Build tools:
35
35
  - @arethetypeswrong/cli@^0.17.4
@@ -364,7 +364,7 @@ function translatePlanStep(apiStep, currentAttrs) {
364
364
  case 'remove-unique': {
365
365
  return {
366
366
  type: 'remove-unique',
367
- friendlyDescription: `Remove uniqueness constarint from ${(0, schema_ts_1.identName)(stepParams['forward-identity'])}.`,
367
+ friendlyDescription: `Remove uniqueness constraint from ${(0, schema_ts_1.identName)(stepParams['forward-identity'])}.`,
368
368
  attrId: stepParams['attr-id'],
369
369
  forwardIdentity: stepParams['forward-identity'],
370
370
  };
@@ -418,7 +418,7 @@ function translatePlanStep(apiStep, currentAttrs) {
418
418
  default: {
419
419
  // Get a type error if we ignore a case
420
420
  const unknownType = stepType;
421
- throw new Error(`Uknown schema operation ${unknownType}.`);
421
+ throw new Error(`Unknown schema operation ${unknownType}.`);
422
422
  }
423
423
  }
424
424
  }
@@ -1 +1 @@
1
- {"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/api.ts"],"names":[],"mappings":";;;;;;AAobA,4CAaC;AAED,kEAgBC;AAmZD,gDAKC;AA32BD,0CAcyB;AACzB,8DAAmC;AACnC,2CAUqB;AACrB,6DAAuD;AACvD,uCAKmB;AACnB,qDAAwD;AACxD,mDAKyB;AAgRzB,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;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AC;gBACjB,CAAC;gBACD,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,KAAK,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,SAAS,CAAC;oBACxD,QAAQ,CAAC,CAAC;wBACR,OAAO,CAAC,CAAC,CAAC,CAAC;oBACb,CAAC;oBACD,KAAK,CAAC,CAAC;wBACL,MAAM,CAAC,CAAC,CAAC,CAAC;oBACZ,CAAC;oBACD,IAAI,CAAC,CAAC;wBACJ,QAAQ,CAAC,CAAC,CAAC,CAAC;oBACd,CAAC;iBACF,CAAC,CAAC;YACL,CAAC;YAAC,OAAO,CAAC,EAAE,CAAC;gBACX,MAAM,CAAC,CAAU,CAAC,CAAC;YACrB,CAAC;QACH,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;AA7ZD,kCA6ZC","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 collectSystemCatalogIdentNames,\n identName,\n InstantAPIPlatformSchema,\n InstantAPISchemaPlanStep,\n InstantAPISchemaPushStep,\n validateSchema,\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';\nimport {\n buildAutoRenameSelector,\n convertTxSteps,\n diffSchemas,\n RenameCommand,\n} from './migrations.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 | {\n schema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;\n overwrite?: false;\n }\n | {\n schema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;\n overwrite: true;\n renames?: RenameCommand[];\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 apiSchemaToAttrs(\n apiSchema: InstantAPIPlatformSchema,\n): InstantDBAttr[] {\n let res: InstantDBAttr[] = [];\n for (const [_, attrs] of sortedEntries(apiSchema.blobs)) {\n Object.values(attrs).forEach((a) => {\n res.push(a);\n });\n }\n for (const [_, a] of sortedEntries(apiSchema.refs)) {\n res.push(a);\n }\n return res;\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 getAppAPISchema(\n apiURI: string,\n token: string,\n appId: string,\n): Promise<InstantAPIPlatformSchema> {\n const { schema: apiSchema } = await jsonFetch<{\n schema: InstantAPIPlatformSchema;\n }>(`${apiURI}/superadmin/apps/${appId}/schema`, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n });\n return apiSchema;\n}\n\nasync function getAppSchema(\n apiURI: string,\n token: string,\n appId: string,\n): Promise<InstantAPIGetAppSchemaResponse> {\n const apiSchema = await getAppAPISchema(apiURI, token, appId);\n return { schema: apiSchemaToInstantSchemaDef(apiSchema) };\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(\n apiStep: PlanStep,\n currentAttrs: InstantDBAttr[],\n): 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 case 'delete-attr': {\n const attrId = stepParams;\n const attr = currentAttrs.find((a) => a.id === attrId);\n const friendlyName = attr ? identName(attr['forward-identity']) : attrId;\n return {\n type: 'delete-attr',\n attrId: stepParams,\n friendlyDescription: `Delete attribute ${friendlyName}.`,\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 currentAttrs: InstantDBAttr[],\n): InstantAPISchemaPlanStep[] {\n return apiSteps.map((step) => translatePlanStep(step, currentAttrs));\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 currentAttrs: InstantDBAttr[],\n): PushObjOf<S> {\n const [stepType, stepParams] = apiStep;\n if (\n stepType === 'add-attr' ||\n stepType === 'update-attr' ||\n stepType === 'delete-attr'\n ) {\n const planStep = translatePlanStep(apiStep, currentAttrs);\n if (\n planStep.type !== 'add-attr' &&\n planStep.type !== 'update-attr' &&\n planStep.type !== 'delete-attr'\n ) {\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, currentAttrs);\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 currentAttrs: InstantDBAttr[],\n): InstantAPISchemaPushStep[] {\n return apiSteps.map((step) => translatePushStep(step, jobs, currentAttrs));\n}\n\nfunction shouldOverwrite(body: InstantAPISchemaPushBody) {\n if ('renames' in body && !body.overwrite) {\n throw new Error(\n 'If you pass in `renames`, you _must_ pass in `overwrite: true`',\n );\n }\n return !!body.overwrite;\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 const currentAttrs = resp['current-attrs'];\n return {\n newSchema: apiSchemaToInstantSchemaDef(resp['new-schema']),\n currentSchema: apiSchemaToInstantSchemaDef(resp['current-schema']),\n steps: translatePlanSteps(resp['steps'], currentAttrs),\n };\n}\n\nasync function planSchemaPushOverwriteInternal(\n apiURI: string,\n token: string,\n appId: string,\n body: InstantAPISchemaPushBody,\n) {\n const apiSchema = await getAppAPISchema(apiURI, token, appId);\n\n const currentSchema = apiSchemaToInstantSchemaDef(apiSchema, {\n disableTypeInference: true,\n });\n const currentAttrs = apiSchemaToAttrs(apiSchema);\n\n const systemCatalogIdentNames = collectSystemCatalogIdentNames(currentAttrs);\n\n const newSchema = body.schema;\n\n validateSchema(newSchema, systemCatalogIdentNames);\n\n const renames = ('renames' in body ? body.renames : null) || [];\n\n const renameSelector = buildAutoRenameSelector(renames);\n\n const diffResult = await diffSchemas(\n currentSchema,\n newSchema,\n renameSelector,\n systemCatalogIdentNames,\n );\n\n const txSteps = convertTxSteps(diffResult, currentAttrs);\n\n return {\n currentSchema,\n currentAttrs,\n txSteps: txSteps,\n steps: translatePlanSteps(txSteps, currentAttrs),\n };\n}\n\nasync function planSchemaPushOverwrite(\n apiURI: string,\n token: string,\n appId: string,\n body: InstantAPISchemaPushBody,\n): Promise<InstantAPIPlanSchemaPushResponse> {\n const { currentSchema, steps } = await planSchemaPushOverwriteInternal(\n apiURI,\n token,\n appId,\n body,\n );\n\n return {\n newSchema: body.schema,\n currentSchema: currentSchema,\n steps: steps,\n };\n}\n\nfunction allJobsComplete(jobs: IndexingJobJSON[]): boolean {\n if (jobs.length === 0) {\n return true;\n }\n return jobs.every(\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 lastJobs = 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 currentAPISchema = await getAppAPISchema(apiURI, token, appId);\n const currentAttrs = apiSchemaToAttrs(currentAPISchema);\n\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(\n stepSummary(translatePushSteps(resp.steps, jobs, currentAttrs)),\n );\n },\n );\n\n const schemaRes = await getAppSchema(apiURI, token, appId);\n resolve({\n newSchema: schemaRes.schema,\n steps: translatePushSteps(resp.steps, jobs, currentAttrs),\n summary: stepSummary(\n translatePushSteps(resp.steps, jobs, currentAttrs),\n ),\n });\n } catch (e) {\n reject(e as Error);\n }\n });\n}\n\nfunction schemaPushOverwrite(\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 { currentAttrs, txSteps } = await planSchemaPushOverwriteInternal(\n apiURI,\n token,\n appId,\n body,\n );\n\n const resp = await jsonFetch<SchemaPushResponseJSON>(\n `${apiURI}/dash/apps/${appId}/schema/steps/apply`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n steps: txSteps,\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(\n stepSummary(translatePushSteps(resp.steps, jobs, currentAttrs)),\n );\n },\n );\n\n const schemaRes = await getAppSchema(apiURI, token, appId);\n resolve({\n newSchema: schemaRes.schema,\n steps: translatePushSteps(resp.steps, jobs, currentAttrs),\n summary: stepSummary(\n translatePushSteps(resp.steps, jobs, currentAttrs),\n ),\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 const useOverwrite = shouldOverwrite(body);\n return this.withRetry(\n useOverwrite ? planSchemaPushOverwrite : planSchemaPush,\n [this.#apiURI, this.token(), appId, 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, { overwrite: true, 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 try {\n const useOverwrite = shouldOverwrite(body);\n const pushFn = useOverwrite ? schemaPushOverwrite : schemaPush;\n\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 pushFn(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 } catch (e) {\n reject(e as Error);\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":";;;;;;AAobA,4CAaC;AAED,kEAgBC;AAmZD,gDAKC;AA32BD,0CAcyB;AACzB,8DAAmC;AACnC,2CAUqB;AACrB,6DAAuD;AACvD,uCAKmB;AACnB,qDAAwD;AACxD,mDAKyB;AAgRzB,KAAK,UAAU,SAAS,CACtB,KAAkB,EAClB,IAA6B;IAE7B,MAAM,OAAO,GAAG;QACd,GAAG,CAAC,IAAI,EAAE,OAAO,IAAI,EAAE,CAAC;QACxB,0BA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E,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC;IACjE,CAAC;CACF;AA7ZD,kCA6ZC","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 collectSystemCatalogIdentNames,\n identName,\n InstantAPIPlatformSchema,\n InstantAPISchemaPlanStep,\n InstantAPISchemaPushStep,\n validateSchema,\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';\nimport {\n buildAutoRenameSelector,\n convertTxSteps,\n diffSchemas,\n RenameCommand,\n} from './migrations.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 | {\n schema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;\n overwrite?: false;\n }\n | {\n schema: InstantSchemaDef<EntitiesDef, LinksDef<EntitiesDef>, RoomsDef>;\n overwrite: true;\n renames?: RenameCommand[];\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 apiSchemaToAttrs(\n apiSchema: InstantAPIPlatformSchema,\n): InstantDBAttr[] {\n let res: InstantDBAttr[] = [];\n for (const [_, attrs] of sortedEntries(apiSchema.blobs)) {\n Object.values(attrs).forEach((a) => {\n res.push(a);\n });\n }\n for (const [_, a] of sortedEntries(apiSchema.refs)) {\n res.push(a);\n }\n return res;\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 getAppAPISchema(\n apiURI: string,\n token: string,\n appId: string,\n): Promise<InstantAPIPlatformSchema> {\n const { schema: apiSchema } = await jsonFetch<{\n schema: InstantAPIPlatformSchema;\n }>(`${apiURI}/superadmin/apps/${appId}/schema`, {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n },\n });\n return apiSchema;\n}\n\nasync function getAppSchema(\n apiURI: string,\n token: string,\n appId: string,\n): Promise<InstantAPIGetAppSchemaResponse> {\n const apiSchema = await getAppAPISchema(apiURI, token, appId);\n return { schema: apiSchemaToInstantSchemaDef(apiSchema) };\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(\n apiStep: PlanStep,\n currentAttrs: InstantDBAttr[],\n): 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 constraint 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 case 'delete-attr': {\n const attrId = stepParams;\n const attr = currentAttrs.find((a) => a.id === attrId);\n const friendlyName = attr ? identName(attr['forward-identity']) : attrId;\n return {\n type: 'delete-attr',\n attrId: stepParams,\n friendlyDescription: `Delete attribute ${friendlyName}.`,\n };\n }\n default: {\n // Get a type error if we ignore a case\n const unknownType: never = stepType;\n throw new Error(`Unknown schema operation ${unknownType}.`);\n }\n }\n}\n\nexport function translatePlanSteps(\n apiSteps: PlanStep[],\n currentAttrs: InstantDBAttr[],\n): InstantAPISchemaPlanStep[] {\n return apiSteps.map((step) => translatePlanStep(step, currentAttrs));\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 currentAttrs: InstantDBAttr[],\n): PushObjOf<S> {\n const [stepType, stepParams] = apiStep;\n if (\n stepType === 'add-attr' ||\n stepType === 'update-attr' ||\n stepType === 'delete-attr'\n ) {\n const planStep = translatePlanStep(apiStep, currentAttrs);\n if (\n planStep.type !== 'add-attr' &&\n planStep.type !== 'update-attr' &&\n planStep.type !== 'delete-attr'\n ) {\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, currentAttrs);\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 currentAttrs: InstantDBAttr[],\n): InstantAPISchemaPushStep[] {\n return apiSteps.map((step) => translatePushStep(step, jobs, currentAttrs));\n}\n\nfunction shouldOverwrite(body: InstantAPISchemaPushBody) {\n if ('renames' in body && !body.overwrite) {\n throw new Error(\n 'If you pass in `renames`, you _must_ pass in `overwrite: true`',\n );\n }\n return !!body.overwrite;\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 const currentAttrs = resp['current-attrs'];\n return {\n newSchema: apiSchemaToInstantSchemaDef(resp['new-schema']),\n currentSchema: apiSchemaToInstantSchemaDef(resp['current-schema']),\n steps: translatePlanSteps(resp['steps'], currentAttrs),\n };\n}\n\nasync function planSchemaPushOverwriteInternal(\n apiURI: string,\n token: string,\n appId: string,\n body: InstantAPISchemaPushBody,\n) {\n const apiSchema = await getAppAPISchema(apiURI, token, appId);\n\n const currentSchema = apiSchemaToInstantSchemaDef(apiSchema, {\n disableTypeInference: true,\n });\n const currentAttrs = apiSchemaToAttrs(apiSchema);\n\n const systemCatalogIdentNames = collectSystemCatalogIdentNames(currentAttrs);\n\n const newSchema = body.schema;\n\n validateSchema(newSchema, systemCatalogIdentNames);\n\n const renames = ('renames' in body ? body.renames : null) || [];\n\n const renameSelector = buildAutoRenameSelector(renames);\n\n const diffResult = await diffSchemas(\n currentSchema,\n newSchema,\n renameSelector,\n systemCatalogIdentNames,\n );\n\n const txSteps = convertTxSteps(diffResult, currentAttrs);\n\n return {\n currentSchema,\n currentAttrs,\n txSteps: txSteps,\n steps: translatePlanSteps(txSteps, currentAttrs),\n };\n}\n\nasync function planSchemaPushOverwrite(\n apiURI: string,\n token: string,\n appId: string,\n body: InstantAPISchemaPushBody,\n): Promise<InstantAPIPlanSchemaPushResponse> {\n const { currentSchema, steps } = await planSchemaPushOverwriteInternal(\n apiURI,\n token,\n appId,\n body,\n );\n\n return {\n newSchema: body.schema,\n currentSchema: currentSchema,\n steps: steps,\n };\n}\n\nfunction allJobsComplete(jobs: IndexingJobJSON[]): boolean {\n if (jobs.length === 0) {\n return true;\n }\n return jobs.every(\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 lastJobs = 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 currentAPISchema = await getAppAPISchema(apiURI, token, appId);\n const currentAttrs = apiSchemaToAttrs(currentAPISchema);\n\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(\n stepSummary(translatePushSteps(resp.steps, jobs, currentAttrs)),\n );\n },\n );\n\n const schemaRes = await getAppSchema(apiURI, token, appId);\n resolve({\n newSchema: schemaRes.schema,\n steps: translatePushSteps(resp.steps, jobs, currentAttrs),\n summary: stepSummary(\n translatePushSteps(resp.steps, jobs, currentAttrs),\n ),\n });\n } catch (e) {\n reject(e as Error);\n }\n });\n}\n\nfunction schemaPushOverwrite(\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 { currentAttrs, txSteps } = await planSchemaPushOverwriteInternal(\n apiURI,\n token,\n appId,\n body,\n );\n\n const resp = await jsonFetch<SchemaPushResponseJSON>(\n `${apiURI}/dash/apps/${appId}/schema/steps/apply`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n },\n body: JSON.stringify({\n steps: txSteps,\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(\n stepSummary(translatePushSteps(resp.steps, jobs, currentAttrs)),\n );\n },\n );\n\n const schemaRes = await getAppSchema(apiURI, token, appId);\n resolve({\n newSchema: schemaRes.schema,\n steps: translatePushSteps(resp.steps, jobs, currentAttrs),\n summary: stepSummary(\n translatePushSteps(resp.steps, jobs, currentAttrs),\n ),\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 const useOverwrite = shouldOverwrite(body);\n return this.withRetry(\n useOverwrite ? planSchemaPushOverwrite : planSchemaPush,\n [this.#apiURI, this.token(), appId, 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, { overwrite: true, 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 try {\n const useOverwrite = shouldOverwrite(body);\n const pushFn = useOverwrite ? schemaPushOverwrite : schemaPush;\n\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 pushFn(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 } catch (e) {\n reject(e as Error);\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"]}
package/dist/esm/api.js CHANGED
@@ -355,7 +355,7 @@ function translatePlanStep(apiStep, currentAttrs) {
355
355
  case 'remove-unique': {
356
356
  return {
357
357
  type: 'remove-unique',
358
- friendlyDescription: `Remove uniqueness constarint from ${identName(stepParams['forward-identity'])}.`,
358
+ friendlyDescription: `Remove uniqueness constraint from ${identName(stepParams['forward-identity'])}.`,
359
359
  attrId: stepParams['attr-id'],
360
360
  forwardIdentity: stepParams['forward-identity'],
361
361
  };
@@ -409,7 +409,7 @@ function translatePlanStep(apiStep, currentAttrs) {
409
409
  default: {
410
410
  // Get a type error if we ignore a case
411
411
  const unknownType = stepType;
412
- throw new Error(`Uknown schema operation ${unknownType}.`);
412
+ throw new Error(`Unknown schema operation ${unknownType}.`);
413
413
  }
414
414
  }
415
415
  }