@medplum/fhir-router 5.1.37 → 5.1.39

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.
@@ -1,4 +1,4 @@
1
- "use strict";var ma=Object.create;var Vt=Object.defineProperty;var ha=Object.getOwnPropertyDescriptor;var ya=Object.getOwnPropertyNames;var Ta=Object.getPrototypeOf,ga=Object.prototype.hasOwnProperty;var Ea=(t,e,r)=>e in t?Vt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Eo=(t,e)=>{for(var r in e)Vt(t,r,{get:e[r],enumerable:!0})},Io=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ya(e))!ga.call(t,i)&&i!==r&&Vt(t,i,{get:()=>e[i],enumerable:!(n=ha(e,i))||n.enumerable});return t};var No=(t,e,r)=>(r=t!=null?ma(Ta(t)):{},Io(e||!t||!t.__esModule?Vt(r,"default",{value:t,enumerable:!0}):r,t)),Ia=t=>Io(Vt({},"__esModule",{value:!0}),t);var $=(t,e,r)=>Ea(t,typeof e!="symbol"?e+"":e,r);var Ul={};Eo(Ul,{BatchProcessor:()=>$t,FhirRepository:()=>mn,FhirRouter:()=>ho,MAX_QUERY_STRING_LENGTH:()=>mo,MemoryRepository:()=>no,RepositoryMode:()=>fr,Router:()=>hr,buildBatchResponseBundle:()=>vo,createResourceImpl:()=>la,getExtraEntries:()=>ro,getSearchIncludeEntries:()=>Js,getSearchRevIncludeEntries:()=>Xs,makeSimpleRequest:()=>Vl,processBatch:()=>Tr,updateResourceImpl:()=>fa});module.exports=Ia(Ul);var R=require("@medplum/core");var Na=50,ba=8,va=/urn(:|%3A)uuid(:|%3A)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/;async function Tr(t,e,r,n){return new $t(r,e,n,t).run()}var $t=class t{constructor(e,r,n,i){$(this,"router");$(this,"repo");$(this,"bundle");$(this,"req");$(this,"resolvedIdentities");$(this,"bundleInfo");$(this,"state");this.router=e,this.repo=r,this.bundle=n,this.req=i,this.resolvedIdentities=Object.create(null),this.state={position:0,resultEntries:new Array(n.entry?.length??0),pendingIndices:[],errors:[]}}static fromState(e,r,n,i,o){let s=new t(e,r,i.bundle,n);return s.resolvedIdentities=i.resolvedIdentities,s.bundleInfo={...i.bundleInfo},s.state.position=o,s}async run(){await this.preprocess();let e=this.bundleInfo;if(!this.isTransaction()){let i=await this.processEntriesAndBuild();return this.dispatchPostEvent(),i}let r=bo(this.state),n=await this.repo.withTransaction(i=>this.withRepo(i,()=>(this.state=bo(r),this.processEntriesAndBuild())),{serializable:e.requiresStrongTransaction,resourceTypes:e.resourceTypes});return this.dispatchPostEvent(),n}async preprocess(){let e=this.bundle.type;if(e!=="batch"&&e!=="transaction")throw new R.OperationOutcomeError((0,R.badRequest)("Unrecognized bundle type: "+e));if(this.bundleInfo=await this.preprocessBundle(),this.isTransaction()){if(this.bundleInfo.updates>Na)throw new R.OperationOutcomeError((0,R.badRequest)("Transaction contains more update operations than allowed"));if(this.bundleInfo.requiresStrongTransaction&&this.state.resultEntries.length>ba)throw new R.OperationOutcomeError((0,R.badRequest)("Transaction requires strict isolation but has too many entries"))}this.dispatchPreEvent();let r=Object.create(null);for(let n=0;n<this.state.resultEntries.length;n++)this.state.resultEntries[n]&&(r[n]=this.state.resultEntries[n]);return{bundle:this.bundle,bundleInfo:{ordering:this.bundleInfo.ordering,resourceTypes:this.bundleInfo.resourceTypes,requiresStrongTransaction:this.bundleInfo.requiresStrongTransaction,updates:this.bundleInfo.updates},resolvedIdentities:this.resolvedIdentities,preprocessResults:r}}hasMoreEntries(){return this.bundleInfo!==void 0&&this.state.position<this.bundleInfo.ordering.length}getPosition(){return this.state.position}takePendingResults(){if(this.state.pendingIndices.length===0)return;let e=Object.create(null);for(let r of this.state.pendingIndices)e[r]=this.state.resultEntries[r];return this.state.pendingIndices=[],e}async processEntriesAndBuild(){for(;this.hasMoreEntries();)await this.processNextEntryImpl();return this.buildResultBundle()}dispatchPreEvent(){let e={type:"batch",bundleType:this.bundle.type,count:this.bundle.entry?.length,size:JSON.stringify(this.bundle).length};this.router.dispatchEvent(e)}dispatchPostEvent(){let e={type:"batch",bundleType:this.bundle.type,errors:this.state.errors.length?this.state.errors:void 0};this.router.dispatchEvent(e)}buildResultBundle(){return{resourceType:"Bundle",type:`${this.bundle.type}-response`,entry:this.state.resultEntries}}async withRepo(e,r){let n=this.repo;this.repo=e;try{return await r()}finally{this.repo=n}}async preprocessBundle(){let e=this.bundle.entry;if(!e?.length)throw new R.OperationOutcomeError((0,R.badRequest)("Missing bundle entries"));let r={transaction:[],batch:[],delete:[],create:[],update:[],patch:[],operation:[],"search-system":[],"search-type":[],read:[],vread:[],"history-system":[],"history-type":[],"history-instance":[]},n=new Set,i=new Set,o=!1,s=0;for(let c=0;c<e.length;c++){let u=e[c];if(!u.request?.method){this.state.resultEntries[c]=Ut((0,R.badRequest)("Missing Bundle entry request method",`Bundle.entry[${c}].request.method`));continue}let f=await this.preprocessEntry(u,c,n);if(f){if(!this.isTransaction()){this.state.resultEntries[c]=Ut(f);continue}throw new R.OperationOutcomeError(f)}let m=this.getRouteForEntry(u),g=m?.data?.interaction;if(!g||!r[g])throw new R.OperationOutcomeError((0,R.badRequest)(`Invalid REST interaction in batch: ${u.request?.method} ${u.request?.url}`));let y=m?.params?.resourceType;y&&i.add(y),g==="create"&&u.request?.ifNoneExist?o=!0:g==="update"?(u.request?.url.includes("?")&&(o=!0),s++):g==="delete"&&u.request?.url.includes("?")&&(o=!0),r[g].push(c)}let a=[];for(let c of Object.values(r))a.push(...c);return{ordering:a,requiresStrongTransaction:o,updates:s,resourceTypes:i}}async preprocessEntry(e,r,n){if(!e.request?.url)return(0,R.badRequest)("Missing Bundle entry request URL",`Bundle.entry[${r}].request.url`);let i;try{i=await this.resolveIdentity(e,`Bundle.entry[${r}]`)}catch(o){if(o instanceof R.OperationOutcomeError)return o.outcome;throw o}if(i&&(this.resolvedIdentities[i.placeholder]=i.reference,this.isTransaction())){if(n.has(i.reference))throw new R.OperationOutcomeError((0,R.badRequest)("Duplicate resource identity found in Bundle"));n.add(i.reference)}}async resolveIdentity(e,r){let i=this.getRouteForEntry(e)?.data?.interaction;if(!i)throw new R.OperationOutcomeError(R.notFound);switch(i){case"create":return this.resolveCreateIdentity(e);case"delete":case"update":case"patch":return this.resolveModificationIdentity(e,r);default:return}}getRouteForEntry(e){return this.router.find(e.request?.method,e.request?.url??"")}async resolveCreateIdentity(e){let r=e.fullUrl??"";if(e.request?.ifNoneExist){let n=await this.repo.searchResources((0,R.parseSearchRequest)(e.request.url+"?"+e.request.ifNoneExist));if(n.length===1)return{placeholder:r,reference:(0,R.getReferenceString)(n[0])}}if(e.resource)return e.resource.id=this.repo.generateId(),{placeholder:r,reference:(0,R.getReferenceString)(e.resource)}}async resolveModificationIdentity(e,r){let n=e.fullUrl??"";if(e.request?.url?.includes("?")){let i=e.request.method,o=(0,R.parseSearchRequest)(e.request.url);o.count=2,o.offset=0,o.sortRules=void 0;let[s,a]=await this.repo.searchResources(o);if(!s)switch(i){case"DELETE":return;case"PUT":if(e.resource){if(e.resource.id)throw new R.OperationOutcomeError((0,R.badRequest)("Cannot provide ID for create by update"));return e.resource.id=this.repo.generateId(),{placeholder:n,reference:(0,R.getReferenceString)(e.resource)}}return;default:throw new R.OperationOutcomeError((0,R.badRequest)(`Conditional ${e.request.method} did not match any resources`,r+".request.url"))}if(a)throw new R.OperationOutcomeError((0,R.badRequest)(`Conditional ${e.request.method} matched multiple resources`,r+".request.url"));let c=(0,R.getReferenceString)(s);return e.request.url=c,e.resource&&(e.resource.id=s.id),{placeholder:n,reference:c}}if(e.request?.url.includes("/"))return{placeholder:n,reference:e.request.url}}async processNextEntry(){if(this.isTransaction())throw new Error("Re-entrant batch processing does not support transaction semantics");await this.processNextEntryImpl()}async processNextEntryImpl(){let e=this.bundleInfo;if(!e)throw new Error("processNextEntry called before preprocess()/fromState()");let r=this.bundle.entry;if(!r)throw new R.OperationOutcomeError((0,R.badRequest)("Missing bundle entry"));if(this.state.position>=e.ordering.length)return;let n=this.state.position,i=e.ordering[n],o=r[i],s=this.rewriteIdsInObject(o);try{this.setResult(i,await this.processBatchEntry(s)),this.state.position=n+1}catch(a){if(this.isTransaction())throw a;if(this.state.errors.push(a.message),a instanceof R.OperationOutcomeError&&(0,R.getStatus)(a.outcome)===429){for(let c=n;c<e.ordering.length;c++)this.setResult(e.ordering[c],Ut(a.outcome));this.state.position=e.ordering.length;return}this.setResult(i,Ut((0,R.normalizeOperationOutcome)(a))),this.state.position=n+1}}setResult(e,r){this.state.resultEntries[e]=r,this.state.pendingIndices.push(e)}async processBatchEntry(e){let r=this.getRouteForEntry(e);if(!r)throw new R.OperationOutcomeError(R.notFound);let n=this.parseBatchRequest(e,r),[i,o]=await r.handler(n,this.repo,this.router,{batch:!0});if(!(0,R.isOk)(i)&&this.isTransaction())throw new R.OperationOutcomeError(i);return Ut(i,o)}parseBatchRequest(e,r){let n=e.request,i=Object.create(null);n.ifNoneExist&&(i["if-none-exist"]=n.ifNoneExist),n.ifMatch&&(i["if-match"]=n.ifMatch),n.ifNoneMatch&&(i["if-none-match"]=n.ifNoneMatch),n.ifModifiedSince&&(i["if-modified-since"]=n.ifModifiedSince);let o;return n.method==="PATCH"?o=this.parsePatchBody(e):o=e.resource,{method:n.method,url:r?.query?n.url.slice(0,n.url.indexOf("?")):n.url,pathname:"",params:r?.params??Object.create(null),query:r?.query??Object.create(null),body:o,headers:i,config:this.req.config}}parsePatchBody(e){let r=e.resource,n;if(r?.resourceType==="Binary"){if(!r.data)throw new R.OperationOutcomeError((0,R.badRequest)("Missing entry.resource.data"));n=JSON.parse(Buffer.from(r.data,"base64").toString("utf8"))}else if(r?.resourceType==="Parameters"){if(Ra(r))return this.rewriteIds(r);if(r.parameter){n=[];for(let i of r.parameter)if(i.name==="operation"){let o=this.parsePatchParameter(i);n.push(o)}}}else throw new R.OperationOutcomeError((0,R.badRequest)("Patch entry must include a Binary or Parameters resource"));if(!Array.isArray(n))throw new R.OperationOutcomeError((0,R.badRequest)("Decoded PATCH body must be an array"));return this.rewriteIdsInArray(n)}parsePatchParameter(e){let r=e.part?.find(i=>i.name==="op")?.valueCode;if(!r)throw new R.OperationOutcomeError((0,R.badRequest)("PATCH Parameters missing op"));let n={op:r};switch(r){case"add":case"replace":case"test":for(let i of e.part)i.name==="path"?n.path=i.valueString:i.name==="value"&&(n.value=JSON.parse(i.valueString??""));break;case"copy":case"move":for(let i of e.part)i.name==="path"?n.path=i.valueString:i.name==="from"&&(n.from=i.valueString);break;case"remove":n.path=e.part?.find(i=>i.name==="path")?.valueString;break}return n}rewriteIds(e){return Array.isArray(e)?this.rewriteIdsInArray(e):typeof e=="string"?this.rewriteIdsInString(e):typeof e=="object"&&e!==null?this.rewriteIdsInObject(e):e}rewriteIdsInArray(e){return e.map(r=>this.rewriteIds(r))}rewriteIdsInObject(e){return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,this.rewriteIds(n)]))}rewriteIdsInString(e){let r=va.exec(e)?.[0];if(!r)return e;let n=r.replaceAll("%3A",":"),i=this.resolvedIdentities[n];return i?e.replaceAll(r,i):e}isTransaction(){return this.bundle.type==="transaction"&&!!this.req.config?.transactions}};function Ra(t){return!!t.parameter?.some(e=>e.name==="operation"&&e.part?.some(r=>r.name==="type"))}function Ut(t,e){return{response:{outcome:t,status:(0,R.getStatus)(t).toString(),location:(0,R.isOk)(t)&&e?.id?(0,R.getReferenceString)(e):void 0},resource:e}}function vo(t,e,r){let n=new Array(e);for(let i=0;i<e;i++)n[i]=r[i];return{resourceType:"Bundle",type:`${t}-response`,entry:n}}function bo(t){return{position:t.position,resultEntries:t.resultEntries.slice(),pendingIndices:t.pendingIndices.slice(),errors:t.errors.slice()}}var O=require("@medplum/core");var M=require("@medplum/core"),ca=No(require("dataloader"),1);function E(t){return gr(t,[])}function gr(t,e){switch(typeof t){case"string":return JSON.stringify(t);case"function":return t.name?`[function ${t.name}]`:"[function]";case"object":return Sa(t,e);default:return String(t)}}function Sa(t,e){if(t===null)return"null";if(e.includes(t))return"[Circular]";let r=[...e,t];if(xa(t)){let n=t.toJSON();if(n!==t)return typeof n=="string"?n:gr(n,r)}else if(Array.isArray(t))return wa(t,r);return Oa(t,r)}function xa(t){return typeof t.toJSON=="function"}function Oa(t,e){let r=Object.entries(t);return r.length===0?"{}":e.length>2?"["+_a(t)+"]":"{ "+r.map(([i,o])=>i+": "+gr(o,e)).join(", ")+" }"}function wa(t,e){if(t.length===0)return"[]";if(e.length>2)return"[Array]";let r=Math.min(10,t.length),n=t.length-r,i=[];for(let o=0;o<r;++o)i.push(gr(t[o],e));return n===1?i.push("... 1 more item"):n>1&&i.push(`... ${n} more items`),"["+i.join(", ")+"]"}function _a(t){let e=Object.prototype.toString.call(t).replace(/^\[object /,"").replace(/]$/,"");if(e==="Object"&&typeof t.constructor=="function"){let r=t.constructor.name;if(typeof r=="string"&&r!=="")return r}return e}function Da(t,e){return t?.__kind===e}var ne=Da;function we(t){return t instanceof Promise}function de(t){return typeof t?.then=="function"}function Er(t){return t instanceof Error?t:new En(t)}var En=class extends Error{constructor(e){super("Unexpected error value: "+E(e)),this.name="NonErrorThrown",this.thrownValue=e}};function H(t){return typeof t=="object"&&t!==null}function L(t,e){if(!t)throw new Error(e??"Unexpected invariant triggered.")}var La=/\r\n|[\n\r]/g;function Nt(t,e){let r=0,n=1;for(let i of t.body.matchAll(La)){if(typeof i.index!="number"&&L(!1),i.index>=e)break;r=i.index+i[0].length,n+=1}return{line:n,column:e+1-r}}function In(t){return Ir(t.source,Nt(t.source,t.start))}function Ir(t,e){let r=t.locationOffset.column-1,n="".padStart(r)+t.body,i=e.line-1,o=t.locationOffset.line-1,s=e.line+o,a=e.line===1?r:0,c=e.column+a,u=`${t.name}:${s}:${c}
1
+ "use strict";var ma=Object.create;var Vt=Object.defineProperty;var ha=Object.getOwnPropertyDescriptor;var ya=Object.getOwnPropertyNames;var Ta=Object.getPrototypeOf,ga=Object.prototype.hasOwnProperty;var Ea=(t,e,r)=>e in t?Vt(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var Eo=(t,e)=>{for(var r in e)Vt(t,r,{get:e[r],enumerable:!0})},Io=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ya(e))!ga.call(t,i)&&i!==r&&Vt(t,i,{get:()=>e[i],enumerable:!(n=ha(e,i))||n.enumerable});return t};var No=(t,e,r)=>(r=t!=null?ma(Ta(t)):{},Io(e||!t||!t.__esModule?Vt(r,"default",{value:t,enumerable:!0}):r,t)),Ia=t=>Io(Vt({},"__esModule",{value:!0}),t);var $=(t,e,r)=>Ea(t,typeof e!="symbol"?e+"":e,r);var $l={};Eo($l,{BatchProcessor:()=>$t,FhirRepository:()=>mn,FhirRouter:()=>ho,MAX_QUERY_STRING_LENGTH:()=>mo,MemoryRepository:()=>no,RepositoryMode:()=>fr,Router:()=>hr,buildBatchResponseBundle:()=>vo,createResourceImpl:()=>la,getExtraEntries:()=>ro,getSearchIncludeEntries:()=>Js,getSearchRevIncludeEntries:()=>Xs,makeSimpleRequest:()=>Ul,processBatch:()=>Tr,updateResourceImpl:()=>fa});module.exports=Ia($l);var R=require("@medplum/core");var Na=50,ba=8,va=/urn(:|%3A)uuid(:|%3A)[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/;async function Tr(t,e,r,n){return new $t(r,e,n,t).run()}var $t=class t{constructor(e,r,n,i){$(this,"router");$(this,"repo");$(this,"bundle");$(this,"req");$(this,"resolvedIdentities");$(this,"bundleInfo");$(this,"state");this.router=e,this.repo=r,this.bundle=n,this.req=i,this.resolvedIdentities=Object.create(null),this.state={position:0,resultEntries:new Array(n.entry?.length??0),pendingIndices:[],errors:[]}}static fromState(e,r,n,i,o){let s=new t(e,r,i.bundle,n);return s.resolvedIdentities=i.resolvedIdentities,s.bundleInfo={...i.bundleInfo},s.state.position=o,s}async run(){await this.preprocess();let e=this.bundleInfo;if(!this.isTransaction()){let i=await this.processEntriesAndBuild();return this.dispatchPostEvent(),i}let r=bo(this.state),n=await this.repo.withTransaction(i=>this.withRepo(i,()=>(this.state=bo(r),this.processEntriesAndBuild())),{serializable:e.requiresStrongTransaction,resourceTypes:e.resourceTypes});return this.dispatchPostEvent(),n}async preprocess(){let e=this.bundle.type;if(e!=="batch"&&e!=="transaction")throw new R.OperationOutcomeError((0,R.badRequest)("Unrecognized bundle type: "+e));if(this.bundleInfo=await this.preprocessBundle(),this.isTransaction()){if(this.bundleInfo.updates>Na)throw new R.OperationOutcomeError((0,R.badRequest)("Transaction contains more update operations than allowed"));if(this.bundleInfo.requiresStrongTransaction&&this.state.resultEntries.length>ba)throw new R.OperationOutcomeError((0,R.badRequest)("Transaction requires strict isolation but has too many entries"))}this.dispatchPreEvent();let r=Object.create(null);for(let n=0;n<this.state.resultEntries.length;n++)this.state.resultEntries[n]&&(r[n]=this.state.resultEntries[n]);return{bundle:this.bundle,bundleInfo:{ordering:this.bundleInfo.ordering,resourceTypes:this.bundleInfo.resourceTypes,requiresStrongTransaction:this.bundleInfo.requiresStrongTransaction,updates:this.bundleInfo.updates},resolvedIdentities:this.resolvedIdentities,preprocessResults:r}}hasMoreEntries(){return this.bundleInfo!==void 0&&this.state.position<this.bundleInfo.ordering.length}getPosition(){return this.state.position}takePendingResults(){if(this.state.pendingIndices.length===0)return;let e=Object.create(null);for(let r of this.state.pendingIndices)e[r]=this.state.resultEntries[r];return this.state.pendingIndices=[],e}async processEntriesAndBuild(){for(;this.hasMoreEntries();)await this.processNextEntryImpl();return this.buildResultBundle()}dispatchPreEvent(){let e={type:"batch",bundleType:this.bundle.type,count:this.bundle.entry?.length,size:JSON.stringify(this.bundle).length};this.router.dispatchEvent(e)}dispatchPostEvent(){let e={type:"batch",bundleType:this.bundle.type,errors:this.state.errors.length?this.state.errors:void 0};this.router.dispatchEvent(e)}buildResultBundle(){return{resourceType:"Bundle",type:`${this.bundle.type}-response`,entry:this.state.resultEntries}}async withRepo(e,r){let n=this.repo;this.repo=e;try{return await r()}finally{this.repo=n}}async preprocessBundle(){let e=this.bundle.entry;if(!e?.length)throw new R.OperationOutcomeError((0,R.badRequest)("Missing bundle entries"));let r={transaction:[],batch:[],delete:[],create:[],update:[],patch:[],operation:[],"search-system":[],"search-type":[],read:[],vread:[],"history-system":[],"history-type":[],"history-instance":[]},n=new Set,i=new Set,o=!1,s=0;for(let c=0;c<e.length;c++){let u=e[c];if(!u.request?.method){this.state.resultEntries[c]=Ut((0,R.badRequest)("Missing Bundle entry request method",`Bundle.entry[${c}].request.method`));continue}let f=await this.preprocessEntry(u,c,n);if(f){if(!this.isTransaction()){this.state.resultEntries[c]=Ut(f);continue}throw new R.OperationOutcomeError(f)}let m=this.getRouteForEntry(u),g=m?.data?.interaction;if(!g||!r[g])throw new R.OperationOutcomeError((0,R.badRequest)(`Invalid REST interaction in batch: ${u.request?.method} ${u.request?.url}`));let y=m?.params?.resourceType;y&&i.add(y),g==="create"&&u.request?.ifNoneExist?o=!0:g==="update"?(u.request?.url.includes("?")&&(o=!0),s++):g==="delete"&&u.request?.url.includes("?")&&(o=!0),r[g].push(c)}let a=[];for(let c of Object.values(r))a.push(...c);return{ordering:a,requiresStrongTransaction:o,updates:s,resourceTypes:i}}async preprocessEntry(e,r,n){if(!e.request?.url)return(0,R.badRequest)("Missing Bundle entry request URL",`Bundle.entry[${r}].request.url`);let i;try{i=await this.resolveIdentity(e,`Bundle.entry[${r}]`)}catch(o){if(o instanceof R.OperationOutcomeError)return o.outcome;throw o}if(i&&(this.resolvedIdentities[i.placeholder]=i.reference,this.isTransaction())){if(n.has(i.reference))throw new R.OperationOutcomeError((0,R.badRequest)("Duplicate resource identity found in Bundle"));n.add(i.reference)}}async resolveIdentity(e,r){let i=this.getRouteForEntry(e)?.data?.interaction;if(!i)throw new R.OperationOutcomeError(R.notFound);switch(i){case"create":return this.resolveCreateIdentity(e);case"delete":case"update":case"patch":return this.resolveModificationIdentity(e,r);default:return}}getRouteForEntry(e){return this.router.find(e.request?.method,e.request?.url??"")}async resolveCreateIdentity(e){let r=e.fullUrl??"";if(e.request?.ifNoneExist){let n=await this.repo.searchResources((0,R.parseSearchRequest)(e.request.url+"?"+e.request.ifNoneExist));if(n.length===1)return{placeholder:r,reference:(0,R.getReferenceString)(n[0])}}if(e.resource)return e.resource.id=this.repo.generateId(),{placeholder:r,reference:(0,R.getReferenceString)(e.resource)}}async resolveModificationIdentity(e,r){let n=e.fullUrl??"";if(e.request?.url?.includes("?")){let i=e.request.method,o=(0,R.parseSearchRequest)(e.request.url);o.count=2,o.offset=0,o.sortRules=void 0;let[s,a]=await this.repo.searchResources(o);if(!s)switch(i){case"DELETE":return;case"PUT":if(e.resource){if(e.resource.id)throw new R.OperationOutcomeError((0,R.badRequest)("Cannot provide ID for create by update"));return e.resource.id=this.repo.generateId(),{placeholder:n,reference:(0,R.getReferenceString)(e.resource)}}return;default:throw new R.OperationOutcomeError((0,R.badRequest)(`Conditional ${e.request.method} did not match any resources`,r+".request.url"))}if(a)throw new R.OperationOutcomeError((0,R.badRequest)(`Conditional ${e.request.method} matched multiple resources`,r+".request.url"));let c=(0,R.getReferenceString)(s);return e.request.url=c,e.resource&&(e.resource.id=s.id),{placeholder:n,reference:c}}if(e.request?.url.includes("/"))return{placeholder:n,reference:e.request.url}}async processNextEntry(){if(this.isTransaction())throw new Error("Re-entrant batch processing does not support transaction semantics");await this.processNextEntryImpl()}async processNextEntryImpl(){let e=this.bundleInfo;if(!e)throw new Error("processNextEntry called before preprocess()/fromState()");let r=this.bundle.entry;if(!r)throw new R.OperationOutcomeError((0,R.badRequest)("Missing bundle entry"));if(this.state.position>=e.ordering.length)return;let n=this.state.position,i=e.ordering[n],o=r[i],s=this.rewriteIdsInObject(o);try{this.setResult(i,await this.processBatchEntry(s)),this.state.position=n+1}catch(a){if(this.isTransaction())throw a;if(this.state.errors.push(a.message),a instanceof R.OperationOutcomeError&&(0,R.getStatus)(a.outcome)===429){for(let c=n;c<e.ordering.length;c++)this.setResult(e.ordering[c],Ut(a.outcome));this.state.position=e.ordering.length;return}this.setResult(i,Ut((0,R.normalizeOperationOutcome)(a))),this.state.position=n+1}}setResult(e,r){this.state.resultEntries[e]=r,this.state.pendingIndices.push(e)}async processBatchEntry(e){let r=this.getRouteForEntry(e);if(!r)throw new R.OperationOutcomeError(R.notFound);let n=this.parseBatchRequest(e,r),[i,o]=await r.handler(n,this.repo,this.router,{batch:!0});if(!(0,R.isOk)(i)&&this.isTransaction())throw new R.OperationOutcomeError(i);return Ut(i,o)}parseBatchRequest(e,r){let n=e.request,i=Object.create(null);n.ifNoneExist&&(i["if-none-exist"]=n.ifNoneExist),n.ifMatch&&(i["if-match"]=n.ifMatch),n.ifNoneMatch&&(i["if-none-match"]=n.ifNoneMatch),n.ifModifiedSince&&(i["if-modified-since"]=n.ifModifiedSince);let o;return n.method==="PATCH"?o=this.parsePatchBody(e):o=e.resource,{method:n.method,url:r?.query?n.url.slice(0,n.url.indexOf("?")):n.url,pathname:"",params:r?.params??Object.create(null),query:r?.query??Object.create(null),body:o,headers:i,config:this.req.config}}parsePatchBody(e){let r=e.resource,n;if(r?.resourceType==="Binary"){if(!r.data)throw new R.OperationOutcomeError((0,R.badRequest)("Missing entry.resource.data"));n=JSON.parse(Buffer.from(r.data,"base64").toString("utf8"))}else if(r?.resourceType==="Parameters"){if(Ra(r))return this.rewriteIds(r);if(r.parameter){n=[];for(let i of r.parameter)if(i.name==="operation"){let o=this.parsePatchParameter(i);n.push(o)}}}else throw new R.OperationOutcomeError((0,R.badRequest)("Patch entry must include a Binary or Parameters resource"));if(!Array.isArray(n))throw new R.OperationOutcomeError((0,R.badRequest)("Decoded PATCH body must be an array"));return this.rewriteIdsInArray(n)}parsePatchParameter(e){let r=e.part?.find(i=>i.name==="op")?.valueCode;if(!r)throw new R.OperationOutcomeError((0,R.badRequest)("PATCH Parameters missing op"));let n={op:r};switch(r){case"add":case"replace":case"test":for(let i of e.part)i.name==="path"?n.path=i.valueString:i.name==="value"&&(n.value=JSON.parse(i.valueString??""));break;case"copy":case"move":for(let i of e.part)i.name==="path"?n.path=i.valueString:i.name==="from"&&(n.from=i.valueString);break;case"remove":n.path=e.part?.find(i=>i.name==="path")?.valueString;break}return n}rewriteIds(e){return Array.isArray(e)?this.rewriteIdsInArray(e):typeof e=="string"?this.rewriteIdsInString(e):typeof e=="object"&&e!==null?this.rewriteIdsInObject(e):e}rewriteIdsInArray(e){return e.map(r=>this.rewriteIds(r))}rewriteIdsInObject(e){return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,this.rewriteIds(n)]))}rewriteIdsInString(e){let r=va.exec(e)?.[0];if(!r)return e;let n=r.replaceAll("%3A",":"),i=this.resolvedIdentities[n];return i?e.replaceAll(r,i):e}isTransaction(){return this.bundle.type==="transaction"&&!!this.req.config?.transactions}};function Ra(t){return!!t.parameter?.some(e=>e.name==="operation"&&e.part?.some(r=>r.name==="type"))}function Ut(t,e){return{response:{outcome:t,status:(0,R.getStatus)(t).toString(),location:(0,R.isOk)(t)&&e?.id?(0,R.getReferenceString)(e):void 0},resource:e}}function vo(t,e,r){let n=new Array(e);for(let i=0;i<e;i++)n[i]=r[i];return{resourceType:"Bundle",type:`${t}-response`,entry:n}}function bo(t){return{position:t.position,resultEntries:t.resultEntries.slice(),pendingIndices:t.pendingIndices.slice(),errors:t.errors.slice()}}var O=require("@medplum/core");var M=require("@medplum/core"),ca=No(require("dataloader"),1);function E(t){return gr(t,[])}function gr(t,e){switch(typeof t){case"string":return JSON.stringify(t);case"function":return t.name?`[function ${t.name}]`:"[function]";case"object":return Sa(t,e);default:return String(t)}}function Sa(t,e){if(t===null)return"null";if(e.includes(t))return"[Circular]";let r=[...e,t];if(xa(t)){let n=t.toJSON();if(n!==t)return typeof n=="string"?n:gr(n,r)}else if(Array.isArray(t))return wa(t,r);return Oa(t,r)}function xa(t){return typeof t.toJSON=="function"}function Oa(t,e){let r=Object.entries(t);return r.length===0?"{}":e.length>2?"["+_a(t)+"]":"{ "+r.map(([i,o])=>i+": "+gr(o,e)).join(", ")+" }"}function wa(t,e){if(t.length===0)return"[]";if(e.length>2)return"[Array]";let r=Math.min(10,t.length),n=t.length-r,i=[];for(let o=0;o<r;++o)i.push(gr(t[o],e));return n===1?i.push("... 1 more item"):n>1&&i.push(`... ${n} more items`),"["+i.join(", ")+"]"}function _a(t){let e=Object.prototype.toString.call(t).replace(/^\[object /,"").replace(/]$/,"");if(e==="Object"&&typeof t.constructor=="function"){let r=t.constructor.name;if(typeof r=="string"&&r!=="")return r}return e}function Da(t,e){return t?.__kind===e}var ne=Da;function we(t){return t instanceof Promise}function de(t){return typeof t?.then=="function"}function Er(t){return t instanceof Error?t:new En(t)}var En=class extends Error{constructor(e){super("Unexpected error value: "+E(e)),this.name="NonErrorThrown",this.thrownValue=e}};function H(t){return typeof t=="object"&&t!==null}function L(t,e){if(!t)throw new Error(e??"Unexpected invariant triggered.")}var La=/\r\n|[\n\r]/g;function Nt(t,e){let r=0,n=1;for(let i of t.body.matchAll(La)){if(typeof i.index!="number"&&L(!1),i.index>=e)break;r=i.index+i[0].length,n+=1}return{line:n,column:e+1-r}}function In(t){return Ir(t.source,Nt(t.source,t.start))}function Ir(t,e){let r=t.locationOffset.column-1,n="".padStart(r)+t.body,i=e.line-1,o=t.locationOffset.line-1,s=e.line+o,a=e.line===1?r:0,c=e.column+a,u=`${t.name}:${s}:${c}
2
2
  `,l=n.split(/\r\n|[\n\r]/g),f=l[i];if(f.length>120){let m=Math.floor(c/80),g=c%80,y=[];for(let x=0;x<f.length;x+=80)y.push(f.slice(x,x+80));return u+Ro([[`${s} |`,y[0]],...y.slice(1,m+1).map(x=>["|",x]),["|","^".padStart(g)],["|",y[m+1]]])}return u+Ro([[`${s-1} |`,l[i-1]],[`${s} |`,f],["|","^".padStart(c)],[`${s+1} |`,l[i+1]]])}function Ro(t){let e=t.filter(([n,i])=>i!==void 0),r=Math.max(...e.map(([n])=>n.length));return e.map(([n,i])=>n.padStart(r)+(i?" "+i:"")).join(`
3
3
  `)}var d=class t extends Error{constructor(e,r={}){let{nodes:n,source:i,positions:o,path:s,originalError:a,cause:c,extensions:u}=r,l="cause"in r,f=l?c:a,m=l||a!=null?{cause:f}:void 0;super(e,m),this.name="GraphQLError",this.path=s??void 0;let g=a??(c instanceof Error?c:void 0);this.originalError=g,this.nodes=So(Array.isArray(n)?n:n?[n]:void 0);let y=So(this.nodes?.map(S=>S.loc).filter(S=>S!=null));this.source=i??y?.[0]?.source,this.positions=o??y?.map(S=>S.start),this.locations=o&&i?o.map(S=>Nt(i,S)):y?.map(S=>Nt(S.source,S.start));let x=H(g?.extensions)?g.extensions:void 0;this.extensions=u??x??Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),a?.stack!=null?Object.defineProperty(this,"stack",{value:a.stack,writable:!0,configurable:!0}):Error.captureStackTrace!=null?Error.captureStackTrace(this,t):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}get[Symbol.toStringTag](){return"GraphQLError"}toString(){let e=this.message;if(this.nodes)for(let r of this.nodes)r.loc&&(e+=`
4
4
 
@@ -50,5 +50,5 @@ In some cases, you need to provide options to alter GraphQL's execution behavior
50
50
  `))}var $n=class{constructor(e){this._errors=[],this.schema=e}reportError(e,r){let n=Array.isArray(r)?r.filter(Boolean):r;this._errors.push(new d(e,{nodes:n}))}getErrors(){return this._errors}};function Kc(t){let e=t.schema;e.getQueryType()==null&&t.reportError("Query root type must be provided.",e.astNode);let r=new Ge;for(let n of Object.values(G)){let i=e.getRootType(n);if(i!=null)if(k(i))r.add(i,n);else{let o=xo(n),s=E(i);t.reportError(n===G.QUERY?`${o} root type must be Object type, it cannot be ${s}.`:`${o} root type must be Object type if provided, it cannot be ${s}.`,ss(e,n)??i.astNode)}}for(let[n,i]of r)if(i.length>1){let o=wo(i);t.reportError(`All root types must be different, "${n}" type is used as ${o} root types.`,i.map(s=>ss(e,s)))}}function ss(t,e){return[t.astNode,...t.extensionASTNodes].flatMap(r=>r?.operationTypes??[]).find(r=>r.operation===e)?.type}function Yc(t){for(let e of t.schema.getDirectives()){if(!Zt(e)){t.reportError(`Expected directive but got: ${E(e)}.`,e?.astNode);continue}ft(t,e),e.locations.length===0&&t.reportError(`Directive ${e} must include 1 or more locations.`,e.astNode);for(let r of e.args)ft(t,r),Z(r.type)||t.reportError(`The type of ${r} must be Input Type but got: ${E(r.type)}.`,r.astNode),Ne(r)&&r.deprecationReason!=null&&t.reportError(`Required argument ${r} cannot be deprecated.`,[$r(r.astNode),r.astNode?.type]),Bn(t,r)}}function Bn(t,e){let r=e.default;if(!r)return;let n=[];if(Qn(r,e.type,(i,o)=>{n.push([i,o])}),n.length!==0){if(!r.literal)try{let i=rr(r.value,e.type),o=[];if(Xt(i,e.type,(s,a)=>{o.push([s,a])}),o.length===0){t.reportError(`${e} has invalid default value: ${E(r.value)}. Did you mean: ${E(i)}?`,e.astNode?.defaultValue);return}}catch{}for(let[i,o]of n)t.reportError(`${e} has invalid default value${ze(o)}: ${i.message}`,i.nodes??e.astNode?.defaultValue)}}function Qn(t,e,r,n){if(t.literal){wt(t.literal,e,r,void 0,void 0,n);return}Xt(t.value,e,r,n)}function rr(t,e){if(_(e))return rr(t,e.ofType);if(t===null)return null;if(C(e))return le(t)?Array.from(t,r=>rr(r,e.ofType)):[rr(t,e.ofType)];if(F(e)){H(t)||L(!1);let r=e.getFields();return ke(t,(n,i)=>(i in r||L(!1),rr(n,r[i].type)))}return Ee(e),e.coerceOutputValue(t)}function ft(t,e){e.name.startsWith("__")&&t.reportError(`Name "${e.name}" must not begin with "__", which is reserved by GraphQL introspection.`,e.astNode)}function Hc(t){let e=nu(t),r=t.schema.getTypeMap(),n=new Map;for(let o of Object.values(r)){if(!_r(o)){t.reportError(`Expected GraphQL named type but got: ${E(o)}.`,o.astNode);continue}Vn(o)||ft(t,o),k(o)||P(o)?(as(t,o),cs(t,o)):ee(o)?Xc(t,o):J(o)?zc(t,o):F(o)&&(Zc(t,o),i(o),e(o))}tu(t,n);function i(o){n.set(o,{inputObj:o,targets:[],dependents:[],unresolvedTargetCount:0,hasFiniteValue:!1})}}function as(t,e){let r=Object.values(e.getFields());r.length===0&&t.reportError(`Type ${e} must define one or more fields.`,[e.astNode,...e.extensionASTNodes]);for(let n of r){ft(t,n),Be(n.type)||t.reportError(`The type of ${n} must be Output Type but got: ${E(n.type)}.`,n.astNode?.type);for(let i of n.args)ft(t,i),Z(i.type)||t.reportError(`The type of ${i} must be Input Type but got: ${E(i.type)}.`,i.astNode?.type),Ne(i)&&i.deprecationReason!=null&&t.reportError(`Required argument ${i} cannot be deprecated.`,[$r(i.astNode),i.astNode?.type]),Bn(t,i)}}function cs(t,e){let r=new Set;for(let n of e.getInterfaces()){if(!P(n)){t.reportError(`Type ${e} must only implement Interface types, it cannot implement ${E(n)}.`,nr(e,n));continue}if(e===n){t.reportError(`Type ${e} cannot implement itself because it would create a circular reference.`,nr(e,n));continue}if(r.has(n.name)){t.reportError(`Type ${e} can only implement ${n} once.`,nr(e,n));continue}r.add(n.name),Jc(t,e,n),Wc(t,e,n)}}function Wc(t,e,r){let n=e.getFields();for(let i of Object.values(r.getFields())){let o=n[i.name];if(o==null){t.reportError(`Interface field ${i} expected but ${e} does not provide it.`,[i.astNode,e.astNode,...e.extensionASTNodes]);continue}qe(t.schema,o.type,i.type)||t.reportError(`Interface field ${i} expects type ${i.type} but ${o} is type ${o.type}.`,[i.astNode?.type,o.astNode?.type]);for(let s of i.args){let a=o.args.find(c=>c.name===s.name);if(!a){t.reportError(`Interface field argument ${s} expected but ${o} does not provide it.`,[s.astNode,o.astNode]);continue}Lr(s.type,a.type)||t.reportError(`Interface field argument ${s} expects type ${s.type} but ${a} is type ${a.type}.`,[s.astNode?.type,a.astNode?.type])}for(let s of o.args)Ne(s)&&(i.args.find(c=>c.name===s.name)||t.reportError(`Argument "${s}" must not be required type "${s.type}" if not provided by the Interface field "${i}".`,[s.astNode,i.astNode]));o.deprecationReason!=null&&i.deprecationReason==null&&t.reportError(`Interface field ${r.name}.${i.name} is not deprecated, so implementation field ${e.name}.${o.name} must not be deprecated.`,[$r(o.astNode),o.astNode?.type])}}function Jc(t,e,r){let n=e.getInterfaces();for(let i of r.getInterfaces())n.includes(i)||t.reportError(i===e?`Type ${e} cannot implement ${r} because it would create a circular reference.`:`Type ${e} must implement ${i} because it is implemented by ${r}.`,[...nr(r,i),...nr(e,r)])}function Xc(t,e){let r=e.getTypes();r.length===0&&t.reportError(`Union type ${e} must define one or more member types.`,[e.astNode,...e.extensionASTNodes]);let n=new Set;for(let i of r){if(n.has(i.name)){t.reportError(`Union type ${e} can only include type ${i} once.`,us(e,i.name));continue}n.add(i.name),k(i)||t.reportError(`Union type ${e} can only include Object types, it cannot include ${E(i)}.`,us(e,String(i)))}}function zc(t,e){let r=e.getValues();r.length===0&&t.reportError(`Enum type ${e} must define one or more values.`,[e.astNode,...e.extensionASTNodes]);for(let n of r)ft(t,n)}function Zc(t,e){let r=Object.values(e.getFields());r.length===0&&t.reportError(`Input Object type ${e} must define one or more fields.`,[e.astNode,...e.extensionASTNodes]);for(let n of r)ft(t,n),Z(n.type)||t.reportError(`The type of ${n} must be Input Type but got: ${E(n.type)}.`,n.astNode?.type),me(n)&&n.deprecationReason!=null&&t.reportError(`Required input field ${n} cannot be deprecated.`,[$r(n.astNode),n.astNode?.type]),Bn(t,n),e.isOneOf&&eu(e,n,t)}function eu(t,e,r){_(e.type)&&r.reportError(`OneOf input field ${t}.${e.name} must be nullable.`,e.astNode?.type),(e.default!==void 0||e.defaultValue!==void 0)&&r.reportError(`OneOf input field ${t}.${e.name} cannot have a default value.`,e.astNode)}function tu(t,e){let r=[];for(let u of e.values()){let l=u.inputObj,f=Object.values(l.getFields());for(let m of f){let g=ru(l,m.type);if(g===void 0)continue;u.targets.push({field:m,target:g});let y=e.get(g);y!==void 0&&y.dependents.push(u)}l.isOneOf?(f.length===0||u.targets.length<f.length)&&a(u):(u.unresolvedTargetCount=u.targets.length,u.targets.length===0&&a(u))}let n;for(;(n=r.pop())!==void 0;)for(let u of n.dependents)if(!u.hasFiniteValue){if(u.inputObj.isOneOf){a(u);continue}--u.unresolvedTargetCount,u.unresolvedTargetCount===0&&a(u)}let i=new Set,o=[],s=new Map;for(let u of e.values())u.hasFiniteValue||c(u);function a(u){u.hasFiniteValue||(u.hasFiniteValue=!0,r.push(u))}function c(u){let l=u.inputObj;if(!i.has(l)){i.add(l),s.set(l,o.length);for(let{field:f,target:m}of u.targets){let g=e.get(m);if(g?.hasFiniteValue!==!1)continue;let y=s.get(m);if(o.push({fieldStr:`${l}.${f.name}`,astNode:f.astNode}),y===void 0)c(g);else{let x=o.slice(y),S=x.map(A=>A.fieldStr).join(", ");t.reportError(`Input Object ${m} cannot be provided a finite value because it references itself through fields: ${S}.`,x.map(A=>A.astNode))}o.pop()}s.delete(l)}}}function ru(t,e){if(t.isOneOf)return F(e)?e:void 0;if(_(e)&&F(e.ofType))return e.ofType}function nu(t){let e=Object.create(null),r=[],n=Object.create(null);return function(c){return i(c,Object.create(null))};function i(a,c){if(le(c)){for(let u of c)i(a,u);return}else if(!H(c))return;for(let u of Object.values(a.getFields())){let l=te(u.type);F(l)&&(Object.hasOwn(c,u.name)?i(l,c[u.name]):s(u,l,`${a}.${u.name}`))}}function o(a,c){if(c.kind===p.LIST){for(let l of c.values)o(a,l);return}else if(c.kind!==p.OBJECT)return;let u=bt(c.fields,l=>l.name.value);for(let l of Object.values(a.getFields())){let f=te(l.type);F(f)&&(Object.hasOwn(u,l.name)?o(f,u[l.name].value):s(l,f,`${a}.${l.name}`))}}function s(a,c,u){let l=a.default;if(l===void 0)return;let f=n[u];if(f!==void 0){t.reportError(`Invalid circular reference. The default value of Input Object field ${u} references itself${f<r.length?` via the default values of: ${r.slice(f).map(([m])=>m).join(", ")}`:""}.`,r.slice(f-1).map(([,m])=>m));return}e[u]===void 0&&(e[u]=!0,n[u]=r.push([u,a.astNode?.defaultValue]),l.literal?o(c,l.literal):i(c,l.value),r.pop(),n[u]=void 0)}}function nr(t,e){let{astNode:r,extensionASTNodes:n}=t;return(r!=null?[r,...n]:n).flatMap(o=>o.interfaces??[]).filter(o=>o.name.value===e.name)}function us(t,e){let{astNode:r,extensionASTNodes:n}=t;return(r!=null?[r,...n]:n).flatMap(o=>o.types??[]).filter(o=>o.name.value===e)}function $r(t){return t?.directives?.find(e=>e.name.value===Cr.name)}function q(t,e,r){return new d(`Syntax Error: ${r}`,{source:t,positions:[e]})}function iu(){let t;try{let e=globalThis.process;typeof e?.getBuiltinModule=="function"&&(t=e.getBuiltinModule("node:diagnostics_channel"))}catch{}return t}var dt=iu(),jn=dt?.tracingChannel("graphql:parse"),qn=dt?.tracingChannel("graphql:validate"),Kn=dt?.tracingChannel("graphql:execute"),ps=dt?.tracingChannel("graphql:execute:variableCoercion"),Yn=dt?.tracingChannel("graphql:execute:rootSelectionSet"),ou=dt?.tracingChannel("graphql:subscribe"),mt=dt?.tracingChannel("graphql:resolve"),su=["start","end","asyncStart","asyncEnd","error"];function xe(t){if(t==null)return!1;let e=t.hasSubscribers;if(e!==void 0)return e;for(let r of su)if(t[r].hasSubscribers)return!0;return!1}function Lt(t,e,r){let n=e;return t.start.runStores(n,()=>{let i;try{i=r()}catch(o){throw n.error=o,t.error.publish(n),t.end.publish(n),o}return de(i)?(t.end.publish(n),i.then(o=>(n.result=o,t.asyncStart.publish(n),t.asyncEnd.publish(n),o),o=>{throw n.error=o,t.error.publish(n),t.asyncStart.publish(n),t.asyncEnd.publish(n),o})):(n.result=i,t.end.publish(n),i)})}var h={SOF:"<SOF>",EOF:"<EOF>",BANG:"!",DOLLAR:"$",AMP:"&",PAREN_L:"(",PAREN_R:")",DOT:".",SPREAD:"...",COLON:":",EQUALS:"=",AT:"@",BRACKET_L:"[",BRACKET_R:"]",BRACE_L:"{",PIPE:"|",BRACE_R:"}",NAME:"Name",INT:"Int",FLOAT:"Float",STRING:"String",BLOCK_STRING:"BlockString",COMMENT:"Comment"};var or=class{constructor(e){let r=new vt(h.SOF,0,0,0,0);this.source=e,this.lastToken=r,this.token=r,this.line=1,this.lineStart=0}get[Symbol.toStringTag](){return"Lexer"}advance(){return this.lastToken=this.token,this.token=this.lookahead()}lookahead(){let e=this.token;if(e.kind!==h.EOF)do if(e.next)e=e.next;else{let r=au(this,e.end);e.next=r,r.prev=e,e=r}while(e.kind===h.COMMENT);return e}};function fs(t){return t===h.BANG||t===h.DOLLAR||t===h.AMP||t===h.PAREN_L||t===h.PAREN_R||t===h.DOT||t===h.SPREAD||t===h.COLON||t===h.EQUALS||t===h.AT||t===h.BRACKET_L||t===h.BRACKET_R||t===h.BRACE_L||t===h.PIPE||t===h.BRACE_R}function At(t){return t>=0&&t<=55295||t>=57344&&t<=1114111}function Br(t,e){return ds(t.charCodeAt(e))&&ms(t.charCodeAt(e+1))}function ds(t){return t>=55296&&t<=56319}function ms(t){return t>=56320&&t<=57343}function ht(t,e){let r=t.source.body.codePointAt(e);if(r===void 0)return h.EOF;if(r>=32&&r<=126){let n=String.fromCodePoint(r);return n==='"'?`'"'`:`"${n}"`}return"U+"+r.toString(16).toUpperCase().padStart(4,"0")}function X(t,e,r,n,i){let o=t.line,s=1+r-t.lineStart;return new vt(e,r,n,o,s,i)}function au(t,e){let r=t.source.body,n=r.length,i=e;for(;i<n;){let o=r.charCodeAt(i);switch(o){case 65279:case 9:case 32:case 44:++i;continue;case 10:++i,++t.line,t.lineStart=i;continue;case 13:r.charCodeAt(i+1)===10?i+=2:++i,++t.line,t.lineStart=i;continue;case 35:return cu(t,i);case 33:return X(t,h.BANG,i,i+1);case 36:return X(t,h.DOLLAR,i,i+1);case 38:return X(t,h.AMP,i,i+1);case 40:return X(t,h.PAREN_L,i,i+1);case 41:return X(t,h.PAREN_R,i,i+1);case 46:{let s=r.charCodeAt(i+1);if(s===46&&r.charCodeAt(i+2)===46)return X(t,h.SPREAD,i,i+3);if(s===46)throw q(t.source,i,'Unexpected "..", did you mean "..."?');if(et(s)){let a=t.source.body.slice(i+1,Gr(t,i+1,s));throw q(t.source,i,`Invalid number, expected digit before ".", did you mean "0.${a}"?`)}break}case 58:return X(t,h.COLON,i,i+1);case 61:return X(t,h.EQUALS,i,i+1);case 64:return X(t,h.AT,i,i+1);case 91:return X(t,h.BRACKET_L,i,i+1);case 93:return X(t,h.BRACKET_R,i,i+1);case 123:return X(t,h.BRACE_L,i,i+1);case 124:return X(t,h.PIPE,i,i+1);case 125:return X(t,h.BRACE_R,i,i+1);case 34:return r.charCodeAt(i+1)===34&&r.charCodeAt(i+2)===34?mu(t,i):pu(t,i)}if(et(o)||o===45)return uu(t,i,o);if(jt(o))return hu(t,i);throw q(t.source,i,o===39?`Unexpected single quote character ('), did you mean to use a double quote (")?`:At(o)||Br(r,i)?`Unexpected character: ${ht(t,i)}.`:`Invalid character: ${ht(t,i)}.`)}return X(t,h.EOF,n,n)}function cu(t,e){let r=t.source.body,n=r.length,i=e+1;for(;i<n;){let o=r.charCodeAt(i);if(o===10||o===13)break;if(At(o))++i;else if(Br(r,i))i+=2;else break}return X(t,h.COMMENT,e,i,r.slice(e+1,i))}function uu(t,e,r){let n=t.source.body,i=e,o=r,s=!1;if(o===45&&(o=n.charCodeAt(++i)),o===48){if(o=n.charCodeAt(++i),et(o))throw q(t.source,i,`Invalid number, unexpected digit after 0: ${ht(t,i)}.`)}else i=Gr(t,i,o),o=n.charCodeAt(i);if(o===46&&(s=!0,o=n.charCodeAt(++i),i=Gr(t,i,o),o=n.charCodeAt(i)),(o===69||o===101)&&(s=!0,o=n.charCodeAt(++i),(o===43||o===45)&&(o=n.charCodeAt(++i)),i=Gr(t,i,o),o=n.charCodeAt(i)),o===46||jt(o))throw q(t.source,i,`Invalid number, expected digit but got: ${ht(t,i)}.`);return X(t,s?h.FLOAT:h.INT,e,i,n.slice(e,i))}function Gr(t,e,r){if(!et(r))throw q(t.source,e,`Invalid number, expected digit but got: ${ht(t,e)}.`);let n=t.source.body,i=e+1;for(;et(n.charCodeAt(i));)++i;return i}function pu(t,e){let r=t.source.body,n=r.length,i=e+1,o=i,s="";for(;i<n;){let a=r.charCodeAt(i);if(a===34)return s+=r.slice(o,i),X(t,h.STRING,e,i+1,s);if(a===92){s+=r.slice(o,i);let c=r.charCodeAt(i+1)===117?r.charCodeAt(i+2)===123?lu(t,i):fu(t,i):du(t,i);s+=c.value,i+=c.size,o=i;continue}if(a===10||a===13)break;if(At(a))++i;else if(Br(r,i))i+=2;else throw q(t.source,i,`Invalid character within String: ${ht(t,i)}.`)}throw q(t.source,i,"Unterminated string.")}function lu(t,e){let r=t.source.body,n=0,i=3;for(;i<12;){let o=r.charCodeAt(e+i++);if(o===125){if(i<5||!At(n))break;return{value:String.fromCodePoint(n),size:i}}if(n=n<<4|ir(o),n<0)break}throw q(t.source,e,`Invalid Unicode escape sequence: "${r.slice(e,e+i)}".`)}function fu(t,e){let r=t.source.body,n=ls(r,e+2);if(At(n))return{value:String.fromCodePoint(n),size:6};if(ds(n)&&r.charCodeAt(e+6)===92&&r.charCodeAt(e+7)===117){let i=ls(r,e+8);if(ms(i))return{value:String.fromCodePoint(n,i),size:12}}throw q(t.source,e,`Invalid Unicode escape sequence: "${r.slice(e,e+6)}".`)}function ls(t,e){return ir(t.charCodeAt(e))<<12|ir(t.charCodeAt(e+1))<<8|ir(t.charCodeAt(e+2))<<4|ir(t.charCodeAt(e+3))}function ir(t){return t>=48&&t<=57?t-48:t>=65&&t<=70?t-55:t>=97&&t<=102?t-87:-1}function du(t,e){let r=t.source.body;switch(r.charCodeAt(e+1)){case 34:return{value:'"',size:2};case 92:return{value:"\\",size:2};case 47:return{value:"/",size:2};case 98:return{value:"\b",size:2};case 102:return{value:"\f",size:2};case 110:return{value:`
51
51
  `,size:2};case 114:return{value:"\r",size:2};case 116:return{value:" ",size:2}}throw q(t.source,e,`Invalid character escape sequence: "${r.slice(e,e+2)}".`)}function mu(t,e){let r=t.source.body,n=r.length,i=t.lineStart,o=e+3,s=o,a="",c=[];for(;o<n;){let u=r.charCodeAt(o);if(u===34&&r.charCodeAt(o+1)===34&&r.charCodeAt(o+2)===34){a+=r.slice(s,o),c.push(a);let l=X(t,h.BLOCK_STRING,e,o+3,Ao(c).join(`
52
52
  `));return t.line+=c.length-1,t.lineStart=i,l}if(u===92&&r.charCodeAt(o+1)===34&&r.charCodeAt(o+2)===34&&r.charCodeAt(o+3)===34){a+=r.slice(s,o),s=o+1,o+=4;continue}if(u===10||u===13){a+=r.slice(s,o),c.push(a),u===13&&r.charCodeAt(o+1)===10?o+=2:++o,a="",s=o,i=o;continue}if(At(u))++o;else if(Br(r,o))o+=2;else throw q(t.source,o,`Invalid character within String: ${ht(t,o)}.`)}throw q(t.source,o,"Unterminated string.")}function hu(t,e){let r=t.source.body,n=r.length,i=e+1;for(;i<n;){let o=r.charCodeAt(i);if(vr(o))++i;else break}return X(t,h.NAME,e,i,r.slice(e,i))}var hs=Symbol("Source"),Ft=class{constructor(e,r="GraphQL request",n={line:1,column:1}){this.__kind=hs,this.body=e,this.name=r,this.locationOffset=n,this.locationOffset.line>0||ye(!1,"line in locationOffset is 1-indexed and must be positive."),this.locationOffset.column>0||ye(!1,"column in locationOffset is 1-indexed and must be positive.")}get[Symbol.toStringTag](){return"Source"}};function ys(t){return ne(t,hs,Ft)}function jr(t,e){return xe(jn)?jn.traceSync(()=>Ts(t,e),{source:t}):Ts(t,e)}function Ts(t,e){let r=new Hn(t,e),n=r.parseDocument();return Object.defineProperty(n,"tokenCount",{enumerable:!1,value:r.tokenCount}),n}var Hn=class{constructor(e,r={}){let{lexer:n,...i}=r;if(n)this._lexer=n;else{let o=ys(e)?e:new Ft(e);this._lexer=new or(o)}this._options=i,this._tokenCounter=0}get tokenCount(){return this._tokenCounter}parseName(){let e=this.expectToken(h.NAME);return this.node(e,{kind:p.NAME,value:e.value})}parseDocument(){return this.node(this._lexer.token,{kind:p.DOCUMENT,definitions:this.many(h.SOF,this.parseDefinition,h.EOF)})}parseDefinition(){if(this.peek(h.BRACE_L))return this.parseOperationDefinition();let e=this.peekDescription(),r=e?this._lexer.lookahead():this._lexer.token;if(e&&r.kind===h.BRACE_L)throw q(this._lexer.source,this._lexer.token.start,"Unexpected description, descriptions are not supported on shorthand queries.");if(r.kind===h.NAME){switch(r.value){case"schema":return this.parseSchemaDefinition();case"scalar":return this.parseScalarTypeDefinition();case"type":return this.parseObjectTypeDefinition();case"interface":return this.parseInterfaceTypeDefinition();case"union":return this.parseUnionTypeDefinition();case"enum":return this.parseEnumTypeDefinition();case"input":return this.parseInputObjectTypeDefinition();case"directive":return this.parseDirectiveDefinition()}switch(r.value){case"query":case"mutation":case"subscription":return this.parseOperationDefinition();case"fragment":return this.parseFragmentDefinition()}if(e)throw q(this._lexer.source,this._lexer.token.start,"Unexpected description, only GraphQL definitions support descriptions.");if(r.value==="extend")return this.parseTypeSystemExtension()}throw this.unexpected(r)}parseOperationDefinition(){let e=this._lexer.token;if(this.peek(h.BRACE_L))return this.node(e,{kind:p.OPERATION_DEFINITION,operation:G.QUERY,description:void 0,name:void 0,variableDefinitions:void 0,directives:void 0,selectionSet:this.parseSelectionSet()});let r=this.parseDescription(),n=this.parseOperationType(),i;return this.peek(h.NAME)&&(i=this.parseName()),this.node(e,{kind:p.OPERATION_DEFINITION,operation:n,description:r,name:i,variableDefinitions:this.parseVariableDefinitions(),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseOperationType(){let e=this.expectToken(h.NAME);switch(e.value){case"query":return G.QUERY;case"mutation":return G.MUTATION;case"subscription":return G.SUBSCRIPTION}throw this.unexpected(e)}parseVariableDefinitions(){return this.optionalMany(h.PAREN_L,this.parseVariableDefinition,h.PAREN_R)}parseVariableDefinition(){return this.node(this._lexer.token,{kind:p.VARIABLE_DEFINITION,description:this.parseDescription(),variable:this.parseVariable(),type:(this.expectToken(h.COLON),this.parseTypeReference()),defaultValue:this.expectOptionalToken(h.EQUALS)?this.parseConstValueLiteral():void 0,directives:this.parseConstDirectives()})}parseVariable(){let e=this._lexer.token;return this.expectToken(h.DOLLAR),this.node(e,{kind:p.VARIABLE,name:this.parseName()})}parseSelectionSet(){return this.node(this._lexer.token,{kind:p.SELECTION_SET,selections:this.many(h.BRACE_L,this.parseSelection,h.BRACE_R)})}parseSelection(){return this.peek(h.SPREAD)?this.parseFragment():this.parseField()}parseField(){let e=this._lexer.token,r=this.parseName(),n,i;return this.expectOptionalToken(h.COLON)?(n=r,i=this.parseName()):i=r,this.node(e,{kind:p.FIELD,alias:n,name:i,arguments:this.parseArguments(!1),directives:this.parseDirectives(!1),selectionSet:this.peek(h.BRACE_L)?this.parseSelectionSet():void 0})}parseArguments(e){let r=e?this.parseConstArgument:this.parseArgument;return this.optionalMany(h.PAREN_L,r,h.PAREN_R)}parseFragmentArguments(){let e=this.parseFragmentArgument;return this.optionalMany(h.PAREN_L,e,h.PAREN_R)}parseArgument(e=!1){let r=this._lexer.token,n=this.parseName();return this.expectToken(h.COLON),this.node(r,{kind:p.ARGUMENT,name:n,value:this.parseValueLiteral(e)})}parseConstArgument(){return this.parseArgument(!0)}parseFragmentArgument(){let e=this._lexer.token,r=this.parseName();return this.expectToken(h.COLON),this.node(e,{kind:p.FRAGMENT_ARGUMENT,name:r,value:this.parseValueLiteral(!1)})}parseFragment(){let e=this._lexer.token;this.expectToken(h.SPREAD);let r=this.expectOptionalKeyword("on");if(!r&&this.peek(h.NAME)){let n=this.parseFragmentName();return this.peek(h.PAREN_L)&&this._options.experimentalFragmentArguments?this.node(e,{kind:p.FRAGMENT_SPREAD,name:n,arguments:this.parseFragmentArguments(),directives:this.parseDirectives(!1)}):this.node(e,{kind:p.FRAGMENT_SPREAD,name:n,directives:this.parseDirectives(!1)})}return this.node(e,{kind:p.INLINE_FRAGMENT,typeCondition:r?this.parseNamedType():void 0,directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseFragmentDefinition(){let e=this._lexer.token,r=this.parseDescription();return this.expectKeyword("fragment"),this._options.experimentalFragmentArguments===!0?this.node(e,{kind:p.FRAGMENT_DEFINITION,description:r,name:this.parseFragmentName(),variableDefinitions:this.parseVariableDefinitions(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()}):this.node(e,{kind:p.FRAGMENT_DEFINITION,description:r,name:this.parseFragmentName(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseFragmentName(){if(this._lexer.token.value==="on")throw this.unexpected();return this.parseName()}parseValueLiteral(e){let r=this._lexer.token;switch(r.kind){case h.BRACKET_L:return this.parseList(e);case h.BRACE_L:return this.parseObject(e);case h.INT:return this.advanceLexer(),this.node(r,{kind:p.INT,value:r.value});case h.FLOAT:return this.advanceLexer(),this.node(r,{kind:p.FLOAT,value:r.value});case h.STRING:case h.BLOCK_STRING:return this.parseStringLiteral();case h.NAME:switch(this.advanceLexer(),r.value){case"true":return this.node(r,{kind:p.BOOLEAN,value:!0});case"false":return this.node(r,{kind:p.BOOLEAN,value:!1});case"null":return this.node(r,{kind:p.NULL});default:return this.node(r,{kind:p.ENUM,value:r.value})}case h.DOLLAR:if(e)if(this.expectToken(h.DOLLAR),this._lexer.token.kind===h.NAME){let n=this._lexer.token.value;throw q(this._lexer.source,r.start,`Unexpected variable "$${n}" in constant value.`)}else throw this.unexpected(r);return this.parseVariable();default:throw this.unexpected()}}parseConstValueLiteral(){return this.parseValueLiteral(!0)}parseStringLiteral(){let e=this._lexer.token;return this.advanceLexer(),this.node(e,{kind:p.STRING,value:e.value,block:e.kind===h.BLOCK_STRING})}parseList(e){let r=()=>this.parseValueLiteral(e);return this.node(this._lexer.token,{kind:p.LIST,values:this.any(h.BRACKET_L,r,h.BRACKET_R)})}parseObject(e){let r=()=>this.parseObjectField(e);return this.node(this._lexer.token,{kind:p.OBJECT,fields:this.any(h.BRACE_L,r,h.BRACE_R)})}parseObjectField(e){let r=this._lexer.token,n=this.parseName();return this.expectToken(h.COLON),this.node(r,{kind:p.OBJECT_FIELD,name:n,value:this.parseValueLiteral(e)})}parseDirectives(e){let r=[];for(;this.peek(h.AT);)r.push(this.parseDirective(e));if(r.length)return r}parseConstDirectives(){return this.parseDirectives(!0)}parseDirective(e){let r=this._lexer.token;return this.expectToken(h.AT),this.node(r,{kind:p.DIRECTIVE,name:this.parseName(),arguments:this.parseArguments(e)})}parseTypeReference(){let e=this._lexer.token,r;if(this.expectOptionalToken(h.BRACKET_L)){let n=this.parseTypeReference();this.expectToken(h.BRACKET_R),r=this.node(e,{kind:p.LIST_TYPE,type:n})}else r=this.parseNamedType();return this.expectOptionalToken(h.BANG)?this.node(e,{kind:p.NON_NULL_TYPE,type:r}):r}parseNamedType(){return this.node(this._lexer.token,{kind:p.NAMED_TYPE,name:this.parseName()})}peekDescription(){return this.peek(h.STRING)||this.peek(h.BLOCK_STRING)}parseDescription(){if(this.peekDescription())return this.parseStringLiteral()}parseSchemaDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("schema");let n=this.parseConstDirectives(),i=this.many(h.BRACE_L,this.parseOperationTypeDefinition,h.BRACE_R);return this.node(e,{kind:p.SCHEMA_DEFINITION,description:r,directives:n,operationTypes:i})}parseOperationTypeDefinition(){let e=this._lexer.token,r=this.parseOperationType();this.expectToken(h.COLON);let n=this.parseNamedType();return this.node(e,{kind:p.OPERATION_TYPE_DEFINITION,operation:r,type:n})}parseScalarTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("scalar");let n=this.parseName(),i=this.parseConstDirectives();return this.node(e,{kind:p.SCALAR_TYPE_DEFINITION,description:r,name:n,directives:i})}parseObjectTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("type");let n=this.parseName(),i=this.parseImplementsInterfaces(),o=this.parseConstDirectives(),s=this.parseFieldsDefinition();return this.node(e,{kind:p.OBJECT_TYPE_DEFINITION,description:r,name:n,interfaces:i,directives:o,fields:s})}parseImplementsInterfaces(){return this.expectOptionalKeyword("implements")?this.delimitedMany(h.AMP,this.parseNamedType):void 0}parseFieldsDefinition(){return this.optionalMany(h.BRACE_L,this.parseFieldDefinition,h.BRACE_R)}parseFieldDefinition(){let e=this._lexer.token,r=this.parseDescription(),n=this.parseName(),i=this.parseArgumentDefs();this.expectToken(h.COLON);let o=this.parseTypeReference(),s=this.parseConstDirectives();return this.node(e,{kind:p.FIELD_DEFINITION,description:r,name:n,arguments:i,type:o,directives:s})}parseArgumentDefs(){return this.optionalMany(h.PAREN_L,this.parseInputValueDef,h.PAREN_R)}parseInputValueDef(){let e=this._lexer.token,r=this.parseDescription(),n=this.parseName();this.expectToken(h.COLON);let i=this.parseTypeReference(),o;this.expectOptionalToken(h.EQUALS)&&(o=this.parseConstValueLiteral());let s=this.parseConstDirectives();return this.node(e,{kind:p.INPUT_VALUE_DEFINITION,description:r,name:n,type:i,defaultValue:o,directives:s})}parseInterfaceTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("interface");let n=this.parseName(),i=this.parseImplementsInterfaces(),o=this.parseConstDirectives(),s=this.parseFieldsDefinition();return this.node(e,{kind:p.INTERFACE_TYPE_DEFINITION,description:r,name:n,interfaces:i,directives:o,fields:s})}parseUnionTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("union");let n=this.parseName(),i=this.parseConstDirectives(),o=this.parseUnionMemberTypes();return this.node(e,{kind:p.UNION_TYPE_DEFINITION,description:r,name:n,directives:i,types:o})}parseUnionMemberTypes(){return this.expectOptionalToken(h.EQUALS)?this.delimitedMany(h.PIPE,this.parseNamedType):void 0}parseEnumTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("enum");let n=this.parseName(),i=this.parseConstDirectives(),o=this.parseEnumValuesDefinition();return this.node(e,{kind:p.ENUM_TYPE_DEFINITION,description:r,name:n,directives:i,values:o})}parseEnumValuesDefinition(){return this.optionalMany(h.BRACE_L,this.parseEnumValueDefinition,h.BRACE_R)}parseEnumValueDefinition(){let e=this._lexer.token,r=this.parseDescription(),n=this.parseEnumValueName(),i=this.parseConstDirectives();return this.node(e,{kind:p.ENUM_VALUE_DEFINITION,description:r,name:n,directives:i})}parseEnumValueName(){if(this._lexer.token.value==="true"||this._lexer.token.value==="false"||this._lexer.token.value==="null")throw q(this._lexer.source,this._lexer.token.start,`${Qr(this._lexer.token)} is reserved and cannot be used for an enum value.`);return this.parseName()}parseInputObjectTypeDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("input");let n=this.parseName(),i=this.parseConstDirectives(),o=this.parseInputFieldsDefinition();return this.node(e,{kind:p.INPUT_OBJECT_TYPE_DEFINITION,description:r,name:n,directives:i,fields:o})}parseInputFieldsDefinition(){return this.optionalMany(h.BRACE_L,this.parseInputValueDef,h.BRACE_R)}parseTypeSystemExtension(){let e=this._lexer.lookahead();if(e.kind===h.NAME)switch(e.value){case"schema":return this.parseSchemaExtension();case"scalar":return this.parseScalarTypeExtension();case"type":return this.parseObjectTypeExtension();case"interface":return this.parseInterfaceTypeExtension();case"union":return this.parseUnionTypeExtension();case"enum":return this.parseEnumTypeExtension();case"input":return this.parseInputObjectTypeExtension();case"directive":return this.parseDirectiveExtension()}throw this.unexpected(e)}parseSchemaExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("schema");let r=this.parseConstDirectives(),n=this.optionalMany(h.BRACE_L,this.parseOperationTypeDefinition,h.BRACE_R);if(r===void 0&&n===void 0)throw this.unexpected();return this.node(e,{kind:p.SCHEMA_EXTENSION,directives:r,operationTypes:n})}parseScalarTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("scalar");let r=this.parseName(),n=this.parseConstDirectives();if(n===void 0)throw this.unexpected();return this.node(e,{kind:p.SCALAR_TYPE_EXTENSION,name:r,directives:n})}parseObjectTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("type");let r=this.parseName(),n=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),o=this.parseFieldsDefinition();if(n===void 0&&i===void 0&&o===void 0)throw this.unexpected();return this.node(e,{kind:p.OBJECT_TYPE_EXTENSION,name:r,interfaces:n,directives:i,fields:o})}parseInterfaceTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("interface");let r=this.parseName(),n=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),o=this.parseFieldsDefinition();if(n===void 0&&i===void 0&&o===void 0)throw this.unexpected();return this.node(e,{kind:p.INTERFACE_TYPE_EXTENSION,name:r,interfaces:n,directives:i,fields:o})}parseUnionTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("union");let r=this.parseName(),n=this.parseConstDirectives(),i=this.parseUnionMemberTypes();if(n===void 0&&i===void 0)throw this.unexpected();return this.node(e,{kind:p.UNION_TYPE_EXTENSION,name:r,directives:n,types:i})}parseEnumTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("enum");let r=this.parseName(),n=this.parseConstDirectives(),i=this.parseEnumValuesDefinition();if(n===void 0&&i===void 0)throw this.unexpected();return this.node(e,{kind:p.ENUM_TYPE_EXTENSION,name:r,directives:n,values:i})}parseInputObjectTypeExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("input");let r=this.parseName(),n=this.parseConstDirectives(),i=this.parseInputFieldsDefinition();if(n===void 0&&i===void 0)throw this.unexpected();return this.node(e,{kind:p.INPUT_OBJECT_TYPE_EXTENSION,name:r,directives:n,fields:i})}parseDirectiveExtension(){let e=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("directive"),this.expectToken(h.AT);let r=this.parseName(),n=this.parseConstDirectives();if(n===void 0)throw this.unexpected();return this.node(e,{kind:p.DIRECTIVE_EXTENSION,name:r,directives:n})}parseDirectiveDefinition(){let e=this._lexer.token,r=this.parseDescription();this.expectKeyword("directive"),this.expectToken(h.AT);let n=this.parseName(),i=this.parseArgumentDefs(),o=this.parseConstDirectives(),s=this.expectOptionalKeyword("repeatable");this.expectKeyword("on");let a=this.parseDirectiveLocations();return this.node(e,{kind:p.DIRECTIVE_DEFINITION,description:r,name:n,arguments:i,directives:o,repeatable:s,locations:a})}parseDirectiveLocations(){return this.delimitedMany(h.PIPE,this.parseDirectiveLocation)}parseDirectiveLocation(){let e=this._lexer.token,r=this.parseName();if(Object.hasOwn(v,r.value))return r;throw this.unexpected(e)}parseSchemaCoordinate(){let e=this._lexer.token,r=this.expectOptionalToken(h.AT),n=this.parseName(),i;!r&&this.expectOptionalToken(h.DOT)&&(i=this.parseName());let o;return(r||i)&&this.expectOptionalToken(h.PAREN_L)&&(o=this.parseName(),this.expectToken(h.COLON),this.expectToken(h.PAREN_R)),r?o?this.node(e,{kind:p.DIRECTIVE_ARGUMENT_COORDINATE,name:n,argumentName:o}):this.node(e,{kind:p.DIRECTIVE_COORDINATE,name:n}):i?o?this.node(e,{kind:p.ARGUMENT_COORDINATE,name:n,fieldName:i,argumentName:o}):this.node(e,{kind:p.MEMBER_COORDINATE,name:n,memberName:i}):this.node(e,{kind:p.TYPE_COORDINATE,name:n})}node(e,r){return this._options.noLocation!==!0&&(r.loc=new Gt(e,this._lexer.lastToken,this._lexer.source)),r}peek(e){return this._lexer.token.kind===e}expectToken(e){let r=this._lexer.token;if(r.kind===e)return this.advanceLexer(),r;throw q(this._lexer.source,r.start,`Expected ${gs(e)}, found ${Qr(r)}.`)}expectOptionalToken(e){return this._lexer.token.kind===e?(this.advanceLexer(),!0):!1}expectKeyword(e){let r=this._lexer.token;if(r.kind===h.NAME&&r.value===e)this.advanceLexer();else throw q(this._lexer.source,r.start,`Expected "${e}", found ${Qr(r)}.`)}expectOptionalKeyword(e){let r=this._lexer.token;return r.kind===h.NAME&&r.value===e?(this.advanceLexer(),!0):!1}unexpected(e){let r=e??this._lexer.token;return q(this._lexer.source,r.start,`Unexpected ${Qr(r)}.`)}any(e,r,n){this.expectToken(e);let i=[];for(;!this.expectOptionalToken(n);)i.push(r.call(this));return i}optionalMany(e,r,n){if(this.expectOptionalToken(e)){let i=[];do i.push(r.call(this));while(!this.expectOptionalToken(n));return i}}many(e,r,n){this.expectToken(e);let i=[];do i.push(r.call(this));while(!this.expectOptionalToken(n));return i}delimitedMany(e,r){this.expectOptionalToken(e);let n=[];do n.push(r.call(this));while(this.expectOptionalToken(e));return n}advanceLexer(){let{maxTokens:e}=this._options,r=this._lexer.advance();if(r.kind!==h.EOF&&(++this._tokenCounter,e!==void 0&&this._tokenCounter>e))throw q(this._lexer.source,r.start,`Document contains more than ${e} tokens. Parsing aborted.`)}};function Qr(t){let e=t.value;return gs(t.kind)+(e!=null?` "${e}"`:"")}function gs(t){return fs(t)?`"${t}"`:t}function j(t,e){switch(e.kind){case p.LIST_TYPE:{let r=j(t,e.type);return r&&new B(r)}case p.NON_NULL_TYPE:{let r=j(t,e.type);return r&&new N(r)}case p.NAMED_TYPE:return t.getType(e.name.value)}}var Ct=class{constructor(e,r,n){this._schema=e,this._typeStack=[],this._parentTypeStack=[],this._inputTypeStack=[],this._fieldDefStack=[],this._defaultValueStack=[],this._directive=null,this._argument=null,this._enumValue=null,this._fragmentSignaturesByName=n??(()=>null),this._fragmentSignature=null,this._fragmentArgument=null,r&&(Z(r)&&this._inputTypeStack.push(r),Ie(r)&&this._parentTypeStack.push(r),Be(r)&&this._typeStack.push(r))}get[Symbol.toStringTag](){return"TypeInfo"}getType(){return this._typeStack.at(-1)}getParentType(){return this._parentTypeStack.at(-1)}getInputType(){return this._inputTypeStack.at(-1)}getParentInputType(){return this._inputTypeStack.at(-2)}getFieldDef(){return this._fieldDefStack.at(-1)}getDefaultValue(){return this._defaultValueStack.at(-1)}getDirective(){return this._directive}getArgument(){return this._argument}getFragmentSignature(){return this._fragmentSignature}getFragmentSignatureByName(){return this._fragmentSignaturesByName}getFragmentArgument(){return this._fragmentArgument}getEnumValue(){return this._enumValue}enter(e){let r=this._schema;switch(e.kind){case p.DOCUMENT:{let n=yu(e);this._fragmentSignaturesByName=i=>n.get(i);break}case p.SELECTION_SET:{let n=te(this.getType());this._parentTypeStack.push(Ie(n)?n:void 0);break}case p.FIELD:{let n=this.getParentType(),i,o;n&&(i=r.getField(n,e.name.value),i&&(o=i.type)),this._fieldDefStack.push(i),this._typeStack.push(Be(o)?o:void 0);break}case p.DIRECTIVE:this._directive=r.getDirective(e.name.value);break;case p.OPERATION_DEFINITION:{let n=r.getRootType(e.operation);this._typeStack.push(k(n)?n:void 0);break}case p.FRAGMENT_SPREAD:{this._fragmentSignature=this.getFragmentSignatureByName()(e.name.value);break}case p.INLINE_FRAGMENT:case p.FRAGMENT_DEFINITION:{let n=e.typeCondition,i=n?j(r,n):te(this.getType());this._typeStack.push(Be(i)?i:void 0);break}case p.VARIABLE_DEFINITION:{let n=j(r,e.type);this._inputTypeStack.push(Z(n)?n:void 0);break}case p.ARGUMENT:{let n,i,o=this.getDirective()??this.getFieldDef();o&&(n=o.args.find(s=>s.name===e.name.value),n&&(i=n.type)),this._argument=n,this._defaultValueStack.push(n?.default??n?.defaultValue??void 0),this._inputTypeStack.push(Z(i)?i:void 0);break}case p.FRAGMENT_ARGUMENT:{let i=this.getFragmentSignature()?.variableDefinitions.get(e.name.value);this._fragmentArgument=i;let o;i&&(o=j(this._schema,i.type)),this._inputTypeStack.push(Z(o)?o:void 0);break}case p.LIST:{let n=wr(this.getInputType()),i=C(n)?n.ofType:void 0;this._defaultValueStack.push(void 0),this._inputTypeStack.push(Z(i)?i:void 0);break}case p.OBJECT_FIELD:{let n=te(this.getInputType()),i,o;F(n)&&(o=n.getFields()[e.name.value],o!=null&&(i=o.type)),this._defaultValueStack.push(o?.default??o?.defaultValue??void 0),this._inputTypeStack.push(Z(i)?i:void 0);break}case p.ENUM:{let n=te(this.getInputType()),i;J(n)&&(i=n.getValue(e.value)),this._enumValue=i;break}default:}}leave(e){switch(e.kind){case p.DOCUMENT:this._fragmentSignaturesByName=()=>null;break;case p.SELECTION_SET:this._parentTypeStack.pop();break;case p.FIELD:this._fieldDefStack.pop(),this._typeStack.pop();break;case p.DIRECTIVE:this._directive=null;break;case p.FRAGMENT_SPREAD:this._fragmentSignature=null;break;case p.OPERATION_DEFINITION:case p.INLINE_FRAGMENT:case p.FRAGMENT_DEFINITION:this._typeStack.pop();break;case p.VARIABLE_DEFINITION:this._inputTypeStack.pop();break;case p.ARGUMENT:this._argument=null,this._defaultValueStack.pop(),this._inputTypeStack.pop();break;case p.FRAGMENT_ARGUMENT:{this._fragmentArgument=null,this._defaultValueStack.pop(),this._inputTypeStack.pop();break}case p.LIST:case p.OBJECT_FIELD:this._defaultValueStack.pop(),this._inputTypeStack.pop();break;case p.ENUM:this._enumValue=null;break;default:}}};function yu(t){let e=new Map;for(let r of t.definitions)if(r.kind===p.FRAGMENT_DEFINITION){let n=new Map;if(r.variableDefinitions)for(let o of r.variableDefinitions)n.set(o.variable.name.value,o);let i={definition:r,variableDefinitions:n};e.set(r.name.value,i)}return e}function qr(t,e){return{enter(...r){let n=r[0];t.enter(n);let i=xt(e,n.kind).enter;if(i){let o=i.apply(e,r);return o!==void 0&&(t.leave(n),Qt(o)&&t.enter(o)),o}},leave(...r){let n=r[0],i=xt(e,n.kind).leave,o;return i&&(o=i.apply(e,r)),t.leave(n),o}}}function Wn(t){let e=new Map;return{Directive(r){if(r.name.value===Qe.name||r.name.value===Ae.name){let i=r.arguments?.find(s=>s.name.value==="label")?.value;if(!i||i.kind===p.NULL)return;if(i.kind!==p.STRING){t.reportError(new d(`Argument "@${r.name.value}(label:)" must be a static string.`,{nodes:r}));return}let o=e.get(i.value);o!=null?t.reportError(new d('Value for arguments "defer(label:)" and "stream(label:)" must be unique across all Defer/Stream directive usages.',{nodes:[o,r]})):e.set(i.value,r)}}}}function Xn(t){return{OperationDefinition(e){let r=t.getDocument(),n=new Map;for(let s of r.definitions)s.kind===p.FRAGMENT_DEFINITION&&n.set(s.name.value,s);if(e.operation!=="subscription"&&e.operation!=="mutation")return;let o=t.getSchema().getRootType(e.operation);o&&Jn({context:t,operationType:e.operation,rootType:o,fragments:n,selectionSet:e.selectionSet,visitedFragments:new Set})}}}function Jn({context:t,operationType:e,rootType:r,fragments:n,selectionSet:i,visitedFragments:o}){for(let s of i.selections)if(s.kind==="Field"){let a=s.directives?.find(c=>c.name.value===Ae.name);a&&t.reportError(new d(`Stream directive cannot be used on root ${e} type "${r}".`,{nodes:a}))}else if(s.kind==="FragmentSpread"){let a=s.name.value;if(o.has(a))continue;let c=n.get(a);if(c){let u=Es(s);u!==void 0&&t.reportError(new d(`Defer directive cannot be used on root ${e} type "${r}".`,{nodes:u})),Jn({context:t,operationType:e,rootType:r,fragments:n,selectionSet:c.selectionSet,visitedFragments:o})}o.add(a)}else if(s.kind==="InlineFragment"){let a=Es(s);a!==void 0&&t.reportError(new d(`Defer directive cannot be used on root ${e} type "${r}".`,{nodes:a})),Jn({context:t,operationType:e,rootType:r,fragments:n,selectionSet:s.selectionSet,visitedFragments:o})}}function Es(t){return t.directives?.find(e=>e.name.value===Qe.name)}function Is(t){let e=t.arguments?.find(r=>r.name.value==="if");if(!e)return!1;if(e.value.kind===p.BOOLEAN){if(e.value.value)return!1}else if(e.value.kind!==p.VARIABLE)return!1;return!0}function Tu(t){let e=t.arguments?.find(r=>r.name.value==="if");return e&&e.value.kind===p.BOOLEAN?!!e.value.value:!0}function gu(t){let e=t.arguments?.find(r=>r.name.value==="if");return e?e?.value.kind===p.BOOLEAN?!e.value.value:!0:!1}function Zn(t){return{OperationDefinition(e){if(e.operation!==G.SUBSCRIPTION)return;let r=t.getDocument(),n=new Map;for(let o of r.definitions)o.kind===p.FRAGMENT_DEFINITION&&n.set(o.name.value,o);let i=new Set;zn({context:t,fragments:n,selectionSet:e.selectionSet,parentNodes:[],visitedFragments:i})}}}function zn({context:t,fragments:e,selectionSet:r,parentNodes:n,visitedFragments:i}){for(let o of r.selections){let s=o.directives?.find(c=>c.name.value===pt.name);if(s&&Tu(s))continue;let a=o.directives?.find(c=>c.name.value===ut.name);if(!(a&&gu(a))){for(let c of o.directives??[])c.name.value===Qe.name?Is(c)||t.reportError(new d("Defer directive not supported on subscription operations. Disable `@defer` by setting the `if` argument to `false`.",{nodes:[c,...n]})):c.name.value===Ae.name&&(Is(c)||t.reportError(new d("Stream directive not supported on subscription operations. Disable `@stream` by setting the `if` argument to `false`.",{nodes:[c,...n]})));if(o.kind==="FragmentSpread"){let c=o.name.value;if(i.has(c))continue;i.add(c);let u=e.get(c);u&&zn({context:t,fragments:e,parentNodes:[o,...n],selectionSet:u?.selectionSet,visitedFragments:i})}else o.selectionSet&&zn({context:t,fragments:e,selectionSet:o.selectionSet,parentNodes:n,visitedFragments:i})}}}function ei(t){return t.kind===p.OPERATION_DEFINITION||t.kind===p.FRAGMENT_DEFINITION}function ti(t){return t.kind===p.SCHEMA_DEFINITION||He(t)||t.kind===p.DIRECTIVE_DEFINITION}function He(t){return t.kind===p.SCALAR_TYPE_DEFINITION||t.kind===p.OBJECT_TYPE_DEFINITION||t.kind===p.INTERFACE_TYPE_DEFINITION||t.kind===p.UNION_TYPE_DEFINITION||t.kind===p.ENUM_TYPE_DEFINITION||t.kind===p.INPUT_OBJECT_TYPE_DEFINITION}function ri(t){return t.kind===p.SCHEMA_EXTENSION||t.kind===p.DIRECTIVE_EXTENSION||Kr(t)}function Kr(t){return t.kind===p.SCALAR_TYPE_EXTENSION||t.kind===p.OBJECT_TYPE_EXTENSION||t.kind===p.INTERFACE_TYPE_EXTENSION||t.kind===p.UNION_TYPE_EXTENSION||t.kind===p.ENUM_TYPE_EXTENSION||t.kind===p.INPUT_OBJECT_TYPE_EXTENSION}function ni(t){return{Document(e){for(let r of e.definitions)if(!ei(r)){let n=r.kind===p.SCHEMA_DEFINITION||r.kind===p.SCHEMA_EXTENSION?"schema":'"'+r.name.value+'"';t.reportError(new d(`The ${n} definition is not executable.`,{nodes:r}))}return!1}}}function ii(t){return{Field(e){let r=t.getParentType();if(r&&!t.getFieldDef()){let i=t.getSchema(),o=e.name.value,s=ie("to use an inline fragment on",t.hideSuggestions?[]:Eu(i,r,o));s===""&&(s=ie(t.hideSuggestions?[]:Iu(r,o))),t.reportError(new d(`Cannot query field "${o}" on type "${r}".`+s,{nodes:e}))}}}}function Eu(t,e,r){if(!ce(e))return[];let n=new Set,i=Object.create(null);for(let o of t.getPossibleTypes(e))if(o.getFields()[r]!=null){n.add(o),i[o.name]=1;for(let s of o.getInterfaces())s.getFields()[r]!=null&&(n.add(s),i[s.name]=(i[s.name]??0)+1)}return[...n].sort((o,s)=>{let a=i[s.name]-i[o.name];return a!==0?a:P(o)&&t.isSubType(o,s)?-1:P(s)&&t.isSubType(s,o)?1:Rt(o.name,s.name)}).map(o=>o.name)}function Iu(t,e){if(k(t)||P(t)){let r=Object.keys(t.getFields());return se(e,r)}return[]}function oi(t){return{InlineFragment(e){let r=e.typeCondition;if(r){let n=j(t.getSchema(),r);if(n&&!Ie(n)){let i=V(r);t.reportError(new d(`Fragment cannot condition on non composite type "${i}".`,{nodes:r}))}}},FragmentDefinition(e){let r=j(t.getSchema(),e.typeCondition);if(r&&!Ie(r)){let n=V(e.typeCondition);t.reportError(new d(`Fragment "${e.name.value}" cannot condition on non composite type "${n}".`,{nodes:e.typeCondition}))}}}}function si(t){return{...ai(t),FragmentArgument(e){let r=t.getFragmentSignature();if(r&&!r.variableDefinitions.get(e.name.value)){let i=e.name.value,o=t.hideSuggestions?[]:se(i,Array.from(r.variableDefinitions.values()).map(s=>s.variable.name.value));t.reportError(new d(`Unknown argument "${i}" on fragment "${r.definition.name.value}".`+ie(o),{nodes:e}))}},Argument(e){let r=t.getArgument(),n=t.getFieldDef();if(!r&&n){let i=e.name.value,o=t.hideSuggestions?[]:se(i,n.args.map(s=>s.name));t.reportError(new d(`Unknown argument "${i}" on field "${n}".`+ie(o),{nodes:e}))}}}}function ai(t){let e=new Map,r=t.getSchema(),n=r?r.getDirectives():Fe;for(let o of n)e.set(o.name,o.args.map(s=>s.name));let i=t.getDocument().definitions;for(let o of i)if(o.kind===p.DIRECTIVE_DEFINITION){let s=o.arguments??[];e.set(o.name.value,s.map(a=>a.name.value))}return{Directive(o){let s=o.name.value,a=e.get(s);if(o.arguments!=null&&a!=null)for(let c of o.arguments){let u=c.name.value;if(!a.includes(u)){let l=se(u,a);t.reportError(new d(`Unknown argument "${u}" on directive "@${s}".`+(t.hideSuggestions?"":ie(l)),{nodes:c}))}}return!1}}}function Yr(t){let e=new Map,r=t.getSchema(),n=r?r.getDirectives():Fe;for(let o of n)e.set(o.name,o.locations);let i=t.getDocument().definitions;for(let o of i)o.kind===p.DIRECTIVE_DEFINITION&&e.set(o.name.value,o.locations.map(s=>s.value));return{Directive(o,s,a,c,u){let l=o.name.value,f=e.get(l);if(f==null){t.reportError(new d(`Unknown directive "@${l}".`,{nodes:o}));return}let m=Nu(u);m!=null&&!f.includes(m)&&t.reportError(new d(`Directive "@${l}" may not be used on ${m}.`,{nodes:o}))}}}function Nu(t){let e=t.at(-1);switch(e!=null&&"kind"in e||L(!1),e.kind){case p.OPERATION_DEFINITION:return bu(e.operation);case p.FIELD:return v.FIELD;case p.FRAGMENT_SPREAD:return v.FRAGMENT_SPREAD;case p.INLINE_FRAGMENT:return v.INLINE_FRAGMENT;case p.FRAGMENT_DEFINITION:return v.FRAGMENT_DEFINITION;case p.VARIABLE_DEFINITION:{let r=t[t.length-3];return"kind"in r||L(!1),r.kind===p.OPERATION_DEFINITION?v.VARIABLE_DEFINITION:v.FRAGMENT_VARIABLE_DEFINITION}case p.SCHEMA_DEFINITION:case p.SCHEMA_EXTENSION:return v.SCHEMA;case p.SCALAR_TYPE_DEFINITION:case p.SCALAR_TYPE_EXTENSION:return v.SCALAR;case p.OBJECT_TYPE_DEFINITION:case p.OBJECT_TYPE_EXTENSION:return v.OBJECT;case p.FIELD_DEFINITION:return v.FIELD_DEFINITION;case p.INTERFACE_TYPE_DEFINITION:case p.INTERFACE_TYPE_EXTENSION:return v.INTERFACE;case p.UNION_TYPE_DEFINITION:case p.UNION_TYPE_EXTENSION:return v.UNION;case p.ENUM_TYPE_DEFINITION:case p.ENUM_TYPE_EXTENSION:return v.ENUM;case p.ENUM_VALUE_DEFINITION:return v.ENUM_VALUE;case p.INPUT_OBJECT_TYPE_DEFINITION:case p.INPUT_OBJECT_TYPE_EXTENSION:return v.INPUT_OBJECT;case p.INPUT_VALUE_DEFINITION:{let r=t.at(-3);return r!=null&&"kind"in r||L(!1),r.kind===p.INPUT_OBJECT_TYPE_DEFINITION||r.kind===p.INPUT_OBJECT_TYPE_EXTENSION?v.INPUT_FIELD_DEFINITION:v.ARGUMENT_DEFINITION}case p.DIRECTIVE_DEFINITION:case p.DIRECTIVE_EXTENSION:return v.DIRECTIVE_DEFINITION;default:L(!1,"Unexpected kind: "+E(e.kind))}}function bu(t){switch(t){case G.QUERY:return v.QUERY;case G.MUTATION:return v.MUTATION;case G.SUBSCRIPTION:return v.SUBSCRIPTION}}function ci(t){return{FragmentSpread(e){let r=e.name.value;t.getFragment(r)||t.reportError(new d(`Unknown fragment "${r}".`,{nodes:e.name}))}}}function ui(t){let e=t.getSchema();return{OperationDefinition(r){let n=r.operation;e.getRootType(n)||t.reportError(new d(`The ${n} operation is not supported by the schema.`,{nodes:r}))}}}function Hr(t){let{definitions:e}=t.getDocument(),r=t.getSchema()?.getTypeMap()??{},n=new Set([...Object.keys(r),...e.filter(He).map(i=>i.name.value)]);return{NamedType(i,o,s,a,c){let u=i.name.value;if(!n.has(u)){let l=c[2]??s,f=l!=null&&vu(l);if(f&&Ns.has(u))return;let m=t.hideSuggestions?[]:se(u,f?[...Ns,...n]:[...n]);t.reportError(new d(`Unknown type "${u}".`+ie(m),{nodes:i}))}}}}var Ns=new Set([...Fr,...Vr].map(t=>t.name));function vu(t){return"kind"in t&&(ti(t)||ri(t))}function pi(t){let e=0;return{Document(r){e=r.definitions.filter(n=>n.kind===p.OPERATION_DEFINITION).length},OperationDefinition(r){!r.name&&e>1&&t.reportError(new d("This anonymous operation must be the only defined operation.",{nodes:r}))}}}function li(t){let e=t.getSchema(),r=e?.astNode??e?.getQueryType()??e?.getMutationType()??e?.getSubscriptionType(),n=0;return{SchemaDefinition(i){if(r){t.reportError(new d("Cannot define a new schema within a schema extension.",{nodes:i}));return}n>0&&t.reportError(new d("Must provide only one schema definition.",{nodes:i})),++n}}}var Ru=3;function fi(t){function e(r,n=Object.create(null),i=0){if(r.kind===p.FRAGMENT_SPREAD){let o=r.name.value;if(n[o]===!0)return!1;let s=t.getFragment(o);if(!s)return!1;try{return n[o]=!0,e(s,n,i)}finally{n[o]=void 0}}if(r.kind===p.FIELD&&(r.name.value==="fields"||r.name.value==="interfaces"||r.name.value==="possibleTypes"||r.name.value==="inputFields")&&(i++,i>=Ru))return!0;if("selectionSet"in r&&r.selectionSet){for(let o of r.selectionSet.selections)if(e(o,n,i))return!0}return!1}return{Field(r){if((r.name.value==="__schema"||r.name.value==="__type")&&e(r))return t.reportError(new d("Maximum introspection depth exceeded",{nodes:[r]})),!1}}}function di(t){let e=new Set,r=[],n=Object.create(null);return{OperationDefinition:()=>!1,FragmentDefinition(o){return i(o),!1}};function i(o){if(e.has(o.name.value))return;let s=o.name.value;e.add(s);let a=t.getFragmentSpreads(o.selectionSet);if(a.length!==0){n[s]=r.length;for(let c of a){let u=c.name.value,l=n[u];if(r.push(c),l===void 0){let f=t.getFragment(u);f&&i(f)}else{let f=r.slice(l),m=f.slice(0,-1).map(g=>'"'+g.name.value+'"').join(", ");t.reportError(new d(`Cannot spread fragment "${u}" within itself`+(m!==""?` via ${m}.`:"."),{nodes:f}))}r.pop()}n[s]=void 0}}}function mi(t){return{OperationDefinition(e){let r=new Set(e.variableDefinitions?.map(i=>i.variable.name.value)),n=t.getRecursiveVariableUsages(e);for(let{node:i,fragmentVariableDefinition:o}of n){if(o)continue;let s=i.name.value;r.has(s)||t.reportError(new d(e.name?`Variable "$${s}" is not defined by operation "${e.name.value}".`:`Variable "$${s}" is not defined.`,{nodes:[i,e]}))}}}}function hi(t){let e=new Set,r=[];return{OperationDefinition(n){for(let i of t.getRecursivelyReferencedFragments(n))e.add(i.name.value);return!1},FragmentDefinition(n){return r.push(n),!1},Document:{leave(){for(let n of r){let i=n.name.value;e.has(i)||t.reportError(new d(`Fragment "${i}" is never used.`,{nodes:n}))}}}}}function yi(t){return{FragmentDefinition(e){let r=t.getVariableUsages(e),n=new Set(r.map(({node:o})=>o.name.value)),i=e.variableDefinitions??[];for(let o of i){let s=o.variable.name.value;n.has(s)||t.reportError(new d(`Variable "$${s}" is never used in fragment "${e.name.value}".`,{nodes:o}))}},OperationDefinition(e){let r=t.getRecursiveVariableUsages(e),n=new Set;for(let{node:o,fragmentVariableDefinition:s}of r){let a=o.name.value;s||n.add(a)}let i=e.variableDefinitions??[];for(let o of i){let s=o.variable.name.value;n.has(s)||t.reportError(new d(e.name?`Variable "$${s}" is never used in operation "${e.name.value}".`:`Variable "$${s}" is never used.`,{nodes:o}))}}}}function sr(t){switch(t.kind){case p.OBJECT:return{...t,fields:Su(t.fields)};case p.LIST:return{...t,values:t.values.map(sr)};case p.INT:case p.FLOAT:case p.STRING:case p.BOOLEAN:case p.NULL:case p.ENUM:case p.VARIABLE:return t}}function Su(t){return t.map(e=>({...e,value:sr(e.value)})).sort((e,r)=>Rt(e.name.value,r.name.value))}function Rs(t){return Array.isArray(t)?t.map(([e,r])=>`subfields "${e}" conflict because `+Rs(r)).join(" and "):t}function Ii(t){let e=new zr,r=new Ei,n=new Map;return{SelectionSet(i){let o=xu(t,n,e,r,t.getParentType(),i);for(let[[s,a],c,u]of o){let l=Rs(a);t.reportError(new d(`Fields "${s}" conflict because ${l}. Use different aliases on the fields to fetch both if this was intentional.`,{nodes:c.concat(u)}))}}}}function xu(t,e,r,n,i,o){let s=[],[a,c]=Xr(t,e,i,o,void 0);if(wu(t,s,e,r,n,a),c.length!==0)for(let u=0;u<c.length;u++){Wr(t,s,e,r,n,!1,a,c[u]);for(let l=u+1;l<c.length;l++)Jr(t,s,e,r,n,!1,c[u],c[l])}return s}function Wr(t,e,r,n,i,o,s,a){if(n.has(s,a.key,o))return;n.add(s,a.key,o);let c=t.getFragment(a.node.name.value);if(!c)return;let[u,l]=gi(t,r,c,a.varMap);if(s!==u){Ni(t,e,r,n,i,o,s,void 0,u,a.varMap);for(let f of l)Wr(t,e,r,n,i,o,s,f)}}function Jr(t,e,r,n,i,o,s,a){if(s.key===a.key)return;if(s.node.name.value===a.node.name.value&&!bi(s.node.arguments,s.varMap,a.node.arguments,a.varMap)){t.reportError(new d(`Spreads "${s.node.name.value}" conflict because ${s.key} and ${a.key} have different fragment arguments.`,{nodes:[s.node,a.node]}));return}if(i.has(s.key,a.key,o))return;i.add(s.key,a.key,o);let c=t.getFragment(s.node.name.value),u=t.getFragment(a.node.name.value);if(!c||!u)return;let[l,f]=gi(t,r,c,s.varMap),[m,g]=gi(t,r,u,a.varMap);Ni(t,e,r,n,i,o,l,s.varMap,m,a.varMap);for(let y of g)Jr(t,e,r,n,i,o,s,y);for(let y of f)Jr(t,e,r,n,i,o,y,a)}function Ou(t,e,r,n,i,o,s,a,c,u,l){let f=[],[m,g]=Xr(t,e,o,s,a),[y,x]=Xr(t,e,c,u,l);Ni(t,f,e,r,n,i,m,a,y,l);for(let S of x)Wr(t,f,e,r,n,i,m,S);for(let S of g)Wr(t,f,e,r,n,i,y,S);for(let S of g)for(let A of x)Jr(t,f,e,r,n,i,S,A);return f}function wu(t,e,r,n,i,o){for(let[s,a]of o.entries())if(a.length>1)for(let c=0;c<a.length;c++)for(let u=c+1;u<a.length;u++){let l=Ss(t,r,n,i,!1,s,a[c],void 0,a[u],void 0);l&&e.push(l)}}function Ni(t,e,r,n,i,o,s,a,c,u){for(let[l,f]of s.entries()){let m=c.get(l);if(m!=null)for(let g of f)for(let y of m){let x=Ss(t,r,n,i,o,l,g,a,y,u);x&&e.push(x)}}}function Ss(t,e,r,n,i,o,s,a,c,u){let[l,f,m]=s,[g,y,x]=c,S=i||l!==g&&k(l)&&k(g);if(!S){let It=f.name.value,oe=y.name.value;if(It!==oe)return[[o,`"${It}" and "${oe}" are different fields`],[f],[y]];if(!bi(f.arguments,a,y.arguments,u))return[[o,"they have differing arguments"],[f],[y]]}let A=f.directives,W=y.directives,K=_u(A,a,W,u);if(K!==void 0)return[[o,K],[f],[y]];let Y=m?.type,pe=x?.type;if(Y&&pe&&Ti(Y,pe))return[[o,`they return conflicting types "${E(Y)}" and "${E(pe)}"`],[f],[y]];let Ve=f.selectionSet,Ue=y.selectionSet;if(Ve&&Ue){let It=Ou(t,e,r,n,S,te(Y),Ve,a,te(pe),Ue,u);return Lu(It,o,f,y)}}function bi(t,e,r,n){if(t===void 0||t.length===0)return r===void 0||r.length===0;if(r===void 0||r.length===0||t.length!==r.length)return!1;let i=new Map(r.map(({name:o,value:s})=>[o.value,n===void 0?s:ar(s,n)]));return t.every(o=>{let s=o.value;e&&(s=ar(s,e));let a=i.get(o.name.value);return a===void 0?!1:bs(s)===bs(a)})}function ar(t,e){switch(t.kind){case p.VARIABLE:return e.get(t.name.value)??t;case p.LIST:return{...t,values:t.values.map(r=>ar(r,e))};case p.OBJECT:return{...t,fields:t.fields.map(r=>({...r,value:ar(r.value,e)}))};default:return t}}function bs(t){return V(sr(t))}function vs(t){return t?.find(e=>e.name.value==="stream")}function _u(t,e,r,n){let i=vs(t),o=vs(r);if(!(!i&&!o))return i&&o&&bi(i.arguments,e,o.arguments,n)?"they have overlapping stream directives. See https://github.com/graphql/defer-stream-wg/discussions/100":"they have overlapping stream directives"}function Ti(t,e){return C(t)?C(e)?Ti(t.ofType,e.ofType):!0:C(e)?!0:_(t)?_(e)?Ti(t.ofType,e.ofType):!0:_(e)?!0:ge(t)||ge(e)?t!==e:!1}function Xr(t,e,r,n,i){let o=e.get(n);if(o)return o;let s=new Map,a=new Map;xs(t,r,n,s,a,i);let c=[s,Array.from(a.values())];return e.set(n,c),c}function gi(t,e,r,n){let i=e.get(r.selectionSet);if(i)return i;let o=j(t.getSchema(),r.typeCondition);return Xr(t,e,o,r.selectionSet,n)}function xs(t,e,r,n,i,o){for(let s of r.selections)switch(s.kind){case p.FIELD:{let a=s.name.value,c;(k(e)||P(e))&&(c=e.getFields()[a]);let u=s.alias?s.alias.value:a,l=n.get(u);l==null&&(l=[],n.set(u,l)),l.push([e,s,c]);break}case p.FRAGMENT_SPREAD:{let a=Du(t,s,o);i.set(a.key,a);break}case p.INLINE_FRAGMENT:{let a=s.typeCondition,c=a?j(t.getSchema(),a):e;xs(t,c,s.selectionSet,n,i,o);break}}}function Du(t,e,r){let n="",i=new Map,o=t.getFragmentSignatureByName()(e.name.value),s=new Map;if(e.arguments)for(let a of e.arguments)s.set(a.name.value,a.value);if(o?.variableDefinitions){n+=e.name.value+"(";for(let[a,c]of o.variableDefinitions){let u=s.get(a);u&&(n+=a+": "+V(sr(u)));let l=s.get(a);l!==void 0?i.set(a,r!==void 0?ar(l,r):l):c.defaultValue&&i.set(a,c.defaultValue)}n+=")"}return{key:n,node:e,varMap:i.size>0?i:void 0}}function Lu(t,e,r,n){if(t.length>0)return[[e,t.map(([i])=>i)],[r,...t.map(([,i])=>i).flat()],[n,...t.map(([,,i])=>i).flat()]]}var zr=class{constructor(){this._data=new Map}has(e,r,n){let i=this._data.get(e)?.get(r);return i===void 0?!1:n?!0:n===i}add(e,r,n){let i=this._data.get(e);i===void 0?this._data.set(e,new Map([[r,n]])):i.set(r,n)}},Ei=class{constructor(){this._orderedPairSet=new zr}has(e,r,n){return e<r?this._orderedPairSet.has(e,r,n):this._orderedPairSet.has(r,e,n)}add(e,r,n){e<r?this._orderedPairSet.add(e,r,n):this._orderedPairSet.add(r,e,n)}};function vi(t){return{InlineFragment(e){let r=t.getType(),n=t.getParentType();if(Ie(r)&&Ie(n)&&!Ln(t.getSchema(),r,n)){let i=E(n),o=E(r);t.reportError(new d(`Fragment cannot be spread here as objects of type "${i}" can never be of type "${o}".`,{nodes:e}))}},FragmentSpread(e){let r=e.name.value,n=Au(t,r),i=t.getParentType();if(n&&i&&!Ln(t.getSchema(),n,i)){let o=E(i),s=E(n);t.reportError(new d(`Fragment "${r}" cannot be spread here as objects of type "${o}" can never be of type "${s}".`,{nodes:e}))}}}}function Au(t,e){let r=t.getFragment(e);if(r){let n=j(t.getSchema(),r.typeCondition);if(Ie(n))return n}}function Ri(t){let e=t.getSchema(),r=new Map;for(let i of t.getDocument().definitions)He(i)&&r.set(i.name.value,i);return{ScalarTypeExtension:n,ObjectTypeExtension:n,InterfaceTypeExtension:n,UnionTypeExtension:n,EnumTypeExtension:n,InputObjectTypeExtension:n};function n(i){let o=i.name.value,s=r.get(o),a=e?.getType(o),c;if(s!=null?c=Fu[s.kind]:a&&(c=Cu(a)),c!=null){if(c!==i.kind){let u=ku(i.kind);t.reportError(new d(`Cannot extend non-${u} type "${o}".`,{nodes:s?[s,i]:i}))}}else{let u=[...r.keys(),...Object.keys(e?.getTypeMap()??{})];t.reportError(new d(`Cannot extend type "${o}" because it is not defined.`+ie(se(o,u)),{nodes:i.name}))}}}var Fu={[p.SCALAR_TYPE_DEFINITION]:p.SCALAR_TYPE_EXTENSION,[p.OBJECT_TYPE_DEFINITION]:p.OBJECT_TYPE_EXTENSION,[p.INTERFACE_TYPE_DEFINITION]:p.INTERFACE_TYPE_EXTENSION,[p.UNION_TYPE_DEFINITION]:p.UNION_TYPE_EXTENSION,[p.ENUM_TYPE_DEFINITION]:p.ENUM_TYPE_EXTENSION,[p.INPUT_OBJECT_TYPE_DEFINITION]:p.INPUT_OBJECT_TYPE_EXTENSION};function Cu(t){if(De(t))return p.SCALAR_TYPE_EXTENSION;if(k(t))return p.OBJECT_TYPE_EXTENSION;if(P(t))return p.INTERFACE_TYPE_EXTENSION;if(ee(t))return p.UNION_TYPE_EXTENSION;if(J(t))return p.ENUM_TYPE_EXTENSION;if(F(t))return p.INPUT_OBJECT_TYPE_EXTENSION;L(!1,"Unexpected type: "+E(t))}function ku(t){switch(t){case p.SCALAR_TYPE_EXTENSION:return"scalar";case p.OBJECT_TYPE_EXTENSION:return"object";case p.INTERFACE_TYPE_EXTENSION:return"interface";case p.UNION_TYPE_EXTENSION:return"union";case p.ENUM_TYPE_EXTENSION:return"enum";case p.INPUT_OBJECT_TYPE_EXTENSION:return"input object";default:L(!1,"Unexpected kind: "+E(t))}}function Si(t){return{...xi(t),Field:{leave(e){let r=t.getFieldDef();if(!r)return!1;let n=new Set(e.arguments?.map(i=>i.name.value));for(let i of r.args)!n.has(i.name)&&Ne(i)&&t.reportError(new d(`Argument "${i}" of type "${i.type}" is required, but it was not provided.`,{nodes:e}))}},FragmentSpread:{leave(e){let r=t.getFragmentSignature();if(!r)return!1;let n=new Set(e.arguments?.map(i=>i.name.value));for(let[i,o]of r.variableDefinitions)if(!n.has(i)&&Os(o)){let s=j(t.getSchema(),o.type),a=E(s);t.reportError(new d(`Fragment "${e.name.value}" argument "${i}" of type "${a}" is required, but it was not provided.`,{nodes:e}))}}}}}function xi(t){let e=new Map,n=t.getSchema()?.getDirectives()??Fe;for(let o of n)e.set(o.name,new Map(o.args.filter(Ne).map(s=>[s.name,s])));let i=t.getDocument().definitions;for(let o of i)if(o.kind===p.DIRECTIVE_DEFINITION){let s=o.arguments??[];e.set(o.name.value,new Map(s.filter(Os).map(a=>[a.name.value,a])))}return{Directive:{leave(o){let s=o.name.value,a=e.get(s);if(a!=null){let c=o.arguments??[],u=new Set(c.map(l=>l.name.value));for(let[l,f]of a.entries())if(!u.has(l)){let m=Yt(f.type)?E(f.type):V(f.type);t.reportError(new d(`Argument "@${s}(${l}:)" of type "${m}" is required, but it was not provided.`,{nodes:o}))}}}}}}function Os(t){return t.type.kind===p.NON_NULL_TYPE&&t.defaultValue==null}function Oi(t){return{Field(e){let r=t.getType(),n=e.selectionSet;if(r)if(ge(te(r))){if(n){let i=e.name.value,o=E(r);t.reportError(new d(`Field "${i}" must not have a selection since type "${o}" has no subfields.`,{nodes:n}))}}else if(n){if(n.selections.length===0){let i=e.name.value,o=E(r);t.reportError(new d(`Field "${i}" of type "${o}" must have at least one field selected.`,{nodes:e}))}}else{let i=e.name.value,o=E(r);t.reportError(new d(`Field "${i}" of type "${o}" must have a selection of subfields. Did you mean "${i} { ... }"?`,{nodes:e}))}}}}function yt(t,e){if(_(e))return t==null?void 0:yt(t,e.ofType);if(t==null)return null;if(C(e)){if(!le(t)){let i=yt(t,e.ofType);return i===void 0?void 0:[i]}let n=[];for(let i of t){let o=yt(i,e.ofType);if(o===void 0)return;n.push(o)}return n}if(F(e)){if(!H(t)||Array.isArray(t))return;let n=Object.create(null),i=e.getFields(),o=0;for(let s of Object.keys(t))if(t[s]!==void 0&&(o++,!Object.hasOwn(i,s)))return;for(let s of Object.values(i)){let a=t[s.name];if(a===void 0){if(me(s))return;let c=Zr(s);c!==void 0&&(n[s.name]=c)}else{let c=yt(a,s.type);if(c===void 0)return;n[s.name]=c}}if(e.isOneOf){let s=Object.keys(n);if(o!==1||s.length!==1)return;let a=s[0];if(n[a]===null)return}return n}let r=Ee(e);try{return r.coerceInputValue(t)}catch{}}function Tt(t,e,r,n){if(t.kind===p.VARIABLE){let o=ws(t,r,n);return o==null&&_(e)?void 0:o}if(_(e))return t.kind===p.NULL?void 0:Tt(t,e.ofType,r,n);if(t.kind===p.NULL)return null;if(C(e)){if(t.kind!==p.LIST){let s=Tt(t,e.ofType,r,n);return s===void 0?void 0:[s]}let o=[];for(let s of t.values){let a=Tt(s,e.ofType,r,n);if(a===void 0)if(s.kind===p.VARIABLE&&ws(s,r,n)==null&&!_(e.ofType))a=null;else return;o.push(a)}return o}if(F(e)){if(t.kind!==p.OBJECT)return;let o=Object.create(null),s=e.getFields();if(t.fields.some(u=>!Object.hasOwn(s,u.name.value)))return;let c=new Map(t.fields.map(u=>[u.name.value,u]));for(let u of Object.values(s)){let l=c.get(u.name);if(!l||l.value.kind===p.VARIABLE&&Pu(l.value,r,n)){if(me(u))return;let f=Zr(u);f!==void 0&&(o[u.name]=f)}else{let f=Tt(l.value,u.type,r,n);if(f===void 0)return;o[u.name]=f}}if(e.isOneOf){let u=Object.keys(o);if(c.size!==1||u.length!==1)return;for(let[l,f]of c)if(f.value.kind===p.NULL||o[l]===null)return}return o}let i=Ee(e);try{return i.coerceInputLiteral?i.coerceInputLiteral(st(t,r,n)):i.parseLiteral(t,r?.coerced)}catch{}}function ws(t,e,r){let n=t.name.value;return r?.sources[n]!==void 0?r.coerced[n]:e?.coerced[n]}function Pu(t,e,r){let n=t.name.value;return(r?.sources[n]!==void 0?r.coerced:e?.coerced)?.[n]===void 0}function Zr(t){let e=t._memoizedCoercedDefaultValue;if(e!==void 0)return e;let r=t.default;if(r!==void 0)return e=r.literal?Tt(r.literal,t.type):yt(r.value,t.type),e===void 0&&L(!1,`Expected value of type "${t.type}" to be valid, found: ${E(r.literal??r.value)}.`),t._memoizedCoercedDefaultValue=e,e;let n=t.defaultValue;return n!==void 0&&(t._memoizedCoercedDefaultValue=n),n}function en(t,e){let r=e.variable.name.value,n=j(t,e.type);if(!Z(n)){let o=V(e.type);return new d(`Variable "$${r}" expected value of type "${o}" which cannot be used as an input type.`,{nodes:e.type})}let i=e.defaultValue;return{name:r,type:n,default:i&&{literal:i}}}function tn(t,e,r,n){let i=[],o=n?.maxErrors;try{let s=Mu(t,e,r,a=>{if(o!=null&&i.length>=o)throw new d("Too many errors processing variables, error limit reached. Execution aborted.");i.push(a)},n?.hideSuggestions);if(i.length===0)return{variableValues:s}}catch(s){i.push($e(s))}return{errors:i}}function Mu(t,e,r,n,i){let o=Object.create(null),s=Object.create(null);for(let a of e){let c=en(t,a);if(c instanceof d){n(c);continue}let{name:u,type:l}=c,f=Object.hasOwn(r,u)?r[u]:void 0;if(f===void 0){if(o[u]={signature:c},a.defaultValue){_i(s,u,c,(g,y)=>{n(new d(`Variable "$${u}" has invalid default value${ze(y)}: ${g.message}`,{nodes:a}))},i);continue}else if(!_(l))continue}else o[u]={signature:c,value:f};let m=yt(f,l);m!==void 0?s[u]=m:Xt(f,l,(g,y)=>{n(new d(`Variable "$${u}" has invalid value${ze(y)}: ${g.message}`,{nodes:a,originalError:g}))},i)}return{sources:o,coerced:s}}function _i(t,e,r,n,i){try{let o=Zr(r);o!==void 0&&(t[e]=o)}catch(o){let s=r.default;if(s===void 0)throw o;let a=!1;Qn(s,r.type,(c,u)=>{a=!0,n(c,u)},i),a||n($e(o),[])}}function _s(t,e,r,n,i){let o=t.arguments??[],s=new Map(o.map(u=>[u.name.value,u])),a=Object.create(null),c=Object.create(null);for(let[u,l]of Object.entries(e)){let f=s.get(u);f!==void 0?a[u]=n==null?{signature:l,value:f.value}:{signature:l,value:f.value,fragmentVariableValues:n}:a[u]={signature:l},Ds(c,t,u,l,f,r,n,i)}return{sources:a,coerced:c}}function We(t,e,r,n,i){let o=Object.create(null),s=e.arguments??[],a=new Map(s.map(c=>[c.name.value,c]));for(let c of t.args){let u=c.name;Ds(o,e,u,c,a.get(c.name),r,n,i)}return o}function Ds(t,e,r,n,i,o,s,a){let c=n.type,u=(m,g)=>{throw new d(`${wi(n,e)} has invalid default value${ze(g)}: ${m.message}`,{nodes:e})};if(!i){if(Ne(n))throw new d(`${wi(n,e)} of required type "${c}" was not provided.`,{nodes:e});_i(t,r,n,u,a);return}let l=i.value;if(l.kind===p.VARIABLE){let m=l.name.value,g=s?.sources[m]?s:o;if((g==null||!Object.hasOwn(g.coerced,m))&&!Ne(n)){_i(t,r,n,u,a);return}}let f=Tt(l,c,o,s);f===void 0&&(wt(l,c,(m,g)=>{throw m.message=`${wi(n,e)} has invalid value${ze(g)}: ${m.message}`,m},o,s,a),L(!1,"Invalid argument")),t[r]=f}function wi(t,e){return xr(t)?`Argument "${t}"`:`Variable "$${t.name}" defined by fragment "${e.name.value}"`}function cr(t,e,r,n,i){let o=e.directives?.find(s=>s.name.value===t.name);if(o)return We(t,o,r,n,i)}function rn(t,e,r,n,i,o,s=!1){let a=new Ge,c=[],u={schema:t,fragments:e,variableValues:r,runtimeType:n,visitedFragmentNames:new Map,hideSuggestions:o,forbiddenDirectiveInstances:[],forbidSkipAndInclude:s};return ur(u,i,a,c),{groupedFieldSet:a,newDeferUsages:c,forbiddenDirectiveInstances:u.forbiddenDirectiveInstances}}function Fs(t,e,r,n,i,o){let s={schema:t,fragments:e,variableValues:r,runtimeType:n,visitedFragmentNames:new Map,hideSuggestions:o,forbiddenDirectiveInstances:[],forbidSkipAndInclude:!1},a=new Ge,c=[];for(let u of i){let l=u.node.selectionSet;if(l){let{deferUsage:f,fragmentVariableValues:m}=u;ur(s,l,a,c,f,m)}}return{groupedFieldSet:a,newDeferUsages:c}}function ur(t,e,r,n,i,o){let{schema:s,fragments:a,variableValues:c,runtimeType:u,visitedFragmentNames:l,hideSuggestions:f}=t;for(let m of e.selections)switch(m.kind){case p.FIELD:{if(!Di(t,m,c,o))continue;r.add(Vu(m),{node:m,deferUsage:i,fragmentVariableValues:o});break}case p.INLINE_FRAGMENT:{if(!Di(t,m,c,o)||!As(s,m,u))continue;let g=Ls(c,o,m,i);g?(n.push(g),ur(t,m.selectionSet,r,n,g,o)):ur(t,m.selectionSet,r,n,i,o);break}case p.FRAGMENT_SPREAD:{let g=m.name.value;if(!Di(t,m,c,o))continue;let y=a[g];if(y==null||!As(s,y.definition,u))continue;let x=Ls(c,o,m,i),S=l.get(g),A;if(x){if(S!==void 0)continue;l.set(g,!0),n.push(x),A=x}else{if(S===!1)continue;l.set(g,!1),A=i}let W=y.variableSignatures,K;W&&(K=_s(m,W,c,o,f)),ur(t,y.definition.selectionSet,r,n,A,K);break}}}function Ls(t,e,r,n){let i=cr(Qe,r,t,e);if(i&&i.if!==!1)return{label:typeof i.label=="string"?i.label:void 0,parentDeferUsage:n}}function Di(t,e,r,n){let i=e.directives?.find(c=>c.name.value===pt.name);if(i&&t.forbidSkipAndInclude)return t.forbiddenDirectiveInstances.push(i),!1;if((i?We(pt,i,r,n,t.hideSuggestions):void 0)?.if===!0)return!1;let s=e.directives?.find(c=>c.name.value===ut.name);return s&&t.forbidSkipAndInclude?(t.forbiddenDirectiveInstances.push(s),!1):(s?We(ut,s,r,n,t.hideSuggestions):void 0)?.if!==!1}function As(t,e,r){let n=e.typeCondition;if(!n)return!0;let i=j(t,n);return i===r?!0:ce(i)?t.isSubType(i,r):!1}function Vu(t){return t.alias?t.alias.value:t.name.value}function Li(t){return t.map(e=>e.node)}function Ai(t){return{OperationDefinition(e){if(e.operation==="subscription"){let r=t.getSchema(),n=r.getSubscriptionType();if(n){let i=e.name?e.name.value:null,o=Object.create(null),s=t.getDocument(),a=Object.create(null);for(let l of s.definitions)l.kind===p.FRAGMENT_DEFINITION&&(a[l.name.value]={definition:l});let{groupedFieldSet:c,forbiddenDirectiveInstances:u}=rn(r,a,o,n,e.selectionSet,t.hideSuggestions,!0);if(u.length>0){t.reportError(new d(i!=null?`Subscription "${i}" must not use \`@skip\` or \`@include\` directives in the top level selection.`:"Anonymous Subscription must not use `@skip` or `@include` directives in the top level selection.",{nodes:u}));return}if(c.size>1){let m=[...c.values()].slice(1).flatMap(g=>Li(g));t.reportError(new d(i!=null?`Subscription "${i}" must select only one top level field.`:"Anonymous Subscription must select only one top level field.",{nodes:m}))}for(let l of c.values())Li(l)[0].name.value.startsWith("__")&&t.reportError(new d(i!=null?`Subscription "${i}" must not select an introspection top level field.`:"Anonymous Subscription must not select an introspection top level field.",{nodes:Li(l)}))}}}}}function Fi(t){return{Directive(e){let r=t.getFieldDef(),n=t.getParentType();r&&n&&e.name.value===Ae.name&&!(C(r.type)||it(r.type)&&C(r.type.ofType))&&t.reportError(new d(`Directive "@stream" cannot be used on non-list field "${n}.${r.name}".`,{nodes:e}))}}}function kt(t,e){let r=new Ge;for(let n of t)r.add(e(n),n);return r}function Ci(t){return{DirectiveDefinition(n){let i=n.arguments??[];return r(`@${n.name.value}`,i)},InterfaceTypeDefinition:e,InterfaceTypeExtension:e,ObjectTypeDefinition:e,ObjectTypeExtension:e};function e(n){let i=n.name.value,o=n.fields??[];for(let s of o){let a=s.name.value,c=s.arguments??[];r(`${i}.${a}`,c)}return!1}function r(n,i){let o=kt(i,s=>s.name.value);for(let[s,a]of o)a.length>1&&t.reportError(new d(`Argument "${n}(${s}:)" can only be defined once.`,{nodes:a.map(c=>c.name)}));return!1}}function nn(t){return{Field:e,Directive:e};function e(r){let n=r.arguments??[],i=kt(n,o=>o.name.value);for(let[o,s]of i)s.length>1&&t.reportError(new d(`There can be only one argument named "${o}".`,{nodes:s.map(a=>a.name)}))}}function ki(t){let e=new Map,r=t.getSchema();return{DirectiveDefinition(n){let i=n.name.value;if(r?.getDirective(i)){t.reportError(new d(`Directive "@${i}" already exists in the schema. It cannot be redefined.`,{nodes:n.name}));return}let o=e.get(i);return o?t.reportError(new d(`There can be only one directive named "@${i}".`,{nodes:[o,n.name]})):e.set(i,n.name),!1}}}function on(t){let e=new Map,r=t.getSchema(),n=r?r.getDirectives():Fe;for(let c of n)e.set(c.name,!c.isRepeatable);let i=t.getDocument().definitions;for(let c of i)c.kind===p.DIRECTIVE_DEFINITION&&e.set(c.name.value,!c.repeatable);let o=new Map,s=new Map,a=new Map;return{enter(c){if(!("directives"in c)||!c.directives)return;let u;if(c.kind===p.SCHEMA_DEFINITION||c.kind===p.SCHEMA_EXTENSION)u=o;else if(He(c)||Kr(c)){let l=c.name.value;u=s.get(l),u===void 0&&(u=new Map,s.set(l,u))}else if(c.kind===p.DIRECTIVE_DEFINITION||c.kind===p.DIRECTIVE_EXTENSION){let l=c.name.value;u=a.get(l),u===void 0&&(u=new Map,a.set(l,u))}else u=new Map;for(let l of c.directives){let f=l.name.value;if(e.get(f)===!0){let m=u.get(f);m!=null?t.reportError(new d(`The directive "@${f}" can only be used once at this location.`,{nodes:[m,l]})):u.set(f,l)}}}}}function Pi(t){let e=t.getSchema(),r=e?e.getTypeMap():Object.create(null),n=new Map;return{EnumTypeDefinition:i,EnumTypeExtension:i};function i(o){let s=o.name.value,a=n.get(s);a==null&&(a=new Map,n.set(s,a));let c=o.values??[];for(let u of c){let l=u.name.value,f=r[s];if(J(f)&&f.getValue(l)){t.reportError(new d(`Enum value "${s}.${l}" already exists in the schema. It cannot also be defined in this type extension.`,{nodes:u.name}));continue}let m=a.get(l);m!=null?t.reportError(new d(`Enum value "${s}.${l}" can only be defined once.`,{nodes:[m,u.name]})):a.set(l,u.name)}return!1}}function Mi(t){let e=t.getSchema(),r=e?e.getTypeMap():Object.create(null),n=new Map;return{InputObjectTypeDefinition:i,InputObjectTypeExtension:i,InterfaceTypeDefinition:i,InterfaceTypeExtension:i,ObjectTypeDefinition:i,ObjectTypeExtension:i};function i(o){let s=o.name.value,a=n.get(s);a==null&&(a=new Map,n.set(s,a));let c=o.fields??[];for(let u of c){let l=u.name.value;if(Uu(r[s],l)){t.reportError(new d(`Field "${s}.${l}" already exists in the schema. It cannot also be defined in this type extension.`,{nodes:u.name}));continue}let f=a.get(l);f!=null?t.reportError(new d(`Field "${s}.${l}" can only be defined once.`,{nodes:[f,u.name]})):a.set(l,u.name)}return!1}}function Uu(t,e){return k(t)||P(t)||F(t)?t.getFields()[e]!=null:!1}function Vi(t){let e=new Map;return{OperationDefinition:()=>!1,FragmentDefinition(r){let n=r.name.value,i=e.get(n);return i!=null?t.reportError(new d(`There can be only one fragment named "${n}".`,{nodes:[i,r.name]})):e.set(n,r.name),!1}}}function sn(t){let e=[],r=new Map;return{ObjectValue:{enter(){e.push(r),r=new Map},leave(){let n=e.pop();n==null&&L(!1),r=n}},ObjectField(n){let i=n.name.value,o=r.get(i);o!=null?t.reportError(new d(`There can be only one input field named "${i}".`,{nodes:[o,n.name]})):r.set(i,n.name)}}}function Ui(t){let e=new Map;return{OperationDefinition(r){let n=r.name;if(n!=null){let i=e.get(n.value);i!=null?t.reportError(new d(`There can be only one operation named "${n.value}".`,{nodes:[i,n]})):e.set(n.value,n)}return!1},FragmentDefinition:()=>!1}}function $i(t){let e=t.getSchema(),r=new Map,n=e?{query:e.getQueryType(),mutation:e.getMutationType(),subscription:e.getSubscriptionType()}:{};return{SchemaDefinition:i,SchemaExtension:i};function i(o){let s=o.operationTypes??[];for(let a of s){let c=a.operation,u=r.get(c);n[c]?t.reportError(new d(`Type for ${c} already defined in the schema. It cannot be redefined.`,{nodes:a})):u?t.reportError(new d(`There can be only one ${c} type in schema.`,{nodes:[u,a]})):r.set(c,a)}return!1}}function Gi(t){let e=new Map,r=t.getSchema();return{ScalarTypeDefinition:n,ObjectTypeDefinition:n,InterfaceTypeDefinition:n,UnionTypeDefinition:n,EnumTypeDefinition:n,InputObjectTypeDefinition:n};function n(i){let o=i.name.value;if(r?.getType(o)){t.reportError(new d(`Type "${o}" already exists in the schema. It cannot also be defined in this type definition.`,{nodes:i.name}));return}let s=e.get(o);return s!=null?t.reportError(new d(`There can be only one type named "${o}".`,{nodes:[s,i.name]})):e.set(o,i.name),!1}}function Bi(t){return{OperationDefinition(e){let r=e.variableDefinitions??[],n=kt(r,i=>i.variable.name.value);for(let[i,o]of n)o.length>1&&t.reportError(new d(`There can be only one variable named "$${i}".`,{nodes:o.map(s=>s.variable.name)}))}}}function Qi(t){return{NullValue:e=>Je(t,e,t.getInputType()),ListValue:e=>Je(t,e,t.getParentInputType()),ObjectValue:e=>Je(t,e,t.getInputType()),EnumValue:e=>Je(t,e,t.getInputType()),IntValue:e=>Je(t,e,t.getInputType()),FloatValue:e=>Je(t,e,t.getInputType()),StringValue:e=>Je(t,e,t.getInputType()),BooleanValue:e=>Je(t,e,t.getInputType())}}function Je(t,e,r){return r&&wt(e,r,n=>{t.reportError(n)},void 0,void 0,t.hideSuggestions),!1}function ji(t){return{VariableDefinition(e){let r=j(t.getSchema(),e.type);if(r!==void 0&&!Z(r)){let n=e.variable.name.value,i=V(e.type);t.reportError(new d(`Variable "$${n}" cannot be non-input type "${i}".`,{nodes:e.type}))}}}}function qi(t){let e;return{OperationDefinition:{enter(){e=new Map},leave(r){let n=t.getRecursiveVariableUsages(r);for(let{node:i,type:o,parentType:s,defaultValue:a,fragmentVariableDefinition:c}of n){let u=i.name.value,l=c;if(l??=e.get(u),l&&o){let f=t.getSchema(),m=j(f,l.type);m&&!$u(f,m,l.defaultValue,o,a)&&t.reportError(new d(`Variable "$${u}" of type "${m}" used in position expecting type "${o}".`,{nodes:[l,i]})),F(s)&&s.isOneOf&&Or(m)&&t.reportError(new d(`Variable "$${u}" is of type "${m}" but must be non-nullable to be used for OneOf Input Object "${s}".`,{nodes:[l,i]}))}}}},VariableDefinition(r){e.set(r.variable.name.value,r)}}}function $u(t,e,r,n,i){if(_(n)&&!_(e)){if(!(r!=null&&r.kind!==p.NULL)&&!(i!==void 0))return!1;let a=n.ofType;return qe(t,e,a)}return qe(t,e,n)}var Ki=Object.freeze([fi]),Pt=Object.freeze([ni,ui,Ui,pi,Ai,Hr,oi,ji,Oi,ii,Vi,ci,hi,vi,di,Bi,mi,yi,Yr,on,Xn,Zn,Wn,Fi,si,nn,Qi,Si,qi,Ii,sn,...Ki]),Gu=Object.freeze([li,$i,Gi,Pi,Mi,Ci,ki,Hr,Yr,on,Ri,ai,nn,sn,xi]);var Yi=class{constructor(e,r){this._ast=e,this._fragments=void 0,this._fragmentSpreads=new Map,this._recursivelyReferencedFragments=new Map,this._onError=r}get[Symbol.toStringTag](){return"ASTValidationContext"}reportError(e){this._onError(e)}getDocument(){return this._ast}getFragment(e){let r;if(this._fragments)r=this._fragments;else{r=Object.create(null);for(let n of this.getDocument().definitions)n.kind===p.FRAGMENT_DEFINITION&&(r[n.name.value]=n);this._fragments=r}return r[e]}getFragmentSpreads(e){let r=this._fragmentSpreads.get(e);if(!r){r=[];let n=[e],i;for(;i=n.pop();)for(let o of i.selections)o.kind===p.FRAGMENT_SPREAD?r.push(o):o.selectionSet&&n.push(o.selectionSet);this._fragmentSpreads.set(e,r)}return r}getRecursivelyReferencedFragments(e){let r=this._recursivelyReferencedFragments.get(e);if(!r){r=[];let n=new Set,i=[e.selectionSet],o;for(;o=i.pop();)for(let s of this.getFragmentSpreads(o)){let a=s.name.value;if(!n.has(a)){n.add(a);let c=this.getFragment(a);c&&(r.push(c),i.push(c.selectionSet))}}this._recursivelyReferencedFragments.set(e,r)}return r}};var pr=class extends Yi{constructor(e,r,n,i,o){super(r,i),this._schema=e,this._typeInfo=n,this._variableUsages=new Map,this._recursiveVariableUsages=new Map,this._hideSuggestions=o??!1}get[Symbol.toStringTag](){return"ValidationContext"}get hideSuggestions(){return this._hideSuggestions}getSchema(){return this._schema}getVariableUsages(e){let r=this._variableUsages.get(e);if(!r){let n=[],i=new Ct(this._schema,void 0,this._typeInfo.getFragmentSignatureByName()),o=e.kind===p.FRAGMENT_DEFINITION?e:void 0;tt(e,qr(i,{VariableDefinition:()=>!1,Variable(s){let a;o?(a=i.getFragmentSignatureByName()(o.name.value)?.variableDefinitions.get(s.name.value),n.push({node:s,type:i.getInputType(),parentType:i.getParentInputType(),defaultValue:void 0,fragmentVariableDefinition:a})):n.push({node:s,type:i.getInputType(),parentType:i.getParentInputType(),defaultValue:i.getDefaultValue(),fragmentVariableDefinition:void 0})}})),r=n,this._variableUsages.set(e,r)}return r}getRecursiveVariableUsages(e){let r=this._recursiveVariableUsages.get(e);if(!r){r=this.getVariableUsages(e);for(let n of this.getRecursivelyReferencedFragments(e))r=r.concat(this.getVariableUsages(n));this._recursiveVariableUsages.set(e,r)}return r}getType(){return this._typeInfo.getType()}getParentType(){return this._typeInfo.getParentType()}getInputType(){return this._typeInfo.getInputType()}getParentInputType(){return this._typeInfo.getParentInputType()}getFieldDef(){return this._typeInfo.getFieldDef()}getDirective(){return this._typeInfo.getDirective()}getArgument(){return this._typeInfo.getArgument()}getFragmentSignature(){return this._typeInfo.getFragmentSignature()}getFragmentSignatureByName(){return this._typeInfo.getFragmentSignatureByName()}getEnumValue(){return this._typeInfo.getEnumValue()}};var Bu=ke(Bt,t=>t.filter(e=>e!=="description")),Hi=new d("Too many validation errors, error limit reached. Validation aborted.");function an(t,e,r=Pt,n){return xe(qn)?qn.traceSync(()=>Cs(t,e,r,n),{schema:t,document:e}):Cs(t,e,r,n)}function Cs(t,e,r,n){let i=n?.maxErrors??100,o=n?.hideSuggestions??!1;Dt(t);let s=[],a=new Ct(t),c=new pr(t,e,a,l=>{if(s.length>=i)throw Hi;s.push(l)},o),u=Rn(r.map(l=>l(c)));try{tt(e,qr(a,u),Bu)}catch(l){if(l===Hi)s.push(Hi);else throw l}return s}function ks(t){return typeof t?.[Symbol.asyncIterator]=="function"}function Wi(t,e,r){let n=Er(t);return Qu(n)?n:new d(n.message,{nodes:n.nodes??e,source:n.source,positions:n.positions,path:r,originalError:n})}function Qu(t){return Array.isArray(t.path)}function Ps(t,e){let r=null;for(let n of t.definitions)if(n.kind===p.OPERATION_DEFINITION){if(e==null){if(r)return null;r=n}else if(n.name?.value===e)return n}return r}function Ms(t,e,r,n,i,o,s){let{schema:a,fragmentDefinitions:c,rootValue:u,operation:l,variableValues:f}=t;return{fieldName:e.name,fieldNodes:r,returnType:e.type,parentType:n,path:i,schema:a,fragments:c,rootValue:u,operation:l,variableValues:f,getAbortSignal:o,getAsyncHelpers:s}}function Vs(){let t,e;return{promise:new Promise((n,i)=>{t=n,e=i}),resolve:t,reject:e}}function Us(t){let{promise:e,resolve:r,reject:n}=Vs(),i=!1,o=a=>{i||(i=!0,r(a))},s=a=>{i||(i=!0,n(a))};return t.then(o,s),{promise:e,abort(a){s(a)}}}var cn=class{constructor(){this.pendingAsyncWork=new Set}add(e){let r=this.pendingAsyncWork,n=e.then(()=>{r.delete(n)},()=>{r.delete(n)});r.add(n)}addValues(e){for(let r of e)de(r)&&this.add(r)}wait(){if(this.pendingAsyncWork.size!==0)return this.waitForPendingAsyncWork()}promiseAllTrackOnReject(e){let r=Promise.all(e);return r.then(void 0,()=>{this.addValues(e)}),r}async waitForPendingAsyncWork(){for(;this.pendingAsyncWork.size>0;)await Promise.allSettled(Array.from(this.pendingAsyncWork))}};function $s(t){let e=new cn,r,n=o=>e.promiseAllTrackOnReject(o);return{asyncWorkTracker:e,getAbortSignal:()=>t,getAsyncHelpers:()=>r??={promiseAll:n,track:o=>e.addValues(o)},promiseAll:n}}function Gs(t){let e;return function(n,i){e??=new WeakMap;let o=e.get(n);o===void 0&&(o=new WeakMap,e.set(n,o));let s=o.get(i);return s===void 0&&(s=t(n,i),o.set(i,s)),s}}function Bs(t){let e;return function(n,i,o){e??=new WeakMap;let s=e.get(n);s===void 0&&(s=new WeakMap,e.set(n,s));let a=s.get(i);a===void 0&&(a=new WeakMap,s.set(i,a));let c=a.get(o);return c===void 0&&(c=t(n,i,o),a.set(o,c)),c}}function Qs(t,e){let r=Object.keys(t),n=Object.values(t);return e(n).then(i=>{let o=Object.create(null);for(let s=0;s<r.length;++s)o[r[s]]=i[s];return o})}function js(t,e,r){let n=r;for(let i of t)n=we(n)?n.then(o=>e(o,i)):e(n,i);return n}var lr=class extends Error{constructor(e,r){super(mp(e),{cause:e}),this.name="AbortedGraphQLExecutionError",this.abortedResult=r}get[Symbol.toStringTag](){return"AbortedGraphQLExecutionError"}};function mp(t){return t instanceof Error||typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"?t.message:String(t)}function qs(t){let e=[];try{for(;;){let r=t.next();if(r.done)return e;de(r.value)&&e.push(r.value)}}catch{return e}}function Ks(t,e){let{operation:r,variableValues:n}=t,i=cr(Ae,e[0].node,n,e[0].fragmentVariableValues);if(!i||i.if===!1)return;typeof i.initialCount!="number"&&L(!1,"initialCount must be a number"),i.initialCount>=0||L(!1,"initialCount must be a positive integer"),r.operation===G.SUBSCRIPTION&&L(!1,"`@stream` directive not supported on subscription operations. Disable `@stream` by setting the `if` argument to `false`.");let o=e.map(s=>({node:s.node,deferUsage:void 0,fragmentVariableValues:s.fragmentVariableValues}));return{initialCount:i.initialCount,label:typeof i.label=="string"?i.label:void 0,fieldDetailsList:o}}function Ys(t,e){try{t?.(e)}catch{}}function Hs(t,e,r){let n=e.asyncWorkTracker.wait();if(n===void 0){Ys(r,{validatedExecutionArgs:t});return}n.then(()=>{Ys(r,{validatedExecutionArgs:t})}).catch(()=>{})}async function Ji(t){try{await t.return?.()}catch{}}var hp=Bs((t,e,r)=>{let{schema:n,fragments:i,variableValues:o,hideSuggestions:s}=t;return Fs(n,i,o,e,r,s)}),un=Gs((t,e)=>Ks(t,e)),Xi=class{constructor(){this._errorPositions=new Set,this._errors=[]}get errors(){return this._errors}add(e,r){this.hasNulledPosition(r)||(this._errorPositions.add(r),this._errors.push(e))}hasNulledPosition(e){let r=e;for(;r!==void 0;){if(this._errorPositions.has(r))return!0;r=r.prev}return this._errorPositions.has(void 0)}},yp=new Error("This operation was aborted"),pn=class{constructor(e,r){this.validatedExecutionArgs=e,this.aborted=!1,this.abortReason=yp,this.collectedErrors=new Xi,r===void 0?(this.resolverAbortController=new AbortController,this.sharedExecutionContext=$s(this.resolverAbortController.signal)):this.sharedExecutionContext=r;let{getAbortSignal:n,getAsyncHelpers:i,promiseAll:o}=this.sharedExecutionContext;this.getAbortSignal=n,this.getAsyncHelpers=i,this.promiseAll=o}executeRootSelectionSet(e){return xe(Yn)?Lt(Yn,this.buildExecuteContextFromValidatedArgs(this.validatedExecutionArgs),()=>this.executeRootSelectionSetImpl(e)):this.executeRootSelectionSetImpl(e)}buildExecuteContextFromValidatedArgs(e){return{schema:e.schema,document:e.document,operation:e.operation,rawVariableValues:e.rawVariableValues,operationName:e.operation.name?.value,operationType:e.operation.operation}}executeRootSelectionSetImpl(e){let r=this.validatedExecutionArgs.externalAbortSignal,n;if(r){r.throwIfAborted();let s=()=>{this.abort(r.reason)};n=()=>r.removeEventListener("abort",s),r.addEventListener("abort",s)}let i=()=>{n?.()},o;try{let{schema:s,fragments:a,rootValue:c,operation:u,variableValues:l,hideSuggestions:f}=this.validatedExecutionArgs,{operation:m,selectionSet:g}=u,y=s.getRootType(m);if(y==null)throw new d(`Schema is not configured to execute ${m} operation.`,{nodes:u});let{groupedFieldSet:x,newDeferUsages:S}=rn(s,a,l,y,g,f);if(o=this.executeCollectedRootFields(y,c,x,e??m===G.MUTATION,S),we(o)){let A=o.then(Y=>(i(),this.buildResponse(Y)),Y=>(i(),this.collectedErrors.add($e(Y),void 0),this.buildResponse(null)));this.sharedExecutionContext.asyncWorkTracker.add(A);let{promise:W,abort:K}=Us(A.then(Y=>this.finish(Y)));return this.abortResultPromise=()=>{K(this.createAbortedExecutionError(A))},this.aborted&&this.abortResultPromise(),W}i()}catch(s){return i(),this.collectedErrors.add($e(s),void 0),this.finish(this.buildResponse(null))}return this.finish(this.buildResponse(o))}abort(e){this.aborted||(this.aborted=!0,e!==void 0&&(this.abortReason=e),this.abortResultPromise?.(),this.resolverAbortController?.abort(this.abortReason))}finish(e){if(this.aborted)throw this.createAbortedExecutionError(e);return this.aborted=!0,e}createAbortedExecutionError(e){return new lr(this.abortReason,e)}getFinishSharedExecution(){let e=this.resolverAbortController,r=this.validatedExecutionArgs.hooks?.asyncWorkFinished;if(r===void 0)return()=>e?.abort();let n=this.validatedExecutionArgs,i=this.sharedExecutionContext;return()=>{e?.abort(),Hs(n,i,r)}}buildResponse(e){this.getFinishSharedExecution()();let r=this.collectedErrors.errors;return r.length?{errors:r,data:e}:{data:e}}executeCollectedRootFields(e,r,n,i,o){return this.executeRootGroupedFieldSet(e,r,n,i,void 0)}executeRootGroupedFieldSet(e,r,n,i,o){return i?this.executeFieldsSerially(e,r,void 0,n,o):this.executeFields(e,r,void 0,n,o)}executeFieldsSerially(e,r,n,i,o){let s=xe(mt)?mt:void 0;return js(i,(a,[c,u])=>{if(this.aborted)throw new Error("Aborted!");let l=be(n,c,e.name),f=this.executeField(e,r,u,l,o,s);return f===void 0?a:we(f)?f.then(m=>(a[c]=m,s=xe(mt)?mt:void 0,a)):(a[c]=f,a)},Object.create(null))}executeFields(e,r,n,i,o){let s=Object.create(null),a=!1,c=xe(mt)?mt:void 0;try{for(let[u,l]of i){let f=be(n,u,e.name),m=this.executeField(e,r,l,f,o,c);m!==void 0&&(s[u]=m,we(m)&&(a=!0))}}catch(u){throw a&&this.sharedExecutionContext.asyncWorkTracker.addValues(Object.values(s)),u}return a?Qs(s,this.promiseAll):s}executeField(e,r,n,i,o,s){let a=this.validatedExecutionArgs,{schema:c,contextValue:u,variableValues:l,hideSuggestions:f}=a,m=n[0],g=m.node,y=g.name.value,x=c.getField(e,y);if(!x)return;let S=x.type,A=x.resolve??a.fieldResolver;if(s!==void 0){let K=A;A=(Y,pe,Ve,Ue)=>Lt(s,this.buildResolveContext(pe,Ue,x.resolve===void 0),()=>K(Y,pe,Ve,Ue))}let W=Ms(a,x,Xe(n),e,i,this.getAbortSignal,this.getAsyncHelpers);try{let K=We(x,g,l,m.fragmentVariableValues,f),Y=A(r,K,u,W);if(de(Y))return this.completePromisedValue(S,n,W,i,Y,o);let pe=this.completeValue(S,n,W,i,Y,o);return we(pe)?pe.then(void 0,Ve=>(this.handleFieldError(Ve,S,n,i),null)):pe}catch(K){return this.handleFieldError(K,S,n,i),null}}buildResolveContext(e,r,n){let i;return{fieldName:r.fieldName,alias:String(r.path.key),parentType:r.parentType.name,fieldType:String(r.returnType),args:e,isDefaultResolver:n,get fieldPath(){return i??=Me(r.path).join("."),i}}}handleFieldError(e,r,n,i){let o=Wi(e,Xe(n),Me(i));if(this.validatedExecutionArgs.errorPropagation&&_(r))throw o;this.collectedErrors.add(o,i)}completeValue(e,r,n,i,o,s){if(o instanceof Error)throw o;if(_(e)){let a=this.completeValue(e.ofType,r,n,i,o,s);if(a===null)throw new Error(`Cannot return null for non-nullable field ${n.parentType}.${n.fieldName}.`);return a}if(o==null)return null;if(C(e))return this.completeListValue(e,r,n,i,o,s);if(ge(e))return this.completeLeafValue(e,o);if(ce(e))return this.completeAbstractValue(e,r,n,i,o,s);if(k(e))return this.completeObjectValue(e,r,n,i,o,s);L(!1,"Cannot complete value of unexpected output type: "+E(e))}async completePromisedValue(e,r,n,i,o,s){try{let a=await o;if(this.aborted)throw new Error("Aborted!");let c=this.completeValue(e,r,n,i,a,s);return we(c)&&(c=await c),c}catch(a){return this.handleFieldError(a,e,r,i),null}}async completeAsyncIterableValue(e,r,n,i,o,s){let a=typeof i.key=="number"?void 0:un(this.validatedExecutionArgs,r),c=!1,u=[],l=o[Symbol.asyncIterator](),f=0,m;try{for(;!(a?.initialCount===f&&this.handleStream(f,i,{handle:l,isAsync:!0},a,n,e));){let g=be(i,f,void 0);try{m=await l.next()}catch(x){throw Wi(x,Xe(r),Me(i))}if(this.aborted||m.done)break;let y=m.value;this.completeMaybePromisedListItemValue(y,u,e,r,n,g,s)&&(c=!0),f++}}catch(g){throw this.sharedExecutionContext.asyncWorkTracker.add(Ji(l)),c&&this.sharedExecutionContext.asyncWorkTracker.addValues(u),g}if(this.aborted)throw m?.done||this.sharedExecutionContext.asyncWorkTracker.add(Ji(l)),new Error("Aborted!");return c?this.promiseAll(u):u}handleStream(e,r,n,i,o,s){return!1}completeListValue(e,r,n,i,o,s){let a=e.ofType;if(ks(o))return this.completeAsyncIterableValue(a,r,n,i,o,s);if(!le(o))throw new d(`Expected Iterable, but did not find one for field "${n.parentType}.${n.fieldName}".`);return this.completeIterableValue(a,r,n,i,o,s)}completeIterableValue(e,r,n,i,o,s){let a=typeof i.key=="number"?void 0:un(this.validatedExecutionArgs,r),c=!1,u=[],l=0,f=o[Symbol.iterator]();try{for(;!(a?.initialCount===l&&this.handleStream(l,i,{handle:f},a,n,e));){let m=f.next();if(m.done)break;let g=m.value,y=be(i,l,void 0);this.completeMaybePromisedListItemValue(g,u,e,r,n,y,s)&&(c=!0),l++}}catch(m){let g=this.sharedExecutionContext.asyncWorkTracker;throw c&&g.addValues(u),g.addValues(qs(f)),m}return c?this.promiseAll(u):u}completeMaybePromisedListItemValue(e,r,n,i,o,s,a){return de(e)?(r.push(this.completePromisedListItemValue(e,n,i,o,s,a)),!0):!!this.completeListItemValue(e,r,n,i,o,s,a)}completeListItemValue(e,r,n,i,o,s,a){try{let c=this.completeValue(n,i,o,s,e,a);if(we(c))return r.push(c.then(void 0,u=>(this.handleFieldError(u,n,i,s),null))),!0;r.push(c)}catch(c){this.handleFieldError(c,n,i,s),r.push(null)}return!1}async completePromisedListItemValue(e,r,n,i,o,s){try{let a=await e;if(this.aborted)throw new Error("Aborted!");let c=this.completeValue(r,n,i,o,a,s);return we(c)&&(c=await c),c}catch(a){return this.handleFieldError(a,r,n,o),null}}completeLeafValue(e,r){let n=e.coerceOutputValue(r);if(n==null)throw new Error(`Expected \`${E(e)}.coerceOutputValue(${E(r)})\` to return non-nullable value, returned: ${E(n)}`);return n}completeAbstractValue(e,r,n,i,o,s){let a=this.validatedExecutionArgs,{schema:c,contextValue:u}=a,f=(e.resolveType??a.typeResolver)(o,u,n,e);return de(f)?f.then(m=>{if(this.aborted)throw new Error("Aborted!");return this.completeObjectValue(this.ensureValidRuntimeType(m,c,e,r,n,o),r,n,i,o,s)}):this.completeObjectValue(this.ensureValidRuntimeType(f,c,e,r,n,o),r,n,i,o,s)}ensureValidRuntimeType(e,r,n,i,o,s){if(e==null)throw new d(`Abstract type "${n}" must resolve to an Object type at runtime for field "${o.parentType}.${o.fieldName}". Either the "${n}" type should provide a "resolveType" function or each possible type should provide an "isTypeOf" function.`,{nodes:Xe(i)});if(typeof e!="string")throw new d(`Abstract type "${n}" must resolve to an Object type at runtime for field "${o.parentType}.${o.fieldName}" with value ${E(s)}, received "${E(e)}", which is not a valid Object type name.`);let a=r.getType(e);if(a==null)throw new d(`Abstract type "${n}" was resolved to a type "${e}" that does not exist inside the schema.`,{nodes:Xe(i)});if(!k(a))throw new d(`Abstract type "${n}" was resolved to a non-object type "${e}".`,{nodes:Xe(i)});if(!r.isSubType(n,a))throw new d(`Runtime Object type "${a}" is not a possible type for "${n}".`,{nodes:Xe(i)});return a}completeObjectValue(e,r,n,i,o,s){if(e.isTypeOf){let a=e.isTypeOf(o,this.validatedExecutionArgs.contextValue,n);if(de(a))return a.then(c=>{if(this.aborted)throw new Error("Aborted!");if(!c)throw this.invalidReturnTypeError(e,o,r);return this.collectAndExecuteSubfields(e,r,i,o,s)});if(!a)throw this.invalidReturnTypeError(e,o,r)}return this.collectAndExecuteSubfields(e,r,i,o,s)}invalidReturnTypeError(e,r,n){return new d(`Expected value of type "${e}" but got: ${E(r)}.`,{nodes:Xe(n)})}collectAndExecuteSubfields(e,r,n,i,o){let{groupedFieldSet:s,newDeferUsages:a}=hp(this.validatedExecutionArgs,e,r);return this.executeCollectedSubfields(e,i,n,s,a,o)}executeCollectedSubfields(e,r,n,i,o,s){return this.executeFields(e,r,n,i,void 0)}};function Xe(t){return t.map(e=>e.node)}var zi="Executing this GraphQL operation would unexpectedly produce multiple payloads (due to @defer or @stream directive)",ln=class extends pn{executeCollectedRootFields(e,r,n,i,o){if(o.length>0){this.validatedExecutionArgs.operation.operation===G.SUBSCRIPTION&&L(!1,"`@defer` directive not supported on subscription operations. Disable `@defer` by setting the `if` argument to `false`.");let s=new Error(zi);throw this.abort(s),s}return this.executeRootGroupedFieldSet(e,r,n,i,void 0)}executeCollectedSubfields(e,r,n,i,o){if(o.length>0){this.validatedExecutionArgs.operation.operation===G.SUBSCRIPTION&&L(!1,"`@defer` directive not supported on subscription operations. Disable `@defer` by setting the `if` argument to `false`.");let s=new Error(zi);throw this.abort(s),s}return this.executeFields(e,r,n,i,void 0)}completeListValue(e,r,n,i,o,s){if(un(this.validatedExecutionArgs,r)!==void 0){this.validatedExecutionArgs.operation.operation===G.SUBSCRIPTION&&L(!1,"`@stream` directive not supported on subscription operations. Disable `@stream` by setting the `if` argument to `false`.");let c=new Error(zi);throw this.abort(c),c}return super.completeListValue(e,r,n,i,o,s)}};var Tp="The provided schema unexpectedly contains experimental directives (@defer or @stream). These directives may only be utilized if experimental execution features are explicitly enabled.";function dn(t){return xe(Kn)?Lt(Kn,gp(t),()=>Ws(t)):Ws(t)}function gp(t){let e,r=()=>(e===void 0&&(e=Ps(t.document,t.operationName)),e);return{schema:t.schema,document:t.document,rawVariableValues:t.variableValues,get operationName(){return t.operationName??r()?.name?.value},get operationType(){return r()?.operation}}}function Ws(t){if(t.schema.getDirective("defer")||t.schema.getDirective("stream"))throw new Error(Tp);let e=eo(t);return"schema"in e?Zi(e):{errors:e}}function Zi(t){return new ln(t).executeRootSelectionSet()}function eo(t){let{schema:e,document:r,rootValue:n,contextValue:i,variableValues:o,operationName:s,fieldResolver:a,typeResolver:c,subscribeFieldResolver:u,abortSignal:l,enableEarlyExecution:f,hooks:m,options:g}=t;Dt(e);let y,x=Object.create(null),S=Object.create(null),A=[];for(let oe of r.definitions)switch(oe.kind){case p.OPERATION_DEFINITION:if(s==null){if(y!==void 0)return[new d("Must provide operation name if query contains multiple operations.")];y=oe}else oe.name?.value===s&&(y=oe);break;case p.FRAGMENT_DEFINITION:{x[oe.name.value]=oe;let To;if(oe.variableDefinitions){let go=Object.create(null);for(let da of oe.variableDefinitions){let yr=en(e,da);if(yr instanceof d){A.push(yr);continue}go[yr.name]=yr}To=go}S[oe.name.value]={definition:oe,variableSignatures:To};break}default:}if(!y)return s!=null?[new d(`Unknown operation named "${s}".`)]:[new d("Must provide an operation.")];if(A.length>0)return A;let W=y.variableDefinitions??[],K=t.hideSuggestions??!1,Y=o??{},pe={maxErrors:g?.maxCoercionErrors??50,hideSuggestions:K},Ve=ps,Ue=xe(Ve)?Lt(Ve,{schema:e,document:r,operation:y,rawVariableValues:o,operationName:y.name?.value,operationType:y.operation},()=>tn(e,W,Y,pe)):tn(e,W,Y,pe);if(Ue.errors)return Ue.errors;let It=!y.directives?.find(oe=>oe.name.value===rs.name);return{schema:e,document:r,fragmentDefinitions:x,fragments:S,rootValue:n,contextValue:i,operation:y,variableValues:Ue.variableValues,fieldResolver:a??fn,typeResolver:c??to,subscribeFieldResolver:u??fn,hideSuggestions:K,errorPropagation:It,externalAbortSignal:l??void 0,enableEarlyExecution:f===!0,hooks:m??void 0,rawVariableValues:o}}var to=function(t,e,r,n){if(H(t)&&typeof t.__typename=="string")return t.__typename;let i=r.schema.getPossibleTypes(n),o=[];try{for(let s=0;s<i.length;s++){let a=i[s];if(a.isTypeOf){let c=a.isTypeOf(t,e,r);if(de(c))o[s]=c;else if(c)return o.length&&r.getAsyncHelpers().track(o),a.name}}}catch(s){throw o.length&&r.getAsyncHelpers().track(o),s}if(o.length)return r.getAsyncHelpers().promiseAll(o).then(s=>{for(let a=0;a<s.length;a++)if(s[a])return i[a].name})},fn=function(t,e,r,n){if(H(t)||typeof t=="function"){let i=t[n.fieldName];return typeof i=="function"?t[n.fieldName](e,r,n):i}};var T=require("@medplum/core");var D=require("@medplum/core"),Lp=new D.LRUCache(1e3),Ap=5,Fp=[D.PropertyType.canonical,D.PropertyType.uri];async function ro(t,e,r,n,i){let o=i?.maxDepth??Ap,s=i?.maxResults??D.DEFAULT_MAX_SEARCH_COUNT,a=r,c=!1,u=new Set(r.map(f=>`${f.resourceType}/${f.id}`)),l=0;for(;a.length>0;){if(l>=o||n.length>s)throw new Error(`Search with _(rev)include reached query scope limit: depth=${l}, results=${n.length}`);let f=(0,D.flatMapFilter)(e.include,y=>!c||y.modifier===D.Operator.ITERATE?Js(t,y,a,i):void 0),m=(0,D.flatMapFilter)(e.revInclude,y=>!c||y.modifier===D.Operator.ITERATE?Xs(t,y,a,i):void 0),g=(await Promise.all([...f,...m])).flat();a=[];for(let y of g){let x=y.resource;a.push(x);let S=`${x.resourceType}/${x.id}`;u.has(S)||n.push(y),u.add(S)}c=!0,l++}}async function Js(t,e,r,n){let{resourceType:i,searchParam:o,targetType:s}=e,a=(0,D.getSearchParameter)(i,o);if(!a)throw new D.OperationOutcomeError((0,D.badRequest)(`Invalid include parameter: ${i}:${o}`));let c=(0,D.evalFhirPathTyped)(a.expression,r.map(D.toTypedValue),void 0,Lp),u=[],l=[];for(let y of c)y.type===D.PropertyType.Reference?u.push(y.value):Fp.includes(y.type)&&l.push(y.value);let f=s?u.filter(y=>y.reference?.startsWith(s+"/")):u,m=(await t.readReferences(f)).filter(y=>(0,D.isResource)(y)),g=s?a.target?.filter(y=>y===s):a.target;if(g?.length&&l.length>0){let y=n?.executeSearch??(A=>t.searchResources(A)),x=g.map(A=>y({resourceType:A,filters:[{code:"url",operator:D.Operator.EQUALS,value:l.join(",")}],count:D.DEFAULT_MAX_SEARCH_COUNT,offset:0})),S=new Set(l);for(let A of await Promise.all(x))for(let W of A){let K=Zs(W);K&&S.has(K)&&m.push(W)}}return m.map(y=>zs(y,n))}async function Xs(t,e,r,n){let{resourceType:i,searchParam:o,targetType:s}=e,a=(0,D.getSearchParameter)(i,o);if(!a)throw new D.OperationOutcomeError((0,D.badRequest)(`Invalid include parameter: ${i}:${o}`));let c=(0,D.getSearchParameterDetails)(i,a).type===D.SearchParameterType.CANONICAL,u=[];for(let m of r)if(!(s&&m.resourceType!==s))if(c){let g=Zs(m);g&&u.push(g)}else{let g=(0,D.getReferenceString)(m);g&&u.push(g)}return u.length===0?[]:(await(n?.executeSearch??(m=>t.searchResources(m)))({resourceType:i,filters:[{code:o,operator:D.Operator.EQUALS,value:u.join(",")}],count:D.DEFAULT_MAX_SEARCH_COUNT,offset:0})).map(m=>zs(m,n))}function zs(t,e){let r=e?.fullUrl?.(t.resourceType,t.id);return{...r?{fullUrl:r}:void 0,search:{mode:"include"},resource:t}}function Zs(t){return"url"in t?t.url:void 0}var fr={READER:"reader",WRITER:"writer"},mn=class{async searchOne(e){return(await this.search({...e,count:1})).entry?.[0]?.resource}async searchResources(e){return(await this.search(e)).entry?.map(n=>n.resource)??[]}async conditionalCreate(e,r,n){if(r.resourceType!==e.resourceType)throw new T.OperationOutcomeError((0,T.badRequest)("Search type must match resource type for conditional update"));return r.count=2,r.sortRules=void 0,this.withTransaction(async i=>{let o=await i.searchResources(r);if(o.length===1){let a=o[0];if(!n?.assignedId&&e.id&&e.id!==a.id)throw new T.OperationOutcomeError((0,T.badRequest)("Resource ID did not match resolved ID",e.resourceType+".id"));return{resource:o[0],outcome:T.allOk}}else if(o.length>1)throw new T.OperationOutcomeError(T.multipleMatches);return{resource:await i.createResource(e,n),outcome:T.created}},{resourceTypes:(0,T.getSearchResourceTypes)(r),serializable:!0})}async conditionalUpdate(e,r,n){if(r.resourceType!==e.resourceType)throw new T.OperationOutcomeError((0,T.badRequest)("Search type must match resource type for conditional update"));return r.count=2,r.sortRules=void 0,this.withTransaction(async i=>{let o=await i.searchResources(r);if(o.length===0){if(e.id&&!n?.assignedId)throw new T.OperationOutcomeError((0,T.badRequest)("Cannot perform create as update with client-assigned ID",e.resourceType+".id"));return{resource:await i.createResource(e,n),outcome:T.created}}else if(o.length>1)throw new T.OperationOutcomeError(T.multipleMatches);let s=o[0];if(e.id&&e.id!==s.id)throw new T.OperationOutcomeError((0,T.badRequest)("Resource ID did not match resolved ID",e.resourceType+".id"));return{resource:await i.updateResource({...e,id:s.id},n),outcome:T.allOk}},{serializable:!0,resourceTypes:(0,T.getSearchResourceTypes)(r)})}async conditionalDelete(e){e.count=2,e.sortRules=void 0,await this.withTransaction(async r=>{let n=await r.searchResources(e);if(n.length>1)throw new T.OperationOutcomeError(T.multipleMatches);if(!n.length)return;let i=n[0];await r.deleteResource(i.resourceType,i.id)},{serializable:!0,resourceTypes:(0,T.getSearchResourceTypes)(e)})}async conditionalPatch(e,r,n){return e.count=2,e.sortRules=void 0,this.withTransaction(async i=>{let o=await i.searchResources(e);if(o.length>1)throw new T.OperationOutcomeError(T.multipleMatches);if(!o.length)throw new T.OperationOutcomeError(T.notFound);let s=o[0];return i.patchResource(s.resourceType,s.id,r,n)},{serializable:!0,resourceTypes:(0,T.getSearchResourceTypes)(e)})}},no=class extends mn{constructor(){super();$(this,"resources");$(this,"history");$(this,"seeding");this.resources=new Map,this.history=new Map,this.seeding=!1}async withSeeding(r){if(this.seeding)return r();this.seeding=!0;let n=await r();return this.seeding=!1,n}clear(){this.resources.clear(),this.history.clear()}setMode(r){}createResourceSync(r,n,i=!1){let o=JSON.parse((0,T.stringify)(r)),s={...o,id:o.id??this.generateId(),meta:o.meta??{}};this.seeding||(s.meta.versionId&&delete s.meta.versionId,s.meta.lastUpdated&&delete s.meta.lastUpdated),s.meta.versionId??=(0,T.generateId)(),s.meta.lastUpdated??=new Date().toISOString();let{resourceType:a,id:c}=s,u=this.resources.get(a);if(u||(u=new Map,this.resources.set(a,u)),!i&&u.has(c))throw new T.OperationOutcomeError((0,T.badRequest)("Assigned ID is already in use"));u.set(c,s);let l=this.history.get(a);l||(l=new Map,this.history.set(a,l));let f=l.get(c);return f||(f=[],l.set(c,f)),f.push(s),(0,T.deepClone)(s)}async createResource(r,n,i=!1){return this.createResourceSync(r,n,i)}generateId(){return(0,T.generateId)()}updateResource(r,n){if(!r.id)throw new T.OperationOutcomeError((0,T.badRequest)("Missing id"));if(n?.ifMatch){let i=n.ifMatch,o=this.resources.get(r.resourceType)?.get(r.id);if(!o)throw new T.OperationOutcomeError(T.notFound);if(o.meta?.versionId!==i)throw new T.OperationOutcomeError(T.preconditionFailed)}return this.createResource(r,void 0,!0)}async patchResource(r,n,i,o){let s=await this.readResource(r,n);try{if(Array.isArray(i)){let a=(0,T.applyPatch)(s,i).filter(Boolean);if(a.length>0)throw new T.OperationOutcomeError((0,T.badRequest)(a.map(c=>c.message).join(`
53
- `)))}else i.parameter&&(0,T.fhirpathPatchTypedValue)((0,T.toTypedValue)(s),(0,T.parseFhirPathPatchParameters)(i))}catch(a){throw new T.OperationOutcomeError((0,T.normalizeOperationOutcome)(a))}return s.meta&&(delete s.meta.versionId,delete s.meta.lastUpdated),this.updateResource(s,o)}async readResource(r,n){let i=this.resources.get(r)?.get(n);if(!i)throw new T.OperationOutcomeError(T.notFound);return(0,T.deepClone)(i)}async readReference(r){let n=r.reference?.split("/");if(n?.length!==2)throw new T.OperationOutcomeError((0,T.badRequest)("Invalid reference"));return this.readResource(n[0],n[1])}async readReferences(r){return Promise.all(r.map(async n=>this.readReference(n).catch(i=>i instanceof T.OperationOutcomeError?i:new T.OperationOutcomeError((0,T.normalizeOperationOutcome)(i)))))}async readHistory(r,n){await this.readResource(r,n);let i=(this.history.get(r)?.get(n)??[]).reverse().map(o=>({resource:(0,T.deepClone)(o)}));return{resourceType:"Bundle",type:"history",...i.length?{entry:i}:void 0}}async readVersion(r,n,i){await this.readResource(r,n);let o=this.history.get(r)?.get(n)?.find(s=>s.meta?.versionId===i);if(!o)throw new T.OperationOutcomeError(T.notFound);return(0,T.deepClone)(o)}searchSync(r){let{resourceType:n}=r,i=this.resources.get(n)??new Map,o=[],s=[];for(let l of r.filters??T.EMPTY){let f=Cp(n,l);f?s.push(f):o.push(l)}let a=s.length?{...r,filters:o}:r,c=[];for(let l of i.values())(0,T.matchesSearchRequest)(l,a)&&s.every(f=>kp(this.resources,l,f))&&c.push(l);let u=c.map(l=>({search:{mode:"match"},resource:(0,T.deepClone)(l)}));for(let l of r.sortRules??T.EMPTY)u=u.sort((f,m)=>Pp(f.resource,m.resource,l));return r.offset!==void 0&&(u=u.slice(r.offset)),r.count!==void 0&&(u=u.slice(0,r.count)),{resourceType:"Bundle",type:"searchset",entry:u.length?u:void 0,total:c.length}}async search(r){let n=this.searchSync(r);if((r.include||r.revInclude)&&n.entry?.length){let i=n.entry,o=i.map(s=>s.resource);await ro(this,r,o,i),n.entry=i}return n}async conditionalCreate(r,n,i){if(n.resourceType!==r.resourceType)throw new T.OperationOutcomeError((0,T.badRequest)("Search type must match resource type for conditional update"));n.count=2,n.sortRules=void 0;let s=this.searchSync(n).entry?.map(c=>c.resource)??[];if(s.length===1){let c=s[0];if(!i?.assignedId&&r.id&&r.id!==c.id)throw new T.OperationOutcomeError((0,T.badRequest)("Resource ID did not match resolved ID",r.resourceType+".id"));return{resource:s[0],outcome:T.allOk}}else if(s.length>1)throw new T.OperationOutcomeError(T.multipleMatches);return{resource:this.createResourceSync(r,i),outcome:T.created}}async searchByReference(r,n,i){r.filters??=[];let o={};for(let s of i){r.filters.push({code:n,operator:T.Operator.EQUALS,value:s});let a=await this.search(r);o[s]=[];for(let c of a.entry??T.EMPTY)c.resource&&o[s].push(c.resource);r.filters.pop()}return o}async deleteResource(r,n){if(!this.resources.get(r)?.get(n))throw new T.OperationOutcomeError(T.notFound);this.resources.get(r)?.delete(n)}withTransaction(r){return r(this)}};function Cp(t,e){let r=e.code.indexOf(".");if(r<0||e.code.startsWith("_has:"))return;if(e.operator!==T.Operator.EQUALS)throw new Error("MemoryRepository does not support this chained filter yet.");let n=e.code.slice(0,r),i=e.code.slice(r+1),o=n.indexOf(":"),s=o<0?n:n.slice(0,o),a=T.globalSchema.types[t]?.searchParams?.[s];if(o===-1&&a?.target?.length!==1)throw new T.OperationOutcomeError((0,T.badRequest)(`Unable to identify next resource type for search parameter: ${t}?${s}`));let c=o<0?a?.target?.[0]:n.slice(o+1);if(!(!a?.expression||!c))return{expression:a.expression,targetType:c,chained:(0,T.parseSearchRequest)(c,{[i]:e.value})}}function kp(t,e,r){let n=(0,T.evalFhirPath)(r.expression,e);for(let i of n){let[o,s]=i?.reference?.split("/")??[];if(o!==r.targetType||!s)continue;let a=t.get(o)?.get(s);if(a&&(0,T.matchesSearchRequest)(a,r.chained))return!0}return!1}var Pp=(t,e,r)=>{let i=T.globalSchema.types[t.resourceType]?.searchParams?.[r.code]?.expression;if(!i)return 0;let o=JSON.stringify((0,T.evalFhirPath)(i,t)),s=JSON.stringify((0,T.evalFhirPath)(i,e));return o.localeCompare(s)*(r.descending?-1:1)};var gt=require("@medplum/core");var Oe=require("@medplum/core"),ea=No(require("dataloader"),1);var hn={base64Binary:b,boolean:Q,canonical:b,code:b,date:b,dateTime:b,decimal:he,id:ve,instant:b,integer:he,markdown:b,number:he,oid:b,positiveInt:he,string:b,time:b,unsignedInt:he,uri:b,url:b,uuid:b,xhtml:b,"http://hl7.org/fhirpath/System.Boolean":Q,"http://hl7.org/fhirpath/System.Date":b,"http://hl7.org/fhirpath/System.DateTime":b,"http://hl7.org/fhirpath/System.Decimal":he,"http://hl7.org/fhirpath/System.Integer":he,"http://hl7.org/fhirpath/System.String":b,"http://hl7.org/fhirpath/System.Time":b};function ta(t,e,r){let n;if(e){let o=r._reference;delete r._reference,n={code:o,operator:Oe.Operator.EQUALS,value:(0,Oe.getReferenceString)(e)}}return r=Object.fromEntries(Object.entries(r).map(([o,s])=>[Mp(o),s])),{searchRequest:(0,Oe.parseSearchRequest)(t,r),referenceFilter:n}}function ra(t,e){let r=t.filters||[];t.filters=[e,...r]}function na(t,e,r){let{searchRequest:n,referenceFilter:i}=ta(t,e,r);return i&&ra(n,i),n}function io(t,e){t.count=Math.min(t.count??Oe.DEFAULT_SEARCH_COUNT,e??Oe.DEFAULT_MAX_SEARCH_COUNT)}function Mp(t){return t.startsWith("_")?t:t.replaceAll("_","-")}function oo(t){return t.replaceAll("-","_")}function Vp(t){return JSON.stringify(t,(r,n)=>n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n).sort((i,o)=>i.localeCompare(o)).reduce((i,o)=>(i[o]=n[o],i),{}):n)}async function yn(t,e,r,n){if(r.searchCount++,r.config?.graphqlMaxSearches&&r.searchCount>r.config.graphqlMaxSearches)throw new Error("Maximum number of searches exceeded");let i=n.fieldName,o=i.substring(0,i.length-4),{searchRequest:s,referenceFilter:a}=ta(o,t,e);io(s,r.config?.graphqlMaxSearches);let c=r.config?.graphqlBatchedSearchSize??0;if(c===0||!a)return a&&ra(s,a),(await r.repo.search(s)).entry?.map(m=>m.resource);let u=Vp(s);return(r.searchDataLoaders[u]??=Up(r.repo,s,c)).load(a)}function Up(t,e,r){return new ea.default(async n=>{let i=await t.searchByReference(e,n[0].code,n.map(o=>o.value));return n.map(o=>i[o.value])},{maxBatchSize:r,cacheKeyFn:n=>`${n.code} ${n.operator} ${n.value}`})}function dr(t){let e={_count:{type:ue,description:"Specify how many elements to return from a repeating list."},_offset:{type:ue,description:"Specify the offset to start at for a repeating element."},_sort:{type:b,description:"Specify the sort order by comma-separated list of sort rules in priority order."},_id:{type:b,description:"Select resources based on the logical id of the resource."},_lastUpdated:{type:b,description:"Select resources based on the last time they were changed."},_filter:{type:b,description:" The _filter parameter provides a syntax for expressing a set of query expressions on the underlying resources."},_cursor:{type:b,description:"The _cursor parameter is used to retrieve the next page of results from a previous search."}},r=(0,Oe.getSearchParameters)(t);if(r)for(let[n,i]of Object.entries(r))e[oo(n)]={type:b,description:i.description};return e}function so(t,e){return t.fieldNodes.some(r=>r.selectionSet?.selections.some(n=>n.kind===p.FIELD&&n.name.value===e))}function ia(t){return{resourceType:"OperationOutcome",issue:t.map(e=>({severity:"error",code:"invalid",details:{text:e.message}}))}}var oa={...hn},sa;function mr(t,e){let r=oa[t];return r||(r=$p(t,e),oa[t]=r),r}function $p(t,e){let r=(0,gt.getDataType)(t);return new je({name:t+e,description:r.description,fields:()=>Gp(t,e)})}function Gp(t,e){let r={};if((0,gt.isResourceType)(t)){let n={description:"The type of resource",type:b};r.resourceType=n}return Bp(t,r,e),r}function Bp(t,e,r){let n=(0,gt.getDataType)(t);for(let[i,o]of Object.entries(n.elements))for(let s of o.type)Qp(e,i,o,s,r)}function Qp(t,e,r,n,i){let o=n.code;if(o==="Resource")return;(o==="Element"||o==="BackboneElement")&&(o=r.type[0].code);let s={description:r.description,type:mr(o,i)};r.max>1&&(s.type=new B(new N(mr(o,i)))),r.min>0&&!e.endsWith("[x]")&&(s.type=new N(s.type));let a=e.split(".").pop().replace("[x]",(0,gt.capitalize)(n.code));t[a]=s}function aa(){return sa??=new je({name:"PatchOperationInput",description:"A JSON Patch operation as per RFC 6902",fields:{op:{type:new N(b),description:"The operation to perform"},path:{type:new N(b),description:"A JSON-Pointer"},value:{type:b,description:"The value to use within the operations. (May be any scalar, but GraphQL input types are limited.)"}}}),sa}var U=require("@medplum/core");var Mt={...hn};function Et(t){let e=Mt[t];return e||(e=ao(t),Mt[t]=e),e}function ao(t){if(t==="ResourceList")return new nt({name:"ResourceList",types:()=>(0,U.getResourceTypes)().map(Et).filter(r=>!!r),resolveType:Zp});let e=(0,U.getDataType)(t);return new z({name:t,description:e.description,fields:()=>jp(t)})}function jp(t){let e={};return qp(t,e),Wp(t,e),e}function qp(t,e){let r=(0,U.getDataType)(t);(0,U.isResourceTypeSchema)(r)&&(e.resourceType={type:new N(b),description:"Resource Type"}),t==="Reference"&&(e.resource={description:"Reference",type:Et("ResourceList"),resolve:zp});for(let[n,i]of Object.entries(r.elements))for(let o of i.type)Kp(e,n,i,o)}function Kp(t,e,r,n){let i=n.code;(i==="Element"||i==="BackboneElement")&&(i=r.type[0].code),i==="Resource"&&(i="ResourceList");let o={description:r.description,type:Jp(r,i,e),resolve:Xp};r.max>1&&(o.args=Yp(i));let s=e.split(".").pop().replace("[x]",(0,U.capitalize)(n.code));t[s]=o}function Yp(t){let e={_count:{type:ue,description:"Specify how many elements to return from a repeating list."},_offset:{type:ue,description:"Specify the offset to start at for a repeating element."}};if(!(0,U.isLowerCase)(t.charAt(0))){e.fhirpath={type:b,description:"A FHIRPath statement selecting which of the subnodes is to be included"};let r=(0,U.tryGetDataType)(t);if(r?.elements)for(let[n,i]of Object.entries(r.elements))for(let o of i.type)Hp(e,n,i,o)}return e}function Hp(t,e,r,n){let i=n.code,o=e.replace("[x]",(0,U.capitalize)(i));switch(i){case"canonical":case"code":case"id":case"oid":case"string":case"uri":case"url":case"uuid":case"http://hl7.org/fhirpath/System.String":t[o]={type:b,description:r.description};break}}function Wp(t,e){for(let r of(0,U.getResourceTypes)()){let n=Et(r),i=(0,U.getSearchParameters)(r),o={},s=0;if(i)for(let[a,c]of Object.entries(i))c.target?.includes(t)&&(o[oo(a)]={value:a},s++);if(s>0){let a=new Pe({name:t+"_"+r+"_reference",values:o}),c=dr(r);c._reference={type:new N(a),description:`Specify which property to use for reverse lookup for ${r}`},e[r+"List"]={type:new B(n),args:c,resolve:yn},e[r+"Connection"]={type:co(r,n),args:c,resolve:uo}}}}function Jp(t,e,r){let n=Et(e),i=t.max>1?new B(new N(n)):n;return t.min!==0&&!r.endsWith("[x]")&&(i=new N(i)),i}async function Xp(t,e,r,n){let i=t?.[n.fieldName];if(!e||!i)return i;let{_offset:o,_count:s,fhirpath:a,...c}=e,u=i;for(let[l,f]of Object.entries(c))u=u.filter(m=>m[l]===f);return a&&(u=u.filter(l=>(0,U.toJsBoolean)((0,U.evalFhirPathTyped)(a,[(0,U.toTypedValue)(l)])))),o&&(u=u.slice(o)),s&&(u=u.slice(0,s)),u}async function zp(t,e,r){if((0,U.isReference)(t))try{return await r.dataLoader.load(t)}catch(n){throw new U.OperationOutcomeError((0,U.normalizeOperationOutcome)(n),{cause:n})}}function Zp(t){let e=t?.resourceType;if(e)return Et(e).name}var el=new M.LRUCache,po;async function ua(t,e,r,n){let{query:i,operationName:o,variables:s}=t.body;if(!i)return[(0,M.badRequest)("Must provide query.")];let a;try{a=jr(i)}catch{return[(0,M.badRequest)("GraphQL syntax error.")]}let c=nl(),u=[...Pt,ml(r,t.config?.graphqlMaxDepth),yl(r)],l=an(c,a,u);if(l.length>0)return[ia(l)];let f=tl(i);if(f&&!r.options?.introspectionEnabled)return[M.forbidden];!n?.batch&&!rl(i)&&e.setMode(fr.READER);let m=new ca.default(y=>e.readReferences(y),{cacheKeyFn:y=>y.reference??""}),g=f&&el.get(i);if(!g){let y={repo:e,config:t.config,dataLoader:m,searchCount:0,searchDataLoaders:Object.create(null)};g=await dn({schema:c,document:a,contextValue:y,operationName:o,variableValues:s})}return[M.allOk,g,{contentType:M.ContentType.JSON}]}function tl(t){return t.includes("query IntrospectionQuery")||t.includes("__schema")}function rl(t){return t.includes("mutation")}function nl(){return po||(po=il()),po}function il(){for(let r of(0,M.getResourceTypes)())Mt[r]=ao(r);let t={},e={};for(let r of(0,M.getResourceTypes)()){let n=Et(r);t[r]={type:n,args:{id:{type:new N(ve),description:r+" ID"}},resolve:cl},t[r+"List"]={type:new B(n),args:dr(r),resolve:yn},t[r+"Connection"]={type:co(r,n),args:dr(r),resolve:uo},e[r+"Create"]={type:n,args:ol(r),resolve:ul},e[r+"Update"]={type:n,args:sl(r),resolve:pl},e[r+"Patch"]={type:n,args:Il(r),resolve:fl},e[r+"Delete"]={type:n,args:{id:{type:new N(ve),description:r+" ID"}},resolve:ll}}return new lt({query:new z({name:"QueryType",fields:t}),mutation:new z({name:"MutationType",fields:e})})}function ol(t){return{res:{type:new N(mr(t,"Create")),description:t+" Create"}}}function sl(t){return{id:{type:new N(ve),description:t+" ID"},res:{type:new N(mr(t,"Update")),description:t+" Update"}}}function co(t,e){let r=t+"Connection",n=Mt[r];return n||(n=al(t,e),Mt[r]=n),n}function al(t,e){return new z({name:t+"Connection",fields:{count:{type:ue},offset:{type:ue},pageSize:{type:ue},first:{type:b},previous:{type:b},next:{type:b},last:{type:b},edges:{type:new B(new z({name:t+"ConnectionEdge",fields:{mode:{type:b},score:{type:he},resource:{type:e}}}))}}})}async function uo(t,e,r,n){let i=n.fieldName,o=i.substring(0,i.length-10),s=na(o,t,e);so(n,"count")&&(s.total="accurate"),so(n,"edges")||(s.count=0),io(s,r.config?.graphqlMaxSearches);let a=await r.repo.search(s);return{count:a.total,offset:s.offset??0,pageSize:s.count??M.DEFAULT_SEARCH_COUNT,edges:a.entry?.map(c=>({mode:c.search?.mode,score:c.search?.score,resource:c.resource})),next:El(a)}}async function cl(t,e,r,n){try{return await r.dataLoader.load({reference:`${n.fieldName}/${e.id}`})}catch(i){throw new M.OperationOutcomeError((0,M.normalizeOperationOutcome)(i),{cause:i})}}async function ul(t,e,r,n){let i=n.fieldName,o=i.substring(0,i.length-6),s=e.res;if(s.resourceType!==o)throw new M.OperationOutcomeError((0,M.badRequest)("Invalid resourceType"));return r.repo.createResource((0,M.deepClone)(s))}async function pl(t,e,r,n){let i=n.fieldName,o=i.substring(0,i.length-6),s=e.res,a=e.id;if(s.resourceType!==o)throw new M.OperationOutcomeError((0,M.badRequest)("Invalid resourceType"));if(a!==s.id)throw new M.OperationOutcomeError((0,M.badRequest)("Invalid ID"));return r.repo.updateResource((0,M.deepClone)(s))}async function ll(t,e,r,n){let i=n.fieldName,o=i.substring(0,i.length-6);await r.repo.deleteResource(o,e.id)}async function fl(t,e,r,n){let i=n.fieldName,o=i.substring(0,i.length-5),s=e.id,a=e.patch;if(!o||!s||!Array.isArray(a))throw new M.OperationOutcomeError((0,M.badRequest)("Invalid patch arguments"));return r.repo.patchResource(o,s,a)}var dl=12,ml=(t,e=dl)=>r=>new lo(r,t,e),lo=class{constructor(e,r,n){$(this,"context");$(this,"maxDepth");$(this,"fragmentDepths");$(this,"router");this.context=e,this.router=r,this.fragmentDepths=Object.create(null),this.maxDepth=n}OperationDefinition(e){let r=this.getDepth(...e.selectionSet.selections);r.depth>this.maxDepth&&this.router.log("warn","Query max depth too high",{depth:r.depth,limit:this.maxDepth,query:e.loc?.source?.body})}getDepth(...e){let r={depth:-1};for(let n of e){let i={depth:0};if(n.kind===p.FIELD)n.selectionSet?.selections?(i=this.getDepth(...n.selectionSet.selections),i.depth+=1):i={depth:0,node:n};else if(n.kind===p.FRAGMENT_SPREAD){let o=n.name.value,s=this.context.getFragment(o),a=this.fragmentDepths[o];a?i=a:s&&(i=this.getDepth(...s.selectionSet.selections),this.fragmentDepths[o]=i)}else n.kind===p.INLINE_FRAGMENT&&(i=this.getDepth(...n.selectionSet.selections));if(i.depth>this.maxDepth)return i;i.depth>r.depth&&(r=i)}return r}},hl=1e4,yl=(t,e)=>r=>new fo(r,t,e),fo=class{constructor(e,r,n){$(this,"context");$(this,"maxCost");$(this,"debug");$(this,"router");$(this,"fragmentCosts");this.context=e,this.maxCost=n?.maxCost??hl,this.debug=n?.debug??!1,this.router=r,this.fragmentCosts=Object.create(null)}OperationDefinition(e){let r=0;for(let n of e.selectionSet.selections){let i=performance.now(),o=this.calculateCost(n);r+=o,this.log(n.kind,"node has final cost",o,"(",performance.now()-i,"ms)"),r>this.maxCost&&this.router.log("warn","GraphQL query too complex",{cost:r,limit:this.maxCost,query:e.loc?.source?.body})}}calculateCost(...e){let r=0;for(let n of e){if(n.kind===p.FIELD&&n.selectionSet){let i=0,o=1;Tl(n)?(this.log("Found search field",n.name.value),i=8,o=this.getCount(n.arguments)??20):gl(n)&&(this.log("Found linked resource"),i=1,o=2);let s=i+o*this.calculateCost(...n.selectionSet.selections);s&&this.log("Field",n.name.value,"costs",s),r+=s}else if(n.kind===p.FRAGMENT_SPREAD){let i=n.name.value,o=this.context.getFragment(i),s=this.fragmentCosts[i];if(s!==void 0)this.log("Fragment",i,"costs",s,"(cached)"),r+=s;else if(o){let a=this.calculateCost(...o.selectionSet.selections);this.fragmentCosts[i]=a,this.log("Fragment",i,"costs",a),r+=a}}else if(n.kind===p.INLINE_FRAGMENT){let i=this.calculateCost(...n.selectionSet.selections);this.log("Inline fragment on",n.typeCondition?.name.value,"costs",i),r+=i}if(r>this.maxCost)return r}return r}getCount(e){let r=e?.find(n=>n.name.value==="_count");if(r?.value.kind===p.INT)return Number.parseInt(r.value.value,10)}log(...e){this.debug&&console.log(...e)}};function Tl(t){return t.name.value.endsWith("List")}function gl(t){return t.name.value==="resource"}function El(t){let e=t.link?.find(r=>r.relation==="next")?.url;if(e)return new URL(e).searchParams.get("_cursor")||void 0}function Il(t){return{id:{type:new N(ve),description:t+" ID"},patch:{type:new N(new B(new N(aa()))),description:"Array of patch operations"}}}var Tn=require("@medplum/core");var mo=7e4,hr=class{constructor(){$(this,"routes",[])}add(e,r,n,i){let o=r.split("/").filter(s=>!!s).map(s=>s.startsWith(":")?{value:s.substring(1),param:!0}:{value:s});this.routes.push({method:e,path:o,handler:n,data:i})}find(e,r){let n=r.indexOf("?"),i=n>-1;if(i&&r.length-n-1>mo)throw new Tn.OperationOutcomeError((0,Tn.badRequest)(`Query string exceeds maximum length of ${mo} characters`));let o=r.substring(0,i?n:r.length).split("/").filter(Boolean),s,a=-1;for(let c of this.routes){let u=Nl(c,e,o);u>a&&(s=c,a=u)}if(s)return{handler:s.handler,path:o.join("/"),params:bl(s,o),query:i?vl(r):void 0,data:s.data}}};function Nl(t,e,r){if(e!==t.method||r.length!==t.path.length)return-1;let n=0;for(let i=0;i<r.length;i++)if(!t.path[i].param){if(r[i]!==t.path[i].value)return-1;n++}return n}function bl(t,e){let r=Object.create(null);for(let n=0;n<e.length;n++)t.path[n].param&&(r[t.path[n].value]=e[n]);return r}function vl(t){let e=new URL(t,"https://example.com/"),r=Object.create(null);for(let[n,i]of e.searchParams){let o=r[n];o===void 0?r[n]=i:Array.isArray(o)?o.push(i):r[n]=[o,i]}return r}async function Rl(t,e,r){let n=t.body;if(n.resourceType!=="Bundle")return[(0,O.badRequest)("Not a bundle")];let i=await Tr(t,e,r,n);return[O.allOk,i]}async function Sl(t,e,r,n){yo(t,e,n);let{resourceType:i}=t.params,o=await e.search((0,O.parseSearchRequest)(i,t.query));return[O.allOk,o]}async function xl(t,e,r,n){yo(t,e,n);let i=(0,O.parseSearchRequest)("MultipleTypes",t.query);if(!i.types||i.types.length===0)return[(0,O.badRequest)("No types specified")];let o=await e.search(i);return[O.allOk,o]}async function Ol(t,e,r,n){yo(t,e,n);let{resourceType:i}=t.params,o=t.body,s=await e.search((0,O.parseSearchRequest)(i,o));return[O.allOk,s]}function yo(t,e,r){!r?.batch&&t.config?.searchOnReader&&e.setMode(fr.READER)}async function wl(t,e,r,n){let{resourceType:i}=t.params,o=t.body,s=!!n?.batch;if(t.query?._account&&typeof t.query._account=="string"&&(o.meta=o.meta||{},o.meta.account={reference:t.query._account}),t.headers?.["if-none-exist"]){let a=(0,O.singularize)(t.headers["if-none-exist"]),c=await e.conditionalCreate(o,(0,O.parseSearchRequest)(`${i}?${a}`),{assignedId:s});return[c.outcome,c.resource]}return la(i,o,e,{assignedId:s})}async function la(t,e,r,n){if(t?.startsWith("$"))return[O.notFound];if(e.resourceType!==t)return[(0,O.badRequest)(`Incorrect resource type: expected ${t}, but found ${e.resourceType||"<EMPTY>"}`)];let i=await r.createResource(e,n);return[O.created,i]}async function _l(t,e){let{resourceType:r,id:n}=t.params,i=await e.readResource(r,n);return[O.allOk,i]}async function Dl(t,e){let{resourceType:r,id:n}=t.params,i=pa(t.query,"_offset"),o=pa(t.query,"_count"),s=await e.readHistory(r,n,{offset:i,limit:o});return[O.allOk,s]}async function Ll(t,e){let{resourceType:r,id:n,vid:i}=t.params,o=await e.readVersion(r,n,i);return[O.allOk,o]}async function Al(t,e){let{resourceType:r,id:n}=t.params,i=t.body;return fa(r,n,i,e,{ifMatch:gn(t.headers?.["if-match"])})}async function fa(t,e,r,n,i){if(r.resourceType!==t)return[(0,O.badRequest)("Incorrect resource type")];if(r.id!==e)return[(0,O.badRequest)("Incorrect resource ID")];let o=await n.updateResource(r,i);return[O.allOk,o]}async function Fl(t,e,r,n){let{resourceType:i}=t.params,o=t.body,s=(0,O.parseSearchRequest)(i,t.query),a=await e.conditionalUpdate(o,s,{assignedId:n?.batch,ifMatch:gn(t.headers?.["if-match"])});return[a.outcome,a.resource]}async function Cl(t,e){let{resourceType:r,id:n}=t.params;return await e.deleteResource(r,n),[O.allOk]}async function kl(t,e){let{resourceType:r}=t.params,n=(0,O.parseSearchRequest)(r,t.query);return await e.conditionalDelete(n),[O.allOk]}async function Pl(t,e){let{resourceType:r,id:n}=t.params,i=t.body;if(!i)return[(0,O.badRequest)("Empty patch body")];if(!Array.isArray(i)&&!(0,O.isResource)(i,"Parameters"))return[(0,O.badRequest)("Invalid patch body")];let o=await e.patchResource(r,n,i,{ifMatch:gn(t.headers?.["if-match"])});return[O.allOk,o]}async function Ml(t,e){let{resourceType:r}=t.params,n=t.body;if(!n)return[(0,O.badRequest)("Empty patch body")];if(!Array.isArray(n))return[(0,O.badRequest)("Patch body must be an array")];let i=(0,O.parseSearchRequest)(r,t.query),o=await e.conditionalPatch(i,n,{ifMatch:gn(t.headers?.["if-match"])});return[O.allOk,o]}var ho=class extends O.EventTarget{constructor(r={}){super();$(this,"router",new hr);$(this,"options");this.options=r,this.router.add("GET","",xl,{interaction:"search-system"}),this.router.add("POST","",Rl,{interaction:"batch"}),this.router.add("GET",":resourceType",Sl,{interaction:"search-type"}),this.router.add("POST",":resourceType/_search",Ol,{interaction:"search-type"}),this.router.add("POST",":resourceType",wl,{interaction:"create"}),this.router.add("GET",":resourceType/:id",_l,{interaction:"read"}),this.router.add("GET",":resourceType/:id/_history",Dl,{interaction:"history-instance"}),this.router.add("GET",":resourceType/:id/_history/:vid",Ll,{interaction:"vread"}),this.router.add("PUT",":resourceType/:id",Al,{interaction:"update"}),this.router.add("PUT",":resourceType",Fl,{interaction:"update"}),this.router.add("DELETE",":resourceType/:id",Cl,{interaction:"delete"}),this.router.add("DELETE",":resourceType",kl,{interaction:"delete"}),this.router.add("PATCH",":resourceType/:id",Pl,{interaction:"patch"}),this.router.add("PATCH",":resourceType",Ml,{interaction:"patch"}),this.router.add("POST","$graphql",ua,{interaction:"operation"})}add(r,n,i,o){this.router.add(r,n,i,{interaction:o??"operation"})}find(r,n){return this.router.find(r,n)}async handleRequest(r,n){let i=r.url;if(r.pathname)throw new O.OperationOutcomeError((0,O.badRequest)("FhirRequest must specify url instead of pathname"));let o;try{o=this.find(r.method,i)}catch(l){return[(0,O.normalizeOperationOutcome)(l)]}if(!o)return[O.notFound];let{handler:s,path:a,params:c,query:u}=o;r.params=c,r.pathname=a,u&&(r.query=u);try{return await s(r,n,this)}catch(l){return[(0,O.normalizeOperationOutcome)(l)]}}log(r,n,i){let o={type:r,message:n,data:i};this.dispatchEvent(o)}};function gn(t){if(!t)return;let e=/"([^"]+)"/.exec(t);return e?e[1]:void 0}function pa(t,e){let r=t[e],n;return Array.isArray(r)?n=r.at(-1):n=r,n?Number.parseInt(n,10):void 0}function Vl(t,e,r){return{method:t,url:e,pathname:"",query:{},params:{},body:r}}0&&(module.exports={BatchProcessor,FhirRepository,FhirRouter,MAX_QUERY_STRING_LENGTH,MemoryRepository,RepositoryMode,Router,buildBatchResponseBundle,createResourceImpl,getExtraEntries,getSearchIncludeEntries,getSearchRevIncludeEntries,makeSimpleRequest,processBatch,updateResourceImpl});
53
+ `)))}else i.parameter&&(0,T.fhirpathPatchTypedValue)((0,T.toTypedValue)(s),(0,T.parseFhirPathPatchParameters)(i))}catch(a){throw new T.OperationOutcomeError((0,T.normalizeOperationOutcome)(a))}return s.meta&&(delete s.meta.versionId,delete s.meta.lastUpdated),this.updateResource(s,o)}async readResource(r,n){let i=this.resources.get(r)?.get(n);if(!i)throw new T.OperationOutcomeError(T.notFound);return(0,T.deepClone)(i)}async readReference(r){let n=r.reference?.split("/");if(n?.length!==2)throw new T.OperationOutcomeError((0,T.badRequest)("Invalid reference"));return this.readResource(n[0],n[1])}async readReferences(r){return Promise.all(r.map(async n=>this.readReference(n).catch(i=>i instanceof T.OperationOutcomeError?i:new T.OperationOutcomeError((0,T.normalizeOperationOutcome)(i)))))}async readHistory(r,n){await this.readResource(r,n);let i=(this.history.get(r)?.get(n)??[]).reverse().map(o=>({resource:(0,T.deepClone)(o)}));return{resourceType:"Bundle",type:"history",...i.length?{entry:i}:void 0}}async readVersion(r,n,i){await this.readResource(r,n);let o=this.history.get(r)?.get(n)?.find(s=>s.meta?.versionId===i);if(!o)throw new T.OperationOutcomeError(T.notFound);return(0,T.deepClone)(o)}searchSync(r){let{resourceType:n}=r,i=this.resources.get(n)??new Map,o=[],s=[];for(let l of r.filters??T.EMPTY){let f=Cp(n,l);f?s.push(f):o.push(l)}let a=s.length?{...r,filters:o}:r,c=[];for(let l of i.values())(0,T.matchesSearchRequest)(l,a)&&s.every(f=>kp(this.resources,l,f))&&c.push(l);let u=c.map(l=>({search:{mode:"match"},resource:(0,T.deepClone)(l)}));for(let l of r.sortRules??T.EMPTY)u=u.sort((f,m)=>Pp(f.resource,m.resource,l));return r.offset!==void 0&&(u=u.slice(r.offset)),r.count!==void 0&&(u=u.slice(0,r.count)),{resourceType:"Bundle",type:"searchset",entry:u.length?u:void 0,total:c.length}}async search(r){let n=this.searchSync(r);if((r.include||r.revInclude)&&n.entry?.length){let i=n.entry,o=i.map(s=>s.resource);await ro(this,r,o,i),n.entry=i}return n}async conditionalCreate(r,n,i){if(n.resourceType!==r.resourceType)throw new T.OperationOutcomeError((0,T.badRequest)("Search type must match resource type for conditional update"));n.count=2,n.sortRules=void 0;let s=this.searchSync(n).entry?.map(c=>c.resource)??[];if(s.length===1){let c=s[0];if(!i?.assignedId&&r.id&&r.id!==c.id)throw new T.OperationOutcomeError((0,T.badRequest)("Resource ID did not match resolved ID",r.resourceType+".id"));return{resource:s[0],outcome:T.allOk}}else if(s.length>1)throw new T.OperationOutcomeError(T.multipleMatches);return{resource:this.createResourceSync(r,i),outcome:T.created}}async searchByReference(r,n,i){r.filters??=[];let o={};for(let s of i){r.filters.push({code:n,operator:T.Operator.EQUALS,value:s});let a=await this.search(r);o[s]=[];for(let c of a.entry??T.EMPTY)c.resource&&o[s].push(c.resource);r.filters.pop()}return o}async deleteResource(r,n){if(!this.resources.get(r)?.get(n))throw new T.OperationOutcomeError(T.notFound);this.resources.get(r)?.delete(n)}withTransaction(r){return r(this)}};function Cp(t,e){let r=e.code.indexOf(".");if(r<0||e.code.startsWith("_has:"))return;if(e.operator!==T.Operator.EQUALS)throw new Error("MemoryRepository does not support this chained filter yet.");let n=e.code.slice(0,r),i=e.code.slice(r+1),o=n.indexOf(":"),s=o<0?n:n.slice(0,o),a=T.globalSchema.types[t]?.searchParams?.[s];if(o===-1&&a?.target?.length!==1)throw new T.OperationOutcomeError((0,T.badRequest)(`Unable to identify next resource type for search parameter: ${t}?${s}`));let c=o<0?a?.target?.[0]:n.slice(o+1);if(!(!a?.expression||!c))return{expression:a.expression,targetType:c,chained:(0,T.parseSearchRequest)(c,{[i]:e.value})}}function kp(t,e,r){let n=(0,T.evalFhirPath)(r.expression,e);for(let i of n){let[o,s]=i?.reference?.split("/")??[];if(o!==r.targetType||!s)continue;let a=t.get(o)?.get(s);if(a&&(0,T.matchesSearchRequest)(a,r.chained))return!0}return!1}var Pp=(t,e,r)=>{let i=T.globalSchema.types[t.resourceType]?.searchParams?.[r.code]?.expression;if(!i)return 0;let o=JSON.stringify((0,T.evalFhirPath)(i,t)),s=JSON.stringify((0,T.evalFhirPath)(i,e));return o.localeCompare(s)*(r.descending?-1:1)};var gt=require("@medplum/core");var Oe=require("@medplum/core"),ea=No(require("dataloader"),1);var hn={base64Binary:b,boolean:Q,canonical:b,code:b,date:b,dateTime:b,decimal:he,id:ve,instant:b,integer:he,markdown:b,number:he,oid:b,positiveInt:he,string:b,time:b,unsignedInt:he,uri:b,url:b,uuid:b,xhtml:b,"http://hl7.org/fhirpath/System.Boolean":Q,"http://hl7.org/fhirpath/System.Date":b,"http://hl7.org/fhirpath/System.DateTime":b,"http://hl7.org/fhirpath/System.Decimal":he,"http://hl7.org/fhirpath/System.Integer":he,"http://hl7.org/fhirpath/System.String":b,"http://hl7.org/fhirpath/System.Time":b};function ta(t,e,r){let n;if(e){let o=r._reference;delete r._reference,n={code:o,operator:Oe.Operator.EQUALS,value:(0,Oe.getReferenceString)(e)}}return r=Object.fromEntries(Object.entries(r).map(([o,s])=>[Mp(o),s])),{searchRequest:(0,Oe.parseSearchRequest)(t,r),referenceFilter:n}}function ra(t,e){let r=t.filters||[];t.filters=[e,...r]}function na(t,e,r){let{searchRequest:n,referenceFilter:i}=ta(t,e,r);return i&&ra(n,i),n}function io(t,e){t.count=Math.min(t.count??Oe.DEFAULT_SEARCH_COUNT,e??Oe.DEFAULT_MAX_SEARCH_COUNT)}function Mp(t){return t.startsWith("_")?t:t.replaceAll("_","-")}function oo(t){return t.replaceAll("-","_")}function Vp(t){return JSON.stringify(t,(r,n)=>n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n).sort((i,o)=>i.localeCompare(o)).reduce((i,o)=>(i[o]=n[o],i),{}):n)}async function yn(t,e,r,n){if(r.searchCount++,r.config?.graphqlMaxSearches&&r.searchCount>r.config.graphqlMaxSearches)throw new Error("Maximum number of searches exceeded");let i=n.fieldName,o=i.substring(0,i.length-4),{searchRequest:s,referenceFilter:a}=ta(o,t,e);io(s,r.config?.graphqlMaxSearches);let c=r.config?.graphqlBatchedSearchSize??0;if(c===0||!a)return a&&ra(s,a),(await r.repo.search(s)).entry?.map(m=>m.resource);let u=Vp(s);return(r.searchDataLoaders[u]??=Up(r.repo,s,c)).load(a)}function Up(t,e,r){return new ea.default(async n=>{let i=await t.searchByReference(e,n[0].code,n.map(o=>o.value));return n.map(o=>i[o.value])},{maxBatchSize:r,cacheKeyFn:n=>`${n.code} ${n.operator} ${n.value}`})}function dr(t){let e={_count:{type:ue,description:"Specify how many elements to return from a repeating list."},_offset:{type:ue,description:"Specify the offset to start at for a repeating element."},_sort:{type:b,description:"Specify the sort order by comma-separated list of sort rules in priority order."},_id:{type:b,description:"Select resources based on the logical id of the resource."},_lastUpdated:{type:b,description:"Select resources based on the last time they were changed."},_filter:{type:b,description:" The _filter parameter provides a syntax for expressing a set of query expressions on the underlying resources."},_cursor:{type:b,description:"The _cursor parameter is used to retrieve the next page of results from a previous search."}},r=(0,Oe.getSearchParameters)(t);if(r)for(let[n,i]of Object.entries(r))e[oo(n)]={type:b,description:i.description};return e}function so(t,e){return t.fieldNodes.some(r=>r.selectionSet?.selections.some(n=>n.kind===p.FIELD&&n.name.value===e))}function ia(t){return{resourceType:"OperationOutcome",issue:t.map(e=>({severity:"error",code:"invalid",details:{text:e.message}}))}}var oa={...hn},sa;function mr(t,e){let r=oa[t];return r||(r=$p(t,e),oa[t]=r),r}function $p(t,e){let r=(0,gt.getDataType)(t);return new je({name:t+e,description:r.description,fields:()=>Gp(t,e)})}function Gp(t,e){let r={};if((0,gt.isResourceType)(t)){let n={description:"The type of resource",type:b};r.resourceType=n}return Bp(t,r,e),r}function Bp(t,e,r){let n=(0,gt.getDataType)(t);for(let[i,o]of Object.entries(n.elements))for(let s of o.type)Qp(e,i,o,s,r)}function Qp(t,e,r,n,i){let o=n.code;if(o==="Resource")return;(o==="Element"||o==="BackboneElement")&&(o=r.type[0].code);let s={description:r.description,type:mr(o,i)};r.max>1&&(s.type=new B(new N(mr(o,i)))),r.min>0&&!e.endsWith("[x]")&&(s.type=new N(s.type));let a=e.split(".").pop().replace("[x]",(0,gt.capitalize)(n.code));t[a]=s}function aa(){return sa??=new je({name:"PatchOperationInput",description:"A JSON Patch operation as per RFC 6902",fields:{op:{type:new N(b),description:"The operation to perform"},path:{type:new N(b),description:"A JSON-Pointer"},value:{type:b,description:"The value to use within the operations. (May be any scalar, but GraphQL input types are limited.)"}}}),sa}var U=require("@medplum/core");var Mt={...hn};function Et(t){let e=Mt[t];return e||(e=ao(t),Mt[t]=e),e}function ao(t){if(t==="ResourceList")return new nt({name:"ResourceList",types:()=>(0,U.getResourceTypes)().map(Et).filter(r=>!!r),resolveType:Zp});let e=(0,U.getDataType)(t);return new z({name:t,description:e.description,fields:()=>jp(t)})}function jp(t){let e={};return qp(t,e),Wp(t,e),e}function qp(t,e){let r=(0,U.getDataType)(t);(0,U.isResourceTypeSchema)(r)&&(e.resourceType={type:new N(b),description:"Resource Type"}),t==="Reference"&&(e.resource={description:"Reference",type:Et("ResourceList"),resolve:zp});for(let[n,i]of Object.entries(r.elements))for(let o of i.type)Kp(e,n,i,o)}function Kp(t,e,r,n){let i=n.code;(i==="Element"||i==="BackboneElement")&&(i=r.type[0].code),i==="Resource"&&(i="ResourceList");let o={description:r.description,type:Jp(r,i,e),resolve:Xp};r.max>1&&(o.args=Yp(i));let s=e.split(".").pop().replace("[x]",(0,U.capitalize)(n.code));t[s]=o}function Yp(t){let e={_count:{type:ue,description:"Specify how many elements to return from a repeating list."},_offset:{type:ue,description:"Specify the offset to start at for a repeating element."}};if(!(0,U.isLowerCase)(t.charAt(0))){e.fhirpath={type:b,description:"A FHIRPath statement selecting which of the subnodes is to be included"};let r=(0,U.tryGetDataType)(t);if(r?.elements)for(let[n,i]of Object.entries(r.elements))for(let o of i.type)Hp(e,n,i,o)}return e}function Hp(t,e,r,n){let i=n.code,o=e.replace("[x]",(0,U.capitalize)(i));switch(i){case"canonical":case"code":case"id":case"oid":case"string":case"uri":case"url":case"uuid":case"http://hl7.org/fhirpath/System.String":t[o]={type:b,description:r.description};break}}function Wp(t,e){for(let r of(0,U.getResourceTypes)()){let n=Et(r),i=(0,U.getSearchParameters)(r),o={},s=0;if(i)for(let[a,c]of Object.entries(i))c.target?.includes(t)&&(o[oo(a)]={value:a},s++);if(s>0){let a=new Pe({name:t+"_"+r+"_reference",values:o}),c=dr(r);c._reference={type:new N(a),description:`Specify which property to use for reverse lookup for ${r}`},e[r+"List"]={type:new B(n),args:c,resolve:yn},e[r+"Connection"]={type:co(r,n),args:c,resolve:uo}}}}function Jp(t,e,r){let n=Et(e),i=t.max>1?new B(new N(n)):n;return t.min!==0&&!r.endsWith("[x]")&&(i=new N(i)),i}async function Xp(t,e,r,n){let i=t?.[n.fieldName];if(!e||!i)return i;let{_offset:o,_count:s,fhirpath:a,...c}=e,u=i;for(let[l,f]of Object.entries(c))u=u.filter(m=>m[l]===f);return a&&(u=u.filter(l=>(0,U.toJsBoolean)((0,U.evalFhirPathTyped)(a,[(0,U.toTypedValue)(l)])))),o&&(u=u.slice(o)),s&&(u=u.slice(0,s)),u}async function zp(t,e,r){if((0,U.isReference)(t))try{return await r.dataLoader.load(t)}catch(n){throw new U.OperationOutcomeError((0,U.normalizeOperationOutcome)(n),{cause:n})}}function Zp(t){let e=t?.resourceType;if(e)return Et(e).name}var el=new M.LRUCache,po;async function ua(t,e,r,n){let{query:i,operationName:o,variables:s}=t.body;if(!i)return[(0,M.badRequest)("Must provide query.")];let a;try{a=jr(i)}catch{return[(0,M.badRequest)("GraphQL syntax error.")]}let c=il(),u=[...Pt,hl(r,t.config?.graphqlMaxDepth),Tl(r)],l=an(c,a,u);if(l.length>0)return[ia(l)];let f=rl(i);if(f&&!r.options?.introspectionEnabled)return[M.forbidden];!n?.batch&&!nl(i)&&e.setMode(fr.READER);let m=new ca.default(y=>e.readReferences(y),{cacheKeyFn:y=>y.reference??""}),g=f&&el.get(i);if(!g){let y={repo:e,config:t.config,dataLoader:m,searchCount:0,searchDataLoaders:Object.create(null)};g=await dn({schema:c,document:a,contextValue:y,operationName:o,variableValues:s})}return[M.allOk,g,{contentType:M.ContentType.JSON}]}var tl=/query IntrospectionQuery|__schema|__type(?!name)/;function rl(t){return tl.test(t)}function nl(t){return t.includes("mutation")}function il(){return po||(po=ol()),po}function ol(){for(let r of(0,M.getResourceTypes)())Mt[r]=ao(r);let t={},e={};for(let r of(0,M.getResourceTypes)()){let n=Et(r);t[r]={type:n,args:{id:{type:new N(ve),description:r+" ID"}},resolve:ul},t[r+"List"]={type:new B(n),args:dr(r),resolve:yn},t[r+"Connection"]={type:co(r,n),args:dr(r),resolve:uo},e[r+"Create"]={type:n,args:sl(r),resolve:pl},e[r+"Update"]={type:n,args:al(r),resolve:ll},e[r+"Patch"]={type:n,args:Nl(r),resolve:dl},e[r+"Delete"]={type:n,args:{id:{type:new N(ve),description:r+" ID"}},resolve:fl}}return new lt({query:new z({name:"QueryType",fields:t}),mutation:new z({name:"MutationType",fields:e})})}function sl(t){return{res:{type:new N(mr(t,"Create")),description:t+" Create"}}}function al(t){return{id:{type:new N(ve),description:t+" ID"},res:{type:new N(mr(t,"Update")),description:t+" Update"}}}function co(t,e){let r=t+"Connection",n=Mt[r];return n||(n=cl(t,e),Mt[r]=n),n}function cl(t,e){return new z({name:t+"Connection",fields:{count:{type:ue},offset:{type:ue},pageSize:{type:ue},first:{type:b},previous:{type:b},next:{type:b},last:{type:b},edges:{type:new B(new z({name:t+"ConnectionEdge",fields:{mode:{type:b},score:{type:he},resource:{type:e}}}))}}})}async function uo(t,e,r,n){let i=n.fieldName,o=i.substring(0,i.length-10),s=na(o,t,e);so(n,"count")&&(s.total="accurate"),so(n,"edges")||(s.count=0),io(s,r.config?.graphqlMaxSearches);let a=await r.repo.search(s);return{count:a.total,offset:s.offset??0,pageSize:s.count??M.DEFAULT_SEARCH_COUNT,edges:a.entry?.map(c=>({mode:c.search?.mode,score:c.search?.score,resource:c.resource})),next:Il(a)}}async function ul(t,e,r,n){try{return await r.dataLoader.load({reference:`${n.fieldName}/${e.id}`})}catch(i){throw new M.OperationOutcomeError((0,M.normalizeOperationOutcome)(i),{cause:i})}}async function pl(t,e,r,n){let i=n.fieldName,o=i.substring(0,i.length-6),s=e.res;if(s.resourceType!==o)throw new M.OperationOutcomeError((0,M.badRequest)("Invalid resourceType"));return r.repo.createResource((0,M.deepClone)(s))}async function ll(t,e,r,n){let i=n.fieldName,o=i.substring(0,i.length-6),s=e.res,a=e.id;if(s.resourceType!==o)throw new M.OperationOutcomeError((0,M.badRequest)("Invalid resourceType"));if(a!==s.id)throw new M.OperationOutcomeError((0,M.badRequest)("Invalid ID"));return r.repo.updateResource((0,M.deepClone)(s))}async function fl(t,e,r,n){let i=n.fieldName,o=i.substring(0,i.length-6);await r.repo.deleteResource(o,e.id)}async function dl(t,e,r,n){let i=n.fieldName,o=i.substring(0,i.length-5),s=e.id,a=e.patch;if(!o||!s||!Array.isArray(a))throw new M.OperationOutcomeError((0,M.badRequest)("Invalid patch arguments"));return r.repo.patchResource(o,s,a)}var ml=12,hl=(t,e=ml)=>r=>new lo(r,t,e),lo=class{constructor(e,r,n){$(this,"context");$(this,"maxDepth");$(this,"fragmentDepths");$(this,"router");this.context=e,this.router=r,this.fragmentDepths=Object.create(null),this.maxDepth=n}OperationDefinition(e){let r=this.getDepth(...e.selectionSet.selections);r.depth>this.maxDepth&&this.router.log("warn","Query max depth too high",{depth:r.depth,limit:this.maxDepth,query:e.loc?.source?.body})}getDepth(...e){let r={depth:-1};for(let n of e){let i={depth:0};if(n.kind===p.FIELD)n.selectionSet?.selections?(i=this.getDepth(...n.selectionSet.selections),i.depth+=1):i={depth:0,node:n};else if(n.kind===p.FRAGMENT_SPREAD){let o=n.name.value,s=this.context.getFragment(o),a=this.fragmentDepths[o];a?i=a:s&&(i=this.getDepth(...s.selectionSet.selections),this.fragmentDepths[o]=i)}else n.kind===p.INLINE_FRAGMENT&&(i=this.getDepth(...n.selectionSet.selections));if(i.depth>this.maxDepth)return i;i.depth>r.depth&&(r=i)}return r}},yl=1e4,Tl=(t,e)=>r=>new fo(r,t,e),fo=class{constructor(e,r,n){$(this,"context");$(this,"maxCost");$(this,"debug");$(this,"router");$(this,"fragmentCosts");this.context=e,this.maxCost=n?.maxCost??yl,this.debug=n?.debug??!1,this.router=r,this.fragmentCosts=Object.create(null)}OperationDefinition(e){let r=0;for(let n of e.selectionSet.selections){let i=performance.now(),o=this.calculateCost(n);r+=o,this.log(n.kind,"node has final cost",o,"(",performance.now()-i,"ms)"),r>this.maxCost&&this.router.log("warn","GraphQL query too complex",{cost:r,limit:this.maxCost,query:e.loc?.source?.body})}}calculateCost(...e){let r=0;for(let n of e){if(n.kind===p.FIELD&&n.selectionSet){let i=0,o=1;gl(n)?(this.log("Found search field",n.name.value),i=8,o=this.getCount(n.arguments)??20):El(n)&&(this.log("Found linked resource"),i=1,o=2);let s=i+o*this.calculateCost(...n.selectionSet.selections);s&&this.log("Field",n.name.value,"costs",s),r+=s}else if(n.kind===p.FRAGMENT_SPREAD){let i=n.name.value,o=this.context.getFragment(i),s=this.fragmentCosts[i];if(s!==void 0)this.log("Fragment",i,"costs",s,"(cached)"),r+=s;else if(o){let a=this.calculateCost(...o.selectionSet.selections);this.fragmentCosts[i]=a,this.log("Fragment",i,"costs",a),r+=a}}else if(n.kind===p.INLINE_FRAGMENT){let i=this.calculateCost(...n.selectionSet.selections);this.log("Inline fragment on",n.typeCondition?.name.value,"costs",i),r+=i}if(r>this.maxCost)return r}return r}getCount(e){let r=e?.find(n=>n.name.value==="_count");if(r?.value.kind===p.INT)return Number.parseInt(r.value.value,10)}log(...e){this.debug&&console.log(...e)}};function gl(t){return t.name.value.endsWith("List")}function El(t){return t.name.value==="resource"}function Il(t){let e=t.link?.find(r=>r.relation==="next")?.url;if(e)return new URL(e).searchParams.get("_cursor")||void 0}function Nl(t){return{id:{type:new N(ve),description:t+" ID"},patch:{type:new N(new B(new N(aa()))),description:"Array of patch operations"}}}var Tn=require("@medplum/core");var mo=7e4,hr=class{constructor(){$(this,"routes",[])}add(e,r,n,i){let o=r.split("/").filter(s=>!!s).map(s=>s.startsWith(":")?{value:s.substring(1),param:!0}:{value:s});this.routes.push({method:e,path:o,handler:n,data:i})}find(e,r){let n=r.indexOf("?"),i=n>-1;if(i&&r.length-n-1>mo)throw new Tn.OperationOutcomeError((0,Tn.badRequest)(`Query string exceeds maximum length of ${mo} characters`));let o=r.substring(0,i?n:r.length).split("/").filter(Boolean),s,a=-1;for(let c of this.routes){let u=bl(c,e,o);u>a&&(s=c,a=u)}if(s)return{handler:s.handler,path:o.join("/"),params:vl(s,o),query:i?Rl(r):void 0,data:s.data}}};function bl(t,e,r){if(e!==t.method||r.length!==t.path.length)return-1;let n=0;for(let i=0;i<r.length;i++)if(!t.path[i].param){if(r[i]!==t.path[i].value)return-1;n++}return n}function vl(t,e){let r=Object.create(null);for(let n=0;n<e.length;n++)t.path[n].param&&(r[t.path[n].value]=e[n]);return r}function Rl(t){let e=new URL(t,"https://example.com/"),r=Object.create(null);for(let[n,i]of e.searchParams){let o=r[n];o===void 0?r[n]=i:Array.isArray(o)?o.push(i):r[n]=[o,i]}return r}async function Sl(t,e,r){let n=t.body;if(n.resourceType!=="Bundle")return[(0,O.badRequest)("Not a bundle")];let i=await Tr(t,e,r,n);return[O.allOk,i]}async function xl(t,e,r,n){yo(t,e,n);let{resourceType:i}=t.params,o=await e.search((0,O.parseSearchRequest)(i,t.query));return[O.allOk,o]}async function Ol(t,e,r,n){yo(t,e,n);let i=(0,O.parseSearchRequest)("MultipleTypes",t.query);if(!i.types||i.types.length===0)return[(0,O.badRequest)("No types specified")];let o=await e.search(i);return[O.allOk,o]}async function wl(t,e,r,n){yo(t,e,n);let{resourceType:i}=t.params,o=t.body,s=await e.search((0,O.parseSearchRequest)(i,o));return[O.allOk,s]}function yo(t,e,r){!r?.batch&&t.config?.searchOnReader&&e.setMode(fr.READER)}async function _l(t,e,r,n){let{resourceType:i}=t.params,o=t.body,s=!!n?.batch;if(t.query?._account&&typeof t.query._account=="string"&&(o.meta=o.meta||{},o.meta.account={reference:t.query._account}),t.headers?.["if-none-exist"]){let a=(0,O.singularize)(t.headers["if-none-exist"]),c=await e.conditionalCreate(o,(0,O.parseSearchRequest)(`${i}?${a}`),{assignedId:s});return[c.outcome,c.resource]}return la(i,o,e,{assignedId:s})}async function la(t,e,r,n){if(t?.startsWith("$"))return[O.notFound];if(e.resourceType!==t)return[(0,O.badRequest)(`Incorrect resource type: expected ${t}, but found ${e.resourceType||"<EMPTY>"}`)];let i=await r.createResource(e,n);return[O.created,i]}async function Dl(t,e){let{resourceType:r,id:n}=t.params,i=await e.readResource(r,n);return[O.allOk,i]}async function Ll(t,e){let{resourceType:r,id:n}=t.params,i=pa(t.query,"_offset"),o=pa(t.query,"_count"),s=await e.readHistory(r,n,{offset:i,limit:o});return[O.allOk,s]}async function Al(t,e){let{resourceType:r,id:n,vid:i}=t.params,o=await e.readVersion(r,n,i);return[O.allOk,o]}async function Fl(t,e){let{resourceType:r,id:n}=t.params,i=t.body;return fa(r,n,i,e,{ifMatch:gn(t.headers?.["if-match"])})}async function fa(t,e,r,n,i){if(r.resourceType!==t)return[(0,O.badRequest)("Incorrect resource type")];if(r.id!==e)return[(0,O.badRequest)("Incorrect resource ID")];let o=await n.updateResource(r,i);return[O.allOk,o]}async function Cl(t,e,r,n){let{resourceType:i}=t.params,o=t.body,s=(0,O.parseSearchRequest)(i,t.query),a=await e.conditionalUpdate(o,s,{assignedId:n?.batch,ifMatch:gn(t.headers?.["if-match"])});return[a.outcome,a.resource]}async function kl(t,e){let{resourceType:r,id:n}=t.params;return await e.deleteResource(r,n),[O.allOk]}async function Pl(t,e){let{resourceType:r}=t.params,n=(0,O.parseSearchRequest)(r,t.query);return await e.conditionalDelete(n),[O.allOk]}async function Ml(t,e){let{resourceType:r,id:n}=t.params,i=t.body;if(!i)return[(0,O.badRequest)("Empty patch body")];if(!Array.isArray(i)&&!(0,O.isResource)(i,"Parameters"))return[(0,O.badRequest)("Invalid patch body")];let o=await e.patchResource(r,n,i,{ifMatch:gn(t.headers?.["if-match"])});return[O.allOk,o]}async function Vl(t,e){let{resourceType:r}=t.params,n=t.body;if(!n)return[(0,O.badRequest)("Empty patch body")];if(!Array.isArray(n))return[(0,O.badRequest)("Patch body must be an array")];let i=(0,O.parseSearchRequest)(r,t.query),o=await e.conditionalPatch(i,n,{ifMatch:gn(t.headers?.["if-match"])});return[O.allOk,o]}var ho=class extends O.EventTarget{constructor(r={}){super();$(this,"router",new hr);$(this,"options");this.options=r,this.router.add("GET","",Ol,{interaction:"search-system"}),this.router.add("POST","",Sl,{interaction:"batch"}),this.router.add("GET",":resourceType",xl,{interaction:"search-type"}),this.router.add("POST",":resourceType/_search",wl,{interaction:"search-type"}),this.router.add("POST",":resourceType",_l,{interaction:"create"}),this.router.add("GET",":resourceType/:id",Dl,{interaction:"read"}),this.router.add("GET",":resourceType/:id/_history",Ll,{interaction:"history-instance"}),this.router.add("GET",":resourceType/:id/_history/:vid",Al,{interaction:"vread"}),this.router.add("PUT",":resourceType/:id",Fl,{interaction:"update"}),this.router.add("PUT",":resourceType",Cl,{interaction:"update"}),this.router.add("DELETE",":resourceType/:id",kl,{interaction:"delete"}),this.router.add("DELETE",":resourceType",Pl,{interaction:"delete"}),this.router.add("PATCH",":resourceType/:id",Ml,{interaction:"patch"}),this.router.add("PATCH",":resourceType",Vl,{interaction:"patch"}),this.router.add("POST","$graphql",ua,{interaction:"operation"})}add(r,n,i,o){this.router.add(r,n,i,{interaction:o??"operation"})}find(r,n){return this.router.find(r,n)}async handleRequest(r,n){let i=r.url;if(r.pathname)throw new O.OperationOutcomeError((0,O.badRequest)("FhirRequest must specify url instead of pathname"));let o;try{o=this.find(r.method,i)}catch(l){return[(0,O.normalizeOperationOutcome)(l)]}if(!o)return[O.notFound];let{handler:s,path:a,params:c,query:u}=o;r.params=c,r.pathname=a,u&&(r.query=u);try{return await s(r,n,this)}catch(l){return[(0,O.normalizeOperationOutcome)(l)]}}log(r,n,i){let o={type:r,message:n,data:i};this.dispatchEvent(o)}};function gn(t){if(!t)return;let e=/"([^"]+)"/.exec(t);return e?e[1]:void 0}function pa(t,e){let r=t[e],n;return Array.isArray(r)?n=r.at(-1):n=r,n?Number.parseInt(n,10):void 0}function Ul(t,e,r){return{method:t,url:e,pathname:"",query:{},params:{},body:r}}0&&(module.exports={BatchProcessor,FhirRepository,FhirRouter,MAX_QUERY_STRING_LENGTH,MemoryRepository,RepositoryMode,Router,buildBatchResponseBundle,createResourceImpl,getExtraEntries,getSearchIncludeEntries,getSearchRevIncludeEntries,makeSimpleRequest,processBatch,updateResourceImpl});
54
54
  //# sourceMappingURL=index.cjs.map