@fidscript/instant-admin 0.1.0

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.
Files changed (41) hide show
  1. package/dist/commonjs/fidscript-defaults.d.ts +14 -0
  2. package/dist/commonjs/fidscript-defaults.d.ts.map +1 -0
  3. package/dist/commonjs/fidscript-defaults.js +17 -0
  4. package/dist/commonjs/fidscript-defaults.js.map +1 -0
  5. package/dist/commonjs/index.d.ts +608 -0
  6. package/dist/commonjs/index.d.ts.map +1 -0
  7. package/dist/commonjs/index.js +1051 -0
  8. package/dist/commonjs/index.js.map +1 -0
  9. package/dist/commonjs/polyfill.d.ts +17 -0
  10. package/dist/commonjs/polyfill.d.ts.map +1 -0
  11. package/dist/commonjs/polyfill.js +26 -0
  12. package/dist/commonjs/polyfill.js.map +1 -0
  13. package/dist/commonjs/subscribe.d.ts +39 -0
  14. package/dist/commonjs/subscribe.d.ts.map +1 -0
  15. package/dist/commonjs/subscribe.js +306 -0
  16. package/dist/commonjs/subscribe.js.map +1 -0
  17. package/dist/commonjs/version.d.ts +3 -0
  18. package/dist/commonjs/version.d.ts.map +1 -0
  19. package/dist/commonjs/version.js +5 -0
  20. package/dist/commonjs/version.js.map +1 -0
  21. package/dist/esm/fidscript-defaults.d.ts +14 -0
  22. package/dist/esm/fidscript-defaults.d.ts.map +1 -0
  23. package/dist/esm/fidscript-defaults.js +14 -0
  24. package/dist/esm/fidscript-defaults.js.map +1 -0
  25. package/dist/esm/index.d.ts +608 -0
  26. package/dist/esm/index.d.ts.map +1 -0
  27. package/dist/esm/index.js +1038 -0
  28. package/dist/esm/index.js.map +1 -0
  29. package/dist/esm/polyfill.d.ts +17 -0
  30. package/dist/esm/polyfill.d.ts.map +1 -0
  31. package/dist/esm/polyfill.js +22 -0
  32. package/dist/esm/polyfill.js.map +1 -0
  33. package/dist/esm/subscribe.d.ts +39 -0
  34. package/dist/esm/subscribe.d.ts.map +1 -0
  35. package/dist/esm/subscribe.js +300 -0
  36. package/dist/esm/subscribe.js.map +1 -0
  37. package/dist/esm/version.d.ts +3 -0
  38. package/dist/esm/version.d.ts.map +1 -0
  39. package/dist/esm/version.js +3 -0
  40. package/dist/esm/version.js.map +1 -0
  41. package/package.json +33 -0
@@ -0,0 +1,1051 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.InstantError = exports.setInstantWarningsEnabled = exports.InstantAPIError = exports.WebhooksManager = exports.Webhooks = exports.createInstantRouteHandler = exports.i = exports.lookup = exports.tx = exports.id = exports.init_experimental = void 0;
7
+ exports.init = init;
8
+ const uuid_1 = require("uuid");
9
+ const fidscript_defaults_js_1 = require("./fidscript-defaults.js");
10
+ const instant_sdk_1 = require("@fidscript/instant-sdk");
11
+ Object.defineProperty(exports, "tx", { enumerable: true, get: function () { return instant_sdk_1.tx; } });
12
+ Object.defineProperty(exports, "lookup", { enumerable: true, get: function () { return instant_sdk_1.lookup; } });
13
+ Object.defineProperty(exports, "i", { enumerable: true, get: function () { return instant_sdk_1.i; } });
14
+ Object.defineProperty(exports, "id", { enumerable: true, get: function () { return instant_sdk_1.id; } });
15
+ Object.defineProperty(exports, "InstantAPIError", { enumerable: true, get: function () { return instant_sdk_1.InstantAPIError; } });
16
+ Object.defineProperty(exports, "setInstantWarningsEnabled", { enumerable: true, get: function () { return instant_sdk_1.setInstantWarningsEnabled; } });
17
+ Object.defineProperty(exports, "InstantError", { enumerable: true, get: function () { return instant_sdk_1.InstantError; } });
18
+ Object.defineProperty(exports, "createInstantRouteHandler", { enumerable: true, get: function () { return instant_sdk_1.createInstantRouteHandler; } });
19
+ const version_ts_1 = __importDefault(require("./version.js"));
20
+ const subscribe_ts_1 = require("./subscribe.js");
21
+ const cookie_1 = require("cookie");
22
+ const eventsource_1 = require("@instantdb/eventsource");
23
+ const polyfill_ts_1 = require("./polyfill.js");
24
+ const webhooks_1 = require("@instantdb/webhooks");
25
+ Object.defineProperty(exports, "Webhooks", { enumerable: true, get: function () { return webhooks_1.Webhooks; } });
26
+ Object.defineProperty(exports, "WebhooksManager", { enumerable: true, get: function () { return webhooks_1.WebhooksManager; } });
27
+ function configWithDefaults(config) {
28
+ const defaultConfig = {
29
+ apiURI: fidscript_defaults_js_1.fidscriptDefaults.apiURI,
30
+ };
31
+ const r = { ...defaultConfig, ...config };
32
+ return r;
33
+ }
34
+ function instantConfigWithDefaults(config) {
35
+ const defaultConfig = {
36
+ apiURI: fidscript_defaults_js_1.fidscriptDefaults.apiURI,
37
+ };
38
+ const r = { ...defaultConfig, ...config };
39
+ if (!r.apiURI) {
40
+ r.apiURI = defaultConfig.apiURI;
41
+ }
42
+ return r;
43
+ }
44
+ function withImpersonation(headers, opts) {
45
+ if ('email' in opts) {
46
+ headers['as-email'] = opts.email;
47
+ }
48
+ else if ('token' in opts) {
49
+ headers['as-token'] = opts.token;
50
+ }
51
+ else if ('guest' in opts) {
52
+ headers['as-guest'] = 'true';
53
+ }
54
+ return headers;
55
+ }
56
+ function validateConfigAndImpersonation(config, impersonationOpts) {
57
+ if (impersonationOpts &&
58
+ ('token' in impersonationOpts || 'guest' in impersonationOpts)) {
59
+ // adminToken is not required for `token` or `guest` impersonation
60
+ return;
61
+ }
62
+ if (config.adminToken) {
63
+ // An adminToken is provided.
64
+ return;
65
+ }
66
+ if (impersonationOpts && 'email' in impersonationOpts) {
67
+ throw new Error('Admin token required. To impersonate users with an email you must pass `adminToken` to `init`.');
68
+ }
69
+ throw new Error('Admin token required. To run this operation pass `adminToken` to `init`, or use `db.asUser`.');
70
+ }
71
+ function authorizedHeaders(config, impersonationOpts) {
72
+ validateConfigAndImpersonation(config, impersonationOpts);
73
+ const { adminToken, appId } = config;
74
+ const headers = {
75
+ 'content-type': 'application/json',
76
+ 'app-id': appId,
77
+ };
78
+ if (adminToken) {
79
+ headers.authorization = `Bearer ${adminToken}`;
80
+ }
81
+ return impersonationOpts
82
+ ? withImpersonation(headers, impersonationOpts)
83
+ : headers;
84
+ }
85
+ // NextJS 13 and 14 cache fetch requests by default.
86
+ //
87
+ // Since adminDB.query uses fetch, this means that it would also cache by default.
88
+ //
89
+ // We don't want this behavior. `adminDB.query` should return the latest result by default.
90
+ //
91
+ // To get around this, we set an explicit `cache` header for NextJS 13 and 14.
92
+ // This is no longer needed in NextJS 15 onwards, as the default is `no-store` again.
93
+ // Once NextJS 13 and 14 are no longer common, we can remove this code.
94
+ function isNextJSVersionThatCachesFetchByDefault() {
95
+ return (
96
+ // NextJS 13 onwards added a `__nextPatched` property to the fetch function
97
+ fetch['__nextPatched'] &&
98
+ // NextJS 15 onwards _also_ added a global `next-patch` symbol.
99
+ !globalThis[Symbol.for('next-patch')]);
100
+ }
101
+ function getDefaultFetchOpts() {
102
+ return isNextJSVersionThatCachesFetchByDefault() ? { cache: 'no-store' } : {};
103
+ }
104
+ async function jsonReject(rejectFn, res) {
105
+ const body = await res.text();
106
+ try {
107
+ const json = JSON.parse(body);
108
+ return rejectFn(new instant_sdk_1.InstantAPIError({ status: res.status, body: json }));
109
+ }
110
+ catch (_e) {
111
+ return rejectFn(new instant_sdk_1.InstantAPIError({
112
+ status: res.status,
113
+ body: { type: undefined, message: body },
114
+ }));
115
+ }
116
+ }
117
+ async function jsonFetch(input, init) {
118
+ const defaultFetchOpts = getDefaultFetchOpts();
119
+ const headers = {
120
+ ...(init?.headers || {}),
121
+ 'Instant-Admin-Version': version_ts_1.default,
122
+ 'Instant-Core-Version': instant_sdk_1.version,
123
+ };
124
+ const res = await fetch(input, { ...defaultFetchOpts, ...init, headers });
125
+ if (res.status === 200) {
126
+ const json = await res.json();
127
+ return Promise.resolve(json);
128
+ }
129
+ return jsonReject((x) => Promise.reject(x), res);
130
+ }
131
+ function makeEventSourceWrapper(opts) {
132
+ return class EventSourceWrapper {
133
+ source;
134
+ static OPEN = eventsource_1.EventSource.OPEN;
135
+ static CONNECTING = eventsource_1.EventSource.CONNECTING;
136
+ static CLOSED = eventsource_1.EventSource.CLOSED;
137
+ url;
138
+ constructor(url) {
139
+ this.url = url;
140
+ this.source = this.#createEventSource(url);
141
+ }
142
+ get onopen() {
143
+ return this.source.onopen;
144
+ }
145
+ set onopen(fn) {
146
+ this.source.onopen = fn;
147
+ }
148
+ get onmessage() {
149
+ return this.source.onmessage;
150
+ }
151
+ set onmessage(fn) {
152
+ this.source.onmessage = fn;
153
+ }
154
+ get onerror() {
155
+ return this.source.onerror;
156
+ }
157
+ set onerror(fn) {
158
+ this.source.onerror = fn;
159
+ }
160
+ get readyState() {
161
+ return this.source.readyState;
162
+ }
163
+ close() {
164
+ this.source.close();
165
+ }
166
+ #createEventSource(url) {
167
+ const es = new eventsource_1.EventSource(url, {
168
+ messageEvent: polyfill_ts_1.MessageEventPolyfill,
169
+ fetch(input, init) {
170
+ return fetch(input, {
171
+ ...init,
172
+ method: 'POST',
173
+ headers: opts.headers,
174
+ body: JSON.stringify({
175
+ 'inference?': opts.inference,
176
+ versions: {
177
+ '@instantdb/admin': version_ts_1.default,
178
+ '@instantdb/core': instant_sdk_1.version,
179
+ },
180
+ }),
181
+ });
182
+ },
183
+ });
184
+ return es;
185
+ }
186
+ };
187
+ }
188
+ /**
189
+ *
190
+ * The first step: init your application!
191
+ *
192
+ * Visit https://instantdb.com/dash to get your `appId` :)
193
+ *
194
+ * @example
195
+ * import { init } from "@instantdb/admin"
196
+ *
197
+ * const db = init({
198
+ * appId: process.env.INSTANT_APP_ID!,
199
+ * adminToken: process.env.INSTANT_APP_ADMIN_TOKEN
200
+ * })
201
+ *
202
+ * // You can also provide a schema for type safety and editor autocomplete!
203
+ *
204
+ * import { init } from "@instantdb/admin"
205
+ * import schema from ""../instant.schema.ts";
206
+ *
207
+ * const db = init({
208
+ * appId: process.env.INSTANT_APP_ID!,
209
+ * adminToken: process.env.INSTANT_APP_ADMIN_TOKEN,
210
+ * schema,
211
+ * })
212
+ * // To learn more: https://instantdb.com/docs/modeling-data
213
+ */
214
+ function init(
215
+ // Allows config with missing `useDateObjects`, but keeps `UseDates`
216
+ // as a non-nullable in the InstantConfig type.
217
+ config) {
218
+ if (!config.appId || !(0, uuid_1.validate)(config.appId)) {
219
+ console.warn('warning: Instant Admin DB must be initialized with a valid appId. Received: ' +
220
+ JSON.stringify(config.appId));
221
+ }
222
+ const configStrict = {
223
+ ...config,
224
+ appId: config.appId?.trim(),
225
+ adminToken: config.adminToken?.trim(),
226
+ useDateObjects: (config.useDateObjects ?? false),
227
+ };
228
+ return new InstantAdminDatabase(configStrict);
229
+ }
230
+ /**
231
+ * @deprecated
232
+ * `init_experimental` is deprecated. You can replace it with `init`.
233
+ *
234
+ * @example
235
+ *
236
+ * // Before
237
+ * import { init_experimental } from "@instantdb/admin"
238
+ * const db = init_experimental({ ... });
239
+ *
240
+ * // After
241
+ * import { init } from "@instantdb/admin"
242
+ * const db = init({ ... });
243
+ */
244
+ const init_experimental = init;
245
+ exports.init_experimental = init_experimental;
246
+ function steps(inputChunks) {
247
+ const chunks = Array.isArray(inputChunks) ? inputChunks : [inputChunks];
248
+ return chunks.flatMap(instant_sdk_1.getOps);
249
+ }
250
+ class Rooms {
251
+ config;
252
+ constructor(config) {
253
+ this.config = config;
254
+ }
255
+ async getPresence(roomType, roomId) {
256
+ const res = await jsonFetch(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(roomType)}&room-id=${roomId}`, {
257
+ method: 'GET',
258
+ headers: authorizedHeaders(this.config),
259
+ });
260
+ return res.sessions || {};
261
+ }
262
+ }
263
+ class Auth {
264
+ config;
265
+ constructor(config) {
266
+ this.config = config;
267
+ this.createToken = this.createToken.bind(this);
268
+ }
269
+ /**
270
+ * Generates a magic code for the user with the given email.
271
+ * This is useful if you want to use your own email provider
272
+ * to send magic codes.
273
+ *
274
+ * @example
275
+ * // Generate a magic code
276
+ * const { code } = await db.auth.generateMagicCode({ email })
277
+ * // Send the magic code to the user with your own email provider
278
+ * await customEmailProvider.sendMagicCode(email, code)
279
+ *
280
+ * @see https://instantdb.com/docs/backend#custom-magic-codes
281
+ */
282
+ generateMagicCode = async (email) => {
283
+ return jsonFetch(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`, {
284
+ method: 'POST',
285
+ headers: authorizedHeaders(this.config),
286
+ body: JSON.stringify({ email }),
287
+ });
288
+ };
289
+ /**
290
+ * Sends a magic code to the user with the given email.
291
+ * This uses Instant's built-in email provider.
292
+ *
293
+ * @example
294
+ * // Send an email to user with magic code
295
+ * await db.auth.sendMagicCode({ email })
296
+ *
297
+ * @see https://instantdb.com/docs/backend#custom-magic-codes
298
+ */
299
+ sendMagicCode = async (email) => {
300
+ return jsonFetch(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`, {
301
+ method: 'POST',
302
+ headers: authorizedHeaders(this.config),
303
+ body: JSON.stringify({ email }),
304
+ });
305
+ };
306
+ /**
307
+ * @deprecated Use {@link checkMagicCode} instead to get the `created` field
308
+ * and support `extraFields`.
309
+ *
310
+ * @see https://instantdb.com/docs/backend#custom-magic-codes
311
+ */
312
+ verifyMagicCode = async (email, code) => {
313
+ const { user } = await jsonFetch(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`, {
314
+ method: 'POST',
315
+ headers: authorizedHeaders(this.config),
316
+ body: JSON.stringify({ email, code }),
317
+ });
318
+ return user;
319
+ };
320
+ /**
321
+ * Verifies a magic code and returns the user along with whether
322
+ * the user was newly created. Supports `extraFields` to set custom
323
+ * `$users` properties at signup.
324
+ *
325
+ * @example
326
+ * const { user, created } = await db.auth.checkMagicCode(
327
+ * email,
328
+ * code,
329
+ * { extraFields: { nickname: 'ari' } },
330
+ * );
331
+ *
332
+ * @see https://instantdb.com/docs/backend#custom-magic-codes
333
+ */
334
+ checkMagicCode = async (email, code, options) => {
335
+ const res = await jsonFetch(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`, {
336
+ method: 'POST',
337
+ headers: authorizedHeaders(this.config),
338
+ body: JSON.stringify({
339
+ email,
340
+ code,
341
+ ...(options?.extraFields
342
+ ? { 'extra-fields': options.extraFields }
343
+ : {}),
344
+ }),
345
+ });
346
+ return { user: res.user, created: res.created };
347
+ };
348
+ async createToken(input) {
349
+ const body = typeof input === 'string' ? { email: input } : input;
350
+ const ret = await jsonFetch(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`, {
351
+ method: 'POST',
352
+ headers: authorizedHeaders(this.config),
353
+ body: JSON.stringify(body),
354
+ });
355
+ return ret.user.refresh_token;
356
+ }
357
+ /**
358
+ * Verifies a given token and returns the associated user.
359
+ *
360
+ * This is often useful for writing custom endpoints, where you need
361
+ * to authenticate users.
362
+ *
363
+ * @example
364
+ * app.post('/custom_endpoint', async (req, res) => {
365
+ * const user = await db.auth.verifyToken(req.headers['token'])
366
+ * if (!user) {
367
+ * return res.status(401).send('Uh oh, you are not authenticated')
368
+ * }
369
+ * // ...
370
+ * })
371
+ * @see https://instantdb.com/docs/backend#custom-endpoints
372
+ */
373
+ verifyToken = async (token) => {
374
+ const res = await jsonFetch(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`, {
375
+ method: 'POST',
376
+ headers: { 'content-type': 'application/json' },
377
+ body: JSON.stringify({
378
+ 'app-id': this.config.appId,
379
+ 'refresh-token': token,
380
+ }),
381
+ });
382
+ return res.user;
383
+ };
384
+ /**
385
+ * Retrieves an app user by id, email, or refresh token.
386
+ * Resolves to `null` when no user matches; throws on malformed
387
+ * input or auth errors.
388
+ *
389
+ * @example
390
+ * const user = await db.auth.getUser({ email });
391
+ * if (!user) {
392
+ * console.log("No user found");
393
+ * return;
394
+ * }
395
+ * console.log("Found user:", user);
396
+ *
397
+ * @see https://instantdb.com/docs/backend#retrieve-a-user
398
+ */
399
+ getUser = async (params) => {
400
+ const qs = new URLSearchParams(Object.entries(params)).toString();
401
+ const response = await jsonFetch(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${qs}`, {
402
+ method: 'GET',
403
+ headers: authorizedHeaders(this.config),
404
+ });
405
+ return response.user;
406
+ };
407
+ /**
408
+ * Deletes an app user by id, email, or refresh token.
409
+ * Resolves to `null` when no user matches; throws on malformed
410
+ * input or auth errors.
411
+ *
412
+ * NB: This _only_ deletes the user; it does not delete all user data.
413
+ * You will need to handle this manually.
414
+ *
415
+ * @example
416
+ * const deletedUser = await db.auth.deleteUser({ email });
417
+ * if (!deletedUser) {
418
+ * console.log("No user found to delete");
419
+ * return;
420
+ * }
421
+ * console.log("Deleted user:", deletedUser);
422
+ *
423
+ * @see https://instantdb.com/docs/backend#delete-a-user
424
+ */
425
+ deleteUser = async (params) => {
426
+ const qs = new URLSearchParams(Object.entries(params)).toString();
427
+ const response = await jsonFetch(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${qs}`, {
428
+ method: 'DELETE',
429
+ headers: authorizedHeaders(this.config),
430
+ });
431
+ return response.deleted;
432
+ };
433
+ async signOut(input) {
434
+ // If input is a string, we assume it's an email.
435
+ // This is because of backwards compatibility: we used to only
436
+ // accept email strings. Eventually we can remove this
437
+ const params = typeof input === 'string' ? { email: input } : input;
438
+ const config = this.config;
439
+ await jsonFetch(`${config.apiURI}/admin/sign_out?app_id=${this.config.appId}`, {
440
+ method: 'POST',
441
+ headers: authorizedHeaders(config),
442
+ body: JSON.stringify(params),
443
+ });
444
+ }
445
+ /**
446
+ * Get instant user from Request
447
+ *
448
+ * Reads cookies and gets a validated user
449
+ * @param req The request containing a cookie synced with createInstantRouteHandler
450
+ * @param opts Allow disabling validation of refresh token
451
+ */
452
+ getUserFromRequest = async (req, opts) => {
453
+ const cookieHeader = req.headers.get('cookie') || '';
454
+ const parsedCookie = (0, cookie_1.parseCookie)(cookieHeader);
455
+ const cookieName = 'instant_user_' + this.config.appId;
456
+ if (!parsedCookie[cookieName]) {
457
+ return null;
458
+ }
459
+ const value = parsedCookie[cookieName];
460
+ const user = JSON.parse(value);
461
+ if (!user?.refresh_token) {
462
+ return null;
463
+ }
464
+ if (opts?.disableValidation) {
465
+ return user;
466
+ }
467
+ const verified = await this.verifyToken(user.refresh_token);
468
+ return verified;
469
+ };
470
+ }
471
+ const isNodeReadable = (v) => v &&
472
+ typeof v === 'object' &&
473
+ typeof v.pipe === 'function' &&
474
+ typeof v.read === 'function';
475
+ const isWebReadable = (v) => v && typeof v.getReader === 'function';
476
+ /**
477
+ * Functions to manage file storage.
478
+ */
479
+ class Storage {
480
+ config;
481
+ impersonationOpts;
482
+ constructor(config, impersonationOpts) {
483
+ this.config = config;
484
+ this.impersonationOpts = impersonationOpts;
485
+ }
486
+ /**
487
+ * Uploads file at the provided path. Accepts a Buffer or a Readable stream.
488
+ *
489
+ * @see https://instantdb.com/docs/storage
490
+ * @example
491
+ * const buffer = fs.readFileSync('demo.png');
492
+ * const isSuccess = await db.storage.uploadFile('photos/demo.png', buffer);
493
+ */
494
+ uploadFile = async (path, file, metadata = {}) => {
495
+ const headers = {
496
+ ...authorizedHeaders(this.config, this.impersonationOpts),
497
+ path,
498
+ };
499
+ if (metadata.contentDisposition) {
500
+ headers['content-disposition'] = metadata.contentDisposition;
501
+ }
502
+ // headers.content-type will become "undefined" (string)
503
+ // if not removed from the object
504
+ delete headers['content-type'];
505
+ if (metadata.contentType) {
506
+ headers['content-type'] = metadata.contentType;
507
+ }
508
+ let duplex;
509
+ if (isNodeReadable(file)) {
510
+ duplex = 'half'; // one-way stream
511
+ }
512
+ if (isNodeReadable(file) || isWebReadable(file)) {
513
+ if (!metadata.fileSize) {
514
+ throw new Error('fileSize is required in metadata when uploading streams');
515
+ }
516
+ headers['content-length'] = metadata.fileSize.toString();
517
+ }
518
+ let options = {
519
+ method: 'PUT',
520
+ headers,
521
+ body: file,
522
+ ...(duplex && { duplex }),
523
+ };
524
+ return jsonFetch(`${this.config.apiURI}/admin/storage/upload?app_id=${this.config.appId}`, options);
525
+ };
526
+ /**
527
+ * Deletes a file by its path name (e.g. "photos/demo.png").
528
+ *
529
+ * @deprecated Use `db.transact` to delete files instead:
530
+ * @example
531
+ * // Delete by id
532
+ * await db.transact(db.tx.$files[fileId].delete());
533
+ *
534
+ * // Delete by path
535
+ * await db.transact(db.tx.$files[lookup('path', 'photos/demo.png')].delete());
536
+ *
537
+ * @see https://instantdb.com/docs/storage
538
+ */
539
+ delete = async (pathname) => {
540
+ return jsonFetch(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(pathname)}`, {
541
+ method: 'DELETE',
542
+ headers: authorizedHeaders(this.config, this.impersonationOpts),
543
+ });
544
+ };
545
+ /**
546
+ * Deletes multiple files by their path names.
547
+ *
548
+ * @deprecated Use `db.transact` to delete files instead:
549
+ * @example
550
+ * // Delete multiple files by path
551
+ * const paths = ['images/1.png', 'images/2.png', 'images/3.png'];
552
+ * await db.transact(paths.map(p => db.tx.$files[lookup('path', p)].delete()));
553
+ *
554
+ * @see https://instantdb.com/docs/storage
555
+ */
556
+ deleteMany = async (pathnames) => {
557
+ return jsonFetch(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`, {
558
+ method: 'POST',
559
+ headers: authorizedHeaders(this.config, this.impersonationOpts),
560
+ body: JSON.stringify({ filenames: pathnames }),
561
+ });
562
+ };
563
+ /**
564
+ * @deprecated. This method will be removed in the future. Use `uploadFile`
565
+ * instead
566
+ */
567
+ upload = async (pathname, file, metadata = {}) => {
568
+ const { data: presignedUrl } = await jsonFetch(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`, {
569
+ method: 'POST',
570
+ headers: authorizedHeaders(this.config),
571
+ body: JSON.stringify({
572
+ app_id: this.config.appId,
573
+ filename: pathname,
574
+ }),
575
+ });
576
+ const headers = {};
577
+ const contentType = metadata.contentType;
578
+ if (contentType) {
579
+ headers['Content-Type'] = contentType;
580
+ }
581
+ const { ok } = await fetch(presignedUrl, {
582
+ method: 'PUT',
583
+ body: file,
584
+ headers,
585
+ });
586
+ return ok;
587
+ };
588
+ /**
589
+ * @deprecated. This method will be removed in the future. Use `query` instead
590
+ * @example
591
+ * const files = await db.query({ $files: {}})
592
+ */
593
+ list = async () => {
594
+ const { data } = await jsonFetch(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`, {
595
+ method: 'GET',
596
+ headers: authorizedHeaders(this.config),
597
+ });
598
+ return data;
599
+ };
600
+ /**
601
+ * @deprecated. getDownloadUrl will be removed in the future.
602
+ * Use `query` instead to query and fetch for valid urls
603
+ *
604
+ * db.useQuery({
605
+ * $files: {
606
+ * $: {
607
+ * where: {
608
+ * path: "moop.png"
609
+ * }
610
+ * }
611
+ * }
612
+ * })
613
+ */
614
+ getDownloadUrl = async (pathname) => {
615
+ const { data } = await jsonFetch(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(pathname)}`, {
616
+ method: 'GET',
617
+ headers: authorizedHeaders(this.config),
618
+ });
619
+ return data;
620
+ };
621
+ }
622
+ /**
623
+ * Functions to manage streams.
624
+ */
625
+ class Streams {
626
+ #ensureInstantStream;
627
+ constructor(ensureInstantStream) {
628
+ this.#ensureInstantStream = ensureInstantStream;
629
+ }
630
+ /**
631
+ * Creates a new ReadableStream for the given clientId.
632
+ *
633
+ * @example
634
+ * const stream = db.streams.createReadStream({clientId: clientId})
635
+ * for await (const chunk of stream) {
636
+ * console.log(chunk);
637
+ * }
638
+ */
639
+ createReadStream = (opts) => {
640
+ return this.#ensureInstantStream().createReadStream(opts);
641
+ };
642
+ /**
643
+ * Creates a new WritableStream for the given clientId.
644
+ *
645
+ * @example
646
+ * const writeStream = db.streams.createWriteStream({clientId: clientId})
647
+ * const writer = writeStream.getWriter();
648
+ * writer.write('Hello world');
649
+ * writer.close();
650
+ */
651
+ createWriteStream = (opts) => {
652
+ return this.#ensureInstantStream().createWriteStream(opts);
653
+ };
654
+ }
655
+ function createLogger(isEnabled, baseLogger = console) {
656
+ return {
657
+ info: isEnabled ? (...args) => baseLogger.info(...args) : () => { },
658
+ debug: isEnabled ? (...args) => baseLogger.debug(...args) : () => { },
659
+ error: isEnabled ? (...args) => baseLogger.error(...args) : () => { },
660
+ };
661
+ }
662
+ /**
663
+ *
664
+ * The first step: init your application!
665
+ *
666
+ * Visit https://instantdb.com/dash to get your `appId` and `adminToken` :)
667
+ *
668
+ * @example
669
+ * const db = init({ appId: "my-app-id", adminToken: "my-admin-token" })
670
+ */
671
+ class InstantAdminDatabase {
672
+ config;
673
+ auth;
674
+ storage;
675
+ streams;
676
+ rooms;
677
+ impersonationOpts;
678
+ webhooks;
679
+ #sseConnection = null;
680
+ #sseBackoff = 0;
681
+ #instantStream = null;
682
+ #log;
683
+ tx = (0, instant_sdk_1.txInit)();
684
+ constructor(_config) {
685
+ this.config = instantConfigWithDefaults(_config);
686
+ this.auth = new Auth(this.config);
687
+ this.storage = new Storage(this.config, this.impersonationOpts);
688
+ this.streams = new Streams(this.#ensureInstantStream.bind(this));
689
+ this.rooms = new Rooms(this.config);
690
+ this.webhooks = new webhooks_1.Webhooks(this.config, jsonFetch);
691
+ this.#log = createLogger(!!this.config.verbose, this.config.logger);
692
+ }
693
+ /**
694
+ * Sometimes you want to scope queries to a specific user.
695
+ *
696
+ * You can provide a user's auth token, email, or impersonate a guest.
697
+ *
698
+ * @see https://instantdb.com/docs/backend#impersonating-users
699
+ * @example
700
+ * await db.asUser({email: "stopa@instantdb.com"}).query({ goals: {} })
701
+ */
702
+ asUser = (opts) => {
703
+ const newClient = new InstantAdminDatabase({
704
+ ...this.config,
705
+ });
706
+ newClient.impersonationOpts = opts;
707
+ newClient.storage = new Storage(this.config, opts);
708
+ return newClient;
709
+ };
710
+ /**
711
+ * Use this to query your data!
712
+ *
713
+ * @see https://instantdb.com/docs/instaql
714
+ *
715
+ * @example
716
+ * // fetch all goals
717
+ * await db.query({ goals: {} })
718
+ *
719
+ * // goals where the title is "Get Fit"
720
+ * await db.query({ goals: { $: { where: { title: "Get Fit" } } } })
721
+ *
722
+ * // all goals, _alongside_ their todos
723
+ * await db.query({ goals: { todos: {} } })
724
+ */
725
+ query = (query, opts = {}) => {
726
+ if (query && opts && 'ruleParams' in opts) {
727
+ query = { $$ruleParams: opts['ruleParams'], ...query };
728
+ }
729
+ if (!this.config.disableValidation) {
730
+ (0, instant_sdk_1.validateQuery)(query, this.config.schema);
731
+ }
732
+ const fetchOpts = opts.fetchOpts || {};
733
+ const fetchOptsHeaders = fetchOpts['headers'] || {};
734
+ return jsonFetch(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`, {
735
+ ...fetchOpts,
736
+ method: 'POST',
737
+ headers: {
738
+ ...fetchOptsHeaders,
739
+ ...authorizedHeaders(this.config, this.impersonationOpts),
740
+ },
741
+ body: JSON.stringify({
742
+ query: query,
743
+ 'inference?': !!this.config.schema,
744
+ }),
745
+ });
746
+ };
747
+ /**
748
+ * Use this to to get a live view of your data!
749
+ *
750
+ * @see https://www.instantdb.com/docs/backend
751
+ *
752
+ * @example
753
+ * // create a subscription to a query
754
+ * const query = { goals: { $: { where: { title: "Get Fit" } } } }
755
+ * const sub = db.subscribeQuery(query);
756
+ *
757
+ * // iterate through the results with an async iterator
758
+ * for await (const payload of sub) {
759
+ * if (payload.error) {
760
+ * console.log(payload.error);
761
+ * // Stop the subscription
762
+ * sub.close();
763
+ * } else {
764
+ * console.log(payload.data);
765
+ * }
766
+ * }
767
+ *
768
+ * // Stop the subscription
769
+ * sub.close();
770
+ *
771
+ * // Create a subscription with a callback
772
+ * const sub = db.subscribeQuery(query, (payload) => {
773
+ * if (payload.error) {
774
+ * console.log(payload.error);
775
+ * // Stop the subscription
776
+ * sub.close();
777
+ * } else {
778
+ * console.log(payload.data);
779
+ * }
780
+ * });
781
+ */
782
+ subscribeQuery(query, cb, opts = {}) {
783
+ if (query && opts && 'ruleParams' in opts) {
784
+ query = { $$ruleParams: opts['ruleParams'], ...query };
785
+ }
786
+ if (!this.config.disableValidation) {
787
+ (0, instant_sdk_1.validateQuery)(query, this.config.schema);
788
+ }
789
+ const fetchOpts = opts.fetchOpts || {};
790
+ const fetchOptsHeaders = fetchOpts['headers'] || {};
791
+ const headers = {
792
+ ...fetchOptsHeaders,
793
+ ...authorizedHeaders(this.config, this.impersonationOpts),
794
+ };
795
+ const inference = !!this.config.schema;
796
+ return (0, subscribe_ts_1.subscribe)(query, cb, {
797
+ headers,
798
+ inference,
799
+ apiURI: this.config.apiURI,
800
+ });
801
+ }
802
+ /**
803
+ * Use this to write data! You can create, update, delete, and link objects
804
+ *
805
+ * @see https://instantdb.com/docs/instaml
806
+ *
807
+ * @example
808
+ * // Create a new object in the `goals` namespace
809
+ * const goalId = id();
810
+ * db.transact(db.tx.goals[goalId].update({title: "Get fit"}))
811
+ *
812
+ * // Update the title
813
+ * db.transact(db.tx.goals[goalId].update({title: "Get super fit"}))
814
+ *
815
+ * // Delete it
816
+ * db.transact(db.tx.goals[goalId].delete())
817
+ *
818
+ * // Or create an association:
819
+ * todoId = id();
820
+ * db.transact([
821
+ * db.tx.todos[todoId].update({ title: 'Go on a run' }),
822
+ * db.tx.goals[goalId].link({todos: todoId}),
823
+ * ])
824
+ */
825
+ transact = (inputChunks) => {
826
+ if (!this.config.disableValidation) {
827
+ (0, instant_sdk_1.validateTransactions)(inputChunks, this.config.schema);
828
+ }
829
+ return jsonFetch(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`, {
830
+ method: 'POST',
831
+ headers: authorizedHeaders(this.config, this.impersonationOpts),
832
+ body: JSON.stringify({
833
+ steps: steps(inputChunks),
834
+ 'throw-on-missing-attrs?': !!this.config.schema,
835
+ }),
836
+ });
837
+ };
838
+ /**
839
+ * Like `query`, but returns debugging information
840
+ * for permissions checks along with the result.
841
+ * Useful for inspecting the values returned by the permissions checks.
842
+ * Note, this will return debug information for *all* entities
843
+ * that match the query's `where` clauses.
844
+ *
845
+ * Requires a user/guest context to be set with `asUser`,
846
+ * since permissions checks are user-specific.
847
+ *
848
+ * Accepts an optional configuration object with a `rules` key.
849
+ * The provided rules will override the rules in the database for the query.
850
+ *
851
+ * @see https://instantdb.com/docs/instaql
852
+ *
853
+ * @example
854
+ * await db.asUser({ guest: true }).debugQuery(
855
+ * { goals: {} },
856
+ * { rules: { goals: { allow: { read: "auth.id != null" } } }
857
+ * )
858
+ */
859
+ debugQuery = async (query, opts) => {
860
+ if (query && opts && 'ruleParams' in opts) {
861
+ query = { $$ruleParams: opts['ruleParams'], ...query };
862
+ }
863
+ const body = {
864
+ query,
865
+ 'rules-override': opts?.rules,
866
+ 'inference?': opts?.cardinalityInference ?? !!this.config.schema,
867
+ };
868
+ if (opts?.ip) {
869
+ body['ip-override'] = opts.ip;
870
+ }
871
+ if (opts?.origin) {
872
+ body['origin-override'] = opts.origin;
873
+ }
874
+ const response = await jsonFetch(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`, {
875
+ method: 'POST',
876
+ headers: authorizedHeaders(this.config, this.impersonationOpts),
877
+ body: JSON.stringify(body),
878
+ });
879
+ return {
880
+ result: response.result,
881
+ checkResults: response['check-results'],
882
+ };
883
+ };
884
+ /**
885
+ * Like `transact`, but does not write to the database.
886
+ * Returns debugging information for permissions checks.
887
+ * Useful for inspecting the values returned by the permissions checks.
888
+ *
889
+ * Requires a user/guest context to be set with `asUser`,
890
+ * since permissions checks are user-specific.
891
+ *
892
+ * Accepts an optional configuration object with a `rules` key.
893
+ * The provided rules will override the rules in the database for the duration of the transaction.
894
+ *
895
+ * @example
896
+ * const goalId = id();
897
+ * db.asUser({ guest: true }).debugTransact(
898
+ * [db.tx.goals[goalId].update({title: "Get fit"})],
899
+ * { rules: { goals: { allow: { update: "auth.id != null" } } }
900
+ * )
901
+ */
902
+ debugTransact = (inputChunks, opts) => {
903
+ const body = {
904
+ steps: steps(inputChunks),
905
+ 'rules-override': opts?.rules,
906
+ // @ts-expect-error because we're using a private API (for now)
907
+ 'dangerously-commit-tx': opts?.__dangerouslyCommit,
908
+ };
909
+ if (opts?.ip) {
910
+ body['ip-override'] = opts.ip;
911
+ }
912
+ if (opts?.origin) {
913
+ body['origin-override'] = opts.origin;
914
+ }
915
+ return jsonFetch(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`, {
916
+ method: 'POST',
917
+ headers: authorizedHeaders(this.config, this.impersonationOpts),
918
+ body: JSON.stringify(body),
919
+ });
920
+ };
921
+ #setupSSEConnection() {
922
+ if (this.#sseConnection) {
923
+ this.#sseConnection.close();
924
+ }
925
+ const headers = {
926
+ ...authorizedHeaders(this.config, this.impersonationOpts),
927
+ };
928
+ const inference = !!this.config.schema;
929
+ const ES = makeEventSourceWrapper({ headers, inference });
930
+ const conn = new instant_sdk_1.SSEConnection(ES, `${this.config.apiURI}/admin/sse?app_id=${this.config.appId}`, `${this.config.apiURI}/admin/sse/push?app_id=${this.config.appId}`);
931
+ conn.onopen = this.#onopen;
932
+ conn.onmessage = this.#onmessage;
933
+ conn.onclose = this.#onclose;
934
+ conn.onerror = this.#onerror;
935
+ this.#sseConnection = conn;
936
+ return conn;
937
+ }
938
+ #ensureSSEConnection() {
939
+ return this.#sseConnection || this.#setupSSEConnection();
940
+ }
941
+ #trySend(eventId, msg) {
942
+ const sseConnection = this.#ensureSSEConnection();
943
+ this.#log.info('[send]', eventId, msg, {
944
+ isOpen: sseConnection.isOpen(),
945
+ });
946
+ if (sseConnection.isOpen()) {
947
+ sseConnection.send({ 'client-event-id': eventId, ...msg });
948
+ }
949
+ }
950
+ #setupInstantStream() {
951
+ this.#ensureSSEConnection();
952
+ const instantStream = new instant_sdk_1.InstantStream({
953
+ WStream: this.config.WritableStream || WritableStream,
954
+ RStream: this.config.ReadableStream || ReadableStream,
955
+ trySend: (eventId, msg) => {
956
+ this.#trySend(eventId, msg);
957
+ },
958
+ log: this.#log,
959
+ });
960
+ this.#instantStream = instantStream;
961
+ return instantStream;
962
+ }
963
+ #ensureInstantStream() {
964
+ return this.#instantStream || this.#setupInstantStream();
965
+ }
966
+ #onopen = (e) => {
967
+ if (e.target !== this.#sseConnection) {
968
+ this.#log.info('[socket][open]', e.target.id, 'skip; this is no longer the current transport');
969
+ return;
970
+ }
971
+ this.#log.info('[socket][open]', e.target.id);
972
+ this.#sseBackoff = 0;
973
+ this.#instantStream?.onConnectionStatusChange('authenticated');
974
+ };
975
+ #onclose = (e) => {
976
+ if (e.target !== this.#sseConnection) {
977
+ this.#log.info('[socket][close]', e.target.id, 'skip; this is no longer the current transport');
978
+ return;
979
+ }
980
+ this.#log.info('[socket][close]', e.target.id);
981
+ this.#instantStream?.onConnectionStatusChange('closed');
982
+ if (this.#sseConnection) {
983
+ this.#sseConnection = null;
984
+ if (!this.#connectionIsIdle()) {
985
+ // We didn't remove the sse connection, and we have streams we care about, so let's try again
986
+ setTimeout(() => this.#ensureSSEConnection(), this.#sseBackoff);
987
+ this.#sseBackoff = Math.min(15000, Math.max(this.#sseBackoff, 500) * 2);
988
+ }
989
+ }
990
+ };
991
+ #onerror = (e) => {
992
+ if (e.target !== this.#sseConnection) {
993
+ this.#log.info('[socket][error]', e.target.id, 'skip; this is no longer the current transport');
994
+ return;
995
+ }
996
+ this.#log.info('[socket][error]', e.target.id);
997
+ this.#instantStream?.onConnectionStatusChange('closed');
998
+ };
999
+ #connectionIsIdle() {
1000
+ return !this.#instantStream || !this.#instantStream.hasActiveStreams();
1001
+ }
1002
+ #maybeShutdownConnection() {
1003
+ if (this.#sseConnection && this.#connectionIsIdle()) {
1004
+ const conn = this.#sseConnection;
1005
+ this.#log.info('cleaning up unused socket', conn.id);
1006
+ this.#sseConnection = null;
1007
+ conn.close();
1008
+ }
1009
+ }
1010
+ #onmessage = (e) => {
1011
+ if (e.target !== this.#sseConnection) {
1012
+ this.#log.info('[socket][message]', e.target.id, 'skip; this is no longer the current transport');
1013
+ return;
1014
+ }
1015
+ const msg = e.message;
1016
+ this.#log.info('[receive]', msg);
1017
+ switch (msg.op) {
1018
+ case 'start-stream-ok': {
1019
+ this.#instantStream?.onStartStreamOk(msg);
1020
+ break;
1021
+ }
1022
+ case 'stream-flushed': {
1023
+ this.#instantStream?.onStreamFlushed(msg);
1024
+ break;
1025
+ }
1026
+ case 'append-failed': {
1027
+ this.#instantStream?.onAppendFailed(msg);
1028
+ break;
1029
+ }
1030
+ case 'stream-append': {
1031
+ this.#instantStream?.onStreamAppend(msg);
1032
+ break;
1033
+ }
1034
+ case 'error': {
1035
+ switch (msg['original-event']?.op) {
1036
+ case 'start-stream':
1037
+ case 'append-stream':
1038
+ case 'subscribe-stream':
1039
+ case 'unsubscribe-stream': {
1040
+ this.#instantStream?.onRecieveError(msg);
1041
+ break;
1042
+ }
1043
+ }
1044
+ break;
1045
+ }
1046
+ }
1047
+ // Closes the connection if we don't have any items pending
1048
+ this.#maybeShutdownConnection();
1049
+ };
1050
+ }
1051
+ //# sourceMappingURL=index.js.map