@magicbell/codegen
Advanced tools
Comparing version 0.2.1 to 0.2.2
/** | ||
* @license @magicbell/codegen v0.2.1 | ||
* @license @magicbell/codegen v0.2.2 | ||
* | ||
@@ -4,0 +4,0 @@ * Copyright (c) MagicBell Inc. and its affiliates. |
/** | ||
* @license @magicbell/codegen v0.2.1 | ||
* @license @magicbell/codegen v0.2.2 | ||
* | ||
@@ -308,2 +308,23 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
} | ||
function findBestMatch(str, keys) { | ||
let bestMatch = ""; | ||
let bestMatchScore = 0; | ||
for (const key of keys) { | ||
let score = 0; | ||
let i = 0; | ||
let j = 0; | ||
while (i < str.length && j < key.length) { | ||
if (str[i] === key[j]) { | ||
score++; | ||
j++; | ||
} | ||
i++; | ||
} | ||
if (score > bestMatchScore) { | ||
bestMatchScore = score; | ||
bestMatch = key; | ||
} | ||
} | ||
return bestMatch; | ||
} | ||
async function getOpenAPIDocument(file, options = { dereference: true }) { | ||
@@ -320,4 +341,3 @@ const parse2 = options.dereference ? parser__default.default.dereference.bind(parser__default.default) : parser__default.default.parse.bind(parser__default.default); | ||
function getRootPathMethods(document, path2) { | ||
var _a, _b, _c; | ||
const paginationProps = Object.keys(((_a = document.components.schemas.PaginationProps) == null ? void 0 : _a.properties) || {}); | ||
var _a, _b; | ||
const methods = []; | ||
@@ -327,3 +347,4 @@ const apiPaths = Object.keys(document.paths).filter((x) => x.startsWith(`/${path2}`)); | ||
const schema = mergeAllOf__default.default(body.schema); | ||
let entity = Object.keys(schema.properties).find((x) => !paginationProps.includes(x)); | ||
const schemaProperties = Object.keys(schema.properties); | ||
let entity = findBestMatch(path2, schemaProperties); | ||
if (entity !== "notification_preferences") { | ||
@@ -358,3 +379,3 @@ entity = entity.replace(/s$/, ""); | ||
const TypePrefix = [name, resource, group].filter(Boolean).map(pascalCase).join(""); | ||
const requestBody = (_b = getRequestBody(operation)) == null ? void 0 : _b.schema; | ||
const requestBody = (_a = getRequestBody(operation)) == null ? void 0 : _a.schema; | ||
const data = query.length ? { | ||
@@ -372,3 +393,3 @@ title: TypePrefix + "PayloadSchema", | ||
}); | ||
const successResponse = (_c = getResponseBody(operation)) == null ? void 0 : _c.schema; | ||
const successResponse = (_b = getResponseBody(operation)) == null ? void 0 : _b.schema; | ||
const returns = __spreadValues({ | ||
@@ -393,2 +414,15 @@ title: TypePrefix + "ResponseSchema", | ||
} | ||
const methodOrder = ["post", "get", "put", "patch", "delete"]; | ||
methods.sort((a, b) => { | ||
const methodDiff = methodOrder.indexOf(a.method) - methodOrder.indexOf(b.method); | ||
if (methodDiff !== 0) | ||
return methodDiff; | ||
if (a.method === "get") { | ||
if (a.type === "list" && b.type !== "list") | ||
return -1; | ||
if (b.type === "list" && a.type !== "list") | ||
return 1; | ||
} | ||
return a.name.localeCompare(b.name); | ||
}); | ||
return methods; | ||
@@ -395,0 +429,0 @@ } |
/** | ||
* @license @magicbell/codegen v0.2.1 | ||
* @license @magicbell/codegen v0.2.2 | ||
* | ||
@@ -10,4 +10,4 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
"use strict";var le=Object.defineProperty,ue=Object.defineProperties;var ce=Object.getOwnPropertyDescriptors;var W=Object.getOwnPropertySymbols;var fe=Object.prototype.hasOwnProperty,de=Object.prototype.propertyIsEnumerable;var v=(e,t,r)=>t in e?le(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,c=(e,t)=>{for(var r in t||(t={}))fe.call(t,r)&&v(e,r,t[r]);if(W)for(var r of W(t))de.call(t,r)&&v(e,r,t[r]);return e},g=(e,t)=>ue(e,ce(t));Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("ast-types"),ye=require("recast"),me=require("recast/parsers/typescript"),be=require("eslint"),ge=require("path"),he=require("prettier"),je=require("prettier/parser-markdown"),Oe=require("fs/promises"),_e=require("@apidevtools/swagger-parser"),$e=require("axios"),Se=require("json-schema-merge-allof"),m=e=>e&&typeof e=="object"&&"default"in e?e:{default:e};function U(e){if(e&&e.__esModule)return e;const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const w=U(ye),G=U(me),H=m(ge),we=m(he),Pe=m(je),E=m(Oe),$=m(_e),Re=m($e),J=m(Se);function Te(e){return we.default.format(e,{parser:"markdown",plugins:[Pe.default],singleQuote:!0,semi:!0,trailingComma:"all",printWidth:120,tabWidth:2})}const Ce=new be.ESLint({fix:!0,useEslintrc:!0,cwd:H.default.join(process.cwd(),"../.."),overrideConfig:{rules:{"prettier/prettier":["error",{parser:"typescript"}]}}});async function q(e){return Ce.lintText(e).then(t=>{var r;return(r=t[0].messages)!=null&&r.length&&(console.log("CODE ERRORS:"),console.dir({t:typeof e,messages:t[0].messages,code:e.split(` | ||
`).map((n,s,f)=>`${String(s+1).padStart(String(f.length).length," ")} ${n}`).join(` | ||
"use strict";var pe=Object.defineProperty,ce=Object.defineProperties;var ue=Object.getOwnPropertyDescriptors;var W=Object.getOwnPropertySymbols;var fe=Object.prototype.hasOwnProperty,de=Object.prototype.propertyIsEnumerable;var v=(e,t,r)=>t in e?pe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,d=(e,t)=>{for(var r in t||(t={}))fe.call(t,r)&&v(e,r,t[r]);if(W)for(var r of W(t))de.call(t,r)&&v(e,r,t[r]);return e},j=(e,t)=>ce(e,ue(t));Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("ast-types"),ye=require("recast"),me=require("recast/parsers/typescript"),be=require("eslint"),ge=require("path"),he=require("prettier"),je=require("prettier/parser-markdown"),Oe=require("fs/promises"),_e=require("@apidevtools/swagger-parser"),Se=require("axios"),$e=require("json-schema-merge-allof"),b=e=>e&&typeof e=="object"&&"default"in e?e:{default:e};function U(e){if(e&&e.__esModule)return e;const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const R=U(ye),G=U(me),H=b(ge),we=b(he),Pe=b(je),E=b(Oe),w=b(_e),Re=b(Se),J=b($e);function Te(e){return we.default.format(e,{parser:"markdown",plugins:[Pe.default],singleQuote:!0,semi:!0,trailingComma:"all",printWidth:120,tabWidth:2})}const Ce=new be.ESLint({fix:!0,useEslintrc:!0,cwd:H.default.join(process.cwd(),"../.."),overrideConfig:{rules:{"prettier/prettier":["error",{parser:"typescript"}]}}});async function q(e){return Ce.lintText(e).then(t=>{var r;return(r=t[0].messages)!=null&&r.length&&(console.log("CODE ERRORS:"),console.dir({t:typeof e,messages:t[0].messages,code:e.split(` | ||
`).map((n,o,p)=>`${String(o+1).padStart(String(p.length).length," ")} ${n}`).join(` | ||
`)},{depth:null})),t[0].output||e})}function Q(e,t=80){return e.replace(new RegExp(`(?![^\\n]{1,${t}}$)([^\\n]{1,${t}})\\s`,"g"),`$1 | ||
@@ -18,8 +18,8 @@ `).split(` | ||
${e.filter(t=>typeof t=="string").flatMap(t=>Q(t).split(` | ||
`).map((r,n,s)=>n>0&&s[0][0]==="@"?` ${r}`:r)).map(t=>` * ${t}`).join(` | ||
`).map((r,n,o)=>n>0&&o[0][0]==="@"?` ${r}`:r)).map(t=>` * ${t}`).join(` | ||
`)} | ||
*`)}function ke(e,t){return i.builders.objectProperty.from({key:i.builders.identifier(e),value:typeof t=="object"?t:typeof t>"u"?i.builders.identifier(e):typeof t=="boolean"?i.builders.booleanLiteral(t):typeof t=="number"?i.builders.numericLiteral(t):i.builders.stringLiteral(t),shorthand:typeof t>"u"})}function Me(e,t,r=!1){return i.builders.identifier.from({name:r?`${e}?`:`${e}`,typeAnnotation:i.builders.tsTypeAnnotation(t==="string"?i.builders.tsStringKeyword():i.builders.tsTypeReference(i.builders.identifier(`${t}`)))})}function De(e,t,r){const n=w.parse(`const schema = ${JSON.stringify(t)}`,{parser:G}).program.body[0].declarations[0].init;return i.builders.exportNamedDeclaration.from({declaration:i.builders.variableDeclaration.from({kind:"const",declarations:[i.builders.variableDeclarator.from({id:i.builders.identifier(e),init:i.builders.tsAsExpression.from({expression:n,typeAnnotation:r?i.builders.tsTypeReference(i.builders.identifier(r)):void 0})})]})})}function Le(e,t,r){return i.builders.tsTypeAliasDeclaration.from({id:i.builders.identifier(e),typeAnnotation:i.builders.tsTypeReference.from({typeName:i.builders.identifier(t),typeParameters:r?i.builders.tsTypeParameterInstantiation.from({params:[i.builders.tsTypeQuery.from({exprName:i.builders.identifier(r)})]}):void 0})})}function Ne(e,t){return i.builders.classProperty.from({key:i.builders.identifier(e),value:typeof t=="string"?i.builders.stringLiteral(t):t})}function Ie(e,...t){return i.builders.newExpression.from({callee:i.builders.identifier(e),arguments:t.map(r=>i.builders.identifier(r)).filter(Boolean)})}function xe(e,...t){return i.builders.callExpression.from({callee:i.builders.identifier(e),arguments:t.map(r=>typeof r=="string"?i.builders.identifier(r):r).filter(Boolean)})}function We(...e){return i.builders.objectExpression(e.filter(Boolean))}function ve(e){return i.builders.identifier(e)}const ze=Object.freeze(Object.defineProperty({__proto__:null,importDeclaration:Ee,commentLine:qe,commentBlock:Be,objectProperty:ke,param:Me,exportObject:De,tsTypeAliasDeclaration:Le,classProperty:Ne,newExpression:Ie,callExpression:xe,objectExpression:We,id:ve},Symbol.toStringTag,{value:"Module"}));async function Fe(e,t,r){const n=await E.default.readFile(e,"utf-8").then(a=>a.split(` | ||
`)),s=n.indexOf(`<!-- AUTO-GENERATED-CONTENT:START (${t}) -->`),f=n.indexOf(`<!-- AUTO-GENERATED-CONTENT:END (${t}) -->`);return n.splice(s+1,f-s-1,"",(Array.isArray(r)?r:[r]).join(` | ||
*`)}function Me(e,t){return i.builders.objectProperty.from({key:i.builders.identifier(e),value:typeof t=="object"?t:typeof t>"u"?i.builders.identifier(e):typeof t=="boolean"?i.builders.booleanLiteral(t):typeof t=="number"?i.builders.numericLiteral(t):i.builders.stringLiteral(t),shorthand:typeof t>"u"})}function ke(e,t,r=!1){return i.builders.identifier.from({name:r?`${e}?`:`${e}`,typeAnnotation:i.builders.tsTypeAnnotation(t==="string"?i.builders.tsStringKeyword():i.builders.tsTypeReference(i.builders.identifier(`${t}`)))})}function De(e,t,r){const n=R.parse(`const schema = ${JSON.stringify(t)}`,{parser:G}).program.body[0].declarations[0].init;return i.builders.exportNamedDeclaration.from({declaration:i.builders.variableDeclaration.from({kind:"const",declarations:[i.builders.variableDeclarator.from({id:i.builders.identifier(e),init:i.builders.tsAsExpression.from({expression:n,typeAnnotation:r?i.builders.tsTypeReference(i.builders.identifier(r)):void 0})})]})})}function Le(e,t,r){return i.builders.tsTypeAliasDeclaration.from({id:i.builders.identifier(e),typeAnnotation:i.builders.tsTypeReference.from({typeName:i.builders.identifier(t),typeParameters:r?i.builders.tsTypeParameterInstantiation.from({params:[i.builders.tsTypeQuery.from({exprName:i.builders.identifier(r)})]}):void 0})})}function Ne(e,t){return i.builders.classProperty.from({key:i.builders.identifier(e),value:typeof t=="string"?i.builders.stringLiteral(t):t})}function Ie(e,...t){return i.builders.newExpression.from({callee:i.builders.identifier(e),arguments:t.map(r=>i.builders.identifier(r)).filter(Boolean)})}function xe(e,...t){return i.builders.callExpression.from({callee:i.builders.identifier(e),arguments:t.map(r=>typeof r=="string"?i.builders.identifier(r):r).filter(Boolean)})}function We(...e){return i.builders.objectExpression(e.filter(Boolean))}function ve(e){return i.builders.identifier(e)}const ze=Object.freeze(Object.defineProperty({__proto__:null,importDeclaration:Ee,commentLine:qe,commentBlock:Be,objectProperty:Me,param:ke,exportObject:De,tsTypeAliasDeclaration:Le,classProperty:Ne,newExpression:Ie,callExpression:xe,objectExpression:We,id:ve},Symbol.toStringTag,{value:"Module"}));async function Fe(e,t,r){const n=await E.default.readFile(e,"utf-8").then(a=>a.split(` | ||
`)),o=n.indexOf(`<!-- AUTO-GENERATED-CONTENT:START (${t}) -->`),p=n.indexOf(`<!-- AUTO-GENERATED-CONTENT:END (${t}) -->`);return n.splice(o+1,p-o-1,"",(Array.isArray(r)?r:[r]).join(` | ||
`).trim(),""),E.default.writeFile(e,n.join(` | ||
`),"utf-8")}function Ue(e){return e&&!("$ref"in e)}function B(e){if(e==null||!("type"in e))return null;if(e.type==="object"||!e.type)return Object.keys(e.properties||{}).reduce((t,r)=>Object.assign(t,{[r]:B(e.properties[r])}),{});if(e.type==="array")return(Array.isArray(e.items)?e.items:[e.items]).map(r=>B(r));if(e.type==="string")return"\u2026";if(e.type==="integer")return 1;if(e.type==="boolean")return!0;if(e.type)throw new Error(`unimplemented schema type: ${e.type}`);return e}function S(e){return typeof e!="object"||e==null||!("type"in e)||e.type==="object"&&!e.properties||e.type==="array"&&!e.items}function X(e){return Object.keys((e==null?void 0:e.responses)||{}).map(t=>Number(t)).find(t=>t>=200&&t<=299)}function k(e){if(!e||typeof e!="object"||!("requestBody"in e&&"content"in e.requestBody))return null;const t=e.requestBody.content["application/json"];return t||null}function M(e,t=X(e)){var s;const r=(s=e==null?void 0:e.responses)==null?void 0:s[t];if(!r||typeof r!="object"||!("content"in r&&"application/json"in r.content))return null;const n=r.content["application/json"];return n||null}function D(e,t){const[r,n,s]=t.replace("#/","").split("/");return e[r][n][s]}async function Y(e,t={dereference:!0}){const r=t.dereference?$.default.dereference.bind($.default):$.default.parse.bind($.default),n=/https?:\/\//.test(e)?await Re.default.get(e).then(s=>s.data):await E.default.readFile(e,"utf-8").then(s=>JSON.parse(s));return r(n)}function ee(e){const r=Object.keys(e.paths).map(n=>n.split("/").filter(Boolean)[0]);return Array.from(new Set(r))}function te(e,t){var u,h,b;const r=Object.keys(((u=e.components.schemas.PaginationProps)==null?void 0:u.properties)||{}),n=[],s=Object.keys(e.paths).filter(d=>d.startsWith(`/${t}`)),f=k(e.paths[`/${t}`].post)||M(e.paths[`/${t}`].get),a=J.default(f.schema);let p=Object.keys(a.properties).find(d=>!r.includes(d));p!=="notification_preferences"&&(p=p.replace(/s$/,""));for(const d of s){const[P,R]=d.replaceAll("_","-").split("/").filter(j=>j&&!j.includes("{"));for(const j of Object.keys(e.paths[d])){const l=e.paths[d][j];if(!l.operationId)continue;const ne=l.operationId.slice(0,P.length),O=l.operationId.startsWith(`${P}-${R}-`)?R:void 0,T=L(l.operationId.slice(P.length+1+(O?R.length+1:0))),ie=T==="list"?"list":null,se=O?V(O.replace(/s$/,"")):p,oe=d.replace(`/${t}`,"").replace(/^\//,""),ae=(d.match(/{\w+}/g)||[]).map(o=>o.replace(/[{}]/g,"")).map(o=>{const y=l.parameters.find(x=>x.in==="path"&&x.name===o);return c({title:o,description:y==null?void 0:y.description,type:"string"},y==null?void 0:y.schema)}),C=(l.parameters||[]).filter(o=>o.in==="query").map(o=>c({title:o.name,description:o.description},o.schema)),A=[T,ne,O].filter(Boolean).map(Z).join(""),pe=(h=k(l))==null?void 0:h.schema,N=C.length?{title:A+"PayloadSchema",type:"object",properties:C.reduce((o,y)=>g(c({},o),{[y.title]:y}),{}),additionalProperties:!1,required:C.filter(o=>o.required).map(o=>o.title)}:g(c({title:A+"PayloadSchema",type:"object"},z(e,pe,{entity:p,excludeReadOnly:!0})),{additionalProperties:!1}),_=(b=M(l))==null?void 0:b.schema,I=c({title:A+"ResponseSchema",description:_==null?void 0:_.description},z(e,_,{entity:p}));n.push(c({name:T,entity:se,type:ie,group:O,path:oe,method:j,private:Boolean(l["x-private"]),beta:Boolean(l["x-beta"]),returns:S(I)?null:I,params:ae.filter(o=>!S(o)),data:S(N)?null:N},l))}}return n}function z(e,t,r){var u;if(!t)return null;const n="$ref"in t?D(e,t.$ref):t,s=((u=n.properties)==null?void 0:u[r.entity])||n,f="$ref"in s?D(e,s.$ref):s,a=J.default(f);if(!r.excludeReadOnly||!a.properties)return a;const p=g(c({},a),{properties:{}});for(const[h,b]of Object.entries(a.properties||{}))(b==null?void 0:b.readOnly)!==!0&&(p.properties[h]=a.properties[h]);return p}const F={tabWidth:2,quote:"single",wrapColumn:120};function Ge(e){return w.parse(e,{parser:G})}function He(e,t=!0){return q(t?w.prettyPrint(e,F).code:w.print(e,F).code)}const Je=Object.freeze(Object.defineProperty({__proto__:null,parse:Ge,print:He},Symbol.toStringTag,{value:"Module"}));async function Qe(e){const t=await Y(e);return ee(t).map(n=>({path:n,methods:te(t,n),summary:t.paths[`/${n}`].summary,description:t.paths[`/${n}`].description}))}function Ze(e,t){return e.map(r=>g(c({},r),{methods:r.methods.filter(n=>t(n))})).filter(r=>r.methods.length)}function Ke(e,t){return e.parameters.some(r=>r.in==="header"&&r.name.toLowerCase()===t.name.toLowerCase()&&r.required===t.required)}function Ve(e){return e.flatMap(t=>t.methods).filter(t=>t.beta).sort((t,r)=>t.operationId.localeCompare(r.operationId))}function re(e){const t=g(c({name:e.path},e),{methods:e.methods.filter(n=>!n.group)}),r=e.methods.reduce((n,s)=>(s.group&&!n.includes(s.group)&&n.push(s.group),n),[]).map(n=>({name:`${e.path}_${n}`,path:`${e.path}/${n}`,methods:e.methods.filter(s=>s.group===n)}));return[t,...r]}async function Xe(e,t,r,n){const s=[];for(const f of e){const[a,...p]=re(f);for(const u of[a,...p])s.push({name:H.default.join(t,K(u.path)+".ts"),source:await r(u,u===a?p:[]),docs:await n(u)})}return s}exports.builders=ze;exports.camelCase=L;exports.capitalize=Ae;exports.filterResourcesMethods=Ze;exports.flattenResourceMethods=re;exports.formatCode=q;exports.formatMarkdown=Te;exports.generateResourceFiles=Xe;exports.getBetaMethods=Ve;exports.getByRef=D;exports.getOpenAPIDocument=Y;exports.getRequestBody=k;exports.getResources=Qe;exports.getResponseBody=M;exports.getRootPathMethods=te;exports.getRootPaths=ee;exports.getSuccessStatusCode=X;exports.hasHeader=Ke;exports.hyphenCase=K;exports.isEmptySchema=S;exports.isSchemaObject=Ue;exports.pascalCase=Z;exports.recast=Je;exports.schemaToObject=B;exports.snakeCase=V;exports.updateReadme=Fe;exports.wrapText=Q; | ||
`),"utf-8")}function Ue(e){return e&&!("$ref"in e)}function B(e){if(e==null||!("type"in e))return null;if(e.type==="object"||!e.type)return Object.keys(e.properties||{}).reduce((t,r)=>Object.assign(t,{[r]:B(e.properties[r])}),{});if(e.type==="array")return(Array.isArray(e.items)?e.items:[e.items]).map(r=>B(r));if(e.type==="string")return"\u2026";if(e.type==="integer")return 1;if(e.type==="boolean")return!0;if(e.type)throw new Error(`unimplemented schema type: ${e.type}`);return e}function P(e){return typeof e!="object"||e==null||!("type"in e)||e.type==="object"&&!e.properties||e.type==="array"&&!e.items}function X(e){return Object.keys((e==null?void 0:e.responses)||{}).map(t=>Number(t)).find(t=>t>=200&&t<=299)}function M(e){if(!e||typeof e!="object"||!("requestBody"in e&&"content"in e.requestBody))return null;const t=e.requestBody.content["application/json"];return t||null}function k(e,t=X(e)){var o;const r=(o=e==null?void 0:e.responses)==null?void 0:o[t];if(!r||typeof r!="object"||!("content"in r&&"application/json"in r.content))return null;const n=r.content["application/json"];return n||null}function D(e,t){const[r,n,o]=t.replace("#/","").split("/");return e[r][n][o]}function Ge(e,t){let r="",n=0;for(const o of t){let p=0,a=0,l=0;for(;a<e.length&&l<o.length;)e[a]===o[l]&&(p++,l++),a++;p>n&&(n=p,r=o)}return r}async function Y(e,t={dereference:!0}){const r=t.dereference?w.default.dereference.bind(w.default):w.default.parse.bind(w.default),n=/https?:\/\//.test(e)?await Re.default.get(e).then(o=>o.data):await E.default.readFile(e,"utf-8").then(o=>JSON.parse(o));return r(n)}function ee(e){const r=Object.keys(e.paths).map(n=>n.split("/").filter(Boolean)[0]);return Array.from(new Set(r))}function te(e,t){var O,g;const r=[],n=Object.keys(e.paths).filter(c=>c.startsWith(`/${t}`)),o=M(e.paths[`/${t}`].post)||k(e.paths[`/${t}`].get),p=J.default(o.schema),a=Object.keys(p.properties);let l=Ge(t,a);l!=="notification_preferences"&&(l=l.replace(/s$/,""));for(const c of n){const[m,h]=c.replaceAll("_","-").split("/").filter(_=>_&&!_.includes("{"));for(const _ of Object.keys(e.paths[c])){const u=e.paths[c][_];if(!u.operationId)continue;const ne=u.operationId.slice(0,m.length),S=u.operationId.startsWith(`${m}-${h}-`)?h:void 0,T=L(u.operationId.slice(m.length+1+(S?h.length+1:0))),ie=T==="list"?"list":null,oe=S?V(S.replace(/s$/,"")):l,se=c.replace(`/${t}`,"").replace(/^\//,""),ae=(c.match(/{\w+}/g)||[]).map(s=>s.replace(/[{}]/g,"")).map(s=>{const y=u.parameters.find(x=>x.in==="path"&&x.name===s);return d({title:s,description:y==null?void 0:y.description,type:"string"},y==null?void 0:y.schema)}),C=(u.parameters||[]).filter(s=>s.in==="query").map(s=>d({title:s.name,description:s.description},s.schema)),A=[T,ne,S].filter(Boolean).map(Z).join(""),le=(O=M(u))==null?void 0:O.schema,N=C.length?{title:A+"PayloadSchema",type:"object",properties:C.reduce((s,y)=>j(d({},s),{[y.title]:y}),{}),additionalProperties:!1,required:C.filter(s=>s.required).map(s=>s.title)}:j(d({title:A+"PayloadSchema",type:"object"},z(e,le,{entity:l,excludeReadOnly:!0})),{additionalProperties:!1}),$=(g=k(u))==null?void 0:g.schema,I=d({title:A+"ResponseSchema",description:$==null?void 0:$.description},z(e,$,{entity:l}));r.push(d({name:T,entity:oe,type:ie,group:S,path:se,method:_,private:Boolean(u["x-private"]),beta:Boolean(u["x-beta"]),returns:P(I)?null:I,params:ae.filter(s=>!P(s)),data:P(N)?null:N},u))}}const f=["post","get","put","patch","delete"];return r.sort((c,m)=>{const h=f.indexOf(c.method)-f.indexOf(m.method);if(h!==0)return h;if(c.method==="get"){if(c.type==="list"&&m.type!=="list")return-1;if(m.type==="list"&&c.type!=="list")return 1}return c.name.localeCompare(m.name)}),r}function z(e,t,r){var f;if(!t)return null;const n="$ref"in t?D(e,t.$ref):t,o=((f=n.properties)==null?void 0:f[r.entity])||n,p="$ref"in o?D(e,o.$ref):o,a=J.default(p);if(!r.excludeReadOnly||!a.properties)return a;const l=j(d({},a),{properties:{}});for(const[O,g]of Object.entries(a.properties||{}))(g==null?void 0:g.readOnly)!==!0&&(l.properties[O]=a.properties[O]);return l}const F={tabWidth:2,quote:"single",wrapColumn:120};function He(e){return R.parse(e,{parser:G})}function Je(e,t=!0){return q(t?R.prettyPrint(e,F).code:R.print(e,F).code)}const Qe=Object.freeze(Object.defineProperty({__proto__:null,parse:He,print:Je},Symbol.toStringTag,{value:"Module"}));async function Ze(e){const t=await Y(e);return ee(t).map(n=>({path:n,methods:te(t,n),summary:t.paths[`/${n}`].summary,description:t.paths[`/${n}`].description}))}function Ke(e,t){return e.map(r=>j(d({},r),{methods:r.methods.filter(n=>t(n))})).filter(r=>r.methods.length)}function Ve(e,t){return e.parameters.some(r=>r.in==="header"&&r.name.toLowerCase()===t.name.toLowerCase()&&r.required===t.required)}function Xe(e){return e.flatMap(t=>t.methods).filter(t=>t.beta).sort((t,r)=>t.operationId.localeCompare(r.operationId))}function re(e){const t=j(d({name:e.path},e),{methods:e.methods.filter(n=>!n.group)}),r=e.methods.reduce((n,o)=>(o.group&&!n.includes(o.group)&&n.push(o.group),n),[]).map(n=>({name:`${e.path}_${n}`,path:`${e.path}/${n}`,methods:e.methods.filter(o=>o.group===n)}));return[t,...r]}async function Ye(e,t,r,n){const o=[];for(const p of e){const[a,...l]=re(p);for(const f of[a,...l])o.push({name:H.default.join(t,K(f.path)+".ts"),source:await r(f,f===a?l:[]),docs:await n(f)})}return o}exports.builders=ze;exports.camelCase=L;exports.capitalize=Ae;exports.filterResourcesMethods=Ke;exports.flattenResourceMethods=re;exports.formatCode=q;exports.formatMarkdown=Te;exports.generateResourceFiles=Ye;exports.getBetaMethods=Xe;exports.getByRef=D;exports.getOpenAPIDocument=Y;exports.getRequestBody=M;exports.getResources=Ze;exports.getResponseBody=k;exports.getRootPathMethods=te;exports.getRootPaths=ee;exports.getSuccessStatusCode=X;exports.hasHeader=Ve;exports.hyphenCase=K;exports.isEmptySchema=P;exports.isSchemaObject=Ue;exports.pascalCase=Z;exports.recast=Qe;exports.schemaToObject=B;exports.snakeCase=V;exports.updateReadme=Fe;exports.wrapText=Q; | ||
//# sourceMappingURL=magicbell-codegen.cjs.min.js.map |
/** | ||
* @license @magicbell/codegen v0.2.1 | ||
* @license @magicbell/codegen v0.2.2 | ||
* | ||
@@ -278,2 +278,23 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
} | ||
function findBestMatch(str, keys) { | ||
let bestMatch = ""; | ||
let bestMatchScore = 0; | ||
for (const key of keys) { | ||
let score = 0; | ||
let i = 0; | ||
let j = 0; | ||
while (i < str.length && j < key.length) { | ||
if (str[i] === key[j]) { | ||
score++; | ||
j++; | ||
} | ||
i++; | ||
} | ||
if (score > bestMatchScore) { | ||
bestMatchScore = score; | ||
bestMatch = key; | ||
} | ||
} | ||
return bestMatch; | ||
} | ||
async function getOpenAPIDocument(file, options = { dereference: true }) { | ||
@@ -290,4 +311,3 @@ const parse2 = options.dereference ? parser.dereference.bind(parser) : parser.parse.bind(parser); | ||
function getRootPathMethods(document, path2) { | ||
var _a, _b, _c; | ||
const paginationProps = Object.keys(((_a = document.components.schemas.PaginationProps) == null ? void 0 : _a.properties) || {}); | ||
var _a, _b; | ||
const methods = []; | ||
@@ -297,3 +317,4 @@ const apiPaths = Object.keys(document.paths).filter((x) => x.startsWith(`/${path2}`)); | ||
const schema = mergeAllOf(body.schema); | ||
let entity = Object.keys(schema.properties).find((x) => !paginationProps.includes(x)); | ||
const schemaProperties = Object.keys(schema.properties); | ||
let entity = findBestMatch(path2, schemaProperties); | ||
if (entity !== "notification_preferences") { | ||
@@ -328,3 +349,3 @@ entity = entity.replace(/s$/, ""); | ||
const TypePrefix = [name, resource, group].filter(Boolean).map(pascalCase).join(""); | ||
const requestBody = (_b = getRequestBody(operation)) == null ? void 0 : _b.schema; | ||
const requestBody = (_a = getRequestBody(operation)) == null ? void 0 : _a.schema; | ||
const data = query.length ? { | ||
@@ -342,3 +363,3 @@ title: TypePrefix + "PayloadSchema", | ||
}); | ||
const successResponse = (_c = getResponseBody(operation)) == null ? void 0 : _c.schema; | ||
const successResponse = (_b = getResponseBody(operation)) == null ? void 0 : _b.schema; | ||
const returns = __spreadValues({ | ||
@@ -363,2 +384,15 @@ title: TypePrefix + "ResponseSchema", | ||
} | ||
const methodOrder = ["post", "get", "put", "patch", "delete"]; | ||
methods.sort((a, b) => { | ||
const methodDiff = methodOrder.indexOf(a.method) - methodOrder.indexOf(b.method); | ||
if (methodDiff !== 0) | ||
return methodDiff; | ||
if (a.method === "get") { | ||
if (a.type === "list" && b.type !== "list") | ||
return -1; | ||
if (b.type === "list" && a.type !== "list") | ||
return 1; | ||
} | ||
return a.name.localeCompare(b.name); | ||
}); | ||
return methods; | ||
@@ -365,0 +399,0 @@ } |
/** | ||
* @license @magicbell/codegen v0.2.1 | ||
* @license @magicbell/codegen v0.2.2 | ||
* | ||
@@ -12,14 +12,14 @@ * Copyright (c) MagicBell Inc. and its affiliates. | ||
var ee = Object.getOwnPropertyDescriptors; | ||
var L = Object.getOwnPropertySymbols; | ||
var D = Object.getOwnPropertySymbols; | ||
var te = Object.prototype.hasOwnProperty, re = Object.prototype.propertyIsEnumerable; | ||
var D = (e, t, r) => t in e ? X(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r, l = (e, t) => { | ||
var L = (e, t, r) => t in e ? X(e, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : e[t] = r, d = (e, t) => { | ||
for (var r in t || (t = {})) | ||
te.call(t, r) && D(e, r, t[r]); | ||
if (L) | ||
for (var r of L(t)) | ||
re.call(t, r) && D(e, r, t[r]); | ||
te.call(t, r) && L(e, r, t[r]); | ||
if (D) | ||
for (var r of D(t)) | ||
re.call(t, r) && L(e, r, t[r]); | ||
return e; | ||
}, g = (e, t) => Y(e, ee(t)); | ||
}, b = (e, t) => Y(e, ee(t)); | ||
import { builders as i } from "ast-types"; | ||
import * as w from "recast"; | ||
import * as P from "recast"; | ||
import * as F from "recast/parsers/typescript"; | ||
@@ -31,6 +31,6 @@ import { ESLint as ne } from "eslint"; | ||
import R from "fs/promises"; | ||
import O from "@apidevtools/swagger-parser"; | ||
import S from "@apidevtools/swagger-parser"; | ||
import se from "axios"; | ||
import G from "json-schema-merge-allof"; | ||
function Fe(e) { | ||
function ze(e) { | ||
return ie.format(e, { | ||
@@ -56,3 +56,3 @@ parser: "markdown", | ||
}); | ||
async function N(e) { | ||
async function M(e) { | ||
return ae.lintText(e).then((t) => { | ||
@@ -65,3 +65,3 @@ var r; | ||
code: e.split(` | ||
`).map((n, o, u) => `${String(o + 1).padStart(String(u.length).length, " ")} ${n}`).join(` | ||
`).map((n, o, c) => `${String(o + 1).padStart(String(c.length).length, " ")} ${n}`).join(` | ||
`) | ||
@@ -79,3 +79,3 @@ }, | ||
} | ||
function ze(e) { | ||
function Ge(e) { | ||
return e.split(/[_\-\s]/).map((t) => t[0].toUpperCase() + t.slice(1)).join(" "); | ||
@@ -89,6 +89,6 @@ } | ||
} | ||
function fe(e) { | ||
function le(e) { | ||
return e[0].toLowerCase() + e.replace(/[A-Z]/g, (t) => `-${t.toLowerCase()}`).replace(/_/g, "-").slice(1); | ||
} | ||
function le(e) { | ||
function fe(e) { | ||
return e[0].toLowerCase() + e.replace(/[A-Z]/g, (t) => `_${t.toLowerCase()}`).replace(/-/g, "_").slice(1); | ||
@@ -135,3 +135,3 @@ } | ||
function he(e, t, r) { | ||
const n = w.parse(`const schema = ${JSON.stringify(t)}`, { | ||
const n = P.parse(`const schema = ${JSON.stringify(t)}`, { | ||
parser: F | ||
@@ -190,6 +190,6 @@ }).program.body[0].declarations[0].init; | ||
} | ||
function Pe(e) { | ||
function Se(e) { | ||
return i.identifier(e); | ||
} | ||
const Ge = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ | ||
const Je = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ | ||
__proto__: null, | ||
@@ -207,10 +207,10 @@ importDeclaration: ue, | ||
objectExpression: we, | ||
id: Pe | ||
id: Se | ||
}, Symbol.toStringTag, { value: "Module" })); | ||
async function Je(e, t, r) { | ||
async function Qe(e, t, r) { | ||
const n = await R.readFile(e, "utf-8").then((a) => a.split(` | ||
`)), o = n.indexOf(`<!-- AUTO-GENERATED-CONTENT:START (${t}) -->`), u = n.indexOf(`<!-- AUTO-GENERATED-CONTENT:END (${t}) -->`); | ||
`)), o = n.indexOf(`<!-- AUTO-GENERATED-CONTENT:START (${t}) -->`), c = n.indexOf(`<!-- AUTO-GENERATED-CONTENT:END (${t}) -->`); | ||
return n.splice( | ||
o + 1, | ||
u - o - 1, | ||
c - o - 1, | ||
"", | ||
@@ -223,6 +223,6 @@ (Array.isArray(r) ? r : [r]).join(` | ||
} | ||
function Qe(e) { | ||
function Ze(e) { | ||
return e && !("$ref" in e); | ||
} | ||
function q(e) { | ||
function N(e) { | ||
if (e == null || !("type" in e)) | ||
@@ -232,7 +232,7 @@ return null; | ||
return Object.keys(e.properties || {}).reduce( | ||
(t, r) => Object.assign(t, { [r]: q(e.properties[r]) }), | ||
(t, r) => Object.assign(t, { [r]: N(e.properties[r]) }), | ||
{} | ||
); | ||
if (e.type === "array") | ||
return (Array.isArray(e.items) ? e.items : [e.items]).map((r) => q(r)); | ||
return (Array.isArray(e.items) ? e.items : [e.items]).map((r) => N(r)); | ||
if (e.type === "string") | ||
@@ -248,9 +248,9 @@ return "\u2026"; | ||
} | ||
function C(e) { | ||
function E(e) { | ||
return typeof e != "object" || e == null || !("type" in e) || e.type === "object" && !e.properties || e.type === "array" && !e.items; | ||
} | ||
function Se(e) { | ||
function Pe(e) { | ||
return Object.keys((e == null ? void 0 : e.responses) || {}).map((t) => Number(t)).find((t) => t >= 200 && t <= 299); | ||
} | ||
function I(e) { | ||
function q(e) { | ||
if (!e || typeof e != "object" || !("requestBody" in e && "content" in e.requestBody)) | ||
@@ -261,3 +261,3 @@ return null; | ||
} | ||
function M(e, t = Se(e)) { | ||
function I(e, t = Pe(e)) { | ||
var o; | ||
@@ -274,7 +274,17 @@ const r = (o = e == null ? void 0 : e.responses) == null ? void 0 : o[t]; | ||
} | ||
async function Te(e, t = { dereference: !0 }) { | ||
const r = t.dereference ? O.dereference.bind(O) : O.parse.bind(O), n = /https?:\/\//.test(e) ? await se.get(e).then((o) => o.data) : await R.readFile(e, "utf-8").then((o) => JSON.parse(o)); | ||
function Te(e, t) { | ||
let r = "", n = 0; | ||
for (const o of t) { | ||
let c = 0, a = 0, p = 0; | ||
for (; a < e.length && p < o.length; ) | ||
e[a] === o[p] && (c++, p++), a++; | ||
c > n && (n = c, r = o); | ||
} | ||
return r; | ||
} | ||
async function Ae(e, t = { dereference: !0 }) { | ||
const r = t.dereference ? S.dereference.bind(S) : S.parse.bind(S), n = /https?:\/\//.test(e) ? await se.get(e).then((o) => o.data) : await R.readFile(e, "utf-8").then((o) => JSON.parse(o)); | ||
return r(n); | ||
} | ||
function Ae(e) { | ||
function Ce(e) { | ||
const r = Object.keys(e.paths).map((n) => n.split("/").filter(Boolean)[0]); | ||
@@ -284,15 +294,15 @@ return Array.from(new Set(r)); | ||
function Ee(e, t) { | ||
var f, h, y; | ||
const r = Object.keys(((f = e.components.schemas.PaginationProps) == null ? void 0 : f.properties) || {}), n = [], o = Object.keys(e.paths).filter((d) => d.startsWith(`/${t}`)), u = I(e.paths[`/${t}`].post) || M(e.paths[`/${t}`].get), a = G(u.schema); | ||
let p = Object.keys(a.properties).find((d) => !r.includes(d)); | ||
var j, g; | ||
const r = [], n = Object.keys(e.paths).filter((l) => l.startsWith(`/${t}`)), o = q(e.paths[`/${t}`].post) || I(e.paths[`/${t}`].get), c = G(o.schema), a = Object.keys(c.properties); | ||
let p = Te(t, a); | ||
p !== "notification_preferences" && (p = p.replace(/s$/, "")); | ||
for (const d of o) { | ||
const [P, S] = d.replaceAll("_", "-").split("/").filter((b) => b && !b.includes("{")); | ||
for (const b of Object.keys(e.paths[d])) { | ||
const c = e.paths[d][b]; | ||
if (!c.operationId) | ||
for (const l of n) { | ||
const [y, h] = l.replaceAll("_", "-").split("/").filter(($) => $ && !$.includes("{")); | ||
for (const $ of Object.keys(e.paths[l])) { | ||
const f = e.paths[l][$]; | ||
if (!f.operationId) | ||
continue; | ||
const Q = c.operationId.slice(0, P.length), j = c.operationId.startsWith(`${P}-${S}-`) ? S : void 0, T = J(c.operationId.slice(P.length + 1 + (j ? S.length + 1 : 0))), Z = T === "list" ? "list" : null, v = j ? le(j.replace(/s$/, "")) : p, H = d.replace(`/${t}`, "").replace(/^\//, ""), K = (d.match(/{\w+}/g) || []).map((s) => s.replace(/[{}]/g, "")).map((s) => { | ||
const m = c.parameters.find((k) => k.in === "path" && k.name === s); | ||
return l({ | ||
const Q = f.operationId.slice(0, y.length), O = f.operationId.startsWith(`${y}-${h}-`) ? h : void 0, T = J(f.operationId.slice(y.length + 1 + (O ? h.length + 1 : 0))), Z = T === "list" ? "list" : null, v = O ? fe(O.replace(/s$/, "")) : p, H = l.replace(`/${t}`, "").replace(/^\//, ""), K = (l.match(/{\w+}/g) || []).map((s) => s.replace(/[{}]/g, "")).map((s) => { | ||
const m = f.parameters.find((k) => k.in === "path" && k.name === s); | ||
return d({ | ||
title: s, | ||
@@ -302,64 +312,76 @@ description: m == null ? void 0 : m.description, | ||
}, m == null ? void 0 : m.schema); | ||
}), A = (c.parameters || []).filter((s) => s.in === "query").map((s) => l({ | ||
}), A = (f.parameters || []).filter((s) => s.in === "query").map((s) => d({ | ||
title: s.name, | ||
description: s.description | ||
}, s.schema)), E = [T, Q, j].filter(Boolean).map(ce).join(""), V = (h = I(c)) == null ? void 0 : h.schema, B = A.length ? { | ||
title: E + "PayloadSchema", | ||
}, s.schema)), C = [T, Q, O].filter(Boolean).map(ce).join(""), V = (j = q(f)) == null ? void 0 : j.schema, B = A.length ? { | ||
title: C + "PayloadSchema", | ||
type: "object", | ||
properties: A.reduce((s, m) => g(l({}, s), { [m.title]: m }), {}), | ||
properties: A.reduce((s, m) => b(d({}, s), { [m.title]: m }), {}), | ||
additionalProperties: !1, | ||
required: A.filter((s) => s.required).map((s) => s.title) | ||
} : g(l({ | ||
title: E + "PayloadSchema", | ||
} : b(d({ | ||
title: C + "PayloadSchema", | ||
type: "object" | ||
}, W(e, V, { entity: p, excludeReadOnly: !0 })), { | ||
additionalProperties: !1 | ||
}), $ = (y = M(c)) == null ? void 0 : y.schema, _ = l({ | ||
title: E + "ResponseSchema", | ||
description: $ == null ? void 0 : $.description | ||
}, W(e, $, { entity: p })); | ||
n.push(l({ | ||
}), w = (g = I(f)) == null ? void 0 : g.schema, _ = d({ | ||
title: C + "ResponseSchema", | ||
description: w == null ? void 0 : w.description | ||
}, W(e, w, { entity: p })); | ||
r.push(d({ | ||
name: T, | ||
entity: v, | ||
type: Z, | ||
group: j, | ||
group: O, | ||
path: H, | ||
method: b, | ||
private: Boolean(c["x-private"]), | ||
beta: Boolean(c["x-beta"]), | ||
returns: C(_) ? null : _, | ||
params: K.filter((s) => !C(s)), | ||
data: C(B) ? null : B | ||
}, c)); | ||
method: $, | ||
private: Boolean(f["x-private"]), | ||
beta: Boolean(f["x-beta"]), | ||
returns: E(_) ? null : _, | ||
params: K.filter((s) => !E(s)), | ||
data: E(B) ? null : B | ||
}, f)); | ||
} | ||
} | ||
return n; | ||
const u = ["post", "get", "put", "patch", "delete"]; | ||
return r.sort((l, y) => { | ||
const h = u.indexOf(l.method) - u.indexOf(y.method); | ||
if (h !== 0) | ||
return h; | ||
if (l.method === "get") { | ||
if (l.type === "list" && y.type !== "list") | ||
return -1; | ||
if (y.type === "list" && l.type !== "list") | ||
return 1; | ||
} | ||
return l.name.localeCompare(y.name); | ||
}), r; | ||
} | ||
function W(e, t, r) { | ||
var f; | ||
var u; | ||
if (!t) | ||
return null; | ||
const n = "$ref" in t ? x(e, t.$ref) : t, o = ((f = n.properties) == null ? void 0 : f[r.entity]) || n, u = "$ref" in o ? x(e, o.$ref) : o, a = G(u); | ||
const n = "$ref" in t ? x(e, t.$ref) : t, o = ((u = n.properties) == null ? void 0 : u[r.entity]) || n, c = "$ref" in o ? x(e, o.$ref) : o, a = G(c); | ||
if (!r.excludeReadOnly || !a.properties) | ||
return a; | ||
const p = g(l({}, a), { properties: {} }); | ||
for (const [h, y] of Object.entries(a.properties || {})) | ||
(y == null ? void 0 : y.readOnly) !== !0 && (p.properties[h] = a.properties[h]); | ||
const p = b(d({}, a), { properties: {} }); | ||
for (const [j, g] of Object.entries(a.properties || {})) | ||
(g == null ? void 0 : g.readOnly) !== !0 && (p.properties[j] = a.properties[j]); | ||
return p; | ||
} | ||
const U = { tabWidth: 2, quote: "single", wrapColumn: 120 }; | ||
function Ce(e) { | ||
return w.parse(e, { parser: F }); | ||
function Re(e) { | ||
return P.parse(e, { parser: F }); | ||
} | ||
function Re(e, t = !0) { | ||
return N(t ? w.prettyPrint(e, U).code : w.print(e, U).code); | ||
function Be(e, t = !0) { | ||
return M(t ? P.prettyPrint(e, U).code : P.print(e, U).code); | ||
} | ||
const Ze = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ | ||
const ve = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ | ||
__proto__: null, | ||
parse: Ce, | ||
print: Re | ||
parse: Re, | ||
print: Be | ||
}, Symbol.toStringTag, { value: "Module" })); | ||
async function ve(e) { | ||
const t = await Te(e); | ||
return Ae(t).map((n) => ({ | ||
async function He(e) { | ||
const t = await Ae(e); | ||
return Ce(t).map((n) => ({ | ||
path: n, | ||
@@ -371,8 +393,8 @@ methods: Ee(t, n), | ||
} | ||
function He(e, t) { | ||
return e.map((r) => g(l({}, r), { | ||
function Ke(e, t) { | ||
return e.map((r) => b(d({}, r), { | ||
methods: r.methods.filter((n) => t(n)) | ||
})).filter((r) => r.methods.length); | ||
} | ||
function Ke(e, t) { | ||
function Ve(e, t) { | ||
return e.parameters.some( | ||
@@ -382,7 +404,7 @@ (r) => r.in === "header" && r.name.toLowerCase() === t.name.toLowerCase() && r.required === t.required | ||
} | ||
function Ve(e) { | ||
function Xe(e) { | ||
return e.flatMap((t) => t.methods).filter((t) => t.beta).sort((t, r) => t.operationId.localeCompare(r.operationId)); | ||
} | ||
function Be(e) { | ||
const t = g(l({ name: e.path }, e), { methods: e.methods.filter((n) => !n.group) }), r = e.methods.reduce((n, o) => (o.group && !n.includes(o.group) && n.push(o.group), n), []).map((n) => ({ | ||
function _e(e) { | ||
const t = b(d({ name: e.path }, e), { methods: e.methods.filter((n) => !n.group) }), r = e.methods.reduce((n, o) => (o.group && !n.includes(o.group) && n.push(o.group), n), []).map((n) => ({ | ||
name: `${e.path}_${n}`, | ||
@@ -394,11 +416,11 @@ path: `${e.path}/${n}`, | ||
} | ||
async function Xe(e, t, r, n) { | ||
async function Ye(e, t, r, n) { | ||
const o = []; | ||
for (const u of e) { | ||
const [a, ...p] = Be(u); | ||
for (const f of [a, ...p]) | ||
for (const c of e) { | ||
const [a, ...p] = _e(c); | ||
for (const u of [a, ...p]) | ||
o.push({ | ||
name: z.join(t, fe(f.path) + ".ts"), | ||
source: await r(f, f === a ? p : []), | ||
docs: await n(f) | ||
name: z.join(t, le(u.path) + ".ts"), | ||
source: await r(u, u === a ? p : []), | ||
docs: await n(u) | ||
}); | ||
@@ -409,30 +431,30 @@ } | ||
export { | ||
Ge as builders, | ||
Je as builders, | ||
J as camelCase, | ||
ze as capitalize, | ||
He as filterResourcesMethods, | ||
Be as flattenResourceMethods, | ||
N as formatCode, | ||
Fe as formatMarkdown, | ||
Xe as generateResourceFiles, | ||
Ve as getBetaMethods, | ||
Ge as capitalize, | ||
Ke as filterResourcesMethods, | ||
_e as flattenResourceMethods, | ||
M as formatCode, | ||
ze as formatMarkdown, | ||
Ye as generateResourceFiles, | ||
Xe as getBetaMethods, | ||
x as getByRef, | ||
Te as getOpenAPIDocument, | ||
I as getRequestBody, | ||
ve as getResources, | ||
M as getResponseBody, | ||
Ae as getOpenAPIDocument, | ||
q as getRequestBody, | ||
He as getResources, | ||
I as getResponseBody, | ||
Ee as getRootPathMethods, | ||
Ae as getRootPaths, | ||
Se as getSuccessStatusCode, | ||
Ke as hasHeader, | ||
fe as hyphenCase, | ||
C as isEmptySchema, | ||
Qe as isSchemaObject, | ||
Ce as getRootPaths, | ||
Pe as getSuccessStatusCode, | ||
Ve as hasHeader, | ||
le as hyphenCase, | ||
E as isEmptySchema, | ||
Ze as isSchemaObject, | ||
ce as pascalCase, | ||
Ze as recast, | ||
q as schemaToObject, | ||
le as snakeCase, | ||
Je as updateReadme, | ||
ve as recast, | ||
N as schemaToObject, | ||
fe as snakeCase, | ||
Qe as updateReadme, | ||
pe as wrapText | ||
}; | ||
//# sourceMappingURL=magicbell-codegen.esm.min.js.map |
{ | ||
"name": "@magicbell/codegen", | ||
"version": "0.2.1", | ||
"version": "0.2.2", | ||
"description": "MagicBell codegen", | ||
@@ -51,4 +51,4 @@ "author": "MagicBell <bot@magicbell.io> (https://magicbell.com)", | ||
"devDependencies": { | ||
"@types/json-schema-merge-allof": "^0.6.2" | ||
"@types/json-schema-merge-allof": "^0.6.4" | ||
} | ||
} |
@@ -10,2 +10,31 @@ import parser from '@apidevtools/swagger-parser'; | ||
function findBestMatch(str: string, keys: string[]) { | ||
let bestMatch = ''; | ||
let bestMatchScore = 0; | ||
for (const key of keys) { | ||
let score = 0; | ||
let i = 0; | ||
let j = 0; | ||
// Compare characters of str and key | ||
while (i < str.length && j < key.length) { | ||
if (str[i] === key[j]) { | ||
score++; | ||
j++; | ||
} | ||
i++; | ||
} | ||
// Update best match if this key has a higher score | ||
if (score > bestMatchScore) { | ||
bestMatchScore = score; | ||
bestMatch = key; | ||
} | ||
} | ||
return bestMatch; | ||
} | ||
export async function getOpenAPIDocument(file: string, options = { dereference: true }) { | ||
@@ -42,4 +71,2 @@ const parse = options.dereference ? parser.dereference.bind(parser) : parser.parse.bind(parser); | ||
export function getRootPathMethods(document: OpenAPI.Document, path: string) { | ||
const paginationProps = Object.keys((document as any).components.schemas.PaginationProps?.properties || {}); | ||
const methods: Array<Method> = []; | ||
@@ -53,4 +80,6 @@ const apiPaths = Object.keys(document.paths).filter((x) => x.startsWith(`/${path}`)); | ||
const schema = mergeAllOf(body.schema as any); | ||
let entity = Object.keys(schema.properties).find((x) => !paginationProps.includes(x)); | ||
const schemaProperties = Object.keys(schema.properties); | ||
let entity = findBestMatch(path, schemaProperties); | ||
// this ain't nice, see comment above | ||
@@ -146,2 +175,21 @@ if (entity !== 'notification_preferences') { | ||
// sort method.name [get, post, put, patch, delete] and then by operationId. | ||
// when method is get, type=list is before type=null | ||
const methodOrder = ['post', 'get', 'put', 'patch', 'delete']; | ||
methods.sort((a, b) => { | ||
// First, sort by HTTP method | ||
const methodDiff = methodOrder.indexOf(a.method) - methodOrder.indexOf(b.method); | ||
if (methodDiff !== 0) return methodDiff; | ||
// Within the same method, prioritize 'list' type | ||
if (a.method === 'get') { | ||
if (a.type === 'list' && b.type !== 'list') return -1; | ||
if (b.type === 'list' && a.type !== 'list') return 1; | ||
} | ||
// Finally, sort by name if all else is equal | ||
return a.name.localeCompare(b.name); | ||
}); | ||
return methods; | ||
@@ -148,0 +196,0 @@ } |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
246849
2212