@moccona/apicodegen 0.0.4 → 0.0.8
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/bin/cli.cjs +2 -2
- package/package.json +1 -1
package/bin/cli.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
#!/bin/env node
|
|
2
|
-
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("node:path");c=s(c,1);let l=require("commander"),u=require("fs-extra");u=s(u,1);let d=require("@moccona/logger"),f=require("undici"),p=require("typescript"),m=require("node:fs/promises"),h=require("prettier");var g={name:`@moccona/apicodegen`,version:`0.0.
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("node:path");c=s(c,1);let l=require("commander"),u=require("fs-extra");u=s(u,1);let d=require("@moccona/logger"),f=require("undici"),p=require("typescript"),m=require("node:fs/promises"),h=require("prettier");var g={name:`@moccona/apicodegen`,version:`0.0.8`,description:``,type:`module`,engines:{node:`>=24`},bin:{apicodegen:`./bin/cli.cjs`},scripts:{dev:`tsdown --watch`,build:`tsdown`,test:`vitest --watch false`,prepublishOnly:`npm run build`,lint:`pnpm exec biome check src`,"lint:fix":`pnpm exec biome check --write src`,format:`pnpm exec biome format --write src`,debug:`node --inspect-brk=9229 bin/cli.cjs`,prepare:`husky`,typecheck:`tsc --noEmit`,version:`changeset version`,publish:`changeset publish`},exports:{"./package.json":`./package.json`,"./vite":{types:`./npm/vite/index.d.mts`,import:`./npm/vite/index.mjs`},"./*":{types:`./npm/*/index.d.mts`,import:`./npm/*/index.mjs`,require:`./npm/*/index.cjs`},".":{types:`./npm/index.d.mts`,import:`./npm/index.mjs`,require:`./npm/index.cjs`}},keywords:[`api-codegen`],repository:{type:`git`,url:`https://github.com/freemode1614/api-codegen`},author:`freemode`,license:`MIT`,publishConfig:{access:`public`},dependencies:{"@moccona/logger":`^0.0.2`,commander:`^13.1.0`,execa:`^9.5.2`,"fs-extra":`^11.3.0`,"openapi-types":`^12.1.3`,prettier:`^3.6.2`,undici:`^7.8.0`},devDependencies:{"@arethetypeswrong/core":`^0.18.2`,"@biomejs/biome":`^2.4.16`,"@changesets/cli":`^2.31.0`,"@types/fs-extra":`^11.0.4`,"@types/node":`^22.14.1`,axios:`^1.11.0`,"fast-glob":`^3.3.3`,husky:`^9.1.7`,"lint-staged":`^17.0.5`,prettier:`^3.6.2`,serve:`^14.2.4`,"serve-handler":`^6.1.7`,tsdown:`^0.22.1`,typescript:`^5.9.2`,vite:`^7.1.5`,"vite-tsconfig-paths":`^6.1.1`,vitest:`^3.2.4`},peerDependencies:{prettier:`^3`,typescript:`^5`,vite:`^7`},peerDependenciesMeta:{vite:{optional:!0}},"lint-staged":{"src/**/*":[`biome check --write`,`biome format --write`]},packageManager:`pnpm@10.9.0`};const _={APICODEGEN_SPEC:`spec`,APICODEGEN_OUTPUT:`output`,APICODEGEN_BASE_URL:`baseURL`,APICODEGEN_ADAPTOR:`adaptor`,APICODEGEN_VERBOSE:`verbose`,APICODEGEN_WATCH:`watch`,APICODEGEN_TYPE_CHECK:`typeCheck`};function v(){let e={};for(let[t,n]of Object.entries(_)){let r=process.env[t];if(r!==void 0)switch(n){case`verbose`:case`watch`:case`typeCheck`:e[n]=r===`true`||r===`1`;break;case`adaptor`:e[n]=r;break;default:e[n]=r}}return e}async function y(e){let t=c.default.extname(e).toLowerCase();try{if(t===`.json`||t===`.jsonc`){let t=await u.default.readFile(e,`utf-8`);return JSON.parse(t)}if(t===`.js`||t===`.cjs`||t===`.mjs`){let t=await import(e);return t.default||t}if(t===`.ts`){let t=await u.default.readFile(e,`utf-8`);try{return JSON.parse(t)}catch{let e=t.match(/export\s+default\s+(\{.+\})/s);if(e)return JSON.parse(e[1])}}let n=await u.default.readFile(e,`utf-8`);return JSON.parse(n)}catch(t){throw Error(`Failed to load config from ${e}: ${t}`)}}async function b(e){for(let t of[`apicodegen.config.json`,`apicodegen.config.js`,`apicodegen.config.mjs`,`.apicodegenrc`,`.apicodegenrc.json`,`.apicodegenrc.js`,`.apicodegenrc.mjs`]){let n=c.default.join(e,t);if(await u.default.pathExists(n))return n}let t=c.default.join(e,`package.json`);if(await u.default.pathExists(t))try{let n=JSON.parse(await u.default.readFile(t,`utf-8`));if(n.apicodegen&&typeof n.apicodegen==`string`)return c.default.resolve(e,n.apicodegen)}catch{}return null}function x(e,...t){let n={...e};for(let e of t)if(e)for(let[t,r]of Object.entries(e))r!==void 0&&(n[t]=r);return n}function ee(e){if(!e.spec)throw Error(`Missing required field: spec (OpenAPI spec file path or URL)`);return!0}async function S(e={}){let t=e.cwd||process.cwd(),n=e.cliOptions||{},r=v(),i={},a;if(e.configFile)a=c.default.resolve(t,e.configFile),i=await y(a);else{let e=await b(t);e&&(a=e,i=await y(e))}let o=c.default.join(t,`package.json`),s={};if(await u.default.pathExists(o))try{let e=JSON.parse(await u.default.readFile(o,`utf-8`));e.apicodegen&&typeof e.apicodegen==`object`&&(s=e.apicodegen)}catch{}let l=x({spec:``,output:`./output.ts`},r,s,i,n);ee(l);let d=e.name||l.baseURL||l.spec;return{...l,configFilePath:a,name:d}}function C(e){return{docURL:e.spec,output:e.output,adaptor:e.adaptor,baseURL:e.baseURL,importClientSource:e.importClientSource,verbose:e.verbose,requestOptions:e.requestOptions}}const w={SPEC_NOT_FOUND:`E_SPEC_NOT_FOUND`,SPEC_FETCH_FAILED:`E_SPEC_FETCH_FAILED`,SPEC_PARSE_FAILED:`E_SPEC_PARSE_FAILED`,OUTPUT_DIR_MISSING:`E_OUTPUT_DIR_MISSING`,CONFIG_INVALID:`E_CONFIG_INVALID`,VALIDATION_FAILED:`E_VALIDATION_FAILED`,GENERATION_FAILED:`E_GENERATION_FAILED`,TYPE_CHECK_FAILED:`E_TYPE_CHECK_FAILED`};var T=class e extends Error{code;location;line;column;path;suggestions;cause;constructor(t){super(t.message),this.name=`ApicodegenError`,this.code=t.code,this.location=t.location,this.line=t.line,this.column=t.column,this.path=t.path,this.suggestions=t.suggestions||[],this.cause=t.cause,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(e=!1){let t=[];if(t.push(`\x1b[1;31mError [${this.code}]\x1b[0m ${this.message}`),this.location&&t.push(` \x1b[36m→ Location:\x1b[0m ${this.location}`),this.path&&t.push(` \x1b[36m→ Path:\x1b[0m ${this.path}`),this.line!==void 0){let e=` \x1b[36m→ Line:\x1b[0m ${this.line}`;this.column!==void 0&&(e+=`, Column: ${this.column}`),t.push(e)}if(this.suggestions.length>0)for(let e of this.suggestions)t.push(` \x1b[32m→ Suggestion:\x1b[0m ${e}`);if(e&&this.cause&&(t.push(`\n \x1b[90mOriginal Error:\x1b[0m ${this.cause.message}`),this.stack)){let e=this.stack.split(`
|
|
3
3
|
`).slice(1).join(`
|
|
4
4
|
`);t.push(`\x1b[90m${e}\x1b[0m`)}return t.join(`
|
|
5
5
|
`)}toJSON(){return{name:this.name,code:this.code,message:this.message,location:this.location,line:this.line,column:this.column,path:this.path,suggestions:this.suggestions,cause:this.cause?.message}}};const E={specNotFound(e,t){return new T({code:w.SPEC_NOT_FOUND,message:`OpenAPI spec file not found`,location:e,suggestions:[`Check if the file exists using 'ls -la'`,`Use --spec to provide the correct path`,`For remote specs, ensure the URL is accessible`],cause:t})},specFetchFailed(e,t,n){let r=t?`Failed to fetch OpenAPI spec (HTTP ${t})`:`Failed to fetch OpenAPI spec from URL`;return new T({code:w.SPEC_FETCH_FAILED,message:r,location:e,suggestions:[`Check if the URL is accessible in a browser`,`Download the spec file locally and use the local path`,`Verify CORS settings if fetching from a different origin`],cause:n})},specParseFailed(e,t,n,r){return new T({code:w.SPEC_PARSE_FAILED,message:`Failed to parse OpenAPI spec (invalid JSON or YAML)`,location:e,line:t,column:n,suggestions:[`Validate JSON syntax using jsonlint.com`,`For YAML specs, ensure proper indentation`,`Check for trailing commas or unquoted special characters`],cause:r})},outputDirMissing(e,t){return new T({code:w.OUTPUT_DIR_MISSING,message:`Output directory does not exist`,location:e,suggestions:[`Create the directory: mkdir -p $(dirname <output>)`,`Check if the path is correct`],cause:t})},configInvalid(e,t){return new T({code:w.CONFIG_INVALID,message:`Invalid configuration file`,location:e,suggestions:[`Validate JSON syntax in the config file`,`Check for required fields (spec, output)`],cause:t})},validationFailed(e,t,n){return new T({code:w.VALIDATION_FAILED,message:`OpenAPI spec validation failed`,location:e,path:t,suggestions:[`Check OpenAPI spec structure at the specified path`,`Ensure all required fields are present`,`Validate using swagger.io editor`],cause:n})},generationFailed(e){return new T({code:w.GENERATION_FAILED,message:`Code generation failed`,suggestions:[`Check for unsupported OpenAPI features`,`Ensure spec follows OpenAPI 2.0, 3.0, or 3.1 specification`,`Use --verbose for more details`],cause:e})},typeCheckFailed(e,t,n){return new T({code:w.TYPE_CHECK_FAILED,message:`TypeScript type check failed`,location:e,suggestions:[`Review type errors above`,`Check for schema inconsistencies`,`Update generated types or fix source schema`],cause:n})},missingRequiredField(e,t){return new T({code:w.VALIDATION_FAILED,message:`Missing required field: ${e}`,path:t,suggestions:[`Add the '${e}' field to your configuration`]})}};function te(e,t){return e instanceof T?e:e instanceof Error?new T({code:t?.code||w.GENERATION_FAILED,message:t?.message||e.message,location:t?.location,suggestions:t?.suggestions,cause:e}):new T({code:t?.code||w.GENERATION_FAILED,message:String(e),suggestions:t?.suggestions})}function D(e){return e instanceof T}var O=class{};const k=new Set(`break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.export.extends.false.finally.for.function.if.import.in.instanceof.new.null.return.super.switch.this.throw.true.try.typeof.var.void.while.with.as.implements.interface.let.package.private.protected.public.static.yield.abstract.any.async.await.constructor.declare.from.get.is.module.namespace.never.require.set.type.unknown.readonly.of.asserts.infer.keyof.boolean.number.string.symbol.object.undefined.bigint`.split(`.`));let A=function(e){return e.JSON=`application/json`,e.TEXT=`text`,e.IMAGE=`image`,e.AUDIO=`audio`,e.VIDEO=`video`,e}({}),j=function(e){return e.GET=`get`,e.PUT=`put`,e.POST=`post`,e.DELETE=`delete`,e.OPTIONS=`options`,e.HEAD=`head`,e.PATCH=`patch`,e.TRACE=`trace`,e}({});var M=class e{constructor(){if(new.target===e)throw Error(`Cannot instantiate abstract class`)}static ref2name(t,n){let r=t.replace(/^#/,``).split(`/`).filter(Boolean);if(!n)return r.slice(-1)[0];let i=n,a=``;for(let e of r){let t=e.replaceAll(`~1`,`/`);i=i[t],a=t}return i?i.$ref?e.ref2name(i.$ref,n):a:`unknown`}static pathToFnName(t,n,r=``){return e.normalize(e.camelCase(e.normalize(t)))+(n?e.capitalize(e.upperCamelCase(`using_${n}`)):``)}static normalize(e){return k.has(e)&&(e+=`_`),e.replace(/[/\-_{}():\s`,*<>$#.]/gm,`_`).replace(/^\d./gm,``).replaceAll(`...`,``)}static capitalize(e){return e=e.trim(),`${e.charAt(0).toUpperCase()}${e.slice(1)}`}static camelCase(t){return t=t.trim(),t.split(`_`).filter(Boolean).map((t,n)=>n===0?t:e.capitalize(t)).join(``)}static upperCamelCase(t){return e.normalize(t).replaceAll(`...`,``).split(`_`).filter(Boolean).map(e.capitalize).join(``)}static async fetchDoc(e,t={}){let{body:n,statusCode:r}=await(0,f.request)(e,{method:`GET`,dispatcher:new f.Agent({connect:{rejectUnauthorized:!1}}),...t});if(r>=400)throw Error(`Failed to fetch OpenAPI documentation from ${e}: HTTP ${r}`);try{return n.json()}catch(t){throw Error(`Failed to parse JSON response from ${e}: ${t instanceof Error?t.message:String(t)}`)}}static getMediaType(e){return Object.values(A).find(t=>e.includes(t))}static isValidEnumType(t){return t.type!==`boolean`&&!e.isBooleanEnum(t)}static isBooleanEnum(e){return e.type===`boolean`||!!e.enum?.some(e=>typeof e==`boolean`)}static isSameEnum(e,t){return e.enum.length===t.enum.length&&e.enum.sort().every((e,n)=>e===t.enum.sort()[n])}static uniqueEnums(e){let t=new Map;for(let n of e){let e=t.get(n.name);if(e)for(let t of n.enum)e.add(t);else t.set(n.name,new Set(n.enum))}return Array.from(t.entries()).map(([e,t])=>({name:e,enum:Array.from(t)}))}static findSameSchema(t,n){return n.find(n=>e.isSameEnum(n,t))}static isRef(e){return typeof e==`object`&&!!e&&`$ref`in e&&typeof e.$ref==`string`}},ne=class{enums=[];schemas={};parameters={};responses={};requestBodies={};apis={};docURL;baseURL;output;requestOptions;importClientSource;constructor(e,t){this.docURL=e.docURL,this.baseURL=e.baseURL??``,this.output=e.output??`.`,this.requestOptions=e.requestOptions??{},this.importClientSource=e.importClientSource??``;let{enums:n,schemas:r,requestBodies:i,responses:a,parameters:o,apis:s}=this.parse(t);this.enums=n,this.schemas=r,this.responses=a,this.parameters=o,this.requestBodies=i,this.apis=s}},N=class e{static toCode(e){if(e.length===0)return`// No api declaration found.`;let t=p.factory.createSourceFile(e,p.factory.createToken(p.SyntaxKind.EndOfFileToken),p.NodeFlags.None);return(0,p.createPrinter)().printFile(t)}static async write(e,t){try{await(0,m.writeFile)(t,e)}catch(e){console.error(e)}}static toUrlTemplate(e,t,n=``){let r=t.filter(e=>e.in===`query`);if(r.length>0){let t=r.map((e,t)=>`${t===0?`?`:`&`}${encodeURIComponent(e.name)}={${M.camelCase(M.normalize(e.name))}}`).join(``);e+=t}let i=e.replaceAll(`{`,"${").split(`$`).filter(Boolean);return i.length===1?p.factory.createNoSubstitutionTemplateLiteral(n+e):p.factory.createTemplateExpression(p.factory.createTemplateHead(n+i[0]),i.slice(1).map((e,t)=>{let n=/^{(.+)}(.+)?/gm.exec(e),r=t===i.length-2;if(!n)throw Error(`Invalid path segment: ${e}`);return p.factory.createTemplateSpan(p.factory.createIdentifier(n[1]),r?p.factory.createTemplateTail(n[2]||``):p.factory.createTemplateMiddle(n[2]))}))}static addComments(e,t){if(!Array.isArray(t)||t.filter(Boolean).length===0)return;let n=`*
|