diff --git a/README.md b/README.md index b8cbee7..d1da8cf 100644 --- a/README.md +++ b/README.md @@ -44,7 +44,7 @@ docs coming soon diff --git a/codegen/codegen.js b/codegen/codegen.js index e663394..5a9e26f 100644 --- a/codegen/codegen.js +++ b/codegen/codegen.js @@ -1,22 +1,24 @@ +import { visit, concatAST, Kind, } from "graphql"; +import "@graphql-codegen/plugin-helpers"; import { ClientSideBaseVisitor, } from "@graphql-codegen/visitor-plugin-common"; -import { concatAST, Kind, visit, } from "graphql"; import { pascalCase } from "pascal-case"; -module.exports = { - plugin: (schema, documents, config) => { - const allAst = concatAST(documents.map((d) => d.document)); - const allFragments = [ - ...allAst.definitions.filter((d) => d.kind === Kind.FRAGMENT_DEFINITION).map((fragmentDef) => ({ - node: fragmentDef, - name: fragmentDef.name.value, - onType: fragmentDef.typeCondition.name.value, - isExternal: false, - })), - ...(config.externalFragments || []), - ]; - const visitor = new ClientSideBaseVisitor(schema, allFragments, {}, { documentVariableSuffix: "Doc" }, documents); - const visitorResult = visit(allAst, { leave: visitor }); - const operations = allAst.definitions.filter((d) => d.kind === Kind.OPERATION_DEFINITION); - const defaultTypes = ` +console.log("codegen.ts"); +export const plugin = (schema, documents, config) => { + console.log("config", config); + const allAst = concatAST(documents.map((d) => d.document)); + const allFragments = [ + ...allAst.definitions.filter((d) => d.kind === Kind.FRAGMENT_DEFINITION).map((fragmentDef) => ({ + node: fragmentDef, + name: fragmentDef.name.value, + onType: fragmentDef.typeCondition.name.value, + isExternal: false, + })), + ...(config.externalFragments || []), + ]; + const visitor = new ClientSideBaseVisitor(schema, allFragments, {}, { documentVariableSuffix: "Doc" }, documents); + const visitorResult = visit(allAst, { leave: visitor }); + const operations = allAst.definitions.filter((d) => d.kind === Kind.OPERATION_DEFINITION); + const defaultTypes = ` type FetchWrapperArgs = { fetch: typeof fetch, @@ -26,39 +28,51 @@ type FetchWrapperArgs = { type SubscribeWrapperArgs = { variables?: T, } + +interface CacheFunctionOptions { + update?: boolean +} + `; - const ops = operations - .map((o) => { - var _a; - if (o) { - const name = ((_a = o === null || o === void 0 ? void 0 : o.name) === null || _a === void 0 ? void 0 : _a.value) || ""; - // const dsl = `export const ${pascalCase(op.name.value)}Doc = gql\` - // ${documents.find((d) => d.rawSDL.includes(`${op.operation} ${op.name.value}`)).rawSDL}\`` - const op = `${pascalCase(name)}${pascalCase(o.operation)}`; - const opv = `${op}Variables`; - let operations = ""; - if (o.operation === "query") { - operations += ` + const ops = operations + .map((o) => { + var _a; + if (o) { + const name = ((_a = o === null || o === void 0 ? void 0 : o.name) === null || _a === void 0 ? void 0 : _a.value) || ""; + // const dsl = `export const ${pascalCase(op.name.value)}Doc = gql\` + // ${documents.find((d) => d.rawSDL.includes(`${op.operation} ${op.name.value}`)).rawSDL}\`` + const op = `${pascalCase(name)}${pascalCase(o.operation)}`; + const opv = `${op}Variables`; + let operations = ""; + if (o.operation === "query") { + operations += ` export const ${name} = ({ variables, fetch}: FetchWrapperArgs<${opv}>): Promise> => g.fetch<${op}>({ queries: [{ query: ${pascalCase(name)}Doc, variables }], fetch }) + + + // Cached + export async function get${pascalCase(name)}(variables, options?: CacheFunctionOptions) { + await gQuery('user', { query: ${name}, variables }, options) +} + `; - // If config is set to have subscription query, also write the - if (config.subscriptionQuery) { - operations += ` + // If config is set to have subscription query, also write the + if (config.subscriptionQuery) { + operations += ` export const ${name}Subscribe = ({ variables }: SubscribeWrapperArgs<${opv}>): Readable> => g.oFetch<${op}>({ queries: [{ query: ${pascalCase(name)}Doc, variables }] }) `; - } } - else if (o.operation === "mutation") { - operations += ` + } + else if (o.operation === "mutation") { + operations += ` export const ${name} = ({ variables }: SubscribeWrapperArgs<${opv}>): Promise> => g.fetch<${op}>({ @@ -66,52 +80,52 @@ Promise> => fetch, }) `; - } - return operations; } - }) - .join("\n"); - const imports = [ - `import type { Readable } from "svelte/store"`, - `import { g } from '${config.gFetchPath}'`, - `import type { GFetchReturnWithErrors } from '$graphql/gfetchLib'`, - `import gql from "graphql-tag"`, - ]; - // let schemaInputs = getCachedDocumentNodeFromSchema(schema).definitions.filter((d) => { - // return d.kind === 'InputObjectTypeDefinition' - // }) - // let inputs = schemaInputs - // .map((d) => { - // console.log('/* START */') - // // @ts-ignore - // console.log('NAME: ', d.fields[0].name.value) - // // @ts-ignore - // let isReq = d.fields[0]?.type?.kind === 'NonNullType' - // console.log('REQUIRED: ', isReq ? '✅' : '❌') - // // @ts-ignore - // console.log('TYPE: ', isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value) - // // @ts-ignore - // // @ts-ignore - // console.log('d.fields[0]', d.fields[0]?.type) - // console.log('/* END */') - // console.log('') - // return ` - // const inputName = { - // ${d.fields[0].name.value}: ${isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value} - // } - // ` - // }) - // .join('\n') - // console.log('inputs', inputs) - return { - prepend: imports, - content: [ - defaultTypes, - visitor.fragments, - ...visitorResult.definitions.filter((t) => typeof t == "string"), - ops, - ].join("\n"), - }; - }, + return operations; + } + }) + .join("\n"); + const imports = [ + `import type { Readable } from "svelte/store"`, + `import { g } from '${config.gPath}'`, + `import type { GFetchReturnWithErrors } from '@leveluptuts/g-query'`, + `import { gQuery } from '@leveluptuts/g-query'`, + `import gql from "graphql-tag"`, + ]; + // let schemaInputs = getCachedDocumentNodeFromSchema(schema).definitions.filter((d) => { + // return d.kind === 'InputObjectTypeDefinition' + // }) + // let inputs = schemaInputs + // .map((d) => { + // console.log('/* START */') + // // @ts-ignore + // console.log('NAME: ', d.fields[0].name.value) + // // @ts-ignore + // let isReq = d.fields[0]?.type?.kind === 'NonNullType' + // console.log('REQUIRED: ', isReq ? '✅' : '❌') + // // @ts-ignore + // console.log('TYPE: ', isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value) + // // @ts-ignore + // // @ts-ignore + // console.log('d.fields[0]', d.fields[0]?.type) + // console.log('/* END */') + // console.log('') + // return ` + // const inputName = { + // ${d.fields[0].name.value}: ${isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value} + // } + // ` + // }) + // .join('\n') + // console.log('inputs', inputs) + return { + prepend: imports, + content: [ + defaultTypes, + visitor.fragments, + ...visitorResult.definitions.filter((t) => typeof t == "string"), + ops, + ].join("\n"), + }; }; //# sourceMappingURL=codegen.js.map \ No newline at end of file diff --git a/codegen/codegen.js.map b/codegen/codegen.js.map index 571c37c..0bdac8a 100644 --- a/codegen/codegen.js.map +++ b/codegen/codegen.js.map @@ -1 +1 @@ -{"version":3,"file":"codegen.js","sourceRoot":"","sources":["codegen.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,qBAAqB,GACtB,MAAM,wCAAwC,CAAC;AAChD,OAAO,EACL,SAAS,EAET,IAAI,EAEJ,KAAK,GACN,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,MAAM,CAAC,OAAO,GAAG;IACf,MAAM,EAAE,CAAC,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,EAAE;QACpC,MAAM,MAAM,GAAG,SAAS,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;QAE3D,MAAM,YAAY,GAAqB;YACrC,GACE,MAAM,CAAC,WAAW,CAAC,MAAM,CACvB,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,mBAAmB,CAE7C,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;gBACtB,IAAI,EAAE,WAAW;gBACjB,IAAI,EAAE,WAAW,CAAC,IAAI,CAAC,KAAK;gBAC5B,MAAM,EAAE,WAAW,CAAC,aAAa,CAAC,IAAI,CAAC,KAAK;gBAC5C,UAAU,EAAE,KAAK;aAClB,CAAC,CAAC;YACH,GAAG,CAAC,MAAM,CAAC,iBAAiB,IAAI,EAAE,CAAC;SACpC,CAAC;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SAAS,KAAK,UAAU,EAAE;oBACrC,UAAU,IAAI;eACX,IAAI,2CAA2C,GAAG;iCAChC,EAAE;WACxB,EAAE;uBACU,UAAU,CAAC,IAAI,CAAC;;;CAGtC,CAAC;iBACS;gBAED,OAAO,UAAU,CAAC;aACnB;QACH,CAAC,CAAC;aACD,IAAI,CAAC,IAAI,CAAC,CAAC;QAEd,MAAM,OAAO,GAAG;YACd,8CAA8C;YAC9C,sBAAsB,MAAM,CAAC,UAAU,GAAG;YAC1C,kEAAkE;YAClE,+BAA+B;SAChC,CAAC;QAEF,6FAA6F;QAC7F,sDAAsD;QACtD,SAAS;QACT,gCAAgC;QAChC,sBAAsB;QACtB,qCAAqC;QACrC,wBAAwB;QACxB,wDAAwD;QACxD,wBAAwB;QACxB,gEAAgE;QAChE,uDAAuD;QACvD,wBAAwB;QACxB,+GAA+G;QAC/G,wBAAwB;QACxB,wBAAwB;QACxB,wDAAwD;QACxD,mCAAmC;QACnC,0BAA0B;QAE1B,mBAAmB;QACnB,sBAAsB;QACtB,+GAA+G;QAC/G,IAAI;QACJ,MAAM;QACN,WAAW;QACX,oBAAoB;QACpB,oCAAoC;QAEpC,OAAO;YACL,OAAO,EAAE,OAAO;YAChB,OAAO,EAAE;gBACP,YAAY;gBACZ,OAAO,CAAC,SAAS;gBACjB,GAAG,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,QAAQ,CAAC;gBAChE,GAAG;aACJ,CAAC,IAAI,CAAC,IAAI,CAAC;SACb,CAAC;IACJ,CAAC;CACe,CAAC"} \ No newline at end of file +{"version":3,"file":"codegen.js","sourceRoot":"","sources":["codegen.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EAEL,SAAS,EACT,IAAI,GAGL,MAAM,SAAS,CAAC;AACjB,OAIO,iCAAiC,CAAC;AAEzC,OAAO,EAEL,qBAAqB,GACtB,MAAM,wCAAwC,CAAC;AAEhD,OAAO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FAA6F;IAC7F,sDAAsD;IACtD,SAAS;IACT,gCAAgC;IAChC,sBAAsB;IACtB,qCAAqC;IACrC,wBAAwB;IACxB,wDAAwD;IACxD,wBAAwB;IACxB,gEAAgE;IAChE,uDAAuD;IACvD,wBAAwB;IACxB,+GAA+G;IAC/G,wBAAwB;IACxB,wBAAwB;IACxB,wDAAwD;IACxD,mCAAmC;IACnC,0BAA0B;IAE1B,mBAAmB;IACnB,sBAAsB;IACtB,+GAA+G;IAC/G,IAAI;IACJ,MAAM;IACN,WAAW;IACX,oBAAoB;IACpB,oCAAoC;IAEpC,OAAO;QACL,OAAO,EAAE,OAAO;QAChB,OAAO,EAAE;YACP,YAAY;YACZ,OAAO,CAAC,SAAS;YACjB,GAAG,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,QAAQ,CAAC;YAChE,GAAG;SACJ,CAAC,IAAI,CAAC,IAAI,CAAC;KACb,CAAC;AACJ,CAAC,CAAC"} \ No newline at end of file diff --git a/codegen/codegen.ts b/codegen/codegen.ts index db15766..ec922d9 100644 --- a/codegen/codegen.ts +++ b/codegen/codegen.ts @@ -1,48 +1,61 @@ +import { + visit, + GraphQLSchema, + concatAST, + Kind, + FragmentDefinitionNode, + OperationDefinitionNode, +} from "graphql"; +import { + Types, + PluginValidateFn, + PluginFunction, +} from "@graphql-codegen/plugin-helpers"; import type { CodegenPlugin } from "@graphql-codegen/plugin-helpers"; import { LoadedFragment, ClientSideBaseVisitor, } from "@graphql-codegen/visitor-plugin-common"; -import { - concatAST, - FragmentDefinitionNode, - Kind, - OperationDefinitionNode, - visit, -} from "graphql"; + import { pascalCase } from "pascal-case"; -module.exports = { - plugin: (schema, documents, config) => { - const allAst = concatAST(documents.map((d) => d.document)); +console.log("codegen.ts"); - const allFragments: LoadedFragment[] = [ - ...( - allAst.definitions.filter( - (d) => d.kind === Kind.FRAGMENT_DEFINITION - ) as FragmentDefinitionNode[] - ).map((fragmentDef) => ({ - node: fragmentDef, - name: fragmentDef.name.value, - onType: fragmentDef.typeCondition.name.value, - isExternal: false, - })), - ...(config.externalFragments || []), - ]; +export const plugin: PluginFunction = ( + schema: GraphQLSchema, + documents: Types.DocumentFile[], + config +) => { + console.log("config", config); + const allAst = concatAST(documents.map((d) => d.document)); - const visitor = new ClientSideBaseVisitor( - schema, - allFragments, - {}, - { documentVariableSuffix: "Doc" }, - documents - ); - const visitorResult = visit(allAst, { leave: visitor }); + const allFragments: LoadedFragment[] = [ + ...( + allAst.definitions.filter( + (d) => d.kind === Kind.FRAGMENT_DEFINITION + ) as FragmentDefinitionNode[] + ).map((fragmentDef) => ({ + node: fragmentDef, + name: fragmentDef.name.value, + onType: fragmentDef.typeCondition.name.value, + isExternal: false, + })), + ...(config.externalFragments || []), + ]; - const operations = allAst.definitions.filter( - (d) => d.kind === Kind.OPERATION_DEFINITION - ) as OperationDefinitionNode[]; - const defaultTypes = ` + const visitor = new ClientSideBaseVisitor( + schema, + allFragments, + {}, + { documentVariableSuffix: "Doc" }, + documents + ); + const visitorResult = visit(allAst, { leave: visitor }); + + const operations = allAst.definitions.filter( + (d) => d.kind === Kind.OPERATION_DEFINITION + ) as OperationDefinitionNode[]; + const defaultTypes = ` type FetchWrapperArgs = { fetch: typeof fetch, @@ -52,39 +65,53 @@ type FetchWrapperArgs = { type SubscribeWrapperArgs = { variables?: T, } + +interface CacheFunctionOptions { + update?: boolean +} + `; - const ops = operations - .map((o) => { - if (o) { - const name = o?.name?.value || ""; - // const dsl = `export const ${pascalCase(op.name.value)}Doc = gql\` - // ${documents.find((d) => d.rawSDL.includes(`${op.operation} ${op.name.value}`)).rawSDL}\`` - const op = `${pascalCase(name)}${pascalCase(o.operation)}`; - const opv = `${op}Variables`; - let operations = ""; + const ops = operations + .map((o) => { + if (o) { + const name = o?.name?.value || ""; + // const dsl = `export const ${pascalCase(op.name.value)}Doc = gql\` + // ${documents.find((d) => d.rawSDL.includes(`${op.operation} ${op.name.value}`)).rawSDL}\`` + const op = `${pascalCase(name)}${pascalCase(o.operation)}`; + const opv = `${op}Variables`; + let operations = ""; - if (o.operation === "query") { - operations += ` + if (o.operation === "query") { + operations += ` export const ${name} = ({ variables, fetch}: FetchWrapperArgs<${opv}>): Promise> => g.fetch<${op}>({ queries: [{ query: ${pascalCase(name)}Doc, variables }], fetch }) + + + // Cached + export async function get${pascalCase( + name + )}(variables, options?: CacheFunctionOptions) { + await gQuery('user', { query: ${name}, variables }, options) +} + `; - // If config is set to have subscription query, also write the - if (config.subscriptionQuery) { - operations += ` + // If config is set to have subscription query, also write the + if (config.subscriptionQuery) { + operations += ` export const ${name}Subscribe = ({ variables }: SubscribeWrapperArgs<${opv}>): Readable> => g.oFetch<${op}>({ queries: [{ query: ${pascalCase(name)}Doc, variables }] }) `; - } - } else if (o.operation === "mutation") { - operations += ` + } + } else if (o.operation === "mutation") { + operations += ` export const ${name} = ({ variables }: SubscribeWrapperArgs<${opv}>): Promise> => g.fetch<${op}>({ @@ -92,56 +119,56 @@ Promise> => fetch, }) `; - } - - return operations; } - }) - .join("\n"); - const imports = [ - `import type { Readable } from "svelte/store"`, - `import { g } from '${config.gFetchPath}'`, - `import type { GFetchReturnWithErrors } from '$graphql/gfetchLib'`, - `import gql from "graphql-tag"`, - ]; + return operations; + } + }) + .join("\n"); - // let schemaInputs = getCachedDocumentNodeFromSchema(schema).definitions.filter((d) => { - // return d.kind === 'InputObjectTypeDefinition' - // }) - // let inputs = schemaInputs - // .map((d) => { - // console.log('/* START */') - // // @ts-ignore - // console.log('NAME: ', d.fields[0].name.value) - // // @ts-ignore - // let isReq = d.fields[0]?.type?.kind === 'NonNullType' - // console.log('REQUIRED: ', isReq ? '✅' : '❌') - // // @ts-ignore - // console.log('TYPE: ', isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value) - // // @ts-ignore - // // @ts-ignore - // console.log('d.fields[0]', d.fields[0]?.type) - // console.log('/* END */') - // console.log('') + const imports = [ + `import type { Readable } from "svelte/store"`, + `import { g } from '${config.gPath}'`, + `import type { GFetchReturnWithErrors } from '@leveluptuts/g-query'`, + `import { gQuery } from '@leveluptuts/g-query'`, + `import gql from "graphql-tag"`, + ]; - // return ` - // const inputName = { - // ${d.fields[0].name.value}: ${isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value} - // } - // ` - // }) - // .join('\n') - // console.log('inputs', inputs) + // let schemaInputs = getCachedDocumentNodeFromSchema(schema).definitions.filter((d) => { + // return d.kind === 'InputObjectTypeDefinition' + // }) + // let inputs = schemaInputs + // .map((d) => { + // console.log('/* START */') + // // @ts-ignore + // console.log('NAME: ', d.fields[0].name.value) + // // @ts-ignore + // let isReq = d.fields[0]?.type?.kind === 'NonNullType' + // console.log('REQUIRED: ', isReq ? '✅' : '❌') + // // @ts-ignore + // console.log('TYPE: ', isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value) + // // @ts-ignore + // // @ts-ignore + // console.log('d.fields[0]', d.fields[0]?.type) + // console.log('/* END */') + // console.log('') - return { - prepend: imports, - content: [ - defaultTypes, - visitor.fragments, - ...visitorResult.definitions.filter((t) => typeof t == "string"), - ops, - ].join("\n"), - }; - }, -} as CodegenPlugin; + // return ` + // const inputName = { + // ${d.fields[0].name.value}: ${isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value} + // } + // ` + // }) + // .join('\n') + // console.log('inputs', inputs) + + return { + prepend: imports, + content: [ + defaultTypes, + visitor.fragments, + ...visitorResult.definitions.filter((t) => typeof t == "string"), + ops, + ].join("\n"), + }; +}; diff --git a/codegen/plugin.js b/codegen/plugin.js index 440c38d..3d3cc2d 100644 --- a/codegen/plugin.js +++ b/codegen/plugin.js @@ -31,8 +31,10 @@ export default function levelupViteCodegen(options) { if (!options.output) { throw new Error("No output directory specified"); } - const { schema, output } = options; - console.log(`${process.cwd()}/${output}/${outputFile}`); + if (!options.gPath) { + throw new Error("No gPath directory specified. gPath is where you've initialized the 'g' client"); + } + const { schema, output, gPath } = options; return { name: "levelup-vite-codegen", async buildStart() { @@ -44,23 +46,21 @@ export default function levelupViteCodegen(options) { [`${process.cwd()}/${output}/gquery-types.generated.ts`]: { plugins: ["typescript"], }, - // [`${process.cwd()}/${output}/${outputFile}`]: { - // // preset: "import-types", - // // presetConfig: { - // // typesPath: `${output}/${outputFile}`, - // // }, - // // preset: "near-operation-file", - // // presetConfig: { - // // extension: ".generated.ts", - // // folder: "./", - // // baseTypesPath: `${output}/${outputFile}`, - // // }, - // plugins: [ - // "typescript", - // // "typescript-operations", - // "../packages/gQueryCodegen/codegen.js", - // ], - // }, + [`${process.cwd()}/${output}`]: { + config: { + gPath, + }, + preset: "near-operation-file", + presetConfig: { + extension: ".generated.ts", + folder: "./", + baseTypesPath: `gquery-types.generated.ts`, + }, + plugins: [ + "typescript-operations", + "@leveluptuts/g-query/codegen-plugin", + ], + }, }, }, true); } diff --git a/codegen/plugin.js.map b/codegen/plugin.js.map index 0a69e50..82b4dc3 100644 --- a/codegen/plugin.js.map +++ b/codegen/plugin.js.map @@ -1 +1 @@ -{"version":3,"file":"plugin.js","sourceRoot":"","sources":["plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,uCAAuC;AAEvC,4EAA4E;AAC5E,4BAA4B;AAC5B,gCAAgC;AAChC,mEAAmE;AAEnE,qDAAqD;AACrD,8CAA8C;AAE9C,wEAAwE;AACxE,MAAM,UAAU,GAAG,qBAAqB,CAAC;AACzC,mBAAmB;AACnB,mBAAmB;AACnB,wJAAwJ;AACxJ,0BAA0B;AAC1B,wCAAwC;AACxC,eAAe;AACf,yCAAyC;AACzC,QAAQ;AACR,yEAAyE;AACzE,SAAS;AACT,OAAO;AACP,iBAAiB;AACjB,oCAAoC;AACpC,OAAO;AACP,KAAK;AAEL,MAAM,SAAS,GAAG,cAAc,CAAC;AAEjC,MAAM,CAAC,OAAO,UAAU,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B;wBACD,CAAC,GAAG,OAAO,CAAC,GAAG,EAAE,IAAI,MAAM,EAAE,CAAC,EAAE;4BAC9B,MAAM,EAAE;gCACN,KAAK;6BACN;4BACD,MAAM,EAAE,qBAAqB;4BAC7B,YAAY,EAAE;gCACZ,SAAS,EAAE,eAAe;gCAC1B,MAAM,EAAE,IAAI;gCACZ,aAAa,EAAE,2BAA2B;6BAC3C;4BACD,OAAO,EAAE;gCACP,uBAAuB;gCACvB,qCAAqC;6BACtC;yBACF;qBACF;iBACF,EACD,IAAI,CACL,CAAC;aACH;YAAC,OAAO,CAAC,EAAE;gBACV,OAAO,CAAC,GAAG,CAAC,+CAA+C,CAAC,CAAC;gBAC7D,OAAO,CAAC,GAAG,CACT,0FAA0F,CAC3F,CAAC;gBACF,OAAO,CAAC,GAAG,CACT,uFAAuF,CACxF,CAAC;aACH;YACD,OAAO;QACT,CAAC;QAED,SAAS,CAAC,GAAG,EAAE,EAAE,IAAG,CAAC;KACtB,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/codegen/plugin.ts b/codegen/plugin.ts index c573e97..2f6ed9c 100644 --- a/codegen/plugin.ts +++ b/codegen/plugin.ts @@ -36,9 +36,14 @@ export default function levelupViteCodegen(options) { if (!options.output) { throw new Error("No output directory specified"); } + if (!options.gPath) { + throw new Error( + "No gPath directory specified. gPath is where you've initialized the 'g' client" + ); + } + + const { schema, output, gPath } = options; - const { schema, output } = options; - console.log(`${process.cwd()}/${output}/${outputFile}`); return { name: "levelup-vite-codegen", @@ -52,23 +57,21 @@ export default function levelupViteCodegen(options) { [`${process.cwd()}/${output}/gquery-types.generated.ts`]: { plugins: ["typescript"], }, - // [`${process.cwd()}/${output}/${outputFile}`]: { - // // preset: "import-types", - // // presetConfig: { - // // typesPath: `${output}/${outputFile}`, - // // }, - // // preset: "near-operation-file", - // // presetConfig: { - // // extension: ".generated.ts", - // // folder: "./", - // // baseTypesPath: `${output}/${outputFile}`, - // // }, - // plugins: [ - // "typescript", - // // "typescript-operations", - // "../packages/gQueryCodegen/codegen.js", - // ], - // }, + [`${process.cwd()}/${output}`]: { + config: { + gPath, + }, + preset: "near-operation-file", + presetConfig: { + extension: ".generated.ts", + folder: "./", + baseTypesPath: `gquery-types.generated.ts`, + }, + plugins: [ + "typescript-operations", + "@leveluptuts/g-query/codegen-plugin", + ], + }, }, }, true diff --git a/package.json b/package.json index ce9de57..ca3ede9 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ }, "dependencies": { "@graphql-codegen/cli": "^2.2.0", + "@graphql-codegen/typescript-operations": "^2.1.6", "camel-case": "^4.1.2", "pascal-case": "^3.1.2", "svelte": "^3.43.1", @@ -12,6 +13,8 @@ }, "description": "Not like jQuery. A GraphQL Fetcher & Cache for Svelte Kit", "devDependencies": { + "@graphql-codegen/import-types-preset": "^2.1.4", + "@graphql-codegen/near-operation-file-preset": "^2.1.4", "@graphql-codegen/plugin-helpers": "^2.1.1", "@graphql-codegen/visitor-plugin-common": "^2.2.1", "graphql": "^15.6.1", @@ -19,7 +22,9 @@ }, "exports": { ".": "./dist/index.js", + "./*": "./dist/index.js", "./codegen": "./codegen/plugin.js", + "./codegen-plugin": "./codegen/codegen.js", "./package.json": "./package.json" }, "homepage": "https://github.com/leveluptuts/gQuery#readme", @@ -27,7 +32,7 @@ "graphql" ], "license": "ISC", - "name": "@leveluptuts/gQuery", + "name": "@leveluptuts/g-query", "repository": { "type": "git", "url": "git+https://github.com/leveluptuts/gQuery.git" @@ -38,5 +43,5 @@ "test": "echo \"Error: no test specified\" && exit 1" }, "type": "module", - "version": "0.0.1" + "version": "0.0.2" } diff --git a/tsconfig.json b/tsconfig.json index b7d0d53..6b71488 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,10 +5,6 @@ "lib": ["es2020", "DOM"], "outDir": "./dist", "target": "es2020", - /** - svelte-preprocess cannot figure out whether you have a value or a type, so tell TypeScript - to enforce using \`import type\` instead of \`import\` for Types. - */ "importsNotUsedAsValues": "error", "isolatedModules": true, "resolveJsonModule": true, @@ -21,6 +17,7 @@ "skipLibCheck": true, "forceConsistentCasingInFileNames": true }, + "exclude": ["node_modules"], - "include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.ts", "src/codegen.ts"] + "include": ["src/**/*.d.ts", "src/**/*.js", "src/**/*.ts"] }