@instantdb/core 0.22.88-experimental.drewh-ssr.20251523170.1 → 0.22.88-experimental.split-store.20252005043.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/__tests__/src/Reactor.test.js +18 -11
- package/__tests__/src/{datalog.test.js → datalog.test.ts} +17 -5
- package/__tests__/src/{instaml.test.js → instaml.test.ts} +183 -119
- package/__tests__/src/instaql.bench.ts +34 -0
- package/__tests__/src/{instaql.test.js → instaql.test.ts} +342 -455
- package/__tests__/src/instaqlInference.test.js +13 -9
- package/__tests__/src/{store.test.js → store.test.ts} +215 -212
- package/dist/commonjs/Reactor.d.ts +24 -19
- package/dist/commonjs/Reactor.d.ts.map +1 -1
- package/dist/commonjs/Reactor.js +112 -106
- package/dist/commonjs/Reactor.js.map +1 -1
- package/dist/commonjs/SyncTable.d.ts +4 -1
- package/dist/commonjs/SyncTable.d.ts.map +1 -1
- package/dist/commonjs/SyncTable.js +35 -37
- package/dist/commonjs/SyncTable.js.map +1 -1
- package/dist/commonjs/index.d.ts +1 -5
- package/dist/commonjs/index.d.ts.map +1 -1
- package/dist/commonjs/index.js +1 -7
- package/dist/commonjs/index.js.map +1 -1
- package/dist/commonjs/instaml.d.ts +17 -4
- package/dist/commonjs/instaml.d.ts.map +1 -1
- package/dist/commonjs/instaml.js +115 -82
- package/dist/commonjs/instaml.js.map +1 -1
- package/dist/commonjs/instaql.d.ts +4 -3
- package/dist/commonjs/instaql.d.ts.map +1 -1
- package/dist/commonjs/instaql.js +65 -63
- package/dist/commonjs/instaql.js.map +1 -1
- package/dist/commonjs/reactorTypes.d.ts +29 -0
- package/dist/commonjs/reactorTypes.d.ts.map +1 -0
- package/dist/commonjs/reactorTypes.js +3 -0
- package/dist/commonjs/reactorTypes.js.map +1 -0
- package/dist/commonjs/store.d.ts +67 -25
- package/dist/commonjs/store.d.ts.map +1 -1
- package/dist/commonjs/store.js +177 -81
- package/dist/commonjs/store.js.map +1 -1
- package/dist/esm/Reactor.d.ts +24 -19
- package/dist/esm/Reactor.d.ts.map +1 -1
- package/dist/esm/Reactor.js +113 -107
- package/dist/esm/Reactor.js.map +1 -1
- package/dist/esm/SyncTable.d.ts +4 -1
- package/dist/esm/SyncTable.d.ts.map +1 -1
- package/dist/esm/SyncTable.js +35 -37
- package/dist/esm/SyncTable.js.map +1 -1
- package/dist/esm/index.d.ts +1 -5
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +2 -5
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/instaml.d.ts +17 -4
- package/dist/esm/instaml.d.ts.map +1 -1
- package/dist/esm/instaml.js +112 -77
- package/dist/esm/instaml.js.map +1 -1
- package/dist/esm/instaql.d.ts +4 -3
- package/dist/esm/instaql.d.ts.map +1 -1
- package/dist/esm/instaql.js +65 -63
- package/dist/esm/instaql.js.map +1 -1
- package/dist/esm/reactorTypes.d.ts +29 -0
- package/dist/esm/reactorTypes.d.ts.map +1 -0
- package/dist/esm/reactorTypes.js +2 -0
- package/dist/esm/reactorTypes.js.map +1 -0
- package/dist/esm/store.d.ts +67 -25
- package/dist/esm/store.d.ts.map +1 -1
- package/dist/esm/store.js +174 -81
- package/dist/esm/store.js.map +1 -1
- package/dist/standalone/index.js +1851 -1961
- package/dist/standalone/index.umd.cjs +3 -3
- package/package.json +2 -2
- package/src/Reactor.js +155 -143
- package/src/SyncTable.ts +85 -45
- package/src/index.ts +0 -9
- package/src/{instaml.js → instaml.ts} +201 -96
- package/src/instaql.ts +88 -62
- package/src/reactorTypes.ts +32 -0
- package/src/store.ts +257 -101
- package/__tests__/src/instaql.bench.js +0 -29
- package/__tests__/src/serializeSchema.test.ts +0 -123
- package/dist/commonjs/createRouteHandler.d.ts +0 -8
- package/dist/commonjs/createRouteHandler.d.ts.map +0 -1
- package/dist/commonjs/createRouteHandler.js +0 -57
- package/dist/commonjs/createRouteHandler.js.map +0 -1
- package/dist/commonjs/framework.d.ts +0 -77
- package/dist/commonjs/framework.d.ts.map +0 -1
- package/dist/commonjs/framework.js +0 -199
- package/dist/commonjs/framework.js.map +0 -1
- package/dist/commonjs/parseSchemaFromJSON.d.ts +0 -3
- package/dist/commonjs/parseSchemaFromJSON.d.ts.map +0 -1
- package/dist/commonjs/parseSchemaFromJSON.js +0 -148
- package/dist/commonjs/parseSchemaFromJSON.js.map +0 -1
- package/dist/esm/createRouteHandler.d.ts +0 -8
- package/dist/esm/createRouteHandler.d.ts.map +0 -1
- package/dist/esm/createRouteHandler.js +0 -53
- package/dist/esm/createRouteHandler.js.map +0 -1
- package/dist/esm/framework.d.ts +0 -77
- package/dist/esm/framework.d.ts.map +0 -1
- package/dist/esm/framework.js +0 -159
- package/dist/esm/framework.js.map +0 -1
- package/dist/esm/parseSchemaFromJSON.d.ts +0 -3
- package/dist/esm/parseSchemaFromJSON.d.ts.map +0 -1
- package/dist/esm/parseSchemaFromJSON.js +0 -144
- package/dist/esm/parseSchemaFromJSON.js.map +0 -1
- package/src/createRouteHandler.ts +0 -44
- package/src/framework.ts +0 -281
- package/src/parseSchemaFromJSON.ts +0 -176
package/dist/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,cAAc,CAAC;AACnC,OAAO,EACL,EAAE,EACF,MAAM,EACN,MAAM,EACN,MAAM,GAGP,MAAM,cAAc,CAAC;AACtB,OAAO,QAAQ,MAAM,qBAAqB,CAAC;AAC3C,OAAO,EAAE,MAAM,iBAAiB,CAAC;AACjC,OAAO,gBAAgB,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,qBAAqB,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EAAE,CAAC,EAAE,MAAM,aAAa,CAAC;AAChC,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,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C,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC5D,OAAO;IACT,CAAC;IAED,aAAa,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;AAC/B,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAE/B,OAAO;AACL,sBAAsB;AACtB,IAAI,EACJ,iBAAiB,EACjB,EAAE,EACF,EAAE,EACF,MAAM,EACN,MAAM,EACN,aAAa,EACb,oBAAoB,EACpB,oBAAoB,EACpB,mBAAmB,EACnB,0BAA0B,EAC1B,eAAe;AAEf,QAAQ;AACR,eAAe;AAEf,MAAM;AACN,CAAC;AAED,OAAO;AACP,MAAM,EACN,WAAW,EACX,QAAQ,EACR,YAAY,EACZ,gBAAgB,EAChB,qBAAqB,EACrB,mBAAmB,EACnB,IAAI,EACJ,OAAO,EACP,OAAO,EACP,YAAY;AAEZ,mBAAmB;AACnB,0BAA0B;AA4G1B,qCAAqC;AACrC,gBAAgB,EAEhB,yBAAyB,GAC1B,CAAC","sourcesContent":["import Reactor from './Reactor.js';\nimport {\n tx,\n txInit,\n lookup,\n getOps,\n type TxChunk,\n type TransactionChunk,\n} from './instatx.js';\nimport weakHash from './utils/weakHash.js';\nimport id from './utils/uuid.js';\nimport IndexedDBStorage from './IndexedDBStorage.ts';\nimport { coerceToDate } from './utils/dates.js';\nimport WindowNetworkListener from './WindowNetworkListener.js';\nimport { i } from './schema.js';\nimport { createDevtool } from './devtool.js';\nimport version from './version.ts';\nimport { validateQuery, QueryValidationError } from './queryValidation.ts';\nimport {\n validateTransactions,\n TransactionValidationError,\n} from './transactionValidation.ts';\n\nimport {\n StorageInterface,\n type StorageInterfaceStoreName,\n} from './utils/PersistedObject.ts';\nimport { createInstantRouteHandler } from './createRouteHandler.ts';\nimport { parseSchemaFromJSON } from './parseSchemaFromJSON.ts';\n\nimport type {\n PresenceOpts,\n PresenceResponse,\n PresenceSlice,\n RoomSchemaShape,\n} from './presence.ts';\nimport type {\n DevtoolConfig,\n IDatabase,\n IInstantDatabase,\n StrictDevtoolConfig,\n} from './coreTypes.ts';\nimport type {\n Query,\n QueryResponse,\n InstaQLResponse,\n PageInfoResponse,\n Exactly,\n InstantObject,\n InstaQLParams,\n InstaQLOptions,\n InstaQLQueryParams,\n InstaQLEntity,\n InstaQLEntitySubquery,\n InstaQLResult,\n InstaQLFields,\n ValidQuery,\n} from './queryTypes.ts';\nimport type { PresencePeer } from './presenceTypes.ts';\nimport type {\n AuthState,\n User,\n AuthResult,\n ConnectionStatus,\n} from './clientTypes.ts';\nimport type {\n InstantQuery,\n InstantQueryResult,\n InstantSchema,\n InstantEntity,\n InstantSchemaDatabase,\n} from './helperTypes.ts';\nimport type {\n InstantDBAttr,\n InstantDBAttrOnDelete,\n InstantDBCheckedDataType,\n InstantDBIdent,\n InstantDBInferredType,\n} from './attrTypes.ts';\nimport type {\n AttrsDefs,\n CardinalityKind,\n DataAttrDef,\n EntitiesDef,\n EntitiesWithLinks,\n EntityDef,\n RoomsDef,\n InstantSchemaDef,\n InstantGraph,\n LinkAttrDef,\n LinkDef,\n LinksDef,\n PresenceOf,\n ResolveAttrs,\n RoomsOf,\n TopicsOf,\n TopicOf,\n ValueTypes,\n InstantUnknownSchema,\n InstantUnknownSchemaDef,\n BackwardsCompatibleSchema,\n UpdateParams,\n LinkParams,\n CreateParams,\n RuleParams,\n} from './schemaTypes.ts';\nimport type { InstantRules } from './rulesTypes.ts';\nimport type { UploadFileResponse, DeleteFileResponse } from './StorageAPI.ts';\nimport { FrameworkClient, type FrameworkConfig } from './framework.ts';\n\nimport type {\n ExchangeCodeForTokenParams,\n SendMagicCodeParams,\n SendMagicCodeResponse,\n SignInWithIdTokenParams,\n VerifyMagicCodeParams,\n VerifyResponse,\n} from './authAPI.ts';\n\nimport { InstantAPIError, type InstantIssue } from './utils/fetch.js';\nimport { InstantError } from './InstantError.ts';\nimport { EventSourceType } from './Connection.ts';\nimport { CallbackEventType as SyncTableCallbackEventType } from './SyncTable.ts';\nimport type {\n SyncTableCallback,\n CallbackEvent as SyncTableCallbackEvent,\n InitialSyncBatch as SyncTableInitialSyncBatch,\n InitialSyncComplete as SyncTableInitialSyncComplete,\n SyncTransaction as SyncTableSyncTransaction,\n LoadFromStorage as SyncTableLoadFromStorage,\n SetupError as SyncTableSetupError,\n} from './SyncTable.ts';\n\nconst defaultOpenDevtool = true;\n\n// types\n\ntype ExactlyOne<T> = {\n [K in keyof T]: Pick<T, K> & Partial<Record<Exclude<keyof T, K>, never>>;\n}[keyof T];\n\nexport type Config = {\n appId: string;\n websocketURI?: string;\n apiURI?: string;\n devtool?: boolean | DevtoolConfig;\n verbose?: boolean;\n queryCacheLimit?: number;\n useDateObjects: boolean;\n disableValidation?: boolean;\n};\n\nexport type InstantConfig<\n S extends InstantSchemaDef<any, any, any>,\n UseDates extends boolean = false,\n> = {\n appId: string;\n schema?: S;\n websocketURI?: string;\n cookieEndpoint?: string;\n apiURI?: string;\n devtool?: boolean | DevtoolConfig;\n verbose?: boolean;\n queryCacheLimit?: number;\n useDateObjects: UseDates;\n disableValidation?: boolean;\n};\n\nexport type ConfigWithSchema<S extends InstantGraph<any, any>> = Config & {\n schema: S;\n};\n\nexport type TransactionResult = {\n status: 'synced' | 'enqueued';\n clientId: string;\n};\n\nexport type PublishTopic<TopicsByKey> = <Key extends keyof TopicsByKey>(\n topic: Key,\n data: TopicsByKey[Key],\n) => void;\n\nexport type SubscribeTopic<PresenceShape, TopicsByKey> = <\n Key extends keyof TopicsByKey,\n>(\n topic: Key,\n onEvent: (event: TopicsByKey[Key], peer: PresenceShape) => void,\n) => () => void;\n\nexport type GetPresence<PresenceShape> = <Keys extends keyof PresenceShape>(\n opts: PresenceOpts<PresenceShape, Keys>,\n) => PresenceResponse<PresenceShape, Keys> | null;\n\nexport type SubscribePresence<PresenceShape> = <\n Keys extends keyof PresenceShape,\n>(\n opts: PresenceOpts<PresenceShape, Keys>,\n onChange: (slice: PresenceResponse<PresenceShape, Keys>) => void,\n) => () => void;\n\nexport type RoomHandle<PresenceShape, TopicsByKey> = {\n leaveRoom: () => void;\n publishTopic: PublishTopic<TopicsByKey>;\n subscribeTopic: SubscribeTopic<PresenceShape, TopicsByKey>;\n publishPresence: (data: Partial<PresenceShape>) => void;\n getPresence: GetPresence<PresenceShape>;\n subscribePresence: SubscribePresence<PresenceShape>;\n};\n\ntype AuthToken = string;\n\ntype SubscriptionState<Q, Schema, WithCardinalityInference extends boolean> =\n | { error: { message: string }; data: undefined; pageInfo: undefined }\n | {\n error: undefined;\n data: QueryResponse<Q, Schema, WithCardinalityInference>;\n pageInfo: PageInfoResponse<Q>;\n };\n\ntype InstaQLSubscriptionState<Schema, Q, UseDates extends boolean> =\n | { error: { message: string }; data: undefined; pageInfo: undefined }\n | {\n error: undefined;\n data: InstaQLResponse<Schema, Q, UseDates>;\n pageInfo: PageInfoResponse<Q>;\n };\n\ntype LifecycleSubscriptionState<\n Q,\n Schema,\n WithCardinalityInference extends boolean,\n> = SubscriptionState<Q, Schema, WithCardinalityInference> & {\n isLoading: boolean;\n};\n\ntype InstaQLLifecycleState<Schema, Q, UseDates extends boolean = false> =\n | (InstaQLSubscriptionState<Schema, Q, UseDates> & {\n isLoading: boolean;\n })\n | {\n isLoading: true;\n data: undefined;\n pageInfo: undefined;\n error: undefined;\n };\n\ntype UnsubscribeFn = () => void;\n\n// consts\n\nconst defaultConfig = {\n apiURI: 'https://api.instantdb.com',\n websocketURI: 'wss://api.instantdb.com/runtime/session',\n};\n\n// hmr\nfunction initSchemaHashStore(): WeakMap<any, string> {\n globalThis.__instantDbSchemaHashStore =\n globalThis.__instantDbSchemaHashStore ?? new WeakMap<any, string>();\n return globalThis.__instantDbSchemaHashStore;\n}\n\nfunction initGlobalInstantCoreStore(): Record<string, any> {\n globalThis.__instantDbStore = globalThis.__instantDbStore ?? {};\n return globalThis.__instantDbStore;\n}\n\nfunction reactorKey(config: InstantConfig<any, boolean>): string {\n // @ts-expect-error\n const adminToken = config.__adminToken;\n return (\n config.appId +\n '_' +\n (config.websocketURI || 'default_ws_uri') +\n '_' +\n (config.apiURI || 'default_api_uri') +\n '_' +\n (adminToken || 'client_only') +\n '_' +\n config.useDateObjects\n );\n}\n\nconst globalInstantCoreStore = initGlobalInstantCoreStore();\nconst schemaHashStore = initSchemaHashStore();\n\ntype SignoutOpts = {\n invalidateToken?: boolean;\n};\n\n/**\n * Functions to log users in and out.\n *\n * @see https://instantdb.com/docs/auth\n */\nclass Auth {\n constructor(private db: Reactor) {}\n\n /**\n * Sends a magic code to the user's email address.\n *\n * Once you send the magic code, see {@link auth.signInWithMagicCode} to let the\n * user verify.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * db.auth.sendMagicCode({email: \"example@gmail.com\"})\n * .catch((err) => console.error(err.body?.message))\n */\n sendMagicCode = (\n params: SendMagicCodeParams,\n ): Promise<SendMagicCodeResponse> => {\n return this.db.sendMagicCode(params);\n };\n\n /**\n * Verify a magic code that was sent to the user's email address.\n *\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * db.auth.signInWithMagicCode({email: \"example@gmail.com\", code: \"123456\"})\n * .catch((err) => console.error(err.body?.message))\n */\n signInWithMagicCode = (\n params: VerifyMagicCodeParams,\n ): Promise<VerifyResponse> => {\n return this.db.signInWithMagicCode(params);\n };\n\n /**\n * Sign in a user with a refresh token\n *\n * @see https://instantdb.com/docs/backend#frontend-auth-sign-in-with-token\n *\n * @example\n * // Get the token from your backend\n * const token = await fetch('/signin', ...);\n * //Sign in\n * db.auth.signInWithToken(token);\n */\n signInWithToken = (token: AuthToken): Promise<VerifyResponse> => {\n return this.db.signInWithCustomToken(token);\n };\n\n /**\n * Sign in as guest, creating a new user without email\n *\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * db.auth.signInAsGuest();\n */\n signInAsGuest = (): Promise<VerifyResponse> => {\n return this.db.signInAsGuest();\n };\n\n /**\n * Create an authorization url to sign in with an external provider.\n *\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * // Get the authorization url from your backend\n * const url = db.auth.createAuthorizationUrl({\n * clientName: \"google\",\n * redirectURL: window.location.href,\n * });\n *\n * // Put it in a sign in link\n * <a href={url}>Log in with Google</a>\n */\n createAuthorizationURL = (params: {\n clientName: string;\n redirectURL: string;\n }): string => {\n return this.db.createAuthorizationURL(params);\n };\n\n /**\n * Sign in with the id_token from an external provider like Google\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * db.auth\n * .signInWithIdToken({\n * // Token from external service\n * idToken: id_token,\n * // The name you gave the client when you registered it with Instant\n * clientName: \"google\",\n * // The nonce, if any, that you used when you initiated the auth flow\n * // with the external service.\n * nonce: your_nonce\n * })\n * .catch((err) => console.error(err.body?.message));\n *\n */\n signInWithIdToken = (\n params: SignInWithIdTokenParams,\n ): Promise<VerifyResponse> => {\n return this.db.signInWithIdToken(params);\n };\n\n /**\n * Sign in with the id_token from an external provider like Google\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * db.auth\n * .exchangeOAuthCode({\n * // code received in redirect from OAuth callback\n * code: code\n * // The PKCE code_verifier, if any, that you used when you\n * // initiated the auth flow\n * codeVerifier: your_code_verifier\n * })\n * .catch((err) => console.error(err.body?.message));\n *\n */\n exchangeOAuthCode = (params: ExchangeCodeForTokenParams) => {\n return this.db.exchangeCodeForToken(params);\n };\n\n /**\n * OpenID Discovery path for use with tools like\n * expo-auth-session that use auto-discovery of\n * OAuth parameters.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const discovery = useAutoDiscovery(\n * db.auth.issuerURI()\n * );\n */\n issuerURI = (): string => {\n return this.db.issuerURI();\n };\n\n /**\n * Sign out the current user\n */\n signOut = (opts: SignoutOpts = { invalidateToken: true }): Promise<void> => {\n return this.db.signOut(opts);\n };\n}\n\ntype FileOpts = {\n contentType?: string;\n contentDisposition?: string;\n fileSize?: number; // Required for streaming uploads\n};\n\n/**\n * Functions to manage file storage.\n */\nclass Storage {\n constructor(private db: Reactor) {}\n\n /**\n * Uploads file at the provided path.\n *\n * @see https://instantdb.com/docs/storage\n * @example\n * const [file] = e.target.files; // result of file input\n * const data = await db.storage.uploadFile('photos/demo.png', file);\n */\n uploadFile = (\n path: string,\n file: File | Blob,\n opts: FileOpts = {},\n ): Promise<UploadFileResponse> => {\n return this.db.uploadFile(path, file, opts);\n };\n\n /**\n * Deletes a file by path name.\n *\n * @see https://instantdb.com/docs/storage\n * @example\n * await db.storage.delete('photos/demo.png');\n */\n delete = (pathname: string) => {\n return this.db.deleteFile(pathname);\n };\n\n // Deprecated Storage API (Jan 2025)\n // ---------------------------------\n\n /**\n * @deprecated. Use `db.storage.uploadFile` instead\n * remove in the future.\n */\n upload = (pathname: string, file: File) => {\n return this.db.upload(pathname, file);\n };\n\n /**\n * @deprecated Use `db.storage.uploadFile` instead\n */\n put = this.upload;\n\n /**\n * @deprecated. getDownloadUrl will be removed in the future.\n * Use `useQuery` instead to query and fetch for valid urls\n *\n * db.useQuery({\n * $files: {\n * $: {\n * where: {\n * path: \"moop.png\"\n * }\n * }\n * }\n * })\n */\n getDownloadUrl = (pathname: string) => {\n return this.db.getDownloadUrl(pathname);\n };\n}\n\n// util\n\nfunction coerceQuery(o: any) {\n // stringify and parse to remove undefined values\n return JSON.parse(JSON.stringify(o));\n}\n\nclass InstantCoreDatabase<\n Schema extends InstantSchemaDef<any, any, any>,\n UseDates extends boolean = false,\n> implements IInstantDatabase<Schema>\n{\n public _reactor: Reactor<RoomsOf<Schema>>;\n public auth: Auth;\n public storage: Storage;\n\n public tx = txInit<Schema>();\n\n constructor(reactor: Reactor<RoomsOf<Schema>>) {\n this._reactor = reactor;\n this.auth = new Auth(this._reactor);\n this.storage = new Storage(this._reactor);\n }\n\n /**\n * Use this to write data! You can create, update, delete, and link objects\n *\n * @see https://instantdb.com/docs/instaml\n *\n * @example\n * // Create a new object in the `goals` namespace\n * const goalId = id();\n * db.transact(db.tx.goals[goalId].update({title: \"Get fit\"}))\n *\n * // Update the title\n * db.transact(db.tx.goals[goalId].update({title: \"Get super fit\"}))\n *\n * // Delete it\n * db.transact(db.tx.goals[goalId].delete())\n *\n * // Or create an association:\n * todoId = id();\n * db.transact([\n * db.tx.todos[todoId].update({ title: 'Go on a run' }),\n * db.tx.goals[goalId].link({todos: todoId}),\n * ])\n */\n transact(\n chunks: TransactionChunk<any, any> | TransactionChunk<any, any>[],\n ): Promise<TransactionResult> {\n return this._reactor.pushTx(chunks);\n }\n\n getLocalId(name: string): Promise<string> {\n return this._reactor.getLocalId(name);\n }\n\n /**\n * Use this to query your data!\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n * // listen to all goals\n * db.subscribeQuery({ goals: {} }, (resp) => {\n * console.log(resp.data.goals)\n * })\n *\n * // goals where the title is \"Get Fit\"\n * db.subscribeQuery(\n * { goals: { $: { where: { title: \"Get Fit\" } } } },\n * (resp) => {\n * console.log(resp.data.goals)\n * }\n * )\n *\n * // all goals, _alongside_ their todos\n * db.subscribeQuery({ goals: { todos: {} } }, (resp) => {\n * console.log(resp.data.goals)\n * });\n */\n subscribeQuery<\n Q extends ValidQuery<Q, Schema>,\n UseDatesLocal extends boolean = UseDates,\n >(\n query: Q,\n cb: (resp: InstaQLSubscriptionState<Schema, Q, UseDatesLocal>) => void,\n opts?: InstaQLOptions,\n ) {\n return this._reactor.subscribeQuery(query, cb, opts);\n }\n\n /**\n * Listen for the logged in state. This is useful\n * for deciding when to show a login screen.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const unsub = db.subscribeAuth((auth) => {\n * if (auth.user) {\n * console.log('logged in as', auth.user.email)\n * } else {\n * console.log('logged out')\n * }\n * })\n */\n subscribeAuth(cb: (auth: AuthResult) => void): UnsubscribeFn {\n return this._reactor.subscribeAuth(cb);\n }\n\n /**\n * One time query for the logged in state. This is useful\n * for scenarios where you want to know the current auth\n * state without subscribing to changes.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const user = await db.getAuth();\n * console.log('logged in as', user.email)\n */\n getAuth(): Promise<User | null> {\n return this._reactor.getAuth();\n }\n\n /**\n * Listen for connection status changes to Instant. This is useful\n * for building things like connectivity indicators\n *\n * @see https://www.instantdb.com/docs/patterns#connection-status\n * @example\n * const unsub = db.subscribeConnectionStatus((status) => {\n * const connectionState =\n * status === 'connecting' || status === 'opened'\n * ? 'authenticating'\n * : status === 'authenticated'\n * ? 'connected'\n * : status === 'closed'\n * ? 'closed'\n * : status === 'errored'\n * ? 'errored'\n * : 'unexpected state';\n *\n * console.log('Connection status:', connectionState);\n * });\n */\n subscribeConnectionStatus(\n cb: (status: ConnectionStatus) => void,\n ): UnsubscribeFn {\n return this._reactor.subscribeConnectionStatus(cb);\n }\n\n /**\n * Join a room to publish and subscribe to topics and presence.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * // init\n * const db = init();\n * const room = db.joinRoom(roomType, roomId);\n * // usage\n * const unsubscribeTopic = room.subscribeTopic(\"foo\", console.log);\n * const unsubscribePresence = room.subscribePresence({}, console.log);\n * room.publishTopic(\"hello\", { message: \"hello world!\" });\n * room.publishPresence({ name: \"joe\" });\n * // later\n * unsubscribePresence();\n * unsubscribeTopic();\n * room.leaveRoom();\n */\n joinRoom<RoomType extends keyof RoomsOf<Schema>>(\n roomType: RoomType = '_defaultRoomType' as RoomType,\n roomId: string = '_defaultRoomId',\n opts?: {\n initialPresence?: Partial<PresenceOf<Schema, RoomType>>;\n },\n ): RoomHandle<PresenceOf<Schema, RoomType>, TopicsOf<Schema, RoomType>> {\n const leaveRoom = this._reactor.joinRoom(roomId, opts?.initialPresence);\n\n return {\n leaveRoom,\n subscribeTopic: (topic, onEvent) =>\n this._reactor.subscribeTopic(roomId, topic, onEvent),\n subscribePresence: (opts, onChange) =>\n this._reactor.subscribePresence(roomType, roomId, opts, onChange),\n publishTopic: (topic, data) =>\n this._reactor.publishTopic({ roomType, roomId, topic, data }),\n publishPresence: (data) =>\n this._reactor.publishPresence(roomType, roomId, data),\n getPresence: (opts) => this._reactor.getPresence(roomType, roomId, opts),\n };\n }\n\n shutdown() {\n delete globalInstantCoreStore[reactorKey(this._reactor.config)];\n this._reactor.shutdown();\n }\n\n /**\n * Use this for one-off queries.\n * Returns local data if available, otherwise fetches from the server.\n * Because we want to avoid stale data, this method will throw an error\n * if the user is offline or there is no active connection to the server.\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n *\n * const resp = await db.queryOnce({ goals: {} });\n * console.log(resp.data.goals)\n */\n queryOnce<Q extends ValidQuery<Q, Schema>>(\n query: Q,\n opts?: InstaQLOptions,\n ): Promise<{\n data: InstaQLResponse<Schema, Q, UseDates>;\n pageInfo: PageInfoResponse<Q>;\n }> {\n return this._reactor.queryOnce(query, opts);\n }\n\n /**\n * @deprecated This is an experimental function that is not yet ready for production use.\n * Use this function to sync an entire namespace.\n * It has many limitations that will be removed in the future:\n * 1. Must be used with an admin token\n * 2. Does not support permissions\n * 3. Does not support where clauses\n * 4. Does not support links\n * It also does not support multiple top-level namespaces. For example,\n * {posts: {}, users: {}} is invalid. Only `posts` or `users` is allowed, but not both.\n */\n _syncTableExperimental<Q extends ValidQuery<Q, Schema>>(\n query: ExactlyOne<Q>,\n cb: SyncTableCallback<Schema, Q, UseDates>,\n ): (\n opts?: { keepSubscription: boolean | null | undefined } | null | undefined,\n ) => void {\n return this._reactor.subscribeTable(query, cb);\n }\n}\n\nfunction schemaHash(schema?: InstantSchemaDef<any, any, any>): string {\n if (!schema) {\n return '0';\n }\n\n const fromStore = schemaHashStore.get(schema);\n if (fromStore) {\n return fromStore;\n }\n const hash = weakHash(schema);\n schemaHashStore.set(schema, hash);\n return hash;\n}\n\nfunction schemaChanged(\n existingClient: InstantCoreDatabase<any, boolean>,\n newSchema?: InstantSchemaDef<any, any, any>,\n): boolean {\n return (\n schemaHash(existingClient._reactor.config.schema) !== schemaHash(newSchema)\n );\n}\n\n/**\n *\n * The first step: init your application!\n *\n * Visit https://instantdb.com/dash to get your `appId` :)\n *\n * @example\n * import { init } from \"@instantdb/core\"\n *\n * const db = init({ appId: \"my-app-id\" })\n *\n * // You can also provide a schema for type safety and editor autocomplete!\n *\n * import { init } from \"@instantdb/core\"\n * import schema from \"\"../instant.schema.ts\";\n *\n * const db = init({ appId: \"my-app-id\", schema })\n *\n * // To learn more: https://instantdb.com/docs/modeling-data\n */\nfunction init<\n Schema extends InstantSchemaDef<any, any, any> = InstantUnknownSchema,\n UseDates extends boolean = false,\n>(\n // Allows config with missing `useDateObjects`, but keeps `UseDates`\n // as a non-nullable in the InstantConfig type.\n config: Omit<InstantConfig<Schema, UseDates>, 'useDateObjects'> & {\n useDateObjects?: UseDates;\n },\n Storage?: any,\n NetworkListener?: any,\n versions?: { [key: string]: string },\n EventSourceImpl?: any,\n): InstantCoreDatabase<Schema, UseDates> {\n const configStrict = {\n ...config,\n useDateObjects: (config.useDateObjects ?? false) as UseDates,\n };\n const existingClient = globalInstantCoreStore[\n reactorKey(configStrict)\n ] as InstantCoreDatabase<any, UseDates>;\n\n if (existingClient) {\n if (schemaChanged(existingClient, configStrict.schema)) {\n existingClient._reactor.updateSchema(configStrict.schema);\n }\n return existingClient;\n }\n\n const reactor = new Reactor<RoomsOf<Schema>>(\n {\n ...defaultConfig,\n ...configStrict,\n cardinalityInference: configStrict.schema ? true : false,\n },\n Storage || IndexedDBStorage,\n NetworkListener || WindowNetworkListener,\n { ...(versions || {}), '@instantdb/core': version },\n EventSourceImpl,\n );\n\n const client = new InstantCoreDatabase<any, UseDates>(reactor);\n globalInstantCoreStore[reactorKey(configStrict)] = client;\n\n handleDevtool(configStrict.appId, configStrict.devtool);\n\n return client;\n}\n\nfunction handleDevtool(\n appId: string,\n devtool: boolean | DevtoolConfig | null | undefined,\n) {\n if (\n typeof window === 'undefined' ||\n typeof window.location === 'undefined' ||\n typeof document === 'undefined'\n ) {\n return;\n }\n\n if (typeof devtool === 'boolean' && !devtool) {\n return;\n }\n\n const config: StrictDevtoolConfig = {\n position: 'bottom-right' as const,\n allowedHosts: ['localhost'],\n ...(typeof devtool === 'object' ? devtool : {}),\n };\n\n if (!config.allowedHosts.includes(window.location.hostname)) {\n return;\n }\n\n createDevtool(appId, config);\n}\n\n/**\n * @deprecated\n * `init_experimental` is deprecated. You can replace it with `init`.\n *\n * @example\n *\n * // Before\n * import { init_experimental } from \"@instantdb/core\"\n * const db = init_experimental({ ... });\n *\n * // After\n * import { init } from \"@instantdb/core\"\n * const db = init({ ... });\n */\nconst init_experimental = init;\n\nexport {\n // bada bing bada boom\n init,\n init_experimental,\n id,\n tx,\n txInit,\n lookup,\n validateQuery,\n QueryValidationError,\n validateTransactions,\n parseSchemaFromJSON,\n TransactionValidationError,\n FrameworkClient,\n\n // error\n InstantAPIError,\n\n // cli\n i,\n\n // util\n getOps,\n coerceQuery,\n weakHash,\n coerceToDate,\n IndexedDBStorage,\n WindowNetworkListener,\n InstantCoreDatabase,\n Auth,\n Storage,\n version,\n InstantError,\n\n // sync table enums\n SyncTableCallbackEventType,\n\n // og types\n type IDatabase,\n type RoomSchemaShape,\n type Query,\n type QueryResponse,\n type InstaQLResponse,\n type PageInfoResponse,\n type InstantObject,\n type Exactly,\n type TransactionChunk,\n type AuthState,\n type ConnectionStatus,\n type User,\n type AuthToken,\n type TxChunk,\n type SubscriptionState,\n type InstaQLSubscriptionState,\n type LifecycleSubscriptionState,\n type InstaQLLifecycleState,\n\n // presence types\n type PresenceOpts,\n type PresenceSlice,\n type PresenceResponse,\n type PresencePeer,\n\n // new query types\n type InstaQLParams,\n type ValidQuery,\n type InstaQLOptions,\n type InstaQLQueryParams,\n type InstantQuery,\n type InstantQueryResult,\n type InstantSchema,\n type InstantEntity,\n type InstantSchemaDatabase,\n type InstaQLFields,\n\n // schema types\n type AttrsDefs,\n type CardinalityKind,\n type DataAttrDef,\n type EntitiesDef,\n type InstantUnknownSchemaDef,\n type EntitiesWithLinks,\n type EntityDef,\n type RoomsDef,\n type InstantGraph,\n type LinkAttrDef,\n type LinkDef,\n type LinksDef,\n type ResolveAttrs,\n type ValueTypes,\n type RoomsOf,\n type PresenceOf,\n type TopicsOf,\n type TopicOf,\n type InstaQLEntity,\n type InstaQLResult,\n type InstaQLEntitySubquery,\n type InstantSchemaDef,\n type InstantUnknownSchema,\n type IInstantDatabase,\n type BackwardsCompatibleSchema,\n type InstantRules,\n type UpdateParams,\n type LinkParams,\n type CreateParams,\n type RuleParams,\n\n // attr types\n type InstantDBAttr,\n type InstantDBAttrOnDelete,\n type InstantDBCheckedDataType,\n type InstantDBIdent,\n type InstantDBInferredType,\n\n // auth types\n type ExchangeCodeForTokenParams,\n type SendMagicCodeParams,\n type SendMagicCodeResponse,\n type SignInWithIdTokenParams,\n type VerifyMagicCodeParams,\n type VerifyResponse,\n\n // storage types\n type FileOpts,\n type UploadFileResponse,\n type DeleteFileResponse,\n\n // SSE\n type EventSourceType,\n type FrameworkConfig,\n\n // sync table types\n type SyncTableCallback,\n type SyncTableCallbackEvent,\n type SyncTableInitialSyncBatch,\n type SyncTableInitialSyncComplete,\n type SyncTableSyncTransaction,\n type SyncTableLoadFromStorage,\n type SyncTableSetupError,\n\n // error types\n type InstantIssue,\n\n // storage (e.g. indexeddb) interface\n StorageInterface,\n type StorageInterfaceStoreName,\n createInstantRouteHandler,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,cAAc,CAAC;AACnC,OAAO,EACL,EAAE,EACF,MAAM,EACN,MAAM,EACN,MAAM,GAGP,MAAM,cAAc,CAAC;AACtB,OAAO,QAAQ,MAAM,qBAAqB,CAAC;AAC3C,OAAO,EAAE,MAAM,iBAAiB,CAAC;AACjC,OAAO,gBAAgB,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,qBAAqB,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EAAE,CAAC,EAAE,MAAM,aAAa,CAAC;AAChC,OAAO,EAAE,aAAa,EAAE,MAAM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AC;AAC/B,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAE/B,OAAO;AACL,sBAAsB;AACtB,IAAI,EACJ,iBAAiB,EACjB,EAAE,EACF,EAAE,EACF,MAAM,EACN,MAAM,EACN,aAAa,EACb,oBAAoB,EACpB,oBAAoB,EACpB,0BAA0B;AAE1B,QAAQ;AACR,eAAe;AAEf,MAAM;AACN,CAAC;AAED,OAAO;AACP,MAAM,EACN,WAAW,EACX,QAAQ,EACR,YAAY,EACZ,gBAAgB,EAChB,qBAAqB,EACrB,mBAAmB,EACnB,IAAI,EACJ,OAAO,EACP,OAAO,EACP,YAAY;AAEZ,mBAAmB;AACnB,0BAA0B;AA2G1B,qCAAqC;AACrC,gBAAgB,GAEjB,CAAC","sourcesContent":["import Reactor from './Reactor.js';\nimport {\n tx,\n txInit,\n lookup,\n getOps,\n type TxChunk,\n type TransactionChunk,\n} from './instatx.js';\nimport weakHash from './utils/weakHash.js';\nimport id from './utils/uuid.js';\nimport IndexedDBStorage from './IndexedDBStorage.ts';\nimport { coerceToDate } from './utils/dates.js';\nimport WindowNetworkListener from './WindowNetworkListener.js';\nimport { i } from './schema.js';\nimport { createDevtool } from './devtool.js';\nimport version from './version.ts';\nimport { validateQuery, QueryValidationError } from './queryValidation.ts';\nimport {\n validateTransactions,\n TransactionValidationError,\n} from './transactionValidation.ts';\nimport {\n StorageInterface,\n type StorageInterfaceStoreName,\n} from './utils/PersistedObject.ts';\n\nimport type {\n PresenceOpts,\n PresenceResponse,\n PresenceSlice,\n RoomSchemaShape,\n} from './presence.ts';\nimport type {\n DevtoolConfig,\n IDatabase,\n IInstantDatabase,\n StrictDevtoolConfig,\n} from './coreTypes.ts';\nimport type {\n Query,\n QueryResponse,\n InstaQLResponse,\n PageInfoResponse,\n Exactly,\n InstantObject,\n InstaQLParams,\n InstaQLOptions,\n InstaQLQueryParams,\n InstaQLEntity,\n InstaQLEntitySubquery,\n InstaQLResult,\n InstaQLFields,\n ValidQuery,\n} from './queryTypes.ts';\nimport type { PresencePeer } from './presenceTypes.ts';\nimport type {\n AuthState,\n User,\n AuthResult,\n ConnectionStatus,\n} from './clientTypes.ts';\nimport type {\n InstantQuery,\n InstantQueryResult,\n InstantSchema,\n InstantEntity,\n InstantSchemaDatabase,\n} from './helperTypes.ts';\nimport type {\n InstantDBAttr,\n InstantDBAttrOnDelete,\n InstantDBCheckedDataType,\n InstantDBIdent,\n InstantDBInferredType,\n} from './attrTypes.ts';\nimport type {\n AttrsDefs,\n CardinalityKind,\n DataAttrDef,\n EntitiesDef,\n EntitiesWithLinks,\n EntityDef,\n RoomsDef,\n InstantSchemaDef,\n InstantGraph,\n LinkAttrDef,\n LinkDef,\n LinksDef,\n PresenceOf,\n ResolveAttrs,\n RoomsOf,\n TopicsOf,\n TopicOf,\n ValueTypes,\n InstantUnknownSchema,\n InstantUnknownSchemaDef,\n BackwardsCompatibleSchema,\n UpdateParams,\n LinkParams,\n CreateParams,\n RuleParams,\n} from './schemaTypes.ts';\nimport type { InstantRules } from './rulesTypes.ts';\nimport type { UploadFileResponse, DeleteFileResponse } from './StorageAPI.ts';\n\nimport type {\n ExchangeCodeForTokenParams,\n SendMagicCodeParams,\n SendMagicCodeResponse,\n SignInWithIdTokenParams,\n VerifyMagicCodeParams,\n VerifyResponse,\n} from './authAPI.ts';\n\nimport { InstantAPIError, type InstantIssue } from './utils/fetch.js';\nimport { InstantError } from './InstantError.ts';\nimport { EventSourceType } from './Connection.ts';\nimport { CallbackEventType as SyncTableCallbackEventType } from './SyncTable.ts';\nimport type {\n SyncTableCallback,\n CallbackEvent as SyncTableCallbackEvent,\n InitialSyncBatch as SyncTableInitialSyncBatch,\n InitialSyncComplete as SyncTableInitialSyncComplete,\n SyncTransaction as SyncTableSyncTransaction,\n LoadFromStorage as SyncTableLoadFromStorage,\n SetupError as SyncTableSetupError,\n} from './SyncTable.ts';\n\nconst defaultOpenDevtool = true;\n\n// types\n\ntype ExactlyOne<T> = {\n [K in keyof T]: Pick<T, K> & Partial<Record<Exclude<keyof T, K>, never>>;\n}[keyof T];\n\nexport type Config = {\n appId: string;\n websocketURI?: string;\n apiURI?: string;\n devtool?: boolean | DevtoolConfig;\n verbose?: boolean;\n queryCacheLimit?: number;\n useDateObjects: boolean;\n disableValidation?: boolean;\n};\n\nexport type InstantConfig<\n S extends InstantSchemaDef<any, any, any>,\n UseDates extends boolean = false,\n> = {\n appId: string;\n schema?: S;\n websocketURI?: string;\n apiURI?: string;\n devtool?: boolean | DevtoolConfig;\n verbose?: boolean;\n queryCacheLimit?: number;\n useDateObjects: UseDates;\n disableValidation?: boolean;\n};\n\nexport type ConfigWithSchema<S extends InstantGraph<any, any>> = Config & {\n schema: S;\n};\n\nexport type TransactionResult = {\n status: 'synced' | 'enqueued';\n clientId: string;\n};\n\nexport type PublishTopic<TopicsByKey> = <Key extends keyof TopicsByKey>(\n topic: Key,\n data: TopicsByKey[Key],\n) => void;\n\nexport type SubscribeTopic<PresenceShape, TopicsByKey> = <\n Key extends keyof TopicsByKey,\n>(\n topic: Key,\n onEvent: (event: TopicsByKey[Key], peer: PresenceShape) => void,\n) => () => void;\n\nexport type GetPresence<PresenceShape> = <Keys extends keyof PresenceShape>(\n opts: PresenceOpts<PresenceShape, Keys>,\n) => PresenceResponse<PresenceShape, Keys> | null;\n\nexport type SubscribePresence<PresenceShape> = <\n Keys extends keyof PresenceShape,\n>(\n opts: PresenceOpts<PresenceShape, Keys>,\n onChange: (slice: PresenceResponse<PresenceShape, Keys>) => void,\n) => () => void;\n\nexport type RoomHandle<PresenceShape, TopicsByKey> = {\n leaveRoom: () => void;\n publishTopic: PublishTopic<TopicsByKey>;\n subscribeTopic: SubscribeTopic<PresenceShape, TopicsByKey>;\n publishPresence: (data: Partial<PresenceShape>) => void;\n getPresence: GetPresence<PresenceShape>;\n subscribePresence: SubscribePresence<PresenceShape>;\n};\n\ntype AuthToken = string;\n\ntype SubscriptionState<Q, Schema, WithCardinalityInference extends boolean> =\n | { error: { message: string }; data: undefined; pageInfo: undefined }\n | {\n error: undefined;\n data: QueryResponse<Q, Schema, WithCardinalityInference>;\n pageInfo: PageInfoResponse<Q>;\n };\n\ntype InstaQLSubscriptionState<Schema, Q, UseDates extends boolean> =\n | { error: { message: string }; data: undefined; pageInfo: undefined }\n | {\n error: undefined;\n data: InstaQLResponse<Schema, Q, UseDates>;\n pageInfo: PageInfoResponse<Q>;\n };\n\ntype LifecycleSubscriptionState<\n Q,\n Schema,\n WithCardinalityInference extends boolean,\n> = SubscriptionState<Q, Schema, WithCardinalityInference> & {\n isLoading: boolean;\n};\n\ntype InstaQLLifecycleState<Schema, Q, UseDates extends boolean = false> =\n | (InstaQLSubscriptionState<Schema, Q, UseDates> & {\n isLoading: boolean;\n })\n | {\n isLoading: true;\n data: undefined;\n pageInfo: undefined;\n error: undefined;\n };\n\ntype UnsubscribeFn = () => void;\n\n// consts\n\nconst defaultConfig = {\n apiURI: 'https://api.instantdb.com',\n websocketURI: 'wss://api.instantdb.com/runtime/session',\n};\n\n// hmr\nfunction initSchemaHashStore(): WeakMap<any, string> {\n globalThis.__instantDbSchemaHashStore =\n globalThis.__instantDbSchemaHashStore ?? new WeakMap<any, string>();\n return globalThis.__instantDbSchemaHashStore;\n}\n\nfunction initGlobalInstantCoreStore(): Record<string, any> {\n globalThis.__instantDbStore = globalThis.__instantDbStore ?? {};\n return globalThis.__instantDbStore;\n}\n\nfunction reactorKey(config: InstantConfig<any, boolean>): string {\n // @ts-expect-error\n const adminToken = config.__adminToken;\n return (\n config.appId +\n '_' +\n (config.websocketURI || 'default_ws_uri') +\n '_' +\n (config.apiURI || 'default_api_uri') +\n '_' +\n (adminToken || 'client_only') +\n '_' +\n config.useDateObjects\n );\n}\n\nconst globalInstantCoreStore = initGlobalInstantCoreStore();\nconst schemaHashStore = initSchemaHashStore();\n\ntype SignoutOpts = {\n invalidateToken?: boolean;\n};\n\n/**\n * Functions to log users in and out.\n *\n * @see https://instantdb.com/docs/auth\n */\nclass Auth {\n constructor(private db: Reactor) {}\n\n /**\n * Sends a magic code to the user's email address.\n *\n * Once you send the magic code, see {@link auth.signInWithMagicCode} to let the\n * user verify.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * db.auth.sendMagicCode({email: \"example@gmail.com\"})\n * .catch((err) => console.error(err.body?.message))\n */\n sendMagicCode = (\n params: SendMagicCodeParams,\n ): Promise<SendMagicCodeResponse> => {\n return this.db.sendMagicCode(params);\n };\n\n /**\n * Verify a magic code that was sent to the user's email address.\n *\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * db.auth.signInWithMagicCode({email: \"example@gmail.com\", code: \"123456\"})\n * .catch((err) => console.error(err.body?.message))\n */\n signInWithMagicCode = (\n params: VerifyMagicCodeParams,\n ): Promise<VerifyResponse> => {\n return this.db.signInWithMagicCode(params);\n };\n\n /**\n * Sign in a user with a refresh token\n *\n * @see https://instantdb.com/docs/backend#frontend-auth-sign-in-with-token\n *\n * @example\n * // Get the token from your backend\n * const token = await fetch('/signin', ...);\n * //Sign in\n * db.auth.signInWithToken(token);\n */\n signInWithToken = (token: AuthToken): Promise<VerifyResponse> => {\n return this.db.signInWithCustomToken(token);\n };\n\n /**\n * Sign in as guest, creating a new user without email\n *\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * db.auth.signInAsGuest();\n */\n signInAsGuest = (): Promise<VerifyResponse> => {\n return this.db.signInAsGuest();\n };\n\n /**\n * Create an authorization url to sign in with an external provider.\n *\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * // Get the authorization url from your backend\n * const url = db.auth.createAuthorizationUrl({\n * clientName: \"google\",\n * redirectURL: window.location.href,\n * });\n *\n * // Put it in a sign in link\n * <a href={url}>Log in with Google</a>\n */\n createAuthorizationURL = (params: {\n clientName: string;\n redirectURL: string;\n }): string => {\n return this.db.createAuthorizationURL(params);\n };\n\n /**\n * Sign in with the id_token from an external provider like Google\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * db.auth\n * .signInWithIdToken({\n * // Token from external service\n * idToken: id_token,\n * // The name you gave the client when you registered it with Instant\n * clientName: \"google\",\n * // The nonce, if any, that you used when you initiated the auth flow\n * // with the external service.\n * nonce: your_nonce\n * })\n * .catch((err) => console.error(err.body?.message));\n *\n */\n signInWithIdToken = (\n params: SignInWithIdTokenParams,\n ): Promise<VerifyResponse> => {\n return this.db.signInWithIdToken(params);\n };\n\n /**\n * Sign in with the id_token from an external provider like Google\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * db.auth\n * .exchangeOAuthCode({\n * // code received in redirect from OAuth callback\n * code: code\n * // The PKCE code_verifier, if any, that you used when you\n * // initiated the auth flow\n * codeVerifier: your_code_verifier\n * })\n * .catch((err) => console.error(err.body?.message));\n *\n */\n exchangeOAuthCode = (params: ExchangeCodeForTokenParams) => {\n return this.db.exchangeCodeForToken(params);\n };\n\n /**\n * OpenID Discovery path for use with tools like\n * expo-auth-session that use auto-discovery of\n * OAuth parameters.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const discovery = useAutoDiscovery(\n * db.auth.issuerURI()\n * );\n */\n issuerURI = (): string => {\n return this.db.issuerURI();\n };\n\n /**\n * Sign out the current user\n */\n signOut = (opts: SignoutOpts = { invalidateToken: true }): Promise<void> => {\n return this.db.signOut(opts);\n };\n}\n\ntype FileOpts = {\n contentType?: string;\n contentDisposition?: string;\n fileSize?: number; // Required for streaming uploads\n};\n\n/**\n * Functions to manage file storage.\n */\nclass Storage {\n constructor(private db: Reactor) {}\n\n /**\n * Uploads file at the provided path.\n *\n * @see https://instantdb.com/docs/storage\n * @example\n * const [file] = e.target.files; // result of file input\n * const data = await db.storage.uploadFile('photos/demo.png', file);\n */\n uploadFile = (\n path: string,\n file: File | Blob,\n opts: FileOpts = {},\n ): Promise<UploadFileResponse> => {\n return this.db.uploadFile(path, file, opts);\n };\n\n /**\n * Deletes a file by path name.\n *\n * @see https://instantdb.com/docs/storage\n * @example\n * await db.storage.delete('photos/demo.png');\n */\n delete = (pathname: string) => {\n return this.db.deleteFile(pathname);\n };\n\n // Deprecated Storage API (Jan 2025)\n // ---------------------------------\n\n /**\n * @deprecated. Use `db.storage.uploadFile` instead\n * remove in the future.\n */\n upload = (pathname: string, file: File) => {\n return this.db.upload(pathname, file);\n };\n\n /**\n * @deprecated Use `db.storage.uploadFile` instead\n */\n put = this.upload;\n\n /**\n * @deprecated. getDownloadUrl will be removed in the future.\n * Use `useQuery` instead to query and fetch for valid urls\n *\n * db.useQuery({\n * $files: {\n * $: {\n * where: {\n * path: \"moop.png\"\n * }\n * }\n * }\n * })\n */\n getDownloadUrl = (pathname: string) => {\n return this.db.getDownloadUrl(pathname);\n };\n}\n\n// util\n\nfunction coerceQuery(o: any) {\n // stringify and parse to remove undefined values\n return JSON.parse(JSON.stringify(o));\n}\n\nclass InstantCoreDatabase<\n Schema extends InstantSchemaDef<any, any, any>,\n UseDates extends boolean = false,\n> implements IInstantDatabase<Schema>\n{\n public _reactor: Reactor<RoomsOf<Schema>>;\n public auth: Auth;\n public storage: Storage;\n\n public tx = txInit<Schema>();\n\n constructor(reactor: Reactor<RoomsOf<Schema>>) {\n this._reactor = reactor;\n this.auth = new Auth(this._reactor);\n this.storage = new Storage(this._reactor);\n }\n\n /**\n * Use this to write data! You can create, update, delete, and link objects\n *\n * @see https://instantdb.com/docs/instaml\n *\n * @example\n * // Create a new object in the `goals` namespace\n * const goalId = id();\n * db.transact(db.tx.goals[goalId].update({title: \"Get fit\"}))\n *\n * // Update the title\n * db.transact(db.tx.goals[goalId].update({title: \"Get super fit\"}))\n *\n * // Delete it\n * db.transact(db.tx.goals[goalId].delete())\n *\n * // Or create an association:\n * todoId = id();\n * db.transact([\n * db.tx.todos[todoId].update({ title: 'Go on a run' }),\n * db.tx.goals[goalId].link({todos: todoId}),\n * ])\n */\n transact(\n chunks: TransactionChunk<any, any> | TransactionChunk<any, any>[],\n ): Promise<TransactionResult> {\n return this._reactor.pushTx(chunks);\n }\n\n getLocalId(name: string): Promise<string> {\n return this._reactor.getLocalId(name);\n }\n\n /**\n * Use this to query your data!\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n * // listen to all goals\n * db.subscribeQuery({ goals: {} }, (resp) => {\n * console.log(resp.data.goals)\n * })\n *\n * // goals where the title is \"Get Fit\"\n * db.subscribeQuery(\n * { goals: { $: { where: { title: \"Get Fit\" } } } },\n * (resp) => {\n * console.log(resp.data.goals)\n * }\n * )\n *\n * // all goals, _alongside_ their todos\n * db.subscribeQuery({ goals: { todos: {} } }, (resp) => {\n * console.log(resp.data.goals)\n * });\n */\n subscribeQuery<\n Q extends ValidQuery<Q, Schema>,\n UseDatesLocal extends boolean = UseDates,\n >(\n query: Q,\n cb: (resp: InstaQLSubscriptionState<Schema, Q, UseDatesLocal>) => void,\n opts?: InstaQLOptions,\n ) {\n return this._reactor.subscribeQuery(query, cb, opts);\n }\n\n /**\n * Listen for the logged in state. This is useful\n * for deciding when to show a login screen.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const unsub = db.subscribeAuth((auth) => {\n * if (auth.user) {\n * console.log('logged in as', auth.user.email)\n * } else {\n * console.log('logged out')\n * }\n * })\n */\n subscribeAuth(cb: (auth: AuthResult) => void): UnsubscribeFn {\n return this._reactor.subscribeAuth(cb);\n }\n\n /**\n * One time query for the logged in state. This is useful\n * for scenarios where you want to know the current auth\n * state without subscribing to changes.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const user = await db.getAuth();\n * console.log('logged in as', user.email)\n */\n getAuth(): Promise<User | null> {\n return this._reactor.getAuth();\n }\n\n /**\n * Listen for connection status changes to Instant. This is useful\n * for building things like connectivity indicators\n *\n * @see https://www.instantdb.com/docs/patterns#connection-status\n * @example\n * const unsub = db.subscribeConnectionStatus((status) => {\n * const connectionState =\n * status === 'connecting' || status === 'opened'\n * ? 'authenticating'\n * : status === 'authenticated'\n * ? 'connected'\n * : status === 'closed'\n * ? 'closed'\n * : status === 'errored'\n * ? 'errored'\n * : 'unexpected state';\n *\n * console.log('Connection status:', connectionState);\n * });\n */\n subscribeConnectionStatus(\n cb: (status: ConnectionStatus) => void,\n ): UnsubscribeFn {\n return this._reactor.subscribeConnectionStatus(cb);\n }\n\n /**\n * Join a room to publish and subscribe to topics and presence.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * // init\n * const db = init();\n * const room = db.joinRoom(roomType, roomId);\n * // usage\n * const unsubscribeTopic = room.subscribeTopic(\"foo\", console.log);\n * const unsubscribePresence = room.subscribePresence({}, console.log);\n * room.publishTopic(\"hello\", { message: \"hello world!\" });\n * room.publishPresence({ name: \"joe\" });\n * // later\n * unsubscribePresence();\n * unsubscribeTopic();\n * room.leaveRoom();\n */\n joinRoom<RoomType extends keyof RoomsOf<Schema>>(\n roomType: RoomType = '_defaultRoomType' as RoomType,\n roomId: string = '_defaultRoomId',\n opts?: {\n initialPresence?: Partial<PresenceOf<Schema, RoomType>>;\n },\n ): RoomHandle<PresenceOf<Schema, RoomType>, TopicsOf<Schema, RoomType>> {\n const leaveRoom = this._reactor.joinRoom(roomId, opts?.initialPresence);\n\n return {\n leaveRoom,\n subscribeTopic: (topic, onEvent) =>\n this._reactor.subscribeTopic(roomId, topic, onEvent),\n subscribePresence: (opts, onChange) =>\n this._reactor.subscribePresence(roomType, roomId, opts, onChange),\n publishTopic: (topic, data) =>\n this._reactor.publishTopic({ roomType, roomId, topic, data }),\n publishPresence: (data) =>\n this._reactor.publishPresence(roomType, roomId, data),\n getPresence: (opts) => this._reactor.getPresence(roomType, roomId, opts),\n };\n }\n\n shutdown() {\n delete globalInstantCoreStore[reactorKey(this._reactor.config)];\n this._reactor.shutdown();\n }\n\n /**\n * Use this for one-off queries.\n * Returns local data if available, otherwise fetches from the server.\n * Because we want to avoid stale data, this method will throw an error\n * if the user is offline or there is no active connection to the server.\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n *\n * const resp = await db.queryOnce({ goals: {} });\n * console.log(resp.data.goals)\n */\n queryOnce<Q extends ValidQuery<Q, Schema>>(\n query: Q,\n opts?: InstaQLOptions,\n ): Promise<{\n data: InstaQLResponse<Schema, Q, UseDates>;\n pageInfo: PageInfoResponse<Q>;\n }> {\n return this._reactor.queryOnce(query, opts);\n }\n\n /**\n * @deprecated This is an experimental function that is not yet ready for production use.\n * Use this function to sync an entire namespace.\n * It has many limitations that will be removed in the future:\n * 1. Must be used with an admin token\n * 2. Does not support permissions\n * 3. Does not support where clauses\n * 4. Does not support links\n * It also does not support multiple top-level namespaces. For example,\n * {posts: {}, users: {}} is invalid. Only `posts` or `users` is allowed, but not both.\n */\n _syncTableExperimental<Q extends ValidQuery<Q, Schema>>(\n query: ExactlyOne<Q>,\n cb: SyncTableCallback<Schema, Q, UseDates>,\n ): (\n opts?: { keepSubscription: boolean | null | undefined } | null | undefined,\n ) => void {\n return this._reactor.subscribeTable(query, cb);\n }\n}\n\nfunction schemaHash(schema?: InstantSchemaDef<any, any, any>): string {\n if (!schema) {\n return '0';\n }\n\n const fromStore = schemaHashStore.get(schema);\n if (fromStore) {\n return fromStore;\n }\n const hash = weakHash(schema);\n schemaHashStore.set(schema, hash);\n return hash;\n}\n\nfunction schemaChanged(\n existingClient: InstantCoreDatabase<any, boolean>,\n newSchema?: InstantSchemaDef<any, any, any>,\n): boolean {\n return (\n schemaHash(existingClient._reactor.config.schema) !== schemaHash(newSchema)\n );\n}\n\n/**\n *\n * The first step: init your application!\n *\n * Visit https://instantdb.com/dash to get your `appId` :)\n *\n * @example\n * import { init } from \"@instantdb/core\"\n *\n * const db = init({ appId: \"my-app-id\" })\n *\n * // You can also provide a schema for type safety and editor autocomplete!\n *\n * import { init } from \"@instantdb/core\"\n * import schema from \"\"../instant.schema.ts\";\n *\n * const db = init({ appId: \"my-app-id\", schema })\n *\n * // To learn more: https://instantdb.com/docs/modeling-data\n */\nfunction init<\n Schema extends InstantSchemaDef<any, any, any> = InstantUnknownSchema,\n UseDates extends boolean = false,\n>(\n // Allows config with missing `useDateObjects`, but keeps `UseDates`\n // as a non-nullable in the InstantConfig type.\n config: Omit<InstantConfig<Schema, UseDates>, 'useDateObjects'> & {\n useDateObjects?: UseDates;\n },\n Storage?: any,\n NetworkListener?: any,\n versions?: { [key: string]: string },\n EventSourceImpl?: any,\n): InstantCoreDatabase<Schema, UseDates> {\n const configStrict = {\n ...config,\n useDateObjects: (config.useDateObjects ?? false) as UseDates,\n };\n const existingClient = globalInstantCoreStore[\n reactorKey(configStrict)\n ] as InstantCoreDatabase<any, UseDates>;\n\n if (existingClient) {\n if (schemaChanged(existingClient, configStrict.schema)) {\n existingClient._reactor.updateSchema(configStrict.schema);\n }\n return existingClient;\n }\n\n const reactor = new Reactor<RoomsOf<Schema>>(\n {\n ...defaultConfig,\n ...configStrict,\n cardinalityInference: configStrict.schema ? true : false,\n },\n Storage || IndexedDBStorage,\n NetworkListener || WindowNetworkListener,\n { ...(versions || {}), '@instantdb/core': version },\n EventSourceImpl,\n );\n\n const client = new InstantCoreDatabase<any, UseDates>(reactor);\n globalInstantCoreStore[reactorKey(configStrict)] = client;\n\n handleDevtool(configStrict.appId, configStrict.devtool);\n\n return client;\n}\n\nfunction handleDevtool(\n appId: string,\n devtool: boolean | DevtoolConfig | null | undefined,\n) {\n if (\n typeof window === 'undefined' ||\n typeof window.location === 'undefined' ||\n typeof document === 'undefined'\n ) {\n return;\n }\n\n if (typeof devtool === 'boolean' && !devtool) {\n return;\n }\n\n const config: StrictDevtoolConfig = {\n position: 'bottom-right' as const,\n allowedHosts: ['localhost'],\n ...(typeof devtool === 'object' ? devtool : {}),\n };\n\n if (!config.allowedHosts.includes(window.location.hostname)) {\n return;\n }\n\n createDevtool(appId, config);\n}\n\n/**\n * @deprecated\n * `init_experimental` is deprecated. You can replace it with `init`.\n *\n * @example\n *\n * // Before\n * import { init_experimental } from \"@instantdb/core\"\n * const db = init_experimental({ ... });\n *\n * // After\n * import { init } from \"@instantdb/core\"\n * const db = init({ ... });\n */\nconst init_experimental = init;\n\nexport {\n // bada bing bada boom\n init,\n init_experimental,\n id,\n tx,\n txInit,\n lookup,\n validateQuery,\n QueryValidationError,\n validateTransactions,\n TransactionValidationError,\n\n // error\n InstantAPIError,\n\n // cli\n i,\n\n // util\n getOps,\n coerceQuery,\n weakHash,\n coerceToDate,\n IndexedDBStorage,\n WindowNetworkListener,\n InstantCoreDatabase,\n Auth,\n Storage,\n version,\n InstantError,\n\n // sync table enums\n SyncTableCallbackEventType,\n\n // og types\n type IDatabase,\n type RoomSchemaShape,\n type Query,\n type QueryResponse,\n type InstaQLResponse,\n type PageInfoResponse,\n type InstantObject,\n type Exactly,\n type TransactionChunk,\n type AuthState,\n type ConnectionStatus,\n type User,\n type AuthToken,\n type TxChunk,\n type SubscriptionState,\n type InstaQLSubscriptionState,\n type LifecycleSubscriptionState,\n type InstaQLLifecycleState,\n\n // presence types\n type PresenceOpts,\n type PresenceSlice,\n type PresenceResponse,\n type PresencePeer,\n\n // new query types\n type InstaQLParams,\n type ValidQuery,\n type InstaQLOptions,\n type InstaQLQueryParams,\n type InstantQuery,\n type InstantQueryResult,\n type InstantSchema,\n type InstantEntity,\n type InstantSchemaDatabase,\n type InstaQLFields,\n\n // schema types\n type AttrsDefs,\n type CardinalityKind,\n type DataAttrDef,\n type EntitiesDef,\n type InstantUnknownSchemaDef,\n type EntitiesWithLinks,\n type EntityDef,\n type RoomsDef,\n type InstantGraph,\n type LinkAttrDef,\n type LinkDef,\n type LinksDef,\n type ResolveAttrs,\n type ValueTypes,\n type RoomsOf,\n type PresenceOf,\n type TopicsOf,\n type TopicOf,\n type InstaQLEntity,\n type InstaQLResult,\n type InstaQLEntitySubquery,\n type InstantSchemaDef,\n type InstantUnknownSchema,\n type IInstantDatabase,\n type BackwardsCompatibleSchema,\n type InstantRules,\n type UpdateParams,\n type LinkParams,\n type CreateParams,\n type RuleParams,\n\n // attr types\n type InstantDBAttr,\n type InstantDBAttrOnDelete,\n type InstantDBCheckedDataType,\n type InstantDBIdent,\n type InstantDBInferredType,\n\n // auth types\n type ExchangeCodeForTokenParams,\n type SendMagicCodeParams,\n type SendMagicCodeResponse,\n type SignInWithIdTokenParams,\n type VerifyMagicCodeParams,\n type VerifyResponse,\n\n // storage types\n type FileOpts,\n type UploadFileResponse,\n type DeleteFileResponse,\n\n // SSE\n type EventSourceType,\n\n // sync table types\n type SyncTableCallback,\n type SyncTableCallbackEvent,\n type SyncTableInitialSyncBatch,\n type SyncTableInitialSyncComplete,\n type SyncTableSyncTransaction,\n type SyncTableLoadFromStorage,\n type SyncTableSetupError,\n\n // error types\n type InstantIssue,\n\n // storage (e.g. indexeddb) interface\n StorageInterface,\n type StorageInterfaceStoreName,\n};\n"]}
|
package/dist/esm/instaml.d.ts
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
export
|
|
4
|
-
|
|
1
|
+
import { AttrsStore, Store } from './store.ts';
|
|
2
|
+
import { IContainEntitiesAndLinks } from './schemaTypes.ts';
|
|
3
|
+
export type AttrMapping = {
|
|
4
|
+
attrIdMap: Record<string, string>;
|
|
5
|
+
refSwapAttrIds: Set<string>;
|
|
6
|
+
};
|
|
7
|
+
type TXStep = any[];
|
|
8
|
+
export declare function rewriteStep(attrMapping: AttrMapping, txStep: TXStep): TXStep;
|
|
9
|
+
type Ctx = {
|
|
10
|
+
stores?: (Store | undefined)[];
|
|
11
|
+
attrsStore: AttrsStore;
|
|
12
|
+
schema?: Schema;
|
|
13
|
+
useDateObjects?: boolean | null;
|
|
14
|
+
};
|
|
15
|
+
type Schema = IContainEntitiesAndLinks<any, any>;
|
|
16
|
+
export declare function transform(ctx: Ctx, inputChunks: any): TXStep[];
|
|
17
|
+
export {};
|
|
5
18
|
//# sourceMappingURL=instaml.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instaml.d.ts","sourceRoot":"","sources":["../../src/instaml.
|
|
1
|
+
{"version":3,"file":"instaml.d.ts","sourceRoot":"","sources":["../../src/instaml.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,UAAU,EAIV,KAAK,EACN,MAAM,YAAY,CAAC;AAKpB,OAAO,EAEL,wBAAwB,EAEzB,MAAM,kBAAkB,CAAC;AAG1B,MAAM,MAAM,WAAW,GAAG;IACxB,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAClC,cAAc,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CAC7B,CAAC;AAEF,KAAK,MAAM,GAAG,GAAG,EAAE,CAAC;AAGpB,wBAAgB,WAAW,CAAC,WAAW,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CA4B5E;AAgMD,KAAK,GAAG,GAAG;IACT,MAAM,CAAC,EAAE,CAAC,KAAK,GAAG,SAAS,CAAC,EAAE,CAAC;IAC/B,UAAU,EAAE,UAAU,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,cAAc,CAAC,EAAE,OAAO,GAAG,IAAI,CAAC;CACjC,CAAC;AAuLF,KAAK,MAAM,GAAG,wBAAwB,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;AA+QjD,wBAAgB,SAAS,CAAC,GAAG,EAAE,GAAG,EAAE,WAAW,KAAA,YAO9C"}
|
package/dist/esm/instaml.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { allMapValues } from "./store.js";
|
|
1
|
+
import { allMapValues, AttrsStoreClass, getAttrByFwdIdentName, getAttrByReverseIdentName, } from "./store.js";
|
|
2
2
|
import { getOps, isLookup, parseLookup } from "./instatx.js";
|
|
3
3
|
import { immutableRemoveUndefined } from './utils/object.js';
|
|
4
4
|
import { coerceToDate } from "./utils/dates.js";
|
|
@@ -32,21 +32,6 @@ export function rewriteStep(attrMapping, txStep) {
|
|
|
32
32
|
}
|
|
33
33
|
return rewritten;
|
|
34
34
|
}
|
|
35
|
-
export function getAttrByFwdIdentName(attrs, inputEtype, inputIdentName) {
|
|
36
|
-
return Object.values(attrs).find((attr) => {
|
|
37
|
-
const [_id, etype, label] = attr['forward-identity'];
|
|
38
|
-
return etype === inputEtype && label === inputIdentName;
|
|
39
|
-
});
|
|
40
|
-
}
|
|
41
|
-
export function getAttrByReverseIdentName(attrs, inputEtype, inputIdentName) {
|
|
42
|
-
return Object.values(attrs).find((attr) => {
|
|
43
|
-
const revIdent = attr['reverse-identity'];
|
|
44
|
-
if (!revIdent)
|
|
45
|
-
return false;
|
|
46
|
-
const [_id, etype, label] = revIdent;
|
|
47
|
-
return etype === inputEtype && label === inputIdentName;
|
|
48
|
-
});
|
|
49
|
-
}
|
|
50
35
|
function explodeLookupRef(eid) {
|
|
51
36
|
if (Array.isArray(eid)) {
|
|
52
37
|
return eid;
|
|
@@ -105,6 +90,7 @@ function extractLookup(attrs, etype, eid) {
|
|
|
105
90
|
return [attr.id, value];
|
|
106
91
|
}
|
|
107
92
|
function withIdAttrForLookup(attrs, etype, eidA, txSteps) {
|
|
93
|
+
var _b;
|
|
108
94
|
const lookup = extractLookup(attrs, etype, eidA);
|
|
109
95
|
if (!Array.isArray(lookup)) {
|
|
110
96
|
return txSteps;
|
|
@@ -112,60 +98,69 @@ function withIdAttrForLookup(attrs, etype, eidA, txSteps) {
|
|
|
112
98
|
const idTuple = [
|
|
113
99
|
'add-triple',
|
|
114
100
|
lookup,
|
|
115
|
-
getAttrByFwdIdentName(attrs, etype, 'id').id,
|
|
101
|
+
(_b = getAttrByFwdIdentName(attrs, etype, 'id')) === null || _b === void 0 ? void 0 : _b.id,
|
|
116
102
|
lookup,
|
|
117
103
|
];
|
|
118
104
|
return [idTuple].concat(txSteps);
|
|
119
105
|
}
|
|
120
|
-
function expandLink({
|
|
106
|
+
function expandLink({ attrsStore }, [etype, eidA, obj]) {
|
|
121
107
|
const addTriples = Object.entries(obj).flatMap(([label, eidOrEids]) => {
|
|
122
108
|
const eids = Array.isArray(eidOrEids) ? eidOrEids : [eidOrEids];
|
|
123
|
-
const fwdAttr = getAttrByFwdIdentName(
|
|
124
|
-
const revAttr = getAttrByReverseIdentName(
|
|
109
|
+
const fwdAttr = getAttrByFwdIdentName(attrsStore, etype, label);
|
|
110
|
+
const revAttr = getAttrByReverseIdentName(attrsStore, etype, label);
|
|
125
111
|
return eids.map((eidB) => {
|
|
126
112
|
const txStep = fwdAttr
|
|
127
113
|
? [
|
|
128
114
|
'add-triple',
|
|
129
|
-
extractLookup(
|
|
115
|
+
extractLookup(attrsStore, etype, eidA),
|
|
130
116
|
fwdAttr.id,
|
|
131
|
-
|
|
117
|
+
// Uses `!` because if we get here, we should have created the attr if it doesn't
|
|
118
|
+
// already exist
|
|
119
|
+
extractLookup(attrsStore, fwdAttr['reverse-identity'][1], eidB),
|
|
132
120
|
]
|
|
133
121
|
: [
|
|
134
122
|
'add-triple',
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
extractLookup(
|
|
123
|
+
// Uses `!` because if we get here, we should have created the attr if it doesn't
|
|
124
|
+
// already exist
|
|
125
|
+
extractLookup(attrsStore, revAttr['forward-identity'][1], eidB),
|
|
126
|
+
revAttr === null || revAttr === void 0 ? void 0 : revAttr.id,
|
|
127
|
+
extractLookup(attrsStore, etype, eidA),
|
|
138
128
|
];
|
|
139
129
|
return txStep;
|
|
140
130
|
});
|
|
141
131
|
});
|
|
142
|
-
return withIdAttrForLookup(
|
|
132
|
+
return withIdAttrForLookup(attrsStore, etype, eidA, addTriples);
|
|
143
133
|
}
|
|
144
|
-
function expandUnlink({
|
|
134
|
+
function expandUnlink({ attrsStore }, [etype, eidA, obj]) {
|
|
145
135
|
const retractTriples = Object.entries(obj).flatMap(([label, eidOrEids]) => {
|
|
146
136
|
const eids = Array.isArray(eidOrEids) ? eidOrEids : [eidOrEids];
|
|
147
|
-
const fwdAttr = getAttrByFwdIdentName(
|
|
148
|
-
const revAttr = getAttrByReverseIdentName(
|
|
137
|
+
const fwdAttr = getAttrByFwdIdentName(attrsStore, etype, label);
|
|
138
|
+
const revAttr = getAttrByReverseIdentName(attrsStore, etype, label);
|
|
149
139
|
return eids.map((eidB) => {
|
|
150
140
|
const txStep = fwdAttr
|
|
151
141
|
? [
|
|
152
142
|
'retract-triple',
|
|
153
|
-
extractLookup(
|
|
143
|
+
extractLookup(attrsStore, etype, eidA),
|
|
154
144
|
fwdAttr.id,
|
|
155
|
-
|
|
145
|
+
// Uses `!` because if we get here, we should have created the attr if it doesn't
|
|
146
|
+
// already exist
|
|
147
|
+
extractLookup(attrsStore, fwdAttr['reverse-identity'][1], eidB),
|
|
156
148
|
]
|
|
157
149
|
: [
|
|
158
150
|
'retract-triple',
|
|
159
|
-
|
|
151
|
+
// Uses `!` because if we get here, we should have created the attr if it doesn't
|
|
152
|
+
// already exist
|
|
153
|
+
extractLookup(attrsStore, revAttr['forward-identity'][1], eidB),
|
|
160
154
|
revAttr.id,
|
|
161
|
-
extractLookup(
|
|
155
|
+
extractLookup(attrsStore, etype, eidA),
|
|
162
156
|
];
|
|
163
157
|
return txStep;
|
|
164
158
|
});
|
|
165
159
|
});
|
|
166
|
-
return withIdAttrForLookup(
|
|
160
|
+
return withIdAttrForLookup(attrsStore, etype, eidA, retractTriples);
|
|
167
161
|
}
|
|
168
|
-
function checkEntityExists(stores, etype, eid) {
|
|
162
|
+
function checkEntityExists(stores, attrsStore, etype, eid) {
|
|
163
|
+
var _b;
|
|
169
164
|
if (Array.isArray(eid)) {
|
|
170
165
|
// lookup ref
|
|
171
166
|
const [entity_a, entity_v] = eid;
|
|
@@ -173,7 +168,7 @@ function checkEntityExists(stores, etype, eid) {
|
|
|
173
168
|
const ev = store === null || store === void 0 ? void 0 : store.aev.get(entity_a);
|
|
174
169
|
if (ev) {
|
|
175
170
|
// This would be a lot more efficient with a ave index
|
|
176
|
-
for (const [
|
|
171
|
+
for (const [_e, _a, v] of allMapValues(ev, 2)) {
|
|
177
172
|
if (v === entity_v) {
|
|
178
173
|
return true;
|
|
179
174
|
}
|
|
@@ -187,7 +182,7 @@ function checkEntityExists(stores, etype, eid) {
|
|
|
187
182
|
const av = store === null || store === void 0 ? void 0 : store.eav.get(eid);
|
|
188
183
|
if (av) {
|
|
189
184
|
for (const attr_id of av.keys()) {
|
|
190
|
-
if (
|
|
185
|
+
if (((_b = attrsStore.getAttr(attr_id)) === null || _b === void 0 ? void 0 : _b['forward-identity'][1]) == etype) {
|
|
191
186
|
return true;
|
|
192
187
|
}
|
|
193
188
|
}
|
|
@@ -196,25 +191,26 @@ function checkEntityExists(stores, etype, eid) {
|
|
|
196
191
|
}
|
|
197
192
|
return false;
|
|
198
193
|
}
|
|
199
|
-
function convertOpts({ stores,
|
|
194
|
+
function convertOpts({ stores, attrsStore }, [etype, eid, obj_, opts]) {
|
|
200
195
|
return (opts === null || opts === void 0 ? void 0 : opts.upsert) === false
|
|
201
196
|
? { mode: 'update' }
|
|
202
197
|
: (opts === null || opts === void 0 ? void 0 : opts.upsert) === true
|
|
203
198
|
? null
|
|
204
|
-
: checkEntityExists(stores, etype, eid)
|
|
199
|
+
: checkEntityExists(stores, attrsStore, etype, eid)
|
|
205
200
|
? { mode: 'update' }
|
|
206
201
|
: null; // auto mode chooses between update and upsert, not update and create, just in case
|
|
207
202
|
}
|
|
208
203
|
function expandCreate(ctx, step) {
|
|
209
|
-
const {
|
|
204
|
+
const { attrsStore } = ctx;
|
|
210
205
|
const [etype, eid, obj_, opts] = step;
|
|
211
206
|
const obj = immutableRemoveUndefined(obj_);
|
|
212
|
-
const lookup = extractLookup(
|
|
207
|
+
const lookup = extractLookup(attrsStore, etype, eid);
|
|
213
208
|
// id first so that we don't clobber updates on the lookup field
|
|
214
209
|
const attrTuples = [['id', lookup]]
|
|
215
210
|
.concat(Object.entries(obj))
|
|
216
211
|
.map(([identName, value]) => {
|
|
217
|
-
|
|
212
|
+
// Uses `!` because we should have optimistically created the attr if it doesn't exist
|
|
213
|
+
const attr = getAttrByFwdIdentName(attrsStore, etype, identName);
|
|
218
214
|
if (attr['checked-data-type'] === 'date' && ctx.useDateObjects) {
|
|
219
215
|
value = coerceToDate(value);
|
|
220
216
|
}
|
|
@@ -223,16 +219,16 @@ function expandCreate(ctx, step) {
|
|
|
223
219
|
return attrTuples;
|
|
224
220
|
}
|
|
225
221
|
function expandUpdate(ctx, step) {
|
|
226
|
-
const {
|
|
222
|
+
const { attrsStore } = ctx;
|
|
227
223
|
const [etype, eid, obj_, opts] = step;
|
|
228
224
|
const obj = immutableRemoveUndefined(obj_);
|
|
229
|
-
const lookup = extractLookup(
|
|
225
|
+
const lookup = extractLookup(attrsStore, etype, eid);
|
|
230
226
|
const serverOpts = convertOpts(ctx, [etype, lookup, obj_, opts]);
|
|
231
227
|
// id first so that we don't clobber updates on the lookup field
|
|
232
228
|
const attrTuples = [['id', lookup]]
|
|
233
229
|
.concat(Object.entries(obj))
|
|
234
230
|
.map(([identName, value]) => {
|
|
235
|
-
const attr = getAttrByFwdIdentName(
|
|
231
|
+
const attr = getAttrByFwdIdentName(attrsStore, etype, identName);
|
|
236
232
|
if (attr['checked-data-type'] === 'date' && ctx.useDateObjects) {
|
|
237
233
|
value = coerceToDate(value);
|
|
238
234
|
}
|
|
@@ -246,18 +242,18 @@ function expandUpdate(ctx, step) {
|
|
|
246
242
|
});
|
|
247
243
|
return attrTuples;
|
|
248
244
|
}
|
|
249
|
-
function expandDelete({
|
|
250
|
-
const lookup = extractLookup(
|
|
245
|
+
function expandDelete({ attrsStore }, [etype, eid]) {
|
|
246
|
+
const lookup = extractLookup(attrsStore, etype, eid);
|
|
251
247
|
return [['delete-entity', lookup, etype]];
|
|
252
248
|
}
|
|
253
249
|
function expandDeepMerge(ctx, step) {
|
|
254
|
-
const {
|
|
250
|
+
const { attrsStore } = ctx;
|
|
255
251
|
const [etype, eid, obj_, opts] = step;
|
|
256
252
|
const obj = immutableRemoveUndefined(obj_);
|
|
257
|
-
const lookup = extractLookup(
|
|
253
|
+
const lookup = extractLookup(attrsStore, etype, eid);
|
|
258
254
|
const serverOpts = convertOpts(ctx, [etype, lookup, obj_, opts]);
|
|
259
255
|
const attrTuples = Object.entries(obj).map(([identName, value]) => {
|
|
260
|
-
const attr = getAttrByFwdIdentName(
|
|
256
|
+
const attr = getAttrByFwdIdentName(attrsStore, etype, identName);
|
|
261
257
|
return [
|
|
262
258
|
'deep-merge-triple',
|
|
263
259
|
lookup,
|
|
@@ -269,15 +265,15 @@ function expandDeepMerge(ctx, step) {
|
|
|
269
265
|
const idTuple = [
|
|
270
266
|
'add-triple',
|
|
271
267
|
lookup,
|
|
272
|
-
getAttrByFwdIdentName(
|
|
268
|
+
getAttrByFwdIdentName(attrsStore, etype, 'id').id,
|
|
273
269
|
lookup,
|
|
274
270
|
...(serverOpts ? [serverOpts] : []),
|
|
275
271
|
];
|
|
276
272
|
// id first so that we don't clobber updates on the lookup field
|
|
277
273
|
return [idTuple].concat(attrTuples);
|
|
278
274
|
}
|
|
279
|
-
function expandRuleParams({
|
|
280
|
-
const lookup = extractLookup(
|
|
275
|
+
function expandRuleParams({ attrsStore }, [etype, eid, ruleParams]) {
|
|
276
|
+
const lookup = extractLookup(attrsStore, etype, eid);
|
|
281
277
|
return [['rule-params', lookup, etype, ruleParams]];
|
|
282
278
|
}
|
|
283
279
|
function removeIdFromArgs(step) {
|
|
@@ -324,8 +320,8 @@ function checkedDataTypeOfValueType(valueType) {
|
|
|
324
320
|
}
|
|
325
321
|
}
|
|
326
322
|
function objectPropsFromSchema(schema, etype, label) {
|
|
327
|
-
var
|
|
328
|
-
const attr = (
|
|
323
|
+
var _b, _c;
|
|
324
|
+
const attr = (_c = (_b = schema.entities[etype]) === null || _b === void 0 ? void 0 : _b.attrs) === null || _c === void 0 ? void 0 : _c[label];
|
|
329
325
|
if (label === 'id')
|
|
330
326
|
return null;
|
|
331
327
|
if (!attr) {
|
|
@@ -349,7 +345,8 @@ function createObjectAttr(schema, etype, label, props) {
|
|
|
349
345
|
return Object.assign(Object.assign({ id: attrId, 'forward-identity': fwdIdent, 'value-type': 'blob', cardinality: 'one', 'unique?': false, 'index?': false, isUnsynced: true }, (schemaObjectProps || {})), (props || {}));
|
|
350
346
|
}
|
|
351
347
|
function findSchemaLink(schema, etype, label) {
|
|
352
|
-
const
|
|
348
|
+
const links = Object.values(schema.links);
|
|
349
|
+
const found = links.find((x) => {
|
|
353
350
|
return ((x.forward.on === etype && x.forward.label === label) ||
|
|
354
351
|
(x.reverse.on === etype && x.reverse.label === label));
|
|
355
352
|
});
|
|
@@ -377,7 +374,13 @@ function createRefAttr(schema, etype, label, props) {
|
|
|
377
374
|
const attrId = uuid();
|
|
378
375
|
const fwdIdent = [uuid(), etype, label];
|
|
379
376
|
const revIdent = [uuid(), label, etype];
|
|
380
|
-
return Object.assign(Object.assign({ id: attrId,
|
|
377
|
+
return Object.assign(Object.assign({ id: attrId,
|
|
378
|
+
// @ts-ignore: ts thinks it's any[]
|
|
379
|
+
'forward-identity': fwdIdent,
|
|
380
|
+
// @ts-ignore: ts thinks it's any[]
|
|
381
|
+
'reverse-identity': revIdent, 'value-type': 'ref',
|
|
382
|
+
// @ts-ignore: ts thinks it's type string
|
|
383
|
+
cardinality: 'many', 'unique?': false, 'index?': false, isUnsynced: true }, (schemaRefProps || {})), (props || {}));
|
|
381
384
|
}
|
|
382
385
|
// Actions that have an object, e.g. not delete
|
|
383
386
|
const OBJ_ACTIONS = new Set(['create', 'update', 'merge', 'link', 'unlink']);
|
|
@@ -421,24 +424,49 @@ function lookupPairsOfOp(op) {
|
|
|
421
424
|
}
|
|
422
425
|
return res;
|
|
423
426
|
}
|
|
424
|
-
function createMissingAttrs({
|
|
425
|
-
var
|
|
426
|
-
const
|
|
427
|
+
function createMissingAttrs({ attrsStore, schema }, ops) {
|
|
428
|
+
var _b, _c;
|
|
429
|
+
const addedIds = new Set();
|
|
430
|
+
const localAttrs = [];
|
|
431
|
+
const addOps = [];
|
|
432
|
+
function attrByFwdIdent(etype, label) {
|
|
433
|
+
return (getAttrByFwdIdentName(attrsStore, etype, label) ||
|
|
434
|
+
localAttrs.find((x) => x['forward-identity'][1] === etype &&
|
|
435
|
+
x['forward-identity'][2] === label));
|
|
436
|
+
}
|
|
437
|
+
function attrByRevIdent(etype, label) {
|
|
438
|
+
return (getAttrByReverseIdentName(attrsStore, etype, label) ||
|
|
439
|
+
localAttrs.find((x) => {
|
|
440
|
+
var _b, _c;
|
|
441
|
+
return ((_b = x['reverse-identity']) === null || _b === void 0 ? void 0 : _b[1]) === etype &&
|
|
442
|
+
((_c = x['reverse-identity']) === null || _c === void 0 ? void 0 : _c[2]) === label;
|
|
443
|
+
}));
|
|
444
|
+
}
|
|
427
445
|
function addAttr(attr) {
|
|
428
|
-
|
|
446
|
+
localAttrs.push(attr);
|
|
429
447
|
addOps.push(['add-attr', attr]);
|
|
430
448
|
addedIds.add(attr.id);
|
|
431
449
|
}
|
|
432
450
|
function addUnsynced(attr) {
|
|
433
|
-
if (
|
|
451
|
+
if (attr &&
|
|
452
|
+
'isUnsynced' in attr &&
|
|
453
|
+
attr.isUnsynced &&
|
|
454
|
+
!addedIds.has(attr.id)) {
|
|
455
|
+
localAttrs.push(attr);
|
|
434
456
|
addOps.push(['add-attr', attr]);
|
|
435
457
|
addedIds.add(attr.id);
|
|
436
458
|
}
|
|
437
459
|
}
|
|
460
|
+
function isRefLookupIdentLocal(etype, identName) {
|
|
461
|
+
return (identName.indexOf('.') !== -1 &&
|
|
462
|
+
// attr names can have `.` in them, so use the attr we find with a `.`
|
|
463
|
+
// before assuming it's a ref lookup.
|
|
464
|
+
!attrByFwdIdent(etype, identName));
|
|
465
|
+
}
|
|
438
466
|
// Adds attrs needed for a ref lookup
|
|
439
467
|
function addForRef(etype, label) {
|
|
440
|
-
const fwdAttr =
|
|
441
|
-
const revAttr =
|
|
468
|
+
const fwdAttr = attrByFwdIdent(etype, label);
|
|
469
|
+
const revAttr = attrByRevIdent(etype, label);
|
|
442
470
|
addUnsynced(fwdAttr);
|
|
443
471
|
addUnsynced(revAttr);
|
|
444
472
|
if (!fwdAttr && !revAttr) {
|
|
@@ -458,29 +486,29 @@ function createMissingAttrs({ attrs: existingAttrs, schema }, ops) {
|
|
|
458
486
|
addForRef(etype, linkLabel);
|
|
459
487
|
// Figure out the link etype so we can make sure we have the attrs
|
|
460
488
|
// for the link lookup
|
|
461
|
-
const fwdAttr =
|
|
462
|
-
const revAttr =
|
|
489
|
+
const fwdAttr = attrByFwdIdent(etype, linkLabel);
|
|
490
|
+
const revAttr = attrByRevIdent(etype, linkLabel);
|
|
463
491
|
addUnsynced(fwdAttr);
|
|
464
492
|
addUnsynced(revAttr);
|
|
465
|
-
const linkEtype = ((
|
|
466
|
-
((
|
|
493
|
+
const linkEtype = ((_b = fwdAttr === null || fwdAttr === void 0 ? void 0 : fwdAttr['reverse-identity']) === null || _b === void 0 ? void 0 : _b[1]) ||
|
|
494
|
+
((_c = revAttr === null || revAttr === void 0 ? void 0 : revAttr['forward-identity']) === null || _c === void 0 ? void 0 : _c[1]) ||
|
|
467
495
|
linkLabel;
|
|
468
|
-
if (
|
|
496
|
+
if (isRefLookupIdentLocal(linkEtype, identName)) {
|
|
469
497
|
addForRef(linkEtype, extractRefLookupFwdName(identName));
|
|
470
498
|
}
|
|
471
499
|
else {
|
|
472
|
-
const attr =
|
|
500
|
+
const attr = attrByFwdIdent(linkEtype, identName);
|
|
473
501
|
if (!attr) {
|
|
474
502
|
addAttr(createObjectAttr(schema, linkEtype, identName, lookupProps));
|
|
475
503
|
}
|
|
476
504
|
addUnsynced(attr);
|
|
477
505
|
}
|
|
478
506
|
}
|
|
479
|
-
else if (
|
|
507
|
+
else if (isRefLookupIdentLocal(etype, identName)) {
|
|
480
508
|
addForRef(etype, extractRefLookupFwdName(identName));
|
|
481
509
|
}
|
|
482
510
|
else {
|
|
483
|
-
const attr =
|
|
511
|
+
const attr = attrByFwdIdent(etype, identName);
|
|
484
512
|
if (!attr) {
|
|
485
513
|
addAttr(createObjectAttr(schema, etype, identName, lookupProps));
|
|
486
514
|
}
|
|
@@ -492,13 +520,13 @@ function createMissingAttrs({ attrs: existingAttrs, schema }, ops) {
|
|
|
492
520
|
for (const op of ops) {
|
|
493
521
|
const [action, etype, eid, obj] = op;
|
|
494
522
|
if (OBJ_ACTIONS.has(action)) {
|
|
495
|
-
const idAttr =
|
|
523
|
+
const idAttr = attrByFwdIdent(etype, 'id');
|
|
496
524
|
addUnsynced(idAttr);
|
|
497
525
|
if (!idAttr) {
|
|
498
526
|
addAttr(createObjectAttr(schema, etype, 'id', { 'unique?': true }));
|
|
499
527
|
}
|
|
500
528
|
for (const label of Object.keys(obj)) {
|
|
501
|
-
const fwdAttr =
|
|
529
|
+
const fwdAttr = attrByFwdIdent(etype, label);
|
|
502
530
|
addUnsynced(fwdAttr);
|
|
503
531
|
if (UPDATE_ACTIONS.has(action)) {
|
|
504
532
|
if (!fwdAttr) {
|
|
@@ -506,7 +534,7 @@ function createMissingAttrs({ attrs: existingAttrs, schema }, ops) {
|
|
|
506
534
|
}
|
|
507
535
|
}
|
|
508
536
|
if (REF_ACTIONS.has(action)) {
|
|
509
|
-
const revAttr =
|
|
537
|
+
const revAttr = attrByRevIdent(etype, label);
|
|
510
538
|
if (!fwdAttr && !revAttr) {
|
|
511
539
|
addAttr(createRefAttr(schema, etype, label));
|
|
512
540
|
}
|
|
@@ -515,13 +543,20 @@ function createMissingAttrs({ attrs: existingAttrs, schema }, ops) {
|
|
|
515
543
|
}
|
|
516
544
|
}
|
|
517
545
|
}
|
|
518
|
-
|
|
546
|
+
if (localAttrs.length) {
|
|
547
|
+
const nextAttrs = Object.assign({}, attrsStore.attrs);
|
|
548
|
+
for (const attr of localAttrs) {
|
|
549
|
+
nextAttrs[attr.id] = attr;
|
|
550
|
+
}
|
|
551
|
+
return [new AttrsStoreClass(nextAttrs, attrsStore.linkIndex), addOps];
|
|
552
|
+
}
|
|
553
|
+
return [attrsStore, addOps];
|
|
519
554
|
}
|
|
520
555
|
export function transform(ctx, inputChunks) {
|
|
521
556
|
const chunks = Array.isArray(inputChunks) ? inputChunks : [inputChunks];
|
|
522
557
|
const ops = chunks.flatMap((tx) => getOps(tx));
|
|
523
558
|
const [newAttrs, addAttrTxSteps] = createMissingAttrs(ctx, ops);
|
|
524
|
-
const newCtx = Object.assign(Object.assign({}, ctx), {
|
|
559
|
+
const newCtx = Object.assign(Object.assign({}, ctx), { attrsStore: newAttrs });
|
|
525
560
|
const txSteps = ops.flatMap((op) => toTxSteps(newCtx, op));
|
|
526
561
|
return [...addAttrTxSteps, ...txSteps];
|
|
527
562
|
}
|