Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ESM build for the browser #2277

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions .babelrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,41 @@ module.exports = {
mjs: {
presets: [['@babel/preset-env', { modules: false }]],
},
esm: {
presets: [['@babel/preset-env', { modules: false }]],
plugins: [
function({ types }) {
return {
visitor: {
ImportDeclaration: function(path, state) {
if (!path.node.source) return;
var source = path.node.source.value;
if (source.match(/^\.{0,2}\//) && !source.endsWith('.es.js')) {
path.replaceWith(
types.importDeclaration(
path.node.specifiers,
types.stringLiteral(source + '.es.js'),
),
);
}
},
ExportNamedDeclaration: function(path, state) {
if (!path.node.source) return;
const source = path.node.source.value;
if (source.match(/^\.{0,2}\//) && !source.endsWith('.es.js')) {
path.replaceWith(
types.exportNamedDeclaration(
path.node.declaration,
path.node.specifiers,
types.stringLiteral(source + '.es.js'),
),
);
}
},
},
};
},
],
},
},
};
1 change: 1 addition & 0 deletions resources/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ function buildJSFile(filepath) {
copyFile(srcPath, destPath + '.flow');
writeFile(destPath, babelBuild(srcPath, 'cjs'));
writeFile(destPath.replace(/\.js$/, '.mjs'), babelBuild(srcPath, 'mjs'));
writeFile(destPath.replace(/\.js$/, '.es.js'), babelBuild(srcPath, 'esm'));
}

function buildPackageJSON() {
Expand Down
2 changes: 1 addition & 1 deletion src/execution/execute.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @flow strict

import { forEach, isCollection } from 'iterall';
import { forEach, isCollection } from '../jsutils/iterall';

import inspect from '../jsutils/inspect';
import memoize3 from '../jsutils/memoize3';
Expand Down
28 changes: 14 additions & 14 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ export {
// Validate GraphQL schema.
validateSchema,
assertValidSchema,
} from './type';
} from './type/index';

export type {
GraphQLType,
Expand Down Expand Up @@ -168,7 +168,7 @@ export type {
GraphQLScalarSerializer,
GraphQLScalarValueParser,
GraphQLScalarLiteralParser,
} from './type';
} from './type/index';

// Parse and operate on GraphQL language source files.
export {
Expand Down Expand Up @@ -204,7 +204,7 @@ export {
isTypeDefinitionNode,
isTypeSystemExtensionNode,
isTypeExtensionNode,
} from './language';
} from './language/index';

export type {
ParseOptions,
Expand Down Expand Up @@ -276,7 +276,7 @@ export type {
UnionTypeExtensionNode,
EnumTypeExtensionNode,
InputObjectTypeExtensionNode,
} from './language';
} from './language/index';

// Execute GraphQL queries.
export {
Expand All @@ -285,12 +285,12 @@ export {
defaultTypeResolver,
responsePathAsArray,
getDirectiveValues,
} from './execution';
} from './execution/index';

export type { ExecutionArgs, ExecutionResult } from './execution';
export type { ExecutionArgs, ExecutionResult } from './execution/index';

export { subscribe, createSourceEventStream } from './subscription';
export type { SubscriptionArgs } from './subscription';
export { subscribe, createSourceEventStream } from './subscription/index';
export type { SubscriptionArgs } from './subscription/index';

// Validate GraphQL documents.
export {
Expand Down Expand Up @@ -324,9 +324,9 @@ export {
ValuesOfCorrectTypeRule,
VariablesAreInputTypesRule,
VariablesInAllowedPositionRule,
} from './validation';
} from './validation/index';

export type { ValidationRule } from './validation';
export type { ValidationRule } from './validation/index';

// Create, format, and print GraphQL errors.
export {
Expand All @@ -335,9 +335,9 @@ export {
locatedError,
printError,
formatError,
} from './error';
} from './error/index';

export type { GraphQLFormattedError } from './error';
export type { GraphQLFormattedError } from './error/index';

// Utilities for operating on GraphQL type schema and parsed sources.
export {
Expand Down Expand Up @@ -406,7 +406,7 @@ export {
findDangerousChanges,
// Report all deprecated usage within a GraphQL document.
findDeprecatedUsages,
} from './utilities';
} from './utilities/index';

export type {
IntrospectionOptions,
Expand Down Expand Up @@ -434,4 +434,4 @@ export type {
BuildSchemaOptions,
BreakingChange,
DangerousChange,
} from './utilities';
} from './utilities/index';
3 changes: 2 additions & 1 deletion src/jsutils/instanceOf.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ declare function instanceOf(

// See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production
// See: https://webpack.js.org/guides/production/
export default process.env.NODE_ENV === 'production'
export default typeof process !== 'undefined' &&
process.env.NODE_ENV === 'production'
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lukejacksonn Can you please extract it into separate PR?
Also, please test that Webpack is able to recognize this pattern and switch to the production code.

Is it the last change we need to support ESM?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeh I can do that.. this is the last source modification required for ESM support (assuming that the mjs build now adds extensions to imports paths).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeh I can do that..

Great πŸ‘ Thanks a lot!

assuming that the mjs build now adds extensions to imports paths

You can see preview build here:
https://github.com/graphql/graphql-js/blob/npm/graphql.mjs
If you have time to try it here is the instruction:
https://github.com/graphql/graphql-js#want-to-ride-the-bleeding-edge

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @lukejacksonn,
Did you have a time to test this change with webpack?
I planning to release new RC so it would be great to also include this change.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @IvanGoncharov sorry this task completely slipped my mind. I have made a PR #2409 but am not so sure about what webpack specific config needs to be checked

? // eslint-disable-next-line no-shadow
function instanceOf(value: mixed, constructor: mixed) {
return value instanceof constructor;
Expand Down
168 changes: 168 additions & 0 deletions src/jsutils/iterall.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
// @flow strict

const SYMBOL = typeof Symbol === 'function' ? Symbol : undefined;
const SYMBOL_ITERATOR = SYMBOL && SYMBOL.iterator;
const SYMBOL_ASYNC_ITERATOR = SYMBOL && SYMBOL.asyncIterator;

function AsyncFromSyncIterator(iterator) {
this._i = iterator;
}

AsyncFromSyncIterator.prototype[$$asyncIterator] = function() {
return this;
};

AsyncFromSyncIterator.prototype.next = function() {
const step = this._i.next();
return Promise.resolve(step.value).then(value => ({
value,
done: step.done,
}));
};

function ArrayLikeIterator(obj) {
this._o = obj;
this._i = 0;
}

ArrayLikeIterator.prototype[$$iterator] = function() {
return this;
};

ArrayLikeIterator.prototype.next = function() {
if (this._o === undefined || this._i >= this._o.length) {
this._o = undefined;
return { value: undefined, done: true };
}
return { value: this._o[this._i++], done: false };
};

export const $$iterator = SYMBOL_ITERATOR || '@@iterator';

export function isIterable(obj) {
return Boolean(getIteratorMethod(obj));
}

export function isArrayLike(obj) {
const length = obj != null && obj.length;
return typeof length === 'number' && length >= 0 && length % 1 === 0;
}

export function isCollection(obj) {
return Object(obj) === obj && (isArrayLike(obj) || isIterable(obj));
}

export function getIterator(iterable) {
const method = getIteratorMethod(iterable);
if (method) {
return method.call(iterable);
}
}

export function getIteratorMethod(iterable) {
if (iterable != null) {
const method =
(SYMBOL_ITERATOR && iterable[SYMBOL_ITERATOR]) || iterable['@@iterator'];
if (typeof method === 'function') {
return method;
}
}
}

export function createIterator(collection) {
if (collection != null) {
const iterator = getIterator(collection);
if (iterator) {
return iterator;
}
if (isArrayLike(collection)) {
return new ArrayLikeIterator(collection);
}
}
}

export function forEach(collection, callback, thisArg) {
if (collection != null) {
if (typeof collection.forEach === 'function') {
return collection.forEach(callback, thisArg);
}
let i = 0;
const iterator = getIterator(collection);
if (iterator) {
let step;
while (!(step = iterator.next()).done) {
callback.call(thisArg, step.value, i++, collection);
if (i > 9999999) {
throw new TypeError('Near-infinite iteration.');
}
}
} else if (isArrayLike(collection)) {
for (; i < collection.length; i++) {
if (Object.prototype.hasOwnProperty.call(collection, i)) {
callback.call(thisArg, collection[i], i, collection);
}
}
}
}
}

export const $$asyncIterator = SYMBOL_ASYNC_ITERATOR || '@@asyncIterator';

export const isAsyncIterable = obj => Boolean(getAsyncIteratorMethod(obj));

export const getAsyncIterator = asyncIterable => {
const method = getAsyncIteratorMethod(asyncIterable);
if (method) {
return method.call(asyncIterable);
}
};

export const getAsyncIteratorMethod = asyncIterable => {
if (asyncIterable != null) {
const method =
(SYMBOL_ASYNC_ITERATOR && asyncIterable[SYMBOL_ASYNC_ITERATOR]) ||
asyncIterable['@@asyncIterator'];
if (typeof method === 'function') {
return method;
}
}
};

export const createAsyncIterator = source => {
if (source != null) {
const asyncIterator = getAsyncIterator(source);
if (asyncIterator) {
return asyncIterator;
}
const iterator = createIterator(source);
if (iterator) {
return new AsyncFromSyncIterator(iterator);
}
}
};

export const forAwaitEach = (source, callback, thisArg) => {
const asyncIterator = createAsyncIterator(source);
if (asyncIterator) {
let i = 0;
return new Promise((resolve, reject) => {
function next() {
asyncIterator
.next()
.then(step => {
if (!step.done) {
Promise.resolve(callback.call(thisArg, step.value, i++, source))
.then(next)
.catch(reject);
} else {
resolve();
}
return null;
})
.catch(reject);
return null;
}
next();
});
}
};
2 changes: 1 addition & 1 deletion src/subscription/__tests__/eventEmitterAsyncIterator.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @flow strict

import type EventEmitter from 'events';
import { $$asyncIterator } from 'iterall';
import { $$asyncIterator } from '../../jsutils/iterall';

/**
* Create an AsyncIterator from an EventEmitter. Useful for mocking a
Expand Down
2 changes: 1 addition & 1 deletion src/subscription/asyncIteratorReject.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @flow strict

import { $$asyncIterator } from 'iterall';
import { $$asyncIterator } from '../jsutils/iterall';

/**
* Given an error, returns an AsyncIterable which will fail with that error.
Expand Down
2 changes: 1 addition & 1 deletion src/subscription/mapAsyncIterator.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @flow strict

import { $$asyncIterator, getAsyncIterator } from 'iterall';
import { $$asyncIterator, getAsyncIterator } from '../jsutils/iterall';

import { type PromiseOrValue } from '../jsutils/PromiseOrValue';

Expand Down
2 changes: 1 addition & 1 deletion src/subscription/subscribe.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @flow strict

import { isAsyncIterable } from 'iterall';
import { isAsyncIterable } from '../jsutils/iterall';

import inspect from '../jsutils/inspect';
import { addPath, pathToArray } from '../jsutils/Path';
Expand Down
2 changes: 1 addition & 1 deletion src/utilities/astFromValue.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @flow strict

import { forEach, isCollection } from 'iterall';
import { forEach, isCollection } from '../jsutils/iterall';

import objectValues from '../polyfills/objectValues';

Expand Down
2 changes: 1 addition & 1 deletion src/utilities/coerceInputValue.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @flow strict

import { forEach, isCollection } from 'iterall';
import { forEach, isCollection } from '../jsutils/iterall';

import objectValues from '../polyfills/objectValues';

Expand Down