Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

fauna

Package Overview
Dependencies
Maintainers
2
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

fauna - npm Package Compare versions

Comparing version 1.2.0 to 1.3.0

2

dist/browser/index.js

@@ -1,2 +0,2 @@

var Ce=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+t+'" is not supported')});var Pe=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)};var i=(t,e,r)=>(Pe(t,e,"read from private field"),r?r.call(t):e.get(t)),c=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},f=(t,e,r,s)=>(Pe(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),Ne=(t,e,r,s)=>({set _(n){f(t,e,n,r)},get _(){return i(t,e,s)}}),l=(t,e,r)=>(Pe(t,e,"access private method"),r);var ke={default:new URL("https://db.fauna.com"),local:new URL("http://localhost:8443"),localhost:new URL("http://localhost:8443")};var C=class extends Error{constructor(...e){super(...e)}},d=class extends C{httpStatus;code;queryInfo;constraint_failures;constructor(e,r){super(e.error.message),Error.captureStackTrace&&Error.captureStackTrace(this,d),this.name="ServiceError",this.code=e.error.code,this.httpStatus=r;let s={txn_ts:e.txn_ts,summary:e.summary,query_tags:e.query_tags,stats:e.stats};this.queryInfo=s,this.constraint_failures=e.error.constraint_failures}},F=class extends d{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,F),this.name="QueryRuntimeError"}},P=class extends d{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,P),this.name="QueryCheckError"}},N=class extends d{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,N),this.name="InvalidRequestError"}},ne=class extends d{abort;constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,P),this.name="AbortError",this.abort=e.error.abort}},M=class extends d{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,M),this.name="AuthenticationError"}},W=class extends d{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,W),this.name="AuthorizationError"}},se=class extends d{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,N),this.name="ContendedTransactionError"}},k=class extends d{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,k),this.name="ThrottlingError"}},v=class extends d{stats;constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,v),this.name="QueryTimeoutError",this.stats=e.stats}},j=class extends d{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,j),this.name="ServiceInternalError"}},$=class extends d{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,$),this.name="ServiceTimeoutError"}},w=class extends C{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,w),this.name="ClientError"}},A=class extends C{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,A),this.name="ClientClosedError"}},x=class extends C{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,x),this.name="NetworkError"}},_=class extends C{httpStatus;constructor(e){super(e.message),Error.captureStackTrace&&Error.captureStackTrace(this,_),this.name="ProtocolError",this.httpStatus=e.httpStatus}};var oe=class{#e;#t;constructor({url:e,fetch_keepalive:r}){this.#e=new URL("/query/1",e).toString(),this.#t=r}async request({data:e,headers:r,method:s,client_timeout_ms:n}){let o=AbortSignal.timeout===void 0?(()=>{let T=new AbortController,m=T.signal;return setTimeout(()=>T.abort(),n),m})():AbortSignal.timeout(n),a=await fetch(this.#e,{method:s,headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(e),signal:o,keepalive:this.#t}).catch(T=>{throw new x("The network connection encountered a problem.",{cause:T})}),u=a.status,p={};a.headers.forEach((T,m)=>p[m]=T);let b=await a.text();return{status:u,body:b,headers:p}}close(){}};var L;try{L=Ce("node:http2")}catch{L=void 0}var J,ie,ae,ce,I,y,pe,ve,K,me,fe,je,ye,$e,U=class{constructor({http2_session_idle_ms:e,url:r,http2_max_streams:s}){c(this,K);c(this,fe);c(this,ye);c(this,ie,void 0);c(this,ae,void 0);c(this,ce,void 0);c(this,I,0);c(this,y,void 0);if(L===void 0)throw new Error("Your platform does not support Node's http2 library");f(this,ie,e),f(this,ae,s),f(this,ce,r),f(this,y,null)}static getClient(e){var n;let r=l(n=U,pe,ve).call(n,e);i(U,J).has(r)||i(U,J).set(r,new U(e));let s=i(U,J).get(r);return Ne(s,I)._++,s}async request(e){let r=0,s;do try{return await l(this,ye,$e).call(this,e)}catch(n){if(n?.code!=="ERR_HTTP2_GOAWAY_SESSION")throw new x("The network connection encountered a problem.",{cause:n});s=n,r++}while(r<3);throw new x("The network connection encountered a problem.",{cause:s})}close(){this.isClosed()||(Ne(this,I)._--,i(this,I)===0&&i(this,y)&&!i(this,y).closed&&i(this,y).close())}isClosed(){return i(this,I)===0}},G=U;J=new WeakMap,ie=new WeakMap,ae=new WeakMap,ce=new WeakMap,I=new WeakMap,y=new WeakMap,pe=new WeakSet,ve=function({http2_session_idle_ms:e,url:r}){return`${r}|${e}`},K=new WeakSet,me=function(){f(this,I,0),i(this,y)&&!i(this,y).closed&&i(this,y).close()},fe=new WeakSet,je=function(){if(!i(this,y)||i(this,y).closed||i(this,y).destroyed){let e=L.connect(i(this,ce),{peerMaxConcurrentStreams:i(this,ae)}).once("error",()=>l(this,K,me).call(this)).once("goaway",()=>l(this,K,me).call(this));e.setTimeout(i(this,ie),()=>{l(this,K,me).call(this)}),f(this,y,e)}return i(this,y)},ye=new WeakSet,$e=function({client_timeout_ms:e,data:r,headers:s,method:n}){return new Promise((o,a)=>{let u,p=b=>{let T=Number(b[L.constants.HTTP2_HEADER_STATUS]),m="";u.on("data",z=>{m+=z}),u.on("end",()=>{o({status:T,body:m,headers:b})})};try{let b={...s,[L.constants.HTTP2_HEADER_PATH]:"/query/1",[L.constants.HTTP2_HEADER_METHOD]:n};u=l(this,fe,je).call(this).request(b).setEncoding("utf8").on("error",m=>{a(m)}).on("response",p),u.write(JSON.stringify(r),"utf8"),u.setTimeout(e,()=>{u.destroy(new Error("Client timeout"))}),u.end()}catch(b){a(b)}})},c(G,pe),c(G,J,new Map);var Ae=t=>mt()?G.getClient(t):new oe(t),Ie=t=>t instanceof Object&&"body"in t&&"headers"in t&&"status"in t,mt=()=>{if(typeof process<"u"&&process&&process.release?.name==="node")try{return Ce("node:http2"),!0}catch{return!1}return!1};var pt=/(?:\d{4}|[\u2212-]\d{4,}|\+\d{5,})/,ft=/(?:0[1-9]|1[0-2])/,yt=/(?:0[1-9]|[12]\d|3[01])/,Le=/(?:[01][0-9]|2[0-3])/,ue=/(?:[0-5][0-9])/,gt=/(?:\.\d+)/,De=new RegExp(`(${pt.source}-(${ft.source})-(${yt.source}))`),Tt=new RegExp(`(${Le.source}:${ue.source}:${ue.source}${gt.source}?)`),ht=new RegExp(`([zZ]|[+\u2212-]${Le.source}(?::?${ue.source}|:${ue.source}:${ue.source}))`),Ue=new RegExp(`^${De.source}$`),Ge=new RegExp(`^${De.source}`),Be=new RegExp(`^${De.source}T${Tt.source}${ht.source}$`);var E=class{isoString;constructor(e){this.isoString=e}static from(e){if(typeof e!="string")throw new TypeError(`Expected string but received ${typeof e}: ${e}`);if(Be.exec(e)===null)throw new RangeError(`(regex) Expected an ISO date string but received '${e}'`);return new E(e)}static fromDate(e){return new E(e.toISOString())}toDate(){let e=new Date(this.isoString);if(e.toString()==="Invalid Date")throw new RangeError("Fauna Date could not be converted to Javascript Date");return e}toString(){return`TimeStub("${this.isoString}")`}},Q=class{dateString;constructor(e){this.dateString=e}static from(e){if(typeof e!="string")throw new TypeError(`Expected string but received ${typeof e}: ${e}`);let r=Ue.exec(e);if(r===null)throw new RangeError(`Expected a plain date string but received '${e}'`);return new Q(r[0])}static fromDate(e){let r=e.toISOString(),s=Ge.exec(r);if(s===null)throw new w(`Failed to parse date '${e}'`);return new Q(s[0])}toDate(){let e=new Date(this.dateString+"T00:00:00Z");if(e.toString()==="Invalid Date")throw new RangeError("Fauna Date could not be converted to Javascript Date");return e}toString(){return`DateStub("${this.dateString}")`}};var D=class{coll;id;constructor({coll:e,id:r}){this.id=r,typeof e=="string"?this.coll=new V(e):this.coll=e}},Z=class extends D{ts;constructor(e){let{coll:r,id:s,ts:n,...o}=e;super({coll:r,id:s}),this.ts=n,Object.assign(this,o)}toObject(){return{...this}}},B=class{coll;name;constructor({coll:e,name:r}){this.name=r,typeof e=="string"?this.coll=new V(e):this.coll=e}},ee=class extends B{ts;data;constructor(e){let{coll:r,name:s,ts:n,data:o,...a}=e;super({coll:r,name:s}),this.ts=n,this.data=o||{},Object.assign(this,a)}toObject(){return{...this}}},V=class{name;constructor(e){this.name=e}},te=class{ref;cause;constructor(e,r){this.ref=e,this.cause=r}};var O=class{data;after;constructor({data:e,after:r}){this.data=e,this.after=r}},q=class{after;constructor(e){this.after=e}},R=class{#e;constructor(e,r,s){if(s=s??{},r instanceof Function)this.#e=wt(e,r,s);else if(r instanceof O||r instanceof q)this.#e=Xe(e,r,s);else throw new TypeError(`Expected 'Page<T> | EmbeddedSet | (() => Promise<T | Page<T> | EmbeddedSet>)', but received ${JSON.stringify(r)}`)}static fromQuery(e,r,s){return new R(e,async()=>(await e.query(r,s)).data,s)}static fromPageable(e,r,s){return new R(e,r,s)}flatten(){return new Ve(this)}async next(){return this.#e.next()}async return(){return this.#e.return()}async throw(e){return this.#e.throw(e)}[Symbol.asyncIterator](){return this}},Ve=class{#e;constructor(e){this.#e=xt(e)}async next(){return this.#e.next()}async return(){return this.#e.return()}async throw(e){return this.#e.throw(e)}[Symbol.asyncIterator](){return this}};async function*Xe(t,e,r){let s=e;for(s instanceof O&&(yield s.data);s.after;){let n=qe`Set.paginate(${s.after})`;s=(await t.query(n,r)).data,yield s.data}}async function*wt(t,e,r){let s=await e();if(s instanceof O||s instanceof q){for await(let n of Xe(t,s,r))yield n;return}yield[s]}async function*xt(t){for await(let e of t)for(let r of e)yield r}var H=class{static encode(e){return ge(e)}static decode(e,r){return JSON.parse(e,(s,n)=>{if(n==null)return null;if(n["@mod"])return new V(n["@mod"]);if(n["@doc"]){if(typeof n["@doc"]=="string"){let[a,u]=n["@doc"].split(":");return new D({coll:a,id:u})}let o=n["@doc"];return o.id?new Z(o):new ee(o)}else if(n["@ref"]){let o=n["@ref"],a;return o.id?a=new D(o):a=new B(o),"exists"in o&&o.exists===!1?new te(a,o.cause):a}else{if(n["@set"])return typeof n["@set"]=="string"?new q(n["@set"]):new O(n["@set"]);if(n["@int"])return Number(n["@int"]);if(n["@long"]){let o=BigInt(n["@long"]);return r.long_type==="number"?((o>Number.MAX_SAFE_INTEGER||o<Number.MIN_SAFE_INTEGER)&&console.warn("Value is too large to be represented as a number. Returning as Number with loss of precision. Use long_type 'bigint' instead."),Number(o)):o}else{if(n["@double"])return Number(n["@double"]);if(n["@date"])return Q.from(n["@date"]);if(n["@time"])return E.from(n["@time"]);if(n["@object"])return n["@object"]}}return n})}},Je=BigInt("-9223372036854775808"),Ke=BigInt("9223372036854775807"),Ye=-(2**31),ze=2**31-1,g={bigint:t=>{if(t<Je||t>Ke)throw new RangeError("BigInt value exceeds max magnitude for a 64-bit Fauna long. Use a 'number' to represent doubles beyond that limit.");return t>=Ye&&t<=ze?{"@int":t.toString()}:{"@long":t.toString()}},number:t=>{if(t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY)throw new RangeError(`Cannot convert ${t} to a Fauna type.`);return Number.isInteger(t)?t>=Ye&&t<=ze?{"@int":t.toString()}:Number.isSafeInteger(t)?{"@long":t.toString()}:{"@double":t.toString()}:{"@double":t.toString()}},string:t=>t,object:t=>{let e=!1,r={};for(let s in t)s.startsWith("@")&&(e=!0),t[s]!==void 0&&(r[s]=ge(t[s]));return e?{"@object":r}:r},array:t=>{let e=[];for(let r in t)e.push(ge(t[r]));return e},date:t=>({"@time":t.toISOString()}),faunadate:t=>({"@date":t.dateString}),faunatime:t=>({"@time":t.isoString}),module:t=>({"@mod":t.name}),documentReference:t=>({"@ref":{id:t.id,coll:{"@mod":t.coll.name}}}),document:t=>({"@ref":{id:t.id,coll:{"@mod":t.coll.name}}}),namedDocumentReference:t=>({"@ref":{name:t.name,coll:{"@mod":t.coll.name}}}),namedDocument:t=>({"@ref":{name:t.name,coll:{"@mod":t.coll.name}}}),set:t=>{throw new w("Page could not be encoded. Fauna does not accept encoded Set values, yet. Use Page.data and Page.after as arguments, instead.")}},ge=t=>{if(t===void 0)throw new TypeError("Passing undefined as a QueryValue is not supported");switch(typeof t){case"bigint":return g.bigint(t);case"string":return g.string(t);case"number":return g.number(t);case"boolean":return t;case"object":return t==null?null:Array.isArray(t)?g.array(t):t instanceof Date?g.date(t):t instanceof Q?g.faunadate(t):t instanceof E?g.faunatime(t):t instanceof V?g.module(t):t instanceof Z?g.document(t):t instanceof D?g.documentReference(t):t instanceof ee?g.namedDocument(t):t instanceof B?g.namedDocumentReference(t):t instanceof te?ge(t.ref):t instanceof O||t instanceof q?g.set(t):g.object(t)}};function qe(t,...e){return new X(t,...e)}var X=class{#e;#t;constructor(e,...r){if(e.length===0||e.length!==r.length+1)throw new Error("invalid query constructed");this.#e=e,this.#t=r}toQuery(e={}){return{...this.#r(e),...e}}#r(e){if(this.#e.length===1)return{query:{fql:[this.#e[0]]},arguments:{}};let r={};return{query:{fql:this.#e.flatMap((n,o)=>{if(o===this.#e.length-1)return n===""?[]:[n];let a=this.#t[o],u;if(a instanceof X){let p=a.toQuery(e);u=p.query,r={...r,...p.arguments}}else u={value:H.encode(a)};return[n,u].filter(p=>p!=="")})},arguments:r}}};var Ze="1.2.0";var Te;try{Te=Ce("node:os")}catch{Te=void 0}var rt=()=>{let t={driver:["javascript",Ze].join("-"),env:"unknown",os:"unknown",runtime:"unknown"};try{let e=typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null,r=typeof window<"u"&&typeof window.document<"u",s=typeof self=="object"&&self.constructor&&self.constructor.name==="DedicatedWorkerGlobalScope";e?(t.runtime=["nodejs",process.version].join("-"),t.env=_t(),t.os=[Te.platform(),Te.release()].join("-")):s?(t.runtime=et(navigator),t.env="Service Worker",t.os=tt(navigator)):r?(t.runtime=et(navigator),t.env="browser",t.os=tt(navigator)):typeof EdgeRuntime!="string"&&(t.runtime="Vercel Edge Runtime",t.env="edge")}catch{}return Object.entries(t).filter(([e,r])=>r!=="unknown").map(e=>e.join("=")).join("; ")},et=t=>{let e=t.appName,r=""+parseFloat(t.appVersion),s,n,o;return(n=t.userAgent.indexOf("Opera"))!=-1?(e="Opera",r=t.userAgent.substring(n+6),(n=t.userAgent.indexOf("Version"))!=-1&&(r=t.userAgent.substring(n+8))):(n=t.userAgent.indexOf("MSIE"))!=-1?(e="Microsoft Internet Explorer",r=t.userAgent.substring(n+5)):e=="Netscape"&&t.userAgent.indexOf("Trident/")!=-1?(e="Microsoft Internet Explorer",r=t.userAgent.substring(n+5),(n=t.userAgent.indexOf("rv:"))!=-1&&(r=t.userAgent.substring(n+3))):(n=t.userAgent.indexOf("Chrome"))!=-1?(e="Chrome",r=t.userAgent.substring(n+7)):(n=t.userAgent.indexOf("Safari"))!=-1?(e="Safari",r=t.userAgent.substring(n+7),(n=t.userAgent.indexOf("Version"))!=-1&&(r=t.userAgent.substring(n+8)),t.userAgent.indexOf("CriOS")!=-1&&(e="Chrome")):(n=t.userAgent.indexOf("Firefox"))!=-1?(e="Firefox",r=t.userAgent.substring(n+8)):(s=t.userAgent.lastIndexOf(" ")+1)<(n=t.userAgent.lastIndexOf("/"))&&(e=t.userAgent.substring(s,n),r=t.userAgent.substring(n+1),e.toLowerCase()==e.toUpperCase()&&(e=t.appName)),(o=r.indexOf(";"))!=-1&&(r=r.substring(0,o)),(o=r.indexOf(" "))!=-1&&(r=r.substring(0,o)),(o=r.indexOf(")"))!=-1&&(r=r.substring(0,o)),[e,r].join("-")},tt=t=>{let e="unknown",r=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Windows Vista",r:/Windows NT 6.0/},{s:"Windows Server 2003",r:/Windows NT 5.2/},{s:"Windows XP",r:/(Windows NT 5.1|Windows XP)/},{s:"Windows 2000",r:/(Windows NT 5.0|Windows 2000)/},{s:"Windows ME",r:/(Win 9x 4.90|Windows ME)/},{s:"Windows 98",r:/(Windows 98|Win98)/},{s:"Windows 95",r:/(Windows 95|Win95|Windows_95)/},{s:"Windows NT 4.0",r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},{s:"Windows CE",r:/Windows CE/},{s:"Windows 3.11",r:/Win16/},{s:"Android",r:/Android/},{s:"Open BSD",r:/OpenBSD/},{s:"Sun OS",r:/SunOS/},{s:"Chrome OS",r:/CrOS/},{s:"Linux",r:/(Linux|X11(?!.*CrOS))/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"QNX",r:/QNX/},{s:"UNIX",r:/UNIX/},{s:"BeOS",r:/BeOS/},{s:"OS/2",r:/OS\/2/},{s:"Search Bot",r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}];for(let n in r){let o=r[n];if(o.r.test(t.userAgent)){e=o.s;break}}let s="unknown";if(/Windows/.test(e)){let n=/Windows (.*)/.exec(e);n&&(s=n[1]),e="Windows"}switch(e){case"Mac OS":case"Mac OS X":case"Android":{let n=/(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([._\d]+)/.exec(t.userAgent);n&&(s=n[1]);break}case"iOS":{let n=/OS (\d+)_(\d+)_?(\d+)?/.exec(t.appVersion);n&&(s=n[1]+"."+n[2]+"."+(n[3]??0));break}}return[e,s].join("-")},St=typeof window<"u"?window:typeof globalThis<"u"?globalThis:typeof global<"u"?global:self,_t=()=>{if(!(typeof process<"u"&&process&&process.env&&typeof process.env=="object"))return"unknown";let e=[{name:"Netlify",check:function(){return!!process.env.NETLIFY_IMAGES_CDN_DOMAIN}},{name:"Vercel",check:function(){return!!process.env.VERCEL}},{name:"Heroku",check:function(){return!!process.env.PATH&&process.env.PATH.indexOf(".heroku")!==-1}},{name:"AWS Lambda",check:function(){return!!process.env.AWS_LAMBDA_FUNCTION_VERSION}},{name:"GCP Cloud Functions",check:function(){return!!process.env._&&process.env._.indexOf("google")!==-1}},{name:"GCP Compute Instances",check:function(){return!!process.env.GOOGLE_CLOUD_PROJECT}},{name:"Azure Cloud Functions",check:function(){return!!process.env.WEBSITE_FUNCTIONS_AZUREMONITOR_CATEGORIES}},{name:"Azure Compute",check:function(){return!!process.env.ORYX_ENV_TYPE&&!!process.env.WEBSITE_INSTANCE_ID&&process.env.ORYX_ENV_TYPE==="AppService"}},{name:"Mongo Stitch",check:function(){return typeof St?.StitchError=="function"}},{name:"Render",check:function(){return!!process.env.RENDER_SERVICE_ID}},{name:"Begin",check:function(){return!!process.env.BEGIN_DATA_SCOPE_ID}}].find(r=>r.check());return e?e.name:"unknown"};var nt=t=>t instanceof Object&&"data"in t,st=t=>t instanceof Object&&"error"in t&&t.error instanceof Object&&"code"in t.error&&"message"in t.error;var He={client_timeout_buffer_ms:5e3,format:"tagged",http2_session_idle_ms:5e3,http2_max_streams:100,long_type:"number",fetch_keepalive:!1,query_timeout_ms:5e3,max_attempts:3,max_backoff:20},be,S,Y,h,re,de,Fe,le,Me,we,ot,xe,it,Se,at,_e,ct,Ee,ut,Qe,dt,We=class{constructor(e,r){c(this,de);c(this,le);c(this,we);c(this,xe);c(this,Se);c(this,_e);c(this,Ee);c(this,Qe);c(this,S,void 0);c(this,Y,void 0);c(this,h,void 0);c(this,re,!1);f(this,S,{...He,...e,secret:l(this,we,ot).call(this,e),endpoint:l(this,xe,it).call(this,e)}),l(this,Qe,dt).call(this),r?f(this,Y,r):f(this,Y,Ae({url:i(this,S).endpoint.toString(),http2_session_idle_ms:i(this,S).http2_session_idle_ms,http2_max_streams:i(this,S).http2_max_streams,fetch_keepalive:i(this,S).fetch_keepalive}))}get lastTxnTs(){return i(this,h)}set lastTxnTs(e){e!==void 0&&f(this,h,i(this,h)?Math.max(e,i(this,h)):e)}get clientConfiguration(){let{...e}=i(this,S);return e}close(){if(i(this,re))throw new A("Your client is closed. You cannot close it again.");i(this,Y).close(),f(this,re,!0)}paginate(e,r){return e instanceof X?R.fromQuery(this,e,r):R.fromPageable(this,e,r)}async query(e,r){if(i(this,re))throw new A("Your client is closed. No further requests can be issued.");let s=e.toQuery(r).query;return l(this,de,Fe).call(this,s,r)}},he=We;be=new WeakMap,S=new WeakMap,Y=new WeakMap,h=new WeakMap,re=new WeakMap,de=new WeakSet,Fe=async function(e,r,s=0){let n=this.clientConfiguration.max_backoff??He.max_backoff,o=this.clientConfiguration.max_attempts??He.max_attempts,a=Math.min(Math.random()*2**s,n)*1e3,u=p=>new Promise(b=>setTimeout(b,p));return s+=1,l(this,_e,ct).call(this,e,r,s).catch(p=>{if(p instanceof k&&s<o)return u(a).then(()=>l(this,de,Fe).call(this,e,r,s));throw p})},le=new WeakSet,Me=function(e){if(e instanceof w||e instanceof x||e instanceof _||e instanceof d)return e;if(Ie(e)){if(st(e.body)){let r=e.body,s=e.status;return l(this,Se,at).call(this,r,s)}return new _({message:`Response is in an unkown format: ${e.body}`,httpStatus:e.status})}return new w("A client level error occurred. Fauna was not called.",{cause:e})},we=new WeakSet,ot=function(e){let r;typeof process<"u"&&process&&typeof process=="object"&&process.env&&typeof process.env=="object"&&(r=process.env.FAUNA_SECRET);let s=e?.secret??r;if(s===void 0)throw new TypeError("You must provide a secret to the driver. Set it in an environmental variable named FAUNA_SECRET or pass it to the Client constructor.");return s},xe=new WeakSet,it=function(e){if(e&&"endpoint"in e&&e.endpoint===void 0)throw new TypeError("ClientConfiguration option endpoint must be defined.");let r;return typeof process<"u"&&process&&typeof process=="object"&&process.env&&typeof process.env=="object"&&(r=process.env.FAUNA_ENDPOINT?new URL(process.env.FAUNA_ENDPOINT):void 0),e?.endpoint??r??ke.default},Se=new WeakSet,at=function(e,r){switch(r){case 400:return Et.includes(e.error.code)?new P(e,r):e.error.code==="invalid_request"?new N(e,r):e.error.code==="abort"&&e.error.abort!==void 0?new ne(e,r):new F(e,r);case 401:return new M(e,r);case 403:return new W(e,r);case 409:return new se(e,r);case 429:return new k(e,r);case 440:return new v(e,r);case 500:return new j(e,r);case 503:return new $(e,r);default:return new d(e,r)}},_e=new WeakSet,ct=async function(e,r,s=0){try{let n={...i(this,S),...r},o={Authorization:`Bearer ${n.secret}`};l(this,Ee,ut).call(this,n,o);let a=n.format==="tagged",u=n.arguments?a?H.encode(n.arguments):n.arguments:void 0,p={query:e,arguments:u},b=n.query_timeout_ms+i(this,S).client_timeout_buffer_ms,T=await i(this,Y).request({client_timeout_ms:b,data:p,headers:o,method:"POST"}),m;try{if(m={...T,body:a?H.decode(T.body,{long_type:n.long_type}):JSON.parse(T.body)},m.body.query_tags){let Re=m.body.query_tags.split(",").map(lt=>lt.split("="));m.body.query_tags=Object.fromEntries(Re)}}catch(Re){throw new _({message:`Error parsing response as JSON: ${Re}`,httpStatus:T.status})}if(!nt(m.body))throw l(this,le,Me).call(this,m);let z=m.body.txn_ts;(i(this,h)===void 0&&z!==void 0||z!==void 0&&i(this,h)!==void 0&&i(this,h)<z)&&f(this,h,z);let Oe=m.body;return Oe.stats&&(Oe.stats.attempts=s),Oe}catch(n){throw l(this,le,Me).call(this,n)}},Ee=new WeakSet,ut=function(e,r){for(let s of Object.entries(e))if(["format","query_timeout_ms","linearized","max_contention_retries","traceparent","typecheck","query_tags"].includes(s[0])){let n,o=`x-${s[0].replaceAll("_","-")}`;s[0]==="query_tags"?n=Object.entries(s[1]).map(a=>a.join("=")).join(","):typeof s[1]=="string"?n=s[1]:n=String(s[1]),s[0]==="traceparent"&&(o=s[0]),r[o]=n}r["x-last-txn-ts"]===void 0&&i(this,h)!==void 0&&(r["x-last-txn-ts"]=i(this,h)),r["x-driver-env"]=i(We,be)},Qe=new WeakSet,dt=function(){let e=i(this,S);if(["client_timeout_buffer_ms","endpoint","format","http2_session_idle_ms","long_type","query_timeout_ms","fetch_keepalive","http2_max_streams"].forEach(s=>{if(e[s]===void 0)throw new TypeError(`ClientConfiguration option '${s}' must be defined.`)}),e.http2_max_streams<=0)throw new RangeError("'http2_max_streams' must be greater than zero.");if(e.client_timeout_buffer_ms<=0)throw new RangeError("'client_timeout_buffer_ms' must be greater than zero.");if(e.query_timeout_ms<=0)throw new RangeError("'query_timeout_ms' must be greater than zero.")},c(he,be,rt());var Et=["invalid_function_definition","invalid_identifier","invalid_query","invalid_syntax","invalid_type"];export{ne as AbortError,M as AuthenticationError,W as AuthorizationError,he as Client,A as ClientClosedError,w as ClientError,se as ContendedTransactionError,Q as DateStub,Z as Document,D as DocumentReference,q as EmbeddedSet,C as FaunaError,oe as FetchClient,N as InvalidRequestError,Ke as LONG_MAX,Je as LONG_MIN,V as Module,ee as NamedDocument,B as NamedDocumentReference,x as NetworkError,G as NodeHTTP2Client,te as NullDocument,O as Page,_ as ProtocolError,P as QueryCheckError,F as QueryRuntimeError,v as QueryTimeoutError,d as ServiceError,j as ServiceInternalError,$ as ServiceTimeoutError,R as SetIterator,H as TaggedTypeFormat,k as ThrottlingError,E as TimeStub,ke as endpoints,qe as fql,Ae as getDefaultHTTPClient,Ie as isHTTPResponse};
var Pe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+t+'" is not supported')});var Ie=(t,e,r)=>{if(!e.has(t))throw TypeError("Cannot "+r)};var i=(t,e,r)=>(Ie(t,e,"read from private field"),r?r.call(t):e.get(t)),a=(t,e,r)=>{if(e.has(t))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(t):e.set(t,r)},p=(t,e,r,s)=>(Ie(t,e,"write to private field"),s?s.call(t,r):e.set(t,r),r),ke=(t,e,r,s)=>({set _(n){p(t,e,n,r)},get _(){return i(t,e,s)}}),d=(t,e,r)=>(Ie(t,e,"access private method"),r);var Ne={default:new URL("https://db.fauna.com"),local:new URL("http://localhost:8443"),localhost:new URL("http://localhost:8443")};var k=class extends Error{constructor(...e){super(...e)}},u=class extends k{httpStatus;code;queryInfo;constraint_failures;constructor(e,r){super(e.error.message),Error.captureStackTrace&&Error.captureStackTrace(this,u),this.name="ServiceError",this.code=e.error.code,this.httpStatus=r;let s={txn_ts:e.txn_ts,summary:e.summary,query_tags:e.query_tags,stats:e.stats};this.queryInfo=s,this.constraint_failures=e.error.constraint_failures}},M=class extends u{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,M),this.name="QueryRuntimeError"}},N=class extends u{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,N),this.name="QueryCheckError"}},A=class extends u{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,A),this.name="InvalidRequestError"}},se=class extends u{abort;constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,N),this.name="AbortError",this.abort=e.error.abort}},W=class extends u{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,W),this.name="AuthenticationError"}},v=class extends u{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,v),this.name="AuthorizationError"}},oe=class extends u{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,A),this.name="ContendedTransactionError"}},D=class extends u{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,D),this.name="ThrottlingError"}},L=class extends u{stats;constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,L),this.name="QueryTimeoutError",this.stats=e.stats}},$=class extends u{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,$),this.name="ServiceInternalError"}},U=class extends u{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,U),this.name="ServiceTimeoutError"}},b=class extends k{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,b),this.name="ClientError"}},F=class extends k{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,F),this.name="ClientClosedError"}},w=class extends k{constructor(e,r){super(e,r),Error.captureStackTrace&&Error.captureStackTrace(this,w),this.name="NetworkError"}},O=class extends k{httpStatus;constructor(e){super(e.message),Error.captureStackTrace&&Error.captureStackTrace(this,O),this.name="ProtocolError",this.httpStatus=e.httpStatus}};var ie=class{#e;#t;constructor({url:e,fetch_keepalive:r}){this.#e=new URL("/query/1",e).toString(),this.#t=r}async request({data:e,headers:r,method:s,client_timeout_ms:n}){let o=AbortSignal.timeout===void 0?(()=>{let g=new AbortController,l=g.signal;return setTimeout(()=>g.abort(),n),l})():AbortSignal.timeout(n),c=await fetch(this.#e,{method:s,headers:{...r,"Content-Type":"application/json"},body:JSON.stringify(e),signal:o,keepalive:this.#t}).catch(g=>{throw new w("The network connection encountered a problem.",{cause:g})}),m=c.status,E={};c.headers.forEach((g,l)=>E[l]=g);let h=await c.text();return{status:m,body:h,headers:E}}close(){}};var G;try{G=Pe("node:http2")}catch{G=void 0}var K,ae,ce,ue,V,f,fe,ve,Z,pe,ye,Le,ge,$e,B=class{constructor({http2_session_idle_ms:e,url:r,http2_max_streams:s}){a(this,Z);a(this,ye);a(this,ge);a(this,ae,void 0);a(this,ce,void 0);a(this,ue,void 0);a(this,V,0);a(this,f,void 0);if(G===void 0)throw new Error("Your platform does not support Node's http2 library");p(this,ae,e),p(this,ce,s),p(this,ue,r),p(this,f,null)}static getClient(e){var n;let r=d(n=B,fe,ve).call(n,e);i(B,K).has(r)||i(B,K).set(r,new B(e));let s=i(B,K).get(r);return ke(s,V)._++,s}async request(e){let r=0,s;do try{return await d(this,ge,$e).call(this,e)}catch(n){if(n?.code!=="ERR_HTTP2_GOAWAY_SESSION")throw new w("The network connection encountered a problem.",{cause:n});s=n,r++}while(r<3);throw new w("The network connection encountered a problem.",{cause:s})}close(){this.isClosed()||(ke(this,V)._--,i(this,V)===0&&i(this,f)&&!i(this,f).closed&&i(this,f).close())}isClosed(){return i(this,V)===0}},X=B;K=new WeakMap,ae=new WeakMap,ce=new WeakMap,ue=new WeakMap,V=new WeakMap,f=new WeakMap,fe=new WeakSet,ve=function({http2_session_idle_ms:e,url:r}){return`${r}|${e}`},Z=new WeakSet,pe=function(){p(this,V,0),i(this,f)&&!i(this,f).closed&&i(this,f).close()},ye=new WeakSet,Le=function(){if(!i(this,f)||i(this,f).closed||i(this,f).destroyed){let e=G.connect(i(this,ue),{peerMaxConcurrentStreams:i(this,ce)}).once("error",()=>d(this,Z,pe).call(this)).once("goaway",()=>d(this,Z,pe).call(this));e.setTimeout(i(this,ae),()=>{d(this,Z,pe).call(this)}),p(this,f,e)}return i(this,f)},ge=new WeakSet,$e=function({client_timeout_ms:e,data:r,headers:s,method:n}){return new Promise((o,c)=>{let m,E=h=>{let g=Number(h[G.constants.HTTP2_HEADER_STATUS]),l="";m.on("data",J=>{l+=J}),m.on("end",()=>{o({status:g,body:l,headers:h})})};try{let h={...s,[G.constants.HTTP2_HEADER_PATH]:"/query/1",[G.constants.HTTP2_HEADER_METHOD]:n};m=d(this,ye,Le).call(this).request(h).setEncoding("utf8").on("error",l=>{c(l)}).on("response",E),m.write(JSON.stringify(r),"utf8"),m.setTimeout(e,()=>{m.destroy(new Error("Client timeout"))}),m.end()}catch(h){c(h)}})},a(X,fe),a(X,K,new Map);var Ae=t=>ft()?X.getClient(t):new ie(t),De=t=>t instanceof Object&&"body"in t&&"headers"in t&&"status"in t,ft=()=>{if(typeof process<"u"&&process&&process.release?.name==="node")try{return Pe("node:http2"),!0}catch{return!1}return!1};var yt=/(?:\d{4}|[\u2212-]\d{4,}|\+\d{5,})/,gt=/(?:0[1-9]|1[0-2])/,Tt=/(?:0[1-9]|[12]\d|3[01])/,Ue=/(?:[01][0-9]|2[0-3])/,de=/(?:[0-5][0-9])/,ht=/(?:\.\d+)/,Fe=new RegExp(`(${yt.source}-(${gt.source})-(${Tt.source}))`),bt=new RegExp(`(${Ue.source}:${de.source}:${de.source}${ht.source}?)`),wt=new RegExp(`([zZ]|[+\u2212-]${Ue.source}(?::?${de.source}|:${de.source}:${de.source}))`),Ge=new RegExp(`^${Fe.source}$`),Be=new RegExp(`^${Fe.source}`),Xe=new RegExp(`^${Fe.source}T${bt.source}${wt.source}$`);var S=class{isoString;constructor(e){this.isoString=e}static from(e){if(typeof e!="string")throw new TypeError(`Expected string but received ${typeof e}: ${e}`);if(Xe.exec(e)===null)throw new RangeError(`(regex) Expected an ISO date string but received '${e}'`);return new S(e)}static fromDate(e){return new S(e.toISOString())}toDate(){let e=new Date(this.isoString);if(e.toString()==="Invalid Date")throw new RangeError("Fauna Date could not be converted to Javascript Date");return e}toString(){return`TimeStub("${this.isoString}")`}},_=class{dateString;constructor(e){this.dateString=e}static from(e){if(typeof e!="string")throw new TypeError(`Expected string but received ${typeof e}: ${e}`);let r=Ge.exec(e);if(r===null)throw new RangeError(`Expected a plain date string but received '${e}'`);return new _(r[0])}static fromDate(e){let r=e.toISOString(),s=Be.exec(r);if(s===null)throw new b(`Failed to parse date '${e}'`);return new _(s[0])}toDate(){let e=new Date(this.dateString+"T00:00:00Z");if(e.toString()==="Invalid Date")throw new RangeError("Fauna Date could not be converted to Javascript Date");return e}toString(){return`DateStub("${this.dateString}")`}};var R=class{coll;id;constructor({coll:e,id:r}){this.id=r,typeof e=="string"?this.coll=new C(e):this.coll=e}},ee=class extends R{ts;constructor(e){let{coll:r,id:s,ts:n,...o}=e;super({coll:r,id:s}),this.ts=n,Object.assign(this,o)}toObject(){return{...this}}},q=class{coll;name;constructor({coll:e,name:r}){this.name=r,typeof e=="string"?this.coll=new C(e):this.coll=e}},te=class extends q{ts;data;constructor(e){let{coll:r,name:s,ts:n,data:o,...c}=e;super({coll:r,name:s}),this.ts=n,this.data=o||{},Object.assign(this,c)}toObject(){return{...this}}},C=class{name;constructor(e){this.name=e}},Y=class{ref;cause;constructor(e,r){this.ref=e,this.cause=r}};var Q=class{data;after;constructor({data:e,after:r}){this.data=e,this.after=r}},P=class{after;constructor(e){this.after=e}},I=class{#e;constructor(e,r,s){if(s=s??{},r instanceof Function)this.#e=Et(e,r,s);else if(r instanceof Q||r instanceof P)this.#e=Ye(e,r,s);else throw new TypeError(`Expected 'Page<T> | EmbeddedSet | (() => Promise<T | Page<T> | EmbeddedSet>)', but received ${JSON.stringify(r)}`)}static fromQuery(e,r,s){return new I(e,async()=>(await e.query(r,s)).data,s)}static fromPageable(e,r,s){return new I(e,r,s)}flatten(){return new Ve(this)}async next(){return this.#e.next()}async return(){return this.#e.return()}async throw(e){return this.#e.throw(e)}[Symbol.asyncIterator](){return this}},Ve=class{#e;constructor(e){this.#e=St(e)}async next(){return this.#e.next()}async return(){return this.#e.return()}async throw(e){return this.#e.throw(e)}[Symbol.asyncIterator](){return this}};async function*Ye(t,e,r){let s=e;for(s instanceof Q&&(yield s.data);s.after;){let n=qe`Set.paginate(${s.after})`;s=(await t.query(n,r)).data,yield s.data}}async function*Et(t,e,r){let s=await e();if(s instanceof Q||s instanceof P){for await(let n of Ye(t,s,r))yield n;return}yield[s]}async function*St(t){for await(let e of t)for(let r of e)yield r}var H=class{static encode(e){return re(e)}static encodeInterpolation(e){return Te(e)}static decode(e,r){return JSON.parse(e,(s,n)=>{if(n==null)return null;if(n["@mod"])return new C(n["@mod"]);if(n["@doc"]){if(typeof n["@doc"]=="string"){let[c,m]=n["@doc"].split(":");return new R({coll:c,id:m})}let o=n["@doc"];return o.id?new ee(o):new te(o)}else if(n["@ref"]){let o=n["@ref"],c;return o.id?c=new R(o):c=new q(o),"exists"in o&&o.exists===!1?new Y(c,o.cause):c}else{if(n["@set"])return typeof n["@set"]=="string"?new P(n["@set"]):new Q(n["@set"]);if(n["@int"])return Number(n["@int"]);if(n["@long"]){let o=BigInt(n["@long"]);return r.long_type==="number"?((o>Number.MAX_SAFE_INTEGER||o<Number.MIN_SAFE_INTEGER)&&console.warn("Value is too large to be represented as a number. Returning as Number with loss of precision. Use long_type 'bigint' instead."),Number(o)):o}else{if(n["@double"])return Number(n["@double"]);if(n["@date"])return _.from(n["@date"]);if(n["@time"])return S.from(n["@time"]);if(n["@object"])return n["@object"]}}return n})}},Ze=BigInt("-9223372036854775808"),et=BigInt("9223372036854775807"),ze=-(2**31),Je=2**31-1,y={bigint:t=>{if(t<Ze||t>et)throw new RangeError("BigInt value exceeds max magnitude for a 64-bit Fauna long. Use a 'number' to represent doubles beyond that limit.");return t>=ze&&t<=Je?{"@int":t.toString()}:{"@long":t.toString()}},number:t=>{if(t===Number.POSITIVE_INFINITY||t===Number.NEGATIVE_INFINITY)throw new RangeError(`Cannot convert ${t} to a Fauna type.`);return Number.isInteger(t)?t>=ze&&t<=Je?{"@int":t.toString()}:Number.isSafeInteger(t)?{"@long":t.toString()}:{"@double":t.toString()}:{"@double":t.toString()}},string:t=>t,object:t=>{let e=!1,r={};for(let s in t)s.startsWith("@")&&(e=!0),t[s]!==void 0&&(r[s]=re(t[s]));return e?{"@object":r}:r},array:t=>t.map(re),date:t=>({"@time":t.toISOString()}),faunadate:t=>({"@date":t.dateString}),faunatime:t=>({"@time":t.isoString}),module:t=>({"@mod":t.name}),documentReference:t=>({"@ref":{id:t.id,coll:{"@mod":t.coll.name}}}),document:t=>({"@ref":{id:t.id,coll:{"@mod":t.coll.name}}}),namedDocumentReference:t=>({"@ref":{name:t.name,coll:{"@mod":t.coll.name}}}),namedDocument:t=>({"@ref":{name:t.name,coll:{"@mod":t.coll.name}}}),set:t=>{throw new b("Page could not be encoded. Fauna does not accept encoded Set values, yet. Use Page.data and Page.after as arguments, instead.")}},re=t=>{switch(typeof t){case"bigint":return y.bigint(t);case"string":return y.string(t);case"number":return y.number(t);case"boolean":return t;case"object":if(t==null)return null;if(Array.isArray(t))return y.array(t);if(t instanceof Date)return y.date(t);if(t instanceof _)return y.faunadate(t);if(t instanceof S)return y.faunatime(t);if(t instanceof C)return y.module(t);if(t instanceof ee)return y.document(t);if(t instanceof R)return y.documentReference(t);if(t instanceof te)return y.namedDocument(t);if(t instanceof q)return y.namedDocumentReference(t);if(t instanceof Y)return re(t.ref);if(t instanceof Q)return y.set(t);if(t instanceof P)return y.set(t);if(t instanceof j)throw new TypeError("Cannot encode instance of type 'Query'. Try using TaggedTypeFormat.encodeInterpolation instead.");return y.object(t);default:throw new TypeError(`Passing ${typeof t} as a QueryValue is not supported`)}},Te=t=>{switch(typeof t){case"bigint":case"string":case"number":case"boolean":return Ke(re(t));case"object":return t==null||t instanceof Date||t instanceof _||t instanceof S||t instanceof C||t instanceof R||t instanceof q||t instanceof Q||t instanceof P?Ke(re(t)):t instanceof Y?Te(t.ref):t instanceof j?Ot(t):Array.isArray(t)?Qt(t):_t(t);default:throw new TypeError(`Passing ${typeof t} as a QueryValue is not supported`)}},_t=t=>{let e={};for(let r in t)t[r]!==void 0&&(e[r]=Te(t[r]));return{object:e}},Qt=t=>({array:t.map(Te)}),Ot=t=>t.toQuery().query,Ke=t=>({value:t});function qe(t,...e){return new j(t,...e)}var j=class{#e;#t;constructor(e,...r){if(e.length===0||e.length!==r.length+1)throw new Error("invalid query constructed");this.#e=e,this.#t=r}toQuery(e={}){return{query:this.#r(),arguments:e.arguments}}#r(){if(this.#e.length===1)return{fql:[this.#e[0]]};let e=this.#e.flatMap((r,s)=>{if(s===this.#e.length-1)return r===""?[]:[r];let n=this.#t[s],o=H.encodeInterpolation(n);return[r,o]});return e=e.filter(r=>r!==""),{fql:e}}};var tt="1.3.0";var he;try{he=Pe("node:os")}catch{he=void 0}var st=()=>{let t={driver:["javascript",tt].join("-"),env:"unknown",os:"unknown",runtime:"unknown"};try{let e=typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null,r=typeof window<"u"&&typeof window.document<"u",s=typeof self=="object"&&self.constructor&&self.constructor.name==="DedicatedWorkerGlobalScope";e?(t.runtime=["nodejs",process.version].join("-"),t.env=Ct(),t.os=[he.platform(),he.release()].join("-")):s?(t.runtime=rt(navigator),t.env="Service Worker",t.os=nt(navigator)):r?(t.runtime=rt(navigator),t.env="browser",t.os=nt(navigator)):typeof EdgeRuntime!="string"&&(t.runtime="Vercel Edge Runtime",t.env="edge")}catch{}return Object.entries(t).filter(([e,r])=>r!=="unknown").map(e=>e.join("=")).join("; ")},rt=t=>{let e=t.appName,r=""+parseFloat(t.appVersion),s,n,o;return(n=t.userAgent.indexOf("Opera"))!=-1?(e="Opera",r=t.userAgent.substring(n+6),(n=t.userAgent.indexOf("Version"))!=-1&&(r=t.userAgent.substring(n+8))):(n=t.userAgent.indexOf("MSIE"))!=-1?(e="Microsoft Internet Explorer",r=t.userAgent.substring(n+5)):e=="Netscape"&&t.userAgent.indexOf("Trident/")!=-1?(e="Microsoft Internet Explorer",r=t.userAgent.substring(n+5),(n=t.userAgent.indexOf("rv:"))!=-1&&(r=t.userAgent.substring(n+3))):(n=t.userAgent.indexOf("Chrome"))!=-1?(e="Chrome",r=t.userAgent.substring(n+7)):(n=t.userAgent.indexOf("Safari"))!=-1?(e="Safari",r=t.userAgent.substring(n+7),(n=t.userAgent.indexOf("Version"))!=-1&&(r=t.userAgent.substring(n+8)),t.userAgent.indexOf("CriOS")!=-1&&(e="Chrome")):(n=t.userAgent.indexOf("Firefox"))!=-1?(e="Firefox",r=t.userAgent.substring(n+8)):(s=t.userAgent.lastIndexOf(" ")+1)<(n=t.userAgent.lastIndexOf("/"))&&(e=t.userAgent.substring(s,n),r=t.userAgent.substring(n+1),e.toLowerCase()==e.toUpperCase()&&(e=t.appName)),(o=r.indexOf(";"))!=-1&&(r=r.substring(0,o)),(o=r.indexOf(" "))!=-1&&(r=r.substring(0,o)),(o=r.indexOf(")"))!=-1&&(r=r.substring(0,o)),[e,r].join("-")},nt=t=>{let e="unknown",r=[{s:"Windows 10",r:/(Windows 10.0|Windows NT 10.0)/},{s:"Windows 8.1",r:/(Windows 8.1|Windows NT 6.3)/},{s:"Windows 8",r:/(Windows 8|Windows NT 6.2)/},{s:"Windows 7",r:/(Windows 7|Windows NT 6.1)/},{s:"Windows Vista",r:/Windows NT 6.0/},{s:"Windows Server 2003",r:/Windows NT 5.2/},{s:"Windows XP",r:/(Windows NT 5.1|Windows XP)/},{s:"Windows 2000",r:/(Windows NT 5.0|Windows 2000)/},{s:"Windows ME",r:/(Win 9x 4.90|Windows ME)/},{s:"Windows 98",r:/(Windows 98|Win98)/},{s:"Windows 95",r:/(Windows 95|Win95|Windows_95)/},{s:"Windows NT 4.0",r:/(Windows NT 4.0|WinNT4.0|WinNT|Windows NT)/},{s:"Windows CE",r:/Windows CE/},{s:"Windows 3.11",r:/Win16/},{s:"Android",r:/Android/},{s:"Open BSD",r:/OpenBSD/},{s:"Sun OS",r:/SunOS/},{s:"Chrome OS",r:/CrOS/},{s:"Linux",r:/(Linux|X11(?!.*CrOS))/},{s:"iOS",r:/(iPhone|iPad|iPod)/},{s:"Mac OS X",r:/Mac OS X/},{s:"Mac OS",r:/(Mac OS|MacPPC|MacIntel|Mac_PowerPC|Macintosh)/},{s:"QNX",r:/QNX/},{s:"UNIX",r:/UNIX/},{s:"BeOS",r:/BeOS/},{s:"OS/2",r:/OS\/2/},{s:"Search Bot",r:/(nuhk|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask Jeeves\/Teoma|ia_archiver)/}];for(let n in r){let o=r[n];if(o.r.test(t.userAgent)){e=o.s;break}}let s="unknown";if(/Windows/.test(e)){let n=/Windows (.*)/.exec(e);n&&(s=n[1]),e="Windows"}switch(e){case"Mac OS":case"Mac OS X":case"Android":{let n=/(?:Android|Mac OS|Mac OS X|MacPPC|MacIntel|Mac_PowerPC|Macintosh) ([._\d]+)/.exec(t.userAgent);n&&(s=n[1]);break}case"iOS":{let n=/OS (\d+)_(\d+)_?(\d+)?/.exec(t.appVersion);n&&(s=n[1]+"."+n[2]+"."+(n[3]??0));break}}return[e,s].join("-")},Rt=typeof window<"u"?window:typeof globalThis<"u"?globalThis:typeof global<"u"?global:self,Ct=()=>{if(!(typeof process<"u"&&process&&process.env&&typeof process.env=="object"))return"unknown";let e=[{name:"Netlify",check:function(){return!!process.env.NETLIFY_IMAGES_CDN_DOMAIN}},{name:"Vercel",check:function(){return!!process.env.VERCEL}},{name:"Heroku",check:function(){return!!process.env.PATH&&process.env.PATH.indexOf(".heroku")!==-1}},{name:"AWS Lambda",check:function(){return!!process.env.AWS_LAMBDA_FUNCTION_VERSION}},{name:"GCP Cloud Functions",check:function(){return!!process.env._&&process.env._.indexOf("google")!==-1}},{name:"GCP Compute Instances",check:function(){return!!process.env.GOOGLE_CLOUD_PROJECT}},{name:"Azure Cloud Functions",check:function(){return!!process.env.WEBSITE_FUNCTIONS_AZUREMONITOR_CATEGORIES}},{name:"Azure Compute",check:function(){return!!process.env.ORYX_ENV_TYPE&&!!process.env.WEBSITE_INSTANCE_ID&&process.env.ORYX_ENV_TYPE==="AppService"}},{name:"Mongo Stitch",check:function(){return typeof Rt?.StitchError=="function"}},{name:"Render",check:function(){return!!process.env.RENDER_SERVICE_ID}},{name:"Begin",check:function(){return!!process.env.BEGIN_DATA_SCOPE_ID}}].find(r=>r.check());return e?e.name:"unknown"};var ot=t=>t instanceof Object&&"data"in t,it=t=>t instanceof Object&&"error"in t&&t.error instanceof Object&&"code"in t.error&&"message"in t.error;var He={client_timeout_buffer_ms:5e3,format:"tagged",http2_session_idle_ms:5e3,http2_max_streams:100,long_type:"number",fetch_keepalive:!1,query_timeout_ms:5e3,max_attempts:3,max_backoff:20},we,x,z,T,ne,le,je,me,Me,xe,at,Ee,ct,Se,ut,_e,dt,Qe,lt,Oe,mt,We=class{constructor(e,r){a(this,le);a(this,me);a(this,xe);a(this,Ee);a(this,Se);a(this,_e);a(this,Qe);a(this,Oe);a(this,x,void 0);a(this,z,void 0);a(this,T,void 0);a(this,ne,!1);p(this,x,{...He,...e,secret:d(this,xe,at).call(this,e),endpoint:d(this,Ee,ct).call(this,e)}),d(this,Oe,mt).call(this),r?p(this,z,r):p(this,z,Ae({url:i(this,x).endpoint.toString(),http2_session_idle_ms:i(this,x).http2_session_idle_ms,http2_max_streams:i(this,x).http2_max_streams,fetch_keepalive:i(this,x).fetch_keepalive}))}get lastTxnTs(){return i(this,T)}set lastTxnTs(e){e!==void 0&&p(this,T,i(this,T)?Math.max(e,i(this,T)):e)}get clientConfiguration(){let{...e}=i(this,x);return e}close(){if(i(this,ne))throw new F("Your client is closed. You cannot close it again.");i(this,z).close(),p(this,ne,!0)}paginate(e,r){return e instanceof j?I.fromQuery(this,e,r):I.fromPageable(this,e,r)}async query(e,r){if(i(this,ne))throw new F("Your client is closed. No further requests can be issued.");let s=e.toQuery(r).query;return d(this,le,je).call(this,s,r)}},be=We;we=new WeakMap,x=new WeakMap,z=new WeakMap,T=new WeakMap,ne=new WeakMap,le=new WeakSet,je=async function(e,r,s=0){let n=this.clientConfiguration.max_backoff??He.max_backoff,o=this.clientConfiguration.max_attempts??He.max_attempts,c=Math.min(Math.random()*2**s,n)*1e3,m=E=>new Promise(h=>setTimeout(h,E));return s+=1,d(this,_e,dt).call(this,e,r,s).catch(E=>{if(E instanceof D&&s<o)return m(c).then(()=>d(this,le,je).call(this,e,r,s));throw E})},me=new WeakSet,Me=function(e){if(e instanceof b||e instanceof w||e instanceof O||e instanceof u)return e;if(De(e)){if(it(e.body)){let r=e.body,s=e.status;return d(this,Se,ut).call(this,r,s)}return new O({message:`Response is in an unkown format: ${e.body}`,httpStatus:e.status})}return new b("A client level error occurred. Fauna was not called.",{cause:e})},xe=new WeakSet,at=function(e){let r;typeof process<"u"&&process&&typeof process=="object"&&process.env&&typeof process.env=="object"&&(r=process.env.FAUNA_SECRET);let s=e?.secret??r;if(s===void 0)throw new TypeError("You must provide a secret to the driver. Set it in an environmental variable named FAUNA_SECRET or pass it to the Client constructor.");return s},Ee=new WeakSet,ct=function(e){if(e&&"endpoint"in e&&e.endpoint===void 0)throw new TypeError("ClientConfiguration option endpoint must be defined.");let r;return typeof process<"u"&&process&&typeof process=="object"&&process.env&&typeof process.env=="object"&&(r=process.env.FAUNA_ENDPOINT?new URL(process.env.FAUNA_ENDPOINT):void 0),e?.endpoint??r??Ne.default},Se=new WeakSet,ut=function(e,r){switch(r){case 400:return Pt.includes(e.error.code)?new N(e,r):e.error.code==="invalid_request"?new A(e,r):e.error.code==="abort"&&e.error.abort!==void 0?new se(e,r):new M(e,r);case 401:return new W(e,r);case 403:return new v(e,r);case 409:return new oe(e,r);case 429:return new D(e,r);case 440:return new L(e,r);case 500:return new $(e,r);case 503:return new U(e,r);default:return new u(e,r)}},_e=new WeakSet,dt=async function(e,r,s=0){try{let n={...i(this,x),...r},o={Authorization:`Bearer ${n.secret}`};d(this,Qe,lt).call(this,n,o);let c=n.format==="tagged",m=n.arguments?c?H.encode(n.arguments):n.arguments:void 0,E={query:e,arguments:m},h=n.query_timeout_ms+i(this,x).client_timeout_buffer_ms,g=await i(this,z).request({client_timeout_ms:h,data:E,headers:o,method:"POST"}),l;try{if(l={...g,body:c?H.decode(g.body,{long_type:n.long_type}):JSON.parse(g.body)},l.body.query_tags){let Ce=l.body.query_tags.split(",").map(pt=>pt.split("="));l.body.query_tags=Object.fromEntries(Ce)}}catch(Ce){throw new O({message:`Error parsing response as JSON: ${Ce}`,httpStatus:g.status})}if(!ot(l.body))throw d(this,me,Me).call(this,l);let J=l.body.txn_ts;(i(this,T)===void 0&&J!==void 0||J!==void 0&&i(this,T)!==void 0&&i(this,T)<J)&&p(this,T,J);let Re=l.body;return Re.stats&&(Re.stats.attempts=s),Re}catch(n){throw d(this,me,Me).call(this,n)}},Qe=new WeakSet,lt=function(e,r){for(let s of Object.entries(e))if(["format","query_timeout_ms","linearized","max_contention_retries","traceparent","typecheck","query_tags"].includes(s[0])){let n,o=`x-${s[0].replaceAll("_","-")}`;s[0]==="query_tags"?n=Object.entries(s[1]).map(c=>c.join("=")).join(","):typeof s[1]=="string"?n=s[1]:n=String(s[1]),s[0]==="traceparent"&&(o=s[0]),r[o]=n}r["x-last-txn-ts"]===void 0&&i(this,T)!==void 0&&(r["x-last-txn-ts"]=i(this,T)),r["x-driver-env"]=i(We,we)},Oe=new WeakSet,mt=function(){let e=i(this,x);if(["client_timeout_buffer_ms","endpoint","format","http2_session_idle_ms","long_type","query_timeout_ms","fetch_keepalive","http2_max_streams"].forEach(s=>{if(e[s]===void 0)throw new TypeError(`ClientConfiguration option '${s}' must be defined.`)}),e.http2_max_streams<=0)throw new RangeError("'http2_max_streams' must be greater than zero.");if(e.client_timeout_buffer_ms<=0)throw new RangeError("'client_timeout_buffer_ms' must be greater than zero.");if(e.query_timeout_ms<=0)throw new RangeError("'query_timeout_ms' must be greater than zero.")},a(be,we,st());var Pt=["invalid_function_definition","invalid_identifier","invalid_query","invalid_syntax","invalid_type"];export{se as AbortError,W as AuthenticationError,v as AuthorizationError,be as Client,F as ClientClosedError,b as ClientError,oe as ContendedTransactionError,_ as DateStub,ee as Document,R as DocumentReference,P as EmbeddedSet,k as FaunaError,ie as FetchClient,A as InvalidRequestError,et as LONG_MAX,Ze as LONG_MIN,C as Module,te as NamedDocument,q as NamedDocumentReference,w as NetworkError,X as NodeHTTP2Client,Y as NullDocument,Q as Page,O as ProtocolError,N as QueryCheckError,M as QueryRuntimeError,L as QueryTimeoutError,u as ServiceError,$ as ServiceInternalError,U as ServiceTimeoutError,I as SetIterator,H as TaggedTypeFormat,D as ThrottlingError,S as TimeStub,Ne as endpoints,qe as fql,Ae as getDefaultHTTPClient,De as isHTTPResponse};
//# sourceMappingURL=index.js.map

@@ -773,5 +773,8 @@ "use strict";

var TaggedTypeFormat = class {
static encode(obj) {
return encode(obj);
static encode(input) {
return encode(input);
}
static encodeInterpolation(input) {
return encodeInterpolation(input);
}
static decode(input, decodeOptions) {

@@ -886,8 +889,3 @@ return JSON.parse(input, (_, value) => {

},
array: (input) => {
const _out = [];
for (const i in input)
_out.push(encode(input[i]));
return _out;
},
array: (input) => input.map(encode),
date: (dateValue) => ({

@@ -918,5 +916,2 @@ "@time": dateValue.toISOString()

var encode = (input) => {
if (input === void 0) {
throw new TypeError("Passing undefined as a QueryValue is not supported");
}
switch (typeof input) {

@@ -958,7 +953,57 @@ case "bigint":

return encodeMap["set"](input);
} else if (input instanceof Query2) {
throw new TypeError(
"Cannot encode instance of type 'Query'. Try using TaggedTypeFormat.encodeInterpolation instead."
);
} else {
return encodeMap["object"](input);
}
default:
throw new TypeError(
`Passing ${typeof input} as a QueryValue is not supported`
);
}
};
var encodeInterpolation = (input) => {
switch (typeof input) {
case "bigint":
case "string":
case "number":
case "boolean":
return encodeValueInterpolation(encode(input));
case "object":
if (input == null || input instanceof Date || input instanceof DateStub || input instanceof TimeStub || input instanceof Module || input instanceof DocumentReference || input instanceof NamedDocumentReference || input instanceof Page || input instanceof EmbeddedSet) {
return encodeValueInterpolation(encode(input));
} else if (input instanceof NullDocument) {
return encodeInterpolation(input.ref);
} else if (input instanceof Query2) {
return encodeQueryInterpolation(input);
} else if (Array.isArray(input)) {
return encodeArrayInterpolation(input);
} else {
return encodeObjectInterpolation(input);
}
default:
throw new TypeError(
`Passing ${typeof input} as a QueryValue is not supported`
);
}
};
var encodeObjectInterpolation = (input) => {
const _out = {};
for (const k in input) {
if (input[k] !== void 0) {
_out[k] = encodeInterpolation(input[k]);
}
}
return { object: _out };
};
var encodeArrayInterpolation = (input) => {
const encodedItems = input.map(encodeInterpolation);
return { array: encodedItems };
};
var encodeQueryInterpolation = (value) => value.toQuery().query;
var encodeValueInterpolation = (value) => ({
value
});

@@ -980,10 +1025,12 @@ // src/query-builder.ts

toQuery(requestHeaders = {}) {
return { ...this.#render(requestHeaders), ...requestHeaders };
return {
query: this.#render_query(),
arguments: requestHeaders.arguments
};
}
#render(requestHeaders) {
#render_query() {
if (this.#queryFragments.length === 1) {
return { query: { fql: [this.#queryFragments[0]] }, arguments: {} };
return { fql: [this.#queryFragments[0]] };
}
let resultArgs = {};
const renderedFragments = this.#queryFragments.flatMap((fragment, i) => {
let renderedFragments = this.#queryFragments.flatMap((fragment, i) => {
if (i === this.#queryFragments.length - 1) {

@@ -993,16 +1040,7 @@ return fragment === "" ? [] : [fragment];

const arg = this.#queryArgs[i];
let subQuery;
if (arg instanceof Query2) {
const request = arg.toQuery(requestHeaders);
subQuery = request.query;
resultArgs = { ...resultArgs, ...request.arguments };
} else {
subQuery = { value: TaggedTypeFormat.encode(arg) };
}
return [fragment, subQuery].filter((x) => x !== "");
const encoded = TaggedTypeFormat.encodeInterpolation(arg);
return [fragment, encoded];
});
return {
query: { fql: renderedFragments },
arguments: resultArgs
};
renderedFragments = renderedFragments.filter((x) => x !== "");
return { fql: renderedFragments };
}

@@ -1012,3 +1050,3 @@ };

// src/util/package-version.ts
var packageVersion = "1.2.0";
var packageVersion = "1.3.0";

@@ -1457,3 +1495,5 @@ // src/util/environment.ts

const isTaggedFormat = requestConfig.format === "tagged";
const queryArgs = requestConfig.arguments ? isTaggedFormat ? TaggedTypeFormat.encode(requestConfig.arguments) : requestConfig.arguments : void 0;
const queryArgs = requestConfig.arguments ? isTaggedFormat ? TaggedTypeFormat.encode(
requestConfig.arguments
) : requestConfig.arguments : void 0;
const requestData = {

@@ -1460,0 +1500,0 @@ query: queryInterpolation,

@@ -1,2 +0,2 @@

import type { QueryValue, QueryRequest, QueryOptions } from "./wire-protocol";
import type { QueryValue, QueryRequest, QueryOptions, FQLFragment } from "./wire-protocol";
/**

@@ -43,3 +43,3 @@ * Creates a new Query. Accepts template literal inputs.

*/
toQuery(requestHeaders?: QueryOptions): QueryRequest;
toQuery(requestHeaders?: QueryOptions): QueryRequest<FQLFragment>;
}

@@ -0,1 +1,2 @@

import { QueryValue, QueryInterpolation } from "./wire-protocol";
export interface DecodeOptions {

@@ -9,9 +10,16 @@ long_type: "number" | "bigint";

/**
* Encode the Object to the Tagged Type format for Fauna
* Encode the value to the Tagged Type format for Fauna
*
* @param obj - Object that will be encoded
* @param input - value that will be encoded
* @returns Map of result
*/
static encode(obj: any): any;
static encode(input: QueryValue): TaggedType;
/**
* Encode the value to a QueryInterpolation to send to Fauna
*
* @param input - value that will be encoded
* @returns Map of result
*/
static encodeInterpolation(input: QueryValue): QueryInterpolation;
/**
* Decode the JSON string result from Fauna to remove Tagged Type formatting.

@@ -24,2 +32,36 @@ *

}
type TaggedDate = {
"@date": string;
};
type TaggedDouble = {
"@double": string;
};
type TaggedInt = {
"@int": string;
};
type TaggedLong = {
"@long": string;
};
type TaggedMod = {
"@mod": string;
};
type TaggedObject = {
"@object": EncodedObject;
};
type TaggedRef = {
"@ref": {
id: string;
coll: TaggedMod;
} | {
name: string;
coll: TaggedMod;
};
};
type TaggedTime = {
"@time": string;
};
type EncodedObject = {
[key: string]: TaggedType;
};
type TaggedType = string | boolean | null | TaggedDate | TaggedDouble | TaggedInt | TaggedLong | TaggedMod | TaggedObject | TaggedRef | TaggedTime | EncodedObject | TaggedType[];
export declare const LONG_MIN: bigint;

@@ -29,1 +71,2 @@ export declare const LONG_MAX: bigint;

export declare const INT_MAX: number;
export {};
/** The current package version. */
export declare const packageVersion = "1.2.0";
export declare const packageVersion = "1.3.0";

@@ -0,1 +1,2 @@

import { Query } from "./query-builder";
import { DateStub, Document, DocumentReference, EmbeddedSet, Module, NamedDocument, NamedDocumentReference, NullDocument, Page, TimeStub } from "./values";

@@ -5,5 +6,5 @@ /**

*/
export interface QueryRequest {
export interface QueryRequest<T = string | QueryInterpolation> {
/** The query */
query: string | QueryInterpolation;
query: T;
/** Optional arguments. Variables in the query will be initialized to the

@@ -179,3 +180,3 @@ * value associated with an argument key.

*/
export type QueryInterpolation = FQLFragment | ValueFragment;
export type QueryInterpolation = FQLFragment | ValueFragment | ObjectFragment | ArrayFragment;
/**

@@ -203,2 +204,38 @@ * A piece of an interpolated query that represents an actual value. Arguments

/**
* A piece of an interpolated query that represents an object. Arguments
* are passed to fauna using ObjectFragments so that query arguments can be
* nested within javascript objects.
*
* ObjectFragments must always be encoded with tags, regardless of the "x-format"
* request header sent.
* @example
* ```typescript
* const arg = { startDate: DateStub.from("2023-09-01") };
* const query = fql`${arg})`;
* // produces
* { fql: [{ object: { startDate: { "@date": "2023-09-01" } } }] }
* ```
*/
export type ObjectFragment = {
object: QueryValueObject;
};
/**
* A piece of an interpolated query that represents an array. Arguments
* are passed to fauna using ArrayFragments so that query arguments can be
* nested within javascript arrays.
*
* ArrayFragments must always be encoded with tags, regardless of the "x-format"
* request header sent.
* @example
* ```typescript
* const arg = [1, 2];
* const query = fql`${arg})`;
* // produces
* { fql: [{ array: [{ "@int": 1 }, { "@int": 2 }] }] }
* ```
*/
export type ArrayFragment = {
array: QueryValue[];
};
/**
* A piece of an interpolated query. Interpolated Queries can be safely composed

@@ -259,2 +296,2 @@ * together without concern of query string injection.

*/
export type QueryValue = null | string | number | bigint | boolean | QueryValueObject | Array<QueryValue> | DateStub | TimeStub | Module | Document | DocumentReference | NamedDocument | NamedDocumentReference | NullDocument | Page<QueryValue> | EmbeddedSet;
export type QueryValue = null | string | number | bigint | boolean | QueryValueObject | Array<QueryValue> | Date | DateStub | TimeStub | Module | Document | DocumentReference | NamedDocument | NamedDocumentReference | NullDocument | Page<QueryValue> | EmbeddedSet | Query;
{
"name": "fauna",
"version": "1.2.0",
"version": "1.3.0",
"description": "A driver to query Fauna databases in browsers, Node.js, and other Javascript runtimes",

@@ -5,0 +5,0 @@ "homepage": "https://fauna.com",

@@ -37,2 +37,3 @@ import { ClientConfiguration, endpoints } from "./client-configuration";

type QueryValue,
QueryValueObject,
} from "./wire-protocol";

@@ -439,3 +440,7 @@

? isTaggedFormat
? TaggedTypeFormat.encode(requestConfig.arguments)
? // Type cast safety: requestConfig.arguments is an object, so
// encoding creates a subtype of QueryValueObject
(TaggedTypeFormat.encode(
requestConfig.arguments
) as QueryValueObject)
: requestConfig.arguments

@@ -442,0 +447,0 @@ : undefined;

@@ -8,2 +8,3 @@ import { TaggedTypeFormat } from "./tagged-type";

QueryOptions,
FQLFragment,
} from "./wire-protocol";

@@ -73,13 +74,15 @@

*/
toQuery(requestHeaders: QueryOptions = {}): QueryRequest {
return { ...this.#render(requestHeaders), ...requestHeaders };
toQuery(requestHeaders: QueryOptions = {}): QueryRequest<FQLFragment> {
return {
query: this.#render_query(),
arguments: requestHeaders.arguments,
};
}
#render(requestHeaders: QueryOptions): QueryRequest {
#render_query(): FQLFragment {
if (this.#queryFragments.length === 1) {
return { query: { fql: [this.#queryFragments[0]] }, arguments: {} };
return { fql: [this.#queryFragments[0]] };
}
let resultArgs: QueryValueObject = {};
const renderedFragments: (string | QueryInterpolation)[] =
let renderedFragments: (string | QueryInterpolation)[] =
this.#queryFragments.flatMap((fragment, i) => {

@@ -91,23 +94,16 @@ // There will always be one more fragment than there are arguments

// arguments in the template format must always be encoded, regardless
// of the "x-format" request header
// TODO: catch and rethrow Errors, indicating bad user input
const arg = this.#queryArgs[i];
let subQuery: string | QueryInterpolation;
if (arg instanceof Query) {
const request = arg.toQuery(requestHeaders);
subQuery = request.query;
resultArgs = { ...resultArgs, ...request.arguments };
} else {
// arguments in the template format must always be encoded, regardless
// of the "x-format" request header
// TODO: catch and rethrow Errors, indicating bad user input
subQuery = { value: TaggedTypeFormat.encode(arg) };
}
const encoded = TaggedTypeFormat.encodeInterpolation(arg);
return [fragment, subQuery].filter((x) => x !== "");
return [fragment, encoded];
});
return {
query: { fql: renderedFragments },
arguments: resultArgs,
};
// We don't need to send empty-string fragments over the wire
renderedFragments = renderedFragments.filter((x) => x !== "");
return { fql: renderedFragments };
}
}
import { ClientError } from "./errors";
import { Query } from "./query-builder";
import {

@@ -14,3 +15,11 @@ DateStub,

} from "./values";
import { QueryValueObject, QueryValue } from "./wire-protocol";
import {
QueryValueObject,
QueryValue,
FQLFragment,
ObjectFragment,
ArrayFragment,
QueryInterpolation,
ValueFragment,
} from "./wire-protocol";

@@ -26,12 +35,22 @@ export interface DecodeOptions {

/**
* Encode the Object to the Tagged Type format for Fauna
* Encode the value to the Tagged Type format for Fauna
*
* @param obj - Object that will be encoded
* @param input - value that will be encoded
* @returns Map of result
*/
static encode(obj: any): any {
return encode(obj);
static encode(input: QueryValue): TaggedType {
return encode(input);
}
/**
* Encode the value to a QueryInterpolation to send to Fauna
*
* @param input - value that will be encoded
* @returns Map of result
*/
static encodeInterpolation(input: QueryValue): QueryInterpolation {
return encodeInterpolation(input);
}
/**
* Decode the JSON string result from Fauna to remove Tagged Type formatting.

@@ -112,3 +131,3 @@ *

type TaggedMod = { "@mod": string };
type TaggedObject = { "@object": QueryValueObject };
type TaggedObject = { "@object": EncodedObject };
type TaggedRef = {

@@ -121,2 +140,18 @@ "@ref": { id: string; coll: TaggedMod } | { name: string; coll: TaggedMod };

type EncodedObject = { [key: string]: TaggedType };
type TaggedType =
| string
| boolean
| null
| TaggedDate
| TaggedDouble
| TaggedInt
| TaggedLong
| TaggedMod
| TaggedObject
| TaggedRef
| TaggedTime
| EncodedObject
| TaggedType[];
export const LONG_MIN = BigInt("-9223372036854775808");

@@ -165,5 +200,5 @@ export const LONG_MAX = BigInt("9223372036854775807");

},
object: (input: QueryValueObject): TaggedObject | QueryValueObject => {
object: (input: QueryValueObject): TaggedObject | EncodedObject => {
let wrapped = false;
const _out: QueryValueObject = {};
const _out: EncodedObject = {};

@@ -180,7 +215,3 @@ for (const k in input) {

},
array: (input: Array<QueryValue>): Array<QueryValue> => {
const _out: QueryValue = [];
for (const i in input) _out.push(encode(input[i]));
return _out;
},
array: (input: QueryValue[]): TaggedType[] => input.map(encode),
date: (dateValue: Date): TaggedTime => ({

@@ -220,6 +251,3 @@ "@time": dateValue.toISOString(),

const encode = (input: QueryValue): QueryValue => {
if (input === undefined) {
throw new TypeError("Passing undefined as a QueryValue is not supported");
}
const encode = (input: QueryValue): TaggedType => {
switch (typeof input) {

@@ -263,7 +291,76 @@ case "bigint":

return encodeMap["set"](input);
} else if (input instanceof Query) {
throw new TypeError(
"Cannot encode instance of type 'Query'. Try using TaggedTypeFormat.encodeInterpolation instead."
);
} else {
return encodeMap["object"](input);
}
default:
// catch "undefined", "symbol", and "function"
throw new TypeError(
`Passing ${typeof input} as a QueryValue is not supported`
);
}
// anything here would be unreachable code
};
const encodeInterpolation = (input: QueryValue): QueryInterpolation => {
switch (typeof input) {
case "bigint":
case "string":
case "number":
case "boolean":
return encodeValueInterpolation(encode(input));
case "object":
if (
input == null ||
input instanceof Date ||
input instanceof DateStub ||
input instanceof TimeStub ||
input instanceof Module ||
input instanceof DocumentReference ||
input instanceof NamedDocumentReference ||
input instanceof Page ||
input instanceof EmbeddedSet
) {
return encodeValueInterpolation(encode(input));
} else if (input instanceof NullDocument) {
return encodeInterpolation(input.ref);
} else if (input instanceof Query) {
return encodeQueryInterpolation(input);
} else if (Array.isArray(input)) {
return encodeArrayInterpolation(input);
} else {
return encodeObjectInterpolation(input);
}
default:
// catch "undefined", "symbol", and "function"
throw new TypeError(
`Passing ${typeof input} as a QueryValue is not supported`
);
}
};
const encodeObjectInterpolation = (input: QueryValueObject): ObjectFragment => {
const _out: QueryValueObject = {};
for (const k in input) {
if (input[k] !== undefined) {
_out[k] = encodeInterpolation(input[k]);
}
}
return { object: _out };
};
const encodeArrayInterpolation = (input: Array<QueryValue>): ArrayFragment => {
const encodedItems = input.map(encodeInterpolation);
return { array: encodedItems };
};
const encodeQueryInterpolation = (value: Query): FQLFragment =>
value.toQuery().query;
const encodeValueInterpolation = (value: QueryValue): ValueFragment => ({
value,
});
//THIS FILE IS AUTOGENERATED. DO NOT EDIT. SEE .husky/pre-commit
/** The current package version. */
export const packageVersion = "1.2.0";
export const packageVersion = "1.3.0";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { fql } from "./query-builder";
import { Query, fql } from "./query-builder";
import {

@@ -19,5 +19,5 @@ DateStub,

*/
export interface QueryRequest {
export interface QueryRequest<T = string | QueryInterpolation> {
/** The query */
query: string | QueryInterpolation;
query: T;

@@ -222,3 +222,7 @@ /** Optional arguments. Variables in the query will be initialized to the

*/
export type QueryInterpolation = FQLFragment | ValueFragment;
export type QueryInterpolation =
| FQLFragment
| ValueFragment
| ObjectFragment
| ArrayFragment;

@@ -246,2 +250,36 @@ /**

/**
* A piece of an interpolated query that represents an object. Arguments
* are passed to fauna using ObjectFragments so that query arguments can be
* nested within javascript objects.
*
* ObjectFragments must always be encoded with tags, regardless of the "x-format"
* request header sent.
* @example
* ```typescript
* const arg = { startDate: DateStub.from("2023-09-01") };
* const query = fql`${arg})`;
* // produces
* { fql: [{ object: { startDate: { "@date": "2023-09-01" } } }] }
* ```
*/
export type ObjectFragment = { object: QueryValueObject };
/**
* A piece of an interpolated query that represents an array. Arguments
* are passed to fauna using ArrayFragments so that query arguments can be
* nested within javascript arrays.
*
* ArrayFragments must always be encoded with tags, regardless of the "x-format"
* request header sent.
* @example
* ```typescript
* const arg = [1, 2];
* const query = fql`${arg})`;
* // produces
* { fql: [{ array: [{ "@int": 1 }, { "@int": 2 }] }] }
* ```
*/
export type ArrayFragment = { array: QueryValue[] };
/**
* A piece of an interpolated query. Interpolated Queries can be safely composed

@@ -312,2 +350,3 @@ * together without concern of query string injection.

| Array<QueryValue>
| Date
// client-provided classes

@@ -323,2 +362,3 @@ | DateStub

| Page<QueryValue>
| EmbeddedSet;
| EmbeddedSet
| Query;

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc