Skip to content

Commit

Permalink
demo imports handling instanceOf
Browse files Browse the repository at this point in the history
  • Loading branch information
yaacovCR committed Oct 8, 2024
1 parent 13e171c commit df62aa2
Show file tree
Hide file tree
Showing 13 changed files with 200 additions and 129 deletions.
6 changes: 0 additions & 6 deletions integrationTests/ts/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,6 @@
"dependencies": {
"graphql": "file:../graphql.tgz",
"graphql-esm": "file:../graphql-esm.tgz",
"typescript-4.4": "npm:[email protected]",
"typescript-4.5": "npm:[email protected]",
"typescript-4.6": "npm:[email protected]",
"typescript-4.7": "npm:[email protected]",
"typescript-4.8": "npm:[email protected]",
"typescript-4.9": "npm:[email protected]",
"typescript-5.0": "npm:[email protected]",
"typescript-5.1": "npm:[email protected]",
"typescript-5.2": "npm:[email protected]",
Expand Down
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,12 @@
"engines": {
"node": "^16.19.0 || ^18.14.0 || >=19.7.0"
},
"imports": {
"#instanceOf": {
"development": "./src/jsutils/instanceOfForDevelopment.ts",
"default": "./src/jsutils/instanceOf.ts"
}
},
"scripts": {
"preversion": "bash -c '. ./resources/checkgit.sh && npm ci --ignore-scripts'",
"version": "node --loader ts-node/esm resources/gen-version.ts && npm test && git add src/version.ts",
Expand Down
22 changes: 18 additions & 4 deletions resources/build-deno.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import ts from 'typescript';
import { inlineInvariant } from './inline-invariant.ts';
import {
prettify,
readPackageJSON,
readTSConfig,
showDirStats,
writeGeneratedFile,
Expand All @@ -14,12 +15,25 @@ import {
fs.rmSync('./denoDist', { recursive: true, force: true });
fs.mkdirSync('./denoDist');

const tsProgram = ts.createProgram(['src/index.ts'], readTSConfig());
for (const sourceFile of tsProgram.getSourceFiles()) {
if (
const packageJSON = readPackageJSON();
const internalImports = Object.keys(packageJSON.imports).map((internal) =>
internal.replace(/^#/, ''),
);

// ts.Program methods think imports map implies external library
function isExternalFile(sourceFile: ts.SourceFile): boolean {
if (internalImports.includes(path.basename(sourceFile.fileName, '.ts'))) {
return false;
}
return (
tsProgram.isSourceFileFromExternalLibrary(sourceFile) ||
tsProgram.isSourceFileDefaultLibrary(sourceFile)
) {
);
}

const tsProgram = ts.createProgram(['src/index.ts'], readTSConfig());
for (const sourceFile of tsProgram.getSourceFiles()) {
if (isExternalFile(sourceFile)) {
continue;
}

Expand Down
28 changes: 28 additions & 0 deletions resources/build-npm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import ts from 'typescript';

import { changeExtensionInImportPaths } from './change-extension-in-import-paths.ts';
import { inlineInvariant } from './inline-invariant.ts';
import type { ImportsMap, PathOrConditionalPath } from './utils.ts';
import {
prettify,
readPackageJSON,
Expand Down Expand Up @@ -102,12 +103,22 @@ async function buildPackage(outDir: string, isESMOnly: boolean): Promise<void> {
packageJSON.exports['./*.js'] = './*.ts';
packageJSON.exports['./*'] = './*.ts';

rewriteImports(packageJSON.imports, (value: string) =>
replaceImportPath(value, '.js'),
);

packageJSON.publishConfig.tag += '-esm';
packageJSON.version += '+esm';
} else {
delete packageJSON.type;
packageJSON.main = 'index';
packageJSON.module = 'index.mjs';

rewriteImports(packageJSON.imports, (value: string) => ({
import: replaceImportPath(value, '.mjs'),
default: replaceImportPath(value, '.js'),
}));

emitTSFiles({ outDir, module: 'commonjs', extension: '.js' });
emitTSFiles({ outDir, module: 'es2020', extension: '.mjs' });
}
Expand All @@ -121,6 +132,23 @@ async function buildPackage(outDir: string, isESMOnly: boolean): Promise<void> {
writeGeneratedFile(packageJsonPath, prettified);
}

function replaceImportPath(value: string, extension: string) {
return value.replace(/\/src\//g, '/').replace(/\.ts$/, extension);
}

function rewriteImports(
imports: ImportsMap,
replacer: (value: string) => PathOrConditionalPath,
) {
for (const [key, value] of Object.entries(imports)) {
if (typeof value === 'string') {
imports[key] = replacer(value);
continue;
}
rewriteImports(value, replacer);
}
}

// Based on https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#getting-the-dts-from-a-javascript-file
function emitTSFiles(options: {
outDir: string;
Expand Down
7 changes: 7 additions & 0 deletions resources/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,12 @@ export function writeGeneratedFile(filepath: string, body: string): void {
fs.writeFileSync(filepath, body);
}

export type PathOrConditionalPath = string | { [condition: string]: string };

export interface ImportsMap {
[path: string]: PathOrConditionalPath;
}

interface PackageJSON {
description: string;
version: string;
Expand All @@ -235,6 +241,7 @@ interface PackageJSON {
scripts?: { [name: string]: string };
type?: string;
exports: { [path: string]: string };
imports: ImportsMap;
types?: string;
typesVersions: { [ranges: string]: { [path: string]: Array<string> } };
devDependencies?: { [name: string]: string };
Expand Down
62 changes: 1 addition & 61 deletions src/jsutils/__tests__/instanceOf-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ describe('instanceOf', () => {
it('do not throw on values without prototype', () => {
class Foo {
get [Symbol.toStringTag]() {
/* c8 ignore next 2 */
return 'Foo';
}
}
Expand All @@ -15,65 +16,4 @@ describe('instanceOf', () => {
expect(instanceOf(null, Foo)).to.equal(false);
expect(instanceOf(Object.create(null), Foo)).to.equal(false);
});

it('detect name clashes with older versions of this lib', () => {
function oldVersion() {
class Foo {}
return Foo;
}

function newVersion() {
class Foo {
get [Symbol.toStringTag]() {
return 'Foo';
}
}
return Foo;
}

const NewClass = newVersion();
const OldClass = oldVersion();
expect(instanceOf(new NewClass(), NewClass)).to.equal(true);
expect(() => instanceOf(new OldClass(), NewClass)).to.throw();
});

it('allows instances to have share the same constructor name', () => {
function getMinifiedClass(tag: string) {
class SomeNameAfterMinification {
get [Symbol.toStringTag]() {
return tag;
}
}
return SomeNameAfterMinification;
}

const Foo = getMinifiedClass('Foo');
const Bar = getMinifiedClass('Bar');
expect(instanceOf(new Foo(), Bar)).to.equal(false);
expect(instanceOf(new Bar(), Foo)).to.equal(false);

const DuplicateOfFoo = getMinifiedClass('Foo');
expect(() => instanceOf(new DuplicateOfFoo(), Foo)).to.throw();
expect(() => instanceOf(new Foo(), DuplicateOfFoo)).to.throw();
});

it('fails with descriptive error message', () => {
function getFoo() {
class Foo {
get [Symbol.toStringTag]() {
return 'Foo';
}
}
return Foo;
}
const Foo1 = getFoo();
const Foo2 = getFoo();

expect(() => instanceOf(new Foo1(), Foo2)).to.throw(
/^Cannot use Foo "{}" from another module or realm./m,
);
expect(() => instanceOf(new Foo2(), Foo1)).to.throw(
/^Cannot use Foo "{}" from another module or realm./m,
);
});
});
83 changes: 83 additions & 0 deletions src/jsutils/__tests__/instanceOfForDevelopment-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { expect } from 'chai';
import { describe, it } from 'mocha';

import { instanceOf as instanceOfForDevelopment } from '../instanceOfForDevelopment.ts';

describe('instanceOfForDevelopment', () => {
it('do not throw on values without prototype', () => {
class Foo {
get [Symbol.toStringTag]() {
return 'Foo';
}
}

expect(instanceOfForDevelopment(true, Foo)).to.equal(false);
expect(instanceOfForDevelopment(null, Foo)).to.equal(false);
expect(instanceOfForDevelopment(Object.create(null), Foo)).to.equal(false);
});

it('detect name clashes with older versions of this lib', () => {
function oldVersion() {
class Foo {}
return Foo;
}

function newVersion() {
class Foo {
get [Symbol.toStringTag]() {
return 'Foo';
}
}
return Foo;
}

const NewClass = newVersion();
const OldClass = oldVersion();
expect(instanceOfForDevelopment(new NewClass(), NewClass)).to.equal(true);
expect(() => instanceOfForDevelopment(new OldClass(), NewClass)).to.throw();
});

it('allows instances to have share the same constructor name', () => {
function getMinifiedClass(tag: string) {
class SomeNameAfterMinification {
get [Symbol.toStringTag]() {
return tag;
}
}
return SomeNameAfterMinification;
}

const Foo = getMinifiedClass('Foo');
const Bar = getMinifiedClass('Bar');
expect(instanceOfForDevelopment(new Foo(), Bar)).to.equal(false);
expect(instanceOfForDevelopment(new Bar(), Foo)).to.equal(false);

const DuplicateOfFoo = getMinifiedClass('Foo');
expect(() =>
instanceOfForDevelopment(new DuplicateOfFoo(), Foo),
).to.throw();
expect(() =>
instanceOfForDevelopment(new Foo(), DuplicateOfFoo),
).to.throw();
});

it('fails with descriptive error message', () => {
function getFoo() {
class Foo {
get [Symbol.toStringTag]() {
return 'Foo';
}
}
return Foo;
}
const Foo1 = getFoo();
const Foo2 = getFoo();

expect(() => instanceOfForDevelopment(new Foo1(), Foo2)).to.throw(
/^Cannot use Foo "{}" from another module or realm./m,
);
expect(() => instanceOfForDevelopment(new Foo2(), Foo1)).to.throw(
/^Cannot use Foo "{}" from another module or realm./m,
);
});
});
57 changes: 3 additions & 54 deletions src/jsutils/instanceOf.ts
Original file line number Diff line number Diff line change
@@ -1,57 +1,6 @@
import { inspect } from './inspect.ts';

/* c8 ignore next 3 */
const isProduction =
globalThis.process != null &&
// eslint-disable-next-line no-undef
process.env.NODE_ENV === 'production';

/**
* A replacement for instanceof which includes an error warning when multi-realm
* constructors are detected.
* See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production
* See: https://webpack.js.org/guides/production/
*/
export const instanceOf: (value: unknown, constructor: Constructor) => boolean =
/* c8 ignore next 6 */
// FIXME: https://github.com/graphql/graphql-js/issues/2317
isProduction
? function instanceOf(value: unknown, constructor: Constructor): boolean {
return value instanceof constructor;
}
: function instanceOf(value: unknown, constructor: Constructor): boolean {
if (value instanceof constructor) {
return true;
}
if (typeof value === 'object' && value !== null) {
// Prefer Symbol.toStringTag since it is immune to minification.
const className = constructor.prototype[Symbol.toStringTag];
const valueClassName =
// We still need to support constructor's name to detect conflicts with older versions of this library.
Symbol.toStringTag in value
? value[Symbol.toStringTag]
: value.constructor?.name;
if (className === valueClassName) {
const stringifiedValue = inspect(value);
throw new Error(
`Cannot use ${className} "${stringifiedValue}" from another module or realm.
Ensure that there is only one instance of "graphql" in the node_modules
directory. If different versions of "graphql" are the dependencies of other
relied on modules, use "resolutions" to ensure only one version is installed.
https://yarnpkg.com/en/docs/selective-version-resolutions
Duplicate "graphql" modules cannot be used at the same time since different
versions may have different capabilities and behavior. The data from one
version used in the function from another could produce confusing and
spurious results.`,
);
}
}
return false;
};

export function instanceOf(value: unknown, constructor: Constructor): boolean {
return value instanceof constructor;
}
interface Constructor extends Function {
prototype: {
[Symbol.toStringTag]: string;
Expand Down
Loading

0 comments on commit df62aa2

Please sign in to comment.