fuse
Version:
The magical GraphQL framework
300 lines (290 loc) • 10.1 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/next/plugin.ts
var plugin_exports = {};
__export(plugin_exports, {
nextFusePlugin: () => nextFusePlugin
});
module.exports = __toCommonJS(plugin_exports);
var import_path2 = __toESM(require("path"));
var import_cli = require("@graphql-codegen/cli");
var import_fs2 = require("fs");
var import_path3 = require("path");
var import_graphql_scalars = require("graphql-scalars");
// src/utils/gql-tada.ts
var import_fs = require("fs");
var import_path = __toESM(require("path"));
var import_graphql = require("graphql");
var import_introspection = require("@urql/introspection");
async function isUsingGraphQLTada(cwd) {
const [pkgJson, tsConfig] = await Promise.allSettled([
import_fs.promises.readFile(import_path.default.resolve(cwd, "package.json"), "utf-8"),
import_fs.promises.readFile(import_path.default.resolve(cwd, "tsconfig.json"), "utf-8")
]);
if (pkgJson.status === "rejected" || tsConfig.status === "rejected") {
return false;
}
try {
const parsed = JSON.parse(pkgJson.value);
const merged = Object.keys({
...parsed.dependencies,
...parsed.devDependencies
});
if (!merged.find((x) => x.includes("gql.tada"))) {
return false;
}
if (!merged.find((x) => x.includes("@0no-co/graphqlsp"))) {
return false;
}
} catch (e) {
return false;
}
try {
const parsed = JSON.parse(tsConfig.value);
const lspPlugin = parsed.compilerOptions.plugins.find(
(plugin) => plugin.name === "@0no-co/graphqlsp"
);
if (!lspPlugin) {
return false;
}
if (!lspPlugin.tadaOutputLocation) {
return false;
}
} catch (e) {
return tsConfig.value.includes("@0no-co/graphqlsp") && tsConfig.value.includes("tadaOutputLocation");
}
return true;
}
var tadaGqlContents = `import { initGraphQLTada } from 'gql.tada';
import type { introspection } from './introspection';
export const graphql = initGraphQLTada<{
introspection: typeof introspection;
}>();
export type { FragmentOf, ResultOf, VariablesOf } from 'gql.tada';
export type { FragmentOf as FragmentType } from 'gql.tada';
export { readFragment } from 'gql.tada';
export { readFragment as useFragment } from 'gql.tada';
`;
var preambleComments = ["/* eslint-disable */", "/* prettier-ignore */"].join("\n") + "\n";
var tsAnnotationComment = [
"/** An IntrospectionQuery representation of your schema.",
" *",
" * @remarks",
" * This is an introspection of your schema saved as a file by GraphQLSP.",
" * You may import it to create a `graphql()` tag function with `gql.tada`",
" * by importing it and passing it to `initGraphQLTada<>()`.",
" *",
" * @example",
" * ```",
" * import { initGraphQLTada } from 'gql.tada';",
" * import type { introspection } from './introspection';",
" *",
" * export const graphql = initGraphQLTada<{",
" * introspection: typeof introspection;",
" * scalars: {",
" * DateTime: string;",
" * Json: any;",
" * };",
" * }>();",
" * ```",
" */"
].join("\n");
// src/next/plugin.ts
var isRunningCodegen = false;
function nextFusePlugin(options = {}) {
return (nextConfig = {}) => {
if (process.env.NODE_ENV === "development" && !isRunningCodegen) {
isRunningCodegen = true;
isUsingGraphQLTada(process.cwd()).then((isUsing) => {
boostrapFuse(isUsing);
try {
if (isUsing) {
let exitHandler2 = function() {
try {
watcher.close();
} catch (e) {
}
};
var exitHandler = exitHandler2;
let baseDirectory = process.cwd();
const hasSrcDir = (0, import_fs2.existsSync)((0, import_path3.resolve)(baseDirectory, "src"));
if (hasSrcDir) {
baseDirectory = (0, import_path3.resolve)(baseDirectory, "src");
}
setTimeout(() => {
fetch(
`http://localhost:${options.port || 3e3}/api/${options.path || "fuse"}?query={__typename}`
);
}, 1e3);
const watcher = (0, import_fs2.watch)(
(0, import_path3.resolve)(baseDirectory, "types"),
{ recursive: true },
() => {
setTimeout(() => {
fetch(
`http://localhost:${options.port || 3e3}/api/${options.path || "fuse"}?query={__typename}`
);
}, 1e3);
}
);
process.on("exit", exitHandler2);
process.on("SIGINT", exitHandler2);
process.on("SIGUSR1", exitHandler2);
process.on("SIGUSR2", exitHandler2);
process.on("uncaughtException", exitHandler2);
} else {
setTimeout(() => {
try {
boostrapCodegen(options.port || 3e3, options.path || "fuse");
} catch (e) {
}
}, 1e3);
}
} catch (e) {
}
});
}
const newNextConfig = Object.assign({}, nextConfig, {
webpack(webpackConfig, webpackOptions) {
webpackConfig.module.rules.push({
test: [
/pages[\\/]api[\\/]fuse.ts/,
/app[\\/]api[\\/]fuse[\\/]route.ts/,
/fuse[\\/]server.ts/
],
use: [
webpackOptions.defaultLoaders.babel,
{ loader: "fuse/next/loader" }
]
});
if (typeof nextConfig.webpack === "function") {
return nextConfig.webpack(webpackConfig, webpackOptions);
}
return webpackConfig;
}
});
return newNextConfig;
};
}
async function boostrapFuse(isUsingTada) {
let baseDirectory = process.cwd();
try {
const hasSrcDir = (0, import_fs2.existsSync)((0, import_path3.resolve)(baseDirectory, "src"));
if (hasSrcDir) {
baseDirectory = (0, import_path3.resolve)(baseDirectory, "src");
}
if (!(0, import_fs2.existsSync)(baseDirectory + "/fuse")) {
await import_fs2.promises.mkdir(baseDirectory + "/fuse");
}
await Promise.allSettled(
[
import_fs2.promises.writeFile(
baseDirectory + "/fuse/server.ts",
`// This is a generated file!
export * from 'fuse/next/server'
export { __internal_execute as execute } from 'fuse/next/server'
`
),
import_fs2.promises.writeFile(
baseDirectory + "/fuse/client.ts",
`// This is a generated file!
export * from 'fuse/next/client'
`
),
import_fs2.promises.writeFile(
baseDirectory + "/fuse/pages.ts",
`// This is a generated file!
export * from 'fuse/next/pages'
`
),
isUsingTada && import_fs2.promises.writeFile(
import_path2.default.resolve(baseDirectory, "fuse/index.ts"),
`// This is a generated file!
export * from './tada'
`
),
isUsingTada && import_fs2.promises.writeFile(
import_path2.default.resolve(baseDirectory, "fuse/tada.ts"),
tadaGqlContents
)
].filter(Boolean)
);
} catch (e) {
}
}
async function boostrapCodegen(port, path3) {
let baseDirectory = process.cwd();
const hasSrcDir = (0, import_fs2.existsSync)((0, import_path3.resolve)(baseDirectory, "src"));
if (hasSrcDir) {
baseDirectory = (0, import_path3.resolve)(baseDirectory, "src");
}
const ctx = new import_cli.CodegenContext({
filepath: "codgen.yml",
config: {
ignoreNoDocuments: true,
errorsOnly: true,
noSilentErrors: true,
watch: [
baseDirectory + "/**/*.{ts,tsx}",
baseDirectory + "/types/**/*.ts",
"!./{node_modules,.next,.git}/**/*"
],
documents: [
hasSrcDir ? "./src/**/*.{ts,tsx}" : "./**/*.{ts,tsx}",
"!./{node_modules,.next,.git}/**/*"
],
schema: `http://localhost:${port}/api/${path3}`,
debug: true,
generates: {
[baseDirectory + "/fuse/"]: {
preset: "client",
config: {
scalars: {
ID: {
input: "string",
output: "string"
},
DateTime: import_graphql_scalars.DateTimeResolver.extensions.codegenScalarType,
JSON: import_graphql_scalars.JSONResolver.extensions.codegenScalarType
},
avoidOptionals: false,
enumsAsTypes: true,
nonOptionalTypename: true,
skipTypename: false
}
}
}
}
});
await (0, import_cli.generate)(ctx, true);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
nextFusePlugin
});
;