@samarium.sdk/new 0.17.2 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bin/samarium +330 -229
  2. package/package.json +1 -1
package/bin/samarium CHANGED
@@ -354,16 +354,68 @@ ${F.comment}`:F.comment}this.doc.range[2]=F.offset;break}default:this.errors.pus
354
354
  `)+1;while(F!==0)this.onNewLine(this.offset+F),F=this.source.indexOf(`
355
355
  `,F)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(D){let F=D.items[D.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,F.value){let P="end"in F.value?F.value.end:void 0;if((Array.isArray(P)?P[P.length-1]:void 0)?.type==="comment")P?.push(this.sourceToken);else D.items.push({start:[this.sourceToken]})}else if(F.sep)F.sep.push(this.sourceToken);else F.start.push(this.sourceToken);return;case"space":case"comment":if(F.value)D.items.push({start:[this.sourceToken]});else if(F.sep)F.sep.push(this.sourceToken);else{if(this.atIndentedComment(F.start,D.indent)){let B=D.items[D.items.length-2]?.value?.end;if(Array.isArray(B)){Array.prototype.push.apply(B,F.start),B.push(this.sourceToken),D.items.pop();return}}F.start.push(this.sourceToken)}return}if(this.indent>=D.indent){let P=!this.onKeyLine&&this.indent===D.indent,B=P&&(F.sep||F.explicitKey)&&this.type!=="seq-item-ind",Z=[];if(B&&F.sep&&!F.value){let q=[];for(let X=0;X<F.sep.length;++X){let J=F.sep[X];switch(J.type){case"newline":q.push(X);break;case"space":break;case"comment":if(J.indent>D.indent)q.length=0;break;default:q.length=0}}if(q.length>=2)Z=F.sep.splice(q[1])}switch(this.type){case"anchor":case"tag":if(B||F.value)Z.push(this.sourceToken),D.items.push({start:Z}),this.onKeyLine=!0;else if(F.sep)F.sep.push(this.sourceToken);else F.start.push(this.sourceToken);return;case"explicit-key-ind":if(!F.sep&&!F.explicitKey)F.start.push(this.sourceToken),F.explicitKey=!0;else if(B||F.value)Z.push(this.sourceToken),D.items.push({start:Z,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(F.explicitKey)if(!F.sep)if(D8(F.start,"newline"))Object.assign(F,{key:null,sep:[this.sourceToken]});else{let q=m8(F.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:q,key:null,sep:[this.sourceToken]}]})}else if(F.value)D.items.push({start:[],key:null,sep:[this.sourceToken]});else if(D8(F.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Z,key:null,sep:[this.sourceToken]}]});else if(lQ(F.key)&&!D8(F.sep,"newline")){let q=m8(F.start),X=F.key,J=F.sep;J.push(this.sourceToken),delete F.key,delete F.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:q,key:X,sep:J}]})}else if(Z.length>0)F.sep=F.sep.concat(Z,this.sourceToken);else F.sep.push(this.sourceToken);else if(!F.sep)Object.assign(F,{key:null,sep:[this.sourceToken]});else if(F.value||B)D.items.push({start:Z,key:null,sep:[this.sourceToken]});else if(D8(F.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else F.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let q=this.flowScalar(this.type);if(B||F.value)D.items.push({start:Z,key:q,sep:[]}),this.onKeyLine=!0;else if(F.sep)this.stack.push(q);else Object.assign(F,{key:q,sep:[]}),this.onKeyLine=!0;return}default:{let q=this.startBlockValue(D);if(q){if(P&&q.type!=="block-seq")D.items.push({start:Z});this.stack.push(q);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(D){let F=D.items[D.items.length-1];switch(this.type){case"newline":if(F.value){let P="end"in F.value?F.value.end:void 0;if((Array.isArray(P)?P[P.length-1]:void 0)?.type==="comment")P?.push(this.sourceToken);else D.items.push({start:[this.sourceToken]})}else F.start.push(this.sourceToken);return;case"space":case"comment":if(F.value)D.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(F.start,D.indent)){let B=D.items[D.items.length-2]?.value?.end;if(Array.isArray(B)){Array.prototype.push.apply(B,F.start),B.push(this.sourceToken),D.items.pop();return}}F.start.push(this.sourceToken)}return;case"anchor":case"tag":if(F.value||this.indent<=D.indent)break;F.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==D.indent)break;if(F.value||D8(F.start,"seq-item-ind"))D.items.push({start:[this.sourceToken]});else F.start.push(this.sourceToken);return}if(this.indent>D.indent){let P=this.startBlockValue(D);if(P){this.stack.push(P);return}}yield*this.pop(),yield*this.step()}*flowCollection(D){let F=D.items[D.items.length-1];if(this.type==="flow-error-end"){let P;do yield*this.pop(),P=this.peek(1);while(P&&P.type==="flow-collection")}else if(D.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!F||F.sep)D.items.push({start:[this.sourceToken]});else F.start.push(this.sourceToken);return;case"map-value-ind":if(!F||F.value)D.items.push({start:[],key:null,sep:[this.sourceToken]});else if(F.sep)F.sep.push(this.sourceToken);else Object.assign(F,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!F||F.value)D.items.push({start:[this.sourceToken]});else if(F.sep)F.sep.push(this.sourceToken);else F.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let B=this.flowScalar(this.type);if(!F||F.value)D.items.push({start:[],key:B,sep:[]});else if(F.sep)this.stack.push(B);else Object.assign(F,{key:B,sep:[]});return}case"flow-map-end":case"flow-seq-end":D.end.push(this.sourceToken);return}let P=this.startBlockValue(D);if(P)this.stack.push(P);else yield*this.pop(),yield*this.step()}else{let P=this.peek(2);if(P.type==="block-map"&&(this.type==="map-value-ind"&&P.indent===D.indent||this.type==="newline"&&!P.items[P.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&P.type!=="flow-collection"){let B=p5(P),Z=m8(B);mQ(D);let q=D.end.splice(1,D.end.length);q.push(this.sourceToken);let X={type:"block-map",offset:D.offset,indent:D.indent,items:[{start:Z,key:D,sep:q}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=X}else yield*this.lineEnd(D)}}flowScalar(D){if(this.onNewLine){let F=this.source.indexOf(`
356
356
  `)+1;while(F!==0)this.onNewLine(this.offset+F),F=this.source.indexOf(`
357
- `,F)+1}return{type:D,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(D){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let F=p5(D),P=m8(F);return P.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:P,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let F=p5(D),P=m8(F);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:P,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(D,F){if(this.type!=="comment")return!1;if(this.indent<=F)return!1;return D.every((P)=>P.type==="newline"||P.type==="space")}*documentEnd(D){if(this.type!=="doc-mode"){if(D.end)D.end.push(this.sourceToken);else D.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(D){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(D.end)D.end.push(this.sourceToken);else D.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}ng.Parser=cQ});var sQ=Q((Zy)=>{var dQ=CP(),og=H6(),G6=U6(),tg=_F(),eg=i(),Dy=_P(),pQ=kP();function rQ(D){let F=D.prettyErrors!==!1;return{lineCounter:D.lineCounter||F&&new Dy.LineCounter||null,prettyErrors:F}}function Fy(D,F={}){let{lineCounter:P,prettyErrors:B}=rQ(F),Z=new pQ.Parser(P?.addNewLine),q=new dQ.Composer(F),X=Array.from(q.compose(Z.parse(D)));if(B&&P)for(let J of X)J.errors.forEach(G6.prettifyError(D,P)),J.warnings.forEach(G6.prettifyError(D,P));if(X.length>0)return X;return Object.assign([],{empty:!0},q.streamInfo())}function aQ(D,F={}){let{lineCounter:P,prettyErrors:B}=rQ(F),Z=new pQ.Parser(P?.addNewLine),q=new dQ.Composer(F),X=null;for(let J of q.compose(Z.parse(D),!0,D.length))if(!X)X=J;else if(X.options.logLevel!=="silent"){X.errors.push(new G6.YAMLParseError(J.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(B&&P)X.errors.forEach(G6.prettifyError(D,P)),X.warnings.forEach(G6.prettifyError(D,P));return X}function Py(D,F,P){let B=void 0;if(typeof F==="function")B=F;else if(P===void 0&&F&&typeof F==="object")P=F;let Z=aQ(D,P);if(!Z)return null;if(Z.warnings.forEach((q)=>tg.warn(Z.options.logLevel,q)),Z.errors.length>0)if(Z.options.logLevel!=="silent")throw Z.errors[0];else Z.errors=[];return Z.toJS(Object.assign({reviver:B},P))}function By(D,F,P){let B=null;if(typeof F==="function"||Array.isArray(F))B=F;else if(P===void 0&&F)P=F;if(typeof P==="string")P=P.length;if(typeof P==="number"){let Z=Math.round(P);P=Z<1?void 0:Z>8?{indent:8}:{indent:Z}}if(D===void 0){let{keepUndefined:Z}=P??F??{};if(!Z)return}if(eg.isDocument(D)&&!B)return D.toString(P);return new og.Document(D,B,P).toString(P)}Zy.parse=Py;Zy.parseAllDocuments=Fy;Zy.parseDocument=aQ;Zy.stringify=By});var iQ=Q((Ey)=>{var Hy=CP(),Uy=H6(),Wy=JP(),xP=U6(),Oy=n1(),K2=i(),zy=R2(),Qy=ED(),Gy=$2(),Ry=M2(),Iy=c5(),$y=uP(),My=_P(),Ky=kP(),r5=sQ(),nQ=a1();Ey.Composer=Hy.Composer;Ey.Document=Uy.Document;Ey.Schema=Wy.Schema;Ey.YAMLError=xP.YAMLError;Ey.YAMLParseError=xP.YAMLParseError;Ey.YAMLWarning=xP.YAMLWarning;Ey.Alias=Oy.Alias;Ey.isAlias=K2.isAlias;Ey.isCollection=K2.isCollection;Ey.isDocument=K2.isDocument;Ey.isMap=K2.isMap;Ey.isNode=K2.isNode;Ey.isPair=K2.isPair;Ey.isScalar=K2.isScalar;Ey.isSeq=K2.isSeq;Ey.Pair=zy.Pair;Ey.Scalar=Qy.Scalar;Ey.YAMLMap=Gy.YAMLMap;Ey.YAMLSeq=Ry.YAMLSeq;Ey.CST=Iy;Ey.Lexer=$y.Lexer;Ey.LineCounter=My.LineCounter;Ey.Parser=Ky.Parser;Ey.parse=r5.parse;Ey.parseAllDocuments=r5.parseAllDocuments;Ey.parseDocument=r5.parseDocument;Ey.stringify=r5.stringify;Ey.visit=nQ.visit;Ey.visitAsync=nQ.visitAsync});var $6={name:"@samarium.sdk/new",version:"0.17.2",main:"bin/samarium",type:"module",repository:{type:"git",url:"https://github.com/liontariai/samarium",directory:"packages/new"},keywords:["graphql","typescript","compiler","api","sdk","openapi","oas3","oas3.1","swagger","graphql-sdk","graphql-codegen"],homepage:"https://liontari.ai",bin:{samarium:"bin/samarium"},publishConfig:{access:"public"},files:["bin/**/*","README.md","package.json"],scripts:{prettier:"prettier --write .",bundle:"bun bundle.js",prepublishOnly:"bun run bundle",test:"bun test"},prettier:{tabWidth:4},devDependencies:{"bun-types":"^1.1.29","@samarium.sdk/make":"workspace:*"},peerDependencies:{typescript:"^5.0.0"},dependencies:{"@inquirer/prompts":"^5.0.5",commander:"^11.1.0","detect-indent":"^7.0.1",prettier:"^3.2.5",yaml:"^2.6.0"}};var XB=UD(qB(),1),{program:Hm,createCommand:Um,createArgument:Wm,createOption:Om,CommanderError:zm,InvalidArgumentError:Qm,InvalidOptionArgumentError:Gm,Command:JB,Argument:Rm,Option:Im,Help:$m}=XB.default;var RU=UD(u0(),1);var A3=UD(u0(),1);class Z2 extends Error{response;request;constructor(D,F){let P=`${Z2.extractMessage(D)}: ${JSON.stringify({response:D,request:F})}`;super(P);if(Object.setPrototypeOf(this,Z2.prototype),this.response=D,this.request=F,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,Z2)}static extractMessage(D){return D.errors?.[0]?.message??`GraphQL Error (Code: ${String(D.status)})`}}var C7=(D)=>D.toUpperCase(),R3=(D)=>{return typeof D==="function"?D():D},L7=(D,F)=>D.map((P,B)=>[P,F[B]]),v2=(D)=>{let F={};if(D instanceof Headers)F=oS(D);else if(Array.isArray(D))D.forEach(([P,B])=>{if(P&&B!==void 0)F[P]=B});else if(D)F=D;return F},oS=(D)=>{let F={};return D.forEach((P,B)=>{F[B]=P}),F},BU=(D)=>{try{let F=D();if(tS(F))return F.catch((P)=>{return PU(P)});return F}catch(F){return PU(F)}},PU=(D)=>{if(D instanceof Error)return D;return new Error(String(D))},tS=(D)=>{return typeof D==="object"&&D!==null&&"then"in D&&typeof D.then==="function"&&"catch"in D&&typeof D.catch==="function"&&"finally"in D&&typeof D.finally==="function"},I3=(D)=>{throw new Error(`Unhandled case: ${String(D)}`)},T1=(D)=>{return typeof D==="object"&&D!==null&&!Array.isArray(D)};var ZU=(D,F)=>{return D.documents?D:{documents:D,requestHeaders:F,signal:void 0}};var qU=(D,F,P)=>{return D.query?D:{query:D,variables:F,requestHeaders:P,signal:void 0}};var YU=UD(u0(),1);var w7="Accept",$3="Content-Type",N1="application/json",M3="application/graphql-response+json";var V7=(D)=>D.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),HU=(D)=>{let F=D.toLowerCase();return F.includes(M3)||F.includes(N1)},j7=(D)=>{try{if(Array.isArray(D))return{_tag:"Batch",executionResults:D.map(XU)};else if(T1(D))return{_tag:"Single",executionResult:XU(D)};else throw new Error(`Invalid execution result: result is not object or array.
357
+ `,F)+1}return{type:D,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(D){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let F=p5(D),P=m8(F);return P.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:P,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let F=p5(D),P=m8(F);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:P,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(D,F){if(this.type!=="comment")return!1;if(this.indent<=F)return!1;return D.every((P)=>P.type==="newline"||P.type==="space")}*documentEnd(D){if(this.type!=="doc-mode"){if(D.end)D.end.push(this.sourceToken);else D.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(D){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(D.end)D.end.push(this.sourceToken);else D.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}ng.Parser=cQ});var sQ=Q((Zy)=>{var dQ=CP(),og=H6(),G6=U6(),tg=_F(),eg=i(),Dy=_P(),pQ=kP();function rQ(D){let F=D.prettyErrors!==!1;return{lineCounter:D.lineCounter||F&&new Dy.LineCounter||null,prettyErrors:F}}function Fy(D,F={}){let{lineCounter:P,prettyErrors:B}=rQ(F),Z=new pQ.Parser(P?.addNewLine),q=new dQ.Composer(F),X=Array.from(q.compose(Z.parse(D)));if(B&&P)for(let J of X)J.errors.forEach(G6.prettifyError(D,P)),J.warnings.forEach(G6.prettifyError(D,P));if(X.length>0)return X;return Object.assign([],{empty:!0},q.streamInfo())}function aQ(D,F={}){let{lineCounter:P,prettyErrors:B}=rQ(F),Z=new pQ.Parser(P?.addNewLine),q=new dQ.Composer(F),X=null;for(let J of q.compose(Z.parse(D),!0,D.length))if(!X)X=J;else if(X.options.logLevel!=="silent"){X.errors.push(new G6.YAMLParseError(J.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(B&&P)X.errors.forEach(G6.prettifyError(D,P)),X.warnings.forEach(G6.prettifyError(D,P));return X}function Py(D,F,P){let B=void 0;if(typeof F==="function")B=F;else if(P===void 0&&F&&typeof F==="object")P=F;let Z=aQ(D,P);if(!Z)return null;if(Z.warnings.forEach((q)=>tg.warn(Z.options.logLevel,q)),Z.errors.length>0)if(Z.options.logLevel!=="silent")throw Z.errors[0];else Z.errors=[];return Z.toJS(Object.assign({reviver:B},P))}function By(D,F,P){let B=null;if(typeof F==="function"||Array.isArray(F))B=F;else if(P===void 0&&F)P=F;if(typeof P==="string")P=P.length;if(typeof P==="number"){let Z=Math.round(P);P=Z<1?void 0:Z>8?{indent:8}:{indent:Z}}if(D===void 0){let{keepUndefined:Z}=P??F??{};if(!Z)return}if(eg.isDocument(D)&&!B)return D.toString(P);return new og.Document(D,B,P).toString(P)}Zy.parse=Py;Zy.parseAllDocuments=Fy;Zy.parseDocument=aQ;Zy.stringify=By});var iQ=Q((Ey)=>{var Hy=CP(),Uy=H6(),Wy=JP(),xP=U6(),Oy=n1(),K2=i(),zy=R2(),Qy=ED(),Gy=$2(),Ry=M2(),Iy=c5(),$y=uP(),My=_P(),Ky=kP(),r5=sQ(),nQ=a1();Ey.Composer=Hy.Composer;Ey.Document=Uy.Document;Ey.Schema=Wy.Schema;Ey.YAMLError=xP.YAMLError;Ey.YAMLParseError=xP.YAMLParseError;Ey.YAMLWarning=xP.YAMLWarning;Ey.Alias=Oy.Alias;Ey.isAlias=K2.isAlias;Ey.isCollection=K2.isCollection;Ey.isDocument=K2.isDocument;Ey.isMap=K2.isMap;Ey.isNode=K2.isNode;Ey.isPair=K2.isPair;Ey.isScalar=K2.isScalar;Ey.isSeq=K2.isSeq;Ey.Pair=zy.Pair;Ey.Scalar=Qy.Scalar;Ey.YAMLMap=Gy.YAMLMap;Ey.YAMLSeq=Ry.YAMLSeq;Ey.CST=Iy;Ey.Lexer=$y.Lexer;Ey.LineCounter=My.LineCounter;Ey.Parser=Ky.Parser;Ey.parse=r5.parse;Ey.parseAllDocuments=r5.parseAllDocuments;Ey.parseDocument=r5.parseDocument;Ey.stringify=r5.stringify;Ey.visit=nQ.visit;Ey.visitAsync=nQ.visitAsync});var $6={name:"@samarium.sdk/new",version:"0.19.0",main:"bin/samarium",type:"module",repository:{type:"git",url:"https://github.com/liontariai/samarium",directory:"packages/new"},keywords:["graphql","typescript","compiler","api","sdk","openapi","oas3","oas3.1","swagger","graphql-sdk","graphql-codegen"],homepage:"https://liontari.ai",bin:{samarium:"bin/samarium"},publishConfig:{access:"public"},files:["bin/**/*","README.md","package.json"],scripts:{prettier:"prettier --write .",bundle:"bun bundle.js",prepublishOnly:"bun run bundle",test:"bun test"},prettier:{tabWidth:4},devDependencies:{"bun-types":"^1.1.29","@samarium.sdk/make":"workspace:*"},peerDependencies:{typescript:"^5.0.0"},dependencies:{"@inquirer/prompts":"^5.0.5",commander:"^11.1.0","detect-indent":"^7.0.1",prettier:"^3.2.5",yaml:"^2.6.0"}};var XB=UD(qB(),1),{program:Hm,createCommand:Um,createArgument:Wm,createOption:Om,CommanderError:zm,InvalidArgumentError:Qm,InvalidOptionArgumentError:Gm,Command:JB,Argument:Rm,Option:Im,Help:$m}=XB.default;var RU=UD(u0(),1);var A3=UD(u0(),1);class Z2 extends Error{response;request;constructor(D,F){let P=`${Z2.extractMessage(D)}: ${JSON.stringify({response:D,request:F})}`;super(P);if(Object.setPrototypeOf(this,Z2.prototype),this.response=D,this.request=F,typeof Error.captureStackTrace==="function")Error.captureStackTrace(this,Z2)}static extractMessage(D){return D.errors?.[0]?.message??`GraphQL Error (Code: ${String(D.status)})`}}var C7=(D)=>D.toUpperCase(),R3=(D)=>{return typeof D==="function"?D():D},L7=(D,F)=>D.map((P,B)=>[P,F[B]]),v2=(D)=>{let F={};if(D instanceof Headers)F=oS(D);else if(Array.isArray(D))D.forEach(([P,B])=>{if(P&&B!==void 0)F[P]=B});else if(D)F=D;return F},oS=(D)=>{let F={};return D.forEach((P,B)=>{F[B]=P}),F},BU=(D)=>{try{let F=D();if(tS(F))return F.catch((P)=>{return PU(P)});return F}catch(F){return PU(F)}},PU=(D)=>{if(D instanceof Error)return D;return new Error(String(D))},tS=(D)=>{return typeof D==="object"&&D!==null&&"then"in D&&typeof D.then==="function"&&"catch"in D&&typeof D.catch==="function"&&"finally"in D&&typeof D.finally==="function"},I3=(D)=>{throw new Error(`Unhandled case: ${String(D)}`)},T1=(D)=>{return typeof D==="object"&&D!==null&&!Array.isArray(D)};var ZU=(D,F)=>{return D.documents?D:{documents:D,requestHeaders:F,signal:void 0}};var qU=(D,F,P)=>{return D.query?D:{query:D,variables:F,requestHeaders:P,signal:void 0}};var YU=UD(u0(),1);var w7="Accept",$3="Content-Type",N1="application/json",M3="application/graphql-response+json";var V7=(D)=>D.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),HU=(D)=>{let F=D.toLowerCase();return F.includes(M3)||F.includes(N1)},j7=(D)=>{try{if(Array.isArray(D))return{_tag:"Batch",executionResults:D.map(XU)};else if(T1(D))return{_tag:"Single",executionResult:XU(D)};else throw new Error(`Invalid execution result: result is not object or array.
358
358
  Got:
359
- ${String(D)}`)}catch(F){return F}},XU=(D)=>{if(typeof D!=="object"||D===null)throw new Error("Invalid execution result: result is not object");let F=void 0,P=void 0,B=void 0;if("errors"in D){if(!T1(D.errors)&&!Array.isArray(D.errors))throw new Error("Invalid execution result: errors is not plain object OR array");F=D.errors}if("data"in D){if(!T1(D.data)&&D.data!==null)throw new Error("Invalid execution result: data is not plain object");P=D.data}if("extensions"in D){if(!T1(D.extensions))throw new Error("Invalid execution result: extensions is not plain object");B=D.extensions}return{data:P,errors:F,extensions:B}},UU=(D)=>D._tag==="Batch"?D.executionResults.some(JU):JU(D.executionResult),JU=(D)=>Array.isArray(D.errors)?D.errors.length>0:Boolean(D.errors),b7=(D)=>{return typeof D==="object"&&D!==null&&"kind"in D&&D.kind===YU.Kind.OPERATION_DEFINITION};var WU=UD(u0(),1),OU=UD(u0(),1),zU=UD(u0(),1),eS=(D)=>{let F=void 0,P=D.definitions.filter(b7);if(P.length===1)F=P[0].name?.value;return F},DT=(D)=>{let F=!1,P=D.definitions.filter(b7);if(P.length===1)F=P[0].operation===WU.OperationTypeNode.MUTATION;return F},u1=(D,F)=>{let P=typeof D==="string"?D:zU.print(D),B=!1,Z=void 0;if(F)return{expression:P,isMutation:B,operationName:Z};let q=BU(()=>typeof D==="string"?OU.parse(D):D);if(q instanceof Error)return{expression:P,isMutation:B,operationName:Z};return Z=eS(q),B=DT(q),{expression:P,operationName:Z,isMutation:B}};var K3=JSON;var E3=async(D)=>{let F={...D,method:D.request._tag==="Single"?D.request.document.isMutation?"POST":C7(D.method??"post"):D.request.hasMutations?"POST":C7(D.method??"post"),fetchOptions:{...D.fetchOptions,errorPolicy:D.fetchOptions.errorPolicy??"none"}},B=await PT(F.method)(F);if(!B.ok)return new Z2({status:B.status,headers:B.headers},{query:D.request._tag==="Single"?D.request.document.expression:D.request.query,variables:D.request.variables});let Z=await FT(B,D.fetchOptions.jsonSerializer??K3);if(Z instanceof Error)throw Z;let q={status:B.status,headers:B.headers};if(UU(Z)&&F.fetchOptions.errorPolicy==="none"){let X=Z._tag==="Batch"?{...Z.executionResults,...q}:{...Z.executionResult,...q};return new Z2(X,{query:D.request._tag==="Single"?D.request.document.expression:D.request.query,variables:D.request.variables})}switch(Z._tag){case"Single":return{...q,...QU(F)(Z.executionResult)};case"Batch":return{...q,data:Z.executionResults.map(QU(F))};default:I3(Z)}},QU=(D)=>(F)=>{return{extensions:F.extensions,data:F.data,errors:D.fetchOptions.errorPolicy==="all"?F.errors:void 0}},FT=async(D,F)=>{let P=D.headers.get($3),B=await D.text();if(P&&HU(P))return j7(F.parse(B));else return j7(B)},PT=(D)=>async(F)=>{let P=new Headers(F.headers),B=null,Z=void 0;if(!P.has(w7))P.set(w7,[M3,N1].join(", "));if(D==="POST"){if(Z=(F.fetchOptions.jsonSerializer??K3).stringify(BT(F)),typeof Z==="string"&&!P.has($3))P.set($3,N1)}else B=ZT(F);let q={method:D,headers:P,body:Z,...F.fetchOptions},X=new URL(F.url),J=q;if(F.middleware){let H=await Promise.resolve(F.middleware({...q,url:F.url,operationName:F.request._tag==="Single"?F.request.document.operationName:void 0,variables:F.request.variables})),{url:W,...U}=H;X=new URL(W),J=U}if(B)B.forEach((H,W)=>{X.searchParams.append(W,H)});return await(F.fetch??fetch)(X,J)},BT=(D)=>{switch(D.request._tag){case"Single":return{query:D.request.document.expression,variables:D.request.variables,operationName:D.request.document.operationName};case"Batch":return L7(D.request.query,D.request.variables??[]).map(([F,P])=>({query:F,variables:P}));default:throw I3(D.request)}},ZT=(D)=>{let F=D.fetchOptions.jsonSerializer??K3,P=new URLSearchParams;switch(D.request._tag){case"Single":{if(P.append("query",V7(D.request.document.expression)),D.request.variables)P.append("variables",F.stringify(D.request.variables));if(D.request.document.operationName)P.append("operationName",D.request.document.operationName);return P}case"Batch":{let B=D.request.variables?.map((X)=>F.stringify(X))??[],Z=D.request.query.map(V7),q=L7(Z,B).map(([X,J])=>({query:X,variables:J}));return P.append("query",F.stringify(q)),P}default:throw I3(D.request)}};class g2{url;requestConfig;constructor(D,F={}){this.url=D,this.requestConfig=F}rawRequest=async(...D)=>{let[F,P,B]=D,Z=qU(F,P,B),{headers:q,fetch:X=globalThis.fetch,method:J="POST",requestMiddleware:Y,responseMiddleware:H,excludeOperationName:W,...U}=this.requestConfig,{url:O}=this;if(Z.signal!==void 0)U.signal=Z.signal;let z=u1(Z.query,W),I=await E3({url:O,request:{_tag:"Single",document:z,variables:Z.variables},headers:{...v2(R3(q)),...v2(Z.requestHeaders)},fetch:X,method:J,fetchOptions:U,middleware:Y});if(H)await H(I,{operationName:z.operationName,variables:P,url:this.url});if(I instanceof Error)throw I;return I};async request(D,...F){let[P,B]=F,Z=GU(D,P,B),{headers:q,fetch:X=globalThis.fetch,method:J="POST",requestMiddleware:Y,responseMiddleware:H,excludeOperationName:W,...U}=this.requestConfig,{url:O}=this;if(Z.signal!==void 0)U.signal=Z.signal;let z=u1(Z.document,W),I=await E3({url:O,request:{_tag:"Single",document:z,variables:Z.variables},headers:{...v2(R3(q)),...v2(Z.requestHeaders)},fetch:X,method:J,fetchOptions:U,middleware:Y});if(H)await H(I,{operationName:z.operationName,variables:Z.variables,url:this.url});if(I instanceof Error)throw I;return I.data}async batchRequests(D,F){let P=ZU(D,F),{headers:B,excludeOperationName:Z,...q}=this.requestConfig;if(P.signal!==void 0)q.signal=P.signal;let X=P.documents.map(({document:U})=>u1(U,Z)),J=X.map(({expression:U})=>U),Y=X.some(({isMutation:U})=>U),H=P.documents.map(({variables:U})=>U),W=await E3({url:this.url,request:{_tag:"Batch",operationName:void 0,query:J,hasMutations:Y,variables:H},headers:{...v2(R3(B)),...v2(P.requestHeaders)},fetch:this.requestConfig.fetch??globalThis.fetch,method:this.requestConfig.method||"POST",fetchOptions:q,middleware:this.requestConfig.requestMiddleware});if(this.requestConfig.responseMiddleware)await this.requestConfig.responseMiddleware(W,{operationName:void 0,variables:H,url:this.url});if(W instanceof Error)throw W;return W.data}setHeaders(D){return this.requestConfig.headers=D,this}setHeader(D,F){let{headers:P}=this.requestConfig;if(P)P[D]=F;else this.requestConfig.headers={[D]:F};return this}setEndpoint(D){return this.url=D,this}}var GU=(D,F,P)=>{return D.document?D:{document:D,variables:F,requestHeaders:P,signal:void 0}};async function y2(D,F){try{let B=await new g2(D).request(A3.getIntrospectionQuery(),void 0,new Headers(F?.map((q)=>q.split("="))));return A3.buildClientSchema(B)}catch(P){throw P}}import qT from"fs";var S7=async(D,F)=>{let P=await y2(D.url,D.headers),B=RU.printSchema(P);qT.writeFileSync(F,B)};var C3=UD(u0(),1),L3=UD(u0(),1),MD=UD(u0(),1),XT=Object.defineProperty,$U=(D,F)=>{for(var P in F)XT(D,P,{get:F[P],enumerable:!0,configurable:!0,set:(B)=>F[P]=()=>B})};class MU{collector;options;static FieldValueWrapperType;static EnumTypesMapped;static HelperTypes;static HelperFunctions;typeMeta;typeName;originalFullTypeName;constructor(D,F,P){this.collector=F,this.options=P,this.typeMeta=F.getType(D),this.originalFullTypeName=D,this.typeName=this.originalTypeNameToTypescriptFriendlyName(D)}originalTypeNameToTypescriptFriendlyName(D){return D.replaceAll("[","").replaceAll("]","Array").replaceAll("!","NotNull")}originalTypeNameToTypescriptTypeNameWithoutModifiers(D,F=""){return`${D.replaceAll("[","").replaceAll("]","").replaceAll("!","")}${F}`}originalTypeNameToTypescriptTypeName(D,F=""){return`${this.originalTypeNameToTypescriptTypeNameWithoutModifiers(D,F)}${Array.from({length:D.split("[").length-1}).fill("[]").join("")}`}static makeRootOperationFunction(D){throw new Error("Method not implemented.")}}var JT=`const Proxy = global.Proxy;
359
+ ${String(D)}`)}catch(F){return F}},XU=(D)=>{if(typeof D!=="object"||D===null)throw new Error("Invalid execution result: result is not object");let F=void 0,P=void 0,B=void 0;if("errors"in D){if(!T1(D.errors)&&!Array.isArray(D.errors))throw new Error("Invalid execution result: errors is not plain object OR array");F=D.errors}if("data"in D){if(!T1(D.data)&&D.data!==null)throw new Error("Invalid execution result: data is not plain object");P=D.data}if("extensions"in D){if(!T1(D.extensions))throw new Error("Invalid execution result: extensions is not plain object");B=D.extensions}return{data:P,errors:F,extensions:B}},UU=(D)=>D._tag==="Batch"?D.executionResults.some(JU):JU(D.executionResult),JU=(D)=>Array.isArray(D.errors)?D.errors.length>0:Boolean(D.errors),b7=(D)=>{return typeof D==="object"&&D!==null&&"kind"in D&&D.kind===YU.Kind.OPERATION_DEFINITION};var WU=UD(u0(),1),OU=UD(u0(),1),zU=UD(u0(),1),eS=(D)=>{let F=void 0,P=D.definitions.filter(b7);if(P.length===1)F=P[0].name?.value;return F},DT=(D)=>{let F=!1,P=D.definitions.filter(b7);if(P.length===1)F=P[0].operation===WU.OperationTypeNode.MUTATION;return F},u1=(D,F)=>{let P=typeof D==="string"?D:zU.print(D),B=!1,Z=void 0;if(F)return{expression:P,isMutation:B,operationName:Z};let q=BU(()=>typeof D==="string"?OU.parse(D):D);if(q instanceof Error)return{expression:P,isMutation:B,operationName:Z};return Z=eS(q),B=DT(q),{expression:P,operationName:Z,isMutation:B}};var K3=JSON;var E3=async(D)=>{let F={...D,method:D.request._tag==="Single"?D.request.document.isMutation?"POST":C7(D.method??"post"):D.request.hasMutations?"POST":C7(D.method??"post"),fetchOptions:{...D.fetchOptions,errorPolicy:D.fetchOptions.errorPolicy??"none"}},B=await PT(F.method)(F);if(!B.ok)return new Z2({status:B.status,headers:B.headers},{query:D.request._tag==="Single"?D.request.document.expression:D.request.query,variables:D.request.variables});let Z=await FT(B,D.fetchOptions.jsonSerializer??K3);if(Z instanceof Error)throw Z;let q={status:B.status,headers:B.headers};if(UU(Z)&&F.fetchOptions.errorPolicy==="none"){let X=Z._tag==="Batch"?{...Z.executionResults,...q}:{...Z.executionResult,...q};return new Z2(X,{query:D.request._tag==="Single"?D.request.document.expression:D.request.query,variables:D.request.variables})}switch(Z._tag){case"Single":return{...q,...QU(F)(Z.executionResult)};case"Batch":return{...q,data:Z.executionResults.map(QU(F))};default:I3(Z)}},QU=(D)=>(F)=>{return{extensions:F.extensions,data:F.data,errors:D.fetchOptions.errorPolicy==="all"?F.errors:void 0}},FT=async(D,F)=>{let P=D.headers.get($3),B=await D.text();if(P&&HU(P))return j7(F.parse(B));else return j7(B)},PT=(D)=>async(F)=>{let P=new Headers(F.headers),B=null,Z=void 0;if(!P.has(w7))P.set(w7,[M3,N1].join(", "));if(D==="POST"){if(Z=(F.fetchOptions.jsonSerializer??K3).stringify(BT(F)),typeof Z==="string"&&!P.has($3))P.set($3,N1)}else B=ZT(F);let q={method:D,headers:P,body:Z,...F.fetchOptions},X=new URL(F.url),J=q;if(F.middleware){let H=await Promise.resolve(F.middleware({...q,url:F.url,operationName:F.request._tag==="Single"?F.request.document.operationName:void 0,variables:F.request.variables})),{url:W,...U}=H;X=new URL(W),J=U}if(B)B.forEach((H,W)=>{X.searchParams.append(W,H)});return await(F.fetch??fetch)(X,J)},BT=(D)=>{switch(D.request._tag){case"Single":return{query:D.request.document.expression,variables:D.request.variables,operationName:D.request.document.operationName};case"Batch":return L7(D.request.query,D.request.variables??[]).map(([F,P])=>({query:F,variables:P}));default:throw I3(D.request)}},ZT=(D)=>{let F=D.fetchOptions.jsonSerializer??K3,P=new URLSearchParams;switch(D.request._tag){case"Single":{if(P.append("query",V7(D.request.document.expression)),D.request.variables)P.append("variables",F.stringify(D.request.variables));if(D.request.document.operationName)P.append("operationName",D.request.document.operationName);return P}case"Batch":{let B=D.request.variables?.map((X)=>F.stringify(X))??[],Z=D.request.query.map(V7),q=L7(Z,B).map(([X,J])=>({query:X,variables:J}));return P.append("query",F.stringify(q)),P}default:throw I3(D.request)}};class g2{url;requestConfig;constructor(D,F={}){this.url=D,this.requestConfig=F}rawRequest=async(...D)=>{let[F,P,B]=D,Z=qU(F,P,B),{headers:q,fetch:X=globalThis.fetch,method:J="POST",requestMiddleware:Y,responseMiddleware:H,excludeOperationName:W,...U}=this.requestConfig,{url:O}=this;if(Z.signal!==void 0)U.signal=Z.signal;let z=u1(Z.query,W),I=await E3({url:O,request:{_tag:"Single",document:z,variables:Z.variables},headers:{...v2(R3(q)),...v2(Z.requestHeaders)},fetch:X,method:J,fetchOptions:U,middleware:Y});if(H)await H(I,{operationName:z.operationName,variables:P,url:this.url});if(I instanceof Error)throw I;return I};async request(D,...F){let[P,B]=F,Z=GU(D,P,B),{headers:q,fetch:X=globalThis.fetch,method:J="POST",requestMiddleware:Y,responseMiddleware:H,excludeOperationName:W,...U}=this.requestConfig,{url:O}=this;if(Z.signal!==void 0)U.signal=Z.signal;let z=u1(Z.document,W),I=await E3({url:O,request:{_tag:"Single",document:z,variables:Z.variables},headers:{...v2(R3(q)),...v2(Z.requestHeaders)},fetch:X,method:J,fetchOptions:U,middleware:Y});if(H)await H(I,{operationName:z.operationName,variables:Z.variables,url:this.url});if(I instanceof Error)throw I;return I.data}async batchRequests(D,F){let P=ZU(D,F),{headers:B,excludeOperationName:Z,...q}=this.requestConfig;if(P.signal!==void 0)q.signal=P.signal;let X=P.documents.map(({document:U})=>u1(U,Z)),J=X.map(({expression:U})=>U),Y=X.some(({isMutation:U})=>U),H=P.documents.map(({variables:U})=>U),W=await E3({url:this.url,request:{_tag:"Batch",operationName:void 0,query:J,hasMutations:Y,variables:H},headers:{...v2(R3(B)),...v2(P.requestHeaders)},fetch:this.requestConfig.fetch??globalThis.fetch,method:this.requestConfig.method||"POST",fetchOptions:q,middleware:this.requestConfig.requestMiddleware});if(this.requestConfig.responseMiddleware)await this.requestConfig.responseMiddleware(W,{operationName:void 0,variables:H,url:this.url});if(W instanceof Error)throw W;return W.data}setHeaders(D){return this.requestConfig.headers=D,this}setHeader(D,F){let{headers:P}=this.requestConfig;if(P)P[D]=F;else this.requestConfig.headers={[D]:F};return this}setEndpoint(D){return this.url=D,this}}var GU=(D,F,P)=>{return D.document?D:{document:D,variables:F,requestHeaders:P,signal:void 0}};async function y2(D,F){try{let B=await new g2(D).request(A3.getIntrospectionQuery(),void 0,new Headers(F?.map((q)=>q.split("="))));return A3.buildClientSchema(B)}catch(P){throw P}}import qT from"fs";var S7=async(D,F)=>{let P=await y2(D.url,D.headers),B=RU.printSchema(P);qT.writeFileSync(F,B)};var C3=UD(u0(),1),L3=UD(u0(),1),MD=UD(u0(),1),XT=Object.defineProperty,$U=(D,F)=>{for(var P in F)XT(D,P,{get:F[P],enumerable:!0,configurable:!0,set:(B)=>F[P]=()=>B})};class MU{collector;options;authConfig;static FieldValueWrapperType;static EnumTypesMapped;static HelperTypes;static HelperFunctions;typeMeta;typeName;originalFullTypeName;constructor(D,F,P,B){this.collector=F,this.options=P,this.authConfig=B,this.typeMeta=F.getType(D),this.originalFullTypeName=D,this.typeName=this.originalTypeNameToTypescriptFriendlyName(D)}originalTypeNameToTypescriptFriendlyName(D){return D.replaceAll("[","").replaceAll("]","Array").replaceAll("!","NotNull")}originalTypeNameToTypescriptTypeNameWithoutModifiers(D,F=""){return`${D.replaceAll("[","").replaceAll("]","").replaceAll("!","")}${F}`}originalTypeNameToTypescriptTypeName(D,F=""){return`${this.originalTypeNameToTypescriptTypeNameWithoutModifiers(D,F)}${Array.from({length:D.split("[").length-1}).fill("[]").join("")}`}static makeRootOperationFunction(D){throw new Error("Method not implemented.")}}var JT=`const Proxy = global.Proxy;
360
360
  Proxy.prototype = {};
361
361
 
362
+ type FnOrPromisOrPrimitive =
363
+ | (() => string | { [key: string]: string })
364
+ | (() => Promise<string | { [key: string]: string }>)
365
+ | string
366
+ | { [key: string]: string };
362
367
  export const _ = Symbol("_") as any;
363
368
  export const OPTIONS = Symbol("OPTIONS");
364
369
  export class RootOperation {
370
+ public static authHeaderName = "[AUTH_HEADER_NAME]";
371
+ private resolveFnOrPromisOrPrimitiveHeaders = (
372
+ arg?: FnOrPromisOrPrimitive,
373
+ ) => {
374
+ if (!arg) return undefined;
375
+ let headers: Record<string, string> | undefined = undefined;
376
+ if (typeof arg === "string") {
377
+ headers = { [RootOperation.authHeaderName]: arg };
378
+ } else if (typeof arg === "function") {
379
+ const tokenOrPromise = arg();
380
+ if (tokenOrPromise instanceof Promise) {
381
+ return tokenOrPromise.then((t) => {
382
+ if (typeof t === "string")
383
+ headers = { [RootOperation.authHeaderName]: t };
384
+ else headers = t;
385
+
386
+ return headers;
387
+ });
388
+ }
389
+ if (typeof tokenOrPromise === "string") {
390
+ headers = { [RootOperation.authHeaderName]: tokenOrPromise };
391
+ } else {
392
+ headers = tokenOrPromise;
393
+ }
394
+ } else {
395
+ headers = arg;
396
+ }
397
+
398
+ return headers;
399
+ };
400
+
401
+ constructor(
402
+ public authArg?: FnOrPromisOrPrimitive,
403
+ public headers?: FnOrPromisOrPrimitive,
404
+ ) {}
405
+ public setAuth(auth: FnOrPromisOrPrimitive) {
406
+ this.authArg = auth;
407
+ return this;
408
+ }
409
+ public setHeaders(headers: FnOrPromisOrPrimitive) {
410
+ this.headers = headers;
411
+ return this;
412
+ }
413
+
365
414
  public static [OPTIONS] = {
366
415
  headers: {},
416
+ fetcher: undefined as unknown as (
417
+ request: Request,
418
+ ) => Promise<Response>,
367
419
  _auth_fn: undefined as
368
420
  | (() => string | { [key: string]: string })
369
421
  | (() => Promise<string | { [key: string]: string }>)
@@ -388,10 +440,27 @@ export class RootOperation {
388
440
  this.rootCollector = collector;
389
441
  }
390
442
  public async execute(headers: Record<string, string> = {}) {
391
- if (!this.rootCollector) {
443
+ if (!this.rootCollector?.op) {
392
444
  throw new Error("RootOperation has no registered collector");
393
445
  }
394
446
 
447
+ const authHeaders =
448
+ await this.rootCollector.op!.resolveFnOrPromisOrPrimitiveHeaders(
449
+ this.rootCollector.op!.authArg ??
450
+ RootOperation[OPTIONS]._auth_fn,
451
+ );
452
+ const headersHeaders =
453
+ await this.rootCollector.op!.resolveFnOrPromisOrPrimitiveHeaders(
454
+ this.rootCollector.op!.headers ??
455
+ RootOperation[OPTIONS].headers,
456
+ );
457
+
458
+ headers = {
459
+ ...authHeaders,
460
+ ...headersHeaders,
461
+ ...headers,
462
+ };
463
+
395
464
  type selection = ReturnType<
396
465
  typeof OperationSelectionCollector.prototype.renderSelections
397
466
  >;
@@ -473,7 +542,7 @@ export class RootOperation {
473
542
  },
474
543
  headers: Record<string, string> = {},
475
544
  ) {
476
- const res = await fetch("[ENDPOINT]", {
545
+ const request = new Request("[ENDPOINT]", {
477
546
  method: "POST",
478
547
  headers: {
479
548
  "Content-Type": "application/json",
@@ -484,6 +553,9 @@ export class RootOperation {
484
553
  variables: query.variables,
485
554
  }),
486
555
  });
556
+ const res = await (RootOperation[OPTIONS].fetcher ?? globalThis.fetch)(
557
+ request,
558
+ );
487
559
  const result = (await res.json()) as { data: any; errors: any[] };
488
560
 
489
561
  const { data, errors } = result ?? {};
@@ -520,9 +592,7 @@ export class OperationSelectionCollector {
520
592
 
521
593
  private executed = false;
522
594
  private operationResult: any | undefined = undefined;
523
- public async execute(
524
- headers: Record<string, string> = RootOperation[OPTIONS].headers,
525
- ) {
595
+ public async execute(headers?: Record<string, string>) {
526
596
  if (!this.op) {
527
597
  throw new Error(
528
598
  "OperationSelectionCollector is not registered to a root operation",
@@ -1030,7 +1100,14 @@ export class SelectionWrapper<
1030
1100
  ref: new OperationSelectionCollector(
1031
1101
  undefined,
1032
1102
  undefined,
1033
- new RootOperation(),
1103
+ new RootOperation(
1104
+ that[
1105
+ ROOT_OP_COLLECTOR
1106
+ ]!.ref.op!.authArg,
1107
+ that[
1108
+ ROOT_OP_COLLECTOR
1109
+ ]!.ref.op!.headers,
1110
+ ),
1034
1111
  ),
1035
1112
  };
1036
1113
 
@@ -1086,14 +1163,46 @@ export class SelectionWrapper<
1086
1163
  newThat,
1087
1164
  );
1088
1165
 
1089
- return new Promise((resolve, reject) => {
1090
- newRootOpCollectorRef.ref
1091
- .execute()
1092
- .catch(reject)
1093
- .then(() => {
1094
- resolve(newThat);
1095
- });
1096
- });
1166
+ const resultProxy = new Proxy(
1167
+ {},
1168
+ {
1169
+ get(_t, _prop) {
1170
+ const result = new Promise(
1171
+ (resolve, reject) => {
1172
+ newRootOpCollectorRef.ref
1173
+ .execute()
1174
+ .catch(reject)
1175
+ .then(() => {
1176
+ resolve(newThat);
1177
+ });
1178
+ },
1179
+ );
1180
+ if (String(_prop) === "then") {
1181
+ return result.then.bind(result);
1182
+ }
1183
+ return result;
1184
+ },
1185
+ },
1186
+ ) as any;
1187
+
1188
+ return new Proxy(
1189
+ {},
1190
+ {
1191
+ get(_t, _prop) {
1192
+ if (String(_prop) === "auth") {
1193
+ return (
1194
+ auth: FnOrPromisOrPrimitive,
1195
+ ) => {
1196
+ newRootOpCollectorRef.ref.op!.setAuth(
1197
+ auth,
1198
+ );
1199
+ return resultProxy;
1200
+ };
1201
+ }
1202
+ return resultProxy[_prop];
1203
+ },
1204
+ },
1205
+ );
1097
1206
  }
1098
1207
  target[SLW_LAZY_FLAG] = true;
1099
1208
  lazy[SLW_LAZY_FLAG] = true;
@@ -1221,10 +1330,17 @@ export class SelectionWrapper<
1221
1330
  }
1222
1331
 
1223
1332
  let slw = slw_value?.[String(prop)];
1224
- const slwOpPathIsIndexAccess = !isNaN(
1225
- +target[SLW_OP_PATH]?.split(".").pop()!,
1226
- );
1227
- if (slwOpPathIsIndexAccess) {
1333
+ let slwOpPathIsIndexAccessOrInArray = false;
1334
+ let targetOpPathArr =
1335
+ target[SLW_OP_PATH]?.split(".") ?? [];
1336
+ while (targetOpPathArr.length) {
1337
+ if (!isNaN(+targetOpPathArr.pop()!)) {
1338
+ slwOpPathIsIndexAccessOrInArray = true;
1339
+ break;
1340
+ }
1341
+ }
1342
+
1343
+ if (slwOpPathIsIndexAccessOrInArray) {
1228
1344
  // index access detected, cloning
1229
1345
  slw = slw[SLW_CLONE]({
1230
1346
  SLW_OP_PATH:
@@ -1279,7 +1395,7 @@ export class SelectionWrapper<
1279
1395
  );
1280
1396
  }
1281
1397
  }
1282
- `;class m2 extends MU{collector;options;static ScalarTypeMap=new Map([["String","string"],["Int","number"],["Float","number"],["Boolean","boolean"],["ID","string"],["Date","Date"],["DateTime","Date"],["DateTimeISO","Date"],["Time","Date"],["JSON","Record<string, any>"]]);ScalarTypeMap=()=>new Map([...m2.ScalarTypeMap.entries()]);static FieldValueWrapperType=JT;static EnumTypesMapped=(D)=>{return`export interface EnumTypesMapped {
1398
+ `;class m2 extends MU{collector;options;authConfig;static ScalarTypeMap=new Map([["String","string"],["Int","number"],["Float","number"],["Boolean","boolean"],["ID","string"],["Date","Date"],["DateTime","Date"],["DateTimeISO","Date"],["Time","Date"],["JSON","Record<string, any>"]]);ScalarTypeMap=()=>new Map([...m2.ScalarTypeMap.entries()]);static FieldValueWrapperType=JT;static EnumTypesMapped=(D)=>{return`export interface EnumTypesMapped {
1283
1399
  ${Array.from(D.enumsTypes.keys()).map((F)=>F.name.replaceAll("[","").replaceAll("]","").replaceAll("!","")).filter((F,P,B)=>B.indexOf(F)===P).map((F)=>`"${F}": ${F},`).join(`
1284
1400
  `)}
1285
1401
  };`};static HelperTypes=(D)=>`
@@ -1335,11 +1451,19 @@ export class SelectionWrapper<
1335
1451
  ? A
1336
1452
  : never;
1337
1453
 
1338
- type ReplaceReturnType<T, R> = T extends (...a: any) => any
1339
- ? (
1340
- ...a: Parameters<T>
1341
- ) => ReturnType<T> extends Promise<any> ? Promise<R> : R
1342
- : never;
1454
+ type ReplaceReturnType<T, R, E = unknown> = T extends (
1455
+ ...a: any
1456
+ ) => (...a: any) => any
1457
+ ? (
1458
+ ...a: Parameters<T>
1459
+ ) => ReturnType<ReturnType<T>> extends Promise<any>
1460
+ ? Promise<R> & E
1461
+ : R & E
1462
+ : T extends (...a: any) => any
1463
+ ? (
1464
+ ...a: Parameters<T>
1465
+ ) => ReturnType<T> extends Promise<any> ? Promise<R> & E : R & E
1466
+ : never;
1343
1467
  type SLW_TPN_ToType<TNP> = TNP extends keyof ScalarTypeMapWithCustom
1344
1468
  ? ScalarTypeMapWithCustom[TNP]
1345
1469
  : TNP extends keyof ScalarTypeMapDefault
@@ -1352,6 +1476,25 @@ export class SelectionWrapper<
1352
1476
  ? T
1353
1477
  : ToTArrayWithDepth<T[], Prev[D]>;
1354
1478
  type ConvertToPromise<T, skip = 1> = skip extends 0 ? T : Promise<T>;
1479
+ type ReplacePlaceHoldersWithTNested<
1480
+ inferedResult,
1481
+ EE,
1482
+ REP extends string | number | symbol,
1483
+ > = {
1484
+ [k in keyof EE]: k extends REP
1485
+ ? EE[k] extends (...args: any) => infer R
1486
+ ? ReplaceReturnType<
1487
+ EE[k],
1488
+ inferedResult,
1489
+ {
1490
+ [kk in Exclude<REP, k>]: kk extends keyof R
1491
+ ? ReplaceReturnType<R[kk], inferedResult>
1492
+ : never;
1493
+ }
1494
+ >
1495
+ : inferedResult
1496
+ : EE[k];
1497
+ };
1355
1498
 
1356
1499
  export type SLFN<
1357
1500
  T extends object,
@@ -1367,61 +1510,30 @@ export class SelectionWrapper<
1367
1510
  SLFN_name: N,
1368
1511
  SLFN_typeNamePure: TNP,
1369
1512
  SLFN_typeArrDepth: TAD,
1370
- ) => <TT = T, FF = F, EE = E>(
1513
+ ) => <
1514
+ TT = T,
1515
+ FF = F,
1516
+ EE = E,
1517
+ inferedResult = {
1518
+ [K in keyof TT]: TT[K] extends SelectionWrapperImpl<
1519
+ infer FN,
1520
+ infer TTNP,
1521
+ infer TTAD,
1522
+ infer VT,
1523
+ infer AT
1524
+ >
1525
+ ? ToTArrayWithDepth<SLW_TPN_ToType<TTNP>, TTAD>
1526
+ : TT[K];
1527
+ },
1528
+ >(
1371
1529
  this: any,
1372
1530
  s: (selection: FF) => TT,
1373
- ) => ConvertToPromise<
1374
- ToTArrayWithDepth<
1375
- {
1376
- [K in keyof TT]: TT[K] extends SelectionWrapperImpl<
1377
- infer FN,
1378
- infer TTNP,
1379
- infer TTAD,
1380
- infer VT,
1381
- infer AT
1382
- >
1383
- ? ToTArrayWithDepth<SLW_TPN_ToType<TTNP>, TTAD>
1384
- : TT[K];
1385
- },
1386
- TAD
1387
- >,
1388
- AS_PROMISE
1389
- > & {
1390
- [k in keyof EE]: k extends REP
1391
- ? EE[k] extends (...args: any) => any
1392
- ? ReplaceReturnType<
1393
- EE[k],
1394
- ToTArrayWithDepth<
1395
- {
1396
- [K in keyof TT]: TT[K] extends SelectionWrapperImpl<
1397
- infer FN,
1398
- infer TTNP,
1399
- infer TTAD,
1400
- infer VT,
1401
- infer AT
1402
- >
1403
- ? ToTArrayWithDepth<SLW_TPN_ToType<TTNP>, TTAD>
1404
- : TT[K];
1405
- },
1406
- TAD
1407
- >
1408
- >
1409
- : ToTArrayWithDepth<
1410
- {
1411
- [K in keyof TT]: TT[K] extends SelectionWrapperImpl<
1412
- infer FN,
1413
- infer TTNP,
1414
- infer TTAD,
1415
- infer VT,
1416
- infer AT
1417
- >
1418
- ? ToTArrayWithDepth<SLW_TPN_ToType<TTNP>, TTAD>
1419
- : TT[K];
1420
- },
1421
- TAD
1422
- >
1423
- : EE[k];
1424
- };
1531
+ ) => ConvertToPromise<ToTArrayWithDepth<inferedResult, TAD>, AS_PROMISE> &
1532
+ ReplacePlaceHoldersWithTNested<
1533
+ ToTArrayWithDepth<inferedResult, TAD>,
1534
+ EE,
1535
+ REP
1536
+ >;
1425
1537
  `;static HelperFunctions=`
1426
1538
  const selectScalars = <S>(selection: Record<string, any>) =>
1427
1539
  Object.fromEntries(
@@ -1491,7 +1603,7 @@ export class SelectionWrapper<
1491
1603
  }
1492
1604
  return _SLFN as ReturnType<SLFN<T, F, N, TNP, TAD>>;
1493
1605
  };
1494
- `;constructor(D,F,P){super(D,F,P);this.collector=F,this.options=P}makeEnumType(){let D=this.originalTypeNameToTypescriptTypeNameWithoutModifiers(this.originalFullTypeName);if(this.collector.hasEnumType(this.typeMeta))return D;if(this.typeMeta.enumValues.length===0)console.warn(`Schema contains empty enum: ${this.typeMeta.name}.
1606
+ `;constructor(D,F,P,B){super(D,F,P,B);this.collector=F,this.options=P,this.authConfig=B}makeEnumType(){let D=this.originalTypeNameToTypescriptTypeNameWithoutModifiers(this.originalFullTypeName);if(this.collector.hasEnumType(this.typeMeta))return D;if(this.typeMeta.enumValues.length===0)console.warn(`Schema contains empty enum: ${this.typeMeta.name}.
1495
1607
  This is not allowed in GraphQL, but it happens. Please check your schema. Code is still generated and will work, but the type is being set to undefined.`);let F=`
1496
1608
  export type ${D} = ${this.typeMeta.enumValues.length===0?"undefined":this.typeMeta.enumValues.map((P)=>`"${P.name}"`).join(" | ")};
1497
1609
  export enum ${D}Enum {
@@ -1560,7 +1672,10 @@ export class SelectionWrapper<
1560
1672
  `:""}`;let Z=new Map,q=`
1561
1673
  export function make${D}Input(this: any) ${this.typeMeta.isUnion?"":`: ReturnTypeFrom${D}`} {
1562
1674
  return {
1563
- ${this.typeMeta.fields.map((J)=>[J,this.makeSelectionFunctionInputObjectValueForField(J,this.typeMeta.isInput?[]:[this.typeName])]).map(([J,Y])=>{return Z.set(J.name,[`${J.hasArgs?`(
1675
+ ${this.typeMeta.fields.map((J)=>[J,this.makeSelectionFunctionInputObjectValueForField(J,this.typeMeta.isInput?[]:[this.typeName])]).map(([J,Y])=>{let H=`
1676
+ $lazy: (
1677
+ ${J.hasArgs?`args: ${this.typeName}${J.name.slice(0,1).toUpperCase()}${J.name.slice(1)}Args`:""}
1678
+ ) => Promise<"T">`;return Z.set(J.name,[`${J.hasArgs?`(
1564
1679
  args: ${this.typeName}${J.name.slice(0,1).toUpperCase()}${J.name.slice(1)}Args
1565
1680
  ) =>`:""}`,`${J.type.isScalar||J.type.isEnum?`SelectionWrapperImpl<"${J.name}", "${J.type.name.replaceAll("[","").replaceAll("]","").replaceAll("!","")}", ${J.type.isList}, {}, ${J.hasArgs?`${this.typeName}${J.name.slice(0,1).toUpperCase()}${J.name.slice(1)}Args`:"undefined"}>`:`ReturnType<
1566
1681
  SLFN<
@@ -1571,11 +1686,12 @@ export class SelectionWrapper<
1571
1686
  ${J.type.isList??0}
1572
1687
  ${P?`,
1573
1688
  {
1574
- $lazy: (
1575
- ${J.hasArgs?`args: ${this.typeName}${J.name.slice(0,1).toUpperCase()}${J.name.slice(1)}Args`:""}
1576
- ) => Promise<"T">
1689
+ ${H} ${this.authConfig?`& {
1690
+ auth: (auth: FnOrPromisOrPrimitive) => Promise<"T">;
1691
+ }`:""};
1692
+ ${this.authConfig?`auth: (auth: FnOrPromisOrPrimitive) => Promise<"T"> & {${H}}`:""}
1577
1693
  },
1578
- "$lazy",
1694
+ "$lazy" ${this.authConfig?'| "auth"':""},
1579
1695
  AS_PROMISE
1580
1696
  `:""}
1581
1697
  >
@@ -1617,29 +1733,17 @@ export class SelectionWrapper<
1617
1733
  } as const;`:""}
1618
1734
  export function _makeRootOperationInput(this: any) {
1619
1735
  return {
1620
- ${P&&D.types.has(P)?`query: ${P}Selection.bind({
1621
- collector: this,
1622
- isRootType: "Query",
1623
- }),`:""}
1624
- ${B&&D.types.has(B)?`mutation: ${B}Selection.bind({
1625
- collector: this,
1626
- isRootType: "Mutation",
1627
- }),`:""}
1628
- ${Z&&D.types.has(Z)?`subscription: ${Z}Selection.bind({
1629
- collector: this,
1630
- isRootType: "Subscription",
1631
- }),`:""}
1736
+ ${q.filter((Y)=>D.types.has(Y)).map((Y)=>{return`${Y}: ${Y}Selection.bind({
1737
+ collector: this,
1738
+ isRootType: "${Y}",
1739
+ }),`}).join(`
1740
+ `)}
1632
1741
 
1633
1742
  ${X?.length?`
1634
1743
  $directives,`:""}
1635
1744
  } as const;
1636
1745
  };
1637
1746
 
1638
- ${F?`type __AuthenticationArg__ =
1639
- | string
1640
- | { [key: string]: string }
1641
- | (() => string | { [key: string]: string })
1642
- | (() => Promise<string | { [key: string]: string }>);`:""}
1643
1747
  function __client__ <
1644
1748
  T extends object,
1645
1749
  F extends ReturnType<typeof _makeRootOperationInput>>(
@@ -1684,103 +1788,53 @@ export class SelectionWrapper<
1684
1788
  ? _TR
1685
1789
  : Promise<_TR>;
1686
1790
 
1687
- let headers: Record<string, string> | undefined = undefined;
1688
- let returnValue: finalReturnTypeBasedOnIfHasLazyPromises;
1689
-
1690
- if (Object.values(result).some((v) => typeof v !== "function")) {
1691
- returnValue = new Promise((resolve, reject) => {
1692
- ${F?`
1693
- const doExecute = () => {
1694
- root.execute(headers)
1695
- .then(() => {
1696
- resolve(result);
1697
- })
1698
- .catch(reject);
1699
- }
1700
- if (typeof RootOperation[OPTIONS]._auth_fn === "function") {
1701
- const tokenOrPromise = RootOperation[OPTIONS]._auth_fn();
1702
- if (tokenOrPromise instanceof Promise) {
1703
- tokenOrPromise.then((t) => {
1704
- if (typeof t === "string")
1705
- headers = { "${F.headerName}": t };
1706
- else headers = t;
1707
-
1708
- doExecute();
1709
- });
1710
- }
1711
- else if (typeof tokenOrPromise === "string") {
1712
- headers = { "${F.headerName}": tokenOrPromise };
1713
-
1714
- doExecute();
1715
- } else {
1716
- headers = tokenOrPromise;
1717
-
1718
- doExecute();
1719
- }
1720
- }
1721
- else {
1722
- doExecute();
1723
- }
1724
- `:`
1725
- root.execute(headers)
1726
- .then(() => {
1727
- resolve(result);
1728
- })
1729
- .catch(reject);
1730
- `}
1731
- }) as finalReturnTypeBasedOnIfHasLazyPromises;
1732
- }
1733
- else {
1734
- returnValue = result as finalReturnTypeBasedOnIfHasLazyPromises;
1735
- }
1736
-
1737
- ${F?`
1738
- Object.defineProperty(returnValue, "auth", {
1739
- enumerable: false,
1740
- get: function () {
1741
- return function (
1742
- auth: __AuthenticationArg__,
1743
- ) {
1744
- if (typeof auth === "string") {
1745
- headers = { "${F.headerName}": auth };
1746
- } else if (typeof auth === "function") {
1747
- const tokenOrPromise = auth();
1748
- if (tokenOrPromise instanceof Promise) {
1749
- return tokenOrPromise.then((t) => {
1750
- if (typeof t === "string")
1751
- headers = { "${F.headerName}": t };
1752
- else headers = t;
1753
-
1754
- return returnValue;
1791
+ const resultProxy = new Proxy(
1792
+ {},
1793
+ {
1794
+ get(_t, _prop) {
1795
+ const rAtProp = result[_prop as keyof T];
1796
+ if (typeof rAtProp === "function") {
1797
+ return rAtProp;
1798
+ }
1799
+ const promise = new Promise((resolve, reject) => {
1800
+ root.execute()
1801
+ .catch(reject)
1802
+ .then(() => {
1803
+ resolve(rAtProp);
1755
1804
  });
1756
- }
1757
- if (typeof tokenOrPromise === "string") {
1758
- headers = { "${F.headerName}": tokenOrPromise };
1759
- } else {
1760
- headers = tokenOrPromise;
1761
- }
1762
- } else {
1763
- headers = auth;
1805
+ });
1806
+ if (String(_prop) === "then") {
1807
+ return promise.then.bind(promise);
1764
1808
  }
1765
-
1766
- return returnValue;
1767
- };
1809
+ return promise;
1810
+ },
1768
1811
  },
1769
- });
1812
+ ) as any;
1770
1813
 
1771
- return returnValue as finalReturnTypeBasedOnIfHasLazyPromises & {
1814
+ return ${F?`new Proxy(
1815
+ {},
1816
+ {
1817
+ get(_t, _prop) {
1818
+ if (String(_prop) === "auth") {
1819
+ return (auth: FnOrPromisOrPrimitive) => {
1820
+ root.op!.setAuth(auth);
1821
+ return resultProxy;
1822
+ };
1823
+ }
1824
+ return resultProxy[_prop];
1825
+ },
1826
+ },
1827
+ )`:"resultProxy"} as finalReturnTypeBasedOnIfHasLazyPromises & {
1772
1828
  auth: (
1773
- auth: __AuthenticationArg__,
1829
+ auth: FnOrPromisOrPrimitive,
1774
1830
  ) => finalReturnTypeBasedOnIfHasLazyPromises;
1775
1831
  };
1776
- `:`
1777
- return returnValue;
1778
- `}
1779
1832
  };
1780
1833
 
1781
1834
  const __init__ = (options: {
1782
- ${F?"auth?: __AuthenticationArg__;":""}
1835
+ ${F?"auth?: FnOrPromisOrPrimitive;":""}
1783
1836
  headers?: { [key: string]: string };
1837
+ fetcher?: (request: Request) => Promise<Response>;
1784
1838
  scalars?: {
1785
1839
  [key in keyof ScalarTypeMapDefault]?: (
1786
1840
  v: string,
@@ -1810,6 +1864,9 @@ export class SelectionWrapper<
1810
1864
  ...options.headers,
1811
1865
  };
1812
1866
  }
1867
+ if (options.fetcher) {
1868
+ RootOperation[OPTIONS].fetcher = options.fetcher;
1869
+ }
1813
1870
  if (options.scalars) {
1814
1871
  RootOperation[OPTIONS].scalars = {
1815
1872
  ...RootOperation[OPTIONS].scalars,
@@ -1825,12 +1882,12 @@ export class SelectionWrapper<
1825
1882
  const _makeOperationShortcut = <O extends ${q.map((Y)=>`"${Y}"`).join(" | ")}>(
1826
1883
  operation: O,
1827
1884
  field: Exclude<
1828
- typeof operation extends "${q[0]}"
1885
+ ${q.length===1?`keyof ReturnTypeFrom${q[0]}Selection,`:`typeof operation extends "${q[0]}"
1829
1886
  ? keyof ReturnTypeFrom${q[0]}Selection
1830
1887
  : ${q.length>2?`
1831
1888
  typeof operation extends "${q[1]}"
1832
1889
  ? keyof ReturnTypeFrom${q[1]}Selection
1833
- : keyof ReturnTypeFrom${q[2]}Selection,`:`keyof ReturnTypeFrom${q[1]}Selection,`}
1890
+ : keyof ReturnTypeFrom${q[2]}Selection,`:`keyof ReturnTypeFrom${q[1]}Selection,`}`}
1834
1891
  "$fragment" | "$scalars"
1835
1892
  >,
1836
1893
  ) => {
@@ -1847,7 +1904,7 @@ export class SelectionWrapper<
1847
1904
  "$fragment" | "$scalars"
1848
1905
  >]`).join(" | ")};
1849
1906
 
1850
- if (operation === "${q[0]}") {
1907
+ ${q.length>1?`if (operation === "${q[0]}") {`:""}
1851
1908
  fieldFn =
1852
1909
  make${q[0]}SelectionInput.bind(rootRef)()[
1853
1910
  field as Exclude<
@@ -1855,7 +1912,7 @@ export class SelectionWrapper<
1855
1912
  "$fragment" | "$scalars"
1856
1913
  >
1857
1914
  ];
1858
- } else ${q.length>2?`if (operation === "${q[1]}")`:""}{
1915
+ ${q.length>1?`} else ${q.length>2?`if (operation === "${q[1]}")`:""}`:""}${q.length>1?`{
1859
1916
  fieldFn =
1860
1917
  make${q[1]}SelectionInput.bind(rootRef)()[
1861
1918
  field as Exclude<
@@ -1863,7 +1920,7 @@ export class SelectionWrapper<
1863
1920
  "$fragment" | "$scalars"
1864
1921
  >
1865
1922
  ];
1866
- }
1923
+ }`:""}
1867
1924
  ${q.length>2?`else {
1868
1925
  fieldFn =
1869
1926
  make${q[2]}SelectionInput.bind(rootRef)()[
@@ -1927,28 +1984,24 @@ export class SelectionWrapper<
1927
1984
  opSlw[ROOT_OP_COLLECTOR] = rootRef;
1928
1985
  // access the keys of the proxy object, to register operations
1929
1986
  (rootSlw as any)[field as any];
1930
-
1931
- return new Proxy(
1987
+
1988
+ const resultProxy = new Proxy(
1932
1989
  {},
1933
1990
  {
1934
1991
  get(_t, _prop) {
1935
1992
  if (String(_prop) === "$lazy") {
1936
- return (fieldSlw as any)[_prop].bind({
1993
+ return (fieldSlw as any)["$lazy"].bind({
1937
1994
  parentSlw: opSlw,
1938
1995
  key: field,
1939
1996
  });
1940
1997
  } else {
1941
- const result = new Promise(
1942
- (resolve, reject) => {
1943
- root.execute({})
1944
- .then(() => {
1945
- resolve(
1946
- (rootSlw as any)[field],
1947
- );
1948
- })
1949
- .catch(reject);
1950
- },
1951
- );
1998
+ const result = new Promise((resolve, reject) => {
1999
+ root.execute()
2000
+ .catch(reject)
2001
+ .then(() => {
2002
+ resolve((rootSlw as any)[field]);
2003
+ });
2004
+ });
1952
2005
  if (String(_prop) === "then") {
1953
2006
  return result.then.bind(result);
1954
2007
  }
@@ -1956,7 +2009,22 @@ export class SelectionWrapper<
1956
2009
  }
1957
2010
  },
1958
2011
  },
1959
- );
2012
+ ) as any;
2013
+
2014
+ return ${F?`new Proxy(
2015
+ {},
2016
+ {
2017
+ get(_t, _prop) {
2018
+ if (String(_prop) === "auth") {
2019
+ return (auth: FnOrPromisOrPrimitive) => {
2020
+ root.op!.setAuth(auth);
2021
+ return resultProxy;
2022
+ };
2023
+ }
2024
+ return resultProxy[_prop];
2025
+ },
2026
+ },
2027
+ )`:"resultProxy"};
1960
2028
  };
1961
2029
 
1962
2030
  // if the fieldFn is the SLFN subselection function without an (args) => .. wrapper
@@ -1998,27 +2066,23 @@ export class SelectionWrapper<
1998
2066
  // access the keys of the proxy object, to register operations
1999
2067
  (rootSlw as any)[field as any];
2000
2068
 
2001
- return new Proxy(
2069
+ const resultProxy = new Proxy(
2002
2070
  {},
2003
2071
  {
2004
2072
  get(_t, _prop) {
2005
2073
  if (String(_prop) === "$lazy") {
2006
- return (fieldSlw as any)[_prop].bind({
2074
+ return (fieldSlw as any)["$lazy"].bind({
2007
2075
  parentSlw: opSlw,
2008
2076
  key: field,
2009
2077
  });
2010
2078
  } else {
2011
- const result = new Promise(
2012
- (resolve, reject) => {
2013
- root.execute({})
2014
- .then(() => {
2015
- resolve(
2016
- (rootSlw as any)[field],
2017
- );
2018
- })
2019
- .catch(reject);
2020
- },
2021
- );
2079
+ const result = new Promise((resolve, reject) => {
2080
+ root.execute()
2081
+ .catch(reject)
2082
+ .then(() => {
2083
+ resolve((rootSlw as any)[field]);
2084
+ });
2085
+ });
2022
2086
  if (String(_prop) === "then") {
2023
2087
  return result.then.bind(result);
2024
2088
  }
@@ -2026,7 +2090,22 @@ export class SelectionWrapper<
2026
2090
  }
2027
2091
  },
2028
2092
  },
2029
- );
2093
+ ) as any;
2094
+
2095
+ return ${F?`new Proxy(
2096
+ {},
2097
+ {
2098
+ get(_t, _prop) {
2099
+ if (String(_prop) === "auth") {
2100
+ return (auth: FnOrPromisOrPrimitive) => {
2101
+ root.op!.setAuth(auth);
2102
+ return resultProxy;
2103
+ };
2104
+ }
2105
+ return resultProxy[_prop];
2106
+ },
2107
+ },
2108
+ )`:"resultProxy"};
2030
2109
  }
2031
2110
  };
2032
2111
 
@@ -2072,7 +2151,19 @@ export class SelectionWrapper<
2072
2151
  ? ToTArrayWithDepth<SLW_TPN_ToType<TTNP>, TTAD> & {
2073
2152
  $lazy: () => Promise<
2074
2153
  ToTArrayWithDepth<SLW_TPN_ToType<TTNP>, TTAD>
2075
- >;
2154
+ > ${F?`& {
2155
+ auth: (
2156
+ auth: FnOrPromisOrPrimitive,
2157
+ ) => Promise<
2158
+ ToTArrayWithDepth<SLW_TPN_ToType<TTNP>, TTAD>
2159
+ >
2160
+ }
2161
+ `:""};
2162
+ ${F?`auth: (token: FnOrPromisOrPrimitive) => Promise<"T"> & {
2163
+ $lazy: () => Promise<
2164
+ ToTArrayWithDepth<SLW_TPN_ToType<TTNP>, TTAD>
2165
+ >;
2166
+ };`:""}
2076
2167
  }
2077
2168
  : ReturnType<typeof make${Y}SelectionInput>[field]extends (
2078
2169
  args: infer A,
@@ -2091,11 +2182,21 @@ export class SelectionWrapper<
2091
2182
  SLW_TPN_ToType<_TTNP>,
2092
2183
  _TTAD
2093
2184
  > & {
2094
- $lazy: (
2095
- args: _A,
2096
- ) => Promise<
2185
+ $lazy: (args: _A) => Promise<
2097
2186
  ToTArrayWithDepth<SLW_TPN_ToType<_TTNP>, _TTAD>
2098
- >;
2187
+ > ${F?`& {
2188
+ auth: (
2189
+ auth: FnOrPromisOrPrimitive,
2190
+ ) => Promise<
2191
+ ToTArrayWithDepth<SLW_TPN_ToType<_TTNP>, _TTAD>
2192
+ >;
2193
+ }
2194
+ `:""};
2195
+ ${F?`auth: (token: FnOrPromisOrPrimitive) => Promise<"T"> & {
2196
+ $lazy: () => Promise<
2197
+ ToTArrayWithDepth<SLW_TPN_ToType<_TTNP>, _TTAD>
2198
+ >;
2199
+ };`:""}
2099
2200
  }
2100
2201
  : ReturnTypeFrom${Y}SelectionRetTypes<1>[field];
2101
2202
  };`).join(`
@@ -3695,7 +3796,7 @@ export class SelectionWrapper<
3695
3796
  export default __client__ as typeof __client__ & {
3696
3797
  init: typeof __init__;
3697
3798
  };
3698
- `}}var k1={};$U(k1,{Generator:()=>EU});var HT=(D,F,P,B)=>{let q=F?.includes("@typedef")?F?.match(/@typedef\s*{(.*)}/)?.[1]:void 0,X={name:D,description:F,isScalar:!0,scalarTSType:q??P,isEnum:!1,isObject:!1,isUnion:!1,isList:0,isNonNull:!1,fields:[],possibleTypes:[],inputFields:[],isInput:!1,enumValues:[],isInterface:!1,isQuery:!1,isMutation:!1,isSubscription:!1};return X.ofType=X,B.addType(X),B.addCustomScalar(X),X},UT=(D,F,P)=>{let B={types:[],directives:[],query:[],mutation:[],subscription:[]};for(let Y in D.getTypeMap()){if(!F.includeSchemaDefinition){if(["__Schema","__Type","__TypeKind","__Field","__InputValue","__EnumValue","__Directive"].includes(Y))continue}let H=D.getTypeMap()[Y];if(H instanceof MD.GraphQLScalarType){if(["String","Int","Float","Boolean","ID","Date","DateTime","DateTimeISO","Time","JSON"].includes(Y))continue;B.types.push(HT(Y,H.description??void 0,"any",P))}}let Z=P.customScalars.size>0,q=D.getQueryType();if(q)for(let Y of Object.values(q.getFields()))B.query.push(T7(D,Y,"query",F,P));let X=D.getMutationType();if(X)for(let Y of Object.values(X.getFields()))B.mutation.push(T7(D,Y,"mutation",F,P));let J=D.getSubscriptionType();if(J)for(let Y of Object.values(J.getFields()))B.subscription.push(T7(D,Y,"subscription",F,P));for(let Y in D.getTypeMap()){if(!F.includeSchemaDefinition){if(["__Schema","__Type","__TypeKind","__Field","__InputValue","__EnumValue","__Directive"].includes(Y))continue}let H=D.getTypeMap()[Y];if(MD.isObjectType(H)||Z&&MD.isInputObjectType(H)||MD.isInterfaceType(H))B.types.push(x1(D,H,F,P))}for(let Y of D.getDirectives())B.directives.push(WT(D,Y,F,P));return B},T7=(D,F,P,B,Z)=>{let q={name:F.name,description:F.description??void 0,operation:P,args:[],type:x1(D,F.type,B,Z)};for(let X in F.args){let J=F.args[X];q.args.push(w3(D,J,B,Z))}return q},w3=(D,F,P,B)=>{return{name:F.name,hasArgs:!1,args:[],description:F.description??void 0,type:x1(D,F.type,P,B)}},x1=(D,F,P,B)=>{let Z=MD.getNamedType(F),q={name:F.toString(),description:Z.description??void 0,isList:F.toString().split("[").length-1,isNonNull:F.toString().endsWith("!"),isScalar:Z instanceof MD.GraphQLScalarType,isEnum:Z instanceof MD.GraphQLEnumType,isInput:Z instanceof MD.GraphQLInputObjectType,isInterface:Z instanceof MD.GraphQLInterfaceType,isObject:Z instanceof MD.GraphQLObjectType,isUnion:Z instanceof MD.GraphQLUnionType,isQuery:!1,isMutation:!1,isSubscription:!1,fields:[],possibleTypes:[],enumValues:[],inputFields:[]};if(B.hasType(q.name))return B.getType(q.name);else B.addType(q);if(q.ofType=q,q.isEnum)for(let X of Z.getValues())q.enumValues.push({name:X.name,description:X.description??void 0});if(q.isInput){let X=Z.getFields();for(let J in X)q.inputFields.push(w3(D,X[J],P,B))}if(q.isInterface){let X=Z.getFields();for(let J in X)q.fields.push(IU(D,X[J],P,B))}if(q.isObject){let X=Z.getFields();for(let J in X)q.fields.push(IU(D,X[J],P,B))}if(q.isUnion)for(let X of Z.getTypes())q.possibleTypes.push(x1(D,X,P,B));if(Z instanceof MD.GraphQLObjectType){if(Z.name==="Query")q.isQuery=!0;else if(Z.name==="Mutation")q.isMutation=!0;else if(Z.name==="Subscription")q.isSubscription=!0}return B.addType(q),q},IU=(D,F,P,B)=>{let Z={name:F.name,description:F.description??void 0,hasArgs:Object.keys(F.args).length>0,args:[],type:x1(D,F.type,P,B)};for(let q in F.args){let X=F.args[q];Z.args.push(w3(D,X,P,B))}return Z},WT=(D,F,P,B)=>{let Z={name:F.name,description:F.description??void 0,locations:F.locations,args:[]};for(let q in F.args){let X=F.args[q];Z.args.push(w3(D,X,P,B))}return B.addType({name:`Directive_${F.name}`,description:F.description??void 0,isList:0,isNonNull:!1,isScalar:!1,isEnum:!1,isInput:!1,isInterface:!1,isObject:!1,isUnion:!1,isQuery:!1,isMutation:!1,isSubscription:!1,fields:[],possibleTypes:[],enumValues:[],inputFields:[],isDirective:Z}),Z};class KU{QueryTypeName;MutationTypeName;SubscriptionTypeName;OperationTypeNames;constructor(D,F,P){this.QueryTypeName=D,this.MutationTypeName=F,this.SubscriptionTypeName=P,this.OperationTypeNames=[D,F,P].filter((B)=>B)}_types=new Map;get types(){return this._types}addType(D){this._types.set(D.name,D)}hasType(D){return this._types.has(D)}getType(D){return this._types.get(D)}_customScalars=new Map;get customScalars(){return this._customScalars}addCustomScalar(D){this._customScalars.set(D.name,D)}hasCustomScalar(D){return this._customScalars.has(D)}getCustomScalar(D){return this._customScalars.get(D)}removeCustomScalar(D){this._customScalars.delete(D)}_enumsTypes=new Map;get enumsTypes(){return this._enumsTypes}addEnumType(D,F){this._enumsTypes.set(D,F)}hasEnumType(D){if(!D)return!1;return this._enumsTypes.has(D)}getEnumType(D){return this._enumsTypes.get(D)}_argumentTypes=new Map;get argumentTypes(){return this._argumentTypes}addArgumentType(D,F){this._argumentTypes.set(D,F)}hasArgumentType(D){return this._argumentTypes.has(D)}getArgumentType(D){return this._argumentTypes.get(D)}_argumentMeta=new Map;get argumentMeta(){return this._argumentMeta}addArgumentMeta(D,F){this._argumentMeta.set(D,F)}hasArgumentMeta(D){return this._argumentMeta.has(D)}getArgumentMeta(D){return this._argumentMeta.get(D)}_directivesFunctions=new Map;get directivesFunctions(){return this._directivesFunctions}addDirectiveFunction(D,F){this._directivesFunctions.set(D,F)}hasDirectiveFunction(D){return this._directivesFunctions.has(D)}getDirectiveFunction(D){return this._directivesFunctions.get(D)}_selectionTypes=new Map;get selectionTypes(){return this._selectionTypes}addSelectionType(D,F){this._selectionTypes.set(D,F)}hasSelectionType(D){if(!D)return!1;return this._selectionTypes.has(D)}getSelectionType(D){return this._selectionTypes.get(D)}_selectionFunctions=new Map;get selectionFunctions(){return this._selectionFunctions}addSelectionFunction(D,F){this._selectionFunctions.set(D,F)}hasSelectionFunction(D){if(!D)return!1;return this._selectionFunctions.has(D)}getSelectionFunction(D){return this._selectionFunctions.get(D)}}class EU{Codegen;constructor(D){this.Codegen=D}async generate({schema:D,options:F,authConfig:P}){let B=D.getQueryType()?.name,Z=D.getMutationType()?.name,q=D.getSubscriptionType()?.name,X=new KU(B,Z,q);UT(D,F,X);for(let[Y,H]of X.types.entries()){if(!H.isEnum)continue;new this.Codegen(Y,X,F).makeEnumType()}for(let[Y,H]of X.types.entries()){if(!H.isInput)continue;new this.Codegen(Y,X,F).makeSelectionType()}for(let[Y,H]of X.types.entries()){if(!H.isDirective?.locations.some((W)=>[L3.DirectiveLocation.FIELD,L3.DirectiveLocation.FRAGMENT_SPREAD,L3.DirectiveLocation.INLINE_FRAGMENT].includes(W)))continue;new this.Codegen(Y,X,F).makeDirective()}for(let[Y,H]of X.types.entries()){if(H.isScalar||H.isInput||H.isEnum||H.isDirective)continue;new this.Codegen(Y,X,F).makeSelectionType(),new this.Codegen(Y,X,F).makeSelectionFunction()}return[this.Codegen.FieldValueWrapperType,this.Codegen.HelperTypes(Array.from(X.customScalars.values())),this.Codegen.HelperFunctions,...[...X.enumsTypes.entries()].map(([Y,H])=>H).filter((Y,H,W)=>W.indexOf(Y)===H),...[...X.argumentTypes.entries()].map(([Y,H])=>H).filter((Y,H,W)=>W.indexOf(Y)===H),...[...X.argumentMeta.entries()].map(([Y,H])=>H).filter((Y,H,W)=>W.indexOf(Y)===H),...[...X.selectionTypes.entries()].filter(([Y])=>Y.isInput||X.customScalars.size>0&&Y.isObject).map(([Y,H])=>H).filter((Y,H,W)=>W.indexOf(Y)===H),this.Codegen.EnumTypesMapped(X),...[...X.selectionFunctions.entries()].filter(([Y])=>!Y.isScalar&&!Y.isEnum&&!Y.isInput).map(([Y,H])=>H),...[...X.directivesFunctions.entries()].map(([Y,H])=>H),this.Codegen.makeRootOperationFunction(X,P)].join(`
3799
+ `}}var k1={};$U(k1,{Generator:()=>EU});var HT=(D,F,P,B)=>{let q=F?.includes("@typedef")?F?.match(/@typedef\s*{(.*)}/)?.[1]:void 0,X={name:D,description:F,isScalar:!0,scalarTSType:q??P,isEnum:!1,isObject:!1,isUnion:!1,isList:0,isNonNull:!1,fields:[],possibleTypes:[],inputFields:[],isInput:!1,enumValues:[],isInterface:!1,isQuery:!1,isMutation:!1,isSubscription:!1};return X.ofType=X,B.addType(X),B.addCustomScalar(X),X},UT=(D,F,P)=>{let B={types:[],directives:[],query:[],mutation:[],subscription:[]};for(let Y in D.getTypeMap()){if(!F.includeSchemaDefinition){if(["__Schema","__Type","__TypeKind","__Field","__InputValue","__EnumValue","__Directive"].includes(Y))continue}let H=D.getTypeMap()[Y];if(H instanceof MD.GraphQLScalarType){if(["String","Int","Float","Boolean","ID","Date","DateTime","DateTimeISO","Time","JSON"].includes(Y))continue;B.types.push(HT(Y,H.description??void 0,"any",P))}}let Z=P.customScalars.size>0,q=D.getQueryType();if(q)for(let Y of Object.values(q.getFields()))B.query.push(T7(D,Y,"query",F,P));let X=D.getMutationType();if(X)for(let Y of Object.values(X.getFields()))B.mutation.push(T7(D,Y,"mutation",F,P));let J=D.getSubscriptionType();if(J)for(let Y of Object.values(J.getFields()))B.subscription.push(T7(D,Y,"subscription",F,P));for(let Y in D.getTypeMap()){if(!F.includeSchemaDefinition){if(["__Schema","__Type","__TypeKind","__Field","__InputValue","__EnumValue","__Directive"].includes(Y))continue}let H=D.getTypeMap()[Y];if(MD.isObjectType(H)||Z&&MD.isInputObjectType(H)||MD.isInterfaceType(H))B.types.push(x1(D,H,F,P))}for(let Y of D.getDirectives())B.directives.push(WT(D,Y,F,P));return B},T7=(D,F,P,B,Z)=>{let q={name:F.name,description:F.description??void 0,operation:P,args:[],type:x1(D,F.type,B,Z)};for(let X in F.args){let J=F.args[X];q.args.push(w3(D,J,B,Z))}return q},w3=(D,F,P,B)=>{return{name:F.name,hasArgs:!1,args:[],description:F.description??void 0,type:x1(D,F.type,P,B)}},x1=(D,F,P,B)=>{let Z=MD.getNamedType(F),q={name:F.toString(),description:Z.description??void 0,isList:F.toString().split("[").length-1,isNonNull:F.toString().endsWith("!"),isScalar:Z instanceof MD.GraphQLScalarType,isEnum:Z instanceof MD.GraphQLEnumType,isInput:Z instanceof MD.GraphQLInputObjectType,isInterface:Z instanceof MD.GraphQLInterfaceType,isObject:Z instanceof MD.GraphQLObjectType,isUnion:Z instanceof MD.GraphQLUnionType,isQuery:!1,isMutation:!1,isSubscription:!1,fields:[],possibleTypes:[],enumValues:[],inputFields:[]};if(B.hasType(q.name))return B.getType(q.name);else B.addType(q);if(q.ofType=q,q.isEnum)for(let X of Z.getValues())q.enumValues.push({name:X.name,description:X.description??void 0});if(q.isInput){let X=Z.getFields();for(let J in X)q.inputFields.push(w3(D,X[J],P,B))}if(q.isInterface){let X=Z.getFields();for(let J in X)q.fields.push(IU(D,X[J],P,B))}if(q.isObject){let X=Z.getFields();for(let J in X)q.fields.push(IU(D,X[J],P,B))}if(q.isUnion)for(let X of Z.getTypes())q.possibleTypes.push(x1(D,X,P,B));if(Z instanceof MD.GraphQLObjectType){if(Z.name==="Query")q.isQuery=!0;else if(Z.name==="Mutation")q.isMutation=!0;else if(Z.name==="Subscription")q.isSubscription=!0}return B.addType(q),q},IU=(D,F,P,B)=>{let Z={name:F.name,description:F.description??void 0,hasArgs:Object.keys(F.args).length>0,args:[],type:x1(D,F.type,P,B)};for(let q in F.args){let X=F.args[q];Z.args.push(w3(D,X,P,B))}return Z},WT=(D,F,P,B)=>{let Z={name:F.name,description:F.description??void 0,locations:F.locations,args:[]};for(let q in F.args){let X=F.args[q];Z.args.push(w3(D,X,P,B))}return B.addType({name:`Directive_${F.name}`,description:F.description??void 0,isList:0,isNonNull:!1,isScalar:!1,isEnum:!1,isInput:!1,isInterface:!1,isObject:!1,isUnion:!1,isQuery:!1,isMutation:!1,isSubscription:!1,fields:[],possibleTypes:[],enumValues:[],inputFields:[],isDirective:Z}),Z};class KU{QueryTypeName;MutationTypeName;SubscriptionTypeName;OperationTypeNames;constructor(D,F,P){this.QueryTypeName=D,this.MutationTypeName=F,this.SubscriptionTypeName=P,this.OperationTypeNames=[D,F,P].filter((B)=>B)}_types=new Map;get types(){return this._types}addType(D){this._types.set(D.name,D)}hasType(D){return this._types.has(D)}getType(D){return this._types.get(D)}_customScalars=new Map;get customScalars(){return this._customScalars}addCustomScalar(D){this._customScalars.set(D.name,D)}hasCustomScalar(D){return this._customScalars.has(D)}getCustomScalar(D){return this._customScalars.get(D)}removeCustomScalar(D){this._customScalars.delete(D)}_enumsTypes=new Map;get enumsTypes(){return this._enumsTypes}addEnumType(D,F){this._enumsTypes.set(D,F)}hasEnumType(D){if(!D)return!1;return this._enumsTypes.has(D)}getEnumType(D){return this._enumsTypes.get(D)}_argumentTypes=new Map;get argumentTypes(){return this._argumentTypes}addArgumentType(D,F){this._argumentTypes.set(D,F)}hasArgumentType(D){return this._argumentTypes.has(D)}getArgumentType(D){return this._argumentTypes.get(D)}_argumentMeta=new Map;get argumentMeta(){return this._argumentMeta}addArgumentMeta(D,F){this._argumentMeta.set(D,F)}hasArgumentMeta(D){return this._argumentMeta.has(D)}getArgumentMeta(D){return this._argumentMeta.get(D)}_directivesFunctions=new Map;get directivesFunctions(){return this._directivesFunctions}addDirectiveFunction(D,F){this._directivesFunctions.set(D,F)}hasDirectiveFunction(D){return this._directivesFunctions.has(D)}getDirectiveFunction(D){return this._directivesFunctions.get(D)}_selectionTypes=new Map;get selectionTypes(){return this._selectionTypes}addSelectionType(D,F){this._selectionTypes.set(D,F)}hasSelectionType(D){if(!D)return!1;return this._selectionTypes.has(D)}getSelectionType(D){return this._selectionTypes.get(D)}_selectionFunctions=new Map;get selectionFunctions(){return this._selectionFunctions}addSelectionFunction(D,F){this._selectionFunctions.set(D,F)}hasSelectionFunction(D){if(!D)return!1;return this._selectionFunctions.has(D)}getSelectionFunction(D){return this._selectionFunctions.get(D)}}class EU{Codegen;constructor(D){this.Codegen=D}async generate({schema:D,options:F,authConfig:P}){let B=D.getQueryType()?.name,Z=D.getMutationType()?.name,q=D.getSubscriptionType()?.name,X=new KU(B,Z,q);UT(D,F,X);for(let[Y,H]of X.types.entries()){if(!H.isEnum)continue;new this.Codegen(Y,X,F,P).makeEnumType()}for(let[Y,H]of X.types.entries()){if(!H.isInput)continue;new this.Codegen(Y,X,F,P).makeSelectionType()}for(let[Y,H]of X.types.entries()){if(!H.isDirective?.locations.some((W)=>[L3.DirectiveLocation.FIELD,L3.DirectiveLocation.FRAGMENT_SPREAD,L3.DirectiveLocation.INLINE_FRAGMENT].includes(W)))continue;new this.Codegen(Y,X,F,P).makeDirective()}for(let[Y,H]of X.types.entries()){if(H.isScalar||H.isInput||H.isEnum||H.isDirective)continue;new this.Codegen(Y,X,F,P).makeSelectionType(),new this.Codegen(Y,X,F,P).makeSelectionFunction()}return[this.Codegen.FieldValueWrapperType,this.Codegen.HelperTypes(Array.from(X.customScalars.values())),this.Codegen.HelperFunctions,...[...X.enumsTypes.entries()].map(([Y,H])=>H).filter((Y,H,W)=>W.indexOf(Y)===H),...[...X.argumentTypes.entries()].map(([Y,H])=>H).filter((Y,H,W)=>W.indexOf(Y)===H),...[...X.argumentMeta.entries()].map(([Y,H])=>H).filter((Y,H,W)=>W.indexOf(Y)===H),...[...X.selectionTypes.entries()].filter(([Y])=>Y.isInput||X.customScalars.size>0&&Y.isObject).map(([Y,H])=>H).filter((Y,H,W)=>W.indexOf(Y)===H),this.Codegen.EnumTypesMapped(X),...[...X.selectionFunctions.entries()].filter(([Y])=>!Y.isScalar&&!Y.isEnum&&!Y.isInput).map(([Y,H])=>H),...[...X.directivesFunctions.entries()].map(([Y,H])=>H),this.Codegen.makeRootOperationFunction(X,P)].join(`
3699
3800
  `)}}var f1={};$U(f1,{Generator:()=>CU});var SD=(D,F="$")=>{let P="";for(let B of D.filter(Boolean))P+=B.charAt(0).toUpperCase()+B.slice(1)+F;return P.slice(0,P.length-F.length).replaceAll("-","_").replaceAll(".","_")},OT=(D,F,P)=>{let B={types:[],operations:[],customScalars:[]};for(let[Z,q]of Object.entries(D?.components?.schemas??{}))B.types.push(lD(D,Z,q,"schemas",{isNonNull:!1},P));for(let[Z,q]of Object.entries(D?.paths??{})){if("$ref"in q)continue;for(let[X,J]of Object.entries(q)){if(!J)continue;if("$ref"in J){console.warn(`TODO: Handle $ref in methodValue for ${Z}`);continue}let Y=GT(D,Z,X,J,F,P);if(!Y)continue;B.operations.push(Y)}}return B},N7=(D,F,P,B)=>{let Z={name:D,description:F,isScalar:!0,scalarTSType:P,isEnum:!1,isObject:!1,isUnion:!1,isList:0,isNonNull:!1,fields:[],possibleTypes:[],inputFields:[],isInput:!1,enumValues:[]};return Z.ofType=Z,B.addType(Z),B.addCustomScalar(Z),Z},u7=(D,F)=>{let P=F?.isInput??D.isInput,B=F?.isNonNull??D.isNonNull;return`${D.name.slice(0,P&&B?-1:void 0)}${P?`${B?"Input!":"Input"}`:""}`.replaceAll("-","_")},_7=(D,F)=>{if(D.isInput||D.isScalar)return D;let P=u7(D,{isInput:!0}),B={...D,name:P,isInput:!0,isObject:!1,inputFields:D.fields.map((Z)=>({...Z,location:"$",type:_7(Z.type,F)})),fields:[],possibleTypes:D.possibleTypes.map((Z)=>_7(Z,F))};return B.ofType=B,F.addType(B),B},lD=(D,F,P,B,Z,q)=>{if("ofType"in P)return P;if("$ref"in P){let H=P.$ref.split("/");H.shift();let W=H.shift(),U=H.shift(),O=H.shift(),z=D[W]?.[U]?.[O];if(z)return lD(D,SD([Z.operationResponseType?"":F,O]),z,U,{isNonNull:Z.isNonNull},q);throw new Error(`Reference ${P.$ref} not found`)}if("schema"in P)return lD(D,F,P.schema,"schemas",{isNonNull:Z.isNonNull,operationResponseType:Z.operationResponseType},q);let X=P;if("properties"in X&&!("type"in X))X.type="object";let J={name:Z.operationResponseType?F:Z.isNonNull?`${F}!`:F,description:X.description,isObject:"type"in X&&(X.type==="object"||JSON.stringify(X.type)===JSON.stringify(["object","null"])),fields:[],isUnion:!!X.oneOf||!!X.anyOf||!!X.allOf,possibleTypes:[],isList:0,isNonNull:Z.isNonNull,isScalar:!1,scalarTSType:void 0,isEnum:{schemas:!!X.enum,parameters:!1,responses:!1,requestBodies:!1,headers:!1}[B],enumValues:[],isInput:B==="parameters"||B==="headers"||B==="requestBodies",inputFields:[],ofType:void 0};J.isScalar=!J.isObject&&!J.isUnion&&!J.isEnum&&!J.isInput;let Y=u7(J);if(q.hasType(Y))return q.getType(Y);else J.name=Y,q.addType(J);if(J.ofType=J,J.isEnum){let H=X;for(let W of[...H.enum??[]])J.enumValues.push({name:String(W),description:X.description,type:lD(D,F,X,B,{isNonNull:Z.isNonNull},q)})}if(J.isInput){let H=X;if("content"in H){let W=H;for(let[U,O]of Object.entries(W.content??{})){q.removeType(Y);let z=_7(lD(D,F,O,B,{isNonNull:W.required??!1},q),q);if(z.fields.length===1&&!!z.fields[0].type.scalarTSType)return q.removeType(Y),J=z.fields[0].type,q.addType(J),J;else return q.removeType(Y),J=z,q.addType(J),J}}if("schema"in H&&"in"in H){let W=H;if(W.schema)J.inputFields.push($8(D,W.name,W.schema,B,W.in,{isNonNull:W.required??!1},q));else J.inputFields.push($8(D,W.name,lD(D,SD([F,"Input",W.name]),W.content["application/json"],B,{isNonNull:W.required??!1},q),B,W.in,{isNonNull:W.required??!1},q))}if("schema"in H&&!("in"in H)){let W=H;if(W.schema)J.inputFields.push($8(D,SD([F,"Header"]),W.schema,B,"header",{isNonNull:W.required??!1},q));else J.inputFields.push($8(D,SD([F,"Header"]),lD(D,SD([F,"Input","Header"]),W.content["application/json"],B,{isNonNull:W.required??!1},q),B,"header",{isNonNull:W.required??!1},q))}}if(J.isObject){let H=X,W=H.properties;for(let[z,I]of Object.entries(W??{})){let R="$ref"in I;q.removeType(SD([F,z]));let $=lD(D,SD([F,z]),I,B,{isNonNull:H.required?.includes(z)??!1},q),E=zT(D,z,$,{isNonNull:H.required?.includes(z)??!1},q);J.fields.push(E)}let U,O=H.additionalProperties;if(O===!0||JSON.stringify(O)===JSON.stringify({}))U=N7(SD([F,"AdditionalProperties"]),"Additional properties","Record<string, any>",q),J.fields.push({name:SD([F,"Any"]),description:"Additional properties",type:U});else if(typeof O==="object")if("type"in O&&O.type==="string")U=N7(SD([F,"AdditionalProperties"]),"Additional properties","Record<string, string>",q),J.fields.push({name:SD([F,"AdditionalProperties"]),description:"Additional properties",type:U});else{let z="$ref"in O,I=lD(D,z?"":SD([F,"AdditionalProperties"]),O,B,{isNonNull:!1},q),R=I.name.replaceAll("!","").replaceAll("[","").replaceAll("]","");R={Int:"number",Float:"number",String:"string",Boolean:"boolean"}[R]??R;let $=R+(I.isList?Array.from({length:I.isList}).map((E)=>"[]").join(""):"");if(I.isScalar&&I.scalarTSType)U=I,J.fields.push({name:SD([F,R]),description:"Additional properties",type:U});else U=N7(SD([F,R]),"Additional properties",`Record<string, ${$}>`,q),J.fields.push({name:SD([F,R]),description:"Additional properties",type:U})}if(U&&J.fields.length===1)return q.removeType(Y),q.addType(U),U}if(J.isUnion){let H=0;for(let W of[...X.oneOf??[],...X.anyOf??[],...X.allOf??[]]){H++,q.removeType(Y);let U="$ref"in W;J.possibleTypes.push(lD(D,U?"":`${F}Subtype${H}`,W,B,{isNonNull:Z.isNonNull},q))}if(J.possibleTypes.length===1){let W=J.possibleTypes[0];J={...W,isList:J.isList,ofType:W,name:J.name}}}if(J.isScalar){let H=X;if(H.type==="array"){let W="$ref"in X.items;if(!W||X.items.$ref!==`#/components/${B}/${Y}`)q.removeType(Y);J.isList++;let U=lD(D,W?"":F,X.items,"schemas",{isNonNull:Z.isNonNull},q),O=J.isList+=U?.isList??0;J={...U,isList:O,name:`[${U.name}]`},J.ofType=J}else if(typeof H.type==="string"){q.removeType(Y),J.name=SD([H.type]);let W={double:"Float",float:"Float",integer:"Int",long:"Int",int32:"Int",int64:"Int",number:"Float",byte:"Int"};if(H.format&&H.format.toLowerCase()in W)J.name=W[H.format.toLowerCase()]}else if(Array.isArray(H))q.removeType(Y),J.name=SD(H);if(Z.isNonNull&&!J.name.endsWith("!"))q.removeType(Y),J.name=`${J.name}!`;J.name=u7(J)}return q.addType(J),J},$8=(D,F,P,B,Z,q,X)=>{return{name:F,description:P.description,location:Z,type:lD(D,F,P,B,q,X)}},zT=(D,F,P,B,Z)=>{return{name:F,description:P.description,type:lD(D,F,P,"schemas",B,Z)}},QT={get:"Get",post:"Create",put:"Update",delete:"Delete",patch:"Patch",options:"Options",head:"Head",trace:"Trace"},GT=(D,F,P,B,Z,q)=>{if(!B.responses){console.warn("Operation has no responses!");return}let X=Object.entries(B.responses).filter(([U,O])=>U.toString().startsWith("2")).sort(([U,O],[z,I])=>+U-+z),J=X.length>0?X[0][1]:B.responses.default,Y=Object.entries(B.responses).filter(([U,O])=>U.toString().startsWith("4")||U.toString().startsWith("5"));if(!J){console.warn("Operation has no success response!",B);return}let H=B.operationId?.replaceAll("-","_")??SD([QT[P],...F.split("/").flatMap((U)=>[U.includes("{")?"By":"",U.replace(/{([^}]+)}/g,"$1")].filter((O)=>O.length>0))],""),W={name:H,description:B.description,path:F,method:P,args:[],type:lD(D,H,"content"in J?J.content["application/json"]??Object.entries(J.content).find(([U,O])=>O)?.[1]:J,"responses",{isNonNull:!1,operationResponseType:!0},q)};for(let U of B.parameters??[]){let O="$ref"in U?U.$ref.split("/").pop():U.name,z="in"in U?U.in:U.$ref.split("/").at(-2),I={parameters:"query",requestBodies:"body",headers:"header",cookie:"cookie",path:"path",query:"query",header:"header"}[z];W.args.push($8(D,O,U,"parameters",I,{isNonNull:"$ref"in U?!1:U.required??!1},q))}if(B.requestBody){let U=B.requestBody,O=$8(D,`${H}RequestBody`,U,"requestBodies","body",{isNonNull:U.required??!1},q);O.name="$",W.args.push(O)}return W};class AU{constructor(){}_types=new Map;get types(){return this._types}addType(D){this._types.set(D.name,D)}hasType(D){return this._types.has(D)}getType(D){return this._types.get(D)}removeType(D){this._types.delete(D)}_customScalars=new Map;get customScalars(){return this._customScalars}addCustomScalar(D){this._customScalars.set(D.name,D)}hasCustomScalar(D){return this._customScalars.has(D)}getCustomScalar(D){return this._customScalars.get(D)}removeCustomScalar(D){this._customScalars.delete(D)}_enumsTypes=new Map;get enumsTypes(){return this._enumsTypes}addEnumType(D,F){this._enumsTypes.set(D,F)}hasEnumType(D){if(!D)return!1;return this._enumsTypes.has(D)}hasEnumTypeName(D){for(let[F,P]of this._enumsTypes.entries())if(F.name===D)return!0;return!1}getEnumType(D){return this._enumsTypes.get(D)}getEnumTypeByName(D){for(let[F,P]of this._enumsTypes.entries())if(F.name===D)return P;return""}_argumentTypes=new Map;get argumentTypes(){return this._argumentTypes}addArgumentType(D,F){this._argumentTypes.set(D,F)}hasArgumentType(D){return this._argumentTypes.has(D)}getArgumentType(D){return this._argumentTypes.get(D)}_argumentMeta=new Map;get argumentMeta(){return this._argumentMeta}addArgumentMeta(D,F){this._argumentMeta.set(D,F)}hasArgumentMeta(D){return this._argumentMeta.has(D)}getArgumentMeta(D){return this._argumentMeta.get(D)}_selectionTypes=new Map;get selectionTypes(){return this._selectionTypes}addSelectionType(D,F){this._selectionTypes.set(D,F)}hasSelectionType(D){if(!D)return!1;return this._selectionTypes.has(D)}getSelectionType(D){return this._selectionTypes.get(D)}_selectionFunctions=new Map;get selectionFunctions(){return this._selectionFunctions}addSelectionFunction(D,F){this._selectionFunctions.set(D,F)}hasSelectionFunction(D){if(!D)return!1;return this._selectionFunctions.has(D)}getSelectionFunction(D){return this._selectionFunctions.get(D)}}class CU{Codegen;constructor(D){this.Codegen=D}async generate({schema:D,options:F,authConfig:P}){let B=new AU,Z=OT(D,F,B);for(let[J,Y]of B.types.entries()){if(!Y.isEnum)continue;new this.Codegen(J,B,F).makeEnumType()}for(let[J,Y]of B.types.entries()){if(!Y.isInput)continue;new this.Codegen(J,B,F).makeSelectionType()}for(let[J,Y]of B.types.entries()){if(Y.isScalar||Y.isInput||Y.isEnum)continue;new this.Codegen(J,B,F).makeSelectionType(),new this.Codegen(J,B,F).makeSelectionFunction()}let q=this.Codegen.makeRootOperationFunction(Z.operations,B,F,P);return[this.Codegen.FieldValueWrapperType,this.Codegen.HelperTypes(Array.from(B.customScalars.values())),this.Codegen.HelperFunctions,...[...B.enumsTypes.entries()].map(([J,Y])=>Y).filter((J,Y,H)=>H.indexOf(J)===Y),...[...B.argumentTypes.entries()].map(([J,Y])=>Y).filter((J,Y,H)=>H.indexOf(J)===Y),...[...B.argumentMeta.entries()].map(([J,Y])=>Y).filter((J,Y,H)=>H.indexOf(J)===Y),...[...B.selectionTypes.entries()].filter(([J])=>!J.isScalar&&!J.isEnum&&!(J.isScalar&&J.isUnion)).map(([J,Y])=>Y).filter((J,Y,H)=>H.indexOf(J)===Y),this.Codegen.EnumTypesMapped(B),this.Codegen.UnionTypesMapped(B),...[...B.selectionFunctions.entries()].filter(([J])=>!J.isScalar&&!J.isEnum&&!J.isInput&&!(J.isScalar&&J.isUnion)).map(([J,Y])=>Y).filter((J)=>!J.startsWith("new SelectionWrapper")).filter((J,Y,H)=>H.indexOf(J)===Y),q].join(`
3700
3801
  `)}}var X2={GraphQL:{default:m2},OpenAPI:{default:q2}};import gO from"fs";import r1 from"fs";import AF from"path";var M8=(D)=>{process.stdout.write("\x1Bc"),process.stdout.write(`
3701
3802
  _____ _
@@ -3723,7 +3824,7 @@ ${r2.default.green("Done! Alias added to 'tsconfig.json'.")}
3723
3824
  ${r2.default.green("Go ahead and import the generated file in your project:")}
3724
3825
 
3725
3826
  ${cD.import("import")} ${cD.name(B)} ${cD.from("from")} ${cD.string(`"${B}"`)};
3726
- `),P=!0}return P};var CF=async(D,F,P,B={})=>{let Z=!0;if(D.url=await X0("GraphQL",D.url,"The URL",Z),D.headers?.length)for(let Y of D.headers){let H=await X0("GraphQL",Y,"The header",Z);D.headers[D.headers.indexOf(Y)]=H}if(B.endpoint)B.endpoint=await X0("GraphQL",B.endpoint,"The endpoint",Z);if(B.authHeaderName)B.authHeaderName=await X0("GraphQL",B.authHeaderName,"The auth header name",Z);P=await X0("GraphQL",P,"The output file",Z);let q;try{q=await y2(D.url,D.headers)}catch(Y){if(Y.response?.status===401||Y.response?.status===403){console.error(`Introspection failed: HTTP ${Y.response.status} Unauthorized. Please check your headers.`);return}console.error("Failed to introspect schema",Y);return}let J=await new k1.Generator(X2.GraphQL[F]).generate({schema:q,options:{},authConfig:D.headers?{headerName:D.headers.length===1?D.headers[0].split("=")[0]:"Authorization"}:void 0});if(!P.endsWith(".ts"))P+=".ts";gO.mkdirSync(P.split("/").slice(0,-1).join("/"),{recursive:!0}),gO.writeFileSync(P,J.replace("[ENDPOINT]",B.endpoint??D.url))};var LF=UD(e3(),1);import tN from"fs";import yO from"path";var mO=async()=>{M8("GraphQL");let D=await D5("Enter the graphql endpoint url:"),F,P;try{F=await y2(D)}catch(X){if(X.response?.status===401||X.response?.status===403){let[J,Y]=await F5();try{F=await y2(D,[`${J}=${Y}`]),P=J}catch(H){console.error("Error: ",H.message);return}}else{console.error("Error: ",X.message),console.error("Failed to introspect schema");return}}if(!F){console.error("Failed to introspect schema");return}let B=await P5(["."]),Z=await B5("Enter the output filename:"),q=yO.resolve(...B,Z);try{let J=await new k1.Generator(X2.GraphQL.default).generate({schema:F,options:{},authConfig:P?{headerName:P}:void 0});tN.writeFileSync(q,J.replace("[ENDPOINT]",D))}catch(X){console.error("Error: ",X.message),console.error("Failed to generate code");return}if(!await Z5(Z,q))console.log(`
3827
+ `),P=!0}return P};var CF=async(D,F,P,B={})=>{let Z=!0;if(D.url=await X0("GraphQL",D.url,"The URL",Z),D.headers?.length)for(let Y of D.headers){let H=await X0("GraphQL",Y,"The header",Z);D.headers[D.headers.indexOf(Y)]=H}if(B.endpoint)B.endpoint=await X0("GraphQL",B.endpoint,"The endpoint",Z);if(B.authHeaderName)B.authHeaderName=await X0("GraphQL",B.authHeaderName,"The auth header name",Z);P=await X0("GraphQL",P,"The output file",Z);let q;try{q=await y2(D.url,D.headers)}catch(Y){if(Y.response?.status===401||Y.response?.status===403){console.error(`Introspection failed: HTTP ${Y.response.status} Unauthorized. Please check your headers.`);return}console.error("Failed to introspect schema",Y);return}let J=await new k1.Generator(X2.GraphQL[F]).generate({schema:q,options:{},authConfig:D.headers?{headerName:D.headers.length===1?D.headers[0].split("=")[0]:"Authorization"}:void 0});if(!P.endsWith(".ts"))P+=".ts";gO.mkdirSync(P.split("/").slice(0,-1).join("/"),{recursive:!0}),gO.writeFileSync(P,J.replace("[AUTH_HEADER_NAME]",B.authHeaderName??"Authorization").replace("[ENDPOINT]",B.endpoint??D.url))};var LF=UD(e3(),1);import tN from"fs";import yO from"path";var mO=async()=>{M8("GraphQL");let D=await D5("Enter the graphql endpoint url:"),F,P;try{F=await y2(D)}catch(X){if(X.response?.status===401||X.response?.status===403){let[J,Y]=await F5();try{F=await y2(D,[`${J}=${Y}`]),P=J}catch(H){console.error("Error: ",H.message);return}}else{console.error("Error: ",X.message),console.error("Failed to introspect schema");return}}if(!F){console.error("Failed to introspect schema");return}let B=await P5(["."]),Z=await B5("Enter the output filename:"),q=yO.resolve(...B,Z);try{let J=await new k1.Generator(X2.GraphQL.default).generate({schema:F,options:{},authConfig:P?{headerName:P}:void 0});tN.writeFileSync(q,J.replace("[ENDPOINT]",D))}catch(X){console.error("Error: ",X.message),console.error("Failed to generate code");return}if(!await Z5(Z,q))console.log(`
3727
3828
  ${LF.default.green(`Done! Generated file saved at ${q}.`)}
3728
3829
  ${LF.default.green("Go ahead and import the generated file in your project:")}
3729
3830
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@samarium.sdk/new",
3
- "version": "0.17.2",
3
+ "version": "0.19.0",
4
4
  "main": "bin/samarium",
5
5
  "type": "module",
6
6
  "repository": {