@fern-api/ruby-dynamic-snippets 1.0.0 → 1.0.2
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.
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -12,7 +12,7 @@ ${f}`);this.isAtStartOfLine()&&(u=f+u),i&&(u+=`
|
|
|
12
12
|
`)}writeSemicolonIfLastCharacterIsNot(){this.lastCharacterIsSemicolon||this.writeInternal(";")}writeNewLineIfLastLineNot(){this.lastCharacterIsNewline||this.writeInternal(`
|
|
13
13
|
`)}indent(){this.indentLevel++}dedent(){this.indentLevel--}delimit({nodes:t,delimiter:e,writeFunction:i}){if(t.length>0){let s=t[0];s!=null&&i(s);for(let f=1;f<t.length;f++){this.write(e);let u=t[f];u!=null&&i(u)}}}toString(){return this.buffer}writeInternal(t){if(t.length===0)return;let e=!this.lastCharacterIsNewline;this.hasWrittenAnything=!0,this.lastCharacterIsNewline=t.endsWith(`
|
|
14
14
|
`),this.lastCharacterIsSemicolon=t.endsWith(";");let i=t.split(`
|
|
15
|
-
`),s=Z&&!this.shouldSkipTracking(i)&&this.lastCharacterIsNewline;e&&(this.lastLine=`${this.lastLine}${i.shift()||""}`),this.lastCharacterIsNewline&&i.pop(),this.lineBuffer.push(...i),s&&this.appendTrackingComment()}set lastLine(t){this.lineBuffer.length>0?this.lineBuffer[this.lineBuffer.length-1]=t:this.lineBuffer.push(t)}get lastLine(){return this.lineBuffer[this.lineBuffer.length-1]||""}shouldSkipTracking(t){return!1}formatStack(t,e=""){return t.map(i=>`${e?`(${e}) `:""} ${i.fn} - ${i.path} : ${i.position}`)}filterStack(t){return t.filter(e=>!e.fn.startsWith(`${this.constructor.name}.`))}appendTrackingComment(){let t=[...this.formatStack(this.filterStack(Qe({maxFrames:15,skip:3}))),...this.formatStack(this.filterStack(this.nodeStackFrames),"node")];switch(this.nodeStackFrames.length=0,wt){case"single":return this.singleLineTrackingComment(t);case"multiline":return this.multiLineTrackingComment(t);case"box":return this.boxTrackingComment(t)}}singleLineTrackingComment(t){this.lastLine=`${this.lastLine} // ${t.join(" ")}`}multiLineTrackingComment(t){this.lineBuffer.push(...t.map(e=>` // ${e}`))}boxTrackingComment(t){this.lineBuffer.push("/*",...t.map(e=>` ${e}`),"*/")}isAtStartOfLine(){return this.lastCharacterIsNewline||!this.hasWrittenAnything}getIndentString(){return" ".repeat(this.indentLevel*this.getTabSize())}getTabSize(){return oo}};c();m();d();c();m();d();c();m();d();var Fe=class{constructor(){y(this,"reporter");y(this,"snippet");y(this,"err");this.snippet=void 0,this.reporter=void 0,this.err=void 0}update({context:t,snippet:e}){this.shouldUpdate({snippet:e,reporter:t.errors})&&(this.reporter=t.errors.clone(),this.snippet=e)}getResponseOrThrow({endpoint:t}){if(this.snippet!=null&&this.reporter!=null)return{snippet:this.snippet,errors:this.reporter.toDynamicSnippetErrors()};throw this.err??new Error(`Failed to generate snippet for endpoint "${t.method} ${t.path}"`)}shouldUpdate({snippet:t,reporter:e}){return this.reporter==null||this.reporter.size()>0&&e.size()===0?!0:t.length>(this.snippet?.length??0)}};var Pe=class{constructor(t){y(this,"context");this.context=t}async generate(t,e={}){let i=this.resolveEndpoints({request:t,options:e});if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let s=new Fe;for(let f of i){let u=this.context.clone(),E=this.createSnippetGenerator(u);try{let w=await E.generateSnippet({endpoint:f,request:t,options:e});if(u.errors.empty())return{snippet:w,errors:void 0};s.update({context:u,snippet:w})}catch(w){s.err==null&&(s.err=w)}}return s.getResponseOrThrow({endpoint:t.endpoint})}async generateSnippetAst(t,e={}){let i=this.resolveEndpoints({request:t,options:e});if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let s;for(let f of i){let u=this.context.clone(),E=this.createSnippetGenerator(u);try{return await E.generateSnippetAst({endpoint:f,request:t,options:e})}catch(w){s=w}}throw s??new Error(`Failed to generate snippet AST for endpoint: ${t.endpoint.method} ${t.endpoint.path}`)}generateSync(t,e={}){let i=this.resolveEndpoints({request:t,options:e});if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let s=new Fe;for(let f of i){let u=this.context.clone(),E=this.createSnippetGenerator(u);try{let w=E.generateSnippetSync({endpoint:f,request:t,options:e});if(u.errors.empty())return{snippet:w,errors:void 0};s.update({context:u,snippet:w})}catch(w){s.err==null&&(s.err=w)}}return s.getResponseOrThrow({endpoint:t.endpoint})}resolveEndpoints({request:t,options:e}){if(e.endpointId!=null){let i=this.context.resolveEndpointById(e.endpointId);if(i==null)throw new Error(`No endpoint found with ID "${e.endpointId}"`);return[i]}return this.context.resolveEndpointLocationOrThrow(t.endpoint)}};c();m();d();c();m();d();c();m();d();var Ue=class{constructor(){y(this,"REFERENCE_REGEX",/^(?:(\w+)::)?(GET|POST|PUT|DELETE|PATCH|HEAD)\s(\/\S*)$/)}validate(t){return this.REFERENCE_REGEX.test(t)?{type:"valid"}:{type:"invalid"}}tryParse(t){if(this.validate(t).type==="invalid")return;let i=t.match(this.REFERENCE_REGEX);if(!(i==null||i[2]==null||i[3]==null))return{namespace:i[1],method:i[2],path:i[3]}}};c();m();d();var S={Critical:"CRITICAL",Warning:"WARNING"},Me=class l{constructor(){y(this,"errors");y(this,"path");this.errors=[],this.path=[]}add(t){this.errors.push({...t,path:[...this.path]})}scope(t){this.path.push(t)}unscope(){this.path.pop()}getBySeverity(t){return this.errors.filter(e=>e.severity===t)}empty(){return this.errors.length===0}size(){return this.errors.length}clone(){let t=new l;return t.errors=[...this.errors],t.path=[...this.path],t}reset(){this.errors=[],this.path=[]}toDynamicSnippetErrors(){return this.errors.map(t=>({severity:t.severity,path:t.path!=null?this.pathToStringArray(t.path):void 0,message:t.message}))}pathToStringArray(t){let e=[];for(let i of t){if(typeof i=="string"){e.push(i);continue}e[e.length-1]+=`[${i.index}]`}return e}};var $e=class{constructor({ir:t,config:e,options:i={}}){y(this,"config");y(this,"options");y(this,"errors");y(this,"_ir");y(this,"httpEndpointReferenceParser");this._ir=t,this.config=e,this.options=i,this.errors=new Me,this.httpEndpointReferenceParser=new Ue}associateQueryParametersByWireValue({parameters:t,values:e}){let i=[];for(let[s,f]of Object.entries(e))if(f!==void 0){this.errors.scope(s);try{let u=t.find(w=>w.name.wireValue===s);if(u==null)throw this.newParameterNotRecognizedError(s);let E=this.isListTypeReference(u.typeReference)&&!Array.isArray(f)?[f]:f;i.push({name:u.name,typeReference:u.typeReference,value:E})}finally{this.errors.unscope()}}return i}associateByWireValueOrDefault({parameters:t,values:e}){let i=[];for(let s of t){this.errors.scope(s.name.wireValue);try{let f=e[s.name.wireValue];if(f==null)if(s.typeReference.type==="primitive"&&s.typeReference.value==="STRING")f=`<${s.name.wireValue}>`;else{this.errors.add({severity:S.Critical,message:this.newParameterNotRecognizedError(s.name.wireValue).message});continue}i.push({name:s.name,typeReference:s.typeReference,value:f})}finally{this.errors.unscope()}}return i}associateByWireValue({parameters:t,values:e,ignoreMissingParameters:i}){let s=[];for(let[f,u]of Object.entries(e))if(u!==void 0){this.errors.scope(f);try{let E=t.find(w=>w.name.wireValue===f);if(E==null){if(i)continue;this.errors.add({severity:S.Critical,message:this.newParameterNotRecognizedError(f).message});continue}s.push({name:E.name,typeReference:E.typeReference,value:u})}finally{this.errors.unscope()}}return s}getExampleObjectProperties({parameters:t,snippetObject:e}){let i=typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{},s=[];for(let f of t){let u=i[f.name.wireValue];u==null?f.typeReference.type==="nullable"&&s.push({name:f.name,typeReference:f.typeReference,value:null}):s.push({name:f.name,typeReference:f.typeReference,value:u})}return s}getSingleFileValue({property:t,record:e}){let i=e[t.wireValue];if(i!=null){if(typeof i!="string"){this.errors.add({severity:S.Critical,message:`Expected file value to be a string, got ${typeof i}`});return}return i}}getFileArrayValues({property:t,record:e}){let i=e[t.wireValue];if(i==null)return;if(!Array.isArray(i)){this.errors.add({severity:S.Critical,message:`Expected file array value to be an array of strings, got ${typeof i}`});return}let s=[];for(let f of i){if(typeof f!="string"){this.errors.add({severity:S.Critical,message:`Expected file array value to be an array of strings, got ${typeof f}`});return}s.push(f)}return s}getRecord(t){if(typeof t!="object"||Array.isArray(t)){this.errors.add({severity:S.Critical,message:`Expected object with key, value pairs but got: ${Array.isArray(t)?"array":typeof t}`});return}return t??{}}resolveNamedType({typeId:t}){let e=this._ir.types[t];if(e==null){this.errors.add({severity:S.Critical,message:`Type identified by "${t}" could not be found`});return}return e}resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:e}){let i=this.getRecord(e);if(i==null)return;let s=t.discriminant.wireValue,f=i[s];if(f==null){this.errors.add({severity:S.Critical,message:this.newParameterNotRecognizedError(s).message});return}if(typeof f!="string"){this.errors.add({severity:S.Critical,message:`Expected discriminant value to be a string but got: ${typeof f}`});return}let u=t.types[f];if(u==null){this.errors.add({severity:S.Critical,message:`No type found for discriminant value "${f}"`});return}let{[s]:E,...w}=i;return{singleDiscriminatedUnionType:u,discriminantValue:u.discriminantValue,value:w}}resolveEndpointOrThrow(t){let e=this.httpEndpointReferenceParser.tryParse(t);if(e==null)throw new Error(`Failed to parse endpoint reference "${t}"`);return this.resolveEndpointLocationOrThrow(e)}resolveEndpointLocation(t){let e=[];for(let i of Object.values(this._ir.endpoints))this.parsedEndpointMatches({endpoint:i,parsedEndpoint:t})&&e.push(i);return e}resolveEndpointLocationOrThrow(t){let e=this.resolveEndpointLocation(t);if(e.length===0)throw new Error(`Failed to find endpoint identified by "${t.method} ${t.path}"`);return e}resolveEndpointById(t){return this._ir.endpoints[t]}resolveEndpointByIdOrThrow(t){let e=this.resolveEndpointById(t);if(e==null)throw new Error(`Failed to find endpoint with ID "${t}"`);return e}needsRequestParameter({request:t,inlinePathParameters:e,inlineFileProperties:i}){return this.includePathParametersInWrappedRequest({request:t,inlinePathParameters:e})||t.queryParameters!=null&&t.queryParameters.length>0||t.headers!=null&&t.headers.length>0?!0:t.body!=null?this.includeRequestBodyInWrappedRequest({body:t.body,inlineFileProperties:i}):!t.metadata?.onlyPathParameters}includePathParametersInWrappedRequest({request:t,inlinePathParameters:e}){return e&&(t.metadata?.includePathParameters??!1)}isFileUploadRequestBody(t){switch(t.type){case"fileUpload":return!0;case"properties":case"referenced":return!1;default:L(t)}}resolveEnvironmentName(t){if(this._ir.environments==null)return;let e=this._ir.environments.environments;switch(e.type){case"singleBaseUrl":{let i=e.environments.find(s=>s.id===t);return i?.name}case"multipleBaseUrls":{let i=e.environments.find(s=>s.id===t);return i?.name}default:L(e)}}isSingleEnvironmentID(t){return typeof t=="string"}isMultiEnvironmentValues(t){return typeof t=="object"}validateMultiEnvironmentUrlValues(t){if(this._ir.environments==null)return this.errors.add({severity:S.Critical,message:"Multiple environments are not supported for single base URL environments; use the baseUrl option instead"}),!1;let e=this._ir.environments.environments;switch(e.type){case"singleBaseUrl":return this.errors.add({severity:S.Critical,message:"Multiple environments are not supported for single base URL environments; use the baseUrl option instead"}),!1;case"multipleBaseUrls":{let i=e.environments[0];if(i==null)return this.errors.add({severity:S.Critical,message:"Multiple environments are not supported; use the baseUrl option instead"}),!1;let s=new Set(Ne(i.urls));for(let f of Ne(t))s.has(f)&&s.delete(f);return s.size>0?(this.errors.add({severity:S.Critical,message:`The provided environments are invalid; got: [${Object.keys(t).join(", ")}], expected: [${Ne(i.urls).join(", ")}]`}),!1):!0}}}getValueAsNumber({value:t}){if(typeof t!="number"){this.errors.add({severity:S.Critical,message:this.newTypeMismatchError({expected:"number",value:t}).message});return}return t}getValueAsBoolean({value:t}){if(typeof t!="boolean"){this.errors.add({severity:S.Critical,message:this.newTypeMismatchError({expected:"boolean",value:t}).message});return}return t}getValueAsString({value:t}){if(typeof t!="string"){this.errors.add({severity:S.Critical,message:this.newTypeMismatchError({expected:"string",value:t}).message});return}return t}isOptional(t){switch(t.type){case"nullable":return this.isOptional(t.value);case"optional":return!0;case"named":{let e=this.resolveNamedType({typeId:t.value});return e==null?!1:e.type==="alias"?this.isNullable(e.typeReference):!1}}return!1}isNullable(t){switch(t.type){case"nullable":return!0;case"optional":return this.isNullable(t.value);case"named":{let e=this.resolveNamedType({typeId:t.value});return e==null?!1:e.type==="alias"?this.isNullable(e.typeReference):!1}}return!1}newAuthMismatchError({auth:t,values:e}){return new Error(`Expected auth type ${t.type}, got ${e.type}`)}newParameterNotRecognizedError(t){return new Error(`"${t}" is not a recognized parameter for this endpoint`)}newTypeMismatchError({expected:t,value:e}){return new Error(`Expected ${t}, got ${typeof e}`)}includeRequestBodyInWrappedRequest({body:t,inlineFileProperties:e}){switch(t.type){case"properties":case"referenced":return!0;case"fileUpload":return this.includeFileUploadBodyInWrappedRequest({fileUpload:t,inlineFileProperties:e});default:L(t)}}includeFileUploadBodyInWrappedRequest({fileUpload:t,inlineFileProperties:e}){return this.fileUploadHasBodyProperties({fileUpload:t})||e&&this.fileUploadHasFileProperties({fileUpload:t})}fileUploadHasBodyProperties({fileUpload:t}){return t.properties.some(e=>{switch(e.type){case"file":case"fileArray":return!1;case"bodyProperty":return!0;default:L(e)}})}fileUploadHasFileProperties({fileUpload:t}){return t.properties.some(e=>{switch(e.type){case"file":case"fileArray":return!0;case"bodyProperty":return!1;default:L(e)}})}isListTypeReference(t){return t.type==="optional"?this.isListTypeReference(t.value):t.type==="list"||t.type==="set"}parsedEndpointMatches({endpoint:t,parsedEndpoint:e}){return t.location.method===e.method&&t.location.path===e.path}};c();m();d();c();m();d();c();m();d();c();m();d();c();m();d();c();m();d();var so=2,Y=class extends Ce{constructor({customConfig:e,formatter:i}){super();y(this,"customConfig");y(this,"formatter");y(this,"requires",new Set);y(this,"_indentLevel",0);this.customConfig=e,this.formatter=i??new Le}addRequire(e){this.requires.add(e)}get currentIndentLevel(){return this._indentLevel}indent(){this._indentLevel++,super.indent()}dedent(){this._indentLevel--,super.dedent()}writeNodeStatement(e){this.writeNode(e),this.writeNewLineIfLastLineNot()}getTabSize(){return so}};var Ie=class extends Y{constructor({customConfig:t,formatter:e}){super({customConfig:t,formatter:e})}async toStringAsync(){let t=this.getContent();if(this.formatter!=null)try{return this.formatter.format(t)}catch(e){throw new Error(`Failed to format Ruby file: ${e}
|
|
15
|
+
`),s=Z&&!this.shouldSkipTracking(i)&&this.lastCharacterIsNewline;e&&(this.lastLine=`${this.lastLine}${i.shift()||""}`),this.lastCharacterIsNewline&&i.pop(),this.lineBuffer.push(...i),s&&this.appendTrackingComment()}set lastLine(t){this.lineBuffer.length>0?this.lineBuffer[this.lineBuffer.length-1]=t:this.lineBuffer.push(t)}get lastLine(){return this.lineBuffer[this.lineBuffer.length-1]||""}shouldSkipTracking(t){return!1}formatStack(t,e=""){return t.map(i=>`${e?`(${e}) `:""} ${i.fn} - ${i.path} : ${i.position}`)}filterStack(t){return t.filter(e=>!e.fn.startsWith(`${this.constructor.name}.`))}appendTrackingComment(){let t=[...this.formatStack(this.filterStack(Qe({maxFrames:15,skip:3}))),...this.formatStack(this.filterStack(this.nodeStackFrames),"node")];switch(this.nodeStackFrames.length=0,wt){case"single":return this.singleLineTrackingComment(t);case"multiline":return this.multiLineTrackingComment(t);case"box":return this.boxTrackingComment(t)}}singleLineTrackingComment(t){this.lastLine=`${this.lastLine} // ${t.join(" ")}`}multiLineTrackingComment(t){this.lineBuffer.push(...t.map(e=>` // ${e}`))}boxTrackingComment(t){this.lineBuffer.push("/*",...t.map(e=>` ${e}`),"*/")}isAtStartOfLine(){return this.lastCharacterIsNewline||!this.hasWrittenAnything}getIndentString(){return" ".repeat(this.indentLevel*this.getTabSize())}getTabSize(){return oo}};c();m();d();c();m();d();c();m();d();var Fe=class{constructor(){y(this,"reporter");y(this,"snippet");y(this,"err");this.snippet=void 0,this.reporter=void 0,this.err=void 0}update({context:t,snippet:e}){this.shouldUpdate({snippet:e,reporter:t.errors})&&(this.reporter=t.errors.clone(),this.snippet=e)}getResponseOrThrow({endpoint:t}){if(this.snippet!=null&&this.reporter!=null)return{snippet:this.snippet,errors:this.reporter.toDynamicSnippetErrors()};throw this.err??new Error(`Failed to generate snippet for endpoint "${t.method} ${t.path}"`)}shouldUpdate({snippet:t,reporter:e}){return this.reporter==null||this.reporter.size()>0&&e.size()===0?!0:t.length>(this.snippet?.length??0)}};var Pe=class{constructor(t){y(this,"context");this.context=t}async generate(t,e={}){let i=this.resolveEndpoints({request:t,options:e});if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let s=new Fe;for(let f of i){let u=this.context.clone(),E=this.createSnippetGenerator(u);try{let w=await E.generateSnippet({endpoint:f,request:t,options:e});if(u.errors.empty())return{snippet:w,errors:void 0};s.update({context:u,snippet:w})}catch(w){s.err==null&&(s.err=w)}}return s.getResponseOrThrow({endpoint:t.endpoint})}async generateSnippetAst(t,e={}){let i=this.resolveEndpoints({request:t,options:e});if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let s;for(let f of i){let u=this.context.clone(),E=this.createSnippetGenerator(u);try{return await E.generateSnippetAst({endpoint:f,request:t,options:e})}catch(w){s=w}}throw s??new Error(`Failed to generate snippet AST for endpoint: ${t.endpoint.method} ${t.endpoint.path}`)}generateSync(t,e={}){let i=this.resolveEndpoints({request:t,options:e});if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let s=new Fe;for(let f of i){let u=this.context.clone(),E=this.createSnippetGenerator(u);try{let w=E.generateSnippetSync({endpoint:f,request:t,options:e});if(u.errors.empty())return{snippet:w,errors:void 0};s.update({context:u,snippet:w})}catch(w){s.err==null&&(s.err=w)}}return s.getResponseOrThrow({endpoint:t.endpoint})}resolveEndpoints({request:t,options:e}){if(e.endpointId!=null){let i=this.context.resolveEndpointById(e.endpointId);if(i==null)throw new Error(`No endpoint found with ID "${e.endpointId}"`);return[i]}return this.context.resolveEndpointLocationOrThrow(t.endpoint)}};c();m();d();c();m();d();c();m();d();var Ue=class{constructor(){y(this,"REFERENCE_REGEX",/^(?:(\w+)::)?(GET|POST|PUT|DELETE|PATCH|HEAD)\s(\/\S*)$/)}validate(t){return this.REFERENCE_REGEX.test(t)?{type:"valid"}:{type:"invalid"}}tryParse(t){if(this.validate(t).type==="invalid")return;let i=t.match(this.REFERENCE_REGEX);if(!(i==null||i[2]==null||i[3]==null))return{namespace:i[1],method:i[2],path:i[3]}}};c();m();d();var S={Critical:"CRITICAL",Warning:"WARNING"},Me=class l{constructor(){y(this,"errors");y(this,"path");this.errors=[],this.path=[]}add(t){this.errors.push({...t,path:[...this.path]})}scope(t){this.path.push(t)}unscope(){this.path.pop()}getBySeverity(t){return this.errors.filter(e=>e.severity===t)}empty(){return this.errors.length===0}size(){return this.errors.length}truncate(t){this.errors.length=t}clone(){let t=new l;return t.errors=[...this.errors],t.path=[...this.path],t}reset(){this.errors=[],this.path=[]}toDynamicSnippetErrors(){return this.errors.map(t=>({severity:t.severity,path:t.path!=null?this.pathToStringArray(t.path):void 0,message:t.message}))}pathToStringArray(t){let e=[];for(let i of t){if(typeof i=="string"){e.push(i);continue}e[e.length-1]+=`[${i.index}]`}return e}};var $e=class{constructor({ir:t,config:e,options:i={}}){y(this,"config");y(this,"options");y(this,"errors");y(this,"_ir");y(this,"httpEndpointReferenceParser");this._ir=t,this.config=e,this.options=i,this.errors=new Me,this.httpEndpointReferenceParser=new Ue}associateQueryParametersByWireValue({parameters:t,values:e}){let i=[];for(let[s,f]of Object.entries(e))if(f!==void 0){this.errors.scope(s);try{let u=t.find(w=>w.name.wireValue===s);if(u==null)throw this.newParameterNotRecognizedError(s);let E=this.isListTypeReference(u.typeReference)&&!Array.isArray(f)?[f]:f;i.push({name:u.name,typeReference:u.typeReference,value:E})}finally{this.errors.unscope()}}return i}associateByWireValueOrDefault({parameters:t,values:e}){let i=[];for(let s of t){this.errors.scope(s.name.wireValue);try{let f=e[s.name.wireValue];if(f==null)if(s.typeReference.type==="primitive"&&s.typeReference.value==="STRING")f=`<${s.name.wireValue}>`;else{this.errors.add({severity:S.Critical,message:this.newParameterNotRecognizedError(s.name.wireValue).message});continue}i.push({name:s.name,typeReference:s.typeReference,value:f})}finally{this.errors.unscope()}}return i}associateByWireValue({parameters:t,values:e,ignoreMissingParameters:i}){let s=[];for(let[f,u]of Object.entries(e))if(u!==void 0){this.errors.scope(f);try{let E=t.find(w=>w.name.wireValue===f);if(E==null){if(i)continue;this.errors.add({severity:S.Critical,message:this.newParameterNotRecognizedError(f).message});continue}s.push({name:E.name,typeReference:E.typeReference,value:u})}finally{this.errors.unscope()}}return s}getExampleObjectProperties({parameters:t,snippetObject:e}){let i=typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{},s=[];for(let f of t){let u=i[f.name.wireValue];u==null?f.typeReference.type==="nullable"&&s.push({name:f.name,typeReference:f.typeReference,value:null}):s.push({name:f.name,typeReference:f.typeReference,value:u})}return s}getSingleFileValue({property:t,record:e}){let i=e[t.wireValue];if(i!=null){if(typeof i!="string"){this.errors.add({severity:S.Critical,message:`Expected file value to be a string, got ${typeof i}`});return}return i}}getFileArrayValues({property:t,record:e}){let i=e[t.wireValue];if(i==null)return;if(!Array.isArray(i)){this.errors.add({severity:S.Critical,message:`Expected file array value to be an array of strings, got ${typeof i}`});return}let s=[];for(let f of i){if(typeof f!="string"){this.errors.add({severity:S.Critical,message:`Expected file array value to be an array of strings, got ${typeof f}`});return}s.push(f)}return s}getRecord(t){if(typeof t!="object"||Array.isArray(t)){this.errors.add({severity:S.Critical,message:`Expected object with key, value pairs but got: ${Array.isArray(t)?"array":typeof t}`});return}return t??{}}resolveNamedType({typeId:t}){let e=this._ir.types[t];if(e==null){this.errors.add({severity:S.Critical,message:`Type identified by "${t}" could not be found`});return}return e}resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:e}){let i=this.getRecord(e);if(i==null)return;let s=t.discriminant.wireValue,f=i[s];if(f==null){this.errors.add({severity:S.Critical,message:this.newParameterNotRecognizedError(s).message});return}if(typeof f!="string"){this.errors.add({severity:S.Critical,message:`Expected discriminant value to be a string but got: ${typeof f}`});return}let u=t.types[f];if(u==null){this.errors.add({severity:S.Critical,message:`No type found for discriminant value "${f}"`});return}let{[s]:E,...w}=i;return{singleDiscriminatedUnionType:u,discriminantValue:u.discriminantValue,value:w}}resolveEndpointOrThrow(t){let e=this.httpEndpointReferenceParser.tryParse(t);if(e==null)throw new Error(`Failed to parse endpoint reference "${t}"`);return this.resolveEndpointLocationOrThrow(e)}resolveEndpointLocation(t){let e=[];for(let i of Object.values(this._ir.endpoints))this.parsedEndpointMatches({endpoint:i,parsedEndpoint:t})&&e.push(i);return e}resolveEndpointLocationOrThrow(t){let e=this.resolveEndpointLocation(t);if(e.length===0)throw new Error(`Failed to find endpoint identified by "${t.method} ${t.path}"`);return e}resolveEndpointById(t){return this._ir.endpoints[t]}resolveEndpointByIdOrThrow(t){let e=this.resolveEndpointById(t);if(e==null)throw new Error(`Failed to find endpoint with ID "${t}"`);return e}needsRequestParameter({request:t,inlinePathParameters:e,inlineFileProperties:i}){return this.includePathParametersInWrappedRequest({request:t,inlinePathParameters:e})||t.queryParameters!=null&&t.queryParameters.length>0||t.headers!=null&&t.headers.length>0?!0:t.body!=null?this.includeRequestBodyInWrappedRequest({body:t.body,inlineFileProperties:i}):!t.metadata?.onlyPathParameters}includePathParametersInWrappedRequest({request:t,inlinePathParameters:e}){return e&&(t.metadata?.includePathParameters??!1)}isFileUploadRequestBody(t){switch(t.type){case"fileUpload":return!0;case"properties":case"referenced":return!1;default:L(t)}}resolveEnvironmentName(t){if(this._ir.environments==null)return;let e=this._ir.environments.environments;switch(e.type){case"singleBaseUrl":{let i=e.environments.find(s=>s.id===t);return i?.name}case"multipleBaseUrls":{let i=e.environments.find(s=>s.id===t);return i?.name}default:L(e)}}isSingleEnvironmentID(t){return typeof t=="string"}isMultiEnvironmentValues(t){return typeof t=="object"}validateMultiEnvironmentUrlValues(t){if(this._ir.environments==null)return this.errors.add({severity:S.Critical,message:"Multiple environments are not supported for single base URL environments; use the baseUrl option instead"}),!1;let e=this._ir.environments.environments;switch(e.type){case"singleBaseUrl":return this.errors.add({severity:S.Critical,message:"Multiple environments are not supported for single base URL environments; use the baseUrl option instead"}),!1;case"multipleBaseUrls":{let i=e.environments[0];if(i==null)return this.errors.add({severity:S.Critical,message:"Multiple environments are not supported; use the baseUrl option instead"}),!1;let s=new Set(Ne(i.urls));for(let f of Ne(t))s.has(f)&&s.delete(f);return s.size>0?(this.errors.add({severity:S.Critical,message:`The provided environments are invalid; got: [${Object.keys(t).join(", ")}], expected: [${Ne(i.urls).join(", ")}]`}),!1):!0}}}getValueAsNumber({value:t}){if(typeof t!="number"){this.errors.add({severity:S.Critical,message:this.newTypeMismatchError({expected:"number",value:t}).message});return}return t}getValueAsBoolean({value:t}){if(typeof t!="boolean"){this.errors.add({severity:S.Critical,message:this.newTypeMismatchError({expected:"boolean",value:t}).message});return}return t}getValueAsString({value:t}){if(typeof t!="string"){this.errors.add({severity:S.Critical,message:this.newTypeMismatchError({expected:"string",value:t}).message});return}return t}isOptional(t){switch(t.type){case"nullable":return this.isOptional(t.value);case"optional":return!0;case"named":{let e=this.resolveNamedType({typeId:t.value});return e==null?!1:e.type==="alias"?this.isNullable(e.typeReference):!1}}return!1}isNullable(t){switch(t.type){case"nullable":return!0;case"optional":return this.isNullable(t.value);case"named":{let e=this.resolveNamedType({typeId:t.value});return e==null?!1:e.type==="alias"?this.isNullable(e.typeReference):!1}}return!1}newAuthMismatchError({auth:t,values:e}){return new Error(`Expected auth type ${t.type}, got ${e.type}`)}newParameterNotRecognizedError(t){return new Error(`"${t}" is not a recognized parameter for this endpoint`)}newTypeMismatchError({expected:t,value:e}){return new Error(`Expected ${t}, got ${typeof e}`)}includeRequestBodyInWrappedRequest({body:t,inlineFileProperties:e}){switch(t.type){case"properties":case"referenced":return!0;case"fileUpload":return this.includeFileUploadBodyInWrappedRequest({fileUpload:t,inlineFileProperties:e});default:L(t)}}includeFileUploadBodyInWrappedRequest({fileUpload:t,inlineFileProperties:e}){return this.fileUploadHasBodyProperties({fileUpload:t})||e&&this.fileUploadHasFileProperties({fileUpload:t})}fileUploadHasBodyProperties({fileUpload:t}){return t.properties.some(e=>{switch(e.type){case"file":case"fileArray":return!1;case"bodyProperty":return!0;default:L(e)}})}fileUploadHasFileProperties({fileUpload:t}){return t.properties.some(e=>{switch(e.type){case"file":case"fileArray":return!0;case"bodyProperty":return!1;default:L(e)}})}isListTypeReference(t){return t.type==="optional"?this.isListTypeReference(t.value):t.type==="list"||t.type==="set"}parsedEndpointMatches({endpoint:t,parsedEndpoint:e}){return t.location.method===e.method&&t.location.path===e.path}};c();m();d();c();m();d();c();m();d();c();m();d();c();m();d();c();m();d();var so=2,Y=class extends Ce{constructor({customConfig:e,formatter:i}){super();y(this,"customConfig");y(this,"formatter");y(this,"requires",new Set);y(this,"_indentLevel",0);this.customConfig=e,this.formatter=i??new Le}addRequire(e){this.requires.add(e)}get currentIndentLevel(){return this._indentLevel}indent(){this._indentLevel++,super.indent()}dedent(){this._indentLevel--,super.dedent()}writeNodeStatement(e){this.writeNode(e),this.writeNewLineIfLastLineNot()}getTabSize(){return so}};var Ie=class extends Y{constructor({customConfig:t,formatter:e}){super({customConfig:t,formatter:e})}async toStringAsync(){let t=this.getContent();if(this.formatter!=null)try{return this.formatter.format(t)}catch(e){throw new Error(`Failed to format Ruby file: ${e}
|
|
16
16
|
${t}`)}return t}toString(){let t=this.getContent();if(this.formatter!=null)try{return this.formatter.formatSync(t)}catch(e){throw new Error(`Failed to format Ruby file: ${e}
|
|
17
17
|
${t}`)}return t}getContent(){let t=this.stringifyRequires();return t.length>0?`${t}
|
|
18
18
|
|
|
@@ -22,7 +22,7 @@ ${this.buffer}`:this.buffer}stringifyRequires(){return Array.from(this.requires)
|
|
|
22
22
|
`,`
|
|
23
23
|
`);i.includes('"')&&!i.includes("'")&&!i.includes("#")?e.write(`'${i}'`):e.write(`"${i.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`);break}case"int":{e.write(this.internalType.value.toString());break}case"float":{e.write(this.internalType.value.toString());break}case"bool":{e.write(this.internalType.value?"true":"false");break}case"hash":{let i=this.internalType.entries.filter(s=>!l.isNop(s.key)&&!l.isNop(s.value));if(i.length===0){e.write("{}");break}e.write(`{
|
|
24
24
|
`),i.forEach((s,f)=>{f>0&&e.writeLine(","),e.indent();let u=!1;if(s.key instanceof l&&s.key.internalType.type==="str"){let E=s.key.internalType.value;/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(E)&&(e.write(`${E}:`),u=!0)}u||(s.key.write(e),e.write(" =>")),e.write(" "),s.value.write(e),e.dedent()}),e.write(`
|
|
25
|
-
}`);break}case"set":{let i=this.internalType.values.filter(s=>!l.isNop(s));if(i.length===0){e.write("Set.new([])");break}e.write("Set.new(["),i.forEach((s,f)=>{f>0&&e.write(", "),s.write(e)}),e.write("])");break}case"list":{let i=this.internalType.values.filter(s=>!l.isNop(s));if(i.length===0){e.write("[]");break}if(i.length>=2&&i.every(s=>s instanceof l&&s.internalType.type==="str"&&!/[\s\\[\]]/.test(s.internalType.value))){let s=i.map(f=>f.internalType.value);e.write(`%w[${s.join(" ")}]`);break}e.write("["),i.forEach((s,f)=>{f>0&&e.write(", "),s.write(e)}),e.write("]");break}case"nop":break;case"nil":e.write("nil");break;default:L(this.internalType)}}};c();m();d();var rt;(function(l){l[l.Invariant=0]="Invariant",l.Covariant="out",l.Contravariant="in"})(rt||(rt={}));var be=class extends N{constructor({name:e,unchecked:i,bound:s,variance:f,defaultType:u}){super();y(this,"name");y(this,"unchecked");y(this,"bound");y(this,"variance");y(this,"defaultType");this.name=e,this.unchecked=i??!1,this.bound=s,this.variance=f??rt.Invariant,this.defaultType=u}write(e){}writeTypeDefinition(e){this.unchecked&&e.write("unchecked "),this.variance!=rt.Invariant&&e.write(`${this.variance} `),e.write(this.name),this.bound&&(e.write(" < "),this.bound.writeTypeDefinition(e)),this.defaultType&&(e.write(" = "),this.defaultType.writeTypeDefinition(e))}};c();m();d();var qe=class extends W{constructor(){super(...arguments);y(this,"initializer")}write(e){e.write(`&${this.name}`)}};c();m();d();var nt=class extends N{constructor({errorClass:e,message:i}){super();y(this,"errorClass");y(this,"message");this.errorClass=e,this.message=i}write(e){e.write("raise"),this.errorClass&&(e.write(" "),this.errorClass.write(e)),this.message&&(this.errorClass&&e.write(", "),this.message.write(e))}};function it(l){return new ye(l)}function lo(){return it("true")}function po(){return it("false")}function fo(){return it("nil")}var co={positional(l){return new _e(l)},keyword(l){return new xe(l)},positionalSplat(l){return new je(l)},keywordSplat(l){return new De(l)},yield(l){return new qe(l)}};function mo(l){return new ue(l)}function ho(l){return new ae(l)}function yo(l){return new se(l)}function go(l){return new X(l)}function xo(l){return new be(l)}function wo(l){return new ne(l)}function bo(l){return new he(l)}function vo(l){return new ge(l)}function Ao(l){return new we(l)}function Eo(l){return new Oe(l)}function To(l){return new tt(l)}function Io(l){return new et(l)}function ko(l){return new nt(l)}function Ro(l,t){let e=l;for(let i of t.toReversed())i.addStatement(e),e=i;return e}c();m();d();var ot=class l{constructor({context:t}){y(this,"context");this.context=t}convert(t){if(t.value===null)return this.context.isNullable(t.typeReference)?x.TypeLiteral.nil():(this.context.errors.add({severity:S.Critical,message:"Expected non-null value, but got null"}),x.TypeLiteral.nop());if(t.value===void 0)return x.TypeLiteral.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value});case"literal":return this.convertLiteral({literalType:t.typeReference.value,value:t.value});case"map":return this.convertMap({map:t.typeReference,value:t.value});case"named":{let e=this.context.resolveNamedType({typeId:t.typeReference.value});return e==null?x.TypeLiteral.nop():this.convertNamed({named:e,value:t.value,as:t.as})}case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as});case"set":return this.convertSet({set:t.typeReference.value,value:t.value});case"unknown":return x.TypeLiteral.nop();default:L(t.typeReference)}}convertLiteral({literalType:t,value:e}){switch(t.type){case"boolean":{let i=this.context.getValueAsBoolean({value:e});return i==null?x.TypeLiteral.nop():x.TypeLiteral.boolean(i)}case"string":{let i=this.context.getValueAsString({value:e});return i==null?x.TypeLiteral.nop():x.TypeLiteral.string(i)}default:L(t)}}convertList({list:t,value:e}){return Array.isArray(e)?x.TypeLiteral.list(e.map((i,s)=>{this.context.errors.scope({index:s});try{return this.convert({typeReference:t,value:i})}finally{this.context.errors.unscope()}})):(this.context.errors.add({severity:S.Critical,message:`Expected array but got: ${typeof e}`}),x.TypeLiteral.nop())}convertSet({set:t,value:e}){return Array.isArray(e)?x.TypeLiteral.set(e.map((i,s)=>{this.context.errors.scope({index:s});try{return this.convert({typeReference:t,value:i})}finally{this.context.errors.unscope()}})):(this.context.errors.add({severity:S.Critical,message:`Expected array but got: ${typeof e}`}),x.TypeLiteral.nop())}convertMap({map:t,value:e}){return typeof e!="object"||e==null?(this.context.errors.add({severity:S.Critical,message:`Expected object but got: ${e==null?"null":typeof e}`}),x.TypeLiteral.nop()):x.TypeLiteral.hash(Object.entries(e).map(([i,s])=>{this.context.errors.scope(i);try{return{key:this.convert({typeReference:t.key,value:i,as:"key"}),value:this.convert({typeReference:t.value,value:s})}}finally{this.context.errors.unscope()}}))}convertNamed({named:t,value:e,as:i}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference,value:e,as:i});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:e});case"object":return this.convertObject({object:t,value:e});case"enum":return this.convertEnum({enum_:t,value:e});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:e});default:L(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:e}){let i=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:e});if(i==null)return x.TypeLiteral.nop();let s=i.singleDiscriminatedUnionType,f=this.convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:i,unionVariant:s});return f==null?x.TypeLiteral.nop():x.TypeLiteral.hash(f)}convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:t,unionVariant:e}){switch(e.type){case"samePropertiesAsObject":{let i=this.context.resolveNamedType({typeId:e.typeId});if(i==null)return;let s=this.convertNamed({named:i,value:t.value});return this.extractHashEntries(s)}case"singleProperty":try{this.context.errors.scope(e.discriminantValue.wireValue);let i=this.context.getRecord(t.value);return i==null?[{key:x.TypeLiteral.string(this.context.getPropertyName(e.discriminantValue.name)),value:this.convert({typeReference:e.typeReference,value:t.value})}]:[{key:x.TypeLiteral.string(this.context.getPropertyName(e.discriminantValue.name)),value:this.convert({typeReference:e.typeReference,value:i[e.discriminantValue.wireValue]})}]}finally{this.context.errors.unscope()}case"noProperties":return[];default:L(e)}}extractHashEntries(t){t instanceof x.TypeLiteral}convertEnum({enum_:t,value:e}){let i=this.getEnumValueName({enum_:t,value:e});return i==null?x.TypeLiteral.nop():x.TypeLiteral.string(i)}getEnumValueName({enum_:t,value:e}){if(typeof e!="string"){this.context.errors.add({severity:S.Critical,message:`Expected enum value string, got: ${typeof e}`});return}let i=t.values.find(s=>s.wireValue===e);if(i==null){this.context.errors.add({severity:S.Critical,message:`An enum value named "${e}" does not exist in this context`});return}return i.wireValue}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:e}){let i=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:e});return i??x.TypeLiteral.nop()}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:e}){for(let i of t.types){let s=this.context.clone(),u=new l({context:s}).convert({typeReference:i,value:e});if(s.errors.empty())return u}this.context.errors.add({severity:S.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof e}" value`})}convertPrimitive({primitive:t,value:e,as:i}){switch(t){case"INTEGER":case"LONG":case"UINT":case"UINT_64":{let s=this.getValueAsNumber({value:e,as:i});return s==null?x.TypeLiteral.nop():x.TypeLiteral.integer(s)}case"FLOAT":case"DOUBLE":{let s=this.getValueAsNumber({value:e});return s==null?x.TypeLiteral.nop():x.TypeLiteral.float(s)}case"BOOLEAN":{let s=this.getValueAsBoolean({value:e,as:i});return s==null?x.TypeLiteral.nop():x.TypeLiteral.boolean(s)}case"BASE_64":case"BIG_INTEGER":case"STRING":{let s=this.context.getValueAsString({value:e});return s==null?x.TypeLiteral.nop():x.TypeLiteral.string(s)}case"UUID":{let s=this.context.getValueAsString({value:e});return s==null?x.TypeLiteral.nop():x.TypeLiteral.string(s)}case"DATE":{let s=this.context.getValueAsString({value:e});return s==null?x.TypeLiteral.nop():x.TypeLiteral.string(s)}case"DATE_TIME":{let s=this.context.getValueAsString({value:e});return s==null?x.TypeLiteral.nop():x.TypeLiteral.string(s)}default:L(t)}}convertObject({object:t,value:e}){return typeof e!="object"||e==null?(this.context.errors.add({severity:S.Critical,message:`Expected object but got: ${e==null?"null":typeof e}`}),x.TypeLiteral.nop()):x.TypeLiteral.hash(Object.entries(e).map(([i,s])=>{this.context.errors.scope(i);let f=t.properties.find(k=>k.name.wireValue===i),u=f?.typeReference??{type:"unknown"},E=f?.name.name.snakeCase.safeName??i,w={key:x.TypeLiteral.string(E),value:this.convert({typeReference:u,value:s})};return this.context.errors.unscope(),w}))}getValueAsNumber({value:t,as:e}){let i=e==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:i})}getValueAsBoolean({value:t,as:e}){let i=e==="key"?typeof t=="string"?t==="true":!!t:t;return this.context.getValueAsBoolean({value:i})}};var st=class l extends $e{constructor({ir:e,config:i}){super({ir:e,config:i});y(this,"ir");y(this,"customConfig");y(this,"dynamicTypeLiteralMapper");this.ir=e,this.customConfig=i.customConfig!=null?i.customConfig:void 0,this.dynamicTypeLiteralMapper=new ot({context:this})}clone(){return new l({ir:this.ir,config:this.config})}getRootClientClassReference(){return x.classReference({name:this.getRootClientClassName(),modules:[this.getRootModuleName()]})}getRootClientClassName(){return this.customConfig?.clientModuleName??"Client"}getRootModuleName(){return xt(this.customConfig?.moduleName??this.customConfig?.clientModuleName??this.config.organization)}isSingleEnvironmentID(e){return typeof e=="string"}isMultiEnvironmentValues(e){return typeof e=="object"}getEnvironmentTypeReferenceFromID(e){let i=this.resolveEnvironmentName(e);if(i!=null)return x.codeblock(s=>{s.writeNode(this.getEnvironmentClassReference()),s.write("::"),s.write(this.getEnumName(i))})}getEnvironmentClassReference(){return x.classReference({name:"Environment",modules:[this.getRootModuleName()]})}getEnumName(e){return this.getName(e.screamingSnakeCase.safeName)}getMethodName(e){return this.getName(e.snakeCase.safeName)}getPropertyName(e){return this.getName(e.snakeCase.safeName)}getName(e){return e}};c();m();d();var Un="client",Bo="@client",at=class{constructor({context:t,formatter:e}){y(this,"context");y(this,"formatter");this.context=t,this.formatter=e}async generateSnippet({endpoint:t,request:e}){return await this.buildCodeBlock({endpoint:t,snippet:e}).toStringAsync({customConfig:this.context.customConfig??{},formatter:this.formatter})}generateSnippetSync({endpoint:t,request:e}){return this.buildCodeBlock({endpoint:t,snippet:e}).toString({customConfig:this.context.customConfig??{},formatter:this.formatter})}async generateSnippetAst({endpoint:t,request:e,options:i}){return i?.skipClientInstantiation?this.buildCodeBlockWithoutClient({endpoint:t,snippet:e}):this.buildCodeBlock({endpoint:t,snippet:e})}buildCodeBlock({endpoint:t,snippet:e}){return x.codeblock(i=>{i.writeNodeStatement(this.constructClient({endpoint:t,snippet:e})),i.newLine(),i.writeNodeStatement(this.callMethod({endpoint:t,snippet:e}))})}buildCodeBlockWithoutClient({endpoint:t,snippet:e}){return x.codeblock(i=>{i.writeNodeStatement(this.callMethodOnExistingClient({endpoint:t,snippet:e}))})}constructClient({endpoint:t,snippet:e}){return x.codeblock(i=>{i.addRequire(this.context.getRootModuleName().toLowerCase());let s=this.context.getRootClientClassReference(),f=this.getRootClientBuilderArgs({endpoint:t,snippet:e});i.write(`${Un} = `),i.writeNode(x.instantiateClass({classReference:s,arguments_:f}))})}getRootClientBaseUrlArg({baseUrl:t,environment:e}){if(t!=null&&e!=null)return this.context.errors.add({severity:"CRITICAL",message:"Cannot specify both baseUrl and environment options"}),[];if(t!=null)return[x.keywordArgument({name:"base_url",value:x.TypeLiteral.string(t)})];if(e!=null){if(this.context.isSingleEnvironmentID(e)){let i=this.context.getEnvironmentTypeReferenceFromID(e);return i==null?(this.context.errors.add({severity:"CRITICAL",message:`Environment ID ${e} not found`}),[]):[x.keywordArgument({name:"environment",value:i})]}if(this.context.isMultiEnvironmentValues(e))return this.context.errors.add({severity:"CRITICAL",message:"Multi-environment values are not supported in Ruby snippets yet"}),[]}return[]}getRootClientAuthArgs({auth:t,values:e}){if(e.type!==t.type)return this.addError(this.context.newAuthMismatchError({auth:t,values:e}).message),[];switch(t.type){case"basic":return e.type==="basic"?this.getRootClientBasicAuthArgs({auth:t,values:e}):[];case"bearer":return e.type==="bearer"?this.getRootClientBearerAuthArgs({auth:t,values:e}):[];case"header":return e.type==="header"?this.getRootClientHeaderAuthArgs({auth:t,values:e}):[];case"oauth":return e.type==="oauth"?this.getRootClientOAuthArgs({auth:t,values:e}):[];case"inferred":return[];default:L(t)}}addError(t){this.context.errors.add({severity:S.Critical,message:t})}addWarning(t){this.context.errors.add({severity:S.Warning,message:t})}getRootClientBasicAuthArgs({auth:t,values:e}){return[x.keywordArgument({name:t.username.snakeCase.safeName,value:x.TypeLiteral.string(e.username)}),x.keywordArgument({name:t.password.snakeCase.safeName,value:x.TypeLiteral.string(e.password)})]}getRootClientBearerAuthArgs({auth:t,values:e}){return[x.keywordArgument({name:t.token.snakeCase.safeName,value:x.TypeLiteral.string(e.token)})]}getRootClientHeaderAuthArgs({auth:t,values:e}){return[x.keywordArgument({name:t.header.name.name.snakeCase.safeName,value:x.TypeLiteral.string(e.value)})]}getRootClientOAuthArgs({auth:t,values:e}){return[x.keywordArgument({name:t.clientId.snakeCase.safeName,value:x.TypeLiteral.string(e.clientId)}),x.keywordArgument({name:t.clientSecret.snakeCase.safeName,value:x.TypeLiteral.string(e.clientSecret)})]}getRootClientHeaderArgs({headers:t,values:e}){let i=[];for(let s of t){let f=e[s.name.name.originalName];f!=null&&typeof f=="string"&&i.push(x.keywordArgument({name:s.name.name.snakeCase.safeName,value:x.TypeLiteral.string(f)}))}return i}getRootClientBuilderArgs({endpoint:t,snippet:e}){let i=[];t.auth!=null&&(e.auth!=null?i.push(...this.getRootClientAuthArgs({auth:t.auth,values:e.auth})):this.context.errors.add({severity:"WARNING",message:`Auth with ${t.auth.type} configuration is required for this endpoint`}));let s=this.getRootClientBaseUrlArg({baseUrl:e.baseURL,environment:e.environment});return s.length>0&&i.push(...s),this.context.errors.scope("Headers"),this.context.ir.headers!=null&&e.headers!=null&&i.push(...this.getRootClientHeaderArgs({headers:this.context.ir.headers,values:e.headers})),this.context.errors.unscope(),i}callMethod({endpoint:t,snippet:e}){let i={on:x.codeblock(Un),method:this.getMethod({endpoint:t}),arguments_:[]};switch(t.request.type){case"inlined":i.keywordArguments=this.getMethodArgsForInlinedRequest({request:t.request,snippet:e});break;case"body":i.keywordArguments=this.getMethodArgsForBodyRequest({request:t.request,snippet:e});break;default:L(t.request)}let s=this.getRequestOptions({endpoint:t,snippet:e});return s!=null&&(i.keywordArguments=i.keywordArguments??[],i.keywordArguments.push(s)),x.invokeMethod(i)}callMethodOnExistingClient({endpoint:t,snippet:e}){let i={on:x.codeblock(Bo),method:this.getMethod({endpoint:t}),arguments_:[]};switch(t.request.type){case"inlined":i.keywordArguments=this.getMethodArgsForInlinedRequest({request:t.request,snippet:e});break;case"body":i.keywordArguments=this.getMethodArgsForBodyRequest({request:t.request,snippet:e});break;default:L(t.request)}let s=this.getRequestOptions({endpoint:t,snippet:e});return s!=null&&(i.keywordArguments=i.keywordArguments??[],i.keywordArguments.push(s)),x.invokeMethod(i)}getRequestOptions({endpoint:t,snippet:e}){let i=e.headers??{},s=Object.entries(i);if(s.length===0)return;let f=new Set;if(this.context.ir.headers!=null)for(let w of this.context.ir.headers)f.add(w.name.wireValue.toLowerCase());if(t.request.type==="inlined"&&t.request.headers!=null)for(let w of t.request.headers)f.add(w.name.wireValue.toLowerCase());let u=s.filter(([w])=>!f.has(w.toLowerCase()));if(u.length===0)return;let E=u.map(([w,k])=>({key:x.TypeLiteral.string(w),value:x.TypeLiteral.string(String(k))}));return x.keywordArgument({name:"request_options",value:x.TypeLiteral.hash([{key:x.TypeLiteral.string("additional_headers"),value:x.TypeLiteral.hash(E)}])})}getMethodArgsForInlinedRequest({request:t,snippet:e}){let i=[];if(i.push(...this.getNamedParameterArgs({kind:"PathParameters",namedParameters:t.pathParameters,values:e.pathParameters})),i.push(...this.getNamedParameterArgs({kind:"QueryParameters",namedParameters:t.queryParameters,values:e.queryParameters})),i.push(...this.getNamedParameterArgs({kind:"Headers",namedParameters:t.headers,values:e.headers})),t.body!=null&&e.requestBody!=null)switch(t.body.type){case"properties":i.push(...this.getMethodArgsForPropertiesRequest({request:t.body,snippet:e}));break;case"referenced":{let s=t.body.bodyType;if(s.type==="typeReference"){let f=s.value;if(f.type==="named"){let u=this.context.resolveNamedType({typeId:f.value});if(u!=null&&u.type==="object"){let E=this.context.getRecord(e.requestBody);if(E!=null){let w=this.getBodyFieldsAsKeywordArgs({namedType:u,bodyRecord:E});i.push(...w)}}else if(u!=null){let E=this.getBodyArgsForNonObjectType({namedType:u,typeRef:f,bodyValue:e.requestBody});i.push(...E)}}else{let u=this.context.dynamicTypeLiteralMapper.convert({typeReference:f,value:e.requestBody});x.TypeLiteral.isNop(u)||i.push(x.keywordArgument({name:t.body.bodyKey.snakeCase.safeName,value:u}))}}break}case"fileUpload":break;default:L(t.body)}return i}getNamedParameterArgs({kind:t,namedParameters:e,values:i}){let s=[];if(this.context.errors.scope(t),e!=null){let f=this.context.associateByWireValue({parameters:e,values:i??{},ignoreMissingParameters:!0});for(let u of f){let E=this.context.dynamicTypeLiteralMapper.convert(u);x.TypeLiteral.isNop(E)||s.push(x.keywordArgument({name:this.context.getPropertyName(u.name.name),value:E}))}}return this.context.errors.unscope(),s}getMethodArgsForPropertiesRequest({request:t,snippet:e}){let i=[],s=this.context.associateByWireValue({parameters:t.value,values:this.context.getRecord(e.requestBody)??{}});for(let f of s){let u=this.context.dynamicTypeLiteralMapper.convert(f);x.TypeLiteral.isNop(u)||i.push(x.keywordArgument({name:this.context.getPropertyName(f.name.name),value:u}))}return i}getMethodArgsForBodyRequest({request:t,snippet:e}){let i=[];if(i.push(...this.getNamedParameterArgs({kind:"PathParameters",namedParameters:t.pathParameters,values:e.pathParameters})),t.body!=null&&e.requestBody!=null)switch(t.body.type){case"bytes":this.context.errors.add({severity:"CRITICAL",message:"Bytes request body is not supported in Ruby snippets yet"});break;case"typeReference":{let s=t.body.value;if(s.type==="named"){let f=this.context.resolveNamedType({typeId:s.value});if(f!=null&&f.type==="object"){let u=this.context.getRecord(e.requestBody);if(u!=null){let E=this.getBodyFieldsAsKeywordArgs({namedType:f,bodyRecord:u});i.push(...E)}}else if(f!=null){let u=this.getBodyArgsForNonObjectType({namedType:f,typeRef:s,bodyValue:e.requestBody});i.push(...u)}}else{let f=this.context.dynamicTypeLiteralMapper.convert({typeReference:s,value:e.requestBody});x.TypeLiteral.isNop(f)||i.push(x.keywordArgument({name:"request",value:f}))}break}default:L(t.body)}return i}getBodyArgsForNonObjectType({namedType:t,typeRef:e,bodyValue:i}){let s=[];switch(t.type){case"undiscriminatedUnion":{let f=this.context.getRecord(i);if(f!=null){for(let E of t.types)if(E.type==="named"){let w=this.context.resolveNamedType({typeId:E.value});if(w!=null&&w.type==="object"){let k=new Set(w.properties.map(D=>D.name.wireValue)),R=Object.keys(f);if(R.every(D=>k.has(D))&&R.length>0){let D=this.getBodyFieldsAsKeywordArgs({namedType:w,bodyRecord:f});return s.push(...D),s}}}}let u=this.context.dynamicTypeLiteralMapper.convert({typeReference:e,value:i});x.TypeLiteral.isNop(u)||s.push(x.keywordArgument({name:"request",value:u}));break}case"alias":{let f=t.typeReference;if(f.type==="named"){let E=this.context.resolveNamedType({typeId:f.value});if(E!=null&&E.type==="object"){let w=this.context.getRecord(i);if(w!=null){let k=this.getBodyFieldsAsKeywordArgs({namedType:E,bodyRecord:w});return s.push(...k),s}}}let u=this.context.dynamicTypeLiteralMapper.convert({typeReference:e,value:i});x.TypeLiteral.isNop(u)||s.push(x.keywordArgument({name:"request",value:u}));break}case"discriminatedUnion":case"enum":{let f=this.context.dynamicTypeLiteralMapper.convert({typeReference:e,value:i});x.TypeLiteral.isNop(f)||s.push(x.keywordArgument({name:"request",value:f}));break}case"object":break;default:L(t)}return s}getBodyFieldsAsKeywordArgs({namedType:t,bodyRecord:e}){let i=[];switch(t.type){case"object":{for(let s of t.properties){let f=s.name.wireValue,u=e[f];if(u!==void 0){this.context.errors.scope(f);let E=this.context.dynamicTypeLiteralMapper.convert({typeReference:s.typeReference,value:u});this.context.errors.unscope(),x.TypeLiteral.isNop(E)||i.push(x.keywordArgument({name:this.context.getPropertyName(s.name.name),value:E}))}}break}case"alias":case"discriminatedUnion":case"undiscriminatedUnion":case"enum":break;default:L(t)}return i}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(e=>`${this.context.getMethodName(e)}`).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}};var ut=class extends Pe{constructor({ir:e,config:i,formatter:s}){super(new st({ir:e,config:i}));y(this,"formatter");this.formatter=s}async generate(e){return super.generate(e)}generateSync(e){return super.generateSync(e)}async generateSnippetAst(e,i){return super.generateSnippetAst(e,i)}createSnippetGenerator(e){return new at({context:e,formatter:this.formatter})}};0&&(module.exports={DynamicSnippetsGenerator});
|
|
25
|
+
}`);break}case"set":{let i=this.internalType.values.filter(s=>!l.isNop(s));if(i.length===0){e.write("Set.new([])");break}e.write("Set.new(["),i.forEach((s,f)=>{f>0&&e.write(", "),s.write(e)}),e.write("])");break}case"list":{let i=this.internalType.values.filter(s=>!l.isNop(s));if(i.length===0){e.write("[]");break}if(i.length>=2&&i.every(s=>s instanceof l&&s.internalType.type==="str"&&!/[\s\\[\]]/.test(s.internalType.value))){let s=i.map(f=>f.internalType.value);e.write(`%w[${s.join(" ")}]`);break}e.write("["),i.forEach((s,f)=>{f>0&&e.write(", "),s.write(e)}),e.write("]");break}case"nop":break;case"nil":e.write("nil");break;default:L(this.internalType)}}};c();m();d();var rt;(function(l){l[l.Invariant=0]="Invariant",l.Covariant="out",l.Contravariant="in"})(rt||(rt={}));var be=class extends N{constructor({name:e,unchecked:i,bound:s,variance:f,defaultType:u}){super();y(this,"name");y(this,"unchecked");y(this,"bound");y(this,"variance");y(this,"defaultType");this.name=e,this.unchecked=i??!1,this.bound=s,this.variance=f??rt.Invariant,this.defaultType=u}write(e){}writeTypeDefinition(e){this.unchecked&&e.write("unchecked "),this.variance!=rt.Invariant&&e.write(`${this.variance} `),e.write(this.name),this.bound&&(e.write(" < "),this.bound.writeTypeDefinition(e)),this.defaultType&&(e.write(" = "),this.defaultType.writeTypeDefinition(e))}};c();m();d();var qe=class extends W{constructor(){super(...arguments);y(this,"initializer")}write(e){e.write(`&${this.name}`)}};c();m();d();var nt=class extends N{constructor({errorClass:e,message:i}){super();y(this,"errorClass");y(this,"message");this.errorClass=e,this.message=i}write(e){e.write("raise"),this.errorClass&&(e.write(" "),this.errorClass.write(e)),this.message&&(this.errorClass&&e.write(", "),this.message.write(e))}};function it(l){return new ye(l)}function lo(){return it("true")}function po(){return it("false")}function fo(){return it("nil")}var co={positional(l){return new _e(l)},keyword(l){return new xe(l)},positionalSplat(l){return new je(l)},keywordSplat(l){return new De(l)},yield(l){return new qe(l)}};function mo(l){return new ue(l)}function ho(l){return new ae(l)}function yo(l){return new se(l)}function go(l){return new X(l)}function xo(l){return new be(l)}function wo(l){return new ne(l)}function bo(l){return new he(l)}function vo(l){return new ge(l)}function Ao(l){return new we(l)}function Eo(l){return new Oe(l)}function To(l){return new tt(l)}function Io(l){return new et(l)}function ko(l){return new nt(l)}function Ro(l,t){let e=l;for(let i of t.toReversed())i.addStatement(e),e=i;return e}c();m();d();var ot=class l{constructor({context:t}){y(this,"context");this.context=t}convert(t){if(t.value===null)return this.context.isNullable(t.typeReference)?x.TypeLiteral.nil():(this.context.errors.add({severity:S.Critical,message:"Expected non-null value, but got null"}),x.TypeLiteral.nop());if(t.value===void 0)return x.TypeLiteral.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value});case"literal":return this.convertLiteral({literalType:t.typeReference.value,value:t.value});case"map":return this.convertMap({map:t.typeReference,value:t.value});case"named":{let e=this.context.resolveNamedType({typeId:t.typeReference.value});return e==null?x.TypeLiteral.nop():this.convertNamed({named:e,value:t.value,as:t.as})}case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as});case"set":return this.convertSet({set:t.typeReference.value,value:t.value});case"unknown":return x.TypeLiteral.nop();default:L(t.typeReference)}}convertLiteral({literalType:t,value:e}){switch(t.type){case"boolean":{let i=this.context.getValueAsBoolean({value:e});return i==null?x.TypeLiteral.nop():x.TypeLiteral.boolean(i)}case"string":{let i=this.context.getValueAsString({value:e});return i==null?x.TypeLiteral.nop():x.TypeLiteral.string(i)}default:L(t)}}convertList({list:t,value:e}){return Array.isArray(e)?x.TypeLiteral.list(e.map((i,s)=>{this.context.errors.scope({index:s});try{return this.convert({typeReference:t,value:i})}finally{this.context.errors.unscope()}})):(this.context.errors.add({severity:S.Critical,message:`Expected array but got: ${typeof e}`}),x.TypeLiteral.nop())}convertSet({set:t,value:e}){return Array.isArray(e)?x.TypeLiteral.set(e.map((i,s)=>{this.context.errors.scope({index:s});try{return this.convert({typeReference:t,value:i})}finally{this.context.errors.unscope()}})):(this.context.errors.add({severity:S.Critical,message:`Expected array but got: ${typeof e}`}),x.TypeLiteral.nop())}convertMap({map:t,value:e}){return typeof e!="object"||e==null?(this.context.errors.add({severity:S.Critical,message:`Expected object but got: ${e==null?"null":typeof e}`}),x.TypeLiteral.nop()):x.TypeLiteral.hash(Object.entries(e).map(([i,s])=>{this.context.errors.scope(i);try{return{key:this.convert({typeReference:t.key,value:i,as:"key"}),value:this.convert({typeReference:t.value,value:s})}}finally{this.context.errors.unscope()}}))}convertNamed({named:t,value:e,as:i}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference,value:e,as:i});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:e});case"object":return this.convertObject({object:t,value:e});case"enum":return this.convertEnum({enum_:t,value:e});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:e});default:L(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:e}){let i=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:e});if(i==null)return x.TypeLiteral.nop();let s=i.singleDiscriminatedUnionType,f=this.convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:i,unionVariant:s});return f==null?x.TypeLiteral.nop():x.TypeLiteral.hash(f)}convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:t,unionVariant:e}){switch(e.type){case"samePropertiesAsObject":{let i=this.context.resolveNamedType({typeId:e.typeId});if(i==null)return;let s=this.convertNamed({named:i,value:t.value});return this.extractHashEntries(s)}case"singleProperty":try{this.context.errors.scope(e.discriminantValue.wireValue);let i=this.context.getRecord(t.value);return i==null?[{key:x.TypeLiteral.string(this.context.getPropertyName(e.discriminantValue.name)),value:this.convert({typeReference:e.typeReference,value:t.value})}]:[{key:x.TypeLiteral.string(this.context.getPropertyName(e.discriminantValue.name)),value:this.convert({typeReference:e.typeReference,value:i[e.discriminantValue.wireValue]})}]}finally{this.context.errors.unscope()}case"noProperties":return[];default:L(e)}}extractHashEntries(t){t instanceof x.TypeLiteral}convertEnum({enum_:t,value:e}){let i=this.getEnumValueName({enum_:t,value:e});return i==null?x.TypeLiteral.nop():x.TypeLiteral.string(i)}getEnumValueName({enum_:t,value:e}){if(typeof e!="string"){this.context.errors.add({severity:S.Critical,message:`Expected enum value string, got: ${typeof e}`});return}let i=t.values.find(s=>s.wireValue===e);if(i==null){this.context.errors.add({severity:S.Critical,message:`An enum value named "${e}" does not exist in this context`});return}return i.wireValue}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:e}){let i=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:e});return i??x.TypeLiteral.nop()}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:e}){for(let i of t.types){let s=this.context.clone(),u=new l({context:s}).convert({typeReference:i,value:e});if(s.errors.empty())return u}this.context.errors.add({severity:S.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof e}" value`})}convertPrimitive({primitive:t,value:e,as:i}){switch(t){case"INTEGER":case"LONG":case"UINT":case"UINT_64":{let s=this.getValueAsNumber({value:e,as:i});return s==null?x.TypeLiteral.nop():x.TypeLiteral.integer(s)}case"FLOAT":case"DOUBLE":{let s=this.getValueAsNumber({value:e});return s==null?x.TypeLiteral.nop():x.TypeLiteral.float(s)}case"BOOLEAN":{let s=this.getValueAsBoolean({value:e,as:i});return s==null?x.TypeLiteral.nop():x.TypeLiteral.boolean(s)}case"BASE_64":case"BIG_INTEGER":case"STRING":{let s=this.context.getValueAsString({value:e});return s==null?x.TypeLiteral.nop():x.TypeLiteral.string(s)}case"UUID":{let s=this.context.getValueAsString({value:e});return s==null?x.TypeLiteral.nop():x.TypeLiteral.string(s)}case"DATE":{let s=this.context.getValueAsString({value:e});return s==null?x.TypeLiteral.nop():x.TypeLiteral.string(s)}case"DATE_TIME":{let s=this.context.getValueAsString({value:e});return s==null?x.TypeLiteral.nop():x.TypeLiteral.string(s)}default:L(t)}}convertObject({object:t,value:e}){return typeof e!="object"||e==null?(this.context.errors.add({severity:S.Critical,message:`Expected object but got: ${e==null?"null":typeof e}`}),x.TypeLiteral.nop()):x.TypeLiteral.hash(Object.entries(e).map(([i,s])=>{this.context.errors.scope(i);let f=t.properties.find(k=>k.name.wireValue===i),u=f?.typeReference??{type:"unknown"},E=f?.name.name.snakeCase.safeName??i,w={key:x.TypeLiteral.string(E),value:this.convert({typeReference:u,value:s})};return this.context.errors.unscope(),w}))}getValueAsNumber({value:t,as:e}){let i=e==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:i})}getValueAsBoolean({value:t,as:e}){let i=e==="key"?typeof t=="string"?t==="true":!!t:t;return this.context.getValueAsBoolean({value:i})}};var st=class l extends $e{constructor({ir:e,config:i}){super({ir:e,config:i});y(this,"ir");y(this,"customConfig");y(this,"dynamicTypeLiteralMapper");this.ir=e,this.customConfig=i.customConfig!=null?i.customConfig:void 0,this.dynamicTypeLiteralMapper=new ot({context:this})}clone(){return new l({ir:this.ir,config:this.config})}getRootClientClassReference(){return x.classReference({name:this.getRootClientClassName(),modules:[this.getRootModuleName()]})}getRootClientClassName(){return this.customConfig?.clientModuleName??"Client"}getRootModuleName(){return xt(this.customConfig?.moduleName??this.config.organization)}isSingleEnvironmentID(e){return typeof e=="string"}isMultiEnvironmentValues(e){return typeof e=="object"}getEnvironmentTypeReferenceFromID(e){let i=this.resolveEnvironmentName(e);if(i!=null)return x.codeblock(s=>{s.writeNode(this.getEnvironmentClassReference()),s.write("::"),s.write(this.getEnumName(i))})}getEnvironmentClassReference(){return x.classReference({name:"Environment",modules:[this.getRootModuleName()]})}getEnumName(e){return this.getName(e.screamingSnakeCase.safeName)}getMethodName(e){return this.getName(e.snakeCase.safeName)}getPropertyName(e){return this.getName(e.snakeCase.safeName)}getName(e){return e}};c();m();d();var Un="client",Bo="@client",at=class{constructor({context:t,formatter:e}){y(this,"context");y(this,"formatter");this.context=t,this.formatter=e}async generateSnippet({endpoint:t,request:e}){return await this.buildCodeBlock({endpoint:t,snippet:e}).toStringAsync({customConfig:this.context.customConfig??{},formatter:this.formatter})}generateSnippetSync({endpoint:t,request:e}){return this.buildCodeBlock({endpoint:t,snippet:e}).toString({customConfig:this.context.customConfig??{},formatter:this.formatter})}async generateSnippetAst({endpoint:t,request:e,options:i}){return i?.skipClientInstantiation?this.buildCodeBlockWithoutClient({endpoint:t,snippet:e}):this.buildCodeBlock({endpoint:t,snippet:e})}buildCodeBlock({endpoint:t,snippet:e}){return x.codeblock(i=>{i.writeNodeStatement(this.constructClient({endpoint:t,snippet:e})),i.newLine(),i.writeNodeStatement(this.callMethod({endpoint:t,snippet:e}))})}buildCodeBlockWithoutClient({endpoint:t,snippet:e}){return x.codeblock(i=>{i.writeNodeStatement(this.callMethodOnExistingClient({endpoint:t,snippet:e}))})}constructClient({endpoint:t,snippet:e}){return x.codeblock(i=>{i.addRequire(this.context.getRootModuleName().toLowerCase());let s=this.context.getRootClientClassReference(),f=this.getRootClientBuilderArgs({endpoint:t,snippet:e});i.write(`${Un} = `),i.writeNode(x.instantiateClass({classReference:s,arguments_:f}))})}getRootClientBaseUrlArg({baseUrl:t,environment:e}){if(t!=null&&e!=null)return this.context.errors.add({severity:"CRITICAL",message:"Cannot specify both baseUrl and environment options"}),[];if(t!=null)return[x.keywordArgument({name:"base_url",value:x.TypeLiteral.string(t)})];if(e!=null){if(this.context.isSingleEnvironmentID(e)){let i=this.context.getEnvironmentTypeReferenceFromID(e);return i==null?(this.context.errors.add({severity:"CRITICAL",message:`Environment ID ${e} not found`}),[]):[x.keywordArgument({name:"environment",value:i})]}if(this.context.isMultiEnvironmentValues(e))return this.context.errors.add({severity:"CRITICAL",message:"Multi-environment values are not supported in Ruby snippets yet"}),[]}return[]}getRootClientAuthArgs({auth:t,values:e}){if(e.type!==t.type)return this.addError(this.context.newAuthMismatchError({auth:t,values:e}).message),[];switch(t.type){case"basic":return e.type==="basic"?this.getRootClientBasicAuthArgs({auth:t,values:e}):[];case"bearer":return e.type==="bearer"?this.getRootClientBearerAuthArgs({auth:t,values:e}):[];case"header":return e.type==="header"?this.getRootClientHeaderAuthArgs({auth:t,values:e}):[];case"oauth":return e.type==="oauth"?this.getRootClientOAuthArgs({auth:t,values:e}):[];case"inferred":return[];default:L(t)}}addError(t){this.context.errors.add({severity:S.Critical,message:t})}addWarning(t){this.context.errors.add({severity:S.Warning,message:t})}getRootClientBasicAuthArgs({auth:t,values:e}){return[x.keywordArgument({name:t.username.snakeCase.safeName,value:x.TypeLiteral.string(e.username)}),x.keywordArgument({name:t.password.snakeCase.safeName,value:x.TypeLiteral.string(e.password)})]}getRootClientBearerAuthArgs({auth:t,values:e}){return[x.keywordArgument({name:t.token.snakeCase.safeName,value:x.TypeLiteral.string(e.token)})]}getRootClientHeaderAuthArgs({auth:t,values:e}){return[x.keywordArgument({name:t.header.name.name.snakeCase.safeName,value:x.TypeLiteral.string(e.value)})]}getRootClientOAuthArgs({auth:t,values:e}){return[x.keywordArgument({name:t.clientId.snakeCase.safeName,value:x.TypeLiteral.string(e.clientId)}),x.keywordArgument({name:t.clientSecret.snakeCase.safeName,value:x.TypeLiteral.string(e.clientSecret)})]}getRootClientHeaderArgs({headers:t,values:e}){let i=[];for(let s of t){let f=e[s.name.name.originalName];f!=null&&typeof f=="string"&&i.push(x.keywordArgument({name:s.name.name.snakeCase.safeName,value:x.TypeLiteral.string(f)}))}return i}getRootClientBuilderArgs({endpoint:t,snippet:e}){let i=[];t.auth!=null&&(e.auth!=null?i.push(...this.getRootClientAuthArgs({auth:t.auth,values:e.auth})):this.context.errors.add({severity:"WARNING",message:`Auth with ${t.auth.type} configuration is required for this endpoint`}));let s=this.getRootClientBaseUrlArg({baseUrl:e.baseURL,environment:e.environment});return s.length>0&&i.push(...s),this.context.errors.scope("Headers"),this.context.ir.headers!=null&&e.headers!=null&&i.push(...this.getRootClientHeaderArgs({headers:this.context.ir.headers,values:e.headers})),this.context.errors.unscope(),i}callMethod({endpoint:t,snippet:e}){let i={on:x.codeblock(Un),method:this.getMethod({endpoint:t}),arguments_:[]};switch(t.request.type){case"inlined":i.keywordArguments=this.getMethodArgsForInlinedRequest({request:t.request,snippet:e});break;case"body":i.keywordArguments=this.getMethodArgsForBodyRequest({request:t.request,snippet:e});break;default:L(t.request)}let s=this.getRequestOptions({endpoint:t,snippet:e});return s!=null&&(i.keywordArguments=i.keywordArguments??[],i.keywordArguments.push(s)),x.invokeMethod(i)}callMethodOnExistingClient({endpoint:t,snippet:e}){let i={on:x.codeblock(Bo),method:this.getMethod({endpoint:t}),arguments_:[]};switch(t.request.type){case"inlined":i.keywordArguments=this.getMethodArgsForInlinedRequest({request:t.request,snippet:e});break;case"body":i.keywordArguments=this.getMethodArgsForBodyRequest({request:t.request,snippet:e});break;default:L(t.request)}let s=this.getRequestOptions({endpoint:t,snippet:e});return s!=null&&(i.keywordArguments=i.keywordArguments??[],i.keywordArguments.push(s)),x.invokeMethod(i)}getRequestOptions({endpoint:t,snippet:e}){let i=e.headers??{},s=Object.entries(i);if(s.length===0)return;let f=new Set;if(this.context.ir.headers!=null)for(let w of this.context.ir.headers)f.add(w.name.wireValue.toLowerCase());if(t.request.type==="inlined"&&t.request.headers!=null)for(let w of t.request.headers)f.add(w.name.wireValue.toLowerCase());let u=s.filter(([w])=>!f.has(w.toLowerCase()));if(u.length===0)return;let E=u.map(([w,k])=>({key:x.TypeLiteral.string(w),value:x.TypeLiteral.string(String(k))}));return x.keywordArgument({name:"request_options",value:x.TypeLiteral.hash([{key:x.TypeLiteral.string("additional_headers"),value:x.TypeLiteral.hash(E)}])})}getMethodArgsForInlinedRequest({request:t,snippet:e}){let i=[];if(i.push(...this.getNamedParameterArgs({kind:"PathParameters",namedParameters:t.pathParameters,values:e.pathParameters})),i.push(...this.getNamedParameterArgs({kind:"QueryParameters",namedParameters:t.queryParameters,values:e.queryParameters})),i.push(...this.getNamedParameterArgs({kind:"Headers",namedParameters:t.headers,values:e.headers})),t.body!=null&&e.requestBody!=null)switch(t.body.type){case"properties":i.push(...this.getMethodArgsForPropertiesRequest({request:t.body,snippet:e}));break;case"referenced":{let s=t.body.bodyType;if(s.type==="typeReference"){let f=s.value;if(f.type==="named"){let u=this.context.resolveNamedType({typeId:f.value});if(u!=null&&u.type==="object"){let E=this.context.getRecord(e.requestBody);if(E!=null){let w=this.getBodyFieldsAsKeywordArgs({namedType:u,bodyRecord:E});i.push(...w)}}else if(u!=null){let E=this.getBodyArgsForNonObjectType({namedType:u,typeRef:f,bodyValue:e.requestBody});i.push(...E)}}else{let u=this.context.dynamicTypeLiteralMapper.convert({typeReference:f,value:e.requestBody});x.TypeLiteral.isNop(u)||i.push(x.keywordArgument({name:t.body.bodyKey.snakeCase.safeName,value:u}))}}break}case"fileUpload":break;default:L(t.body)}return i}getNamedParameterArgs({kind:t,namedParameters:e,values:i}){let s=[];if(this.context.errors.scope(t),e!=null){let f=this.context.associateByWireValue({parameters:e,values:i??{},ignoreMissingParameters:!0});for(let u of f){let E=this.context.dynamicTypeLiteralMapper.convert(u);x.TypeLiteral.isNop(E)||s.push(x.keywordArgument({name:this.context.getPropertyName(u.name.name),value:E}))}}return this.context.errors.unscope(),s}getMethodArgsForPropertiesRequest({request:t,snippet:e}){let i=[],s=this.context.associateByWireValue({parameters:t.value,values:this.context.getRecord(e.requestBody)??{}});for(let f of s){let u=this.context.dynamicTypeLiteralMapper.convert(f);x.TypeLiteral.isNop(u)||i.push(x.keywordArgument({name:this.context.getPropertyName(f.name.name),value:u}))}return i}getMethodArgsForBodyRequest({request:t,snippet:e}){let i=[];if(i.push(...this.getNamedParameterArgs({kind:"PathParameters",namedParameters:t.pathParameters,values:e.pathParameters})),t.body!=null&&e.requestBody!=null)switch(t.body.type){case"bytes":this.context.errors.add({severity:"CRITICAL",message:"Bytes request body is not supported in Ruby snippets yet"});break;case"typeReference":{let s=t.body.value;if(s.type==="named"){let f=this.context.resolveNamedType({typeId:s.value});if(f!=null&&f.type==="object"){let u=this.context.getRecord(e.requestBody);if(u!=null){let E=this.getBodyFieldsAsKeywordArgs({namedType:f,bodyRecord:u});i.push(...E)}}else if(f!=null){let u=this.getBodyArgsForNonObjectType({namedType:f,typeRef:s,bodyValue:e.requestBody});i.push(...u)}}else{let f=this.context.dynamicTypeLiteralMapper.convert({typeReference:s,value:e.requestBody});x.TypeLiteral.isNop(f)||i.push(x.keywordArgument({name:"request",value:f}))}break}default:L(t.body)}return i}getBodyArgsForNonObjectType({namedType:t,typeRef:e,bodyValue:i}){let s=[];switch(t.type){case"undiscriminatedUnion":{let f=this.context.getRecord(i);if(f!=null){for(let E of t.types)if(E.type==="named"){let w=this.context.resolveNamedType({typeId:E.value});if(w!=null&&w.type==="object"){let k=new Set(w.properties.map(D=>D.name.wireValue)),R=Object.keys(f);if(R.every(D=>k.has(D))&&R.length>0){let D=this.getBodyFieldsAsKeywordArgs({namedType:w,bodyRecord:f});return s.push(...D),s}}}}let u=this.context.dynamicTypeLiteralMapper.convert({typeReference:e,value:i});x.TypeLiteral.isNop(u)||s.push(x.keywordArgument({name:"request",value:u}));break}case"alias":{let f=t.typeReference;if(f.type==="named"){let E=this.context.resolveNamedType({typeId:f.value});if(E!=null&&E.type==="object"){let w=this.context.getRecord(i);if(w!=null){let k=this.getBodyFieldsAsKeywordArgs({namedType:E,bodyRecord:w});return s.push(...k),s}}}let u=this.context.dynamicTypeLiteralMapper.convert({typeReference:e,value:i});x.TypeLiteral.isNop(u)||s.push(x.keywordArgument({name:"request",value:u}));break}case"discriminatedUnion":case"enum":{let f=this.context.dynamicTypeLiteralMapper.convert({typeReference:e,value:i});x.TypeLiteral.isNop(f)||s.push(x.keywordArgument({name:"request",value:f}));break}case"object":break;default:L(t)}return s}getBodyFieldsAsKeywordArgs({namedType:t,bodyRecord:e}){let i=[];switch(t.type){case"object":{for(let s of t.properties){let f=s.name.wireValue,u=e[f];if(u!==void 0){this.context.errors.scope(f);let E=this.context.dynamicTypeLiteralMapper.convert({typeReference:s.typeReference,value:u});this.context.errors.unscope(),x.TypeLiteral.isNop(E)||i.push(x.keywordArgument({name:this.context.getPropertyName(s.name.name),value:E}))}}break}case"alias":case"discriminatedUnion":case"undiscriminatedUnion":case"enum":break;default:L(t)}return i}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(e=>`${this.context.getMethodName(e)}`).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}};var ut=class extends Pe{constructor({ir:e,config:i,formatter:s}){super(new st({ir:e,config:i}));y(this,"formatter");this.formatter=s}async generate(e){return super.generate(e)}generateSync(e){return super.generateSync(e)}async generateSnippetAst(e,i){return super.generateSnippetAst(e,i)}createSnippetGenerator(e){return new at({context:e,formatter:this.formatter})}};0&&(module.exports={DynamicSnippetsGenerator});
|
|
26
26
|
/*! Bundled license information:
|
|
27
27
|
|
|
28
28
|
@jspm/core/nodelibs/browser/chunk-DtuTasat.js:
|