@getcronit/pylon-dev
Version:
CLI for creating a Pylon
154 lines (134 loc) • 25.5 kB
JavaScript
import*as ce from"@getcronit/pylon-telemetry";import{program as z}from"commander";import A from"consola";import we from"dotenv";import R from"pm2";var Y="2.0.0-canary-20250218210337.5fd3a977d589c14cc224729b00d712f57339cb3d";import he from"path";import{context as ye}from"esbuild";import de from"esbuild-plugin-tsc";import O from"path";import ne from"fs/promises";import $ from"path";import ue from"fs/promises";import Z from"fs/promises";async function v(c,r){try{if(await Z.readFile(c,"utf8")===r)return!1}catch(t){if(t.code!=="ENOENT")throw t}return await Z.writeFile(c,r,"utf8"),!0}var X=({getBuildDefs:c,outputDir:r})=>({name:"inject-code",setup(t){t.onLoad({filter:/src[\/\\]index\.ts$/,namespace:"file"},async e=>{if($.relative(process.cwd(),e.path)!==$.join("src","index.ts"))return;let{typeDefs:n,resolvers:o}=c(),i=ee(o),a=await ue.readFile(e.path,"utf-8"),l=$.join(process.cwd(),r,"schema.graphql");await v(l,n);let p=$.join(process.cwd(),r,"resolvers.js");return await v(p,`export const resolvers = ${i}`),{loader:"ts",contents:a+`
import {handler as __internalPylonHandler} from "@getcronit/pylon"
let __internalPylonConfig = undefined
try {
__internalPylonConfig = config
} catch {
// config is not declared, pylonConfig remains undefined
}
app.use(__internalPylonHandler({
typeDefs: ${JSON.stringify(n)},
graphql,
resolvers: ${i},
config: __internalPylonConfig
}))
`}})}});function ee(c){return`{${Object.entries(c).map(([t,e])=>{if(e!==void 0)return typeof e=="string"?`${t}:${e}`:typeof e=="function"?`${t}:${e.toString()}`:typeof e=="object"&&!Array.isArray(e)?`${t}:${ee(e)}`:`${t}:${JSON.stringify(e)}`}).join(",")}}`}import me from"path";import te from"fs/promises";import k from"consola";var ie=({dir:c,onBuild:r})=>({name:"notify",async setup(t){let e=async()=>{let o=me.join(c,"schema.graphql");try{await te.access(o)}catch{return null}return await te.readFile(o,"utf-8")},s=await e(),n=Date.now();t.onStart(async()=>{n=Date.now(),k.start("[Pylon]: Building...")}),t.onEnd(async o=>{if(o.errors.length>0){for(let f of o.errors)k.error(`[Pylon]: ${f.text}
${f.location?`at ${f.location.file}:${f.location.line}:${f.location.column}`:""}
${f.detail?f.detail:""}`);throw new Error("Failed to build Pylon")}if(o.warnings.length>0)for(let f of o.warnings)k.warn(f);let i=Date.now()-n,a=Object.keys(o.metafile.inputs).length,l=Object.values(o.metafile.outputs).reduce((f,g)=>f+g.bytes,0),p=await e();k.success(`[Pylon]: Built in ${i}ms`);let u=p!==s;u&&(k.info("[Pylon]: Schema updated"),s=p),r&&await r({totalFiles:a,totalSize:l,schemaChanged:u,duration:i})})}});var E=class{sfiFilePath;outputDir;constructor(r,t="./.pylon"){this.sfiFilePath=r,this.outputDir=t}async initBuildPlugins(r){let t=O.join(process.cwd(),this.outputDir,"index.js"),e;try{e=(await import(t)).config}catch(o){console.error("Error loading config",o)}let s=[],n=e?.plugins||[];for(let o of n)if(o.build){let i=o.build({onBuild:r.onBuild});s.push(i)}return s}async build(r){let t=O.join(process.cwd(),this.sfiFilePath),e=O.join(process.cwd(),this.outputDir);await ne.mkdir(e,{recursive:!0});let s={name:"write-on-end",setup(i){i.onEnd(async a=>{await Promise.all(a.outputFiles.map(async l=>{await ne.mkdir(O.dirname(l.path),{recursive:!0}),await v(l.path,l.text)}))})}},n=await ye({write:!1,logLevel:"silent",metafile:!0,entryPoints:[t],outdir:e,bundle:!0,format:"esm",sourcemap:"inline",packages:"external",plugins:[ie({dir:e,onBuild:async i=>{await r.onBuild?.(i)}}),X({getBuildDefs:r.getBuildDefs,outputDir:this.outputDir}),de({tsconfigPath:O.join(process.cwd(),"tsconfig.json")}),s]});await n.rebuild();let o=await this.initBuildPlugins({onBuild:()=>{r.onBuild?.({totalFiles:0,totalSize:0,schemaChanged:!1,duration:0})}});return await Promise.all(o.map(async i=>{await(await i).rebuild()})),{watch:async()=>{for(let i of o)await(await i).watch();return await n.watch()},rebuild:async()=>{for(let i of o)await(await i).rebuild();await n.rebuild()},dispose:async()=>{for(let i of o)await(await i).dispose();await n.dispose()},cancel:async()=>{for(let i of o)await(await i).cancel();await n.cancel()}}}};import S from"typescript";import F from"typescript";import y from"typescript";var se=c=>c.flags&y.TypeFlags.Object&&c.getProperties().length===0&&c.getCallSignatures().length===0,N=(c,r)=>{let t=c.typeToTypeNode(r,void 0,void 0),e=!!(t&&(t.kind===y.SyntaxKind.ArrayType||t.kind===y.SyntaxKind.TupleType));return!e&&r.getSymbol()?.getName()==="Array"?!0:e};var b=c=>c.flags&y.TypeFlags.String||c.flags&y.TypeFlags.Number||c.flags&y.TypeFlags.Boolean||c.flags&y.TypeFlags.StringLiteral||c.flags&y.TypeFlags.NumberLiteral||c.flags&y.TypeFlags.BooleanLiteral,_=c=>c.getCallSignatures().length>0,x=c=>b(c)?!1:!!(c.types?.length>1&&c.types.every(e=>e.flags&y.TypeFlags.StringLiteral||e.flags&y.TypeFlags.NumberLiteral||e.flags&y.TypeFlags.BooleanLiteral)),j=c=>c.getSymbol()?.getName()==="Promise",I=c=>{if(c.objectFlags&y.ObjectFlags.Reference){let e=c.typeArguments;if(e&&e.length>0)return e[0]}},re=c=>{if(!c.isUnion())return{type:c,wasOptional:!1};let t=c.types.filter(e=>!(e.flags&y.TypeFlags.Undefined||e.flags&y.TypeFlags.Null)).length!==c.types.length;return{type:c.getNonNullableType(),wasOptional:t}};function oe(c,r){let t=r;if(t.isUnion()){let n=t.types.filter(a=>!(a.flags&y.TypeFlags.Object&&a.objectFlags&y.ObjectFlags.Reference&&a.typeArguments?.length)),o=t.types.filter(a=>a.flags&y.TypeFlags.Object&&a.objectFlags&y.ObjectFlags.Reference&&a.typeArguments?.length).map(a=>a.typeArguments[0]),i=n.filter(a=>!o.some(l=>l===a));t=c.getUnionType(i)}let e=[];if(N(c,t)||b(t)||x(t))return e;let s=[];s=t.resolvedProperties||t.getProperties()||[];for(let n of s)(n.valueDeclaration&&!(y.getCombinedModifierFlags(n.valueDeclaration)&y.ModifierFlags.Private)&&!n.getName().startsWith("#"))!==!1&&e.push(n);return e}var D=c=>c.replace(/[^0-9a-zA-Z_]/g,"_"),L=c=>!!c.getSymbol()?.getDeclarations()?.some(r=>r.getSourceFile().fileName.includes("@repeaterjs"));import w from"typescript";var B=class{checker;schema;typesNameMap=new Map;inputsNameMap=new Map;unions=[];enums=[];constructor(r,t){this.checker=r,this.schema=t}getTypeDefinition=(r,t={isInputType:!1})=>{let{type:e,wasOptional:s}=re(r);if(e.flags&w.TypeFlags.Void||e.flags&w.TypeFlags.Undefined||e.flags&w.TypeFlags.Null)return{name:"Void",isList:!1,isRequired:!1};if(L(e)){let l=this.checker.getTypeArguments(e)[0];if(l)return this.getTypeDefinition(l,t)}if(j(e)){let l=I(e);if(l)return this.getTypeDefinition(l,t)}let n=t.isRequired!==void 0?t.isRequired:!s;if(se(e))return{name:"Object",isList:!1,isRequired:n};let o=t.isInputType?this.inputsNameMap:this.typesNameMap;if(o.has(e))return{name:o.get(e),isList:!1,isRequired:n};let i=e.aliasSymbol?.escapedName?.toString()||e.symbol?.escapedName.toString();(i==="__type"||i==="__object")&&(t.propertyName?i=t.propertyName.charAt(0).toUpperCase()+t.propertyName.slice(1):i=void 0),i&&(i=D(i));let a=l=>Array.from(o.values()).includes(l);if(i&&!this.schema.scalars.includes(i)){t.isInputType&&(i=`${i}Input`);let l=1,p=i;for(;a(i);)i=`${p}_${l}`,l++}if(i&&this.schema.scalars.includes(i))return{name:i,isList:!1,isRequired:n};if(N(this.checker,e)){let l=this.checker.getIndexTypeOfType(e,w.IndexKind.Number);if(l){let p=this.getTypeDefinition(l,t);return{name:p.name,isList:!0,isRequired:p.isRequired,isListRequired:n}}}else if(x(e)){let l=this.checker.typeToTypeNode(e,void 0,void 0),u=e.types.map(f=>{if(f.isLiteral()){let g=f.value?.toString();if(!g)throw new Error("Enum member name is undefined");return D(g)}throw new Error("Invalid type for enum member")});u.length>0&&(i=i||l.typeName?.symbol?.escapedName,i||(i=u.join("_").toUpperCase(),i=t.isInputType?`${i}Input`:i),this.enums.push({name:i,values:u,rawType:e}))}else if(b(e)){let l=this.checker.typeToString(e);return e.flags&w.TypeFlags.StringLiteral?l="String":e.flags&w.TypeFlags.NumberLiteral?l="Number":e.flags&w.TypeFlags.BooleanLiteral?l="Boolean":e.flags&w.TypeFlags.String?l="String":e.flags&w.TypeFlags.Number?l="Number":e.flags&w.TypeFlags.Boolean&&(l="Boolean"),{name:D(l),isList:!1,isRequired:n}}else if(e.isIntersection()){let p=e.types.map(u=>this.getTypeDefinition(u,t).name);i=D(i||p.join("And"))}else if(e.isUnion()){let l=e.types,p=e.types.length===l.length,u=l.some(m=>{let h=N(this.checker,m)?this.checker.getIndexTypeOfType(m,w.IndexKind.Number):m;return h?b(h)||x(h):!0}),f=[...new Set(l.map(m=>this.getTypeDefinition(m,{...t,isRequired:p})))],g=f.filter(m=>m.isList);for(let m of g){let h=f.findIndex(T=>T.name===m.name&&!T.isList);h>-1&&f.splice(h,1)}let d=f.map(m=>m.name);if(i=D(i||d.join("Or")),i){let m=1,h=i;for(;a(i);)i=`${h}_${m}`,m++}if(f.length>1&&!t.isInputType&&!u)this.unions.push({name:i,types:d,rawType:e});else{let m=f[0];if(!m)throw new Error("Cannot get type definition");let h=f.some(T=>T.isList&&T.name===m.name);return{name:m.name,isList:h,isRequired:n}}}else if(_(e)){let p=e.getCallSignatures()[0]?.getReturnType();if(p&&j(p)){let u=I(p);u&&(p=u)}if(p)return this.getTypeDefinition(p,t)}return i||(i="Any"),o.set(e,i),{name:i,isList:!1,isRequired:n}};getUnions(){return this.unions}getEnums(){return this.enums}typeDefinitionToGraphQLType=r=>{let t=r.name,{isList:e,isRequired:s,isListRequired:n}=r;return s&&(t=`${t}!`),e&&(t=`[${t}]`,n&&(t=`${t}!`)),t}};import H from"consola";var U=class{schema;checker;program;sfiFile;typeDefinitionBuilder;constructor(r,t,e){this.schema={types:[],inputs:[],interfaces:[],unions:[],enums:[],scalars:["ID","Int","Float","Number","Any","Void","Object","File","Date","JSON","String","Boolean"]},this.checker=r,this.sfiFile=t,this.program=e,this.typeDefinitionBuilder=new B(r,this.schema)}parse(r){let t=this.makeReferenceSchema(r);for(let[e,s]of t.types){let n;r.Query===e?n="Query":r.Mutation===e?n="Mutation":r.Subscription===e&&(n="Subscription"),this.processSchemaReference(e,s,n,"types")}for(let[e,s]of t.inputs)this.processSchemaReference(e,s,void 0,"inputs");this.extractForbiddenFieldNamesFromSchema(),this.schema.unions=this.typeDefinitionBuilder.getUnions().map(e=>({...e,description:this.getTypeDocumentation(e.rawType)})),this.schema.enums=this.typeDefinitionBuilder.getEnums().map(e=>({...e,description:this.getTypeDocumentation(e.rawType)})),this.schema.types=this.schema.types.filter(e=>!this.schema.enums.find(s=>s.name===e.name)),this.schema.inputs=this.schema.inputs.filter(e=>!this.schema.enums.find(s=>s.name===e.name)),this.schema.unions.forEach(e=>{let s=this.checkIfInterfaceIsPossibleForUnion(e,this.schema.types);s&&(this.schema.interfaces.push(s),this.schema.unions=this.schema.unions.filter(n=>n.name!==e.name),this.schema.types.map(n=>{if(e.types.includes(n.name))return n.implements||(n.implements=[]),n.implements.push(s.name),n}))});for(let[e,s]of t.classImplementsMap){this.schema.types.map(n=>{let o=this.schema.types.find(i=>i.rawType===e);return o&&(o.implements=Array.from(new Set([...o.implements||[],...s.map(i=>this.checker.typeToString(i))]))),n});for(let n of s){let o=this.schema.types.find(i=>i.rawType===n);o&&(this.schema.interfaces.push({name:this.checker.typeToString(n),description:this.getTypeDocumentation(n),fields:o.fields}),this.schema.types=this.schema.types.filter(i=>i.rawType!==n))}}this.schema.types=this.schema.types.map(e=>((e.implements||this.schema.unions.find(s=>s.types.includes(e.name)))&&(e.fields=e.fields.filter(s=>s.type.name!=="Void")),e)),this.schema.unions=this.schema.unions.map(e=>({...e,__resolveType:this.getResolveTypeForUnionOrInterface(e,this.schema.types)})),this.schema.interfaces=this.schema.interfaces.map(e=>({...e,__resolveType:this.getResolveTypeForUnionOrInterface(e,this.schema.types)}))}checkIfInterfaceIsPossibleForUnion(r,t){let e=r.types.map(o=>{let i=t.find(a=>a.name===o);if(!i)throw new Error(`Type ${o} not found`);return i}),n=e[0].fields.filter(o=>e.every(i=>i.fields.some(a=>JSON.stringify(a)===JSON.stringify(o))));return n.length>0?{name:r.name,description:r.description,fields:n}:null}getResolveTypeForUnionOrInterface(r,t){let e="types"in r?t.filter(i=>r.types.includes(i.name)):t.filter(i=>i.implements?.includes(r.name));e.sort((i,a)=>a.fields.length-i.fields.length);let s=new Map;e.forEach(i=>{let a=i.fields.map(l=>l.name).sort().join(", ");if(s.has(a)){let l=s.get(a);H.warn(`Warning: Union types "${i.name}" and "${l?.name}" have the same fields: [${a}].
Consider differentiating these types by adding unique fields or using different type names.
This may cause ambiguity in type resolution.`)}else s.set(a,i)});let o=`function resolveType(node) { if (node && typeof node === 'object') { ${e.map(i=>`if (${i.fields.map(p=>`"${p.name}" in node`).join(" && ")}) {return '${i.name}'};`).join(" ")} } }`;return new Function("return "+o)()}toString(){let{typeDefinitionToGraphQLType:r}=this.typeDefinitionBuilder,t=s=>s?`"""
${s}
"""
`:"",e="";for(let s of this.schema.inputs){e+=t(s.description),e+=`input ${s.name} {
`,s.fields.length===0&&(e+=` _ : String
`);for(let n of s.fields)e+=`${t(n.type.description)}`,e+=` ${n.name}: ${r(n.type)}
`;e+=`}
`}for(let s of this.schema.types)if(s.fields.length!==0){e+=t(s.description),e+=`type ${s.name}`,s.implements&&(e+=` implements ${s.implements.join(" & ")}`),e+=` {
`;for(let n of s.fields){let o="";n.args.length>0&&(o=`(${n.args.map(i=>`${t(i.type.description)}${i.name}: ${r(i.type)}`).join(", ")})`),e+=`${t(n.type.description)}`,e+=`${n.name}${o}: ${r(n.type)}
`}e+=`}
`}for(let s of this.schema.unions)e+=t(s.description),e+=`union ${s.name} = ${s.types.join(" | ")}
`;for(let s of this.schema.interfaces){e+=t(s.description),e+=`interface ${s.name} {
`;for(let n of s.fields)e+=`${t(n.type.description)}`,e+=`${n.name}: ${r(n.type)}
`;e+=`}
`}for(let s of this.schema.scalars)e+=`scalar ${s}
`;for(let s of this.schema.enums){e+=t(s.description),e+=`enum ${s.name} {
`;for(let n of s.values)e+=` ${n}
`;e+=`}
`}return e}getSchema(){return this.schema}getResolvers(){let r={};for(let t of this.schema.unions)r[t.name]={__resolveType:t.__resolveType};for(let t of this.schema.interfaces)r[t.name]={__resolveType:t.__resolveType};return r}processSchemaReference(r,t,e,s="types"){let{getTypeDefinition:n}=this.typeDefinitionBuilder,o=s==="inputs",i=n(r,{isInputType:o}),a=e||i.name,l=this.schema[s].find(p=>p.name===a);if(!l){if(this.schema.scalars.includes(a))return;this.schema[s].push({name:a,description:this.getTypeDocumentation(r),fields:[],rawType:N(this.checker,r)&&(r.getNumberIndexType()||r.getStringIndexType())||r}),l=this.schema[s][this.schema[s].length-1]}for(let[p,u]of Object.entries(t)){let f=u.returnType,g=n(f,{isInputType:o,propertyName:p});if(s==="types"){let d={name:p,type:{...g,description:this.getTypeDocumentation(f)},args:[]};if(u.args)for(let[m,h]of Object.entries(u.args)){let T=h,P=n(T.type,{isInputType:!0,propertyName:m,isRequired:h.isRequired});this.schema.scalars.includes(this.checker.typeToString(T.type))&&(P.name=this.checker.typeToString(T.type)),d.args.push({name:m,type:{...P,description:T.documentation}})}l.fields.push(d)}else if(s==="inputs"){let d={name:p,type:{...g,description:this.getTypeDocumentation(f)}};l.fields.find(m=>m.name===d.name)||l.fields.push(d)}}}getSymbolDocumentation(r){let t="";t+=F.displayPartsToString(r.getDocumentationComment(this.checker));let e=r.getJsDocTags(this.checker).map(s=>`@${s.name} ${F.displayPartsToString(s.text)}`).join(`
`);return e&&(t+=`
`+e),t}getTypeDocumentation=r=>{let t=r.getSymbol();return t?this.getSymbolDocumentation(t):""};extractForbiddenFieldNamesFromSchema(){let r=/^[_A-Za-z][_0-9A-Za-z]*$/,t=e=>r.test(e)?e.startsWith("__"):!0;for(let e of this.schema.types)e.fields=e.fields.filter(s=>!t(s.name));for(let e of this.schema.inputs)e.fields=e.fields.filter(s=>!t(s.name))}makeReferenceSchema(r){let t={types:new Map,inputs:new Map,classImplementsMap:new Map},e=(n,o={},i="types",a=[])=>{if(t[i].has(n))return;if(L(n)){let p=this.checker.getTypeArguments(n)[0];e(p,o,i,[...a,"REPEATER_ITEM"]);return}if(this.checker.typeToString(n)!=="[]"&&!this.schema.scalars.includes(this.checker.typeToString(n))&&!b(n)){if(j(n)){if(i==="inputs")return;let p=I(n);p&&e(p,o,i,[...a,"PROMISE"]);return}if(n.isClass()){let p=n.getBaseTypes();p&&p.forEach(u=>{t.classImplementsMap.has(u)||t.classImplementsMap.set(u,[]),t.classImplementsMap.get(u).push(n)})}if(n.isUnion())if(x(n))t[i].has(n)||t[i].set(n,{}),e(n,o,i,[...a,"ENUM"]);else if(i==="types")n.types.forEach(p=>{p.flags&F.TypeFlags.Null||p.flags&F.TypeFlags.Undefined||b(p)||e(p,o,i,[...a,p.symbol?.getName()||`N/A ${this.checker.typeToString(p)}`])});else{let p=n.getNonNullableType();p.isUnion()&&!b(p)&&(H.warn(`Warning: Union types in input fields are not supported yet. Defaulting to the first type (${this.checker.typeToString(p)}) at path: ${a.join(" > ")}`),p=p.types[0]),e(p,o,i,[...a,"NON_NULLABLE"])}else if(_(n)){if(i==="inputs")return;if(!o.parentType)throw new Error("Cannot have a function without a parent type");let p=n.getCallSignatures()[0],u=p?.getParameters()||[],f=p?.getReturnType(),g=t[i].get(o.parentType)[o.propetyName];u.forEach(d=>{let m=this.checker.getTypeOfSymbolAtLocation(d,this.sfiFile);if(this.checker.isTupleType(m))m.target.labeledElementDeclarations.forEach((P,Fe)=>{let K=this.checker.getTypeAtLocation(P),V=P.name.text,pe=this.checker.getSymbolAtLocation(P),le=this.getSymbolDocumentation(pe||d);g.args[V]={type:K,isRequired:P.initializer===void 0?void 0:!1,documentation:le},e(K,{parentType:n},"inputs",[...a,V])});else if(d.valueDeclaration&&F.isParameter(d.valueDeclaration)&&d.valueDeclaration.dotDotDotToken)H.warn(`Warning: Rest parameters without explicit names are not supported. Skipping rest parameter at path: ${a.join(" > ")}.
Unsupported: \`function example(...args: any[]) { }\`.
Supported: \`function example(...namedArgs: [first: string, second: number]) { }\`.
Please provide named rest parameters to ensure proper type resolution.`);else{let h=d.valueDeclaration;g.args&&(g.args[d.escapedName]={type:m,isRequired:h.initializer===void 0?void 0:!1,documentation:this.getSymbolDocumentation(d)},e(m,{parentType:n},"inputs",[...a,d.escapedName]))}}),f&&e(f,o,i,[...a,"RETURN_TYPE"])}else if(N(this.checker,n)){let p=this.checker.getIndexTypeOfType(n,F.IndexKind.Number);p&&!b(p)&&(t[i].has(n)||t[i].set(n,{}),e(p,o,i,[...a,"ITEM_TYPE"]))}else if(!b(n)){let p=oe(this.checker,n);t[i].has(n)||t[i].set(n,{}),p.forEach(u=>{let f=this.checker.getTypeOfSymbolAtLocation(u,this.sfiFile);t[i].get(n)[u.escapedName]||(t[i].get(n)[u.escapedName]={returnType:f,args:{}}),e(f,{propetyName:u.escapedName,parentType:n},i,[...a,u.escapedName])})}}};r.Query&&e(r.Query),r.Mutation&&e(r.Mutation),r.Subscription&&e(r.Subscription);let s=this.program.getSourceFiles();for(let n of s)F.forEachChild(n,o=>{if(F.isClassDeclaration(o)){let i=o.heritageClauses?.flatMap(a=>a.types.map(l=>l))||[];if(i.length>0)for(let a of i)t.types.has(this.checker.getTypeAtLocation(a))&&(t.classImplementsMap.set(this.checker.getTypeAtLocation(o),[this.checker.getTypeAtLocation(a)]),e(this.checker.getTypeAtLocation(o)))}});return t}};import C from"path";var M=class{program;checker;sfiFile;sfi;sfiFilePath;constructor(r){this.sfiFilePath=r;let t=this.loadTsConfigOptions(),e=S.sys.readDirectory(C.dirname(this.sfiFilePath),[".ts"],[".d.ts"]).concat([C.join(C.dirname(this.sfiFilePath),"..","pylon.d.ts")]);this.program=S.createProgram(e,t),this.checker=this.program.getTypeChecker(),this.loadSfi()}loadSfi(){let t=this.program.getSourceFiles().find(o=>C.resolve(o.fileName)===this.sfiFilePath);if(!t)throw new Error("Could not find index.ts (pylon entrypoint)");this.sfiFile=t;let e=this.checker.getSymbolAtLocation(t),n=this.checker.getExportsOfModule(e).find(o=>o.escapedName==="graphql");if(!n)throw new Error("Could not find graphql export");this.sfi=n}loadTsConfigOptions(){let r={target:S.ScriptTarget.ESNext,module:S.ModuleKind.CommonJS,strict:!0,esModuleInterop:!0,skipLibCheck:!1,forceConsistentCasingInFileNames:!0,noImplicitAny:!0,experimentalDecorators:!0},t=S.findConfigFile(C.dirname(this.sfiFilePath),S.sys.fileExists,"tsconfig.json");if(!t)return console.log("Could not find tsconfig.json"),r;let e=S.readConfigFile(t,S.sys.readFile);return e.error?(console.log("Could not read tsconfig.json",e.error),r):S.parseJsonConfigFileContent(e.config,S.sys,C.dirname(t)).options}build(){let r=this.checker.getTypeOfSymbolAtLocation(this.sfi,this.sfiFile),t=r.getProperty("Query"),e=r.getProperty("Mutation"),s=r.getProperty("Subscription"),n=t?this.checker.getTypeOfSymbolAtLocation(t,this.sfiFile):void 0,o=e?this.checker.getTypeOfSymbolAtLocation(e,this.sfiFile):void 0,i=s?this.checker.getTypeOfSymbolAtLocation(s,this.sfiFile):void 0,a=new U(this.checker,this.sfiFile,this.program);return a.parse({Query:n,Mutation:o,Subscription:i}),{typeDefs:a.toString(),schema:a.getSchema(),resolvers:a.getResolvers()}}};var J=async c=>{let r=new E(c.sfiFilePath,c.outputFilePath),t=new M(he.join(process.cwd(),c.sfiFilePath));return await r.build({getBuildDefs:()=>{let e=t.build();return{typeDefs:e.typeDefs,resolvers:e.resolvers}},onBuild:c.onBuild})};import G from"path";import q from"fs/promises";import{generateClient as ge}from"@gqty/cli";import{buildSchema as Te}from"graphql";var ae=G.join(process.cwd(),".pylon/schema.graphql"),Q=G.join(process.cwd(),".pylon/client/index.ts"),W=async({schemaChanged:c})=>{try{await q.access(ae)}catch{throw new Error("Schema not found. Please run `pylon build` or `pylon dev` first.")}if(!c)try{await q.access(Q);return}catch{}let r=await q.readFile(ae,"utf-8"),t=Te(r);await q.mkdir(G.dirname(Q),{recursive:!0}),await v(Q,be),await ge(t,{endpoint:"will-be-overwritten",frameworks:["react"],destination:Q,react:!0,scalarTypes:{Number:"number",Object:"Record<string, unknown>"}})},be=`/**
* GQty: You can safely modify this file based on your needs.
*/
import {createReactClient} from '@gqty/react'
import {
Cache,
createClient,
defaultResponseHandler,
type QueryFetcher
} from 'gqty'
import {
generatedSchema,
scalarsEnumsHash,
type GeneratedSchema
} from './schema.generated'
const queryFetcher: QueryFetcher = async function (
{query, variables, operationName},
fetchOptions
) {
let browserOrInternalFetch: typeof fetch | typeof app.request = fetch
try {
const moduleNameToPreventBundling = '@getcronit/pylon'
const {app} = await import(moduleNameToPreventBundling)
browserOrInternalFetch = app.request
} catch (error) {
// Pylon is not found. Maybe we are running in a different environment.
}
const response = await browserOrInternalFetch('/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
query,
variables,
operationName
}),
mode: 'cors',
...fetchOptions
})
return await defaultResponseHandler(response)
}
const cache = new Cache(
undefined,
/**
* Default option is immediate cache expiry but keep it for 5 minutes,
* allowing soft refetches in background.
*/
{
maxAge: Infinity,
staleWhileRevalidate: 5 * 60 * 1000,
normalization: true
}
)
export const client = createClient<GeneratedSchema>({
schema: generatedSchema,
scalars: scalarsEnumsHash,
cache,
fetchOptions: {
fetcher: queryFetcher
}
})
// Core functions
export const {resolve, subscribe, schema} = client
// Legacy functions
export const {query, mutation, mutate, subscription, resolved, refetch, track} =
client
export const {
graphql,
useQuery,
usePaginatedQuery,
useTransactionQuery,
useLazyQuery,
useRefetch,
useMutation,
useMetaState,
prepareReactRender,
useHydrateCache,
prepareQuery
} = createReactClient<GeneratedSchema>(client, {
defaults: {
// Enable Suspense, you can override this option for each hook.
suspense: false
}
})
export * from './schema.generated'`;we.config();z.name("pylon-dev").description("Pylon Development CLI").version(Y);z.command("build").description("Build the Pylon Schema").action(async()=>{let c=await J({sfiFilePath:"./src/index.ts",outputFilePath:"./.pylon",onBuild:async({totalFiles:r,totalSize:t,duration:e,schemaChanged:s})=>{await ce.sendBuildEvent({duration:e,totalFiles:r,totalSize:t,isDevelopment:!1}),await W({schemaChanged:s})}});await c.rebuild(),await c.dispose()});z.name("dev").option("-c, --command <command>","Command to run the server","bun run .pylon/index.js").action(Se);async function Se(c,r){R.connect(async function(t){t&&(A.error(t),process.exit(1));let e=await J({sfiFilePath:"./src/index.ts",outputFilePath:"./.pylon",onBuild:async({schemaChanged:s,totalFiles:n,totalSize:o,duration:i})=>{await W({schemaChanged:s})}});await e.watch(),R.launchBus((s,n)=>{if(s){A.error(s);return}n.on("log:out",o=>{A.log(o.data.trim())}),n.on("log:err",o=>{A.error(o.data)})}),R.start({name:"pylon-dev",script:c.command,exec_mode:"fork",instances:1,autorestart:!0,watch:["./.pylon"],restart_delay:1e3,watch_delay:1e3,ignore_watch:["node_modules"],env:{...process.env,NODE_ENV:"development"}},function(s,n){if(s)throw s;A.box(`
Pylon is up and running!
Press \`Ctrl + C\` to stop the server.
Encounter any issues? Report them here:
https://github.com/getcronit/pylon/issues
We value your feedback\u2014help us make Pylon even better!`)}),process.on("SIGINT",async s=>{await e.cancel(),R.delete("pylon-dev",function(n){R.disconnect(),process.exit(0)})})})}z.parse();
//# sourceMappingURL=index.js.map