Skip to content

Commit

Permalink
fix: bundling env support (#8150)
Browse files Browse the repository at this point in the history
* fix: bundler support

* fix: bundling env support

* ..

* Lets go
  • Loading branch information
ardatan authored Dec 16, 2024
1 parent e12242b commit 10ba2c4
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 31 deletions.
7 changes: 7 additions & 0 deletions .changeset/plenty-trees-live.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@graphql-mesh/config': patch
'@graphql-mesh/utils': patch
---

Fix support for bundling environments like Next.js
Regression introduced in [#8082](https://github.com/ardatan/graphql-mesh/pull/8082)
49 changes: 26 additions & 23 deletions packages/legacy/config/src/process.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export async function processConfig(
const importCodes = new Set([
`import type { GetMeshOptions } from '@graphql-mesh/runtime';`,
`import type { YamlConfig } from '@graphql-mesh/types';`,
`import { defaultImportFn } from '@graphql-mesh/utils';`,
`import { defaultImportFn, handleImport } from '@graphql-mesh/utils';`,
]);
const codes = new Set([
`export const rawServeConfig: YamlConfig.Config['serve'] = ${JSON.stringify(
Expand All @@ -124,7 +124,7 @@ export async function processConfig(
if (config.require) {
await Promise.all(config.require.map(mod => importFn(mod)));
for (const mod of config.require) {
importCodes.add(`import '${mod}';`);
codes.add(`await import('${mod}');`);
}
}

Expand Down Expand Up @@ -208,11 +208,10 @@ export async function processConfig(
additionalPrefixes: additionalPackagePrefixes,
}).then(({ resolved: HandlerCtor, moduleName }) => {
if (options.generateCode) {
const handlerImportName = pascalCase(handlerName + '_Handler');
const handlerImportName = pascalCase(handlerVariableName);
codes.add(
`const ${handlerImportName} = await defaultImportFn(${JSON.stringify(moduleName)});`,
);
codes.add(`const ${handlerVariableName} = new ${handlerImportName}({
`const ${handlerImportName} = await import(${JSON.stringify(moduleName)}).then(handleImport);\n` +
`const ${handlerVariableName} = new ${handlerImportName}({
name: ${JSON.stringify(source.name)},
config: ${JSON.stringify(handlerConfig)},
baseDir,
Expand All @@ -221,7 +220,8 @@ export async function processConfig(
store: sourcesStore.child(${JSON.stringify(source.name)}),
logger: logger.child(${JSON.stringify(source.name)}),
importFn,
});`);
});`,
);
}
return new HandlerCtor({
name: source.name,
Expand All @@ -248,19 +248,19 @@ export async function processConfig(
});

if (options.generateCode) {
const transformImportName = pascalCase(transformName + '_Transform');
const transformImportName = pascalCase(transformsVariableName);
codes.add(
`const ${transformImportName} = await defaultImportFn(${JSON.stringify(moduleName)});`,
);
codes.add(`${transformsVariableName}[${transformIndex}] = new ${transformImportName}({
`const ${transformImportName} = await import(${JSON.stringify(moduleName)}).then(handleImport);\n` +
`${transformsVariableName}[${transformIndex}] = new ${transformImportName}({
apiName: ${JSON.stringify(source.name)},
config: ${JSON.stringify(transformConfig)},
baseDir,
cache,
pubsub,
importFn,
logger,
});`);
});`,
);
}

return new TransformCtor({
Expand Down Expand Up @@ -304,18 +304,19 @@ export async function processConfig(
});

if (options.generateCode) {
const transformImportName = pascalCase(transformName + '_Transform');
importCodes.add(`import ${transformImportName} from ${JSON.stringify(moduleName)};`);

codes.add(`transforms[${transformIndex}] = new (${transformImportName} as any)({
const transformImportName = pascalCase('Root_Transform_' + transformIndex);
codes.add(
`const ${transformImportName} = await import(${JSON.stringify(moduleName)}).then(handleImport);\n` +
`transforms[${transformIndex}] = new ${transformImportName}({
apiName: '',
config: ${JSON.stringify(transformConfig)},
baseDir,
cache,
pubsub,
importFn,
logger,
})`);
})`,
);
}
return new TransformLibrary({
apiName: '',
Expand All @@ -337,7 +338,7 @@ export async function processConfig(
if (options.generateCode) {
const importProp = `[${JSON.stringify(importName)}]`;
codes.add(
`const ${importName} = await defaultImportFn(${JSON.stringify(moduleName)}).then(m => m?.${importProp});`,
`const ${importName} = await import(${JSON.stringify(moduleName)}).then(m => m?.${importProp});`,
);
codes.add(
`additionalEnvelopPlugins[${pluginIndex}] = await ${importName}(${JSON.stringify(
Expand Down Expand Up @@ -367,7 +368,7 @@ export async function processConfig(
if (options.generateCode) {
const importName = camelCase('use_' + pluginName);
codes.add(
`const ${importName} = await defaultImportFn(${JSON.stringify(moduleName)});`,
`const ${importName} = await import(${JSON.stringify(moduleName)}).then(handleImport);`,
);
codes.add(`additionalEnvelopPlugins[${pluginIndex}] = await ${importName}({
...(${JSON.stringify(pluginConfig, null, 2)}),
Expand Down Expand Up @@ -548,7 +549,9 @@ export async function processConfig(

const mergerLoggerPrefix = `${mergerName}Merger`;
if (options.generateCode) {
codes.add(`const Merger = await defaultImportFn(${JSON.stringify(mergerModuleName)});`);
codes.add(
`const Merger = await import(${JSON.stringify(mergerModuleName)}).then(handleImport);`,
);
codes.add(`const merger = new Merger({
cache,
pubsub,
Expand All @@ -566,9 +569,9 @@ export async function processConfig(

if (config.additionalEnvelopPlugins) {
codes.add(
`const importedAdditionalEnvelopPlugins = await defaultImportFn(${JSON.stringify(
`const importedAdditionalEnvelopPlugins = await import(${JSON.stringify(
pathModule.join('..', config.additionalEnvelopPlugins).split('\\').join('/'),
)});`,
)}).then(handleImport);`,
);
const importedAdditionalEnvelopPlugins = await importFn(
pathModule.isAbsolute(config.additionalEnvelopPlugins)
Expand Down Expand Up @@ -649,7 +652,7 @@ export async function processConfig(
${[...documentHashMapCodes].join(',\n')}
}`);
codes.add(
`const usePersistedOperations = await defaultImportFn('@graphql-yoga/plugin-persisted-operations').then(m => m?.usePersistedOperations);`,
`const usePersistedOperations = await import('@graphql-yoga/plugin-persisted-operations').then(m => m?.usePersistedOperations);`,
);
codes.add(`additionalEnvelopPlugins.push(usePersistedOperations({
getPersistedOperation(key) {
Expand Down
10 changes: 5 additions & 5 deletions packages/legacy/config/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ export async function resolveCustomFetch({
if (!fetchConfig) {
return {
fetchFn: defaultFetch,
code: `const fetchFn = await defaultImportFn('@whatwg-node/fetch').then(m => m?.fetch || m);`,
code: `const fetchFn = await import('@whatwg-node/fetch').then(m => m?.fetch || m);`,
};
}
const { moduleName, resolved: fetchFn } = await getPackage<MeshFetch>({
Expand All @@ -132,7 +132,7 @@ export async function resolveCustomFetch({
});

const processedModuleName = moduleName.startsWith('.') ? path.join('..', moduleName) : moduleName;
const code = `const fetchFn = await defaultImportFn(${JSON.stringify(processedModuleName)}).then(m => m?.fetch || m);`;
const code = `const fetchFn = await import(${JSON.stringify(processedModuleName)}).then(m => m?.fetch || m);`;

return {
fetchFn,
Expand Down Expand Up @@ -173,7 +173,7 @@ export async function resolveCache(
logger,
});

const code = `const MeshCache = await defaultImportFn(${JSON.stringify(moduleName)});
const code = `const MeshCache = await import(${JSON.stringify(moduleName)}).then(handleImport);
const cache = new MeshCache({
...${JSON.stringify(config)},
importFn,
Expand Down Expand Up @@ -218,7 +218,7 @@ export async function resolvePubSub(

const pubsub = new PubSub(pubsubConfig);

const code = `const PubSub = await defaultImportFn(${JSON.stringify(moduleName)});
const code = `const PubSub = await import(${JSON.stringify(moduleName)}).then(handleImport);
const pubsub = new PubSub(${JSON.stringify(pubsubConfig)});`;

return {
Expand Down Expand Up @@ -280,7 +280,7 @@ export async function resolveLogger(
return {
logger,
importCode: ``,
code: `const logger = await defaultImportFn(${JSON.stringify(processedModuleName)});`,
code: `const logger = await import(${JSON.stringify(processedModuleName)}).then(handleImport);`,
};
}
const logger = new DefaultLogger(initialLoggerPrefix);
Expand Down
4 changes: 2 additions & 2 deletions packages/legacy/config/test/processConfig.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ describe('processConfig', () => {
let codesIteratorResult = codesIterator.next();
let includesCustomFetch;
while (!codesIteratorResult.done) {
if (codesIteratorResult.value.startsWith('const fetchFn = await defaultImportFn(')) {
if (codesIteratorResult.value.startsWith('const fetchFn = await import(')) {
meshConfigContent = meshConfigContent.concat(codesIteratorResult.value, '\n');
includesCustomFetch = true;
break;
Expand All @@ -42,7 +42,7 @@ describe('processConfig', () => {
// Adding export of fetch function so its resolution is actually attempted
meshConfigContent = meshConfigContent.concat('export { fetchFn };', '\n');

meshConfigContent = meshConfigContent.replace('await defaultImportFn', 'fakeImport');
meshConfigContent = meshConfigContent.replace('await import', 'fakeImport');
meshConfigContent =
'const fakeImport = m => require("@graphql-tools/utils").fakePromise(require(m));\n' +
meshConfigContent;
Expand Down
24 changes: 23 additions & 1 deletion packages/legacy/utils/src/defaultImportFn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,26 @@ function defaultImportFn(path: string): Promise<any> {
);
}

export { defaultImportFn };
function handleImport<T>(module: T): T {
let i = 0;
while ((module as any)?.default != null) {
if (i > 10 || module === (module as any).default) {
break;
}
module = (module as any).default;
i++;
}
if (typeof module === 'object' && module != null) {
const prototypeOfObject = Object.getPrototypeOf(module);
if (prototypeOfObject == null || prototypeOfObject === Object.prototype) {
const normalizedVal: Record<string, any> = {};
for (const key in module) {
normalizedVal[key] = module[key];
}
return normalizedVal as T;
}
}
return module;
}

export { defaultImportFn, handleImport };

0 comments on commit 10ba2c4

Please sign in to comment.