Giter Site home page Giter Site logo

invariant-packages's Introduction

invariant-packages CI

Packages for working with invariant(condition, message) assertions.

⚠️ If you came here because of an Apollo Client error message like the following:

Invariant Violation: Invariant Violation: 27 (see https://github.com/apollographql/invariant-packages)

you should consult the file node_modules/@apollo/client/invariantErrorCodes.js for more details about the numbered invariant:

  27: {
    file: "@apollo/client/react/context/ApolloConsumer.js",

    node: invariant(context && context.client, 'Could not find "client" in the context of ApolloConsumer. ' +
        'Wrap the root component in an <ApolloProvider>.')
  },

The exact contents of the invariantErrorCodes.js file can change between @apollo/client releases, so make sure you're consulting the same version of @apollo/client that threw the error. Note also that the file is generated during the release process, and is not checked into the https://github.com/apollographql/apollo-client repository. This file was first included in @apollo/[email protected].

Usage

This repository is home to the ts-invariant and rollup-plugin-invariant packages.

Runtime usage (ts-invariant)

The ts-invariant package exports the following utilities:

invariant(condition: any, message: string)

Similar to the the invariant function used by React, this function throws an InvariantError with the given message if the condition argument evaluates to a falsy value.

invariant.error(...args: any[])

Equivalent to calling console.error(...args).

invariant.warn(...args: any[])

Equivalent to calling console.warn(...args).

new InvariantError(message: string)

The Error subclass thrown by failed invariant calls.

Build-time usage (rollup-plugin-invariant)

If you're using Rollup to bundle your code, or using a library that was bundled using Rollup and rollup-plugin-invariant, then the above utilities will be transformed so that minifiers can strip the long error strings from your production bundle.

Calls of the form invariant(condition, message) are transformed to

process.env.NODE_ENV === 'production'
  ? invariant(condition)
  : invariant(condition, message)

Expressions of the form new InvariantError(message) are transformed to

process.env.NODE_ENV === 'production'
  ? new InvariantError()
  : new InvariantError(message)

Although this looks like more code, it enables minifiers to prune the unreached branch of the conditional expression based on the value of process.env.NODE_ENV, so only the shorter version remains in production.

Configuration

Here's how you might configure Rollup to use rollup-plugin-invariant and also minify the transformed code effectively:

// rollup.config.js

import invariantPlugin from "rollup-plugin-invariant";
import { terser as minify } from "rollup-plugin-terser";

export default [{
  input: "src/index.js",
  output: {
    file: "lib/bundle.js",
    format: "cjs"
  },
  plugins: [
    invariantPlugin({
      errorCodes: true,
    }),
  ],
}, {
  input: "lib/bundle.js",
  output: {
    file: "lib/bundle.min.js",
    format: "cjs"
  },
  plugins: [
    minify({
      compress: {
        global_defs: {
          "@process.env.NODE_ENV": JSON.stringify("production"),
        },
      },
    }),
  ],
}];

Error codes

If you create an instance of the plugin with the { errorCodes: true } option, message strings will be replaced with numeric error codes instead of simply disappearing, so invariant(condition, message) becomes

process.env.NODE_ENV === 'production'
  ? invariant(condition, <error code>)
  : invariant(condition, message)

and new InvariantError(message) becomes

process.env.NODE_ENV === 'production'
  ? new InvariantError(<error code>)
  : new InvariantError(message)

With errorCodes enabled, InvariantError messages will be displayed as

Invariant Violation: <error code> (see https://github.com/apollographql/invariant-packages)

For example, if you see an error of the form

Invariant Violation: Invariant Violation: 38 (see https://github.com/apollographql/invariant-packages)

you should consult the file node_modules/@apollo/client/invariantErrorCodes.js for more details about the numbered invariant:

  38: {
    file: "@apollo/client/utilities/graphql/directives.js",
    node: invariant(evaledValue !== void 0, "Invalid variable referenced in @" + directive.name.value + " directive.")
  },

The dynamic value of directive.name.value will not be provided because those arguments are pruned in production (leaving just invariant(evaledValue !== void)), but this information should allow you to set a breakpoint in the node_modules/@apollo/client/utilities/graphql/directives.js file to investigate further.

The exact contents of the invariantErrorCodes.js file can change between @apollo/client releases, so make sure you're consulting the same version of @apollo/client that threw the error. Note also that the file is generated during the release process, and is not checked into the https://github.com/apollographql/apollo-client repository. This file was first included in @apollo/[email protected].

Automatic process import

If you create an instance of the plugin with the { importProcessPolyfill: true } option, any import ... from "ts-invariant" declarations will have process added to the list of imported identifiers.

When ts-invariant is used in a JS environment where process is globally defined, the process export will simply be the same as that global object. Otherwise, it will be an object of the shape { env: {} }, to ensure process.env.NODE_ENV is safe to evaluate at runtime, in case it has not been replaced by the minifier.

invariant-packages's People

Contributors

benjamn avatar benmccann avatar dependabot[bot] avatar fila90 avatar hwillson avatar michaeldeboey avatar phryneas avatar powerkiki avatar rafgraph avatar shevchenkonik avatar svc-secops avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

invariant-packages's Issues

Typescript nodenext module issue

i'm getting the error Assertions require every name in the call target to be declared with an explicit type annotation.. i'm using typescript 4.7.3 with module: 'nodenext'


const { invariant } = await import('ts-invariant');
const { merge } = await import('merge-anything');

export const ethersOverride = (context: IEthersContext, options: TOverride): Readonly<TEthersAdaptor> => {
  // check if there is an override
  if (options.adaptorEnabled) {
    invariant(
      options.alternateContextKey == null,
      'You cannot use both contextOverride and contextKey at the same time'
    );

    return options.adaptor ?? {};
    Í;
  }

  return asEthersAdaptor(context);
};

2022 06 15-07 33-Visual Studio Code hookHelpers ts — eth-hooks

`process = { env: {} }` leaks into global namespace

tl;dr is that an exports.process = { env: {} }; call is being made (likely from here), which causes a process.env variable to appear as seen below.

image

This lead to a really rough debug session. Our app uses musickit.js from Apple, which failed to identify what type of module to return since process.env existed.

We ran into this by installing pubnub/react, but I suspect many others will in the future

Package.json deps in case they help. We're using vite and rollup :)

{
  "dependencies": {
    "@react-hook/debounce": "^3.0.0",
    "howler": "^2.2.1",
    "jotai": "^0.14.0",
    "pubnub": "^4.29.11",
    "pubnub-react": "^2.1.0",
    "react": "^17.0.0",
    "react-dnd": "^11.1.3",
    "react-dnd-html5-backend": "^11.1.3",
    "react-dom": "^17.0.0",
    "react-double-marquee": "^1.1.0",
    "react-ga": "^3.3.0",
    "react-is": "^17.0.2",
    "react-json-view": "^1.21.1",
    "react-phone-input-2": "^2.14.0",
    "react-query": "^3.8.2",
    "socket.io-client": "^4.0.0",
    "styled-components": "^5.2.3",
    "uuid": "^8.3.2",
    "wouter": "^2.7.3",
    "zustand": "^3.3.3"
  },
  "devDependencies": {
    "@types/howler": "^2.2.2",
    "@types/pubnub": "^4.29.1",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "@types/react-phone-number-input": "^3.0.6",
    "@types/styled-components": "^5.1.7",
    "@types/uuid": "^8.3.0",
    "@typescript-eslint/eslint-plugin": "^4.19.0",
    "@typescript-eslint/parser": "^4.19.0",
    "@vercel/node": "^1.9.1",
    "@vitejs/plugin-react-refresh": "^1.3.1",
    "esbuild": "^0.8.47",
    "eslint": "^7.23.0",
    "eslint-plugin-prettier": "^3.3.1",
    "node-fetch": "^2.6.1",
    "prettier": "2.2.1",
    "typescript": "^4.0.0",
    "vite": "^2.1.5"
  }
}

Incompatibility since version 0.5.1 with commonjs modules

Problem:

I am building an executable from my Apollo application using the framework pkg. Since version 0.5.1 of ts-invariant, I get the following error message when launching the executable:

#> .\program.exe start
pkg/prelude/bootstrap.js:1244
throw error;
^
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /snapshot/program/node_modules/@ungap/global-this/cjs/index.js
require() of ES modules is not supported.
require() of /snapshot/program/node_modules/@ungap/global-this/cjs/index.js from /snapshot/program/node_modules/ts-invariant/lib/invariant.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /snapshot/program/node_modules/@ungap/global-this/package.json.

Interpretation:

I know that I don't get support for the framework pkg here. However, I am not sure if this is just a module integration error.

Unfortunately I cannot work with the current version of @apollo/client (with ts-invariant as dependency).

I would be very grateful for help with this problem.

Workaround:

I set the exact versions of @apollo/client and ts-invariant:

  "dependencies": {
    ...
    "@apollo/client": "3.3.3",
    "ts-invariant": "0.5.1",
    ...
  }

Parentheses added inside href in error message (Nextjs) creating broken links

This might be a better issue for Nextjs, but I'm gonna leave it here if its of any interest. Feel free to close the issue if its irrelevant.

I get this error message from time to time:
image
(Mostly when graphql-generator hasn't generated the types yet, but that's no the issue here).

The link unfortunately gets parsed incorrectly by (I'm guessing) the Nextjs error modal. The last parenthesis is added inside the href of the a tag:
<a href="https://github.com/apollographql/invariant-packages)">https://github.com/apollographql/invariant-packages)</a>

Its not a big deal, but could probably fixed by adding a space, getting Nextjs to fix it or just let it be. It was just jarring to click the link and get a 404 from github.

ts-invariant 'cant resolve imported dependency process/browser' -- conflict with webpack 5 typical polyfill

this package appears to conflict with a seemingly standard polyfill in webpack5:

        cfg.resolve.alias = {
          ...cfg.resolve.alias,
          process: 'process/browser',
        }
        cfg.plugins = [
          ...cfg.plugins,
          new webpack.ProvidePlugin({
            Buffer: ['buffer', 'Buffer'],
            process: 'process/browser',
          }),
        ]

resulting in this error:

/node_modules/@apollo/client/node_modules/ts-invariant/process/index.js
Module not found: Can't resolve imported dependency "process/browser"
Did you forget to install it? You can run: yarn add process/browser

eg, https://stackoverflow.com/questions/65018431/webpack-5-uncaught-referenceerror-process-is-not-defined

Not sure how process is working in this instance, but a likely fix is just to rename the folder for import.

It compiles without the plugin/alias, but then throws in other packages because process is not available.

Make process stub writeable.

Ran across a use case where I need to modify the process stub to include a property so another third party library doesn't blow up.

But I can't edit it, due to the way its created.

When the property is defined using defineProperty can it be made writeable?

Explain in README how ts-invariant is different than `invariant`

I might be missing something here, but I can't figure out why one would use ts-invariant over invariant.

The README states:

TypeScript implementation of invariant(condition, message).

and

This class is especially useful when writing TypeScript, because

invariant(typeof value === "number", "not a number");
console.log(value * 2); // type error!

doesn't tell TypeScript anything useful about value, whereas the following code can take full advantage of TypeScript's conditional type narrowing functionality:

if (typeof value !== "number") {
  throw InvariantError("not a number");
}
// TypeScript understands that value must be a number here:
console.log(value * 2);

But if using @types/invariant, this isn't true. The type definition here allows TS to narrow the type after an invariant() assertion.

So - what are the use cases for ts-invariant? Is the only difference that ts-invariant has built-in TS types whereas you need DefinitelyTyped annotations for invariant? Perhaps it's because this was only changed 4 months ago...

Thanks for any insights!

React-scripts build error?

I'm not really sure what this repo is, but I can't figure out why I'm getting an Invariant error when I'm trying to build my create-react-app project with Apollo dependencies. Any ideas?

From package.json

  "dependencies": {
    "apollo-cache-inmemory": "^1.5.1",
    "apollo-cache-redux": "^0.1.2",
    "apollo-client": "^2.5.1",
    "apollo-link": "^1.2.11",
    "apollo-link-error": "^1.1.10",
    "apollo-link-http": "^1.5.14",
    "connected-react-router": "^6.3.2",
    "cors": "^2.8.4",
    "dotenv": "^4.0.0",
    "express": "^4.16.4",
    "graphql": "^14.2.1",
    "graphql-tag": "^2.10.1",
    "history": "^4.9.0",
    "path": "^0.12.7",
    "prop-types": "^15.7.2",
    "react": "^16.8.5",
    "react-apollo": "^2.5.3",
    "react-dom": "^16.8.5",
    "react-helmet": "^5.2.0",
    "react-redux": "^6.0.1",
    "react-responsive": "^4.0.3",
    "react-router": "^5.0.0",
    "react-router-dom": "^5.0.0",
    "react-scripts": "^2.1.8",
    "react-snapshot": "^1.3.0",
    "recompose": "^0.30.0",
    "redux": "^4.0.1",
    "redux-actions": "^2.6.5",
    "redux-form": "^8.1.0",
    "redux-logger": "^3.0.6",
    "redux-thunk": "^2.3.0",
    "styled-components": "^4.2.0"
  },

Error:

$ react-scripts build && react-snapshot
Creating an optimized production build...

File sizes after gzip:

  183.35 KB (+696 B)  build/static/js/2.fec2c2d6.chunk.js
  10.53 KB (+133 B)   build/static/js/main.129c5f3b.chunk.js
  762 B               build/static/js/runtime~main.a8a9905a.js
  373 B               build/static/css/main.b2c2abb0.chunk.css

The project was built assuming it is hosted at /.
You can control this with the homepage field in your package.json.

The build folder is ready to be deployed.
You may serve it with a static server:

  yarn global add serve
  serve -s build

Find out more about deployment here:

  https://bit.ly/CRA-deploy

🕷   Starting crawling http://localhost:61033/
client running env production
iconbtn function(e){return o.a.createElement(be,Object(de.pick)(e,["style","onClick","title"]),e.content?e.content:o.a.createElement(ge,{icon:e.icon}),e.text)}
Error: Uncaught [Invariant Violation: Invariant Violation: 1 (see https://github.com/apollographql/invariant-packages)]
    at reportException (/Users/oahourai/Development/storyfork/web/node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:58:24)
    at processJavaScript (/Users/oahourai/Development/storyfork/web/node_modules/jsdom/lib/jsdom/living/nodes/HTMLScriptElement-impl.js:130:7)
    at HTMLScriptElementImpl._eval (/Users/oahourai/Development/storyfork/web/node_modules/jsdom/lib/jsdom/living/nodes/HTMLScriptElement-impl.js:65:7)
    at /Users/oahourai/Development/storyfork/web/node_modules/jsdom/lib/jsdom/browser/resource-loader.js:31:22
    at Object.check (/Users/oahourai/Development/storyfork/web/node_modules/jsdom/lib/jsdom/living/nodes/Document-impl.js:89:11)
    at Object.check (/Users/oahourai/Development/storyfork/web/node_modules/jsdom/lib/jsdom/living/nodes/Document-impl.js:92:23)
    at /Users/oahourai/Development/storyfork/web/node_modules/jsdom/lib/jsdom/living/nodes/Document-impl.js:108:12
    at wrappedEnqueued (/Users/oahourai/Development/storyfork/web/node_modules/jsdom/lib/jsdom/browser/resource-loader.js:255:16)
    at Request.request [as _callback] (/Users/oahourai/Development/storyfork/web/node_modules/jsdom/lib/jsdom/browser/resource-loader.js:203:9)
    at Request.self.callback (/Users/oahourai/Development/storyfork/web/node_modules/request/request.js:185:22) { Invariant Violation: Invariant Violation: 1 (see https://github.com/apollographql/invariant-packages)
    at new t (http://localhost:61033/static/js/2.fec2c2d6.chunk.js:1:355286)
    at http://localhost:61033/static/js/2.fec2c2d6.chunk.js:1:356406
    at v (http://localhost:61033/static/js/2.fec2c2d6.chunk.js:1:356415)
    at new t (http://localhost:61033/static/js/2.fec2c2d6.chunk.js:1:359389)
    at Module.312 (http://localhost:61033/static/js/main.129c5f3b.chunk.js:1:31774)
    at f (http://localhost:61033/:1:518)
    at Object.184 (http://localhost:61033/static/js/main.129c5f3b.chunk.js:1:3999)
    at f (http://localhost:61033/:1:518)
    at a (http://localhost:61033/:1:387)
    at Array.e [as push] (http://localhost:61033/:1:250) framesToPop: 1, name: 'Invariant Violation' }
🔥 'render' from react-snapshot was never called. Did you replace the call to ReactDOM.render()?
🕸   Finished crawling.
✨  Done in 28.70s.

SyntaxError: Unexpected token - rollup-plugin-invariant

Hi, after adding browserslist to package.json I started getting Unexpected token error when building the bundle, do you might have an idea why?

When there is no browserslist on the package.json it all works fine

browserlist:

"browserslist": [
    "last 2 chrome major version",
],

devDependecies:

"@rollup/plugin-babel": "^5.3.0",
"@rollup/plugin-commonjs": "^20.0.0",
"@rollup/plugin-json": "4.1.0",
"@rollup/plugin-node-resolve": "^13.0.0",
"@rollup/plugin-replace": "^2.4.2",
"rollup": "^2.53.0",
"rollup-plugin-copy": "^3.4.0",
"rollup-plugin-invariant": "^0.9.2",
"rollup-plugin-postcss": "^4.0.0",

Error:

[!] (plugin rollup-plugin-invariant) SyntaxError: Unexpected token (18:7)
src/index.tsx (18:7)
SyntaxError: Unexpected token (18:7)
    at Parser.pp$4.raise (/node_modules/rollup/dist/shared/rollup.js:16909:13)
    at Parser.pp.unexpected (/node_modules/rollup/dist/shared/rollup.js:14417:8)
    at Parser.pp.expect (/node_modules/rollup/dist/shared/rollup.js:14411:26)
    at Parser.pp$1.parseExportSpecifiers (/node_modules/rollup/dist/shared/rollup.js:15402:8)
    at Parser.pp$1.parseExport (/node_modules/rollup/dist/shared/rollup.js:15323:28)
    at Parser.pp$1.parseStatement (/node_modules/rollup/dist/shared/rollup.js:14593:72)
    at Parser.pp$1.parseTopLevel (/node_modules/rollup/dist/shared/rollup.js:14474:21)
    at Parser.parse (/node_modules/rollup/dist/shared/rollup.js:14266:15)
    at Function.parse (/node_modules/rollup/dist/shared/rollup.js:14297:35)
    at Graph.contextParse (/node_modules/rollup/dist/shared/rollup.js:20278:38)

Invariant Violation: 9

Hello,

I am having an issue with Apollo (used in a VueJS project). The following error message is displayed where I am referred to this repository:

Invariant Violation: Invariant Violation: 9 (see https://github.com/apollographql/invariant-packages)
    at new e (https://alpha.loyaly.app/js/chunk-vendors.228b37e2.js:34:16801)
    at https://alpha.loyaly.app/js/chunk-vendors.228b37e2.js:57:14337
    .....
    .....

Googling only led me to the same error message, but with a different code. I couldn't manage to find these number code documented or understand what the code 9 meant.

In my case, I am using a mutation with variables for the first time on this project, so there is a high chance that my code is faulty

Hope somebody can help

Instructions are way too vague

Since the full development version of the error is colocated with the production one in code that has been transformed by rollup-plugin-invariant, it should be relatively easy to determine the nature of the error by looking for the given error code in the unminified bundle.

Although it says "it should be relatively easy" I honestly have no idea what I'm supposed to be looking for. Maybe an example would help?

ts-invariant TS config missing "node" type

Typescript fails for projects that don't define "node" in their TS config types attribute. To simply fix this issue, ts-invariant should add that requirement to its own TS config file.

However, it seems to me ts-invariant shouldn't require "node" at all. The library is mostly being used by Apollo, which can be installed in React Native and that creates a lot of type conflicts since both node and react-native types define a lot of duplicate definitions. The node type is only being used by ts-invariant for the processStub: NodeJS.Process type, so it seems a bit exaggerated to require a massive type definition such as node for a single variable. Perhaps there's a better way of defining processStub's type so that importing node definitions become optional.

This repo is the landing page for error messages that it doesn't help with

Right now for many Apollo errors in production, you get an error message that looks like (for example):

Invariant Violation: Invariant Violation: 19 (see https://github.com/apollographql/invariant-packages)

However, the README for this repository contains no information about how to recover the error message. This is quite bad, and leads to lots of people (including me) spending significant time on wild goose chases.

The answer is: look in node_modules/@apollo/client/invariantErrorCodes.js. Do NOT look in the apollo-client github repo for that file, because it's not there.

Usage of const keyword in ts-invariant package

Hello 👋

We recently noticed that the ts-invariant package seems to be shipping code with const references within it which can break on browsers that don't support those es6 features (e.g. IE).

Would it be possible to ship an es5 compatible version of this package? We're currently relying on this package via a few Apollo dependencies.

How to skip invariant in webpack?

Hello, I found this module attempting to violate my Content Security Policy after tracking it down in my webpack bundle line 1, column 554,074 as it were. After finding that actual column, then grepping my node_modules for Function('stub', I am greeted with the lovely code comment here: https://github.com/apollographql/invariant-packages/blob/master/packages/ts-invariant/src/invariant.ts#L54-L57

As I would very much like to not include "unsafe-eval" and also not post back csp-violations to my server, how can I disable this functionality in my production webpack build?

I build with Angular CLI --prod so the minified code looks like this:

var c={env:{}};if("object"==typeof process)c=process;else try{Function("stub","process = stub")(c)}catch(l){}}

ES module support (ts-invariant\process)

Loading ts-invariant in an ESM context, leads to the following error

(node:16684) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
D:\Programming\JabRefOnline\node_modules\ts-invariant\process\index.js:15
export function install() {
^^^^^^

SyntaxError: Unexpected token 'export'
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1025:15)
    at Module._compile (node:internal/modules/cjs/loader:1059:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:190:29)
    at ModuleJob.run (node:internal/modules/esm/module_job:185:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
[vite dev] Error loading external "D:/Programming/JabRefOnline/node_modules/ts-invariant/process/index.js".
  at file:///D:/Programming/JabRefOnline/.nuxt/dist/server/server.mjs:19525:284
  at async __instantiateModule__ (file:///D:/Programming/JabRefOnline/.nuxt/dist/server/server.mjs:51609:3)
[vite dev] Error loading external "D:/Programming/JabRefOnline/node_modules/ts-invariant/process/index.js".
  at file:///D:/Programming/JabRefOnline/.nuxt/dist/server/server.mjs:19525:284
  at async __instantiateModule__ (file:///D:/Programming/JabRefOnline/.nuxt/dist/server/server.mjs:51609:3)

It works after one adds ts-invariant/process to the transpile option (or noExternal in vite ssr config). Such a workaround is not needed for the 'main' ts-invariant package. So I guess there is a problem with

Failed to parse source map warning

After upgrading @apollo/client to 3.6.0 that depends on ts-invariant 0.10.1 I'm seeing the following warning from the React dev server at every code change:

Compiled with warnings.

Failed to parse source map from '/path/to/project/node_modules/ts-invariant/src/invariant.ts' file: Error: ENOENT: no such file or directory, open '/path/to/project/node_modules/ts-invariant/src/invariant.ts'

Search for the keywords to learn more about each warning.
To ignore, add // eslint-disable-next-line to the line before.

WARNING in ./node_modules/ts-invariant/lib/invariant.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):

This is in a project using react-scripts 5.0.1.

Before the upgrade I had @apollo/client 3.5.4 which used ts-invariant 0.9.4 (still the latest according to the npm registry) and there were no warnings.

breaks gatsby build with "Invariant Violation: 1"

When I run yarn build:

alexa@PCA C:\Users\alexa\ae2
$ yarn build
yarn run v1.15.2
$ gatsby clean && gatsby build
info Deleting .cache, public
info Successfully deleted directories

success open and validate gatsby-configs - 0.144 s
success load plugins - 0.892 s
success onPreInit - 0.073 s
success delete html and css files from previous builds - 0.070 s
success initialize cache - 0.078 s
success copy gatsby files - 0.249 s
success onPreBootstrap - 0.087 s
success source and transform nodes - 0.150 s
success building schema - 0.191 s
success createPages - 0.148 s
success createPagesStatefully - 0.105 s
success onPreExtractQueries - 0.076 s
success update schema - 0.088 s
success extract queries from components - 0.719 s
success write out requires - 0.074 s
success write out redirect data - 0.071 s
success Build manifest and related icons - 0.187 s
success onPostBootstrap - 0.267 s
⠀
info bootstrap finished - 7.380 s
⠀
success run static queries - 0.063 s
success Building production JavaScript and CSS bundles - 58.145 s
success Rewriting compilation hashes - 0.058 s
success run page queries - 0.065 s — 3/3 304.21 queries/second
⠼ Building static HTML for pages
(node:9272) UnhandledPromiseRejectionWarning: MissingAPIError: indexedDB API not found. If using IE10+, make sure to run your code on a server URL (not locally). If using old Safari versions, make sure to include indexedDB polyfill.
    at Transaction.create (C:\Users\alexa\ae2\public\render-page.js:48507:31)
    at tempTransaction (C:\Users\alexa\ae2\public\render-page.js:47466:23)
    at C:\Users\alexa\ae2\public\render-page.js:47461:61
    at C:\Users\alexa\ae2\public\render-page.js:46976:23
    at callListener (C:\Users\alexa\ae2\public\render-page.js:46659:19)
    at endMicroTickScope (C:\Users\alexa\ae2\public\render-page.js:46746:25)
    at physicalTick (C:\Users\alexa\ae2\public\render-page.js:46721:30)
(node:9272) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

 ERROR #95313

Building static HTML failed for path "/offline-plugin-app-shell-fallback/"

See our docs page for more info on this error: https://gatsby.dev/debug-html


  10 |     function InvariantError(message) {
  11 |         if (message === void 0) { message = genericMessage; }
> 12 |         var _this = _super.call(this, typeof message === "number"
     | ^
  13 |             ? genericMessage + ": " + message + " (see https://github.com/apollographql/invariant-packages)"
  14 |             : message) || this;
  15 |         _this.framesToPop = 1;


  WebpackError: Invariant Violation: Invariant Violation: 1 (see https://github.com/apollographql/invariant-packages)

  - invariant.esm.js:12 new InvariantError
    node_modules/ts-invariant/lib/invariant.esm.js:12:1

  - bundle.esm.js:64 checkFetcher
    node_modules/apollo-link-http-common/lib/bundle.esm.js:64:52

  - bundle.esm.js:11 new BatchHttpLink
    node_modules/apollo-link-batch-http/lib/bundle.esm.js:11:21

  - client.js:59 ./src/client.js.__webpack_exports__.default
    src/client.js:59:25

  - App.js:32 App
    src/App.js:32:27


⠼ Building static HTML for pages
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

This package exists because:

alexa@PCA C:\Users\alexa\ae2
$ yarn why ts-invariant
yarn why v1.15.2
[1/4] Why do we have the module "ts-invariant"...?
[2/4] Initialising dependency graph...
[3/4] Finding dependency...
[4/4] Calculating file sizes...
=> Found "[email protected]"
info Reasons this module exists
   - "apollo-cache-inmemory" depends on it
   - Hoisted from "apollo-cache-inmemory#ts-invariant"
   - Hoisted from "apollo-client#ts-invariant"
   - Hoisted from "apollo-link#ts-invariant"
   - Hoisted from "@apollo#react-hooks#ts-invariant"
   - Hoisted from "apollo-link-batch-http#apollo-link-http-common#ts-invariant"
   - Hoisted from "apollo-client#apollo-utilities#ts-invariant"
   - Hoisted from "@apollo#react-hooks#@apollo#react-common#ts-invariant"
info Disk size without dependencies: "48KB"
info Disk size with unique dependencies: "108KB"
info Disk size with transitive dependencies: "108KB"
info Number of shared dependencies: 1
Done in 0.94s.

Seems related to #2

The weird thing is: I have another gatsby project using apollo and thus ts-invariant. Also v0.4.4. This does not happen there.

What I have tried to do:

  • del yarn.lock && rmdir /s node_modules && yarn cache clean && yarn && yarn build: still happens
  • building on my notebook with macOS Mojave: exact same error

My project: https://github.com/FNSKtZH/ae2

Versions:

Invariant Violation: Invariant Violation: 44

Sent to here with the following:
Invariant Violation: Invariant Violation: 44 (see https://github.com/apollographql/invariant-packages)

I have not a single clue what I am supposed to do. I have seen folks using grep like:

grep -r "InvariantError(" node_modules/**/bundle.cjs.js

or

grep -r "InvariantError(" node_modules/**/bundle.esm.js

None of those have a 44.

What does that mean? How should I debug this?

using:

"@apollo/client": "^3.0.0-rc.2",
"@apollo/link-context": "^2.0.0-beta.3",

not sure what else is relevant, cause I don't know the error's origin.

Could someone help with this?

UPDATE: I resolved the issue in my code. The problem was that I used useQuery/useMutation hooks of @apollo/client outside of ApolloProvider.

This does resolves this issue itself, the dev experience was somewhat cumbersome, and my solution was to hunt down the breaking commit, rather than getting a clear message of the possible error.

Enable CircleCI

The configuration for CircleCI exists, but is not used. We should enable CircleCI for this repository in order to test incoming PR.

Does anyone know where the reference to @types/node is coming from?

In the latest published version of this package of 0.6.0: https://registry.npmjs.com/ts-invariant/-/ts-invariant-0.6.0.tgz

In lib/invariant.d.ts, you can see this right at the top:

/// <reference types="node" />

Though how is it getting there? I don't see it anywhere in the sources within this repo.

This is causing the node types to leak into our projects based on this issue:
microsoft/TypeScript#31148 (comment)

I've also already commented on this package here:
apollographql/apollo-client#7734

Though I'm confused and would like some clarification.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.