Skip to content

Commit

Permalink
[@graphiql/toolkit] do not include require statements in ESM build,…
Browse files Browse the repository at this point in the history
… include `import` in esm and `require` in cjs builds (#3747)

* aa

* fix lint

* fix vitest
  • Loading branch information
dimaMachina authored Aug 23, 2024
1 parent 2ad4e75 commit 21c4409
Show file tree
Hide file tree
Showing 7 changed files with 42 additions and 25 deletions.
7 changes: 7 additions & 0 deletions .changeset/gold-ears-knock.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@graphiql/toolkit': minor
---

do not include `require` statements in ESM build, include `import` in esm and `require` in cjs builds

make `getWsFetcher`, `createWebsocketsFetcherFromUrl` async
26 changes: 14 additions & 12 deletions packages/graphiql-toolkit/src/create-fetcher/__tests__/lib.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { createClient } from 'graphql-ws';

import { SubscriptionClient } from 'subscriptions-transport-ws';

const exampleWithSubscription = /* GraphQL */ parse(`
const exampleWithSubscription = parse(/* GraphQL */ `
subscription Example {
example
}
Expand Down Expand Up @@ -47,9 +47,9 @@ describe('createWebsocketsFetcherFromUrl', () => {
jest.resetAllMocks();
});

it('creates a websockets client using provided url', () => {
it('creates a websockets client using provided url', async () => {
createClient.mockReturnValue(true);
createWebsocketsFetcherFromUrl('wss://example.com');
await createWebsocketsFetcherFromUrl('wss://example.com');
// @ts-ignore
expect(createClient.mock.calls[0][0]).toEqual({ url: 'wss://example.com' });
});
Expand All @@ -66,39 +66,41 @@ describe('getWsFetcher', () => {
afterEach(() => {
jest.resetAllMocks();
});
it('provides an observable wsClient when custom wsClient option is provided', () => {
it('provides an observable wsClient when custom wsClient option is provided', async () => {
createClient.mockReturnValue(true);
getWsFetcher({ url: '', wsClient: true });
await getWsFetcher({ url: '', wsClient: true });
// @ts-ignore
expect(createClient.mock.calls).toHaveLength(0);
});
it('creates a subscriptions-transports-ws observable when custom legacyClient option is provided', () => {
it('creates a subscriptions-transports-ws observable when custom legacyClient option is provided', async () => {
createClient.mockReturnValue(true);
getWsFetcher({ url: '', legacyClient: true });
await getWsFetcher({ url: '', legacyClient: true });
// @ts-ignore
expect(createClient.mock.calls).toHaveLength(0);
expect(SubscriptionClient.mock.calls).toHaveLength(0);
});

it('if subscriptionsUrl is provided, create a client on the fly', () => {
it('if subscriptionsUrl is provided, create a client on the fly', async () => {
createClient.mockReturnValue(true);
getWsFetcher({ url: '', subscriptionUrl: 'wss://example' });
await getWsFetcher({ url: '', subscriptionUrl: 'wss://example' });
expect(createClient.mock.calls[0]).toEqual([
{ connectionParams: {}, url: 'wss://example' },
]);
expect(SubscriptionClient.mock.calls).toHaveLength(0);
});
});

describe('missing graphql-ws dependency', () => {
it('should throw a nice error', () => {
describe('missing `graphql-ws` dependency', () => {
it('should throw a nice error', async () => {
jest.resetModules();
jest.doMock('graphql-ws', () => {
// eslint-disable-next-line no-throw-literal
throw { code: 'MODULE_NOT_FOUND' };
});

expect(() => createWebsocketsFetcherFromUrl('wss://example.com')).toThrow(
await expect(
createWebsocketsFetcherFromUrl('wss://example.com'),
).rejects.toThrow(
/You need to install the 'graphql-ws' package to use websockets when passing a 'subscriptionUrl'/,
);
});
Expand Down
4 changes: 2 additions & 2 deletions packages/graphiql-toolkit/src/create-fetcher/createFetcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export function createGraphiQLFetcher(options: CreateFetcherOptions): Fetcher {
? createMultipartFetcher(options, httpFetch)
: simpleFetcher;

return (graphQLParams, fetcherOpts) => {
return async (graphQLParams, fetcherOpts) => {
if (graphQLParams.operationName === 'IntrospectionQuery') {
return (options.schemaFetcher || simpleFetcher)(
graphQLParams,
Expand All @@ -41,7 +41,7 @@ export function createGraphiQLFetcher(options: CreateFetcherOptions): Fetcher {
)
: false;
if (isSubscription) {
const wsFetcher = getWsFetcher(options, fetcherOpts);
const wsFetcher = await getWsFetcher(options, fetcherOpts);

if (!wsFetcher) {
throw new Error(
Expand Down
19 changes: 10 additions & 9 deletions packages/graphiql-toolkit/src/create-fetcher/lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,16 @@ export const createSimpleFetcher =
return data.json();
};

export const createWebsocketsFetcherFromUrl = (
export async function createWebsocketsFetcherFromUrl(
url: string,
connectionParams?: ClientOptions['connectionParams'],
) => {
): Promise<Fetcher | void> {
let wsClient;
try {
const { createClient } = require('graphql-ws') as {
createClient: typeof createClientType;
};
const { createClient } =
process.env.USE_IMPORT === 'false'
? (require('graphql-ws') as { createClient: typeof createClientType })
: await import('graphql-ws');

// TODO: defaults?
wsClient = createClient({ url, connectionParams });
Expand All @@ -90,7 +91,7 @@ export const createWebsocketsFetcherFromUrl = (
// eslint-disable-next-line no-console
console.error(`Error creating websocket client for ${url}`, err);
}
};
}

/**
* Create ws/s fetcher using provided wsClient implementation
Expand Down Expand Up @@ -177,10 +178,10 @@ export const createMultipartFetcher = (
/**
* If `wsClient` or `legacyClient` are provided, then `subscriptionUrl` is overridden.
*/
export const getWsFetcher = (
export async function getWsFetcher(
options: CreateFetcherOptions,
fetcherOpts?: FetcherOpts,
): Fetcher | void => {
): Promise<Fetcher | void> {
if (options.wsClient) {
return createWebsocketsFetcherFromClient(options.wsClient);
}
Expand All @@ -194,4 +195,4 @@ export const getWsFetcher = (
if (legacyWebsocketsClient) {
return createLegacyWebsocketsFetcher(legacyWebsocketsClient);
}
};
}
2 changes: 1 addition & 1 deletion packages/graphiql-toolkit/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"compilerOptions": {
"target": "es2016",
"target": "es2017",
"module": "ESNext",
"declaration": true,
"noEmit": true,
Expand Down
7 changes: 7 additions & 0 deletions packages/graphiql-toolkit/tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const opts: Options = {
bundle: false,
clean: true,
dts: true,
minifySyntax: true,
};

export default defineConfig([
Expand All @@ -13,10 +14,16 @@ export default defineConfig([
format: 'esm',
outDir: 'dist/esm',
outExtension: () => ({ js: '.js' }),
env: {
USE_IMPORT: 'true',
},
},
{
...opts,
format: 'cjs',
outDir: 'dist/cjs',
env: {
USE_IMPORT: 'false',
},
},
]);
2 changes: 1 addition & 1 deletion packages/monaco-graphql/test/monaco-editor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ describe('monaco-editor', () => {
// expect(lines[1]).toMatch(' building for production...');
// expect(lines[2]).toBe('transforming...');
expect(lines[3]).toMatch(
`✓ ${parseInt(version, 10) > 16 ? 857 : 843} modules transformed.`,
`✓ ${parseInt(version, 10) > 16 ? 862 : 843} modules transformed.`,
);
// expect(lines[4]).toBe('rendering chunks...');
// expect(lines[5]).toBe('computing gzip size...');
Expand Down

0 comments on commit 21c4409

Please sign in to comment.