Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@arpc-packages/schema-gen

Package Overview
Dependencies
Maintainers
0
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@arpc-packages/schema-gen - npm Package Compare versions

Comparing version 0.2.6 to 0.3.0

src/getValibotSignature.ts

4

dist/index.js

@@ -1,3 +0,3 @@

"use strict";var X=Object.create;var P=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var N=Object.getOwnPropertyNames;var q=Object.getPrototypeOf,tt=Object.prototype.hasOwnProperty;var et=(t,e)=>{for(var i in e)P(t,i,{get:e[i],enumerable:!0})},I=(t,e,i,l)=>{if(e&&typeof e=="object"||typeof e=="function")for(let u of N(e))!tt.call(t,u)&&u!==i&&P(t,u,{get:()=>e[u],enumerable:!(l=W(e,u))||l.enumerable});return t};var B=(t,e,i)=>(i=t!=null?X(q(t)):{},I(e||!t||!t.__esModule?P(i,"default",{value:t,enumerable:!0}):i,t)),nt=t=>I(P({},"__esModule",{value:!0}),t);var st={};et(st,{generateSchema:()=>G});module.exports=nt(st);var j=require("fs/promises"),x=require("path"),K=require("@arpc-packages/lockfile"),r=require("typescript"),Y=B(require("zod"));var J=[{name:"BadRequest",description:"Thrown when a request is invalid."},{name:"Ratelimited",description:"Thrown when a user is ratelimited."},{name:"Unauthorized",description:"Thrown when a user is not authorized."},{name:"InternalServerError",description:"Thrown when the server encounters an internal error."}];var o=B(require("zod"));function R(t,e,i,l,u){if(t instanceof o.ZodString)return{type:"string"};if(t instanceof o.ZodNumber)return{type:"number"};if(t instanceof o.ZodBigInt)return{type:"bigint"};if(t instanceof o.ZodBoolean)return{type:"boolean"};if(t instanceof o.ZodNullable||t instanceof o.ZodOptional)return{type:"nullable",inner:R(t._def.innerType,e,i,l,u)};if(t instanceof o.ZodArray)return{type:"array",inner:R(t._def.type,e,i,l,u)};if(t instanceof o.ZodUnion){let m=function(w){for(let p of w.options)p instanceof o.ZodUnion?m(p):d.push(p)};var O=m;let d=[];return m(t),{type:"union",inner:d.map((w,p)=>R(w,e,i,l,()=>`${u()}Variant${p}`))}}if(t instanceof o.ZodRecord||t instanceof o.ZodMap)return{type:"map",key:R(t._def.keyType,e,i,l,u),value:R(t._def.valueType,e,i,l,u)};if(t instanceof o.ZodObject){let d={};for(let[h,b]of Object.entries(t.shape))d[h]=R(b,e,i,l,()=>`${u()}${h[0].toUpperCase()}${h.slice(1)}`);let m=u(),w=1,p=m;for(;l.has(p);){let h=i.find(b=>b.name===p);if(h&&JSON.stringify(h.fields)===JSON.stringify(d))return{type:"object",key:p};w++,p=`${m}V${w}`}return l.add(p),i.push({name:p,fields:d}),{type:"object",key:p}}if(t instanceof o.ZodEnum){let d=t.Enum,m=Object.keys(d),w=new Map;for(let Z of m)w.set(Z.replaceAll(" ","").replace(/[^a-zA-Z0-9_]/g,"_"),d[Z]);let p={type:"string"};if(m.length!==0){let Z=["string","number","bigint","boolean"],F=typeof d[m[0]];if(!Z.includes(F))throw new Error("Enums can only have string, number, bigint, or boolean values");p={type:F}}let h=u(),b=1,S=h;for(;l.has(S);){let Z=e.find(F=>F.name===S);if(Z&&JSON.stringify(Z.data)===JSON.stringify(w))return{type:"enum_value",enum:S};b++,S=`${h}V${b}`}return l.add(S),e.push({name:S,valueType:p,data:w}),{type:"enum_value",enum:S}}if(t instanceof o.ZodNull||t instanceof o.ZodUndefined)return{type:"literal",value:null};if(t instanceof o.ZodLiteral)return{type:"literal",value:t.value};throw new Error(`arpc doesn't support the type ${t.constructor.name} yet`)}var it=/^(["'`])(.*)\1$/;function _(t){let e=it.exec(t);return e?e[2]:t}function U(t,e){for(let i of Object.values(t)){if(typeof i!="string"){U(i,e);continue}e.has(i)||e.add(i)}}var ot=/^TokenTypes\.([A-Za-z0-9_]+)$/;function rt(t){if(t==="undefined")return;let e=ot.exec(t||"");if(!e)throw new Error(`Invalid token type: ${t}`);return e[1]}async function G(t){let e=(0,x.join)(process.cwd(),"rpc"),i=(0,K.parse)(await(0,j.readFile)((0,x.join)(e,"index.ts"),"utf-8")),l=[(0,x.join)(e,"index.ts")];i.hasAuthentication&&l.push((0,x.join)(e,"authentication.ts")),i.hasRatelimiting&&l.push((0,x.join)(e,"ratelimiting.ts"));let u=new Set;U(i.routes,u),U(i.exceptions,u);for(let a of u)l.push((0,x.join)(e,a));let O=(0,r.createProgram)(l,{allowJs:!0,alwaysStrict:!1});O.getTypeChecker();let d=null;if(i.hasAuthentication){let a=O.getSourceFile((0,x.join)(e,"authentication.ts"));if(!a)throw new Error("Failed to parse rpc/authentication.ts");let s=null,z=null;if(d=a.forEachChild(f=>{if((0,r.isEnumDeclaration)(f)&&f.name.text==="TokenTypes"){s={};for(let c of f.members){let T=_(c.name.getText());if(!c.initializer||!(0,r.isStringLiteral)(c.initializer))throw new Error(`TokenTypes.${T} must be a string literal`);s[T]=_(c.initializer.getText())}return z!==null?{tokenTypes:s,defaultTokenType:z}:void 0}if((0,r.isVariableStatement)(f)){let c=f.declarationList.declarations;if(c.length===1){let T=c[0];if(T.name.getText()==="defaultTokenType"&&(z=rt(T.initializer?.getText()),s))return{tokenTypes:s,defaultTokenType:z}}}})||null,s)d||(d={tokenTypes:s});else throw new Error("Failed to find TokenTypes enum in rpc/authentication.ts")}let m=[],w=Object.keys(i.exceptions).sort();for(let a of w){let s=(0,x.join)(e,i.exceptions[a]+".ts"),z=O.getSourceFile(s);if(!z)throw new Error(`Failed to parse ${s}`);let f=z.forEachChild(y=>{if((0,r.isClassDeclaration)(y)&&y.name?.text===a)return y});if(!f)throw new Error(`Failed to find class ${a} in ${s}`);let c=null,T=f.getFullStart(),k=f.getStart();if(T!==k){let y=z.getFullText(),g=(0,r.getLeadingCommentRanges)(y,k);g&&(c=y.substring(g[0].pos,g[0].end).trim())}m.push({name:a,description:c||`A ${a} custom exception`})}let p=t._routes,h=[],b=[],S=new Set;function Z(a,s,z){let f=(p||{})[z],c=null,T=null,k,y=0;for(;f;){let n=f[s[y]];if(n.input&&n.input instanceof Y.ZodType){c=n.input,T=n.output,k=n.mutation;break}f=n,y++}if(!c||!T)throw new Error("Lockfile and router routes are out of sync");let g=new Map;a.forEachChild(n=>{(0,r.isTypeAliasDeclaration)(n)&&g.set(n.name.text,n.type.getText())});for(let[n,E]of g){for(;g.has(E);)E=g.get(E);g.set(n,E)}let $=a.forEachChild(n=>{if((0,r.isVariableStatement)(n)){let E=n.declarationList.declarations;if(E.length!==1)return;let M=E[0];if(M.name.getText()==="method"){if(M.initializer&&((0,r.isArrowFunction)(M.initializer)||(0,r.isFunctionExpression)(M.initializer)))return M.initializer;throw new Error("method must be an arrow function or function expression")}}if(((0,r.isMethodDeclaration)(n)||(0,r.isFunctionDeclaration)(n))&&n.name?.getText()==="method")return n});if(!$)throw new Error("Failed to find method");let v=$.parameters[0];if(!v)throw new Error("Method must have at least one argument");let C=null;if(v.type){let n=v.type.getText();if(n!=="z.infer<typeof input>"){if(g.get(n)!=="z.infer<typeof input>")throw new Error(`Method argument must be of type or alias a type that is equal to z.infer<typeof input> in the same file, got ${n}`);C=n}}let A={name:v.name.getText(),signature:R(c,h,b,S,()=>C||s.map(n=>n[0].toUpperCase()+n.slice(1)).join("")+"Opts")},H=R(T,h,b,S,()=>s.map(n=>n[0].toUpperCase()+n.slice(1)).join("")+"Response"),V=null,Q=$.getFullStart(),D=$.getStart();if(Q!==D){let n=a.getFullText(),E=(0,r.getLeadingCommentRanges)(n,D);E&&(V=n.substring(E[0].pos,E[0].end).trim())}return k===void 0&&(k=!0),{input:A,output:H,description:V,mutation:k}}let F=Object.keys(i.routes).sort(),L=[];for(let a of F){let c=function(T,k,y){for(let[g,$]of Object.entries(T)){if(typeof $!="string"){let A={};k[g]=A,y.push(g),c($,A,y),y.pop();continue}let v=(0,x.join)(e,$+".ts"),C=O.getSourceFile(v);if(!C)throw new Error(`Failed to parse ${v}`);y.push(g),k[g]=Z(C,y,a),y.pop()}};var at=c;let s=null;try{s=await(0,j.readFile)((0,x.join)(e,"descriptions",`${a}.md`),"utf-8")}catch{}s===`You can write markdown here to describe your API version.
`&&(s=null);let z=i.routes[a],f={};L.push({apiVersion:a,methods:f,description:s,defaultProtocol:"",defaultHostname:"",authentication:d}),c(z,f,[])}return{enums:h,objects:b,builtinExceptions:J,customExceptions:m,clients:L}}0&&(module.exports={generateSchema});
"use strict";var A=Object.defineProperty;var Z=Object.getOwnPropertyDescriptor;var G=Object.getOwnPropertyNames;var H=Object.prototype.hasOwnProperty;var Q=(t,e)=>{for(var i in e)A(t,i,{get:e[i],enumerable:!0})},X=(t,e,i,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let l of G(e))!H.call(t,l)&&l!==i&&A(t,l,{get:()=>e[l],enumerable:!(s=Z(e,l))||s.enumerable});return t};var W=t=>X(A({},"__esModule",{value:!0}),t);var nt={};Q(nt,{generateSchema:()=>J});module.exports=W(nt);var j=require("fs/promises"),E=require("path"),D=require("@arpc-packages/lockfile"),r=require("typescript");var U=[{name:"BadRequest",description:"Thrown when a request is invalid."},{name:"Ratelimited",description:"Thrown when a user is ratelimited."},{name:"Unauthorized",description:"Thrown when a user is not authorized."},{name:"InternalServerError",description:"Thrown when the server encounters an internal error."}];var N=["string","number","bigint","boolean"];function O(t,e,i,s,l){if(N.indexOf(t.type)!==-1)return{type:t.type};if(t.type==="nullable"||t.type==="optional")return{type:"nullable",inner:O(t.wrapped,e,i,s,l)};if(t.type==="array")return{type:"array",inner:O(t.item,e,i,s,l)};if(t.type==="union"){let h=function(S){for(let u of S.options)u.type==="union"?h(u):y.push(u)};var M=h;let y=[];return h(t),{type:"union",inner:y.map((S,u)=>O(S,e,i,s,()=>`${l()}Variant${u}`))}}if(t.type==="map")return{type:"map",key:O(t.key,e,i,s,l),value:O(t.value,e,i,s,l)};if(t.type==="object"){let y={};for(let[d,b]of Object.entries(t.entries))y[d]=O(b,e,i,s,()=>`${l()}${d[0].toUpperCase()}${d.slice(1)}`);let h=l(),S=1,u=h;for(;s.has(u);){let d=i.find(b=>b.name===u);if(d&&JSON.stringify(d.fields)===JSON.stringify(y))return{type:"object",key:u};S++,u=`${h}V${S}`}return s.add(u),i.push({name:u,fields:y}),{type:"object",key:u}}if(t.type==="enum"){let y=t.enum,h=Object.keys(y),S=new Map;for(let R of h)S.set(R.replaceAll(" ","").replace(/[^a-zA-Z0-9_]/g,"_"),y[R]);let u={type:"string"};if(h.length!==0){let R=["string","number","bigint","boolean"],F=typeof y[h[0]];if(!R.includes(F))throw new Error("Enums can only have string, number, bigint, or boolean values");u={type:F}}let d=l(),b=1,x=d;for(;s.has(x);){let R=e.find(F=>F.name===x);if(R&&JSON.stringify(R.data)===JSON.stringify(S))return{type:"enum_value",enum:x};b++,x=`${d}V${b}`}return s.add(x),e.push({name:x,valueType:u,data:S}),{type:"enum_value",enum:x}}if(t.type==="literal")return{type:"literal",value:t.literal};throw new Error(`arpc doesn't support the type ${t.constructor.name} yet`)}var q=/^(["'`])(.*)\1$/;function C(t){let e=q.exec(t);return e?e[2]:t}function L(t,e){for(let i of Object.values(t)){if(typeof i!="string"){L(i,e);continue}e.has(i)||e.add(i)}}var tt=/^TokenTypes\.([A-Za-z0-9_]+)$/;function et(t){if(t==="undefined")return;let e=tt.exec(t||"");if(!e)throw new Error(`Invalid token type: ${t}`);return e[1]}async function J(t){let e=(0,E.join)(process.cwd(),"rpc"),i=(0,D.parse)(await(0,j.readFile)((0,E.join)(e,"index.ts"),"utf-8")),s=[(0,E.join)(e,"index.ts")];i.hasAuthentication&&s.push((0,E.join)(e,"authentication.ts")),i.hasRatelimiting&&s.push((0,E.join)(e,"ratelimiting.ts"));let l=new Set;L(i.routes,l),L(i.exceptions,l);for(let a of l)s.push((0,E.join)(e,a));let M=(0,r.createProgram)(s,{allowJs:!0,alwaysStrict:!1});M.getTypeChecker();let y=null;if(i.hasAuthentication){let a=M.getSourceFile((0,E.join)(e,"authentication.ts"));if(!a)throw new Error("Failed to parse rpc/authentication.ts");let o=null,w=null;if(y=a.forEachChild(p=>{if((0,r.isEnumDeclaration)(p)&&p.name.text==="TokenTypes"){o={};for(let c of p.members){let g=C(c.name.getText());if(!c.initializer||!(0,r.isStringLiteral)(c.initializer))throw new Error(`TokenTypes.${g} must be a string literal`);o[g]=C(c.initializer.getText())}return w!==null?{tokenTypes:o,defaultTokenType:w}:void 0}if((0,r.isVariableStatement)(p)){let c=p.declarationList.declarations;if(c.length===1){let g=c[0];if(g.name.getText()==="defaultTokenType"&&(w=et(g.initializer?.getText()),o))return{tokenTypes:o,defaultTokenType:w}}}})||null,o)y||(y={tokenTypes:o});else throw new Error("Failed to find TokenTypes enum in rpc/authentication.ts")}let h=[],S=Object.keys(i.exceptions).sort();for(let a of S){let o=(0,E.join)(e,i.exceptions[a]+".ts"),w=M.getSourceFile(o);if(!w)throw new Error(`Failed to parse ${o}`);let p=w.forEachChild(f=>{if((0,r.isClassDeclaration)(f)&&f.name?.text===a)return f});if(!p)throw new Error(`Failed to find class ${a} in ${o}`);let c=null,g=p.getFullStart(),k=p.getStart();if(g!==k){let f=w.getFullText(),m=(0,r.getLeadingCommentRanges)(f,k);m&&(c=f.substring(m[0].pos,m[0].end).trim())}h.push({name:a,description:c||`A ${a} custom exception`})}let u=t._routes,d=[],b=[],x=new Set;function R(a,o,w){let p=(u||{})[w],c=null,g=null,k,f=0;for(;p;){let n=p[o[f]];if(typeof n.input?.["~standard"]=="number"){c=n.input,g=n.output,k=n.mutation;break}p=n,f++}if(!c||!g)throw new Error("Lockfile and router routes are out of sync");let m=new Map;a.forEachChild(n=>{(0,r.isTypeAliasDeclaration)(n)&&m.set(n.name.text,n.type.getText())});for(let[n,T]of m){for(;m.has(T);)T=m.get(T);m.set(n,T)}let $=a.forEachChild(n=>{if((0,r.isVariableStatement)(n)){let T=n.declarationList.declarations;if(T.length!==1)return;let z=T[0];if(z.name.getText()==="method"){if(z.initializer&&((0,r.isArrowFunction)(z.initializer)||(0,r.isFunctionExpression)(z.initializer)))return z.initializer;throw new Error("method must be an arrow function or function expression")}}if(((0,r.isMethodDeclaration)(n)||(0,r.isFunctionDeclaration)(n))&&n.name?.getText()==="method")return n});if(!$)throw new Error("Failed to find method");let v=$.parameters[0];if(!v)throw new Error("Method must have at least one argument");let P=null;if(v.type){let n=v.type.getText();if(n!=="z.infer<typeof input>"){if(m.get(n)!=="z.infer<typeof input>")throw new Error(`Method argument must be of type or alias a type that is equal to z.infer<typeof input> in the same file, got ${n}`);P=n}}let B={name:v.name.getText(),signature:O(c,d,b,x,()=>P||o.map(n=>n[0].toUpperCase()+n.slice(1)).join("")+"Opts")},Y=O(g,d,b,x,()=>o.map(n=>n[0].toUpperCase()+n.slice(1)).join("")+"Response"),V=null,K=$.getFullStart(),I=$.getStart();if(K!==I){let n=a.getFullText(),T=(0,r.getLeadingCommentRanges)(n,I);T&&(V=n.substring(T[0].pos,T[0].end).trim())}return k===void 0&&(k=!0),{input:B,output:Y,description:V,mutation:k}}let F=Object.keys(i.routes).sort(),_=[];for(let a of F){let c=function(g,k,f){for(let[m,$]of Object.entries(g)){if(typeof $!="string"){let B={};k[m]=B,f.push(m),c($,B,f),f.pop();continue}let v=(0,E.join)(e,$+".ts"),P=M.getSourceFile(v);if(!P)throw new Error(`Failed to parse ${v}`);f.push(m),k[m]=R(P,f,a),f.pop()}};var it=c;let o=null;try{o=await(0,j.readFile)((0,E.join)(e,"descriptions",`${a}.md`),"utf-8")}catch{}o===`You can write markdown here to describe your API version.
`&&(o=null);let w=i.routes[a],p={};_.push({apiVersion:a,methods:p,description:o,defaultProtocol:"",defaultHostname:"",authentication:y}),c(w,p,[])}return{enums:d,objects:b,builtinExceptions:U,customExceptions:h,clients:_}}0&&(module.exports={generateSchema});
//# sourceMappingURL=index.js.map
{
"name": "@arpc-packages/schema-gen",
"version": "0.2.6",
"version": "0.3.0",
"module": "dist/index.mjs",

@@ -20,3 +20,3 @@ "main": "dist/index.js",

"peerDependencies": {
"zod": "*"
"valibot": "*"
},

@@ -23,0 +23,0 @@ "devDependencies": {

@@ -14,5 +14,5 @@ import { readFile } from "fs/promises";

} from "typescript";
import * as z from "zod";
import type { BaseSchema } from "valibot";
import { builtinExceptions } from "./builtinExceptions";
import { getZodSignature } from "./getZodSignature";
import { getValibotSignature } from "./getValibotSignature";
import { dequotify } from "./helpers";

@@ -184,4 +184,4 @@

[key: string]: {
input: z.ZodType<any, any, any>;
output: z.ZodType<any, any, any>;
input: BaseSchema<any, any, any>;
output: BaseSchema<any, any, any>;
mutation?: boolean;

@@ -204,4 +204,4 @@ } | RoutesRoutesPartial;

let currentPathItem = (routerRoutes || {})[version];
let inputSchema: z.ZodType<any, any, any> | null = null;
let outputSchema: z.ZodType<any, any, any> | null = null;
let inputSchema: BaseSchema<any, any, any> | null = null;
let outputSchema: BaseSchema<any, any, any> | null = null;
let mutation: boolean | undefined = undefined;

@@ -213,6 +213,7 @@ let pathIndex = 0;

// If this contains a Zod schema, we are at the end of the path.
if (nextItem.input && nextItem.input instanceof z.ZodType) {
inputSchema = nextItem.input;
outputSchema = nextItem.output as z.ZodType<any, any, any>;
// If this contains a compliant schema, we are at the end of the path.
// @ts-expect-error: This is technically not valid TS, but the worst result will be undefined.
if (typeof nextItem.input?.["~standard"] === "number") {
inputSchema = nextItem.input as BaseSchema<any, any, any>;
outputSchema = nextItem.output as BaseSchema<any, any, any>;
mutation = nextItem.mutation as boolean;

@@ -306,6 +307,6 @@ break;

// Process the Zod schema to get the input type.
// Process the input schema to get the input type.
const input = {
name: arg.name.getText(),
signature: getZodSignature(
signature: getValibotSignature(
inputSchema, enums, objects, uniqueNames, () => inputTypeName || (path.map(

@@ -316,4 +317,4 @@ (x) => x[0].toUpperCase() + x.slice(1)).join("") + "Opts"),

// Process the Zod schema to get the output type.
const output = getZodSignature(
// Process the output schema to get the output type.
const output = getValibotSignature(
outputSchema, enums, objects, uniqueNames, () => path.map(

@@ -320,0 +321,0 @@ (x) => x[0].toUpperCase() + x.slice(1)).join("") + "Response",

@@ -10,4 +10,5 @@ {

"target": "ESNext",
"module": "ES2022"
"module": "ES2022",
"lib": ["ES2021"]
}
}

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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc