/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/@instantdb/admin@1.0.1/dist/commonjs/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
"use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.setInstantWarningsEnabled=exports.InstantAPIError=exports.createInstantRouteHandler=exports.i=exports.lookup=exports.tx=exports.id=exports.init_experimental=void 0,exports.init=init;const uuid_1=require("uuid"),core_1=require("@instantdb/core");Object.defineProperty(exports,"tx",{enumerable:!0,get:function(){return core_1.tx}}),Object.defineProperty(exports,"lookup",{enumerable:!0,get:function(){return core_1.lookup}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return core_1.i}}),Object.defineProperty(exports,"id",{enumerable:!0,get:function(){return core_1.id}}),Object.defineProperty(exports,"InstantAPIError",{enumerable:!0,get:function(){return core_1.InstantAPIError}}),Object.defineProperty(exports,"setInstantWarningsEnabled",{enumerable:!0,get:function(){return core_1.setInstantWarningsEnabled}}),Object.defineProperty(exports,"createInstantRouteHandler",{enumerable:!0,get:function(){return core_1.createInstantRouteHandler}});const version_ts_1=__importDefault(require("./version.js")),subscribe_ts_1=require("./subscribe.js"),cookie_1=require("cookie"),eventsource_1=require("eventsource");function configWithDefaults(e){return{apiURI:"https://api.instantdb.com",...e}}function instantConfigWithDefaults(e){const t={apiURI:"https://api.instantdb.com"},n={...t,...e};return n.apiURI||(n.apiURI=t.apiURI),n}function withImpersonation(e,t){return"email"in t?e["as-email"]=t.email:"token"in t?e["as-token"]=t.token:"guest"in t&&(e["as-guest"]="true"),e}function validateConfigAndImpersonation(e,t){if(!(t&&("token"in t||"guest"in t)||e.adminToken)){if(t&&"email"in t)throw new Error("Admin token required. To impersonate users with an email you must pass `adminToken` to `init`.");throw new Error("Admin token required. To run this operation pass `adminToken` to `init`, or use `db.asUser`.")}}function authorizedHeaders(e,t){validateConfigAndImpersonation(e,t);const{adminToken:n,appId:i}=e,s={"content-type":"application/json","app-id":i};return n&&(s.authorization=`Bearer ${n}`),t?withImpersonation(s,t):s}function isNextJSVersionThatCachesFetchByDefault(){return fetch.__nextPatched&&!globalThis[Symbol.for("next-patch")]}function getDefaultFetchOpts(){return isNextJSVersionThatCachesFetchByDefault()?{cache:"no-store"}:{}}async function jsonReject(e,t){const n=await t.text();try{const i=JSON.parse(n);return e(new core_1.InstantAPIError({status:t.status,body:i}))}catch(i){return e(new core_1.InstantAPIError({status:t.status,body:{type:void 0,message:n}}))}}async function jsonFetch(e,t){const n=getDefaultFetchOpts(),i={...t?.headers||{},"Instant-Admin-Version":version_ts_1.default,"Instant-Core-Version":core_1.version},s=await fetch(e,{...n,...t,headers:i});if(200===s.status){const e=await s.json();return Promise.resolve(e)}return jsonReject((e=>Promise.reject(e)),s)}function makeEventSourceWrapper(e){return class{source;static OPEN=eventsource_1.EventSource.OPEN;static CONNECTING=eventsource_1.EventSource.CONNECTING;static CLOSED=eventsource_1.EventSource.CLOSED;url;constructor(e){this.url=e,this.source=this.#e(e)}get onopen(){return this.source.onopen}set onopen(e){this.source.onopen=e}get onmessage(){return this.source.onmessage}set onmessage(e){this.source.onmessage=e}get onerror(){return this.source.onerror}set onerror(e){this.source.onerror=e}get readyState(){return this.source.readyState}close(){this.source.close()}#e(t){const n=new eventsource_1.EventSource(t,{fetch:(t,n)=>fetch(t,{...n,method:"POST",headers:e.headers,body:JSON.stringify({"inference?":e.inference,versions:{"@instantdb/admin":version_ts_1.default,"@instantdb/core":core_1.version}})})});return n}}}function init(e){e.appId&&(0,uuid_1.validate)(e.appId)||console.warn("warning: Instant Admin DB must be initialized with a valid appId. Received: "+JSON.stringify(e.appId));const t={...e,appId:e.appId?.trim(),adminToken:e.adminToken?.trim(),useDateObjects:e.useDateObjects??!1};return new InstantAdminDatabase(t)}const init_experimental=init;function steps(e){return(Array.isArray(e)?e:[e]).flatMap(core_1.getOps)}exports.init_experimental=init_experimental;class Rooms{config;constructor(e){this.config=e}async getPresence(e,t){return(await jsonFetch(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(e)}&room-id=${t}`,{method:"GET",headers:authorizedHeaders(this.config)})).sessions||{}}}class Auth{config;constructor(e){this.config=e,this.createToken=this.createToken.bind(this)}generateMagicCode=async e=>jsonFetch(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config),body:JSON.stringify({email:e})});sendMagicCode=async e=>jsonFetch(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config),body:JSON.stringify({email:e})});verifyMagicCode=async(e,t)=>{const{user:n}=await jsonFetch(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config),body:JSON.stringify({email:e,code:t})});return n};checkMagicCode=async(e,t,n)=>{const i=await jsonFetch(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config),body:JSON.stringify({email:e,code:t,...n?.extraFields?{"extra-fields":n.extraFields}:{}})});return{user:i.user,created:i.created}};async createToken(e){const t="string"==typeof e?{email:e}:e;return(await jsonFetch(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config),body:JSON.stringify(t)})).user.refresh_token}verifyToken=async e=>(await jsonFetch(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":this.config.appId,"refresh-token":e})})).user;getUser=async e=>{const t=Object.entries(e).map((([e,t])=>`${e}=${encodeURIComponent(t)}`)).join("&");return(await jsonFetch(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${t}`,{method:"GET",headers:authorizedHeaders(this.config)})).user};deleteUser=async e=>{const t=Object.entries(e).map((([e,t])=>`${e}=${t}`));return(await jsonFetch(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${t}`,{method:"DELETE",headers:authorizedHeaders(this.config)})).deleted};async signOut(e){const t="string"==typeof e?{email:e}:e,n=this.config;await jsonFetch(`${n.apiURI}/admin/sign_out?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(n),body:JSON.stringify(t)})}getUserFromRequest=async(e,t)=>{const n=e.headers.get("cookie")||"",i=(0,cookie_1.parseCookie)(n),s="instant_user_"+this.config.appId;if(!i[s])return null;const o=i[s],r=JSON.parse(o);if(!r?.refresh_token)return null;if(t?.disableValidation)return r;return await this.verifyToken(r.refresh_token)}}const isNodeReadable=e=>e&&"object"==typeof e&&"function"==typeof e.pipe&&"function"==typeof e.read,isWebReadable=e=>e&&"function"==typeof e.getReader;class Storage{config;impersonationOpts;constructor(e,t){this.config=e,this.impersonationOpts=t}uploadFile=async(e,t,n={})=>{const i={...authorizedHeaders(this.config,this.impersonationOpts),path:e};let s;if(n.contentDisposition&&(i["content-disposition"]=n.contentDisposition),delete i["content-type"],n.contentType&&(i["content-type"]=n.contentType),isNodeReadable(t)&&(s="half"),isNodeReadable(t)||isWebReadable(t)){if(!n.fileSize)throw new Error("fileSize is required in metadata when uploading streams");i["content-length"]=n.fileSize.toString()}let o={method:"PUT",headers:i,body:t,...s&&{duplex:s}};return jsonFetch(`${this.config.apiURI}/admin/storage/upload?app_id=${this.config.appId}`,o)};delete=async e=>jsonFetch(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(e)}`,{method:"DELETE",headers:authorizedHeaders(this.config,this.impersonationOpts)});deleteMany=async e=>jsonFetch(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config,this.impersonationOpts),body:JSON.stringify({filenames:e})});upload=async(e,t,n={})=>{const{data:i}=await jsonFetch(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config),body:JSON.stringify({app_id:this.config.appId,filename:e})}),s={},o=n.contentType;o&&(s["Content-Type"]=o);const{ok:r}=await fetch(i,{method:"PUT",body:t,headers:s});return r};list=async()=>{const{data:e}=await jsonFetch(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`,{method:"GET",headers:authorizedHeaders(this.config)});return e};getDownloadUrl=async e=>{const{data:t}=await jsonFetch(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(e)}`,{method:"GET",headers:authorizedHeaders(this.config)});return t}}class Streams{#t;constructor(e){this.#t=e}createReadStream=e=>this.#t().createReadStream(e);createWriteStream=e=>this.#t().createWriteStream(e)}function createLogger(e){return{info:e?(...e)=>console.info(...e):()=>{},debug:e?(...e)=>console.debug(...e):()=>{},error:e?(...e)=>console.error(...e):()=>{}}}class InstantAdminDatabase{config;auth;storage;streams;rooms;impersonationOpts;#n=null;#i=0;#s=null;#o;tx=(0,core_1.txInit)();constructor(e){this.config=instantConfigWithDefaults(e),this.auth=new Auth(this.config),this.storage=new Storage(this.config,this.impersonationOpts),this.streams=new Streams(this.#t.bind(this)),this.rooms=new Rooms(this.config),this.#o=createLogger(!!this.config.verbose)}asUser=e=>{const t=new InstantAdminDatabase({...this.config});return t.impersonationOpts=e,t.storage=new Storage(this.config,e),t};query=(e,t={})=>{e&&t&&"ruleParams"in t&&(e={$$ruleParams:t.ruleParams,...e}),this.config.disableValidation||(0,core_1.validateQuery)(e,this.config.schema);const n=t.fetchOpts||{},i=n.headers||{};return jsonFetch(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`,{...n,method:"POST",headers:{...i,...authorizedHeaders(this.config,this.impersonationOpts)},body:JSON.stringify({query:e,"inference?":!!this.config.schema})})};subscribeQuery(e,t,n={}){e&&n&&"ruleParams"in n&&(e={$$ruleParams:n.ruleParams,...e}),this.config.disableValidation||(0,core_1.validateQuery)(e,this.config.schema);const i={...(n.fetchOpts||{}).headers||{},...authorizedHeaders(this.config,this.impersonationOpts)},s=!!this.config.schema;return(0,subscribe_ts_1.subscribe)(e,t,{headers:i,inference:s,apiURI:this.config.apiURI})}transact=e=>(this.config.disableValidation||(0,core_1.validateTransactions)(e,this.config.schema),jsonFetch(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config,this.impersonationOpts),body:JSON.stringify({steps:steps(e),"throw-on-missing-attrs?":!!this.config.schema})}));debugQuery=async(e,t)=>{e&&t&&"ruleParams"in t&&(e={$$ruleParams:t.ruleParams,...e});const n={query:e,"rules-override":t?.rules,"inference?":t?.cardinalityInference??!!this.config.schema};t?.ip&&(n["ip-override"]=t.ip),t?.origin&&(n["origin-override"]=t.origin);const i=await jsonFetch(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config,this.impersonationOpts),body:JSON.stringify(n)});return{result:i.result,checkResults:i["check-results"]}};debugTransact=(e,t)=>{const n={steps:steps(e),"rules-override":t?.rules,"dangerously-commit-tx":t?.__dangerouslyCommit};return t?.ip&&(n["ip-override"]=t.ip),t?.origin&&(n["origin-override"]=t.origin),jsonFetch(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:authorizedHeaders(this.config,this.impersonationOpts),body:JSON.stringify(n)})};#r(){this.#n&&this.#n.close();const e=makeEventSourceWrapper({headers:{...authorizedHeaders(this.config,this.impersonationOpts)},inference:!!this.config.schema}),t=new core_1.SSEConnection(e,`${this.config.apiURI}/admin/sse?app_id=${this.config.appId}`,`${this.config.apiURI}/admin/sse/push?app_id=${this.config.appId}`);return t.onopen=this.#a,t.onmessage=this.#c,t.onclose=this.#d,t.onerror=this.#h,this.#n=t,t}#p(){return this.#n||this.#r()}#u(e,t){const n=this.#p();this.#o.info("[send]",e,t,{isOpen:n.isOpen()}),n.isOpen()&&n.send({"client-event-id":e,...t})}#f(){this.#p();const e=new core_1.InstantStream({WStream:this.config.WritableStream||WritableStream,RStream:this.config.ReadableStream||ReadableStream,trySend:(e,t)=>{this.#u(e,t)},log:this.#o});return this.#s=e,e}#t(){return this.#s||this.#f()}#a=e=>{e.target===this.#n?(this.#o.info("[socket][open]",e.target.id),this.#i=0,this.#s?.onConnectionStatusChange("authenticated")):this.#o.info("[socket][open]",e.target.id,"skip; this is no longer the current transport")};#d=e=>{e.target===this.#n?(this.#o.info("[socket][close]",e.target.id),this.#s?.onConnectionStatusChange("closed"),this.#n&&(this.#n=null,this.#g()||(setTimeout((()=>this.#p()),this.#i),this.#i=Math.min(15e3,2*Math.max(this.#i,500))))):this.#o.info("[socket][close]",e.target.id,"skip; this is no longer the current transport")};#h=e=>{e.target===this.#n?(this.#o.info("[socket][error]",e.target.id),this.#s?.onConnectionStatusChange("closed")):this.#o.info("[socket][error]",e.target.id,"skip; this is no longer the current transport")};#g(){return!this.#s||!this.#s.hasActiveStreams()}#m(){if(this.#n&&this.#g()){const e=this.#n;this.#o.info("cleaning up unused socket",e.id),this.#n=null,e.close()}}#c=e=>{if(e.target!==this.#n)return void this.#o.info("[socket][message]",e.target.id,"skip; this is no longer the current transport");const t=e.message;switch(this.#o.info("[receive]",t),t.op){case"start-stream-ok":this.#s?.onStartStreamOk(t);break;case"stream-flushed":this.#s?.onStreamFlushed(t);break;case"append-failed":this.#s?.onAppendFailed(t);break;case"stream-append":this.#s?.onStreamAppend(t);break;case"error":switch(t["original-event"]?.op){case"start-stream":case"append-stream":case"subscribe-stream":case"unsubscribe-stream":this.#s?.onRecieveError(t)}}this.#m()}}
//# sourceMappingURL=/sm/fcaf26621411ef194558e5d5f633314471d99324e0b16133c81737c9bbb1ef3c.map