@fern-api/swift-dynamic-snippets 0.1.0 → 0.1.1
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/cjs/DynamicSnippetsGenerator.cjs +19 -1
- package/cjs/DynamicSnippetsGenerator.cjs.map +1 -1
- package/cjs/EndpointSnippetGenerator.cjs +30 -1
- package/cjs/EndpointSnippetGenerator.cjs.map +1 -1
- package/cjs/context/DynamicSnippetsGeneratorContext.cjs +19 -1
- package/cjs/context/DynamicSnippetsGeneratorContext.cjs.map +1 -1
- package/cjs/context/DynamicTypeLiteralMapper.cjs +19 -1
- package/cjs/context/DynamicTypeLiteralMapper.cjs.map +1 -1
- package/cjs/context/DynamicTypeMapper.cjs +19 -1
- package/cjs/context/DynamicTypeMapper.cjs.map +1 -1
- package/cjs/context/FilePropertyMapper.cjs +30 -1
- package/cjs/context/FilePropertyMapper.cjs.map +1 -1
- package/cjs/context/index.cjs +19 -1
- package/cjs/context/index.cjs.map +1 -1
- package/cjs/index.cjs +29 -11
- package/cjs/index.cjs.map +1 -1
- package/esm/Config.js +1 -1
- package/esm/DynamicSnippetsGenerator.js +1 -1
- package/esm/EndpointSnippetGenerator.js +1 -1
- package/esm/{chunk-4YR7VIA5.js → chunk-2M2RBZK2.js} +2 -2
- package/esm/chunk-6DFEQNIA.js +2 -0
- package/esm/{chunk-NEAKFXXW.js.map → chunk-6DFEQNIA.js.map} +1 -1
- package/esm/chunk-7RC2HH3P.js +2 -0
- package/esm/{chunk-JBDWOK23.js.map → chunk-7RC2HH3P.js.map} +1 -1
- package/esm/chunk-FX6IFKZ7.js +2 -0
- package/esm/chunk-HTU5V5TT.js +2 -0
- package/esm/chunk-IHG2VZKL.js +2 -0
- package/esm/chunk-IHG2VZKL.js.map +1 -0
- package/esm/chunk-JFTYS7SI.js +20 -0
- package/esm/chunk-JFTYS7SI.js.map +1 -0
- package/esm/chunk-KIHSBETU.js +2 -0
- package/esm/{chunk-QKXS634U.js.map → chunk-KIHSBETU.js.map} +1 -1
- package/esm/chunk-PJTPV2D6.js +15 -0
- package/esm/chunk-PJTPV2D6.js.map +1 -0
- package/esm/{chunk-PKOEJ7HU.js → chunk-PYMG6Y4R.js} +2 -2
- package/esm/{chunk-P4BOVZKM.js → chunk-WG3NZOM6.js} +2 -2
- package/esm/chunk-WXHVUJ6D.js +2 -0
- package/esm/{chunk-T6A4SG7G.js.map → chunk-WXHVUJ6D.js.map} +1 -1
- package/esm/chunk-ZIQ5ITTV.js +2 -0
- package/esm/{chunk-F6NGJ242.js.map → chunk-ZIQ5ITTV.js.map} +1 -1
- package/esm/context/DynamicSnippetsGeneratorContext.js +1 -1
- package/esm/context/DynamicTypeLiteralMapper.js +1 -1
- package/esm/context/DynamicTypeMapper.js +1 -1
- package/esm/context/FilePropertyMapper.js +1 -1
- package/esm/context/index.js +1 -1
- package/esm/index.js +1 -1
- package/esm/index.js.map +1 -1
- package/esm/util/pascal-case.js +1 -1
- package/package.json +1 -1
- package/esm/chunk-243PMR4C.js +0 -2
- package/esm/chunk-7GLUP3NF.js +0 -2
- package/esm/chunk-7GLUP3NF.js.map +0 -1
- package/esm/chunk-BGT34OGK.js +0 -15
- package/esm/chunk-BGT34OGK.js.map +0 -1
- package/esm/chunk-F6NGJ242.js +0 -2
- package/esm/chunk-JBDWOK23.js +0 -2
- package/esm/chunk-NEAKFXXW.js +0 -2
- package/esm/chunk-NH2Q3QVN.js +0 -2
- package/esm/chunk-QKXS634U.js +0 -2
- package/esm/chunk-T6A4SG7G.js +0 -2
- /package/esm/{chunk-4YR7VIA5.js.map → chunk-2M2RBZK2.js.map} +0 -0
- /package/esm/{chunk-NH2Q3QVN.js.map → chunk-FX6IFKZ7.js.map} +0 -0
- /package/esm/{chunk-243PMR4C.js.map → chunk-HTU5V5TT.js.map} +0 -0
- /package/esm/{chunk-PKOEJ7HU.js.map → chunk-PYMG6Y4R.js.map} +0 -0
- /package/esm/{chunk-P4BOVZKM.js.map → chunk-WG3NZOM6.js.map} +0 -0
package/esm/Config.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./chunk-
|
|
1
|
+
import"./chunk-FX6IFKZ7.js";import"./chunk-PYMG6Y4R.js";
|
|
2
2
|
//# sourceMappingURL=Config.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
1
|
+
import{a}from"./chunk-WG3NZOM6.js";import"./chunk-HTU5V5TT.js";import"./chunk-WXHVUJ6D.js";import"./chunk-7RC2HH3P.js";import"./chunk-6DFEQNIA.js";import"./chunk-2M2RBZK2.js";import"./chunk-ZIQ5ITTV.js";import"./chunk-IHG2VZKL.js";import"./chunk-KIHSBETU.js";import"./chunk-JFTYS7SI.js";import"./chunk-PJTPV2D6.js";import"./chunk-PYMG6Y4R.js";export{a as DynamicSnippetsGenerator};
|
|
2
2
|
//# sourceMappingURL=DynamicSnippetsGenerator.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a}from"./chunk-
|
|
1
|
+
import{a}from"./chunk-WXHVUJ6D.js";import"./chunk-2M2RBZK2.js";import"./chunk-JFTYS7SI.js";import"./chunk-PJTPV2D6.js";import"./chunk-PYMG6Y4R.js";export{a as EndpointSnippetGenerator};
|
|
2
2
|
//# sourceMappingURL=EndpointSnippetGenerator.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as h,b as R}from"./chunk-7GLUP3NF.js";import{a as P,b as T,c as S,d as b,j as a,k as p,m as l}from"./chunk-PKOEJ7HU.js";p();l();p();l();var y=class{constructor(){a(this,"reporter");a(this,"snippet");a(this,"err");this.snippet=void 0,this.reporter=void 0,this.err=void 0}update({context:e,snippet:r}){this.shouldUpdate({snippet:r,reporter:e.errors})&&(this.reporter=e.errors.clone(),this.snippet=r)}getResponseOrThrow({endpoint:e}){var r;if(this.snippet!=null&&this.reporter!=null)return{snippet:this.snippet,errors:this.reporter.toDynamicSnippetErrors()};throw(r=this.err)!=null?r:new Error(`Failed to generate snippet for endpoint "${e.method} ${e.path}"`)}shouldUpdate({snippet:e,reporter:r}){var t,n;return this.reporter==null||this.reporter.size()>0&&r.size()===0?!0:e.length>((n=(t=this.snippet)==null?void 0:t.length)!=null?n:0)}};var E=class{constructor(e){a(this,"context");this.context=e}async generate(e,r={}){let t=this.context.resolveEndpointLocationOrThrow(e.endpoint);if(t.length===0)throw new Error(`No endpoints found that match "${e.endpoint.method} ${e.endpoint.path}"`);let n=new y;for(let i of t){let s=this.context.clone(),d=this.createSnippetGenerator(s);try{let u=await d.generateSnippet({endpoint:i,request:e,options:r});if(s.errors.empty())return{snippet:u,errors:void 0};n.update({context:s,snippet:u})}catch(u){n.err==null&&(n.err=u)}}return n.getResponseOrThrow({endpoint:e.endpoint})}generateSync(e,r={}){let t=this.context.resolveEndpointLocationOrThrow(e.endpoint);if(t.length===0)throw new Error(`No endpoints found that match "${e.endpoint.method} ${e.endpoint.path}"`);let n=new y;for(let i of t){let s=this.context.clone(),d=this.createSnippetGenerator(s);try{let u=d.generateSnippetSync({endpoint:i,request:e,options:r});if(s.errors.empty())return{snippet:u,errors:void 0};n.update({context:s,snippet:u})}catch(u){n.err==null&&(n.err=u)}}return n.getResponseOrThrow({endpoint:e.endpoint})}};p();l();var o={Critical:"CRITICAL",Warning:"WARNING"},v=class m{constructor(){a(this,"errors");a(this,"path");this.errors=[],this.path=[]}add(e){this.errors.push(T(P({},e),{path:[...this.path]}))}scope(e){this.path.push(e)}unscope(){this.path.pop()}getBySeverity(e){return this.errors.filter(r=>r.severity===e)}empty(){return this.errors.length===0}size(){return this.errors.length}clone(){let e=new m;return e.errors=[...this.errors],e.path=[...this.path],e}reset(){this.errors=[],this.path=[]}toDynamicSnippetErrors(){return this.errors.map(e=>({severity:e.severity,path:e.path!=null?this.pathToStringArray(e.path):void 0,message:e.message}))}pathToStringArray(e){let r=[];for(let t of e){if(typeof t=="string"){r.push(t);continue}r[r.length-1]+=`[${t.index}]`}return r}};p();l();p();l();p();l();var g=class{constructor(){a(this,"REFERENCE_REGEX",/^(GET|POST|PUT|DELETE|PATCH|HEAD)\s(\/\S*)$/)}validate(e){return this.REFERENCE_REGEX.test(e)?{type:"valid"}:{type:"invalid"}}tryParse(e){if(this.validate(e).type==="invalid")return;let t=e.match(this.REFERENCE_REGEX);if(!(t==null||t[1]==null||t[2]==null))return{method:t[1],path:t[2]}}};var w=class{constructor({ir:e,config:r,options:t={}}){a(this,"config");a(this,"options");a(this,"errors");a(this,"_ir");a(this,"httpEndpointReferenceParser");this._ir=e,this.config=r,this.options=t,this.errors=new v,this.httpEndpointReferenceParser=new g}associateQueryParametersByWireValue({parameters:e,values:r}){let t=[];for(let[n,i]of Object.entries(r)){this.errors.scope(n);try{let s=e.find(u=>u.name.wireValue===n);if(s==null)throw this.newParameterNotRecognizedError(n);let d=this.isListTypeReference(s.typeReference)&&!Array.isArray(i)?[i]:i;t.push({name:s.name,typeReference:s.typeReference,value:d})}finally{this.errors.unscope()}}return t}associateByWireValueOrDefault({parameters:e,values:r}){let t=[];for(let n of e){this.errors.scope(n.name.wireValue);try{let i=r[n.name.wireValue];if(i==null)if(n.typeReference.type==="primitive"&&n.typeReference.value==="STRING")i=`<${n.name.wireValue}>`;else{this.errors.add({severity:o.Critical,message:this.newParameterNotRecognizedError(n.name.wireValue).message});continue}t.push({name:n.name,typeReference:n.typeReference,value:i})}finally{this.errors.unscope()}}return t}associateByWireValue({parameters:e,values:r,ignoreMissingParameters:t}){let n=[];for(let[i,s]of Object.entries(r)){this.errors.scope(i);try{let d=e.find(u=>u.name.wireValue===i);if(d==null){if(t)continue;this.errors.add({severity:o.Critical,message:this.newParameterNotRecognizedError(i).message});continue}n.push({name:d.name,typeReference:d.typeReference,value:s})}finally{this.errors.unscope()}}return n}getExampleObjectProperties({parameters:e,snippetObject:r}){let t=typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{},n=[];for(let i of e){let s=t[i.name.wireValue];s==null?i.typeReference.type==="nullable"&&n.push({name:i.name,typeReference:i.typeReference,value:null}):n.push({name:i.name,typeReference:i.typeReference,value:s})}return n}getSingleFileValue({property:e,record:r}){let t=r[e.wireValue];if(t!=null){if(typeof t!="string"){this.errors.add({severity:o.Critical,message:`Expected file value to be a string, got ${typeof t}`});return}return t}}getFileArrayValues({property:e,record:r}){let t=r[e.wireValue];if(t==null)return;if(!Array.isArray(t)){this.errors.add({severity:o.Critical,message:`Expected file array value to be an array of strings, got ${typeof t}`});return}let n=[];for(let i of t){if(typeof i!="string"){this.errors.add({severity:o.Critical,message:`Expected file array value to be an array of strings, got ${typeof i}`});return}n.push(i)}return n}getRecord(e){if(typeof e!="object"||Array.isArray(e)){this.errors.add({severity:o.Critical,message:`Expected object with key, value pairs but got: ${Array.isArray(e)?"array":typeof e}`});return}return e==null?{}:e}resolveNamedType({typeId:e}){let r=this._ir.types[e];if(r==null){this.errors.add({severity:o.Critical,message:`Type identified by "${e}" could not be found`});return}return r}resolveDiscriminatedUnionTypeInstance({discriminatedUnion:e,value:r}){let t=this.getRecord(r);if(t==null)return;let n=e.discriminant.wireValue,i=t[n];if(i==null){this.errors.add({severity:o.Critical,message:this.newParameterNotRecognizedError(n).message});return}if(typeof i!="string"){this.errors.add({severity:o.Critical,message:`Expected discriminant value to be a string but got: ${typeof i}`});return}let s=e.types[i];if(s==null){this.errors.add({severity:o.Critical,message:`No type found for discriminant value "${i}"`});return}let x=t,{[n]:d}=x,u=b(x,[S(n)]);return{singleDiscriminatedUnionType:s,discriminantValue:s.discriminantValue,value:u}}resolveEndpointOrThrow(e){let r=this.httpEndpointReferenceParser.tryParse(e);if(r==null)throw new Error(`Failed to parse endpoint reference "${e}"`);return this.resolveEndpointLocationOrThrow(r)}resolveEndpointLocation(e){let r=[];for(let t of Object.values(this._ir.endpoints))this.parsedEndpointMatches({endpoint:t,parsedEndpoint:e})&&r.push(t);return r}resolveEndpointLocationOrThrow(e){let r=this.resolveEndpointLocation(e);if(r.length===0)throw new Error(`Failed to find endpoint identified by "${e.method} ${e.path}"`);return r}needsRequestParameter({request:e,inlinePathParameters:r,inlineFileProperties:t}){var n;return this.includePathParametersInWrappedRequest({request:e,inlinePathParameters:r})||e.queryParameters!=null&&e.queryParameters.length>0||e.headers!=null&&e.headers.length>0?!0:e.body!=null?this.includeRequestBodyInWrappedRequest({body:e.body,inlineFileProperties:t}):!((n=e.metadata)!=null&&n.onlyPathParameters)}includePathParametersInWrappedRequest({request:e,inlinePathParameters:r}){var t,n;return r&&((n=(t=e.metadata)==null?void 0:t.includePathParameters)!=null?n:!1)}isFileUploadRequestBody(e){switch(e.type){case"fileUpload":return!0;case"properties":case"referenced":return!1;default:h(e)}}resolveEnvironmentName(e){if(this._ir.environments==null)return;let r=this._ir.environments.environments;switch(r.type){case"singleBaseUrl":{let t=r.environments.find(n=>n.id===e);return t==null?void 0:t.name}case"multipleBaseUrls":{let t=r.environments.find(n=>n.id===e);return t==null?void 0:t.name}default:h(r)}}isSingleEnvironmentID(e){return typeof e=="string"}isMultiEnvironmentValues(e){return typeof e=="object"}validateMultiEnvironmentUrlValues(e){if(this._ir.environments==null)return this.errors.add({severity:o.Critical,message:"Multiple environments are not supported for single base URL environments; use the baseUrl option instead"}),!1;let r=this._ir.environments.environments;switch(r.type){case"singleBaseUrl":return this.errors.add({severity:o.Critical,message:"Multiple environments are not supported for single base URL environments; use the baseUrl option instead"}),!1;case"multipleBaseUrls":{let t=r.environments[0];if(t==null)return this.errors.add({severity:o.Critical,message:"Multiple environments are not supported; use the baseUrl option instead"}),!1;let n=new Set(R(t.urls));for(let i of R(e))n.has(i)&&n.delete(i);return n.size>0?(this.errors.add({severity:o.Critical,message:`The provided environments are invalid; got: [${Object.keys(e).join(", ")}], expected: [${R(t.urls).join(", ")}]`}),!1):!0}}}getValueAsNumber({value:e}){if(typeof e!="number"){this.errors.add({severity:o.Critical,message:this.newTypeMismatchError({expected:"number",value:e}).message});return}return e}getValueAsBoolean({value:e}){if(typeof e!="boolean"){this.errors.add({severity:o.Critical,message:this.newTypeMismatchError({expected:"boolean",value:e}).message});return}return e}getValueAsString({value:e}){if(typeof e!="string"){this.errors.add({severity:o.Critical,message:this.newTypeMismatchError({expected:"string",value:e}).message});return}return e}isOptional(e){switch(e.type){case"nullable":return this.isOptional(e.value);case"optional":return!0;case"named":{let r=this.resolveNamedType({typeId:e.value});return r==null?!1:r.type==="alias"?this.isNullable(r.typeReference):!1}}return!1}isNullable(e){switch(e.type){case"nullable":return!0;case"optional":return this.isNullable(e.value);case"named":{let r=this.resolveNamedType({typeId:e.value});return r==null?!1:r.type==="alias"?this.isNullable(r.typeReference):!1}}return!1}newAuthMismatchError({auth:e,values:r}){return new Error(`Expected auth type ${e.type}, got ${r.type}`)}newParameterNotRecognizedError(e){return new Error(`"${e}" is not a recognized parameter for this endpoint`)}newTypeMismatchError({expected:e,value:r}){return new Error(`Expected ${e}, got ${typeof r}`)}includeRequestBodyInWrappedRequest({body:e,inlineFileProperties:r}){switch(e.type){case"properties":case"referenced":return!0;case"fileUpload":return this.includeFileUploadBodyInWrappedRequest({fileUpload:e,inlineFileProperties:r});default:h(e)}}includeFileUploadBodyInWrappedRequest({fileUpload:e,inlineFileProperties:r}){return this.fileUploadHasBodyProperties({fileUpload:e})||r&&this.fileUploadHasFileProperties({fileUpload:e})}fileUploadHasBodyProperties({fileUpload:e}){return e.properties.some(r=>{switch(r.type){case"file":case"fileArray":return!1;case"bodyProperty":return!0;default:h(r)}})}fileUploadHasFileProperties({fileUpload:e}){return e.properties.some(r=>{switch(r.type){case"file":case"fileArray":return!0;case"bodyProperty":return!1;default:h(r)}})}isListTypeReference(e){return e.type==="optional"?this.isListTypeReference(e.value):e.type==="list"||e.type==="set"}parsedEndpointMatches({endpoint:e,parsedEndpoint:r}){return e.location.method===r.method&&e.location.path===r.path}};p();l();var A={PathParameters:"pathParameters",QueryParameters:"queryParameters",Headers:"headers",RequestBody:"requestBody"};p();l();export{E as a,o as b,w as c,A as d};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as h,b as R}from"./chunk-JFTYS7SI.js";import{a as P,b as T,c as S,d as b,j as a,l as p,n as l}from"./chunk-PYMG6Y4R.js";p();l();p();l();var y=class{constructor(){a(this,"reporter");a(this,"snippet");a(this,"err");this.snippet=void 0,this.reporter=void 0,this.err=void 0}update({context:e,snippet:r}){this.shouldUpdate({snippet:r,reporter:e.errors})&&(this.reporter=e.errors.clone(),this.snippet=r)}getResponseOrThrow({endpoint:e}){var r;if(this.snippet!=null&&this.reporter!=null)return{snippet:this.snippet,errors:this.reporter.toDynamicSnippetErrors()};throw(r=this.err)!=null?r:new Error(`Failed to generate snippet for endpoint "${e.method} ${e.path}"`)}shouldUpdate({snippet:e,reporter:r}){var t,n;return this.reporter==null||this.reporter.size()>0&&r.size()===0?!0:e.length>((n=(t=this.snippet)==null?void 0:t.length)!=null?n:0)}};var E=class{constructor(e){a(this,"context");this.context=e}async generate(e,r={}){let t=this.context.resolveEndpointLocationOrThrow(e.endpoint);if(t.length===0)throw new Error(`No endpoints found that match "${e.endpoint.method} ${e.endpoint.path}"`);let n=new y;for(let i of t){let s=this.context.clone(),d=this.createSnippetGenerator(s);try{let u=await d.generateSnippet({endpoint:i,request:e,options:r});if(s.errors.empty())return{snippet:u,errors:void 0};n.update({context:s,snippet:u})}catch(u){n.err==null&&(n.err=u)}}return n.getResponseOrThrow({endpoint:e.endpoint})}generateSync(e,r={}){let t=this.context.resolveEndpointLocationOrThrow(e.endpoint);if(t.length===0)throw new Error(`No endpoints found that match "${e.endpoint.method} ${e.endpoint.path}"`);let n=new y;for(let i of t){let s=this.context.clone(),d=this.createSnippetGenerator(s);try{let u=d.generateSnippetSync({endpoint:i,request:e,options:r});if(s.errors.empty())return{snippet:u,errors:void 0};n.update({context:s,snippet:u})}catch(u){n.err==null&&(n.err=u)}}return n.getResponseOrThrow({endpoint:e.endpoint})}};p();l();var o={Critical:"CRITICAL",Warning:"WARNING"},v=class m{constructor(){a(this,"errors");a(this,"path");this.errors=[],this.path=[]}add(e){this.errors.push(T(P({},e),{path:[...this.path]}))}scope(e){this.path.push(e)}unscope(){this.path.pop()}getBySeverity(e){return this.errors.filter(r=>r.severity===e)}empty(){return this.errors.length===0}size(){return this.errors.length}clone(){let e=new m;return e.errors=[...this.errors],e.path=[...this.path],e}reset(){this.errors=[],this.path=[]}toDynamicSnippetErrors(){return this.errors.map(e=>({severity:e.severity,path:e.path!=null?this.pathToStringArray(e.path):void 0,message:e.message}))}pathToStringArray(e){let r=[];for(let t of e){if(typeof t=="string"){r.push(t);continue}r[r.length-1]+=`[${t.index}]`}return r}};p();l();p();l();p();l();var g=class{constructor(){a(this,"REFERENCE_REGEX",/^(GET|POST|PUT|DELETE|PATCH|HEAD)\s(\/\S*)$/)}validate(e){return this.REFERENCE_REGEX.test(e)?{type:"valid"}:{type:"invalid"}}tryParse(e){if(this.validate(e).type==="invalid")return;let t=e.match(this.REFERENCE_REGEX);if(!(t==null||t[1]==null||t[2]==null))return{method:t[1],path:t[2]}}};var w=class{constructor({ir:e,config:r,options:t={}}){a(this,"config");a(this,"options");a(this,"errors");a(this,"_ir");a(this,"httpEndpointReferenceParser");this._ir=e,this.config=r,this.options=t,this.errors=new v,this.httpEndpointReferenceParser=new g}associateQueryParametersByWireValue({parameters:e,values:r}){let t=[];for(let[n,i]of Object.entries(r)){this.errors.scope(n);try{let s=e.find(u=>u.name.wireValue===n);if(s==null)throw this.newParameterNotRecognizedError(n);let d=this.isListTypeReference(s.typeReference)&&!Array.isArray(i)?[i]:i;t.push({name:s.name,typeReference:s.typeReference,value:d})}finally{this.errors.unscope()}}return t}associateByWireValueOrDefault({parameters:e,values:r}){let t=[];for(let n of e){this.errors.scope(n.name.wireValue);try{let i=r[n.name.wireValue];if(i==null)if(n.typeReference.type==="primitive"&&n.typeReference.value==="STRING")i=`<${n.name.wireValue}>`;else{this.errors.add({severity:o.Critical,message:this.newParameterNotRecognizedError(n.name.wireValue).message});continue}t.push({name:n.name,typeReference:n.typeReference,value:i})}finally{this.errors.unscope()}}return t}associateByWireValue({parameters:e,values:r,ignoreMissingParameters:t}){let n=[];for(let[i,s]of Object.entries(r)){this.errors.scope(i);try{let d=e.find(u=>u.name.wireValue===i);if(d==null){if(t)continue;this.errors.add({severity:o.Critical,message:this.newParameterNotRecognizedError(i).message});continue}n.push({name:d.name,typeReference:d.typeReference,value:s})}finally{this.errors.unscope()}}return n}getExampleObjectProperties({parameters:e,snippetObject:r}){let t=typeof r=="object"&&r!==null&&!Array.isArray(r)?r:{},n=[];for(let i of e){let s=t[i.name.wireValue];s==null?i.typeReference.type==="nullable"&&n.push({name:i.name,typeReference:i.typeReference,value:null}):n.push({name:i.name,typeReference:i.typeReference,value:s})}return n}getSingleFileValue({property:e,record:r}){let t=r[e.wireValue];if(t!=null){if(typeof t!="string"){this.errors.add({severity:o.Critical,message:`Expected file value to be a string, got ${typeof t}`});return}return t}}getFileArrayValues({property:e,record:r}){let t=r[e.wireValue];if(t==null)return;if(!Array.isArray(t)){this.errors.add({severity:o.Critical,message:`Expected file array value to be an array of strings, got ${typeof t}`});return}let n=[];for(let i of t){if(typeof i!="string"){this.errors.add({severity:o.Critical,message:`Expected file array value to be an array of strings, got ${typeof i}`});return}n.push(i)}return n}getRecord(e){if(typeof e!="object"||Array.isArray(e)){this.errors.add({severity:o.Critical,message:`Expected object with key, value pairs but got: ${Array.isArray(e)?"array":typeof e}`});return}return e==null?{}:e}resolveNamedType({typeId:e}){let r=this._ir.types[e];if(r==null){this.errors.add({severity:o.Critical,message:`Type identified by "${e}" could not be found`});return}return r}resolveDiscriminatedUnionTypeInstance({discriminatedUnion:e,value:r}){let t=this.getRecord(r);if(t==null)return;let n=e.discriminant.wireValue,i=t[n];if(i==null){this.errors.add({severity:o.Critical,message:this.newParameterNotRecognizedError(n).message});return}if(typeof i!="string"){this.errors.add({severity:o.Critical,message:`Expected discriminant value to be a string but got: ${typeof i}`});return}let s=e.types[i];if(s==null){this.errors.add({severity:o.Critical,message:`No type found for discriminant value "${i}"`});return}let x=t,{[n]:d}=x,u=b(x,[S(n)]);return{singleDiscriminatedUnionType:s,discriminantValue:s.discriminantValue,value:u}}resolveEndpointOrThrow(e){let r=this.httpEndpointReferenceParser.tryParse(e);if(r==null)throw new Error(`Failed to parse endpoint reference "${e}"`);return this.resolveEndpointLocationOrThrow(r)}resolveEndpointLocation(e){let r=[];for(let t of Object.values(this._ir.endpoints))this.parsedEndpointMatches({endpoint:t,parsedEndpoint:e})&&r.push(t);return r}resolveEndpointLocationOrThrow(e){let r=this.resolveEndpointLocation(e);if(r.length===0)throw new Error(`Failed to find endpoint identified by "${e.method} ${e.path}"`);return r}needsRequestParameter({request:e,inlinePathParameters:r,inlineFileProperties:t}){var n;return this.includePathParametersInWrappedRequest({request:e,inlinePathParameters:r})||e.queryParameters!=null&&e.queryParameters.length>0||e.headers!=null&&e.headers.length>0?!0:e.body!=null?this.includeRequestBodyInWrappedRequest({body:e.body,inlineFileProperties:t}):!((n=e.metadata)!=null&&n.onlyPathParameters)}includePathParametersInWrappedRequest({request:e,inlinePathParameters:r}){var t,n;return r&&((n=(t=e.metadata)==null?void 0:t.includePathParameters)!=null?n:!1)}isFileUploadRequestBody(e){switch(e.type){case"fileUpload":return!0;case"properties":case"referenced":return!1;default:h(e)}}resolveEnvironmentName(e){if(this._ir.environments==null)return;let r=this._ir.environments.environments;switch(r.type){case"singleBaseUrl":{let t=r.environments.find(n=>n.id===e);return t==null?void 0:t.name}case"multipleBaseUrls":{let t=r.environments.find(n=>n.id===e);return t==null?void 0:t.name}default:h(r)}}isSingleEnvironmentID(e){return typeof e=="string"}isMultiEnvironmentValues(e){return typeof e=="object"}validateMultiEnvironmentUrlValues(e){if(this._ir.environments==null)return this.errors.add({severity:o.Critical,message:"Multiple environments are not supported for single base URL environments; use the baseUrl option instead"}),!1;let r=this._ir.environments.environments;switch(r.type){case"singleBaseUrl":return this.errors.add({severity:o.Critical,message:"Multiple environments are not supported for single base URL environments; use the baseUrl option instead"}),!1;case"multipleBaseUrls":{let t=r.environments[0];if(t==null)return this.errors.add({severity:o.Critical,message:"Multiple environments are not supported; use the baseUrl option instead"}),!1;let n=new Set(R(t.urls));for(let i of R(e))n.has(i)&&n.delete(i);return n.size>0?(this.errors.add({severity:o.Critical,message:`The provided environments are invalid; got: [${Object.keys(e).join(", ")}], expected: [${R(t.urls).join(", ")}]`}),!1):!0}}}getValueAsNumber({value:e}){if(typeof e!="number"){this.errors.add({severity:o.Critical,message:this.newTypeMismatchError({expected:"number",value:e}).message});return}return e}getValueAsBoolean({value:e}){if(typeof e!="boolean"){this.errors.add({severity:o.Critical,message:this.newTypeMismatchError({expected:"boolean",value:e}).message});return}return e}getValueAsString({value:e}){if(typeof e!="string"){this.errors.add({severity:o.Critical,message:this.newTypeMismatchError({expected:"string",value:e}).message});return}return e}isOptional(e){switch(e.type){case"nullable":return this.isOptional(e.value);case"optional":return!0;case"named":{let r=this.resolveNamedType({typeId:e.value});return r==null?!1:r.type==="alias"?this.isNullable(r.typeReference):!1}}return!1}isNullable(e){switch(e.type){case"nullable":return!0;case"optional":return this.isNullable(e.value);case"named":{let r=this.resolveNamedType({typeId:e.value});return r==null?!1:r.type==="alias"?this.isNullable(r.typeReference):!1}}return!1}newAuthMismatchError({auth:e,values:r}){return new Error(`Expected auth type ${e.type}, got ${r.type}`)}newParameterNotRecognizedError(e){return new Error(`"${e}" is not a recognized parameter for this endpoint`)}newTypeMismatchError({expected:e,value:r}){return new Error(`Expected ${e}, got ${typeof r}`)}includeRequestBodyInWrappedRequest({body:e,inlineFileProperties:r}){switch(e.type){case"properties":case"referenced":return!0;case"fileUpload":return this.includeFileUploadBodyInWrappedRequest({fileUpload:e,inlineFileProperties:r});default:h(e)}}includeFileUploadBodyInWrappedRequest({fileUpload:e,inlineFileProperties:r}){return this.fileUploadHasBodyProperties({fileUpload:e})||r&&this.fileUploadHasFileProperties({fileUpload:e})}fileUploadHasBodyProperties({fileUpload:e}){return e.properties.some(r=>{switch(r.type){case"file":case"fileArray":return!1;case"bodyProperty":return!0;default:h(r)}})}fileUploadHasFileProperties({fileUpload:e}){return e.properties.some(r=>{switch(r.type){case"file":case"fileArray":return!0;case"bodyProperty":return!1;default:h(r)}})}isListTypeReference(e){return e.type==="optional"?this.isListTypeReference(e.value):e.type==="list"||e.type==="set"}parsedEndpointMatches({endpoint:e,parsedEndpoint:r}){return e.location.method===r.method&&e.location.path===r.path}};p();l();var A={PathParameters:"pathParameters",QueryParameters:"queryParameters",Headers:"headers",RequestBody:"requestBody"};p();l();export{E as a,o as b,w as c,A as d};
|
|
2
|
+
//# sourceMappingURL=chunk-2M2RBZK2.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{b as o}from"./chunk-2M2RBZK2.js";import{a as x}from"./chunk-ZIQ5ITTV.js";import{a,c as l,d as y,e as u,f as t}from"./chunk-JFTYS7SI.js";import{j as m,l as d,n as f}from"./chunk-PYMG6Y4R.js";d();f();var v=class{constructor({context:e}){m(this,"context");this.context=e}convert(e){switch(e.typeReference.type){case"list":return this.convertList({list:e.typeReference.value,value:e.value});case"literal":{if(e.typeReference.value.type==="string")return t.Expression.enumCaseShorthand(y.generateEnumCaseLabel(e.typeReference.value.value));if(e.typeReference.value.type==="boolean")return t.Expression.nop();a(e.typeReference.value);break}case"map":return this.convertMap({map:e.typeReference,value:e.value});case"named":{let n=this.context.resolveNamedType({typeId:e.typeReference.value});return n==null?t.Expression.nop():this.convertNamed({named:n,value:e.value,as:e.as})}case"nullable":return this.convertNullable({nullable:e.typeReference,value:e.value,as:e.as});case"optional":return this.convert({typeReference:e.typeReference.value,value:e.value,as:e.as});case"primitive":return this.convertPrimitive({primitive:e.typeReference.value,value:e.value,as:e.as});case"set":return t.Expression.nop();case"unknown":return this.convertUnknown(e.value);default:a(e.typeReference)}}convertList({list:e,value:n}){return Array.isArray(n)?t.Expression.arrayLiteral({elements:n.map((i,r)=>{this.context.errors.scope({index:r});try{return this.convert({typeReference:e,value:i})}finally{this.context.errors.unscope()}}),multiline:!0}):(this.context.errors.add({severity:o.Critical,message:`Expected array but got: ${typeof n}`}),t.Expression.nop())}convertMap({map:e,value:n}){return typeof n!="object"||n==null?(this.context.errors.add({severity:o.Critical,message:`Expected object but got: ${n==null?"null":typeof n}`}),t.Expression.nop()):t.Expression.dictionaryLiteral({entries:Object.entries(n).map(([i,r])=>{this.context.errors.scope(i);try{return[this.convert({typeReference:e.key,value:i,as:"mapKey"}),this.convert({typeReference:e.value,value:r,as:"mapValue"})]}finally{this.context.errors.unscope()}}),multiline:!0})}convertNamed({named:e,value:n,as:i}){switch(e.type){case"alias":return this.convert({typeReference:e.typeReference,value:n,as:i});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:e,value:n});case"enum":return this.convertEnum({enum_:e,value:n});case"object":return this.convertObject({object_:e,value:n,as:i});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:e,value:n});default:a(e)}}convertNullable({nullable:e,value:n,as:i}){return n==null?t.Expression.enumCaseShorthand("null"):t.Expression.contextualMethodCall({methodName:"value",arguments_:[t.functionArgument({value:this.convert({typeReference:e.value,value:n,as:i})})]})}convertDiscriminatedUnion({discriminatedUnion:e,value:n}){let i=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:e,value:n});if(i==null)return t.Expression.nop();let r=i.singleDiscriminatedUnionType,s=this.convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:i,unionVariant:r});return s==null?t.Expression.nop():t.Expression.methodCall({target:t.Expression.reference(e.declaration.name.pascalCase.unsafeName),methodName:l.sanitizeToCamelCase(r.discriminantValue.name.camelCase.unsafeName),arguments_:[t.functionArgument({value:t.Expression.contextualMethodCall({methodName:"init",arguments_:s,multiline:!0})})],multiline:!0})}convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:e,unionVariant:n}){var r;let i=this.getBaseFields({discriminatedUnionTypeInstance:e,singleDiscriminatedUnionType:n});switch(n.type){case"samePropertiesAsObject":{let s=this.context.resolveNamedType({typeId:n.typeId});if(s==null)return;let c=this.convertNamed({named:s,value:e.value});if(!c.isStructInitialization()){this.context.errors.add({severity:o.Critical,message:"Internal error; expected union value to be a struct"});return}let p=c.asStructInitializationOrThrow();return[...i,...(r=p.arguments_)!=null?r:[]]}case"singleProperty":try{this.context.errors.scope(n.discriminantValue.wireValue);let s=this.context.getRecord(e.value);return s==null?[...i]:[...i,t.functionArgument({label:u(l.sanitizeToCamelCase(n.discriminantValue.name.camelCase.unsafeName)),value:this.convert({typeReference:n.typeReference,value:s[n.discriminantValue.wireValue]})})]}finally{this.context.errors.unscope()}case"noProperties":return i;default:a(n)}}getBaseFields({discriminatedUnionTypeInstance:e,singleDiscriminatedUnionType:n}){var r;return this.context.getExampleObjectProperties({parameters:(r=n.properties)!=null?r:[],snippetObject:e.value}).map(s=>{this.context.errors.scope(s.name.wireValue);try{return t.functionArgument({label:u(s.name.name.camelCase.unsafeName),value:this.convert(s)})}finally{this.context.errors.unscope()}})}convertEnum({enum_:e,value:n}){let i=this.getEnumValue({enum_:e,value:n});return i==null?t.Expression.nop():t.Expression.enumCaseShorthand(i.name.camelCase.unsafeName)}getEnumValue({enum_:e,value:n}){if(typeof n!="string"){this.context.errors.add({severity:o.Critical,message:`Expected enum value string, got: ${typeof n}`});return}let i=e.values.find(r=>r.wireValue===n);if(i==null){this.context.errors.add({severity:o.Critical,message:`An enum value named "${n}" does not exist in this context`});return}return i}convertObject({object_:e,value:n,as:i}){return t.Expression.structInitialization({unsafeName:e.declaration.name.pascalCase.unsafeName,arguments_:this.context.getExampleObjectProperties({parameters:e.properties,snippetObject:n}).map(r=>this.convert(r).isNop()?null:t.functionArgument({label:u(r.name.name.camelCase.unsafeName),value:this.convert(r)})).filter(r=>r!=null),multiline:!0})}convertUndiscriminatedUnion({undiscriminatedUnion:e,value:n}){let i=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:e,value:n});return i==null?t.Expression.nop():i}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:e,value:n}){for(let i of e.types)try{let r=this.convert({typeReference:i,value:n}),c=new x({context:this.context}).convert({typeReference:i});return t.Expression.methodCall({target:t.Expression.reference(e.declaration.name.pascalCase.unsafeName),methodName:c.toCaseName(),arguments_:[t.functionArgument({value:r})],multiline:!0})}catch(r){continue}this.context.errors.add({severity:o.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof n}" value`})}convertUnknown(e){switch(typeof e){case"boolean":return t.Expression.contextualMethodCall({methodName:"bool",arguments_:[t.functionArgument({value:t.Expression.boolLiteral(e)})]});case"string":return t.Expression.contextualMethodCall({methodName:"string",arguments_:[t.functionArgument({value:t.Expression.stringLiteral(e)})]});case"number":return t.Expression.contextualMethodCall({methodName:"number",arguments_:[t.functionArgument({value:t.Expression.numberLiteral(e)})]});case"object":return e===null?t.Expression.enumCaseShorthand("null"):Array.isArray(e)?t.Expression.contextualMethodCall({methodName:"array",arguments_:[t.functionArgument({value:t.Expression.arrayLiteral({elements:e.map(n=>this.convertUnknown(n)),multiline:!0})})]}):t.Expression.contextualMethodCall({methodName:"object",arguments_:[t.functionArgument({value:t.Expression.dictionaryLiteral({entries:Object.entries(e).map(([n,i])=>[t.Expression.stringLiteral(n),this.convertUnknown(i)]),multiline:!0})})]});default:throw new Error(`Internal error; unsupported unknown type: ${typeof e}`)}}convertPrimitive({primitive:e,value:n,as:i}){switch(e){case"INTEGER":case"UINT":case"LONG":case"UINT_64":case"FLOAT":case"DOUBLE":{let r=this.getValueAsNumber({value:n,as:i});return r==null?t.Expression.nop():t.Expression.numberLiteral(r)}case"BOOLEAN":{let r=this.getValueAsBoolean({value:n,as:i});return r==null?t.Expression.nop():t.Expression.boolLiteral(r)}case"STRING":{let r=this.context.getValueAsString({value:n});return r==null?t.Expression.nop():t.Expression.stringLiteral(r)}case"DATE":{let r=this.context.getValueAsString({value:n});return r==null?t.Expression.nop():t.Expression.calendarDateLiteral(r)}case"DATE_TIME":{let r=this.context.getValueAsString({value:n});if(r==null)return t.Expression.nop();let s=new Date(r).getTime(),c=Math.round(s/1e3),h=new Date(c*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");return t.Expression.dateLiteral(h)}case"UUID":{let r=this.context.getValueAsString({value:n});return r==null?t.Expression.nop():t.Expression.uuidLiteral(r)}case"BASE_64":{let r=this.context.getValueAsString({value:n});return r==null?t.Expression.nop():t.Expression.stringLiteral(r)}case"BIG_INTEGER":return this.context.getValueAsString({value:n})==null?t.Expression.nop():t.Expression.nop();default:a(e)}}getValueAsNumber({value:e,as:n}){let i=n==="mapKey"&&typeof e=="string"?Number(e):e;return this.context.getValueAsNumber({value:i})}getValueAsBoolean({value:e,as:n}){let i=(()=>{switch(n){case"mapKey":return e==="true"?!0:e==="false"?!1:e;case"mapValue":case void 0:return e;default:a(n)}})();return this.context.getValueAsBoolean({value:i})}};export{v as a};
|
|
2
|
+
//# sourceMappingURL=chunk-6DFEQNIA.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/context/DynamicTypeLiteralMapper.ts"],"sourcesContent":["import { DiscriminatedUnionTypeInstance, Severity } from \"@fern-api/browser-compatible-base-generator\";\nimport { assertNever } from \"@fern-api/core-utils\";\nimport { FernIr } from \"@fern-api/dynamic-ir-sdk\";\nimport { EnumWithAssociatedValues, LiteralEnum, sanitizeSelf, swift } from \"@fern-api/swift-codegen\";\n\nimport { DynamicSnippetsGeneratorContext } from \"./DynamicSnippetsGeneratorContext\";\nimport { DynamicTypeMapper } from \"./DynamicTypeMapper\";\n\nexport declare namespace DynamicTypeLiteralMapper {\n interface Args {\n typeReference: FernIr.dynamic.TypeReference;\n value: unknown;\n as?: ConvertedAs;\n }\n\n // Identifies what the type is being converted as, which sometimes influences how\n // the type is instantiated.\n type ConvertedAs = \"mapKey\" | \"mapValue\";\n}\n\nexport class DynamicTypeLiteralMapper {\n private context: DynamicSnippetsGeneratorContext;\n\n constructor({ context }: { context: DynamicSnippetsGeneratorContext }) {\n this.context = context;\n }\n\n public convert(args: DynamicTypeLiteralMapper.Args): swift.Expression {\n switch (args.typeReference.type) {\n case \"list\":\n return this.convertList({ list: args.typeReference.value, value: args.value });\n case \"literal\": {\n if (args.typeReference.value.type === \"string\") {\n return swift.Expression.enumCaseShorthand(\n LiteralEnum.generateEnumCaseLabel(args.typeReference.value.value)\n );\n } else if (args.typeReference.value.type === \"boolean\") {\n return swift.Expression.nop();\n } else {\n assertNever(args.typeReference.value);\n break;\n }\n }\n case \"map\":\n return this.convertMap({ map: args.typeReference, value: args.value });\n case \"named\": {\n const named = this.context.resolveNamedType({ typeId: args.typeReference.value });\n if (named == null) {\n return swift.Expression.nop();\n }\n return this.convertNamed({ named, value: args.value, as: args.as });\n }\n case \"nullable\":\n return this.convertNullable({ nullable: args.typeReference, value: args.value, as: args.as });\n case \"optional\":\n return this.convert({ typeReference: args.typeReference.value, value: args.value, as: args.as });\n case \"primitive\":\n return this.convertPrimitive({ primitive: args.typeReference.value, value: args.value, as: args.as });\n case \"set\":\n return swift.Expression.nop();\n case \"unknown\":\n return this.convertUnknown(args.value);\n default:\n assertNever(args.typeReference);\n }\n }\n\n private convertList({ list, value }: { list: FernIr.dynamic.TypeReference; value: unknown }): swift.Expression {\n if (!Array.isArray(value)) {\n this.context.errors.add({\n severity: Severity.Critical,\n message: `Expected array but got: ${typeof value}`\n });\n return swift.Expression.nop();\n }\n return swift.Expression.arrayLiteral({\n elements: value.map((v, index) => {\n this.context.errors.scope({ index });\n try {\n return this.convert({ typeReference: list, value: v });\n } finally {\n this.context.errors.unscope();\n }\n }),\n multiline: true\n });\n }\n\n private convertMap({ map, value }: { map: FernIr.dynamic.MapType; value: unknown }): swift.Expression {\n if (typeof value !== \"object\" || value == null) {\n this.context.errors.add({\n severity: Severity.Critical,\n message: `Expected object but got: ${value == null ? \"null\" : typeof value}`\n });\n return swift.Expression.nop();\n }\n return swift.Expression.dictionaryLiteral({\n entries: Object.entries(value).map(([key, value]) => {\n this.context.errors.scope(key);\n try {\n return [\n this.convert({ typeReference: map.key, value: key, as: \"mapKey\" }),\n this.convert({ typeReference: map.value, value, as: \"mapValue\" })\n ];\n } finally {\n this.context.errors.unscope();\n }\n }),\n multiline: true\n });\n }\n\n private convertNamed({\n named,\n value,\n as\n }: {\n named: FernIr.dynamic.NamedType;\n value: unknown;\n as?: DynamicTypeLiteralMapper.ConvertedAs;\n }): swift.Expression {\n switch (named.type) {\n case \"alias\":\n return this.convert({ typeReference: named.typeReference, value, as });\n case \"discriminatedUnion\":\n return this.convertDiscriminatedUnion({ discriminatedUnion: named, value });\n case \"enum\":\n return this.convertEnum({ enum_: named, value });\n case \"object\":\n return this.convertObject({ object_: named, value, as });\n case \"undiscriminatedUnion\":\n return this.convertUndiscriminatedUnion({ undiscriminatedUnion: named, value });\n default:\n assertNever(named);\n }\n }\n\n private convertNullable({\n nullable,\n value,\n as\n }: {\n nullable: FernIr.dynamic.TypeReference.Nullable;\n value: unknown;\n as?: DynamicTypeLiteralMapper.ConvertedAs;\n }): swift.Expression {\n if (value == null) {\n return swift.Expression.enumCaseShorthand(\"null\");\n }\n return swift.Expression.contextualMethodCall({\n methodName: \"value\",\n arguments_: [\n swift.functionArgument({\n value: this.convert({ typeReference: nullable.value, value, as })\n })\n ]\n });\n }\n\n private convertDiscriminatedUnion({\n discriminatedUnion,\n value\n }: {\n discriminatedUnion: FernIr.dynamic.DiscriminatedUnionType;\n value: unknown;\n }): swift.Expression {\n const discriminatedUnionTypeInstance = this.context.resolveDiscriminatedUnionTypeInstance({\n discriminatedUnion: discriminatedUnion,\n value\n });\n if (discriminatedUnionTypeInstance == null) {\n return swift.Expression.nop();\n }\n const unionVariant = discriminatedUnionTypeInstance.singleDiscriminatedUnionType;\n const unionProperties = this.convertDiscriminatedUnionProperties({\n discriminatedUnionTypeInstance,\n unionVariant\n });\n if (unionProperties == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.methodCall({\n target: swift.Expression.reference(discriminatedUnion.declaration.name.pascalCase.unsafeName),\n methodName: EnumWithAssociatedValues.sanitizeToCamelCase(\n unionVariant.discriminantValue.name.camelCase.unsafeName\n ),\n arguments_: [\n swift.functionArgument({\n value: swift.Expression.contextualMethodCall({\n methodName: \"init\",\n arguments_: unionProperties,\n multiline: true\n })\n })\n ],\n multiline: true\n });\n }\n\n private convertDiscriminatedUnionProperties({\n discriminatedUnionTypeInstance,\n unionVariant\n }: {\n discriminatedUnionTypeInstance: DiscriminatedUnionTypeInstance;\n unionVariant: FernIr.dynamic.SingleDiscriminatedUnionType;\n }): swift.FunctionArgument[] | undefined {\n const baseFields = this.getBaseFields({\n discriminatedUnionTypeInstance,\n singleDiscriminatedUnionType: unionVariant\n });\n switch (unionVariant.type) {\n case \"samePropertiesAsObject\": {\n const named = this.context.resolveNamedType({\n typeId: unionVariant.typeId\n });\n if (named == null) {\n return undefined;\n }\n const converted = this.convertNamed({ named, value: discriminatedUnionTypeInstance.value });\n if (!converted.isStructInitialization()) {\n this.context.errors.add({\n severity: Severity.Critical,\n message: \"Internal error; expected union value to be a struct\"\n });\n return undefined;\n }\n const structInitialization = converted.asStructInitializationOrThrow();\n return [...baseFields, ...(structInitialization.arguments_ ?? [])];\n }\n case \"singleProperty\": {\n try {\n this.context.errors.scope(unionVariant.discriminantValue.wireValue);\n const record = this.context.getRecord(discriminatedUnionTypeInstance.value);\n if (record == null) {\n return [...baseFields];\n }\n return [\n ...baseFields,\n swift.functionArgument({\n label: sanitizeSelf(\n EnumWithAssociatedValues.sanitizeToCamelCase(\n unionVariant.discriminantValue.name.camelCase.unsafeName\n )\n ),\n value: this.convert({\n typeReference: unionVariant.typeReference,\n value: record[unionVariant.discriminantValue.wireValue]\n })\n })\n ];\n } finally {\n this.context.errors.unscope();\n }\n }\n case \"noProperties\":\n return baseFields;\n default:\n assertNever(unionVariant);\n }\n }\n\n private getBaseFields({\n discriminatedUnionTypeInstance,\n singleDiscriminatedUnionType\n }: {\n discriminatedUnionTypeInstance: DiscriminatedUnionTypeInstance;\n singleDiscriminatedUnionType: FernIr.dynamic.SingleDiscriminatedUnionType;\n }): swift.FunctionArgument[] {\n const properties = this.context.getExampleObjectProperties({\n parameters: singleDiscriminatedUnionType.properties ?? [],\n snippetObject: discriminatedUnionTypeInstance.value\n });\n return properties.map((property) => {\n this.context.errors.scope(property.name.wireValue);\n try {\n return swift.functionArgument({\n label: sanitizeSelf(property.name.name.camelCase.unsafeName),\n value: this.convert(property)\n });\n } finally {\n this.context.errors.unscope();\n }\n });\n }\n\n private convertEnum({ enum_, value }: { enum_: FernIr.dynamic.EnumType; value: unknown }): swift.Expression {\n const nameAndWireValue = this.getEnumValue({ enum_, value });\n if (nameAndWireValue == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.enumCaseShorthand(nameAndWireValue.name.camelCase.unsafeName);\n }\n\n private getEnumValue({ enum_, value }: { enum_: FernIr.dynamic.EnumType; value: unknown }) {\n if (typeof value !== \"string\") {\n this.context.errors.add({\n severity: Severity.Critical,\n message: `Expected enum value string, got: ${typeof value}`\n });\n return undefined;\n }\n const enumValue = enum_.values.find((v) => v.wireValue === value);\n if (enumValue == null) {\n this.context.errors.add({\n severity: Severity.Critical,\n message: `An enum value named \"${value}\" does not exist in this context`\n });\n return undefined;\n }\n return enumValue;\n }\n\n private convertObject({\n object_,\n value,\n as\n }: {\n object_: FernIr.dynamic.ObjectType;\n value: unknown;\n as?: DynamicTypeLiteralMapper.ConvertedAs;\n }): swift.Expression {\n return swift.Expression.structInitialization({\n unsafeName: object_.declaration.name.pascalCase.unsafeName,\n arguments_: this.context\n .getExampleObjectProperties({\n parameters: object_.properties,\n snippetObject: value\n })\n .map((typeInstance) => {\n const expression = this.convert(typeInstance);\n if (expression.isNop()) {\n return null;\n }\n return swift.functionArgument({\n label: sanitizeSelf(typeInstance.name.name.camelCase.unsafeName),\n value: this.convert(typeInstance)\n });\n })\n .filter((argument) => argument != null),\n multiline: true\n });\n }\n\n private convertUndiscriminatedUnion({\n undiscriminatedUnion,\n value\n }: {\n undiscriminatedUnion: FernIr.dynamic.UndiscriminatedUnionType;\n value: unknown;\n }): swift.Expression {\n const result = this.findMatchingUndiscriminatedUnionType({\n undiscriminatedUnion,\n value\n });\n if (result == null) {\n return swift.Expression.nop();\n }\n return result;\n }\n\n private findMatchingUndiscriminatedUnionType({\n undiscriminatedUnion,\n value\n }: {\n undiscriminatedUnion: FernIr.dynamic.UndiscriminatedUnionType;\n value: unknown;\n }): swift.Expression | undefined {\n for (const typeReference of undiscriminatedUnion.types) {\n try {\n const converted = this.convert({ typeReference, value });\n const typeMapper = new DynamicTypeMapper({ context: this.context });\n const swiftType = typeMapper.convert({ typeReference });\n return swift.Expression.methodCall({\n target: swift.Expression.reference(undiscriminatedUnion.declaration.name.pascalCase.unsafeName),\n methodName: swiftType.toCaseName(),\n arguments_: [\n swift.functionArgument({\n value: converted\n })\n ],\n multiline: true\n });\n } catch (e) {\n continue;\n }\n }\n this.context.errors.add({\n severity: Severity.Critical,\n message: `None of the types in the undiscriminated union matched the given \"${typeof value}\" value`\n });\n return undefined;\n }\n\n private convertUnknown(value: unknown): swift.Expression {\n switch (typeof value) {\n case \"boolean\": {\n return swift.Expression.contextualMethodCall({\n methodName: \"bool\",\n arguments_: [\n swift.functionArgument({\n value: swift.Expression.boolLiteral(value)\n })\n ]\n });\n }\n case \"string\": {\n return swift.Expression.contextualMethodCall({\n methodName: \"string\",\n arguments_: [\n swift.functionArgument({\n value: swift.Expression.stringLiteral(value)\n })\n ]\n });\n }\n case \"number\": {\n return swift.Expression.contextualMethodCall({\n methodName: \"number\",\n arguments_: [\n swift.functionArgument({\n value: swift.Expression.numberLiteral(value)\n })\n ]\n });\n }\n case \"object\": {\n if (value === null) {\n return swift.Expression.enumCaseShorthand(\"null\");\n }\n if (Array.isArray(value)) {\n return swift.Expression.contextualMethodCall({\n methodName: \"array\",\n arguments_: [\n swift.functionArgument({\n value: swift.Expression.arrayLiteral({\n elements: value.map((v) => this.convertUnknown(v)),\n multiline: true\n })\n })\n ]\n });\n }\n return swift.Expression.contextualMethodCall({\n methodName: \"object\",\n arguments_: [\n swift.functionArgument({\n value: swift.Expression.dictionaryLiteral({\n entries: Object.entries(value).map(([key, value]) => [\n swift.Expression.stringLiteral(key),\n this.convertUnknown(value)\n ]),\n multiline: true\n })\n })\n ]\n });\n }\n default:\n throw new Error(`Internal error; unsupported unknown type: ${typeof value}`);\n }\n }\n\n private convertPrimitive({\n primitive,\n value,\n as\n }: {\n primitive: FernIr.PrimitiveTypeV1;\n value: unknown;\n as?: DynamicTypeLiteralMapper.ConvertedAs;\n }): swift.Expression {\n switch (primitive) {\n case \"INTEGER\":\n case \"UINT\":\n case \"LONG\":\n case \"UINT_64\":\n case \"FLOAT\":\n case \"DOUBLE\": {\n const num = this.getValueAsNumber({ value, as });\n if (num == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.numberLiteral(num);\n }\n case \"BOOLEAN\": {\n const bool = this.getValueAsBoolean({ value, as });\n if (bool == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.boolLiteral(bool);\n }\n case \"STRING\": {\n const str = this.context.getValueAsString({ value });\n if (str == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.stringLiteral(str);\n }\n case \"DATE\": {\n const date = this.context.getValueAsString({ value });\n if (date == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.calendarDateLiteral(date);\n }\n case \"DATE_TIME\": {\n const dateTime = this.context.getValueAsString({ value });\n if (dateTime == null) {\n return swift.Expression.nop();\n }\n const timestampMs = new Date(dateTime).getTime();\n const timestampSec = Math.round(timestampMs / 1000);\n const roundedDateTime = new Date(timestampSec * 1000).toISOString();\n // Remove fractional seconds (.000Z -> Z) for Swift compatibility\n const dateTimeWithoutFractional = roundedDateTime.replace(/\\.\\d{3}Z$/, \"Z\");\n return swift.Expression.dateLiteral(dateTimeWithoutFractional);\n }\n case \"UUID\": {\n const uuid = this.context.getValueAsString({ value });\n if (uuid == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.uuidLiteral(uuid);\n }\n case \"BASE_64\": {\n const base64 = this.context.getValueAsString({ value });\n if (base64 == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.stringLiteral(base64);\n }\n case \"BIG_INTEGER\": {\n const bigInt = this.context.getValueAsString({ value });\n if (bigInt == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.nop();\n }\n default:\n assertNever(primitive);\n }\n }\n\n private getValueAsNumber({\n value,\n as\n }: {\n value: unknown;\n as?: DynamicTypeLiteralMapper.ConvertedAs;\n }): number | undefined {\n const num = as === \"mapKey\" ? (typeof value === \"string\" ? Number(value) : value) : value;\n return this.context.getValueAsNumber({ value: num });\n }\n\n private getValueAsBoolean({\n value,\n as\n }: {\n value: unknown;\n as?: DynamicTypeLiteralMapper.ConvertedAs;\n }): boolean | undefined {\n const bool = (() => {\n switch (as) {\n case \"mapKey\": {\n if (value === \"true\") {\n return true;\n }\n if (value === \"false\") {\n return false;\n }\n return value;\n }\n case \"mapValue\":\n case undefined:\n return value;\n default:\n assertNever(as);\n }\n })();\n return this.context.getValueAsBoolean({ value: bool });\n }\n}\n"],"mappings":"yKAAAA,IAAAC,IAGA,OAAS,4BAAAC,EAA0B,eAAAC,EAAa,gBAAAC,EAAc,SAAAC,MAAa,0BAiBpE,IAAMC,EAAN,KAA+B,CAGlC,YAAY,CAAE,QAAAC,CAAQ,EAAiD,CAFvEC,EAAA,KAAQ,WAGJ,KAAK,QAAUD,CACnB,CAEO,QAAQE,EAAuD,CAClE,OAAQA,EAAK,cAAc,KAAM,CAC7B,IAAK,OACD,OAAO,KAAK,YAAY,CAAE,KAAMA,EAAK,cAAc,MAAO,MAAOA,EAAK,KAAM,CAAC,EACjF,IAAK,UAAW,CACZ,GAAIA,EAAK,cAAc,MAAM,OAAS,SAClC,OAAOC,EAAM,WAAW,kBACpBC,EAAY,sBAAsBF,EAAK,cAAc,MAAM,KAAK,CACpE,EACG,GAAIA,EAAK,cAAc,MAAM,OAAS,UACzC,OAAOC,EAAM,WAAW,IAAI,EAE5BE,EAAYH,EAAK,cAAc,KAAK,EACpC,KAER,CACA,IAAK,MACD,OAAO,KAA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,EAGuB,CACnB,IAAM4B,EAAM5B,IAAO,UAAY,OAAON,GAAU,SAAW,OAAOA,CAAK,EAAaA,EACpF,OAAO,KAAK,QAAQ,iBAAiB,CAAE,MAAOkC,CAAI,CAAC,CACvD,CAEQ,kBAAkB,CACtB,MAAAlC,EACA,GAAAM,CACJ,EAGwB,CACpB,IAAM6B,GAAQ,IAAM,CAChB,OAAQ7B,EAAI,CACR,IAAK,SACD,OAAIN,IAAU,OACH,GAEPA,IAAU,QACH,GAEJA,EAEX,IAAK,WACL,KAAK,OACD,OAAOA,EACX,QACIH,EAAYS,CAAE,CACtB,CACJ,GAAG,EACH,OAAO,KAAK,QAAQ,kBAAkB,CAAE,MAAO6B,CAAK,CAAC,CACzD,CACJ","names":["init_process","init_buffer","EnumWithAssociatedValues","LiteralEnum","sanitizeSelf","swift","DynamicTypeLiteralMapper","context","__publicField","args","swift","LiteralEnum","assertNever","named","list","value","v","index","Severity","map","key","as","nullable","discriminatedUnion","discriminatedUnionTypeInstance","unionVariant","unionProperties","EnumWithAssociatedValues","_a","baseFields","converted","structInitialization","record","sanitizeSelf","singleDiscriminatedUnionType","property","enum_","nameAndWireValue","enumValue","object_","typeInstance","argument","undiscriminatedUnion","result","typeReference","swiftType","DynamicTypeMapper","e","primitive","num","bool","str","date","dateTime","timestampMs","timestampSec","dateTimeWithoutFractional","uuid","base64"]}
|
|
1
|
+
{"version":3,"sources":["../../src/context/DynamicTypeLiteralMapper.ts"],"sourcesContent":["import { DiscriminatedUnionTypeInstance, Severity } from \"@fern-api/browser-compatible-base-generator\";\nimport { assertNever } from \"@fern-api/core-utils\";\nimport { FernIr } from \"@fern-api/dynamic-ir-sdk\";\nimport { EnumWithAssociatedValues, LiteralEnum, sanitizeSelf, swift } from \"@fern-api/swift-codegen\";\n\nimport { DynamicSnippetsGeneratorContext } from \"./DynamicSnippetsGeneratorContext\";\nimport { DynamicTypeMapper } from \"./DynamicTypeMapper\";\n\nexport declare namespace DynamicTypeLiteralMapper {\n interface Args {\n typeReference: FernIr.dynamic.TypeReference;\n value: unknown;\n as?: ConvertedAs;\n }\n\n // Identifies what the type is being converted as, which sometimes influences how\n // the type is instantiated.\n type ConvertedAs = \"mapKey\" | \"mapValue\";\n}\n\nexport class DynamicTypeLiteralMapper {\n private context: DynamicSnippetsGeneratorContext;\n\n constructor({ context }: { context: DynamicSnippetsGeneratorContext }) {\n this.context = context;\n }\n\n public convert(args: DynamicTypeLiteralMapper.Args): swift.Expression {\n switch (args.typeReference.type) {\n case \"list\":\n return this.convertList({ list: args.typeReference.value, value: args.value });\n case \"literal\": {\n if (args.typeReference.value.type === \"string\") {\n return swift.Expression.enumCaseShorthand(\n LiteralEnum.generateEnumCaseLabel(args.typeReference.value.value)\n );\n } else if (args.typeReference.value.type === \"boolean\") {\n return swift.Expression.nop();\n } else {\n assertNever(args.typeReference.value);\n break;\n }\n }\n case \"map\":\n return this.convertMap({ map: args.typeReference, value: args.value });\n case \"named\": {\n const named = this.context.resolveNamedType({ typeId: args.typeReference.value });\n if (named == null) {\n return swift.Expression.nop();\n }\n return this.convertNamed({ named, value: args.value, as: args.as });\n }\n case \"nullable\":\n return this.convertNullable({ nullable: args.typeReference, value: args.value, as: args.as });\n case \"optional\":\n return this.convert({ typeReference: args.typeReference.value, value: args.value, as: args.as });\n case \"primitive\":\n return this.convertPrimitive({ primitive: args.typeReference.value, value: args.value, as: args.as });\n case \"set\":\n return swift.Expression.nop();\n case \"unknown\":\n return this.convertUnknown(args.value);\n default:\n assertNever(args.typeReference);\n }\n }\n\n private convertList({ list, value }: { list: FernIr.dynamic.TypeReference; value: unknown }): swift.Expression {\n if (!Array.isArray(value)) {\n this.context.errors.add({\n severity: Severity.Critical,\n message: `Expected array but got: ${typeof value}`\n });\n return swift.Expression.nop();\n }\n return swift.Expression.arrayLiteral({\n elements: value.map((v, index) => {\n this.context.errors.scope({ index });\n try {\n return this.convert({ typeReference: list, value: v });\n } finally {\n this.context.errors.unscope();\n }\n }),\n multiline: true\n });\n }\n\n private convertMap({ map, value }: { map: FernIr.dynamic.MapType; value: unknown }): swift.Expression {\n if (typeof value !== \"object\" || value == null) {\n this.context.errors.add({\n severity: Severity.Critical,\n message: `Expected object but got: ${value == null ? \"null\" : typeof value}`\n });\n return swift.Expression.nop();\n }\n return swift.Expression.dictionaryLiteral({\n entries: Object.entries(value).map(([key, value]) => {\n this.context.errors.scope(key);\n try {\n return [\n this.convert({ typeReference: map.key, value: key, as: \"mapKey\" }),\n this.convert({ typeReference: map.value, value, as: \"mapValue\" })\n ];\n } finally {\n this.context.errors.unscope();\n }\n }),\n multiline: true\n });\n }\n\n private convertNamed({\n named,\n value,\n as\n }: {\n named: FernIr.dynamic.NamedType;\n value: unknown;\n as?: DynamicTypeLiteralMapper.ConvertedAs;\n }): swift.Expression {\n switch (named.type) {\n case \"alias\":\n return this.convert({ typeReference: named.typeReference, value, as });\n case \"discriminatedUnion\":\n return this.convertDiscriminatedUnion({ discriminatedUnion: named, value });\n case \"enum\":\n return this.convertEnum({ enum_: named, value });\n case \"object\":\n return this.convertObject({ object_: named, value, as });\n case \"undiscriminatedUnion\":\n return this.convertUndiscriminatedUnion({ undiscriminatedUnion: named, value });\n default:\n assertNever(named);\n }\n }\n\n private convertNullable({\n nullable,\n value,\n as\n }: {\n nullable: FernIr.dynamic.TypeReference.Nullable;\n value: unknown;\n as?: DynamicTypeLiteralMapper.ConvertedAs;\n }): swift.Expression {\n if (value == null) {\n return swift.Expression.enumCaseShorthand(\"null\");\n }\n return swift.Expression.contextualMethodCall({\n methodName: \"value\",\n arguments_: [\n swift.functionArgument({\n value: this.convert({ typeReference: nullable.value, value, as })\n })\n ]\n });\n }\n\n private convertDiscriminatedUnion({\n discriminatedUnion,\n value\n }: {\n discriminatedUnion: FernIr.dynamic.DiscriminatedUnionType;\n value: unknown;\n }): swift.Expression {\n const discriminatedUnionTypeInstance = this.context.resolveDiscriminatedUnionTypeInstance({\n discriminatedUnion: discriminatedUnion,\n value\n });\n if (discriminatedUnionTypeInstance == null) {\n return swift.Expression.nop();\n }\n const unionVariant = discriminatedUnionTypeInstance.singleDiscriminatedUnionType;\n const unionProperties = this.convertDiscriminatedUnionProperties({\n discriminatedUnionTypeInstance,\n unionVariant\n });\n if (unionProperties == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.methodCall({\n target: swift.Expression.reference(discriminatedUnion.declaration.name.pascalCase.unsafeName),\n methodName: EnumWithAssociatedValues.sanitizeToCamelCase(\n unionVariant.discriminantValue.name.camelCase.unsafeName\n ),\n arguments_: [\n swift.functionArgument({\n value: swift.Expression.contextualMethodCall({\n methodName: \"init\",\n arguments_: unionProperties,\n multiline: true\n })\n })\n ],\n multiline: true\n });\n }\n\n private convertDiscriminatedUnionProperties({\n discriminatedUnionTypeInstance,\n unionVariant\n }: {\n discriminatedUnionTypeInstance: DiscriminatedUnionTypeInstance;\n unionVariant: FernIr.dynamic.SingleDiscriminatedUnionType;\n }): swift.FunctionArgument[] | undefined {\n const baseFields = this.getBaseFields({\n discriminatedUnionTypeInstance,\n singleDiscriminatedUnionType: unionVariant\n });\n switch (unionVariant.type) {\n case \"samePropertiesAsObject\": {\n const named = this.context.resolveNamedType({\n typeId: unionVariant.typeId\n });\n if (named == null) {\n return undefined;\n }\n const converted = this.convertNamed({ named, value: discriminatedUnionTypeInstance.value });\n if (!converted.isStructInitialization()) {\n this.context.errors.add({\n severity: Severity.Critical,\n message: \"Internal error; expected union value to be a struct\"\n });\n return undefined;\n }\n const structInitialization = converted.asStructInitializationOrThrow();\n return [...baseFields, ...(structInitialization.arguments_ ?? [])];\n }\n case \"singleProperty\": {\n try {\n this.context.errors.scope(unionVariant.discriminantValue.wireValue);\n const record = this.context.getRecord(discriminatedUnionTypeInstance.value);\n if (record == null) {\n return [...baseFields];\n }\n return [\n ...baseFields,\n swift.functionArgument({\n label: sanitizeSelf(\n EnumWithAssociatedValues.sanitizeToCamelCase(\n unionVariant.discriminantValue.name.camelCase.unsafeName\n )\n ),\n value: this.convert({\n typeReference: unionVariant.typeReference,\n value: record[unionVariant.discriminantValue.wireValue]\n })\n })\n ];\n } finally {\n this.context.errors.unscope();\n }\n }\n case \"noProperties\":\n return baseFields;\n default:\n assertNever(unionVariant);\n }\n }\n\n private getBaseFields({\n discriminatedUnionTypeInstance,\n singleDiscriminatedUnionType\n }: {\n discriminatedUnionTypeInstance: DiscriminatedUnionTypeInstance;\n singleDiscriminatedUnionType: FernIr.dynamic.SingleDiscriminatedUnionType;\n }): swift.FunctionArgument[] {\n const properties = this.context.getExampleObjectProperties({\n parameters: singleDiscriminatedUnionType.properties ?? [],\n snippetObject: discriminatedUnionTypeInstance.value\n });\n return properties.map((property) => {\n this.context.errors.scope(property.name.wireValue);\n try {\n return swift.functionArgument({\n label: sanitizeSelf(property.name.name.camelCase.unsafeName),\n value: this.convert(property)\n });\n } finally {\n this.context.errors.unscope();\n }\n });\n }\n\n private convertEnum({ enum_, value }: { enum_: FernIr.dynamic.EnumType; value: unknown }): swift.Expression {\n const nameAndWireValue = this.getEnumValue({ enum_, value });\n if (nameAndWireValue == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.enumCaseShorthand(nameAndWireValue.name.camelCase.unsafeName);\n }\n\n private getEnumValue({ enum_, value }: { enum_: FernIr.dynamic.EnumType; value: unknown }) {\n if (typeof value !== \"string\") {\n this.context.errors.add({\n severity: Severity.Critical,\n message: `Expected enum value string, got: ${typeof value}`\n });\n return undefined;\n }\n const enumValue = enum_.values.find((v) => v.wireValue === value);\n if (enumValue == null) {\n this.context.errors.add({\n severity: Severity.Critical,\n message: `An enum value named \"${value}\" does not exist in this context`\n });\n return undefined;\n }\n return enumValue;\n }\n\n private convertObject({\n object_,\n value,\n as\n }: {\n object_: FernIr.dynamic.ObjectType;\n value: unknown;\n as?: DynamicTypeLiteralMapper.ConvertedAs;\n }): swift.Expression {\n return swift.Expression.structInitialization({\n unsafeName: object_.declaration.name.pascalCase.unsafeName,\n arguments_: this.context\n .getExampleObjectProperties({\n parameters: object_.properties,\n snippetObject: value\n })\n .map((typeInstance) => {\n const expression = this.convert(typeInstance);\n if (expression.isNop()) {\n return null;\n }\n return swift.functionArgument({\n label: sanitizeSelf(typeInstance.name.name.camelCase.unsafeName),\n value: this.convert(typeInstance)\n });\n })\n .filter((argument) => argument != null),\n multiline: true\n });\n }\n\n private convertUndiscriminatedUnion({\n undiscriminatedUnion,\n value\n }: {\n undiscriminatedUnion: FernIr.dynamic.UndiscriminatedUnionType;\n value: unknown;\n }): swift.Expression {\n const result = this.findMatchingUndiscriminatedUnionType({\n undiscriminatedUnion,\n value\n });\n if (result == null) {\n return swift.Expression.nop();\n }\n return result;\n }\n\n private findMatchingUndiscriminatedUnionType({\n undiscriminatedUnion,\n value\n }: {\n undiscriminatedUnion: FernIr.dynamic.UndiscriminatedUnionType;\n value: unknown;\n }): swift.Expression | undefined {\n for (const typeReference of undiscriminatedUnion.types) {\n try {\n const converted = this.convert({ typeReference, value });\n const typeMapper = new DynamicTypeMapper({ context: this.context });\n const swiftType = typeMapper.convert({ typeReference });\n return swift.Expression.methodCall({\n target: swift.Expression.reference(undiscriminatedUnion.declaration.name.pascalCase.unsafeName),\n methodName: swiftType.toCaseName(),\n arguments_: [\n swift.functionArgument({\n value: converted\n })\n ],\n multiline: true\n });\n } catch (e) {\n continue;\n }\n }\n this.context.errors.add({\n severity: Severity.Critical,\n message: `None of the types in the undiscriminated union matched the given \"${typeof value}\" value`\n });\n return undefined;\n }\n\n private convertUnknown(value: unknown): swift.Expression {\n switch (typeof value) {\n case \"boolean\": {\n return swift.Expression.contextualMethodCall({\n methodName: \"bool\",\n arguments_: [\n swift.functionArgument({\n value: swift.Expression.boolLiteral(value)\n })\n ]\n });\n }\n case \"string\": {\n return swift.Expression.contextualMethodCall({\n methodName: \"string\",\n arguments_: [\n swift.functionArgument({\n value: swift.Expression.stringLiteral(value)\n })\n ]\n });\n }\n case \"number\": {\n return swift.Expression.contextualMethodCall({\n methodName: \"number\",\n arguments_: [\n swift.functionArgument({\n value: swift.Expression.numberLiteral(value)\n })\n ]\n });\n }\n case \"object\": {\n if (value === null) {\n return swift.Expression.enumCaseShorthand(\"null\");\n }\n if (Array.isArray(value)) {\n return swift.Expression.contextualMethodCall({\n methodName: \"array\",\n arguments_: [\n swift.functionArgument({\n value: swift.Expression.arrayLiteral({\n elements: value.map((v) => this.convertUnknown(v)),\n multiline: true\n })\n })\n ]\n });\n }\n return swift.Expression.contextualMethodCall({\n methodName: \"object\",\n arguments_: [\n swift.functionArgument({\n value: swift.Expression.dictionaryLiteral({\n entries: Object.entries(value).map(([key, value]) => [\n swift.Expression.stringLiteral(key),\n this.convertUnknown(value)\n ]),\n multiline: true\n })\n })\n ]\n });\n }\n default:\n throw new Error(`Internal error; unsupported unknown type: ${typeof value}`);\n }\n }\n\n private convertPrimitive({\n primitive,\n value,\n as\n }: {\n primitive: FernIr.PrimitiveTypeV1;\n value: unknown;\n as?: DynamicTypeLiteralMapper.ConvertedAs;\n }): swift.Expression {\n switch (primitive) {\n case \"INTEGER\":\n case \"UINT\":\n case \"LONG\":\n case \"UINT_64\":\n case \"FLOAT\":\n case \"DOUBLE\": {\n const num = this.getValueAsNumber({ value, as });\n if (num == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.numberLiteral(num);\n }\n case \"BOOLEAN\": {\n const bool = this.getValueAsBoolean({ value, as });\n if (bool == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.boolLiteral(bool);\n }\n case \"STRING\": {\n const str = this.context.getValueAsString({ value });\n if (str == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.stringLiteral(str);\n }\n case \"DATE\": {\n const date = this.context.getValueAsString({ value });\n if (date == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.calendarDateLiteral(date);\n }\n case \"DATE_TIME\": {\n const dateTime = this.context.getValueAsString({ value });\n if (dateTime == null) {\n return swift.Expression.nop();\n }\n const timestampMs = new Date(dateTime).getTime();\n const timestampSec = Math.round(timestampMs / 1000);\n const roundedDateTime = new Date(timestampSec * 1000).toISOString();\n // Remove fractional seconds (.000Z -> Z) for Swift compatibility\n const dateTimeWithoutFractional = roundedDateTime.replace(/\\.\\d{3}Z$/, \"Z\");\n return swift.Expression.dateLiteral(dateTimeWithoutFractional);\n }\n case \"UUID\": {\n const uuid = this.context.getValueAsString({ value });\n if (uuid == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.uuidLiteral(uuid);\n }\n case \"BASE_64\": {\n const base64 = this.context.getValueAsString({ value });\n if (base64 == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.stringLiteral(base64);\n }\n case \"BIG_INTEGER\": {\n const bigInt = this.context.getValueAsString({ value });\n if (bigInt == null) {\n return swift.Expression.nop();\n }\n return swift.Expression.nop();\n }\n default:\n assertNever(primitive);\n }\n }\n\n private getValueAsNumber({\n value,\n as\n }: {\n value: unknown;\n as?: DynamicTypeLiteralMapper.ConvertedAs;\n }): number | undefined {\n const num = as === \"mapKey\" ? (typeof value === \"string\" ? Number(value) : value) : value;\n return this.context.getValueAsNumber({ value: num });\n }\n\n private getValueAsBoolean({\n value,\n as\n }: {\n value: unknown;\n as?: DynamicTypeLiteralMapper.ConvertedAs;\n }): boolean | undefined {\n const bool = (() => {\n switch (as) {\n case \"mapKey\": {\n if (value === \"true\") {\n return true;\n }\n if (value === \"false\") {\n return false;\n }\n return value;\n }\n case \"mapValue\":\n case undefined:\n return value;\n default:\n assertNever(as);\n }\n })();\n return this.context.getValueAsBoolean({ value: bool });\n }\n}\n"],"mappings":"qMAAAA,IAAAC,IAoBO,IAAMC,EAAN,KAA+B,CAGlC,YAAY,CAAE,QAAAC,CAAQ,EAAiD,CAFvEC,EAAA,KAAQ,WAGJ,KAAK,QAAUD,CACnB,CAEO,QAAQE,EAAuD,CAClE,OAAQA,EAAK,cAAc,KAAM,CAC7B,IAAK,OACD,OAAO,KAAK,YAAY,CAAE,KAAMA,EAAK,cAAc,MAAO,MAAOA,EAAK,KAAM,CAAC,EACjF,IAAK,UAAW,CACZ,GAAIA,EAAK,cAAc,M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gD,CAAM,CAChD,CACA,IAAK,cAED,OADe,KAAK,QAAQ,iBAAiB,CAAE,MAAA3C,CAAM,CAAC,GACxC,KACHL,EAAM,WAAW,IAAI,EAEzBA,EAAM,WAAW,IAAI,EAEhC,QACIE,EAAYoC,CAAS,CAC7B,CACJ,CAEQ,iBAAiB,CACrB,MAAAjC,EACA,GAAAM,CACJ,EAGuB,CACnB,IAAM4B,EAAM5B,IAAO,UAAY,OAAON,GAAU,SAAW,OAAOA,CAAK,EAAaA,EACpF,OAAO,KAAK,QAAQ,iBAAiB,CAAE,MAAOkC,CAAI,CAAC,CACvD,CAEQ,kBAAkB,CACtB,MAAAlC,EACA,GAAAM,CACJ,EAGwB,CACpB,IAAM6B,GAAQ,IAAM,CAChB,OAAQ7B,EAAI,CACR,IAAK,SACD,OAAIN,IAAU,OACH,GAEPA,IAAU,QACH,GAEJA,EAEX,IAAK,WACL,KAAK,OACD,OAAOA,EACX,QACIH,EAAYS,CAAE,CACtB,CACJ,GAAG,EACH,OAAO,KAAK,QAAQ,kBAAkB,CAAE,MAAO6B,CAAK,CAAC,CACzD,CACJ","names":["init_process","init_buffer","DynamicTypeLiteralMapper","context","__publicField","args","swift_exports","literal_enum_exports","assertNever","named","list","value","v","index","Severity","map","key","as","nullable","discriminatedUnion","discriminatedUnionTypeInstance","unionVariant","unionProperties","enum_with_associated_values_exports","_a","baseFields","converted","structInitialization","record","sanitizeSelf","singleDiscriminatedUnionType","property","enum_","nameAndWireValue","enumValue","object_","typeInstance","argument","undiscriminatedUnion","result","typeReference","swiftType","DynamicTypeMapper","e","primitive","num","bool","str","date","dateTime","timestampMs","timestampSec","dateTimeWithoutFractional","uuid","base64"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as m}from"./chunk-6DFEQNIA.js";import{c as a}from"./chunk-2M2RBZK2.js";import{a as s}from"./chunk-ZIQ5ITTV.js";import{a as r}from"./chunk-IHG2VZKL.js";import{a as c}from"./chunk-KIHSBETU.js";import{b as o}from"./chunk-PJTPV2D6.js";import{j as t,l as n,n as p}from"./chunk-PYMG6Y4R.js";n();p();var l=class u extends a{constructor({ir:i,config:e,options:f}){super({ir:i,config:e,options:f});t(this,"ir");t(this,"customConfig");t(this,"dynamicTypeMapper");t(this,"dynamicTypeLiteralMapper");t(this,"filePropertyMapper");this.ir=i,this.customConfig=e.customConfig!=null?e.customConfig:void 0,this.dynamicTypeMapper=new s({context:this}),this.dynamicTypeLiteralMapper=new m({context:this}),this.filePropertyMapper=new c({context:this})}clone(){return new u({ir:this.ir,config:this.config,options:this.options})}getModuleName(){var i,e;return(e=(i=this.customConfig)==null?void 0:i.moduleName)!=null?e:r(this.getApiName())}getRootClientClassName(){var i,e;return(e=(i=this.customConfig)==null?void 0:i.clientClassName)!=null?e:`${r(this.getApiName())}Client`}getApiName(){return o(this.config.workspaceName)}};export{l as a};
|
|
2
|
+
//# sourceMappingURL=chunk-7RC2HH3P.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/context/DynamicSnippetsGeneratorContext.ts"],"sourcesContent":["import {\n AbstractDynamicSnippetsGeneratorContext,\n FernGeneratorExec,\n Options\n} from \"@fern-api/browser-compatible-base-generator\";\nimport { FernIr } from \"@fern-api/dynamic-ir-sdk\";\nimport { BaseSwiftCustomConfigSchema } from \"@fern-api/swift-codegen\";\nimport { camelCase } from \"lodash-es\";\n\nimport { pascalCase } from \"../util/pascal-case\";\nimport { DynamicTypeLiteralMapper } from \"./DynamicTypeLiteralMapper\";\nimport { DynamicTypeMapper } from \"./DynamicTypeMapper\";\nimport { FilePropertyMapper } from \"./FilePropertyMapper\";\n\nexport class DynamicSnippetsGeneratorContext extends AbstractDynamicSnippetsGeneratorContext {\n public ir: FernIr.dynamic.DynamicIntermediateRepresentation;\n public customConfig: BaseSwiftCustomConfigSchema | undefined;\n public dynamicTypeMapper: DynamicTypeMapper;\n public dynamicTypeLiteralMapper: DynamicTypeLiteralMapper;\n public filePropertyMapper: FilePropertyMapper;\n\n public constructor({\n ir,\n config,\n options\n }: {\n ir: FernIr.dynamic.DynamicIntermediateRepresentation;\n config: FernGeneratorExec.GeneratorConfig;\n options?: Options;\n }) {\n super({ ir: ir, config, options });\n this.ir = ir;\n this.customConfig =\n config.customConfig != null ? (config.customConfig as BaseSwiftCustomConfigSchema) : undefined;\n this.dynamicTypeMapper = new DynamicTypeMapper({ context: this });\n this.dynamicTypeLiteralMapper = new DynamicTypeLiteralMapper({ context: this });\n this.filePropertyMapper = new FilePropertyMapper({ context: this });\n }\n\n public clone(): DynamicSnippetsGeneratorContext {\n return new DynamicSnippetsGeneratorContext({\n ir: this.ir,\n config: this.config,\n options: this.options\n });\n }\n\n public getModuleName(): string {\n return this.customConfig?.[\"moduleName\"] ?? pascalCase(this.getApiName());\n }\n\n public getRootClientClassName(): string {\n return this.customConfig?.[\"clientClassName\"] ?? `${pascalCase(this.getApiName())}Client`;\n }\n\n private getApiName(): string {\n return camelCase(this.config.workspaceName);\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../../src/context/DynamicSnippetsGeneratorContext.ts"],"sourcesContent":["import {\n AbstractDynamicSnippetsGeneratorContext,\n FernGeneratorExec,\n Options\n} from \"@fern-api/browser-compatible-base-generator\";\nimport { FernIr } from \"@fern-api/dynamic-ir-sdk\";\nimport { BaseSwiftCustomConfigSchema } from \"@fern-api/swift-codegen\";\nimport { camelCase } from \"lodash-es\";\n\nimport { pascalCase } from \"../util/pascal-case\";\nimport { DynamicTypeLiteralMapper } from \"./DynamicTypeLiteralMapper\";\nimport { DynamicTypeMapper } from \"./DynamicTypeMapper\";\nimport { FilePropertyMapper } from \"./FilePropertyMapper\";\n\nexport class DynamicSnippetsGeneratorContext extends AbstractDynamicSnippetsGeneratorContext {\n public ir: FernIr.dynamic.DynamicIntermediateRepresentation;\n public customConfig: BaseSwiftCustomConfigSchema | undefined;\n public dynamicTypeMapper: DynamicTypeMapper;\n public dynamicTypeLiteralMapper: DynamicTypeLiteralMapper;\n public filePropertyMapper: FilePropertyMapper;\n\n public constructor({\n ir,\n config,\n options\n }: {\n ir: FernIr.dynamic.DynamicIntermediateRepresentation;\n config: FernGeneratorExec.GeneratorConfig;\n options?: Options;\n }) {\n super({ ir: ir, config, options });\n this.ir = ir;\n this.customConfig =\n config.customConfig != null ? (config.customConfig as BaseSwiftCustomConfigSchema) : undefined;\n this.dynamicTypeMapper = new DynamicTypeMapper({ context: this });\n this.dynamicTypeLiteralMapper = new DynamicTypeLiteralMapper({ context: this });\n this.filePropertyMapper = new FilePropertyMapper({ context: this });\n }\n\n public clone(): DynamicSnippetsGeneratorContext {\n return new DynamicSnippetsGeneratorContext({\n ir: this.ir,\n config: this.config,\n options: this.options\n });\n }\n\n public getModuleName(): string {\n return this.customConfig?.[\"moduleName\"] ?? pascalCase(this.getApiName());\n }\n\n public getRootClientClassName(): string {\n return this.customConfig?.[\"clientClassName\"] ?? `${pascalCase(this.getApiName())}Client`;\n }\n\n private getApiName(): string {\n return camelCase(this.config.workspaceName);\n }\n}\n"],"mappings":"sSAAAA,IAAAC,IAcO,IAAMC,EAAN,MAAMC,UAAwCC,CAAwC,CAOlF,YAAY,CACf,GAAAC,EACA,OAAAC,EACA,QAAAC,CACJ,EAIG,CACC,MAAM,CAAE,GAAIF,EAAI,OAAAC,EAAQ,QAAAC,CAAQ,CAAC,EAfrCC,EAAA,KAAO,MACPA,EAAA,KAAO,gBACPA,EAAA,KAAO,qBACPA,EAAA,KAAO,4BACPA,EAAA,KAAO,sBAYH,KAAK,GAAKH,EACV,KAAK,aACDC,EAAO,cAAgB,KAAQA,EAAO,aAA+C,OACzF,KAAK,kBAAoB,IAAIG,EAAkB,CAAE,QAAS,IAAK,CAAC,EAChE,KAAK,yBAA2B,IAAIC,EAAyB,CAAE,QAAS,IAAK,CAAC,EAC9E,KAAK,mBAAqB,IAAIC,EAAmB,CAAE,QAAS,IAAK,CAAC,CACtE,CAEO,OAAyC,CAC5C,OAAO,IAAIR,EAAgC,CACvC,GAAI,KAAK,GACT,OAAQ,KAAK,OACb,QAAS,KAAK,OAClB,CAAC,CACL,CAEO,eAAwB,CA/CnC,IAAAS,EAAAC,EAgDQ,OAAOA,GAAAD,EAAA,KAAK,eAAL,YAAAA,EAAoB,aAApB,KAAAC,EAAqCC,EAAW,KAAK,WAAW,CAAC,CAC5E,CAEO,wBAAiC,CAnD5C,IAAAF,EAAAC,EAoDQ,OAAOA,GAAAD,EAAA,KAAK,eAAL,YAAAA,EAAoB,kBAApB,KAAAC,EAA0C,GAAGC,EAAW,KAAK,WAAW,CAAC,CAAC,QACrF,CAEQ,YAAqB,CACzB,OAAOC,EAAU,KAAK,OAAO,aAAa,CAC9C,CACJ","names":["init_process","init_buffer","DynamicSnippetsGeneratorContext","_DynamicSnippetsGeneratorContext","AbstractDynamicSnippetsGeneratorContext","ir","config","options","__publicField","DynamicTypeMapper","DynamicTypeLiteralMapper","FilePropertyMapper","_a","_b","pascalCase","camelCase_default"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/util/pascal-case.ts"],"sourcesContent":["import { camelCase, upperFirst } from \"lodash-es\";\n\nexport function pascalCase(str: string): string {\n return upperFirst(camelCase(str));\n}\n"],"mappings":"8FAAAA,IAAAC,IAEO,SAASC,EAAWC,EAAqB,CAC5C,OAAOC,EAAWC,EAAUF,CAAG,CAAC,CACpC","names":["init_process","init_buffer","pascalCase","str","upperFirst_default","camelCase_default"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import{a as E,b as I,c as he}from"./chunk-PJTPV2D6.js";import{a as w,f as A,g as ue,h as Ge,j as a,k as h,l as r,n as o}from"./chunk-PYMG6Y4R.js";var me=A((cn,ke)=>{"use strict";r();o();function Xe(i){return!(typeof i!="number"||i!==i||i===1/0||i===-1/0)}ke.exports=Xe});var Oe=A((pn,Ae)=>{"use strict";r();o();var _e=9007199254740991;Ae.exports=_e});var de=A((fn,Ce)=>{"use strict";r();o();var Qe=Oe();function et(i){return typeof i=="number"&&Math.abs(i)<=Qe}Ce.exports=et});var De=A((wn,Me)=>{"use strict";r();o();var tt=me(),nt=de();function it(i){var n=parseInt(i,10);if(!tt(n))throw new TypeError("Not a finite number: "+i+" ("+typeof i+")");if(!nt(n))throw new RangeError("Input is not a safe number, it\u2019s either too large or too small.");var e=String(n),t=Math.abs(n%100),s=t>=11&&t<=13,l=e.charAt(e.length-1);return e+(s?"th":l==="1"?"st":l==="2"?"nd":l==="3"?"rd":"th")}Me.exports=it});var fe=A((Tn,$e)=>{"use strict";r();o();var st=/(hundred|thousand|(m|b|tr|quadr)illion)$/,at=/teen$/,Be=/y$/,Fe=/(zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve)$/,rt={zero:"zeroth",one:"first",two:"second",three:"third",four:"fourth",five:"fifth",six:"sixth",seven:"seventh",eight:"eighth",nine:"ninth",ten:"tenth",eleven:"eleventh",twelve:"twelfth"};function ot(i){return st.test(i)||at.test(i)?i+"th":Be.test(i)?i.replace(Be,"ieth"):Fe.test(i)?i.replace(Fe,lt):i}function lt(i,n){return rt[n]}$e.exports=ot});var xe=A((Nn,qe)=>{"use strict";r();o();var ct=fe(),ut=me(),ht=de(),We=10,ye=100,be=1e3,we=1e6,ge=1e9,Se=1e12,Te=1e15,pt=9007199254740992,ze=["zero","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],mt=["zero","ten","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"];function dt(i,n){var e,t=parseInt(i,10);if(!ut(t))throw new TypeError("Not a finite number: "+i+" ("+typeof i+")");if(!ht(t))throw new RangeError("Input is not a safe number, it\u2019s either too large or too small.");return e=O(t),n?ct(e):e}function O(i){var n,e,t=arguments[1];return i===0?t?t.join(" ").replace(/,$/,""):"zero":(t||(t=[]),i<0&&(t.push("minus"),i=Math.abs(i)),i<20?(n=0,e=ze[i]):i<ye?(n=i%We,e=mt[Math.floor(i/We)],n&&(e+="-"+ze[n],n=0)):i<be?(n=i%ye,e=O(Math.floor(i/ye))+" hundred"):i<we?(n=i%be,e=O(Math.floor(i/be))+" thousand,"):i<ge?(n=i%we,e=O(Math.floor(i/we))+" million,"):i<Se?(n=i%ge,e=O(Math.floor(i/ge))+" billion,"):i<Te?(n=i%Se,e=O(Math.floor(i/Se))+" trillion,"):i<=pt&&(n=i%Te,e=O(Math.floor(i/Te))+" quadrillion,"),t.push(e),O(n,t))}qe.exports=dt});var Re=A((In,Ue)=>{"use strict";r();o();var ft=fe(),yt=xe();function bt(i){var n=yt(i);return ft(n)}Ue.exports=bt});var Ve=A((On,Pe)=>{"use strict";r();o();Pe.exports={toOrdinal:De(),toWords:xe(),toWordsOrdinal:Re()}});r();o();function X(i,n){if(i===void 0)throw new Error(n!=null?n:"Expected value to be defined but got undefined.")}function x(i,n){if(i===null)throw new Error(n!=null?n:"Expected value to be non-null but got null.")}function S(i){throw new Error("Unexpected value: "+JSON.stringify(i))}r();o();r();o();function pe(){}r();o();function Je(i){return Object.keys(i)}r();o();function _(i){return Object.values(i)}var Ne={};ue(Ne,{sanitizeForIdentifier:()=>ve,sanitizeToCamelCase:()=>gt,sanitizeToPascalCase:()=>wt});r();o();var je=Ge(Ve(),1);r();o();function Q(i){return E(I(i))}function wt(i){let n=ve(i);return Q(n)}function gt(i){let n=ve(i);return I(n)}function ve(i){if(i==="")return"empty";let n=i;if(/^\d/.test(n)){let t=St(n);n=t.numberAsWords+E(t.rest)}return/^[a-zA-Z][a-zA-Z0-9]*$/.test(n)||(n=n.replace(/^[^a-zA-Z0-9]+/,""),n=I(n)),/^\d/.test(n)&&(n="value"+n),n===""?"value":n}function St(i){let n=i.match(/^(\d+)/);if(!n||!n[1])return{numberAsWords:"",rest:i};let e=n[1],t=i.slice(e.length);try{return{numberAsWords:(0,je.toWords)(parseInt(e,10)),rest:t}}catch(s){let l={0:"zero",1:"one",2:"two",3:"three",4:"four",5:"five",6:"six",7:"seven",8:"eight",9:"nine"};return{numberAsWords:e.split("").map(u=>l[u]||u).join(""),rest:t}}}r();o();var Ee={};ue(Ee,{generateEnumCaseLabel:()=>xt,generateName:()=>Tt,sanitizeLiteralValue:()=>Le});r();o();function Tt(i){let n=Le(i);return Q(n)}function xt(i){let n=Le(i);return I(n)}function Le(i){if(i==="")return"empty";let n=i;return/^[a-zA-Z][a-zA-Z0-9]*$/.test(i)||(n=n.replace(/^[^a-zA-Z0-9]+/,""),n=I(n)),/^\d/.test(n)||n===""?"value":n}r();o();r();o();var vt=["Any","as","associatedtype","break","case","catch","class","continue","default","defer","deinit","do","else","fallthrough","false","for","guard","enum","extension","fileprivate","func","if","import","in","init","inout","internal","is","let","nil","operator","private","precedencegroup","Protocol","protocol","public","repeat","rethrows","return","Self","self","static","struct","subscript","super","switch","throw","throws","true","try","Type","typealias","var","where","while"],Nt=new Set(vt);function C(i){return Nt.has(i)}function T(i){return C(i)?`\`${i}\``:i}function Xn(i){return i==="self"?"self_":i}var Ie={};ue(Ie,{AccessLevel:()=>Ye,Class:()=>D,CodeBlock:()=>g,Comment:()=>B,ComputedProperty:()=>$,DeclarationType:()=>Z,DocComment:()=>W,EnumWithAssociatedValues:()=>z,EnumWithRawValues:()=>q,Expression:()=>k,Extension:()=>U,FunctionArgument:()=>R,FunctionParameter:()=>P,Initializer:()=>V,LineBreak:()=>te,Method:()=>j,Pattern:()=>ne,Property:()=>Y,Protocol:()=>Ze,Statement:()=>F,Struct:()=>K,Symbol:()=>b,SymbolRegistry:()=>ce,Type:()=>se,TypeReference:()=>ae,class_:()=>Et,codeBlock:()=>It,comment:()=>kt,computedProperty:()=>At,docComment:()=>Ot,enumWithAssociatedValues:()=>Ct,enumWithRawValues:()=>Mt,extension:()=>Dt,functionArgument:()=>Bt,functionParameter:()=>Ft,initializer:()=>$t,method:()=>Wt,property:()=>zt,struct:()=>qt});r();o();r();o();r();o();var Ye={Open:"open",Public:"public",Package:"package",Internal:"internal",Fileprivate:"fileprivate",Private:"private"};r();o();r();o();r();o();r();o();r();o();var M=class{};r();o();r();o();var v=class extends M{constructor(e){super();a(this,"value");this.value=e}write(e){typeof this.value=="string"?e.write(this.value):typeof this.value=="function"?this.value(e):this.value.write(e)}};var Lt=4,Ke=!!h.env.FERN_STACK_TRACK;Ke&&(Error.stackTraceLimit=50);var H=class{constructor(){a(this,"buffer","");a(this,"indentLevel",0);a(this,"hasWrittenAnything",!1);a(this,"lastCharacterIsSemicolon",!1);a(this,"lastCharacterIsNewline",!1)}write(...n){for(let e of n)if(e!=null)if(typeof e=="string"){let t=e.length>0&&e.endsWith(`
|
|
2
|
+
`),s=t?e.substring(0,e.length-1):e,l=this.getIndentString(),c=s.replaceAll(`
|
|
3
|
+
`,`
|
|
4
|
+
${l}`);this.isAtStartOfLine()&&(c=l+c),t&&(c+=`
|
|
5
|
+
`),this.writeInternal(c)}else this.writeNode(e)}writeStatement(...n){this.write(...n),this.write(";"),this.writeNewLineIfLastLineNot()}writeNoIndent(n){let e=this.indentLevel;this.indentLevel=0,this.write(n),this.indentLevel=e}writeNode(n){n.write(this)}writeNodeOrString(n){if(typeof n=="string"){this.write(n);return}this.writeNode(n)}writeNodeStatement(n){n.write(this),this.write(";"),this.writeNewLineIfLastLineNot()}writeTextStatement(n){new v(n).write(this),n.endsWith(";")||this.write(";"),this.writeNewLineIfLastLineNot()}controlFlow(n,e){new v(n).write(this),this.write(" (",e,")"),this.pushScope()}controlFlowWithoutStatement(n){new v(n).write(this),this.pushScope()}endControlFlow(){this.popScope()}contiguousControlFlow(n,e){this.dedent(),this.write("} "),new v(n).write(this),this.write(" (",e,")"),this.pushScope()}alternativeControlFlow(n){this.dedent(),this.write("} "),new v(n).write(this),this.pushScope()}pushScope(){this.writeLine("{"),this.indent()}popScope(n=!0){this.dedent(),this.writeNewLineIfLastLineNot(),n?this.writeLine("}"):this.write("}")}writeLine(n=""){this.write(n),this.writeNewLineIfLastLineNot()}newLine(){this.writeInternal(`
|
|
6
|
+
`)}writeSemicolonIfLastCharacterIsNot(){this.lastCharacterIsSemicolon||this.writeInternal(";")}writeNewLineIfLastLineNot(){this.lastCharacterIsNewline||this.writeInternal(`
|
|
7
|
+
`)}indent(){this.indentLevel++}dedent(){this.indentLevel--}delimit({nodes:n,delimiter:e,writeFunction:t}){if(n.length>0){let s=n[0];s!=null&&t(s);for(let l=1;l<n.length;l++){this.write(e);let c=n[l];c!=null&&t(c)}}}toString(){return this.buffer}writeInternal(n){if(n.length>0&&(this.hasWrittenAnything=!0,this.lastCharacterIsNewline=n.endsWith(`
|
|
8
|
+
`),this.lastCharacterIsSemicolon=n.endsWith(";")),this.buffer+=n,Ke&&this.buffer.endsWith(`
|
|
9
|
+
`)&&!this.buffer.endsWith(`"""
|
|
10
|
+
`)){let e=this.stacktrace(15).map(t=>`${t.fn} - ${t.path}:${t.position}`).join(" ");e&&(this.buffer=this.buffer.slice(0,-1),this.buffer+=`//@@ ${e}
|
|
11
|
+
`)}return this.buffer}isAtStartOfLine(){return this.lastCharacterIsNewline||!this.hasWrittenAnything}getIndentString(){return" ".repeat(this.indentLevel*this.getTabSize())}getTabSize(){return Lt}stacktrace(n=50){var t;let e=!1;return((t=new Error().stack)!=null?t:"").split(`
|
|
12
|
+
`).map(s=>{var c;let l=s.match(/at\s+(.*)\s+\((.*):(\d+):(\d+)\)/);if(l&&l.length===5){let[,u,m,y,L]=l;if(e||u!=null&&u.includes("runInteractiveTask")){e=!0;return}switch(u){case"Object.<anonymous>":u="";break;case"Object.object":case"Object.alias":case"Object.union":case"Object.enum":case"Object.undiscriminatedUnion":u=`${u.substring(u.indexOf(".")+1)}()=> { ... }`;break}return{fn:u,path:(c=m==null?void 0:m.replace(/^.*?fern.*?\//,""))!=null?c:"",position:`${y}:${L}`}}}).filter(s=>{var l,c,u,m,y,L,J;return s&&!((l=s.path)!=null&&l.startsWith("node:"))&&!((c=s.path)!=null&&c.endsWith(".js"))&&!((u=s.path)!=null&&u.includes("AbstractWriter"))&&!((m=s.fn)!=null&&m.includes("stacktrace"))&&!((y=s.fn)!=null&&y.includes("stackLine"))&&!((L=s.fn)!=null&&L.includes("SdkGeneratorCLI"))&&!((J=s.fn)!=null&&J.includes("runCli"))}).slice(0,n)}};r();o();var ee=class extends H{toString(){return this.buffer}};var f=class extends M{toString(){let n=new ee;return this.write(n),n.toString()}};var D=class extends f{constructor({accessLevel:e,name:t,final:s,conformances:l,properties:c,initializers:u,methods:m,docs:y}){super();a(this,"name");a(this,"final");a(this,"accessLevel");a(this,"conformances");a(this,"properties");a(this,"initializers");a(this,"methods");a(this,"docs");this.name=t,this.final=s,this.accessLevel=e,this.conformances=l!=null?l:[],this.properties=c,this.initializers=u!=null?u:[],this.methods=m!=null?m:[],this.docs=y}write(e){this.docs!=null&&this.docs.write(e),this.accessLevel!=null&&(e.write(this.accessLevel),e.write(" ")),this.final&&e.write("final "),e.write(`class ${this.name}`),this.conformances.forEach((t,s)=>{s===0?e.write(": "):s>0&&e.write(", "),e.write(t)}),e.write(" {"),e.newLine(),e.indent(),this.properties.forEach(t=>{t.write(e),e.newLine()}),this.initializers.length>0&&(e.newLine(),this.initializers.forEach((t,s)=>{s>0&&e.newLine(),t.write(e),e.newLine()})),this.methods.length>0&&(e.newLine(),this.methods.forEach((t,s)=>{s>0&&e.newLine(),t.write(e),e.newLine()})),e.dedent(),e.write("}")}};r();o();var g=class i extends f{constructor(e){super();a(this,"args");this.args=e}write(e){let t=new v(this.args);e.write("{"),e.newLine(),e.indent(),t.write(e),e.dedent(),e.write("}")}static empty(){return new i(pe)}static withStatements(e){return new i(t=>{e.forEach(s=>{s.write(t)})})}};r();o();var B=class extends f{constructor({content:e}){super();a(this,"content");this.content=e}write(e){this.content.split(`
|
|
13
|
+
`).forEach(s=>{e.write(`// ${s}`),e.newLine()})}};r();o();r();o();function He(i){return i.replace(/\\u([0-9a-fA-F]{4})/g,"\\u{$1}").replace(new RegExp("(?<!\\\\)\\\\f","g"),"\\u{000C}").replace(new RegExp("(?<!\\\\)\\\\v","g"),"\\u{000B}").replace(new RegExp("(?<!\\\\)\\\\0","g"),"\\u{0000}").replace(new RegExp('(?<!\\\\)"',"g"),'\\"')}r();o();var k=class extends f{constructor(e){super();a(this,"internalExpression");this.internalExpression=e}isNop(){return this.internalExpression.type==="nop"}isStructInitialization(){return this.internalExpression.type==="struct-initialization"}asStructInitializationOrThrow(){if(this.internalExpression.type!=="struct-initialization")throw new Error("Internal error; swift.Expression is not a struct initialization");return this.internalExpression}write(e){switch(this.internalExpression.type){case"reference":e.write(T(this.internalExpression.unsafeName));break;case"member-access":this.internalExpression.target.write(e),this.internalExpression.optionalChain&&e.write("?"),e.write("."),e.write(this.internalExpression.memberName);break;case"equals":this.internalExpression.left.write(e),e.write(" == "),this.internalExpression.right.write(e);break;case"enum-case-shorthand":e.write("."),e.write(this.internalExpression.caseName);break;case"function-call":this.writeCallableExpression({writer:e,target:T(this.internalExpression.unsafeName),arguments_:this.internalExpression.arguments_,multiline:!!this.internalExpression.multiline});break;case"struct-initialization":this.writeCallableExpression({writer:e,target:T(this.internalExpression.unsafeName),arguments_:this.internalExpression.arguments_,multiline:!!this.internalExpression.multiline});break;case"class-initialization":this.writeCallableExpression({writer:e,target:T(this.internalExpression.unsafeName),arguments_:this.internalExpression.arguments_,multiline:!!this.internalExpression.multiline});break;case"method-call":this.internalExpression.target.write(e),e.write("."),this.writeCallableExpression({writer:e,target:this.internalExpression.methodName,arguments_:this.internalExpression.arguments_,multiline:!!this.internalExpression.multiline});break;case"method-call-with-trailing-closure":this.internalExpression.target.write(e),e.write("."),e.write(this.internalExpression.methodName),e.write(" {"),this.internalExpression.multiline?(e.newLine(),e.indent()):e.write(" "),this.internalExpression.closureBody.write(e),this.internalExpression.multiline?(e.newLine(),e.dedent()):e.write(" "),e.write("}");break;case"contextual-method-call":e.write("."),this.writeCallableExpression({writer:e,target:this.internalExpression.methodName,arguments_:this.internalExpression.arguments_,multiline:!!this.internalExpression.multiline});break;case"try":e.write("try "),this.internalExpression.expression.write(e);break;case"optional-try":e.write("try? "),this.internalExpression.expression.write(e);break;case"force-try":e.write("try! "),this.internalExpression.expression.write(e);break;case"await":e.write("await "),this.internalExpression.expression.write(e);break;case"string-literal":e.write(`"${this.internalExpression.value}"`);break;case"number-literal":e.write(this.internalExpression.value.toString());break;case"bool-literal":e.write(this.internalExpression.value?"true":"false");break;case"date-literal":e.write(`try! Date("${this.internalExpression.isoString}", strategy: .iso8601)`);break;case"calendar-date-literal":e.write(`CalendarDate("${this.internalExpression.isoString}")!`);break;case"uuid-literal":e.write(`UUID(uuidString: "${this.internalExpression.value}")!`);break;case"dictionary-literal":this.writeDictionaryLiteral(e,this.internalExpression);break;case"array-literal":this.writeArrayLiteral(e,this.internalExpression);break;case"data-literal":e.write(`Data("${this.internalExpression.value}".utf8)`);break;case"raw-value":e.write(this.internalExpression.value);break;case"nop":break;default:S(this.internalExpression)}}writeCallableExpression({writer:e,target:t,arguments_:s,multiline:l}){e.write(t),e.write("("),l&&(e.newLine(),e.indent()),s==null||s.forEach((c,u)=>{u>0&&(e.write(","),l?e.newLine():e.write(" ")),c.write(e)}),l&&(e.newLine(),e.dedent()),e.write(")")}writeDictionaryLiteral(e,t){var l;if(!t.entries||t.entries.length===0){e.write("[:]");return}e.write("[");let s=!!t.multiline;s&&(e.newLine(),e.indent()),(l=t.entries)==null||l.forEach(([c,u],m)=>{m>0&&(e.write(", "),s&&e.newLine()),c.write(e),e.write(": "),u.write(e)}),s&&(e.newLine(),e.dedent()),e.write("]")}writeArrayLiteral(e,t){var l;if(!t.elements||t.elements.length===0){e.write("[]");return}e.write("[");let s=!!t.multiline;s&&(e.newLine(),e.indent()),(l=t.elements)==null||l.forEach((c,u)=>{u>0&&(e.write(","),s?e.newLine():e.write(" ")),c.write(e)}),s&&(e.newLine(),e.dedent()),e.write("]")}static reference(e){return new this({type:"reference",unsafeName:e})}static memberAccess(e){return new this(w({type:"member-access"},e))}static equals(e,t){return new this({type:"equals",left:e,right:t})}static enumCaseShorthand(e){return new this({type:"enum-case-shorthand",caseName:e})}static functionCall(e){return new this(w({type:"function-call"},e))}static structInitialization(e){return new this(w({type:"struct-initialization"},e))}static classInitialization(e){return new this(w({type:"class-initialization"},e))}static stringLiteral(e){return new this({type:"string-literal",value:e})}static numberLiteral(e){return new this({type:"number-literal",value:e})}static boolLiteral(e){return new this({type:"bool-literal",value:e})}static dateLiteral(e){return new this({type:"date-literal",isoString:e})}static calendarDateLiteral(e){return new this({type:"calendar-date-literal",isoString:e})}static uuidLiteral(e){return new this({type:"uuid-literal",value:e})}static dictionaryLiteral(e){return new this(w({type:"dictionary-literal"},e))}static arrayLiteral(e){return new this(w({type:"array-literal"},e))}static dataLiteral(e){return new this({type:"data-literal",value:e})}static methodCall(e){return new this(w({type:"method-call"},e))}static methodCallWithTrailingClosure(e){return new this(w({type:"method-call-with-trailing-closure"},e))}static contextualMethodCall(e){return new this(w({type:"contextual-method-call"},e))}static try(e){return new this({type:"try",expression:e})}static optionalTry(e){return new this({type:"optional-try",expression:e})}static forceTry(e){return new this({type:"force-try",expression:e})}static await(e){return new this({type:"await",expression:e})}static rawValue(e){return new this({type:"raw-value",value:e})}static nop(){return new this({type:"nop"})}static nil(){return new this({type:"raw-value",value:"nil"})}static self(){return new this({type:"raw-value",value:"self"})}};r();o();r();o();var Z={Var:"var",Let:"let"};var F=class extends f{constructor(e){super();a(this,"internalStatement");this.internalStatement=e}write(e){var t,s,l;switch(this.internalStatement.type){case"typealias-declaration":this.internalStatement.docs!=null&&this.internalStatement.docs.write(e),this.internalStatement.accessLevel&&(e.write(this.internalStatement.accessLevel),e.write(" ")),e.write("typealias "),e.write(this.internalStatement.unsafeName),e.write(" = "),this.internalStatement.aliasedType.write(e),e.newLine();break;case"constant-declaration":e.write(Z.Let),e.write(" "),e.write(T(this.internalStatement.unsafeName)),e.write(" = "),this.internalStatement.value.write(e),this.internalStatement.noTrailingNewline||e.newLine();break;case"variable-declaration":e.write(Z.Var),e.write(" "),e.write(T(this.internalStatement.unsafeName)),e.write(" = "),this.internalStatement.value.write(e),this.internalStatement.noTrailingNewline||e.newLine();break;case"function-declaration":this.internalStatement.docs!=null&&this.internalStatement.docs.write(e),this.internalStatement.accessLevel!=null&&(e.write(this.internalStatement.accessLevel),e.write(" ")),e.write("func "),e.write(T(this.internalStatement.unsafeName)),e.write("("),(t=this.internalStatement.parameters)==null||t.forEach((c,u)=>{u>0&&e.write(", "),c.write(e)}),e.write(")"),this.internalStatement.async&&e.write(" async"),this.internalStatement.throws&&e.write(" throws"),this.internalStatement.returnType&&(e.write(" -> "),this.internalStatement.returnType.write(e)),e.write(" "),((s=this.internalStatement.body)!=null?s:g.empty()).write(e),e.newLine();break;case"variable-assignment":e.write(T(this.internalStatement.unsafeName)),e.write(" = "),this.internalStatement.value.write(e),e.newLine();break;case"self-assignment":e.write("self = "),e.write(this.internalStatement.value.toString()),e.newLine();break;case"property-assignment":e.write("self."),e.write(this.internalStatement.unsafeName),e.write(" = "),this.internalStatement.value.write(e),e.newLine();break;case"discard-assignment":e.write("_ = "),this.internalStatement.value.write(e),e.newLine();break;case"return":e.write("return "),this.internalStatement.expression.write(e),e.newLine();break;case"throw":e.write("throw "),this.internalStatement.expression.write(e),e.newLine();break;case"expression-statement":this.internalStatement.expression.write(e),e.newLine();break;case"import":e.write("import "),e.write(this.internalStatement.moduleName),e.newLine();break;case"switch":e.write("switch "),this.internalStatement.target.write(e),e.write(" {"),e.newLine();for(let c of this.internalStatement.cases)if(e.write("case "),c.pattern.write(e),e.write(":"),e.newLine(),c.body.length>0){e.indent();for(let u of c.body)u.write(e);e.dedent()}if(this.internalStatement.defaultCase&&(e.write("default:"),e.newLine(),this.internalStatement.defaultCase.length>0)){e.indent();for(let c of this.internalStatement.defaultCase)c.write(e);e.dedent()}e.write("}"),e.newLine();break;case"if":{e.write("if "),this.internalStatement.condition.write(e),e.write(" "),g.withStatements(this.internalStatement.body).write(e);for(let c of(l=this.internalStatement.elseIfs)!=null?l:[])e.write(" else if "),c.condition.write(e),e.write(" "),g.withStatements(c.body).write(e);this.internalStatement.else&&(e.write(" else "),g.withStatements(this.internalStatement.else).write(e)),e.newLine();break}case"raw":e.write(this.internalStatement.content),e.newLine();break;default:S(this.internalStatement)}}static typealiasDeclaration(e){return new this(w({type:"typealias-declaration"},e))}static constantDeclaration(e){return new this(w({type:"constant-declaration"},e))}static variableDeclaration(e){return new this(w({type:"variable-declaration"},e))}static functionDeclaration(e){return new this(w({type:"function-declaration"},e))}static variableAssignment(e,t){return new this({type:"variable-assignment",unsafeName:e,value:t})}static selfAssignment(e){return new this({type:"self-assignment",value:e})}static propertyAssignment(e,t){return new this({type:"property-assignment",unsafeName:e,value:t})}static discardAssignment(e){return new this({type:"discard-assignment",value:e})}static return(e){return new this({type:"return",expression:e})}static throw(e){return new this({type:"throw",expression:e})}static expressionStatement(e){return new this({type:"expression-statement",expression:e})}static import(e){return new this({type:"import",moduleName:e})}static switch(e){return new this(w({type:"switch"},e))}static if(e){return new this(w({type:"if"},e))}static raw(e){return new this({type:"raw",content:e})}};var $=class extends f{constructor({unsafeName:e,accessLevel:t,type:s,body:l,docs:c}){super();a(this,"unsafeName");a(this,"accessLevel");a(this,"type");a(this,"body");a(this,"docs");this.unsafeName=e,this.accessLevel=t,this.type=s,this.body=l,this.docs=c}write(e){this.docs!=null&&this.docs.write(e),this.accessLevel!=null&&(e.write(this.accessLevel),e.write(" ")),e.write("var "),e.write(T(this.unsafeName)),e.write(": "),this.type.write(e),e.write(" "),this.body instanceof g?this.body.write(e):this.body instanceof k?g.withStatements([F.expressionStatement(this.body)]).write(e):S(this.body)}};r();o();var W=class i extends f{constructor({summary:e,description:t,parameters:s,returns:l,throws:c}){super();a(this,"summary");a(this,"description");a(this,"parameters");a(this,"returns");a(this,"throws");this.summary=i.sanitizeText(e),this.description=t!=null?i.sanitizeText(t):void 0,this.parameters=(s!=null?s:[]).map(u=>({name:u.name,description:i.sanitizeText(u.description)})),this.returns=l!=null?i.sanitizeText(l):void 0,this.throws=(c!=null?c:[]).map(u=>i.sanitizeText(u))}write(e){if(this.writeMultilineText(e,this.summary),this.description!=null&&(e.write("///"),e.newLine(),this.writeMultilineText(e,this.description)),this.parameters.length>0){e.write("///"),e.newLine();for(let t of this.parameters)t.description.split(`
|
|
14
|
+
`).forEach((l,c)=>{c===0?(e.write("/// - Parameter "),e.write(t.name),e.write(": "),e.write(l)):(e.write("/// "),e.write(l)),e.newLine()})}if(this.returns!=null&&this.returns.split(`
|
|
15
|
+
`).forEach((s,l)=>{l===0?(e.write("/// - Returns: "),e.write(s)):(e.write("/// "),e.write(s)),e.newLine()}),this.throws.length>0)for(let t of this.throws)t.split(`
|
|
16
|
+
`).forEach((l,c)=>{c===0?(e.write("/// - Throws: "),e.write(l)):(e.write("/// "),e.write(l)),e.newLine()})}writeMultilineText(e,t){let s=t.split(`
|
|
17
|
+
`);for(let l of s)e.write("/// "),e.write(l),e.newLine()}static sanitizeText(e){return e=e.replace(/\r\n/g,`
|
|
18
|
+
`).replace(/\r/g,`
|
|
19
|
+
`),e=e.replace(/\x00/g,""),e}};r();o();var z=class extends f{constructor({accessLevel:e,name:t,conformances:s,cases:l,initializers:c,methods:u,nestedTypes:m,docs:y}){super();a(this,"name");a(this,"accessLevel");a(this,"conformances");a(this,"cases");a(this,"initializers");a(this,"methods");a(this,"nestedTypes");a(this,"docs");this.name=t,this.accessLevel=e,this.conformances=s!=null?s:[],this.cases=l,this.initializers=c!=null?c:[],this.methods=u!=null?u:[],this.nestedTypes=m!=null?m:[],this.docs=y}write(e){this.docs!=null&&this.docs.write(e),this.accessLevel!=null&&(e.write(this.accessLevel),e.write(" ")),e.write(`enum ${this.name}`),this.conformances.forEach((t,s)=>{s===0?e.write(": "):s>0&&e.write(", "),e.write(t)}),e.write(" {"),e.newLine(),e.indent(),this.cases.forEach(t=>{t.docs!=null&&t.docs.write(e),e.write("case "),C(t.unsafeName)?e.write(`\`${t.unsafeName}\``):e.write(t.unsafeName),e.write("("),t.associatedValue.forEach((s,l)=>{l>0&&e.write(", "),s.write(e)}),e.write(")"),e.newLine()}),this.initializers.length>0&&(e.newLine(),this.initializers.forEach((t,s)=>{s>0&&e.newLine(),t.write(e),e.newLine()})),this.methods.length>0&&(e.newLine(),this.methods.forEach((t,s)=>{s>0&&e.newLine(),t.write(e),e.newLine()})),this.nestedTypes.length>0&&(e.newLine(),this.nestedTypes.forEach((t,s)=>{s>0&&e.newLine(),t.write(e),e.newLine()})),e.dedent(),e.write("}")}};r();o();var q=class extends f{constructor({accessLevel:e,name:t,conformances:s,cases:l,docs:c}){super();a(this,"name");a(this,"accessLevel");a(this,"conformances");a(this,"cases");a(this,"docs");this.name=t,this.accessLevel=e,this.conformances=s!=null?s:[],this.cases=l,this.docs=c}write(e){if(this.docs!=null&&this.docs.write(e),this.accessLevel!=null&&(e.write(this.accessLevel),e.write(" ")),e.write(`enum ${this.name}`),this.conformances.forEach((t,s)=>{s===0?e.write(": "):s>0&&e.write(", "),e.write(t)}),this.cases.length===0){e.write(" {}");return}e.write(" {"),e.newLine(),e.indent(),this.cases.forEach(t=>{t.docs!=null&&t.docs.write(e),e.write("case "),C(t.unsafeName)?e.write(`\`${t.unsafeName}\``):e.write(t.unsafeName),t.rawValue!==t.unsafeName&&(e.write(" = "),e.write(`"${He(t.rawValue)}"`)),e.newLine()}),e.dedent(),e.write("}")}};r();o();var U=class extends f{constructor({name:e,conformances:t,initializers:s,computedProperties:l,methods:c,nestedTypes:u,docs:m}){super();a(this,"name");a(this,"conformances");a(this,"initializers");a(this,"computedProperties");a(this,"methods");a(this,"nestedTypes");a(this,"docs");this.name=e,this.conformances=t!=null?t:[],this.initializers=s!=null?s:[],this.computedProperties=l!=null?l:[],this.methods=c!=null?c:[],this.nestedTypes=u!=null?u:[],this.docs=m}write(e){this.docs!=null&&this.docs.write(e),e.write(`extension ${this.name}`),this.conformances.forEach((t,s)=>{s===0?e.write(": "):s>0&&e.write(", "),e.write(t)}),e.write(" {"),this.initializers.length>0&&(e.newLine(),e.indent(),this.initializers.forEach((t,s)=>{s>0&&e.newLine(),t.write(e),e.newLine()}),e.dedent()),this.computedProperties.length>0&&(e.newLine(),e.indent(),this.computedProperties.forEach((t,s)=>{s>0&&e.newLine(),t.write(e),e.newLine()}),e.dedent()),this.methods.length>0&&(e.newLine(),e.indent(),this.methods.forEach((t,s)=>{s>0&&e.newLine(),t.write(e),e.newLine()}),e.dedent()),this.nestedTypes.length>0&&(e.newLine(),e.indent(),this.nestedTypes.forEach((t,s)=>{s>0&&e.newLine(),t.write(e),e.newLine()}),e.dedent()),e.write("}")}};r();o();var R=class extends f{constructor({label:e,value:t}){super();a(this,"label");a(this,"value");this.label=e,this.value=t}write(e){this.label!=null&&(e.write(this.label),e.write(": ")),this.value.write(e)}};r();o();var P=class extends f{constructor({argumentLabel:e,unsafeName:t,escaping:s,type:l,defaultValue:c,docsContent:u}){super();a(this,"argumentLabel");a(this,"unsafeName");a(this,"escaping");a(this,"type");a(this,"defaultValue");a(this,"docsContent");this.argumentLabel=e,this.unsafeName=t,this.escaping=s,this.type=l,this.defaultValue=c,this.docsContent=u}write(e){this.argumentLabel==null?e.write("_ "):this.argumentLabel!==this.unsafeName&&(e.write(this.argumentLabel),e.write(" ")),e.write(this.unsafeName),e.write(": "),this.escaping&&e.write("@escaping "),this.type.write(e),this.defaultValue!=null&&(e.write(" = "),this.defaultValue.write(e))}};r();o();var V=class extends f{constructor({accessLevel:e,convenience:t,failable:s,throws:l,parameters:c,body:u,multiline:m,docs:y}){super();a(this,"accessLevel");a(this,"convenience");a(this,"failable");a(this,"throws");a(this,"parameters");a(this,"body");a(this,"multiline");a(this,"docs");this.accessLevel=e,this.convenience=t,this.failable=s,this.throws=l,this.parameters=c!=null?c:[],this.body=u!=null?u:g.empty(),this.multiline=m,this.docs=y}write(e){this.docs!=null&&this.docs.write(e),this.accessLevel!=null&&(e.write(this.accessLevel),e.write(" ")),this.convenience&&e.write("convenience "),e.write("init"),this.failable&&e.write("?"),e.write("("),this.multiline&&(e.newLine(),e.indent()),this.parameters.forEach((t,s)=>{s>0&&(e.write(","),this.multiline?e.newLine():e.write(" ")),t.write(e)}),this.multiline&&(e.newLine(),e.dedent()),e.write(") "),this.throws&&e.write("throws "),this.body.write(e)}};r();o();var te=class i extends f{constructor({count:e=1}={}){super();a(this,"count");this.count=e}write(e){for(let t=0;t<this.count;t++)e.newLine()}static single(){return new i({count:1})}static double(){return new i({count:2})}static multiple(e){return new i({count:e})}};r();o();var j=class extends f{constructor({attributes:e,unsafeName:t,accessLevel:s,static_:l,parameters:c,async:u,throws:m,returnType:y,body:L,docs:J}){super();a(this,"attributes");a(this,"unsafeName");a(this,"accessLevel");a(this,"static_");a(this,"parameters");a(this,"async");a(this,"throws");a(this,"returnType");a(this,"body");a(this,"docs");this.attributes=e!=null?e:[],this.unsafeName=t,this.accessLevel=s,this.static_=l,this.parameters=c!=null?c:[],this.async=u,this.throws=m,this.returnType=y,this.body=L!=null?L:g.empty(),this.docs=J}write(e){this.docs!=null&&this.docs.write(e),this.attributes.forEach(t=>{var s;(s=t.arguments)!=null&&s.length?k.functionCall({unsafeName:`@${t.name}`,arguments_:t.arguments}).write(e):(e.write("@"),e.write(t.name)),e.write(" ")}),this.accessLevel!=null&&(e.write(this.accessLevel),e.write(" ")),this.static_&&e.write("static "),e.write("func "),e.write(T(this.unsafeName)),e.write("("),this.parameters.forEach((t,s)=>{s>0&&e.write(", "),t.write(e)}),e.write(")"),this.async&&e.write(" async"),this.throws&&e.write(" throws"),e.write(" -> "),this.returnType.write(e),e.write(" "),this.body.write(e)}};r();o();var ne=class extends f{constructor(e){super();a(this,"internalPattern");this.internalPattern=e}write(e){switch(this.internalPattern.type){case"enum-case-value-binding":e.write("."),e.write(this.internalPattern.caseName),e.write("("),e.write(this.internalPattern.declarationType),e.write(" "),e.write(this.internalPattern.referenceName),e.write(")");break;default:S(this.internalPattern.type)}}static enumCaseValueBinding(e){return new this(w({type:"enum-case-value-binding"},e))}};r();o();var Y=class extends f{constructor({unsafeName:e,accessLevel:t,static_:s,declarationType:l,type:c,defaultValue:u,docs:m}){super();a(this,"unsafeName");a(this,"accessLevel");a(this,"static_");a(this,"declarationType");a(this,"type");a(this,"defaultValue");a(this,"docs");this.unsafeName=e,this.accessLevel=t,this.static_=s,this.declarationType=l,this.type=c,this.defaultValue=u,this.docs=m}write(e){this.docs!=null&&this.docs.write(e),this.accessLevel!=null&&(e.write(this.accessLevel),e.write(" ")),this.static_&&e.write("static "),e.write(this.declarationType),e.write(" "),C(this.unsafeName)?e.write(`\`${this.unsafeName}\``):e.write(this.unsafeName),e.write(": "),this.type.write(e),this.defaultValue!=null&&(e.write(" = "),this.defaultValue.write(e))}};r();o();var Ze={CaseIterable:"CaseIterable",Codable:"Codable",CodingKey:"CodingKey",Decodable:"Decodable",Encodable:"Encodable",Equatable:"Equatable",Error:"Error",Hashable:"Hashable",Sendable:"Sendable",MultipartFormDataConvertible:"MultipartFormDataConvertible"};r();o();var K=class extends f{constructor({attributes:e,accessLevel:t,name:s,conformances:l,properties:c,initializers:u,methods:m,nestedTypes:y,docs:L}){super();a(this,"attributes");a(this,"name");a(this,"accessLevel");a(this,"conformances");a(this,"properties");a(this,"initializers");a(this,"methods");a(this,"nestedTypes");a(this,"docs");this.attributes=e!=null?e:[],this.name=s,this.accessLevel=t,this.conformances=l!=null?l:[],this.properties=c!=null?c:[],this.initializers=u!=null?u:[],this.methods=m!=null?m:[],this.nestedTypes=y!=null?y:[],this.docs=L}write(e){this.docs!=null&&this.docs.write(e),this.attributes.forEach(m=>{var y;(y=m.arguments)!=null&&y.length?k.functionCall({unsafeName:`@${m.name}`,arguments_:m.arguments}).write(e):(e.write("@"),e.write(m.name)),e.write(" ")}),this.accessLevel!=null&&(e.write(this.accessLevel),e.write(" ")),e.write(`struct ${this.name}`),this.conformances.forEach((m,y)=>{y===0?e.write(": "):y>0&&e.write(", "),e.write(m)}),e.write(" {"),e.newLine(),e.indent();let t=this.properties.length>0,s=this.initializers.length>0,l=this.methods.length>0,c=this.nestedTypes.length>0;this.properties.forEach(m=>{m.write(e),e.newLine()});let u=t;s&&(u&&e.newLine(),this.initializers.forEach((m,y)=>{y>0&&e.newLine(),m.write(e),e.newLine()}),u=!0),l&&(u&&e.newLine(),this.methods.forEach((m,y)=>{y>0&&e.newLine(),m.write(e),e.newLine()}),u=!0),c&&(u&&e.newLine(),this.nestedTypes.forEach((m,y)=>{y>0&&e.newLine(),m.write(e),e.newLine()})),e.dedent(),e.write("}")}};r();o();var N={String:{type:"string",symbolName:"String"},Bool:{type:"bool",symbolName:"Bool"},Int:{type:"int",symbolName:"Int"},Int64:{type:"int64",symbolName:"Int64"},UInt:{type:"uint",symbolName:"UInt"},UInt64:{type:"uint64",symbolName:"UInt64"},Float:{type:"float",symbolName:"Float"},Double:{type:"double",symbolName:"Double"},Void:{type:"void",symbolName:"Void"},Any:{type:"any",symbolName:"Any"}},ie={Data:{type:"data",symbolName:"Data"},Date:{type:"date",symbolName:"Date"},UUID:{type:"uuid",symbolName:"UUID"}},se=class i extends f{constructor(e){super();a(this,"internalType");this.internalType=e}get type(){return this.internalType.type}get nonOptionalType(){return this.internalType.type==="optional"?this.internalType.valueType.nonOptionalType:this.internalType.type}get nonNullableType(){return this.internalType.type==="nullable"?this.internalType.valueType.nonNullableType:this.internalType.type}get isOptional(){return this.internalType.type==="optional"}get isNullable(){return this.internalType.type==="nullable"}get isOptionalNullable(){return this.isOptional&&this.nonOptional().isNullable}nonOptional(){return i.nonOptional(this)}nonNullable(){return i.nonNullable(this)}equals(e){switch(this.internalType.type){case"string":case"bool":case"int":case"int64":case"uint":case"uint64":case"float":case"double":case"void":case"any":case"data":case"date":case"uuid":case"json-value":return this.internalType.type===e.internalType.type;case"tuple":{if(e.internalType.type!=="tuple"||this.internalType.elements.length!==e.internalType.elements.length)return!1;for(let t=0;t<this.internalType.elements.length;t++){let s=this.internalType.elements[t],l=e.internalType.elements[t];if(!s||!l||!s.equals(l))return!1}return!0}case"array":return e.internalType.type==="array"&&this.internalType.elementType.equals(e.internalType.elementType);case"dictionary":return e.internalType.type==="dictionary"&&this.internalType.keyType.equals(e.internalType.keyType)&&this.internalType.valueType.equals(e.internalType.valueType);case"optional":return e.internalType.type=="optional"&&this.internalType.valueType.equals(e.internalType.valueType);case"nullable":return e.internalType.type==="nullable"&&this.internalType.valueType.equals(e.internalType.valueType);case"custom":return e.internalType.type==="custom"&&this.internalType.name===e.internalType.name;case"existential-any":return e.internalType.type==="existential-any"&&this.internalType.protocolName===e.internalType.protocolName;case"calendar-date":return e.internalType.type==="calendar-date";default:S(this.internalType)}}toCaseName(){return i.toCaseName(this)}static toCaseName(e){switch(e.internalType.type){case"string":return"string";case"bool":return"bool";case"int":return"int";case"int64":return"int64";case"uint":return"uint";case"uint64":return"uint64";case"float":return"float";case"double":return"double";case"void":return"void";case"any":return"any";case"data":return"data";case"date":return"date";case"uuid":return"uuid";case"tuple":{let t=e.internalType.elements.map(s=>i.toCaseName(s)).join("And");return`tuple${E(t)}`}case"array":return`${he(i.toCaseName(e.internalType.elementType))}Array`;case"dictionary":{let t=he(i.toCaseName(e.internalType.keyType)),s=E(i.toCaseName(e.internalType.valueType));return`${t}To${s}Dictionary`}case"optional":return`optional${E(i.toCaseName(e.internalType.valueType))}`;case"nullable":return`nullable${E(i.toCaseName(e.internalType.valueType))}`;case"custom":return I(e.internalType.name);case"existential-any":return`any${E(e.internalType.protocolName)}`;case"calendar-date":return"calendarDate";case"json-value":return"json";default:S(e.internalType)}}write(e){switch(this.internalType.type){case"string":e.write("String");break;case"bool":e.write("Bool");break;case"int":e.write("Int");break;case"int64":e.write("Int64");break;case"uint":e.write("UInt");break;case"uint64":e.write("UInt64");break;case"float":e.write("Float");break;case"double":e.write("Double");break;case"void":e.write("Void");break;case"any":e.write("Any");break;case"data":e.write("Data");break;case"date":e.write("Date");break;case"uuid":e.write("UUID");break;case"tuple":e.write("("),this.internalType.elements.forEach((t,s)=>{s>0&&e.write(", "),t.write(e)}),e.write(")");break;case"array":e.write("["),this.internalType.elementType.write(e),e.write("]");break;case"dictionary":e.write("["),this.internalType.keyType.write(e),e.write(": "),this.internalType.valueType.write(e),e.write("]");break;case"optional":this.internalType.valueType.write(e),e.write("?");break;case"nullable":e.write("Nullable<"),this.internalType.valueType.write(e),e.write(">");break;case"custom":e.write(this.internalType.name);break;case"existential-any":e.write("any "),e.write(this.internalType.protocolName);break;case"calendar-date":e.write("CalendarDate");break;case"json-value":e.write("JSONValue");break;default:S(this.internalType)}}static primitiveSymbolNames(){return _(N).map(e=>e.symbolName)}static foundationSymbolNames(){return _(ie).map(e=>e.symbolName)}static string(){return new this(N.String)}static bool(){return new this(N.Bool)}static int(){return new this(N.Int)}static uint(){return new this(N.UInt)}static uint64(){return new this(N.UInt64)}static int64(){return new this(N.Int64)}static float(){return new this(N.Float)}static double(){return new this(N.Double)}static void(){return new this(N.Void)}static any(){return new this(N.Any)}static data(){return new this(ie.Data)}static date(){return new this(ie.Date)}static uuid(){return new this(ie.UUID)}static tuple(e){return new this({type:"tuple",elements:e})}static array(e){return new this({type:"array",elementType:e})}static dictionary(e,t){return new this({type:"dictionary",keyType:e,valueType:t})}static optional(e){return e.internalType.type==="optional"?e:new this({type:"optional",valueType:e})}static nullable(e){return new this({type:"nullable",valueType:e})}static nonOptional(e){return e.internalType.type==="optional"?i.nonOptional(e.internalType.valueType):e}static nonNullable(e){return e.internalType.type==="nullable"?i.nonNullable(e.internalType.valueType):e}static custom(e){return new this({type:"custom",name:e})}static existentialAny(e){return new this({type:"existential-any",protocolName:e})}static calendarDate(){return new this({type:"calendar-date"})}static jsonValue(){return new this({type:"json-value"})}};r();o();var ae=class i extends f{constructor(e){super();a(this,"variant");this.variant=e}nonOptional(){return i.nonOptional(this)}nonNullable(){return i.nonNullable(this)}getReferenceIfSymbolType(){return this.variant.type==="symbol"?this.variant.symbol:null}write(e){let{variant:t}=this;switch(t.type){case"symbol":e.write(t.symbol);break;case"generic":{t.reference.write(e),t.arguments.length>0&&(e.write("<"),t.arguments.forEach((s,l)=>{s.write(e),l<t.arguments.length-1&&e.write(", ")}),e.write(">"));break}case"tuple":e.write("("),t.elements.forEach((s,l)=>{l>0&&e.write(", "),s.write(e)}),e.write(")");break;case"array":e.write("["),t.elementType.write(e),e.write("]");break;case"dictionary":e.write("["),t.keyType.write(e),e.write(": "),t.valueType.write(e),e.write("]");break;case"optional":t.valueType.write(e),e.write("?");break;case"nullable":e.write("Nullable<"),t.valueType.write(e),e.write(">");break;case"member-access":t.target.write(e),e.write("."),e.write(t.memberName);break;default:S(t)}}equals(e){switch(this.variant.type){case"symbol":return e.variant.type==="symbol"&&this.variant.symbol===e.variant.symbol;case"generic":return e.variant.type==="generic"&&this.variant.reference.equals(e.variant.reference)&&this.variant.arguments.every((t,s)=>e.variant.type==="generic"&&e.variant.arguments[s]&&t.equals(e.variant.arguments[s]));case"tuple":return e.variant.type==="tuple"&&this.variant.elements.every((t,s)=>e.variant.type==="tuple"&&e.variant.elements[s]&&t.equals(e.variant.elements[s]));case"array":return e.variant.type==="array"&&this.variant.elementType.equals(e.variant.elementType);case"dictionary":return e.variant.type==="dictionary"&&this.variant.keyType.equals(e.variant.keyType)&&this.variant.valueType.equals(e.variant.valueType);case"optional":return e.variant.type=="optional"&&this.variant.valueType.equals(e.variant.valueType);case"nullable":return e.variant.type==="nullable"&&this.variant.valueType.equals(e.variant.valueType);case"member-access":return e.variant.type==="member-access"&&this.variant.target.equals(e.variant.target)&&this.variant.memberName===e.variant.memberName;default:S(this.variant)}}static symbol(e){return new this({type:"symbol",symbol:e})}static generic(e,t){return new this({type:"generic",reference:e,arguments:t})}static tuple(e){return new this({type:"tuple",elements:e})}static array(e){return new this({type:"array",elementType:e})}static dictionary(e,t){return new this({type:"dictionary",keyType:e,valueType:t})}static optional(e){return e.variant.type==="optional"?e:new this({type:"optional",valueType:e})}static nullable(e){return e.variant.type==="nullable"?e:new this({type:"nullable",valueType:e})}static memberAccess(e,t){return new this({type:"member-access",target:e,memberName:t})}static nonOptional(e){return e.variant.type==="optional"?i.nonOptional(e.variant.valueType):e}static nonNullable(e){return e.variant.type==="nullable"?i.nonNullable(e.variant.valueType):e}static unqualifiedToSwiftType(e){return i.symbol(e)}static unqualifiedToFoundationType(e){return i.symbol(e)}};r();o();r();o();var d=class d{constructor(n,e,t){a(this,"id");a(this,"name");a(this,"shape");this.id=n,this.name=e,this.shape=t}static isSwiftSymbol(n){return d.SWIFT_SYMBOL_ID===n||n.startsWith(`${d.SWIFT_SYMBOL_ID}.`)}static isSwiftSymbolName(n){return n in d.swiftTypeSymbolsByName}static isFoundationSymbol(n){return d.FOUNDATION_SYMBOL_ID===n||n.startsWith(`${d.FOUNDATION_SYMBOL_ID}.`)}static isFoundationSymbolName(n){return n in d.foundationTypeSymbolsByName}static isCustomSymbol(n){return!d.isSwiftSymbol(n)&&!d.isFoundationSymbol(n)}static create(n,e,t){return new d(n,e,t)}static swiftType(n){return d.create(`${d.SWIFT_SYMBOL_ID}.${n}`,n,{type:"system"})}static foundationType(n){return d.create(`${d.FOUNDATION_SYMBOL_ID}.${n}`,n,{type:"system"})}get isSwiftSymbol(){return d.isSwiftSymbol(this.id)}get isFoundationSymbol(){return d.isFoundationSymbol(this.id)}get isCustomSymbol(){return d.isCustomSymbol(this.id)}};a(d,"SWIFT_SYMBOL_NAME","Swift"),a(d,"SWIFT_SYMBOL_ID",d.SWIFT_SYMBOL_NAME),a(d,"swiftTypeSymbolsByName",{String:d.swiftType("String"),Bool:d.swiftType("Bool"),Int:d.swiftType("Int"),Int64:d.swiftType("Int64"),UInt:d.swiftType("UInt"),UInt64:d.swiftType("UInt64"),Float:d.swiftType("Float"),Double:d.swiftType("Double"),Void:d.swiftType("Void"),Encoder:d.swiftType("Encoder"),Decoder:d.swiftType("Decoder"),Any:d.swiftType("Any")}),a(d,"swiftTypeSymbols",Object.values(d.swiftTypeSymbolsByName)),a(d,"FOUNDATION_SYMBOL_NAME","Foundation"),a(d,"FOUNDATION_SYMBOL_ID",d.FOUNDATION_SYMBOL_NAME),a(d,"foundationTypeSymbolsByName",{Data:d.foundationType("Data"),Date:d.foundationType("Date"),URLSession:d.foundationType("URLSession"),UUID:d.foundationType("UUID")}),a(d,"foundationTypeSymbols",Object.values(d.foundationTypeSymbolsByName));var b=d;r();o();r();o();r();o();r();o();var re=class{constructor(n,e){a(this,"id");a(this,"name");a(this,"childrenByName");this.id=n,this.name=e,this.childrenByName=new Map}get children(){return Array.from(this.childrenByName.values())}addChild(n){if(this.childrenByName.has(n.name))throw new Error(`A child with the name '${n.name}' already exists in module '${this.name}'.`);this.childrenByName.set(n.name,n)}getChildByName(n){return this.childrenByName.get(n)}},oe=class extends re{constructor(e,t){super(e,t);a(this,"kind","module");a(this,"imports");a(this,"parent",null);this.imports=[]}addImport(e){this.imports.push(e)}get qualifiedPath(){return[this.name]}get qualifiedName(){return this.name}},le=class extends re{constructor(e,t,s){super(t,e);a(this,"kind","type");a(this,"shape");a(this,"parent");this.parent=null,this.shape=s}getNearestModuleAncestorOrThrow(){let e=this.parent;for(;e!==null&&e.kind!=="module";)e=e.parent;return x(e,`No module ancestor found for type symbol '${this.id}'`),e}get qualifiedPath(){var e,t;return[...(t=(e=this.parent)==null?void 0:e.qualifiedPath)!=null?t:[],this.name]}get qualifiedName(){return this.qualifiedPath.join(".")}};var G=class{constructor(){a(this,"symbolsById",new Map)}createModuleSymbol({symbolId:n,symbolName:e}){this.validateSymbolNotExists(n);let t=new oe(n,e);return this.symbolsById.set(n,t),t}createTypeSymbol({symbolId:n,symbolName:e,shape:t}){this.validateSymbolNotExists(n);let s=new le(e,n,t);return this.symbolsById.set(n,s),s}addImportRelation({clientSymbolId:n,importedSymbolId:e}){let t=this.getSymbolByIdOrThrow(n),s=this.getSymbolByIdOrThrow(e);if(t.kind!=="module"||s.kind!=="module")throw new Error(`Client module '${t.id}' and imported module '${s.id}' must both be module symbols.`);t.addImport(s)}nestSymbol({parentSymbolId:n,childSymbolId:e}){let t=this.getSymbolByIdOrThrow(n),s=this.getSymbolByIdOrThrow(e);t.addChild(s),s.parent=t}reference({fromSymbolId:n,targetSymbolId:e}){let t=this.getSymbolByIdOrThrow(n),s=this.getSymbolByIdOrThrow(e),l=s.qualifiedPath;for(let c=1;c<=l.length;c++){let u=l.slice(l.length-c),m=this.resolvePath(t,u);if((m==null?void 0:m.id)===s.id)return u.join(".")}return s.qualifiedName}resolveReference({fromSymbolId:n,reference:e}){let t=this.getSymbolByIdOrThrow(n),s=e.split(".").filter(l=>l.length>0);return this.resolvePath(t,s)}resolvePath(n,e){var u;let[t,...s]=e;if(t===void 0)return null;let l=this.resolveFirstSegment(n,t);if(l===null)return null;let c=l;for(let m=0;m<s.length;m++){let y=s[m];if(X(y),c=(u=c.getChildByName(y))!=null?u:null,c===null)return null}return c}resolveFirstSegment(n,e){let t=n;for(;t!==null;){let c=t.getChildByName(e);if(c)return c;t=t.parent}let s=n.kind==="module"?n:n.getNearestModuleAncestorOrThrow();if(s.name===e)return s;for(let c of s.imports)if(c.name===e)return c;let l=null;for(let c of s.imports){let u=c.getChildByName(e);if(u){if(l!=null&&l.id!==u.id)return null;l=u}}return l}getSymbolByIdOrThrow(n){let e=this.symbolsById.get(n);return X(e,`A symbol with the ID '${n}' was not found in the registry.`),e}getSymbolById(n){var e;return(e=this.symbolsById.get(n))!=null?e:null}validateSymbolNotExists(n){if(this.symbolsById.has(n))throw new Error(`A symbol with the ID '${n}' already exists in the registry.`)}};var ce=class i{constructor(n,e,t){a(this,"graph");a(this,"swiftSymbol");a(this,"foundationSymbol");a(this,"registeredSourceModule");a(this,"registeredTestModule");this.graph=n,this.swiftSymbol=e,this.foundationSymbol=t,this.registeredSourceModule=null,this.registeredTestModule=null}static create(){let{graph:n,swiftSymbol:e,foundationSymbol:t}=i.createGraph();return new i(n,e,t)}static createGraph(){let n=new G,e=()=>{let c=n.createModuleSymbol({symbolId:b.SWIFT_SYMBOL_ID,symbolName:b.SWIFT_SYMBOL_NAME});return b.swiftTypeSymbols.forEach(u=>{let m=n.createTypeSymbol({symbolId:u.id,symbolName:u.name,shape:{type:"system"}});n.nestSymbol({parentSymbolId:c.id,childSymbolId:m.id})}),c},t=()=>{let c=n.createModuleSymbol({symbolId:b.FOUNDATION_SYMBOL_ID,symbolName:b.FOUNDATION_SYMBOL_NAME});return b.foundationTypeSymbols.forEach(u=>{let m=n.createTypeSymbol({symbolId:u.id,symbolName:u.name,shape:{type:"system"}});n.nestSymbol({parentSymbolId:c.id,childSymbolId:m.id})}),c},s=e(),l=t();return{graph:n,swiftSymbol:s,foundationSymbol:l}}getRegisteredSourceModuleSymbolOrThrow(){return x(this.registeredSourceModule,"Module symbol not found."),b.create(this.registeredSourceModule.id,this.registeredSourceModule.name,{type:"other"})}getRegisteredTestModuleSymbolOrThrow(){return x(this.registeredTestModule,"Module symbol not found."),b.create(this.registeredTestModule.id,this.registeredTestModule.name,{type:"other"})}getSymbolByIdOrThrow(n){let e=this.graph.getSymbolById(n);return x(e,`Symbol with ID '${n}' not found in registry.`),b.create(e.id,e.name,e.kind==="type"?e.shape:{type:"other"})}registerSourceModule(n){let e=n,t=this.graph.createModuleSymbol({symbolId:e,symbolName:n});return t.addImport(this.swiftSymbol),t.addImport(this.foundationSymbol),this.registeredSourceModule=t,b.create(t.id,t.name,{type:"other"})}registerTestModule(n){let e=n,t=this.graph.createModuleSymbol({symbolId:e,symbolName:n});return t.addImport(this.swiftSymbol),t.addImport(this.foundationSymbol),x(this.registeredSourceModule,"Cannot register a test module before registering a source module."),t.addImport(this.registeredSourceModule),this.registeredTestModule=t,b.create(t.id,t.name,{type:"other"})}registerSourceModuleType(n,e){x(this.registeredSourceModule,"Cannot register a type before registering a module.");let t=this.inferSymbolIdForSourceModuleType(n),s=this.graph.createTypeSymbol({symbolId:t,symbolName:n,shape:e});return this.graph.nestSymbol({parentSymbolId:this.registeredSourceModule.id,childSymbolId:s.id}),b.create(s.id,s.name,e)}registerTestModuleType(n,e){x(this.registeredTestModule,"Cannot register a type before registering a module.");let t=this.inferSymbolIdForTestModuleType(n),s=this.graph.createTypeSymbol({symbolId:t,symbolName:n,shape:e});return this.graph.nestSymbol({parentSymbolId:this.registeredTestModule.id,childSymbolId:s.id}),b.create(s.id,s.name,e)}registerNestedType({parentSymbol:n,symbolName:e,shape:t}){let s=typeof n=="string"?n:n.id,l=this.inferSymbolIdForNestedType(s,e),c=this.graph.createTypeSymbol({symbolId:l,symbolName:e,shape:t});return this.graph.nestSymbol({parentSymbolId:s,childSymbolId:c.id}),b.create(c.id,c.name,t)}reference({fromSymbol:n,toSymbol:e}){let t=typeof n=="string"?n:n.id,s=typeof e=="string"?e:e.id;return this.graph.reference({fromSymbolId:t,targetSymbolId:s})}resolveReference({fromSymbol:n,reference:e}){let t=typeof n=="string"?n:n.id,s=this.graph.resolveReference({fromSymbolId:t,reference:e});return s?b.create(s.id,s.name,s.kind==="type"?s.shape:{type:"other"}):null}inferSymbolIdForSourceModuleType(n){return x(this.registeredSourceModule,"Cannot get symbol id for a type before registering a module."),`${this.registeredSourceModule.id}.${n}`}inferSymbolIdForTestModuleType(n){return x(this.registeredTestModule,"Cannot get symbol id for a type before registering a module."),`${this.registeredTestModule.id}.${n}`}inferSymbolIdForNestedType(n,e){return`${n}.${e}`}};function Et(i){return new D(i)}function It(i){return new g(i)}function kt(i){return new B(i)}function At(i){return new $(i)}function Ot(i){return new W(i)}function Ct(i){return new z(i)}function Mt(i){return new q(i)}function Dt(i){return new U(i)}function Bt(i){return new R(i)}function Ft(i){return new P(i)}function $t(i){return new V(i)}function Wt(i){return new j(i)}function zt(i){return new Y(i)}function qt(i){return new K(i)}r();o();export{S as a,Je as b,Ne as c,Ee as d,Xn as e,Ie as f};
|
|
20
|
+
//# sourceMappingURL=chunk-JFTYS7SI.js.map
|