import type { Readable } from 'node:stream'; import { tx, lookup, i, id, InstantAPIError, setInstantWarningsEnabled, type InstantIssue, type TransactionChunk, type AuthToken, type User, type Query, InstantError, type QueryResponse, type InstaQLResponse, type InstaQLParams, type ValidQuery, type InstaQLFields, type InstantQuery, type InstantQueryResult, type InstantSchema, type InstantSchemaDatabase, type InstantObject, type InstantEntity, type BackwardsCompatibleSchema, type IInstantDatabase, type AttrsDefs, type CardinalityKind, type DataAttrDef, type EntitiesDef, type EntitiesWithLinks, type EntityDef, type InstantGraph, type LinkAttrDef, type LinkDef, type InstantUnknownSchemaDef, type LinksDef, type RoomsOf, type RoomsDef, type PresenceOf, type RoomHandle, type ResolveAttrs, type ValueTypes, type InstantSchemaDef, type InstantUnknownSchema, type InstaQLEntity, type InstaQLResult, type InstaQLEntitySubquery, type InstantRules, type UpdateParams, type CreateParams, type LinkParams, type RuleParams, type FileOpts, type UploadFileResponse, type DeleteFileResponse, createInstantRouteHandler, InstantStream, type WritableStreamCtor, type ReadableStreamCtor, InstantWritableStream, InstantReadableStream } from '@instantdb/core'; import { SubscribeQueryCallback, SubscribeQueryResponse, SubscribeQueryPayload, SubscriptionReadyState } from './subscribe.ts'; import { Webhooks, WebhooksManager, type WebhookAction, type WebhookStatus, type WebhookEventStatus, type WebhookInfo, type WebhookAttempt, type WebhookEventInfo, type WebhookEventsPage, type WebhookBody, type WebhookEntity, type WebhookPayload, type WebhookPayloadRecord, type WebhookPayloadRecordFor, type WebhookHandlerFn, type WebhookHandlers, type WebhookHelpers, type CreateWebhookParams, type UpdateWebhookParams } from '@instantdb/webhooks'; type DebugCheckResult = { /** The ID of the record. */ id: string; /** The namespace/table of the record. */ entity: string; /** The value of the record. */ record: Record; /** The result of evaluating the corresponding permissions rule for a record. */ check: any; }; type Config = { appId: string; adminToken?: string; apiURI?: string; useDateObjects?: boolean; disableValidation?: boolean; verbose?: boolean; }; export type InstantConfig, UseDates extends boolean = false> = { appId: string; adminToken?: string; apiURI?: string; schema?: Schema; useDateObjects: UseDates; disableValidation?: boolean; verbose?: boolean; WritableStream?: WritableStreamCtor; ReadableStream?: ReadableStreamCtor; }; type InstantConfigFilled, UseDates extends boolean> = InstantConfig & { apiURI: string; }; type FilledConfig = Config & { apiURI: string; }; type ImpersonationOpts = { email: string; } | { token: AuthToken; } | { guest: boolean; }; type DebugTransactResult = { 'tx-id': number; 'all-checks-ok?': boolean; }; /** * * The first step: init your application! * * Visit https://instantdb.com/dash to get your `appId` :) * * @example * import { init } from "@instantdb/admin" * * const db = init({ * appId: process.env.INSTANT_APP_ID!, * adminToken: process.env.INSTANT_APP_ADMIN_TOKEN * }) * * // You can also provide a schema for type safety and editor autocomplete! * * import { init } from "@instantdb/admin" * import schema from ""../instant.schema.ts"; * * const db = init({ * appId: process.env.INSTANT_APP_ID!, * adminToken: process.env.INSTANT_APP_ADMIN_TOKEN, * schema, * }) * // To learn more: https://instantdb.com/docs/modeling-data */ declare function init = InstantUnknownSchema, UseDates extends boolean = false>(config: Omit, 'useDateObjects'> & { useDateObjects?: UseDates; }): InstantAdminDatabase>; /** * @deprecated * `init_experimental` is deprecated. You can replace it with `init`. * * @example * * // Before * import { init_experimental } from "@instantdb/admin" * const db = init_experimental({ ... }); * * // After * import { init } from "@instantdb/admin" * const db = init({ ... }); */ declare const init_experimental: typeof init; type PresenceResult = { [peerId: string]: { data: Data; 'peer-id': string; user: User | null; }; }; declare class Rooms> { config: FilledConfig; constructor(config: FilledConfig); getPresence>(roomType: RoomType, roomId: string): Promise>>; } declare class Auth> { config: FilledConfig; constructor(config: FilledConfig); /** * Generates a magic code for the user with the given email. * This is useful if you want to use your own email provider * to send magic codes. * * @example * // Generate a magic code * const { code } = await db.auth.generateMagicCode({ email }) * // Send the magic code to the user with your own email provider * await customEmailProvider.sendMagicCode(email, code) * * @see https://instantdb.com/docs/backend#custom-magic-codes */ generateMagicCode: (email: string) => Promise<{ code: string; }>; /** * Sends a magic code to the user with the given email. * This uses Instant's built-in email provider. * * @example * // Send an email to user with magic code * await db.auth.sendMagicCode({ email }) * * @see https://instantdb.com/docs/backend#custom-magic-codes */ sendMagicCode: (email: string) => Promise<{ code: string; }>; /** * @deprecated Use {@link checkMagicCode} instead to get the `created` field * and support `extraFields`. * * @see https://instantdb.com/docs/backend#custom-magic-codes */ verifyMagicCode: (email: string, code: string) => Promise; /** * Verifies a magic code and returns the user along with whether * the user was newly created. Supports `extraFields` to set custom * `$users` properties at signup. * * @example * const { user, created } = await db.auth.checkMagicCode( * email, * code, * { extraFields: { nickname: 'ari' } }, * ); * * @see https://instantdb.com/docs/backend#custom-magic-codes */ checkMagicCode: (email: string, code: string, options?: { extraFields?: UpdateParams; }) => Promise<{ user: User; created: boolean; }>; /** * Creates a login token for the user with the given email. * If that user does not exist, we create one. * * This is often useful for writing custom auth flows. * * @example * app.post('/custom_sign_in', async (req, res) => { * // ... your custom flow for users * const token = await db.auth.createToken({ email }) * return res.status(200).send({ token }) * }) * * @see https://instantdb.com/docs/backend#custom-auth */ createToken(email: { email: string; } | { id: string; }): Promise; /** * * @deprecated Passing an email string directly is deprecated. * * Use an object with the `email` key instead. * * @example * // Before * const token = await auth.createToken(email) * // After * const token = await auth.createToken({ email }) */ createToken(email: string): Promise; /** * Verifies a given token and returns the associated user. * * This is often useful for writing custom endpoints, where you need * to authenticate users. * * @example * app.post('/custom_endpoint', async (req, res) => { * const user = await db.auth.verifyToken(req.headers['token']) * if (!user) { * return res.status(401).send('Uh oh, you are not authenticated') * } * // ... * }) * @see https://instantdb.com/docs/backend#custom-endpoints */ verifyToken: (token: AuthToken) => Promise; /** * Retrieves an app user by id, email, or refresh token. * Resolves to `null` when no user matches; throws on malformed * input or auth errors. * * @example * const user = await db.auth.getUser({ email }); * if (!user) { * console.log("No user found"); * return; * } * console.log("Found user:", user); * * @see https://instantdb.com/docs/backend#retrieve-a-user */ getUser: (params: { email: string; } | { id: string; } | { refresh_token: string; }) => Promise | null>; /** * Deletes an app user by id, email, or refresh token. * Resolves to `null` when no user matches; throws on malformed * input or auth errors. * * NB: This _only_ deletes the user; it does not delete all user data. * You will need to handle this manually. * * @example * const deletedUser = await db.auth.deleteUser({ email }); * if (!deletedUser) { * console.log("No user found to delete"); * return; * } * console.log("Deleted user:", deletedUser); * * @see https://instantdb.com/docs/backend#delete-a-user */ deleteUser: (params: { email: string; } | { id: string; } | { refresh_token: string; }) => Promise; /** * Signs out the user with the given email. * This invalidates any tokens associated with the user. * If the user is not found, an error will be thrown. * * @example * try { * await auth.signOut({ email: "alyssa_p_hacker@instantdb.com" }); * console.log("Successfully signed out"); * } catch (err) { * console.error("Sign out failed:", err.message); * } * * @see https://instantdb.com/docs/backend#sign-out */ signOut(params: { email: string; } | { id: string; } | { refresh_token: string; }): Promise; /** * @deprecated Passing an email string directly is deprecated. * Use an object with the `email` key instead. * * @example * // Before * auth.signOut(email) * * // After * auth.signOut({ email }) */ signOut(email: string): Promise; /** * Get instant user from Request * * Reads cookies and gets a validated user * @param req The request containing a cookie synced with createInstantRouteHandler * @param opts Allow disabling validation of refresh token */ getUserFromRequest: (req: Request, opts?: { disableValidation?: boolean; }) => Promise; } type StorageFile = { key: string; name: string; size: number; etag: string; last_modified: number; }; type DeleteManyFileResponse = { data: { ids: string[] | null; }; }; /** * Functions to manage file storage. */ declare class Storage { config: FilledConfig; impersonationOpts?: ImpersonationOpts; constructor(config: FilledConfig, impersonationOpts?: ImpersonationOpts); /** * Uploads file at the provided path. Accepts a Buffer or a Readable stream. * * @see https://instantdb.com/docs/storage * @example * const buffer = fs.readFileSync('demo.png'); * const isSuccess = await db.storage.uploadFile('photos/demo.png', buffer); */ uploadFile: (path: string, file: Buffer | Readable | ReadableStream | Uint8Array, metadata?: FileOpts) => Promise; /** * Deletes a file by its path name (e.g. "photos/demo.png"). * * @deprecated Use `db.transact` to delete files instead: * @example * // Delete by id * await db.transact(db.tx.$files[fileId].delete()); * * // Delete by path * await db.transact(db.tx.$files[lookup('path', 'photos/demo.png')].delete()); * * @see https://instantdb.com/docs/storage */ delete: (pathname: string) => Promise; /** * Deletes multiple files by their path names. * * @deprecated Use `db.transact` to delete files instead: * @example * // Delete multiple files by path * const paths = ['images/1.png', 'images/2.png', 'images/3.png']; * await db.transact(paths.map(p => db.tx.$files[lookup('path', p)].delete())); * * @see https://instantdb.com/docs/storage */ deleteMany: (pathnames: string[]) => Promise; /** * @deprecated. This method will be removed in the future. Use `uploadFile` * instead */ upload: (pathname: string, file: Buffer, metadata?: FileOpts) => Promise; /** * @deprecated. This method will be removed in the future. Use `query` instead * @example * const files = await db.query({ $files: {}}) */ list: () => Promise; /** * @deprecated. getDownloadUrl will be removed in the future. * Use `query` instead to query and fetch for valid urls * * db.useQuery({ * $files: { * $: { * where: { * path: "moop.png" * } * } * } * }) */ getDownloadUrl: (pathname: string) => Promise; } type CreateReadStreamOpts = { clientId?: string | null | undefined; streamId?: string | null | undefined; byteOffset?: number | null | undefined; ruleParams?: RuleParams | null | undefined; }; type CreateWriteStreamOpts = { clientId: string; /** * A function that takes a promise and ensures that the current program stays alive * until the promise is resolved. * * Useful in serverless environments to ensure the writer fully flushes before the * environment is shut down. * * @example * import { after } from 'next/server' * db.streams.createWriteStream({clientId, waitUntil: after}) */ waitUntil?: (promise: Promise) => void | null | undefined; ruleParams?: RuleParams | null | undefined; }; /** * Functions to manage streams. */ declare class Streams { #private; constructor(ensureInstantStream: () => InstantStream); /** * Creates a new ReadableStream for the given clientId. * * @example * const stream = db.streams.createReadStream({clientId: clientId}) * for await (const chunk of stream) { * console.log(chunk); * } */ createReadStream: (opts: CreateReadStreamOpts) => InstantReadableStream; /** * Creates a new WritableStream for the given clientId. * * @example * const writeStream = db.streams.createWriteStream({clientId: clientId}) * const writer = writeStream.getWriter(); * writer.write('Hello world'); * writer.close(); */ createWriteStream: (opts: CreateWriteStreamOpts) => InstantWritableStream; } type AdminQueryOpts = { ruleParams?: RuleParams; fetchOpts?: RequestInit; }; /** * * The first step: init your application! * * Visit https://instantdb.com/dash to get your `appId` and `adminToken` :) * * @example * const db = init({ appId: "my-app-id", adminToken: "my-admin-token" }) */ declare class InstantAdminDatabase, UseDates extends boolean = false, Config extends InstantConfig = InstantConfig> { #private; config: InstantConfigFilled; auth: Auth; storage: Storage; streams: Streams; rooms: Rooms; impersonationOpts?: ImpersonationOpts; webhooks: Webhooks; tx: import("@instantdb/core").TxChunk>; constructor(_config: Config); /** * Sometimes you want to scope queries to a specific user. * * You can provide a user's auth token, email, or impersonate a guest. * * @see https://instantdb.com/docs/backend#impersonating-users * @example * await db.asUser({email: "stopa@instantdb.com"}).query({ goals: {} }) */ asUser: (opts: ImpersonationOpts) => InstantAdminDatabase; /** * Use this to query your data! * * @see https://instantdb.com/docs/instaql * * @example * // fetch all goals * await db.query({ goals: {} }) * * // goals where the title is "Get Fit" * await db.query({ goals: { $: { where: { title: "Get Fit" } } } }) * * // all goals, _alongside_ their todos * await db.query({ goals: { todos: {} } }) */ query: >(query: Q, opts?: AdminQueryOpts) => Promise>; /** * Use this to to get a live view of your data! * * @see https://www.instantdb.com/docs/backend * * @example * // create a subscription to a query * const query = { goals: { $: { where: { title: "Get Fit" } } } } * const sub = db.subscribeQuery(query); * * // iterate through the results with an async iterator * for await (const payload of sub) { * if (payload.error) { * console.log(payload.error); * // Stop the subscription * sub.close(); * } else { * console.log(payload.data); * } * } * * // Stop the subscription * sub.close(); * * // Create a subscription with a callback * const sub = db.subscribeQuery(query, (payload) => { * if (payload.error) { * console.log(payload.error); * // Stop the subscription * sub.close(); * } else { * console.log(payload.data); * } * }); */ subscribeQuery>(query: Q, cb?: SubscribeQueryCallback, opts?: AdminQueryOpts): SubscribeQueryResponse; /** * Use this to write data! You can create, update, delete, and link objects * * @see https://instantdb.com/docs/instaml * * @example * // Create a new object in the `goals` namespace * const goalId = id(); * db.transact(db.tx.goals[goalId].update({title: "Get fit"})) * * // Update the title * db.transact(db.tx.goals[goalId].update({title: "Get super fit"})) * * // Delete it * db.transact(db.tx.goals[goalId].delete()) * * // Or create an association: * todoId = id(); * db.transact([ * db.tx.todos[todoId].update({ title: 'Go on a run' }), * db.tx.goals[goalId].link({todos: todoId}), * ]) */ transact: (inputChunks: TransactionChunk | TransactionChunk[]) => Promise; /** * Like `query`, but returns debugging information * for permissions checks along with the result. * Useful for inspecting the values returned by the permissions checks. * Note, this will return debug information for *all* entities * that match the query's `where` clauses. * * Requires a user/guest context to be set with `asUser`, * since permissions checks are user-specific. * * Accepts an optional configuration object with a `rules` key. * The provided rules will override the rules in the database for the query. * * @see https://instantdb.com/docs/instaql * * @example * await db.asUser({ guest: true }).debugQuery( * { goals: {} }, * { rules: { goals: { allow: { read: "auth.id != null" } } } * ) */ debugQuery: >(query: Q, opts?: { rules?: any; ruleParams?: { [key: string]: any; }; ip?: string | null | undefined; origin?: string | null | undefined; cardinalityInference?: boolean; }) => Promise<{ result: InstaQLResponse; checkResults: DebugCheckResult[]; }>; /** * Like `transact`, but does not write to the database. * Returns debugging information for permissions checks. * Useful for inspecting the values returned by the permissions checks. * * Requires a user/guest context to be set with `asUser`, * since permissions checks are user-specific. * * Accepts an optional configuration object with a `rules` key. * The provided rules will override the rules in the database for the duration of the transaction. * * @example * const goalId = id(); * db.asUser({ guest: true }).debugTransact( * [db.tx.goals[goalId].update({title: "Get fit"})], * { rules: { goals: { allow: { update: "auth.id != null" } } } * ) */ debugTransact: (inputChunks: TransactionChunk | TransactionChunk[], opts?: { rules?: any; ip?: string | null | undefined; origin?: string | null | undefined; }) => Promise; } export { init, init_experimental, id, tx, lookup, i, createInstantRouteHandler, Webhooks, WebhooksManager, type WebhookAction, type WebhookStatus, type WebhookEventStatus, type WebhookInfo, type WebhookAttempt, type WebhookEventInfo, type WebhookEventsPage, type WebhookBody, type WebhookEntity, type WebhookPayload, type WebhookPayloadRecord, type WebhookPayloadRecordFor, type WebhookHandlerFn, type WebhookHandlers, type WebhookHelpers, type CreateWebhookParams, type UpdateWebhookParams, InstantAPIError, setInstantWarningsEnabled, type Config, type ImpersonationOpts, type TransactionChunk, type DebugCheckResult, type InstantAdminDatabase, type User, type InstaQLParams, type ValidQuery, type Query, InstantError, type QueryResponse, type InstaQLResponse, type InstantQuery, type InstantUnknownSchemaDef, type InstantQueryResult, type InstantSchema, type InstantSchemaDatabase, type IInstantDatabase, type InstantObject, type InstantEntity, type BackwardsCompatibleSchema, type InstaQLFields, type SubscribeQueryCallback, type SubscribeQueryResponse, type SubscribeQueryPayload, type SubscriptionReadyState, type AttrsDefs, type CardinalityKind, type DataAttrDef, type EntitiesDef, type EntitiesWithLinks, type EntityDef, type InstantGraph, type LinkAttrDef, type LinkDef, type LinksDef, type ResolveAttrs, type RoomsOf, type PresenceOf, type RoomsDef, type RoomHandle, type ValueTypes, type InstantSchemaDef, type InstantUnknownSchema, type InstaQLEntity, type InstaQLResult, type InstaQLEntitySubquery, type InstantRules, type CreateParams, type UpdateParams, type LinkParams, type FileOpts, type UploadFileResponse, type DeleteFileResponse, type DeleteManyFileResponse, type CreateReadStreamOpts, type CreateWriteStreamOpts, type InstantWritableStream, type InstantIssue, }; //# sourceMappingURL=index.d.ts.map