requires to access .default after build while it's not required in dev (CJS dependency)

Describe the bug
Encountered “Minified React error” in the production environment, the dev environment is fine.
error: Minified React error #130; visit https://reactjs.org/docs/error-decoder.html?invariant=130&args[]=object&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
    at vc (vendor.93c27df6.js:23)
    at d (vendor.93c27df6.js:23)
    at vendor.93c27df6.js:23
    at vendor.93c27df6.js:23
    at Ts (vendor.93c27df6.js:23)
    at ul (vendor.93c27df6.js:23)
    at ic (vendor.93c27df6.js:23)
    at tc (vendor.93c27df6.js:23)
    at ql (vendor.93c27df6.js:23)
    at zl (vendor.93c27df6.js:23)

Reproduction
Repo: https://github.com/songquanpeng/snippet-manager/tree/aa02a582c676bd3dcd5254f18d7087bb8a1a7220
My React application is on the  web folder.
System Info

vite version: 2.0.0
Operating System: Windows 10
Node version: v14.15.3
Package manager (npm/yarn/pnpm) and version: 7.5.4

Summarization of the root problem
https://github.com/vitejs/vite/issues/2139#issuecomment-1024852072

Not encountered this error. Can you have a try after upgrade vite?

PS D:\Project\Go\snippet-manager\web> vite --version
vite/2.0.1 win32-x64 node-v14.15.3

And you can check out the deployed version here, built with Github Action: https://snippet.justsong.cn/

I can confirm i have the same error only in production.
System Info

vite version: 2.0.3
Operating System: MacOS Big Sur
Node version: v14.15.4

I ran into the same issue using latest Vite version.
Note
The title of the issue is very vague as this error is displayed by minified React instead of ANY React error. So it can be anything really.
The first thing to do in this case is to debug the app in order to have more details: Use minify and dev mode in your vite.config.js in order to get the real issue with the possibility to inspect in the browser dev tools.
export default defineConfig({
  plugins: [reactRefresh()],
  mode: "development",
  build: {
    minify: false,
  }
});

In my case it was coming from using react-switch. And I hacked it to work using the following (don't tell anyone about this)
import S from "react-switch";
const Switch = S.default? S.default: S
console.log(S); // inspecting

Basically this is the content of the import {__esModule: true, default: ƒ}
The react-switch library is built as cjs so this  is probably a cjs compatibility issue for Vite's Rollup build configuration ?

It's because esbuild is checking for __esModule at runtime and rollup is not. So it will happen to any library that has an entry point with
module.exports = require("./something");

Since this file does not include the 'magic string' __esModule as checked by https://github.com/rollup/plugins/blob/master/packages/commonjs/src/generate-exports.js#L82 it's not converted correctly.

vite dev
vite build

import Switch from 'react-switch'; Switch
ok

import Switch from 'react-switch'; Switch.default

ok

import Switch from 'react-switch/dist/react-switch.dev.js'; Switch
ok
ok

So need to raise a bug in rollup for this.

Unsurprisingly, it's a known issue mentioned in https://github.com/rollup/plugins/issues/481 but it doesn't seem like there will be a solution very soon.
One thing to note is that the node behaviour is mutually exclusive with supporting __esModule. When running natively from Node, Switch.default would be the only correct option. In the end the best way would probably to ask the library author to publish an esm version to avoid this problem completely.

It's because esbuild is checking for __esModule at runtime and rollup is not

Then we should issue a big warning at dev time about this behaviour. It's a critical bug (in the libraries) that affects the Vite experience drastically.

Yup, same problem here: https://github.com/vitejs/vite/issues/2692.

After looking into this some more, I think vite should switch to behave the same as rollup. That way it would be consistent with how node works (and snowpack as well).
For now, importing a commonjs module should probably show a warning somewhere.

@ntkoopman would you expand a bit in what needs to be changed in Vite? A PR would be great so we can discuss what the implications are there (from anyone that is following this issue)
Agree about the warning in the meantime in case that change is not easy to land, PR welcome for that patch too

So I already changed my mind again, since changing the dev behaviour will still break dependencies. So, the best case would still be that it gets fixed in rollup. I tested with a commonjs plugin I wrote and it seems to work for us for now:
import cjs from 'rollup-plugin-cjs';

export default defineConfig({
  build: {
    rollupOptions: {
      input: {
        index: resolve(__dirname, 'src/index.html'),
      },
      plugins: [cjs()],
    },
    commonjsOptions: {
      exclude: [/./],
    },
  },
});

I looked into returning a warning, but decided not to, because if it's possible to detect the issue it should be possible to fix it..
I'll continue on the commonjs plugin and see if I can fix it there (or maybe it's just a configuration option that's missing?) now that I have some unit tests.

I ran into the same issue using latest Vite version.
Note
The title of the issue is very vague as this error is displayed by minified React instead of ANY React error. So it can be anything really.
But in both our cases, this is the actual error Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
The first thing to do in this case is to debug the app in order to have more details: Use minify and dev mode in your vite.config.js in order to get the real issue with the possibility to inspect in the browser dev tools.
export default defineConfig({
  plugins: [reactRefresh()],
  mode: "development",
  build: {
    minify: false,
  }
});

Hacky solution in my case
In my case it was coming from using react-switch. And I hacked it to work using the following (don't tell anyone about this)
import S from "react-switch";
const Switch = S.default? S.default: S
console.log(S); // inspecting

Basically this is the content of the import {__esModule: true, default: ƒ}
The react-switch library is built as cjs so this is probably a cjs compatibility issue for Vite's Rollup build configuration ?
In the reproduction repo
If you follow the debugging steps, you will discover that the culprit in your case is react-highlight

Notes for reproduction
In order to reproduce the issue, you need to:

Run npx vite build
Serve the dist folder using an http server. e.g: npx http-server dist --port 3002

I used this to fix this issue cropping up with react-no-ssr.

This issue is complete blocker for me from using Vite in my React production apps.
In my case, the issue does not show up in the development mode (it works completely fine there) and it does only show up in production.
The thing is... since a lot of external React components (like react-switch, react-notfification, react-select) uses export default (unfortunetly) - it forces developer to guess which one of it crashes the app. However, trying setting "development" mode for production build and disabling minifier option doesn't help either, because DevTools also doesn't show me any exact place in the stacktrace where the problem can exist.
Hope this issue will be resolved soon, because I loved using Vite so far 😔

🔥 I'm blocked by the same issue. My team is thinking about stopping using vite, and going back to webpack. Please give more power and fix it as soon as possible.
index.d0639777.js:6 Error: Minified Redux error #7; visit https://redux.js.org/Errors?code=7 for the full message or use the non-minified dev environment for full errors.      at d (index.d0639777.js:33)     at index.d0639777.js:22     at Bu (index.d0639777.js:6)     at t.unstable_runWithPriority (index.d0639777.js:6)     at Ya (index.d0639777.js:6)     at Du (index.d0639777.js:6)     at index.d0639777.js:6     at R (index.d0639777.js:6)     at MessagePort.w.port1.onmessage (index.d0639777.js:6)

Vite development react seems not suitable for production

React + vite doesn't work well in a production environment, need to wait..  :(

Note: This isn't a React-specific or Vite-specific issue, but a Rollup issue (specifically with their CommonJS plugin).
The Workaround
Example: https://github.com/alloc/vite-react-jsx/commit/2db2870f5ad888ed7d4a57e5ba10a82f8bdf80b2
Instead of importing the CJS package directly, use a middle man that unwraps the module.default property like so:
import S from 'react-switch'

export const Switch = interopDefault(S)

function interopDefault<T>(value: T): T {
  return (value as any).default
}

It's ugly, but it works. If 10 people sponsor me on Github for $1 a month, I'll make a plugin that handles this compatibility layer automatically (and maybe even work it into Vite core).

@smajl My goal is to increase my sponsor count. I'm the only React-focused maintainer of Vite, so if any of you use React, please sponsor me, or I can't justify sharing my contributions. I recently made vite-react-jsx too.

@aleclarson uncaught at  Error: Minified React error #130; visit https://reactjs.org/docs/error-decoder.html?invariant=130&args[]=object&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
I had the same problem,
I like vite but it is still a lot of problems with react production.

@rollup/plugin-commonjs works for me with the commonjsOptions exclude pattern ntkoopman used (thank you). I don't understand how that works, since that should match any path longer than 0 characters. @rollup/plugin-commonjs is also used internally in vite, but not passed to rollup.
import { defineConfig } from 'vite'
import commonjs from '@rollup/plugin-commonjs';

// https://vitejs.dev/config/
export default defineConfig({
  build: {
    rollupOptions: {
      plugins: [commonjs()],
    },
    commonjsOptions: {
      exclude: [/./],
    },
  }
})

Someone should at least rename and pin this issue imo (if documenting or fixing the issue are not viable short term options). Like many others in here I had a terrible onboarding experience with Vite spending hours debugging and finding the solution for this, because some of my dependencies used commonjs-only libraries (example: https://github.com/plurals/pluralize). aleclarson's solution was not viable, as I can't wrap my dependencies import logic, and it didn't import an object with the default property. It imported an empty object ({}).

Same issue here with just this:
import React from 'react';
import ReactDOM from 'react-dom';

import JSONTree from 'react-json-tree';

ReactDOM.render(
    <React.StrictMode>
        <JSONTree data={{ test: 'Hello World' }} />
    </React.StrictMode>,
    document.getElementById('root')
);

Neither '@rollup/plugin-commonjs' or 'rollup-plugin-cjs' worked for me as I would run into 'x is not a function()'.

@jrmyio Disable minification to see the real error https://github.com/vitejs/vite/issues/2139#issuecomment-802981228

@jrmyio Disable minification to see the real error #2139 (comment)

Thanks, the error is
Uncaught ReferenceError: Cannot access '__çjs$synthetic__' before initialization
    at vendor.0646077f.js:1
(anonymous) @ vendor.0646077f.js:1

@jrmyio Disable minification to see the real error #2139 (comment)

I did the configuration to disable minification but seems not work for me. Still showing Minify 130 error.

@jrmyio Disable minification to see the real error #2139 (comment)

I did the configuration to disable minification but seems not work for me. Still showing Minify 130 error.

Likewise. How do we get proper errors with stack traces in production? Preferably like CRA.

Same issue when using react-json-tree. Workaround in this issue like
import T from 'react-json-tree';
const JSONTree = T.default? T.default: T

didn't work for me. It seems this package have some ESModule import inside itself, but hacking the index is not sufficient.
// lib/JSONNode.js
// ...
var _default = JSONNode;
exports["default"] = _default;

// lib/index.js
var _JSONNode = _interopRequireDefault(require("./JSONNode"));

My workaround is import this module source directly. But it is really tricky and breaking type check.
import JSONTree from 'react-json-tree/src/index'

Same error, using: I don't know, my project grow up, when I'm ready to deploy and publish: ERROR. 😢

This is a major issue that wasted several days of work attempting to migrate from CRA to Vite. Unfortunately this problem was not discovered until a production build was attempted once everything was working in dev mode.
I agree with @jugglingcats that any insights to identify offending components would be helpful. A 'non-minified' 'development mode' build seems like a critical feature for debugging.
Related Discussion: https://github.com/vitejs/vite/discussions/5803

encounter same issue, is there a solution? thanks!

Any tips on identifying which module causes this when the stacktrace just points to ReactDOM ? Mocking ReactDOM as mentioned by @aleclarson doesn't seem to do anything (only causes a render is not a function error) so I guess that ain't the source of my issues.

Alas, I've also given up. I've spent one week trying to migrate a CRAv4 project, but it seems like Vite ain't ready yet. Will upgrade to CRAv5 for now, looking forward to trying again in the future. :)

I'm also experiencing this issue with a package I've authored, and I don't understand how to build this package to avoid this issue.

built using tsc typescript compiler https://github.com/betagouv/publicodes/blob/master/packages/react-ui/tsconfig.json
output file that I try to import<EMAIL_ADDRESS>

A sum up:
The root problem is that many packages follow a bad practice that breaks Rollup ESM-CJS interop:

Like react, they use a CJS entry with mere conditional require()s to redirect the request to different source modules based on NODE_ENV. (e.g. https://unpkg.com/browse/react-switch@6.0.0/index.js). The actual source modules are compiled ESM with an exports.__esModule flag; (e.g<EMAIL_ADDRESS>Unlike react, they use default exports in the source;
Tools with runtime helpers (esbuild, babel, etc.) can detect the __esModule flag from the entry module at runtime and only at runtime
Rollup CJS plugin is compile-time only, it can't possibly know that a CJS module should be treated as ESM after the non-top-level require() call resolves at runtime.
This issue doesn't matter when the exports are all named (like in react). But when there's a default export, it would become nested after Rollup bundling (import Switch from 'react-switch' returns { default: ... }).

It's easy to work around at the user side with the above-mentioned hack:

import S from "react-switch";
const Switch = S.default? S.default: S
console.log(S); // inspecting

But a more general solution might not be that easy, especially since there could be named exports along with default exports in the same module.
Detecting such possible breakages seems not easy too because they are resolved at runtime… I'll see what I can do here to help mitigate the issue.

Ideally, these packages should:

Either stop using the entry CJS module for redirecting
Or stop using default exports until they can ship proper ESM modules.

You should just make these fail in development as well.
Why you think it's good idea to have these modules working only in development and then fail in prod build?

Thanks you @sodatea for the detailed write up. I've found that the PR that introduced this feature in esbuild provide some interesting additional context https://github.com/evanw/esbuild/pull/1849#issue-1079368644
I agree that the behavior should be the same in dev and in prod modes, which imply either:

disabling esbuild runtime helpers in dev mode
or using esbuild to “pre-bundle” in prod before running Rollup as proposed by Evan You in https://github.com/vitejs/vite/discussions/4921

Just wanna chime in I ran into this today and while I'm upset it's blocking, I want to encourage sponsoring maintainers like @aleclarson not only for their work so far but so hopefully someday we can get this fixed :)

Question for maintainers: has anyone already tried implementing Evan's idea #2 of pre-bundling dependencies with esbuild in production as well? Do we know how much work that would involve?

@fwouts https://github.com/vitejs/vite/pull/4677

For anyone looking at this issue, this should hopefully be solved by https://github.com/rollup/plugins/pull/1165, which depends on another big Rollup CJS PR, so I'm not exactly sure when we'll get it all released and updated in Vite, but a fix is in sight at least 👀
If it takes too long, we could also consider patching the Rollup CJS plugin in Vite (it's a small diff when you exclude tests).

for now, it's we need to change some of our import statments
instead of
import S from "react-switch";

use following
import * as S from "react-switch";

// then use S.default

but still, it's weird to use : (

I'm about to finish the migration from CRA to Vite, but I found this same error with react-switch, thanks to this thread I could fix the issue, thanks
But, now I'm wondering if there is another library with the same problem in my project, there is a way to validate more libraries have the same issue?

Hey!! I've just encountered this, and I've realized that rollup has already issued the fix for this in release v22.0.0 https://github.com/rollup/plugins/commit/3bc287cd6ad067a54e69ec17a1869cb12da2e952
Can we get the rollup plugin in vite bumped to v22?

@Kylar13 we're hitting some issues with the update to rollup plugin commonjs v22, in case someone wants to help check out the issue:

https://github.com/vitejs/vite/pull/7894

I'm completely lost as to how Vite works internally so I am unable to help, but I will add that the library that was giving me issues is https://www.npmjs.com/package/react-phone-input-2, and the fix for now is the one suggested by @haikyuu:
import RPI from "react-phone-input-2";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const ReactPhoneInput = RPI.default ? RPI.default : RPI;

@Kylar13 we're hitting some issues with the update to rollup plugin commonjs v22, in case someone wants to help check out the issue:

https://github.com/vitejs/vite/pull/7894

Until we manage to make it work, we could stay on v21 and patch it in Vite with https://github.com/rollup/plugins/pull/1165 (it's just a couple of lines of actual code). I believe this would at least allow us to close this issue.
Patching is not ideal, but I bet it would unlock the next level of growth for Vite as this issue is holding back larger codebases from migrating over from Webpack.

That could be an option @fwouts. I think we should still try to get v22 to work, but we could go there if we can't get it for v3.

Hi @aleclarson
Awesome, the current alpha fixed the issue for me.
However a new issue has occured useRef.current is null https://imgur.com/a/qeELLa2
I've double checked it works flawless in develop mode.

I can't really replicate it because I don't know where the issue is coming from.
Its really weird. sometimes all components work perfectly fine. Then I rebuild and it doesnt work.
I've tried a few things but so far I only got it to happen occasionally.
I'll create an issue when I figure out more, atleast the commonjs issue is solved soon 🎉

I'm completely lost as to how Vite works internally so I am unable to help, but I will add that the library that was giving me issues is https://www.npmjs.com/package/react-phone-input-2, and the fix for now is the one suggested by @haikyuu:
import RPI from "react-phone-input-2";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const ReactPhoneInput = RPI.default ? RPI.default : RPI;

After migrating from Create React App to Vite that same library react-phone-input-2 started giving me issues and your solution worked perfectly, thank you very much for sharing it!

I'm completely lost as to how Vite works internally so I am unable to help, but I will add that the library that was giving me issues is https://www.npmjs.com/package/react-phone-input-2, and the fix for now is the one suggested by @haikyuu:
import RPI from "react-phone-input-2";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const ReactPhoneInput = RPI.default ? RPI.default : RPI;

After migrating from Create React App to Vite that same library react-phone-input-2 started giving me issues and your solution worked perfectly, thank you very much for sharing it @Kylar13!

Same here. Thanks @Kylar13 !

For anyone still having this problem, bump vite to v3 (merged #8743) did the trick for me.

Still seeing these in v3, stack traces on these errors are completely unreadable and sourcemap is not able to resolve those those stack traces either.

my culprit was react-cookie-consent, i had to bump vite to v3, and also react-cookie-consent to the latest version, then it worked.
if you need to run a development build, to see the stacktrace, run vite build --mode development (i had to search for this for some time)

I ran into the same issue using latest Vite version.
Note
The title of the issue is very vague as this error is displayed by minified React instead of ANY React error. So it can be anything really. But in both our cases, this is the actual error Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.
The first thing to do in this case is to debug the app in order to have more details: Use minify and dev mode in your vite.config.js in order to get the real issue with the possibility to inspect in the browser dev tools.
export default defineConfig({
  plugins: [reactRefresh()],
  mode: "development",
  build: {
    minify: false,
  }
});

Hacky solution in my case
In my case it was coming from using react-switch. And I hacked it to work using the following (don't tell anyone about this)
import S from "react-switch";
const Switch = S.default? S.default: S
console.log(S); // inspecting

Basically this is the content of the import {__esModule: true, default: ƒ}
The react-switch library is built as cjs so this is probably a cjs compatibility issue for Vite's Rollup build configuration ?
In the reproduction repo
If you follow the debugging steps, you will discover that the culprit in your case is react-highlight
Notes for reproduction
In order to reproduce the issue, you need to:

Run npx vite build
Serve the dist folder using an http server. e.g: npx http-server dist --port 3002

I had this same issue with the react-dropzone-uploader package and this helped fix it. Thanks so much

Thank you all!
This was a life saver in my case (react-select + TypeScript):
import RS from 'react-select';

const ReactSelect = (RS as any).default ? (RS as any).default : RS;

export const MyComponent = () => {
  return (
    <ReactSelect options={[]} />
  );
};

My React app was crashing in production only with:
Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object

No development nor build issues of any kind. It took me hours to find the cause.

you save my life. thanks a lot.

I'm completely lost as to how Vite works internally so I am unable to help, but I will add that the library that was giving me issues is https://www.npmjs.com/package/react-phone-input-2, and the fix for now is the one suggested by @haikyuu:
import RPI from "react-phone-input-2";
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const ReactPhoneInput = RPI.default ? RPI.default : RPI;

you save my life. thanks a lot

For me it was react-datetime
Thanks for the solution!
import DT from "react-datetime";
// @ts-ignore
const DateTime = DT.default ? DT.default : DT;

For me it was @mdi/react

Just want to add my 5 cents on this issue...
I've spent ~20hours migrating large project from CRA2 to vite. 100s of changed files, writing custom plugins and it finally worked on dev and prod.
Imagine my frustration, when I see some of the pages crush because rollup can't handle cjs files in the same way as esbuild and webpack does. Imagine my frustration, when I see such hyped project as vite having this issue opened for 2.5 years.
Since rollup struggle to fix this issue, vite should implement its own rollup plugin to reexport cjs in the same way as esbuild does.

I also encountered this issue in the library react-foco,
My temporary solution is to force cjs tranform to use default field.
// in vite.config.ts, build field
commonjsOptions: {
    defaultIsModuleExports(id) {
        if (/react-foco/.test(id)) return false; // cannot automatically detect react-foco's default export, fix a rollup issue https://github.com/vitejs/vite/issues/2139
        return 'auto';
      },
},

I found downgrade @rollup/plugin-commonjs to version 21 also fix the issue for me. To use custom version of @rollup/plugin-commonjs, we can do this
import commonjs from '@rollup/plugin-commonjs'; // our version of commonjs plugin

defineConfig({
  build: { commonjsOptions: { include: [] } },
  plugins: [commonjs()]
})

You're life saver it's work like a charm

I had the same issue and now the error is fixed. I added a few lines of code in Vite config.
I'm using  @vitejs/plugin-react: 2.2.0 and vite: 3.2.3

I have the same issue but only sometimes 😸. Vite (or more likely rollup?) doesn't produce deterministic outputs in our case.
The lucky output snippet is:
var _Checkbox$1 = _interopRequireDefault$8(requireCheckbox());
var _default$a = Checkbox$2.default = _Checkbox$1.default;
...
react.exports.createElement(_default$a) // ok

while sometimes it produces
function requireCheckbox() {
  ...
  Checkbox$2.__esModule = true;
  var _Checkbox2 = _interopRequireDefault2(requireCheckbox$1());
  Checkbox$2.default = _Checkbox2.default;
  return Checkbox$2;
}
var CheckboxExports = requireCheckbox();
...
react.exports.createElement(CheckboxExports) // crashes because {__esModule: true, default: f} is obviously no valid react type

Same issue with 4.0.0-alpha.6.
I was able to workaround it with the hacky solution https://github.com/vitejs/vite/issues/2139#issuecomment-824557740. But non deterministic results really scare me to use vite in production.

Getting the same issue

Still same issue (with react-audio-player).. what is the recommended fix or workaround as of now?

Hit this with @mdi/react as well, for typescript I added to the fix proposed in https://github.com/vitejs/vite/issues/2139#issuecomment-802981228 to preserve types
Icon.tsx
import I from '@mdi/react';
// @ts-ignore
const IconComponent = I.default ? I.default : I;

const Icon: typeof I = IconComponent;

export default Icon;

Hit this with @mdi/react as well, for typescript I added to the fix proposed in #2139 (comment) to preserve types
Icon.tsx
import I from '@mdi/react';
// @ts-ignore
const IconComponent = I.default ? I.default : I;

const Icon: typeof I = IconComponent;

export default Icon;

You can also use
import { Icon } from '@mdi/react';

instead of the default import, that fixed it for me.

I had the same problem of @songquanpeng, The solution in my case was update vite version 2 to 4

Still getting this issue in Vite 4.0.4.
This is an awful error because:
a) you don't see it in dev (deploying is the only way to try and fix it?)
b) there's no way apart from trial-and-error to find out the culprit
c) this has seemingly been open since 2021 without any meaningful progress
I'd love to be wrong on any of these points

I also encountered this problem while dealing with vite and react-phone-input-2 package.
After a couple of hours trying to understand @rollup/plugin-commonjs and how defaultIsModuleExports flag affects modules, I came up with a (possibly not the silver bullet but working) solution.
Plugin (at this moment of writing) handles package bundles with default exports only when module.exports=... it's either an object expression (with truthy __esModule property value) or a require call function. This (and probably other technics added to the plugin over time) solve problems with some of the mentioned above dependencies (react-switch, react-cookie-consent, react-foco, react-select) but others (like react-audio-player, react-date-time, @mdi/react and react-phone-input-2) are basically IIFE's putted into module.exports, which are not covered by the plugin.
Playing with AST parsers and walkers doesn't give me much progress (at some point it's just too hard to handle with all those nodes), but having in mind, that defaultIsModuleExports flag accepts a function with an argument of package path, I ended up with this:
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

// Without it dynamic require is not possible in config file
import { createRequire } from "module";
const require = createRequire(import.meta.url);

export default defineConfig({
  build: {
    commonjsOptions: {
      defaultIsModuleExports(id) {
        const module = require(id);
        if (module?.default) {
          return false;
        }
        return "auto";
      },
    },
  },
  plugins: [react()],
});

All IIFE packages are now converted by plugin to have same export structure both in localhost and production.
Probably in larger projects, it could potentially slow down the build process, but IMO it's better than manually putting a ternary operator on each file.

Is there any linting rule we can use to prevent this bug from happening in prod?

Slightly modified solution @Boni0
This config works for my case:
import { defineConfig} from 'vite';
import react from '@vitejs/plugin-react';
import { viteCommonjs } from '@originjs/vite-plugin-commonjs';

export default defineConfig({
  plugins: [viteCommonjs(), react()],
  build: {
    commonjsOptions: {
      defaultIsModuleExports(id) {
        try {
          const module = require(id);
          if (module?.default) {
            return false;
          }
          return 'auto';
        } catch (error) {
          return 'auto';
        }
      },
      transformMixedEsModules: true,
    },
  },
});

Tried several suggestions to try and debug, but even this is a bug:
mode: "development",
build: {
    minify: false,
},

Which gets ignored and continues to minify during build even though while building it states "vite v4.1.1 building for development...", and yet still get:
Unexpected Application Error!
Minified React error #130; visit https://re...

during preview, and deployment i.e. Vercel.
Still getting Minified React error #130 after trying suggestions above, and its funny. In the link presented I'm informed "We highly recommend using the development build...", lol, I'm trying to!!!!

Replying for google hits in case anyone elses searches for the library:
This tripped me up with react-modal. I fixed it, as above,
``
import * as RM from 'react-modal/lib';
const ReactModal = (RM as any).default || RM;

Hello, i've been tried to follows the step using

It's because esbuild is checking for __esModule at runtime and rollup is not. So it will happen to any library that has an entry point with
module.exports = require("./something");

Since this file does not include the 'magic string' __esModule as checked by https://github.com/rollup/plugins/blob/master/packages/commonjs/src/generate-exports.js#L82 it's not converted correctly.
vite dev vite build
import Switch from 'react-switch'; Switch	ok
import Switch from 'react-switch'; Switch.default		ok
import Switch from 'react-switch/dist/react-switch.dev.js'; Switch	ok	ok
So need to raise a bug in rollup for this.

hello, I want to use my custom component in other components of my project. I've been trying to follow this step, but unfortunately, I've got a problem while using google-maps-react.
Uncaught TypeError: dist.GoogleApiWrapper is not a function
    at MapContainer-a4e5bce3.js:75:29

here's the mapContainer file:
import { GoogleApiWrapper, Map, Marker, InfoWindow } from "google-maps-react";
import React, { Component } from "react";

class MapContainer extends Component {
  state = {
    selectedPlace: {},
    activeMarker: {},
    showingInfoWindow: false,
  };

  onMapClicked = (props) => {
    if (this.state.showingInfoWindow) {
      this.setState({
        showingInfoWindow: false,
        activeMarker: null,
      });
    }
  };

  onMarkerClick = (props, marker, e) => {
    this.setState({
      selectedPlace: props,
      activeMarker: marker,
      showingInfoWindow: true,
    });
  };

  onInfoWindowClose = (e) => {};

  render() {
    return (
      <Map
        google={this.props.google}
        style={{ width: "100%", height: "100%", borderRadius: "5px" }}
        initialCenter={
          this.props.origin === null
            ? { lat: -2.548926, lng:<PHONE_NUMBER> }
            : this.props.origin
        }
        center={
          this.props.origin
            ? this.props.origin
            : { lat: -2.548926, lng:<PHONE_NUMBER> }
        }
        zoom={this.props.origin === null ? 4 : 10}
        onClick={this.onMapClicked}
      >
        {this.props.origin ? (
          <Marker
            position={this.props.origin}
            onClick={this.onMarkerClick}
            name={this.props.originName}
          />
        ) : null}

        {this.props.destination ? (
          <Marker
            position={this.props.destination}
            onClick={this.onMarkerClick}
            name={this.props.destinationName}
          />
        ) : null}

        <InfoWindow
          marker={this.state.activeMarker}
          visible={this.state.showingInfoWindow}
        >
          <div>
            <h1>{this.state.selectedPlace.name}</h1>
          </div>
        </InfoWindow>
      </Map>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: import.meta.env.VITE_APP_GMAP_API_KEY,
})(MapContainer);

thank you

Glad I came across this thread. Kinda appreciate create-react-app.

stick to create-react-app, this is bs. Stuck with this error in production with no clue what is causing it

It's an issue with one of your imports. The way it's importing with export default is conflicting with how vite is processing modules
// this import causes an issue and I can't import it as { StyledFirebaseAuth }
import StyledFirebaseAuth from "react-firebaseui/StyledFirebaseAuth";

export const AuthComponent = (StyledFirebaseAuth as any).default
  ? (StyledFirebaseAuth as any).default
  : StyledFirebaseAuth;

// this import causes an issue and I can't import it as { StyledFirebaseAuth }
import StyledFirebaseAuth from "react-firebaseui/StyledFirebaseAuth";

export const AuthComponent = (StyledFirebaseAuth as any).default
  ? (StyledFirebaseAuth as any).default
  : StyledFirebaseAuth;

stick to create-react-app, this is bs. Stuck with this error in production with no clue what is causing it

// this import causes an issue and I can't import it as { StyledFirebaseAuth }
import StyledFirebaseAuth from "react-firebaseui/StyledFirebaseAuth";
export const AuthComponent = (StyledFirebaseAuth as any).default
? (StyledFirebaseAuth as any).default
: StyledFirebaseAuth;

stick to create-react-app, this is bs. Stuck with this error in production with no clue what is causing it

It's an issue with one of your imports. The way it's importing with export default is conflicting with how vite is processing modules
// this import causes an issue and I can't import it as { StyledFirebaseAuth }
import StyledFirebaseAuth from "react-firebaseui/StyledFirebaseAuth";

export const AuthComponent = (StyledFirebaseAuth as any).default
  ? (StyledFirebaseAuth as any).default
  : StyledFirebaseAuth;

I'm migrating a CRA app to Vite, and I encountered an error in dev mode:
react-dom.development.js:26923 Uncaught TypeError: _events2.default is not a constructor
    at BootstrapTableContainer.RemoteResolver (remote-resolver.js:132:29)
    at new BootstrapTableContainer (index.js:72:138)
    at constructClassInstance (react-dom.development.js:14323:18)
    at updateClassComponent (react-dom.development.js:19688:5)
    at beginWork (react-dom.development.js:21611:16)
    at beginWork$1 (react-dom.development.js:27426:14)
    at performUnitOfWork (react-dom.development.js:26557:12)
    at workLoopSync (react-dom.development.js:26466:5)
    at renderRootSync (react-dom.development.js:26434:7)
    at recoverFromConcurrentError (react-dom.development.js:25850:20)

An error which doesn't happen in CRA, notice that I'm using the same exact versions in the dependencies as with the old one, I didn't update or anything.
In my search, I came across the following:

https://github.com/react-bootstrap-table/react-bootstrap-table2/issues/1624
https://gist.github.com/FbN/0e651105937c8000f10fefdf9ec9af3d?permalink_comment_id=4413693#gistcomment-4413693
This issue here

But none of the solutions/workarounds presented anywhere actually worked, I was able to make the dev mode work by using the suggested solution -- which to use polyfills and stuff, but then I get this error here. Which again, doesn't happen in CRA.

@aprilmintacpineda the error you show doesn't seems related to this issue or the other links you listed. If you find an issue with Vite, and you would like to help the project, please create a minimal reproduction of your problem and a new bug report. But if you are happier with CRA, you should probably avoid migrating your project.

@patak-dev Okay maybe the following line wasn't clear.

I was able to make the dev mode work by using the suggested solution -- which to use polyfills and stuff, but then I get this error here. Which again, doesn't happen in CRA.

I edited it to be clearer.
My comment is actually complete together with the trace of where it started until where it is now, if you just read with the intent to understand -- the error started on bootstrap (and I added relevant links) which I was able to fix on dev mode, then after fixing that on dev mode and built for production, I got this error here which is already 3 years old.

@aprilmintacpineda thanks for the edit, that makes your comment more clear. Your comment doesn't add anything to this issue in particular though, so I suggest avoiding this kind of interaction with OSS projects. For example, you can provide a better minimal reproduction, or dig into this issue and try to see if you see other solutions that we haven't yet seen for it.

@aprilmintacpineda thanks for the edit, that makes your comment more clear. Your comment doesn't add anything to this issue in particular though, so I suggest avoiding this kind of interaction with OSS projects. For example, you can provide a better minimal reproduction, or dig into this issue and try to see if you see other solutions that we haven't yet seen for it.

I think my comment is complete with the leads, I posted that comment in hopes that someone will look into those leads and find a solution or an explanation on why this is happening on various projects. In addition to that, I'm not the only one experiencing the error, so I think it's good that everyone is putting in leads that may contribute to the problem being solved.
If you didn't find my comment useful, you always have the choice to ignore it just as you ignored all other comments above. This begs the question, why didn't you? Why did you find the need to respond to my comment but completely ignore the rest above? must be because I pointed out something obvious, which is that this issue has been ignore for 3 years and that it doesn't happen in CRA, and that offended you and provoked you to post comments that attempt to gatekeep me. I apologize for that, I may have phrase my comment in an offensive manner. I have edited my comment, hopefully this edited version is not as offensive to you (and to others too).
 My comment was actually clear even without the edit, you simply read with the intent to judge rather than understand. I recommend not practicing this gatekeeping behavior on OSS projects, OSS is "open" not "closed" you  should expect all sorts of comments to come through and you should exercise your ability to ignore (just as you've previously done) rather than react. Thank you for your time.

Again, what I said was that your comment was not helpful for this issue in particular. Thanks for editing the original post that ended with "Funny thing is, this issue is now 3 years old! Can you imagine that?". I took the time to answer you and avoid ignoring your post or marking it as spam because of that last line. Please let's move now this discussion to a better forum, I invite you to join https://chat.vitejs.com where we can chat about what accounts to healthy OSS interactions without notifying everyone that is subscribed to this issue (because they are interested in the issue itself and not in our discussion here). Thanks!

This is the actual solution for the problem which works pretty well. Recently I have migrated one of my big projects from CRA to Vite. Then after the build, I was getting that issue on my product. This solution helped me.
Thanks a lot.

There is some package that causes this error. Please remove those packages to solve this error. In my case, I installed an animation package and it caused this error. Then I wasn't sure but I removed this package and solved the error.

As I have said I just migrated one of my big projects from CRA to Vite and you know there are a lot of dependencies. So, it is not even possible to detect the actual culprit. So, I was looking for a solution and the above comment was very helpful to me.

Hi there, I have the same problem. It's telling me I have an invalid hook call and I have gone file by file looking for the repeated React import or hook used outside of a React component and found nothing substantial. Tried several changes including all of the above and still see the same error. In my case this is the libraries used:
    "axios": "^1.2.1",
    "file-saver": "^2.0.5",
    "js-cookie": "^3.0.1",
    "react": "^18.2.0",
    "react-animate-height": "^3.1.1",
    "react-countup": "^6.4.0",
    "react-dom": "^18.2.0",
    "react-loading": "^2.0.3",
    "react-router-dom": "^6.6.0",
    "react-select": "^5.7.0",
    "react-toastify": "^9.1.1",
    "recharts": "^2.2.0"```

    I'm pretty sure I can remove any of these packages for another one, do you think it's coming form one of them?

    This is my exact error btw:
    ```Uncaught (in promise) Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
    at it (blur.js:42:3933)
    at s.useContext (blur.js:42:5675)
    at cr (blur.js:57:31858)
    at blur.js:61:494
    at blur.js:126:5191
    at Generator.next (<anonymous>)
    at I (blur.js:126:4967)```

    What can I do? I am afraid of breaking production.

Can you copy your full error? And when you are getting this error? On vite build or where?

Hey there, didn't realise the error got cut somehow. Here is it in full:
Uncaught (in promise) Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
    at it (blur.js:42:3933)
    at s.useContext (blur.js:42:5675)
    at cr (blur.js:57:31858)
    at blur.js:61:494
    at blur.js:126:5191
    at Generator.next (<anonymous>)
    at I (blur.js:126:4967)

It says it's coming from context, here is my context ( simplified ) :
import axios from "axios";
import React, { useState, createContext, useEffect } from "react";
import Cookies from "js-cookie";

import Loading from "../components/general/Loading";
import { api } from "../helpers/api";

export const AuthContext = createContext(null);

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [isLoggedIn, setIsLoggedIn] = useState(null);

  const getUserInfo = async () => { ... };

  const updateUserInfo = async () => { ... };

  useEffect(() => {
    const checkAuthCookie = async () => { ... };
    checkAuthCookie();
  }, []);

  const login = (receivedUser) => { ... };

  const logout = () => { ... };

  if (isLoggedIn === null) return <Loading />;
  return (
    <AuthContext.Provider
      value={{ user, isLoggedIn, login, logout, updateUserInfo }}
    >
      {children}
    </AuthContext.Provider>
  );
};

``
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks

You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
``

This is basically the error that is happening on your code said by the error code decoder of React.
Take a look over your code, so you can confirm that your code doesn't contain any of mentioned above issues.

The extension's name is Loom, so if you are soming here looking for a solution and have Loom installed, most likely it's coming from there.

Had the same issue and it was Loom as well - thank you so much for updating the thread @ToneeEnguix !

I'm getting same error for react-coinbase-commerce
in the dist folder I opened the index.js and found that it export with something like this:
module.exports = (() =>

Which bundler you are using?

whatever vite use's by default

Bumped into this thread when I am migrating from CRA to Vite. Package that has problem is react-datetime. Yes the hacky solution do work but it's bad when it didn't show the problem in development

Modified version of the solution to prevent the raises of TS error :

import { createRequire } from 'module';
import { defineConfig } from 'vite';
import type { RollupCommonJSOptions } from '@rollup/plugin-commonjs';

const require = createRequire(import.meta.url);

export default defineConfig({
  build: {
    // Bugfix required to handle issue with vite, rollup and libs (like react-phone-input-2)
    commonjsOptions: {
      defaultIsModuleExports(id) {
        try {
          const module = require(id);
          if (module?.default) {
            return false;
          }
          return 'auto';
        } catch (error) {
          return 'auto';
        }
      },
      transformMixedEsModules: true,
    } as RollupCommonJSOptions,
  },
  // ...
})

I have some problem, but I use nextjs with yarn, im not using Vite
any solutions?

(to be clear this isn't a faulty package, it's how most things on npm work - it's just CJS)

with @mdi/react
https://github.com/Templarian/MaterialDesign-React/issues/69

You shouldn't need this if you're using the vite types: https://vitejs.dev/guide/features.html#client-types

Modified version of the solution to prevent the raises of TS error :
import { createRequire } from 'module';
import { defineConfig } from 'vite';
import type { RollupCommonJSOptions } from '@rollup/plugin-commonjs';

const require = createRequire(import.meta.url);

export default defineConfig({
  build: {
    // Bugfix required to handle issue with vite, rollup and libs (like react-phone-input-2)
    commonjsOptions: {
      defaultIsModuleExports(id) {
        try {
          const module = require(id);
          if (module?.default) {
            return false;
          }
          return 'auto';
        } catch (error) {
          return 'auto';
        }
      },
      transformMixedEsModules: true,
    } as RollupCommonJSOptions,
  },
  // ...
})

You shouldn't need to cast to RollupCommonJSOptions if you're using the vite client types: https://vitejs.dev/guide/features.html#client-types

Hello. Also ran into the 130 problem when building the project on the Vite. Found such a working solution in the documentation to add the following settings to viteconfig: optimizeDeps: {
include: ['esm-dep > cjs-dep']
}

This worked. Thank you

https://github.com/vitejs/vite/pull/8743 was merged June 24th. I guess this is fixed now, right?

Any update on this ? I am facing similar issue when using a package with default export https://www.npmjs.com/package/markdown-to-text and changing the export to named export solves the issue.

Are you hitting this issue for browser or SSR? I know there's still the inconsistency in SSR (which I want to look into for Vite 5), but I'm not sure about browsers if the comment above mentioned #8743 fixes it?

@ljharb I am facing the issue in browser. Changing the above mentioned library to named export fixes the issue. I am using vite version 4.4.2

Updating to 4.4.9 has fixed this for me

Are you hitting this issue for browser or SSR? I know there's still the inconsistency in SSR (which I want to look into for Vite 5), but I'm not sure about browsers if the comment above mentioned #8743 fixes it?

I can actually confirm that<EMAIL_ADDRESS>(which includes https://github.com/rollup/plugins/pull/1455) fixes this issue in the browser for me (haven't tried SSR). I've tried various packages with default exports such as react-csv-reader and the aforementioned markdown-to-text.
See also

https://github.com/vitejs/vite/issues/13378#issuecomment-1568794690
https://github.com/vitejs/vite/issues/13009#issuecomment-1522941747
https://github.com/vitejs/vite/issues/11986#issuecomment-1469577589

I've tried all the repros and packages mentioned here and I cannot reproduce the issue today (Vite 4.5.0). I'll close this as fixed. If you still see the issue, please leave a comment with a repro, or open a new issue. Thanks!

亲，你的信我已收到，真希望尽快看到它！


Spacing between list elements

When list text wraps to more than one line it can be hard to distinguish one list item from another. Adding extra spacing between the list items can make it easier to scan through and pick out the individual list items. Not sure of the best way to do this padding? margin? something else?:
Current list:

With 4px top padding:

With 8px top padding:

Examples pages: https://www.nice.org.uk/about/covid-19/support-for-developers-of-medicinal-products-for-covid-19

I'm not sure top padding/margin is the way to go as it moves lists out of alignment with other items potentially, so would favour bottom margin I think. Adding a bottom margin looks like this:

Which has the benefit (maybe?) that the first list item of a sub list is closer to the item above. Or does that just look wrong/weird? As in, should it be equal spacing? If we did want equal spacing then we'd have to opt for a padding top I think unless we do something for nested list items too. Not sure if any of that made sense.

We need to consider tabs and stacked navs if we're changing list item margins/paddings, and ensure there's no regressions in global nav

I'm not sure top padding/margin is the way to go as it moves lists out of alignment with other items potentially, so would favour bottom margin I think. Adding a bottom margin looks like this:

Which has the benefit (maybe?) that the first list item of a sub list is closer to the item above. Or does that just look wrong/weird? As in, should it be equal spacing? If we did want equal spacing then we'd have to opt for a padding top I think unless we do something for nested list items too. Not sure if any of that made sense.

This example looks good to me, makes sense to group the nested items underneath

Revisiting this as i think this could have a big impact on CKS with it's multiple list structure. Needs a bit more thought as you can get up to 3 level deep lists on CKS but spacing should help make it more scannable and readable until the underlying content can be properly marked up.
Examples
Values to be tweaked as needed, ignore left hand nav spacing - this wouldn't change.
3 level list
Current

Modified with margin bottom - ul il - 16px,  ul li ul li - 4px, ul li ul li ul li - 0px

2 level list
Current

Modified with margin bottom - ul li - 16px, ul li ul li - 4px


Custom textures

Is it possible to insert custom textures?

yes

Edit the textures in RP/textures/ folder.


react-native-video:mergeDebugAndroidTestResources FAILED

Current behavior
Describe what happens when you encounter this issue.
When react-native run-android, I encountered this issue.
Building and installing the app on the device (cd android && ./gradlew installDebug)...
Parallel execution with configuration on demand is an incubating feature.

> Configure project :app
AWS Device Farm Plugin version 1.3
WARNING: Configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.
It will be removed at the end of 2018. For more information see: http://d.android.com/r/tools/update-dependency-configurations.html
AWS Device Farm configuration is NOT VALID
AWS Device Farm configuration is NOT VALID
Could not find google-services.json while looking in [src/dev/kernel/debug, src/devKernel/debug, src/debug/devKernel, src/dev/debug, src/dev/kernel, src/dev/kernelDebug, src/devKernel, src/debug, src/devKernelDebug, src/dev, src/devDebug]
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
Could not find google-services.json while looking in [src/dev/kernel/release, src/devKernel/release, src/release/devKernel, src/dev/release, src/dev/kernel, src/dev/kernelRelease, src/devKernel, src/release, src/devKernelRelease, src/dev, src/devRelease]
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
Could not find google-services.json while looking in [src/prod/kernel/debug, src/prodKernel/debug, src/debug/prodKernel, src/prod/debug, src/prod/kernel, src/prod/kernelDebug, src/prodKernel, src/debug, src/prodKernelDebug, src/prod, src/prodDebug]
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
Could not find google-services.json while looking in [src/prod/kernel/release, src/prodKernel/release, src/release/prodKernel, src/prod/release, src/prod/kernel, src/prod/kernelRelease, src/prodKernel, src/release, src/prodKernelRelease, src/prod, src/prodRelease]
registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)

> Configure project :react-native-video
WARNING: The specified Android SDK Build Tools version (27.0.3) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.2.1.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '27.0.3'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.

* What went wrong:
Execution failed for task ':react-native-video:mergeDebugAndroidTestResources'.
> java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2InternalException: AAPT2 aapt2-3.2.1-4818971-linux Daemon #2: Daemon startup failed
  This should not happen under normal circumstances, please file an issue if it does.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2s
13 actionable tasks: 2 executed, 11 up-to-date
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/getting-started.html

Reproduction steps
A 1, 2, 3, etc. list of what's needed to see the issue happen.
Expected behavior
Describe what you wanted to happen
I excepted to work flawlessly
Platform
Which player are you experiencing the problem on:

iOS
Android ExoPlayer (x)
Android MediaPlayer
Windows UWP
Windows WPF

Video sample
If possible, include a link to the video that has the problem that can be streamed or downloaded from.
Actually it is not a video, i only want sound play from aws s3 services

facing same issue


use previously working node version until rush issue is fixed

Latest nodejs security patch breaks rush integration on Windows: https://nodejs.org/en/blog/vulnerability/april-2024-security-releases-2/
This can get builds moving again until the issue is fixed. We can also hold if we think it's worth waiting for.
See:

https://github.com/microsoft/rushstack/issues/4636
https://github.com/node-red/node-red/pull/4652

4.6.6 snuck in, but is prevented from releasing due to the error I am fixing in this PR. Reverting that so we can get green once again.

@mergifyio backport release/4.5.x


Add stress test and add metrics workload for stress

Description of the issue
Add a validator for Stress/Performance to leverage in case of running in containerized environment. Moreover, from now, developer only needs to supply a yaml and CloudWatchAgent Json Configuration in order to run the tests.

e.g Agent configuration
Test case yaml information

receivers: ["statsd"]
processors: []
exporters: []

test_case: "statsd_stress"
validate_type: "stress"
data_type: "metrics"
data_rate: "<data_rate>"
datapoint_period: 60

cloudwatch_agent_config: "<cloudwatch_agent_config>"

# Metric that the test needs to validate
metric_namespace: "CloudWatchAgentStress"
metric_validation:
  - metric_name: "procstat_cpu_usage"
    metric_dimension:
      - name: "exe"
        value: "cloudwatch-agent"
      - name: "process_name"
        value: "amazon-cloudwatch-agent"
  - metric_name: "procstat_memory_rss"
    metric_dimension:
      - name: "exe"
        value: "cloudwatch-agent"
      - name: "process_name"
        value: "amazon-cloudwatch-agent"
  - metric_name: "procstat_memory_swap"
    metric_dimension:
      - name: "exe"
        value: "cloudwatch-agent"
      - name: "process_name"
        value: "amazon-cloudwatch-agent"
  - metric_name: "procstat_memory_vms"
    metric_dimension:
      - name: "exe"
        value: "cloudwatch-agent"
      - name: "process_name"
        value: "amazon-cloudwatch-agent"
  - metric_name: "procstat_num_fds"
    metric_dimension:
      - name: "exe"
        value: "cloudwatch-agent"
      - name: "process_name"
        value: "amazon-cloudwatch-agent"
  - metric_name: "procstat_write_bytes"
    metric_dimension:
      - name: "exe"
        value: "cloudwatch-agent"
      - name: "process_name"
        value: "amazon-cloudwatch-agent"
  - metric_name: "net_bytes_sent"
    metric_dimension:
      - name: "interface"
        value: "eth0"
  - metric_name: "net_packets_sent"
    metric_dimension:
      - name: "interface"
        value: "eth0"

The validator service will have two modes: preparation (e.g preparing writing the agent configuration) and validate (sending the metrics and validate the metrics). Afterwords, the yaml which contains the test case information will be decoded by the validator and used widespread to validate the test case.
License
By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.
Tests
Running only stress test to confirm:

https://github.com/khanhntd/amazon-cloudwatch-agent/actions/runs/4075755079

When performance testing the internal, we learned logs are expensive. Should our logs performance test hit localstack? This may not be necessary since our internal performance out put is higher and runs indefinitely instead of only the time it takes to execute the test.

When performance testing the internal, we learned logs are expensive. Should our logs performance test hit localstack? This may not be necessary since our internal performance out put is higher and runs indefinitely instead of only the time it takes to execute the test.

Its expensive but it should be worthwhile in exchange for gaining customers. We only need to define the custom major use case for logs (e.g running 1000 data logs and see what customers should expect) additional would be how if we increase 1 log, what would be the CPU request, Memory request in exchange for it

Could this have been made in to smaller PRs.  Maybe starting with infra + hello world test, and then eventually adding the more complex tests.  This seems like it should be 2 or 3 PRs.  It is hard to review this many changes

Could this have been made in to smaller PRs. Maybe starting with infra + hello world test, and then eventually adding the more complex tests. This seems like it should be 2 or 3 PRs. It is hard to review this many changes

Some changes are moving to the general function. However, IMO, I don't think its a large scale change enough to introduce into many PRs since the only purpose is to validate the metric  (sample count, value, etc). If I am wrong, please correct me.

When performance testing the internal, we learned logs are expensive. Should our logs performance test hit localstack? This may not be necessary since our internal performance out put is higher and runs indefinitely instead of only the time it takes to execute the test.

Its expensive but it worthwhile to help us in know the characteristics of CWAgent, same for customers too. We only need to define the customer major use case for logs (e.g running 1000 data logs and see what customers should expect) additional would be how if we increase 1 log, what would be the CPU request, Memory request in exchange for it

Agree with everyone ;). I recommend start with the simple form of the test which uses the real CloudWatch Logs backend. If/when we decide cost is prohibitive we add a more complex solution using LocalStack, or even making it a test option on which backend to use.

Agree with everyone ;). I recommend start with the simple form of the test which uses the real CloudWatch Logs backend. If/when we decide cost is prohibitive we add a more complex solution using LocalStack, or even making it a test option on which backend to use.

The criteria for me when choosing test double would be:

Determinism
Dependency construction
Execution time

Cost maybe not the factor here since failing is a good thing as long as we able to identify the root cause ! Using local stack would make it harder to maintain or improve


Allow default reports to be updated in place

Migrated from GitLab: https://gitlab.com/meltano/meltano/-/issues/1914
Originally created by @DouweM on 2020-03-26 22:53:17

View 4 previous comments from the original issue on GitLab


Review the "merge all pending changes from google doc" commit

In commit a68803b1, a lot of changes were merged into the guideline without proper discussion. Those originated as change proposals in our internal Google doc, and had different states of approval at this point.
I was already surprised by several of those changes since then. I guess we should go systematically over all those changes and discuss whether they are good, and then possibly roll back the bad ones, or replace the text with better text.
This issue is a meta issue, we should create separate issues for individual points.

Apart from #42 all the sub-issues are now closed, so I'm closing this one too.


Search old results by one state

Hello!
I have an issue, which happens just on stage and production servers. On localhost everything works fine.
I’m using react-instantsearch-dom inside Next.js project.
The problem is that results, visible for a user, are old, they were fetched by previous search state, not by current one. In other words:

you see initial search page with all results
you type search query for a 1st time - nothing changed (but in this step results should be different)
you change search param/query again and see results from step 2 (in this step you already have 3rd SearchState)
you change something - create 4th SearchState, but see results from step 3

Like one step behind, hope I clearly explained it.
To my mind the problem is in connectInfiniteHits, because in console I see that Algolia made a correct request (by new SearchState, also url is updating correctly), in response there is a new portion of data, but inside connectInfiniteHits component I receive an old portion of data (by previous search state, not by current). It’s soooo bad for user experience and I don’t understand what is wrong.
Will be appreciate for any suggestion and help

Looks like this is a duplicate of https://github.com/algolia/react-instantsearch/issues/3018, will handle there :)


Feature request: Nice fluent interfaces

I often find myself writing a lot of:
$mockIterator = m::mock('SomeClass')
$mockIterator    ->shouldReceive('rewind')
                   ->andReturn($mockIterator)
                 ->shouldReceive('next')
                   ->andReturn($mockIterator)
                 ->shouldReceive('valid')
                   ->andReturn(false)
                 ->shouldReceive('current')
                   ->andThrow('SomeException')
                 ->mock();

As much as I love it, notice I have to instantiate the object - and then use it again to return itself - which seems a bit of a hack to be honest.
I think it could be a lot nicer if we could have something like this perhaps:
$mockIterator = m::mock('SomeClass')
                 ->shouldReceive('rewind')
                   ->andReturn(m::this())
                 ->shouldReceive('next')
                   ->andReturn(m::this())
                 ->shouldReceive('valid')
                   ->andReturn(false)
                 ->shouldReceive('current')
                   ->andThrow('SomeException')
                 ->mock();

or even:
$mockIterator = m::mock('SomeClass')
                 ->shouldReceive('rewind', 'next', 'someOtherFluentMethod')
                   ->andReturn(m::this())
                 ->shouldReceive('valid')
                   ->andReturn(false)
                 ->shouldReceive('current')
                   ->andThrow('SomeException')
                 ->mock();

Added to master :P. You can use the new \Mockery::self() static call when setting expectations to grab the current mock more easily.


DRYing up the test suite using pytest fixtures

Using pytest fixtures for test cases. Resolves #2287

@Tafkas can you resolve the merge conflicts?
Is this otherwise ready for final review/merge or are you still working on it?

I am finished. I keep resolving merge conflicts after upstream keeps changing. @davidism

Thanks again @Tafkas! Really, really appreciated.


Lookup altitude2

[x] Closes #1516
[x] I am familiar with the contributing guidelines
[x] Tests added
[x] Updates entries in docs/sphinx/source/reference for API changes.
[ ] Adds description and name entries in the appropriate "what's new" file in docs/sphinx/source/whatsnew for all changes. Includes link to the GitHub Issue with :issue:`num` or this Pull Request with :pull:`num`. Includes contributor name and/or GitHub username (link with :ghuser:`user`).
[x] New code is fully documented. Includes numpydoc compliant docstrings, examples, and comments where necessary.
[x] Pull request is nearly complete and ready for detailed review.
[x] Maintainer: Appropriate GitHub Labels (including remote-data) and Milestone are assigned to the Pull Request and linked Issue.

In this pull request, I fix the outstanding issues from the last pull request and replace functions to use lookup_altitude by default

The coverage for the spa_c solar position method keeps failing even though it is covered in tests.
Could that be caused by a dependency issue? Like the spa.c and spa.h files missing from the test?

@nicomt we're on the cusp of releasing 0.9.3, which includes your last PR.  Do you agree that there is no problem making that release without including this PR?  Since some defaults are changing, I think it makes sense to wait for 0.10.0 here, just want to confirm that the previous PR can stand on its own without this one.

Those concerns are valid, and leaving sea level as the default seems reasonable.
I can close this PR, but then that leaves us with a few options:

We make the altitude lookup automatic for the Location class only.

loc = Location(latitude, longitude)  # altitude == location.lookup_altitude
spa_c(times, latitude, longitude) # altitude == 0

We integrate the altitude lookup everywhere but make it more explicit

loc = Location(latitude, longitude)  # altitude == 0
spa_c(times, latitude, longitude) # altitude == 0
loc = Location(latitude, longitude, altitude="lookup")  # altitude == location.lookup_altitude
spa_c(times, latitude, longitude, altitude="lookup")  # altitude == location.lookup_altitude

We make the altitude lookup explicit and only available for the Location class.

loc = Location(latitude, longitude)  # altitude == 0
loc = Location(latitude, longitude, altitude="lookup")  # altitude == location.lookup_altitude
spa_c(times, latitude, longitude)  # altitude == 0

We leave it as it is and let the user pass the altitude manually

loc = Location(latitude, longitude, altitude=location.lookup_altitude(latitude, longitude))
spa_c(times, latitude, longitude, altitude=location.lookup_altitude(latitude, longitude))

What do you guys think?

Closing for now.
While we decide what to do.

@nicomt my vote is #1, let Location lookup altitude, but require it explicitly for the solar position functions.


Add ignoreHTTPSError option on journeys and CLI

Users sometimes need to test sites that have known bad certs, we should probably  set this on a per-journey and CLI options level, both probably have their uses. See https://github.com/microsoft/playwright/issues/2814 for more info on implementation, it's a browser level option.

We could start supporting chrome flags and other options when launching suites. Could also work for our emulation strategy if we are going to depend on devtools emulation for network and cpu slowdown.

We could start supporting chrome flags and other options when launching suites. Could also work for our emulation strategy if we are going to depend on devtools emulation for network and cpu slowdown.

Hey, @andrewvc  and @vigneshshanmugam any fix of this using Synthetic run.


Validation has incorrect caching of stale schema version

Describe the bug
As I'm working on a spec I will see errors pop up (correctly) indicating that I've violated some rule or other. As I update the specification and correct the errors, it appears revalidation still finds those errors. Watching the validation happening in the Spectral output window, I definitely see it finding errors that aren't there anymore.
I can then jump over to my web browser (like now) and, without changing anything, see the Spectral linting get kicked off, like it's a queue of validation requests that have somehow been delayed against stale versions of the document. The "dam broke" and the old requests for validation suddenly started going through but instead of being the latest copy of the document, it's a cached version - the version that was there when the request to lint got kicked off.
That queue logic/explanation sort of makes sense - since that is pretty much how validation gets kicked off. I remember I grabbed that from the (MIT licensed) ESLint plugin implementation and I don't know if perhaps they've figured out some improvements to the mechanism or something since the Spectral extension started.
This seems to happen more with large schemas (e.g., 2700 lines, 20 paths, 50 operations) rather than smaller schemas (maybe 1000 lines, 10 paths, etc.). Unclear if there's a tie between memory usage or schema size and the delay here.

I've verified that rolling back to 1.1.0 seems to resolve the delay/caching problem. I don't see much that happened between 1.1.0 and 1.1.2 other than some package updates, so something in there is going to be the problem.


Exceptions with headers are converted to errors without those headers

When using middleware that rejects a request by throwing an exception it is eventually passed off to JsonApi handler to create a valid jsonapi error object.
However for some errors that add headers to the response, and those headers are lost. Most notably, and easily reproducible, it happens when you configure a throttle middleware and hit the rate limit. This generates a ThrottleRequestsException and it includes some headers that should be added to the response that inform the user-agent when it is allowed to make requests again.
JsonApi should probably include headers from exceptions that have them.
It seems like some thought was already put into it, as there is a function to do just that, but it doesn't do anything currently.
ExceptionParser.php:231
/**
 * @param Exception $e
 * @return array
 */
protected function getHeaders(Exception $e)
{
    return [];
}

Shouldn't this just do the following:
/**
 * @param Exception $e
 * @return array
 */
protected function getHeaders(Exception $e)
{
    return method_exists($e, 'getHeaders') ? $e->getHeaders() : [];
}

Or am I missing something?
I can imagine how you could have cases where exception generate undesirable headers or conflicts, but for me it feels like it might be better to handle those cases as they popup/are found, there shouldn't be too many.

Thanks for pointing this out - think when I wrote ExceptionParser::getHeaders (a long time ago) there weren't Laravel exceptions with getHeaders methods... or at least I wasn't aware of any!

The ThrottleRequestsException extends Symfony\Component\HttpKernel\Exception\HttpException where the headers are added as an option.
This class is used as a prototype for pretty much all HTTP type exceptions I could find, and I think it is safe to assume that any exceptions extending this class have a http-safe headers object. Checking for that would be stricter / less prone to errors.
So maybe this is enough/cleaner
return ($e instanceof HttpException ? $e->getHeaders() : []);

You already also check for this class in the getErrors method too, so maybe more consideration for this type could clean things up even more.
Maybe there is a case to be made to allow adding extra headers to the Error object so that Exception -> Error conversions are a more direct mapping of attributes. Rendering a response that combines the headers if there are multiple errors with extra headers somehow. Maybe not, also seems kinda messy 😛
Looking forward to the 1.0.0 release. Thank you for the effort!

@sg3s thanks for pointing this out, it's a neat addition!


question: changing index on database upgrades

I currently serialise my DB to disk, and I see that this includes the indexes on the collections contained in it. If at some point I need to update what I want indexed on a collection, how can I do this while retaining the data? The only place I see I can specify my index is in addCollection, but after DB load, the collections + indexes are already there.

Currently there is no api for this but you can manually do this after loading / before saving :
// remove all binary indexes
coll.binaryIndices = {};

// Unique indexes are not saved but their names are (to be rebuilt on every load)
// This will remove all unique indexes on the next save/load cycle
coll.uniqueNames = [];

We probably should add a few official api methods to this... maybe in next week or so.

So those remove them, but how do I add new ones?

Or can I just assign to those after load to have them be rebuilt?

// add binary index
coll.ensureIndex("lastname");

// add unique index
coll.ensureUniqueIndex("userId");

Those methods are covered in docs on Techfort's website also :
http://lokijs.org/#/docs

Super -- thanks!

Given that I have previously declared addCollection('cache', { indices: ['itemID', 'exportCharset', 'getCollections', 'exportNotes', 'translatorID', 'useJournalAbbreviation', 'citekey'] })
How do I detect that I still have an index on getCollections after load so I can remove it?

You can examine the collection.binaryIndices object.  Plug this into loki sandbox and run it so see example :
var db = new loki('test');
var coll = db.addCollection('cache', { indices: ['itemID', 'exportCharset', 'getCollections', 'exportNotes', 'translatorID', 'useJournalAbbreviation', 'citekey'] });

logObject(coll.binaryIndices);

or I think this will work :
if (collection.binaryIndices.hasOwnProperty("getCollections")) {
  delete collection.binaryIndices.getCollections;
}

Super! But then simply
delete collection.binaryIndices.getCollections;

should also work


EDEV-93: Image Block transcript + translations

Ticket URL: EDEV-93
About these changes
Added transcript + translation values from the CustomImage model to the returned JSON when the APIImageChooserBlock is turned into the API representation.
How to check these changes
http://localhost:8000/api/v2/pages/202/ and look at some images
Before assigning to reviewer, please make sure you have

[x] Checked things thoroughly before handing over to reviewer
[x] Checked PR title starts with ticket number as per project conventions to help us keep track of changes
[x] Ensured that PR includes only commits relevant to the ticket
[x] Waited for all CI jobs to pass before requesting a review
[x] Added/updated tests and documentation where relevant

Merging PR guidance
Follow docs\developer-guide\contributing.md
Deployment guidance
Follow docs\infra\environments.md

How easy would it be to get the value of the heading? In the case below, "Partial transcript"?
If easy then could we do that? If not, I can do it in the front end but it feels like that should come from the CMS.

@ahosgood done!


Update plutus & dependencies

endpoint seems to be taking a continuation now and return a Promise
use selectList to switch between multiple promises and await the first of them
The default port switched to 9080 so I have consistently hard-coded it to 8888
The PAB API seemingly is not "new" anymore so those paths components needed to be dropped

LGTM. This change from Contract -> Promise is quite significant but might help clarifies the API?

I did like the fact that endpoint was just another side effect which can be done in Contract though.. but whatever, it's glue code to us.


Add into_builder methods for Arrays

Is your feature request related to a problem or challenge? Please describe what you are trying to do.
While working with various arrays and builders in DataFusion one thing that we often want to do is convert between an array and some modifiable version of it (for example, in StringView trim it would be nice to just modify existing views rather than mutate them)
I think in general it would be good to use the various Builder APIs for this
Describe the solution you'd like
I would like all the Arrays to have equivalent methods to PrimitiveArray::into_builder().
Like I want to be able to do
let array: StringViewArray = ...;
let builder = array.into_builder();
// mutate the builder (more APIs TBD)
// recreate the array
let array = builder.build()

Similarly it would be nice to do something similar with BooleanBuiler, possibly other arrays
Describe alternatives you've considered

Additional context
Example DataFusion PRs: https://github.com/apache/datafusion/pull/12395

Yes, I think into_builder is something necessary to make in-place modification for performance.
I think maybe another promising improvement in datafusion https://github.com/apache/datafusion/pull/12526 requires this ability to run even better, too.
Maybe I can help this.

I'm glad to work on this ticket. Thanks @Rachelint.

take.

@ShiKaiWi  I would recommend:

Start with a single array type (perhaps BooleanArray)
Add an example of using the into_builder as a doc comment

Perhaps initially start with something like this
let arr: BooleanArray = vec![true, true, false].into();
let mut builder = arr.into_builder()
// Append 2 new rows
builder.append_value(false);
builder.append_null();
let arr = builder.finish();
assert_eq!(....)

When trying to start from the BooleanArray, I find that the current BooleanBufferBuilder can't reuse the buffer from a sliced BooleanArray if the slicing is not aligned.
Here is the BooleanBufferBuilder's definition:
pub struct BooleanBufferBuilder {
    buffer: MutableBuffer,
    len: usize,
}

And it assumes that the boolean values must start from the first bit, but a sliced BooleanArray may skip some bits of the first byte. So I guess I have to enhance the BooleanBufferBuilder by adding an offset field to support reuse of the buffer of a sliced BooleanArray first.
@alamb @Rachelint Please let me know your opinions.

When trying to start from the BooleanArray, I find that the current BooleanBufferBuilder can't reuse the buffer from a sliced BooleanArray if the slicing is not aligned.
Here is the BooleanBufferBuilder's definition:
pub struct BooleanBufferBuilder {
    buffer: MutableBuffer,
    len: usize,
}

And it assumes that the boolean values must start from the first bit, but a sliced BooleanArray may skip some bits of the first byte. So I guess I have to enhance the BooleanBufferBuilder by adding an offset field to support reuse of the buffer of a sliced BooleanArray first.
@alamb @Rachelint Please let me know your opinions.

Yes, it is a actually problem for converting from BooleanArray to BooleanBuilder.
And for in-place modification, I found another challenge that we can't modify bit through index using BooleanBuilder?
In my opinion, can we define something like BooleanArrayMutator? I am still reading codes and thinking.

In my opinion, can we define something like BooleanArrayMutator? I am still reading codes and thinking.

I think we can use the builders for this rather than adding a new API. I think we can use the existing structures for low level manipulation we made it a bit easier to convert between them.
I think we should make conversion from array --> builder such that they don't copy if possible, but if necessary copy the underlying buffers. A sliced array is likely to be share so copying the bitmap to modify it will be needed anyways

And for in-place modification, I found another challenge that we can't modify bit through index using BooleanBuilder?

The lower level BooleanBufferBuilder contains the relevant APIs, like this:
https://docs.rs/arrow/latest/arrow/array/builder/struct.BooleanBufferBuilder.html#method.set_bit
Rather than changing BooleanBuilder to allow direct manipulation of the underling boolean buffer, maybe we could make it easier to further destructure it (see source)
For example
// convert boolean array --> BooleanBuilder
let builder = boolean_array.into_builder();

// Deconstruct the BooleanBuilder into `BooleanBufferBuilder` and `NullBufferBuilder
let (bool_builder, null_builder) = builder.into_builders();

.. modify the boolean/null buffers via low level builders

// put it back together
let builder = BooleanBuilder::new_from_builders(bool_builder, null_builder);
let array = builder.finish()

new_from_builders is inspired by https://docs.rs/arrow/latest/arrow/array/builder/struct.PrimitiveBuilder.html#method.new_from_buffer

In my opinion, can we define something like BooleanArrayMutator? I am still reading codes and thinking.

I think we can use the builders for this rather than adding a new API. I think we can use the existing structures for low level manipulation if we made it a bit easier to convert between them.
I think we should make conversion from array --> builder such that they don't copy if possible, but if necessary copy the underlying buffers. A sliced array is likely to be share so copying the bitmap to modify it will be needed anyways

And for in-place modification, I found another challenge that we can't modify bit through index using BooleanBuilder?

The lower level BooleanBufferBuilder contains the relevant APIs, like this: https://docs.rs/arrow/latest/arrow/array/builder/struct.BooleanBufferBuilder.html#method.set_bit
Rather than changing BooleanBuilder to allow direct manipulation of the underling boolean buffer, maybe we could make it easier to further destructure it (see source)
For example
// convert boolean array --> BooleanBuilder
let builder = boolean_array.into_builder();

// Deconstruct the BooleanBuilder into `BooleanBufferBuilder` and `NullBufferBuilder
let (bool_builder, null_builder) = builder.into_builders();

.. modify the boolean/null buffers via low level builders

// put it back together
let builder = BooleanBuilder::new_from_builders(bool_builder, null_builder);
let array = builder.finish()

new_from_builders is inspired by https://docs.rs/arrow/latest/arrow/array/builder/struct.PrimitiveBuilder.html#method.new_from_buffer

Got it!
The alternative may can be something like slices_mut in PrimitiveBuilder?
impl<T: ArrowPrimitiveType> PrimitiveBuilder<T> {
       /// Returns the current values buffer and null buffer as a slice
      pub fn slices_mut(&mut self) -> (&mut [T::Native], Option<&mut [u8]>) {
          (
              self.values_builder.as_slice_mut(),
              self.null_buffer_builder.as_slice_mut(),
          )
      }
}

We offer the similar api like:
impl BooleanBuilder {
    pub fn builders_mut(&mut self) -> (&mut BooleanBufferBuilder, &mut NullBufferBuilder) {
      ...
    }
}

@ShiKaiWi I read codes today, and I found maybe we can use BooleanArray::sliced to solve the offset problem.
It may be not so efficient if found buffer not aligned(clone will be triggered), but can work currently.

Thanks a lot for your responses and suggestions. @alamb @Rachelint
In conclusion, the two problems and the proposed solutions to them are as follows:
1. Whether to clone the underlying buffer for the unaligned-sliced boolean array

I think we should make conversion from array --> builder such that they don't copy if possible, but if necessary copy the underlying buffers. A sliced array is likely to be share so copying the bitmap to modify it will be needed anyways

I read codes today, and I found maybe we can use BooleanArray::slicedBooleanBuffer::sliced to solve the offset problem.
It may be not so efficient if found buffer not aligned(clone will be triggered), but can work currently.

Basically, I agree with using BooleanBuffer::sliced to get the underlying buffer, which may introduce clone.
However, it makes me worried that in the implementation of PrimitiveArray::into_builder the error will be thrown if the underlying buffer is found shared, and here is the comment of it:
    /// Returns a `PrimitiveBuilder` for this array, suitable for mutating values
    /// in place.
    ///
    /// # Buffer Reuse
    ///
    /// If the underlying data buffer has no other outstanding references, the
    /// buffer is used without copying.
    ///
    /// If the underlying data buffer does have outstanding references, returns
    /// `Err(self)`
    pub fn into_builder(self) -> Result<PrimitiveBuilder<T>, Self> {
    ...
    }

And if we allow the clone for BooleanArray::into_builder the consistency of into_builder between PrimitiveArray::into_builder and BooleanArray::into_builder will be broken, and will it be confusing?
Actually, I'm in favor of totally avoiding copying for a not-shared sliced boolean array for performance and api consistency, but some breaking changes in the public api of BooleanBufferBuilder will be introduced...
So considering the api consistency, shall we insist on allowing clone for sliced BooleanArray?
2. Allow direct manipulation of the underling boolean buffer
The proposed solutions are similar -- exposing the underlying two builders. However, the provided two builders are required to be manipulated correctly, which seems not user-friendly, if some bit needs to be set/unset. And I guess it would be better if we add a new method to the BooleanBuilder:
    pub fn set_bit(&mut self, index: usize, v: Option<bool>) {
    ... manipulating the `BooleanBufferBuilder` and `NullBufferBuilder`.
    }

So how about this proposal?

So considering the api consistency, shall we insist on allowing clone for sliced BooleanArray?

No, I think we should follow the model of PrimitiveArray rather than cloning implicitly

The proposed solutions are similar -- exposing the underlying two builders. However, the provided two builders are required to be manipulated correctly, which seems not user-friendly, if some bit needs to be set/unset. And I guess it would be better if we add a new method to the BooleanBuilder:

I think we should still permit converting BooleanBuilder into its two internal builders as well as creating a BooleanBuilder from the two builders - I agree it is not as user friendly but it offers the most control
Adding some additional easier to use apis like BooleanBuilder::set_value also seems reasonable to me, as we have usercases for them
So perhaps we can first focus on more easily converting back / forth between builders, and then we can figure out what additional APIs we could add to the builders to make it easier to use?


Unnecessary delay before fading-in new tab pane - tab.js

Using version 4.1.0, I found out a delay before new tab pane is shown with JS behavior and fade effect.
This delay is the transition-duration value of the fade utility class.
Issue comes from the _activate method, line 144 in tab.js file.
There is a listener added to the previously activated tab pane for the transitionend event, but no classes are added to this element after that, so only the emulator can triggers the callback which activates the new one.
Have a look at the demo in the official doc.

This is a huge problem for ie11 and edge. The page containing say 4 tabs loads with the first one active and shown, but when we click on the second or third tab the inspector shows the active and fade classes applied properly but the tabpane is always blank. When I click on the tabpane in the inspector then the content becomes visible in the tab pane. I was not able to understand why it is happening but now it seems it may be related to this problem - outlined above by @Djules

@Djules Thanks for the tip. I was infact using 4.0.0 , I upgraded it to 4.1.0 , however the problem remains. I don't know why?

In 4.0.0 : https://codepen.io/Johann-S/pen/LmgVKL?editors=1010#0
In 4.1.1 : https://codepen.io/Johann-S/pen/Xqxbvd?editors=1010#0
I don't see a difference 😟

@Johann-S There is no difference indeed, still the issue is there, don't you see the 150ms delay when switching tab, before the new tab pane shows up?
If you increase the transition-duration value for the fade effect, the delay increases obviously (since 4.1.0).
Here is a fork of the 4.1.1 demo with a fix : https://codepen.io/Djules/pen/ELdPer
I'm going to give a PR about that.

yep but that's the behavior we had since the beginning 🤔 and that's why we added the ability to change that value with CSS

I made a quick demo with Bootstrap 3.3.7 : https://codepen.io/Djules/pen/ELdKPq
As you can see, there were no delay when switching tabs; current one fade-out then new one fade-in.

That's strange 🤔 because that's the same in v3 (https://github.com/twbs/bootstrap/blob/v3.4.0-dev/js/tab.js#L108)

The next line is the one which actually fade-out the active tab: https://github.com/twbs/bootstrap/blob/v3.4.0-dev/js/tab.js#L111
There is no such line in v4, this is the fix I made in the 4.1.1 demo above.

I saw you removed .active before the transition-end event, but why ?
It'll be done by this line after the transition : https://github.com/twbs/bootstrap/blob/v4-dev/js/src/tab.js#L175 ?

It'll be done by this line after the transition

I agree, but what triggers this transition ? There is no class added or removed to the active tab before the callback, so there is no transitionend event triggered from CSS, only the emulator did.
It's pretty clear for me where the issue comes from but it doesn't seem for your…
By the way, thanks for your time involved.

Ok I understand, I made a CodePen which demonstrate what you explained see: https://codepen.io/Johann-S/pen/jxeRoa?editors=1010#0
Open the console and you'll see a warning which said: transition end not called, emulate
BTW it was better in Alpha 6 than now see: http://v4-alpha.getbootstrap.com/components/navs/#javascript-behavior
And now: https://getbootstrap.com/docs/4.1/components/navs/#javascript-behavior

@Johann-S: is this still valid?

Yep still valid


Fix warning of environment injector plugin

Warnings have been published for the following currently installed components.
Environment Injector Plugin 2.1.6
Exposure of sensitive build variables stored by EnvInject 1.90 and earlier

I read the reason of warning. I can ignore the warning.


Run periodic cleanup before installing any formulae

[x] Have you followed the guidelines in our Contributing document?
[x] Have you checked to ensure there aren't other open Pull Requests for the same change?
[x] Have you added an explanation of what your changes do and why you'd like us to include them?
[ ] Have you written new tests for your changes? Here's an example.

[x] Have you successfully run brew typecheck with your changes locally?
[ ] Have you successfully run brew tests with your changes locally?

This makes brew install and co. run the monthly automatic cleanup before any formulae are installed so that there isn't a wall of text in the middle of the install/upgrade output.

I like this idea but I don't know how necessary it really is since the periodic cleanup only runs periodically. It would be a nicer user experience though because it'd be a bit less confusing.
If we decide to do this, I think there are two things we should consider first.

We've been discussing runningbrew autoremove after the periodic cleanup based on the presence of the HOMEBREW_AUTOREMOVE environment variable (#13532). I mention this because it would make the periodic cleanup output even more verbose. Does that change when we want this to periodic cleanup to happen? Would it be better to run this afterwards instead of before?
I think it would make more sense for the #periodic_clean! and #install_formula_clean! methods to be class methods though that would require more refactoring inside of the Cleanup class.

Would it be better to run this afterwards instead of before?

Yeh, I think running the periodic brew cleanup after all brew install/brew reinstall/brew upgrade have completed would make more sense than running before (like in this PR) and both make more sense than the current master behaviour.

Thanks for reviewing, I like what I have now a lot better!!

Let's land https://github.com/Homebrew/brew/pull/13532 first, I think it's going to conflict.

Let's land #13532 first, I think it's going to conflict.

@MikeMcQuaid I'm not sure when I'm gonna get around to finishing that PR (things have been busy lately) so go ahead and merge this in when you think it's ready.

@FnControlOption I just merged in #13532 which means this should be ready to go after resolving merge conflicts (luckily it doesn't seem like there are a lot). Sorry, it took me so long to finish the other PR.

Great work again @FnControlOption!


Connectivity_plus detect no-network on Android M and above

Description
connectivity_plus plugin uses ConnectivityManager.NetworkCallback() when the Android OS version is VERSION_CODES.M or above.
Once the network is changed, it sends the latest network state to Flutter by using ConnectivityManager.getActiveNetwork()
(Ref: connectivity_plus/android/src/main/java/dev/fluttercommunity/plus/connectivity/Connectivity.java)
Sometimes getActiveNetwork() returns the network interface (not null) which is just disconnected for network disconnection.
This causes that the network state is shown as connected when it's disconnected.

I just created a simple patch since the issue #290 is not fixed quickly. If you have a better fix already prepared, please ignore this PR.

Related Issues
https://github.com/fluttercommunity/plus_plugins/issues/290
Checklist
Before you create this PR confirm that it meets all requirements listed below by checking the relevant checkboxes ([x]).
This will ensure a smooth and quick review process. Updating the pubspec.yaml and changelogs is not required.

[x] I read the Contributor Guide and followed the process outlined there for submitting PRs.
[ ] My PR includes unit or integration tests for all changed/updated/fixed behaviors (See Contributor Guide).
[x] All existing and new tests are passing.
[ ] I updated/added relevant documentation (doc comments with ///).
[x] The analyzer (flutter analyze) does not report any problems on my PR.
[x] I read and followed the Flutter Style Guide.
[ ] I am willing to follow-up on review comments in a timely manner.

Breaking Change
Does your PR require plugin users to manually update their apps to accommodate your change?

[ ] Yes, this is a breaking change (please indicate a breaking change in CHANGELOG.md and increment major revision).
[x] No, this is not a breaking change.

@innim98 can you please increase the version in the package and add a changelog so we can release it after merging.

Updated the version and change log. Thank you.

@mhadaily yes, make sense to me!

@mhadaily could you merge if it's okay?


Changing the color of the dark grey Table Barcharts in the cells

Great job Nicolas!
This is my first time of using this and its absolutely great.
When i use Table Barchart the barcharts are in dark grey. Is there a way to change the color to something else?
Secondly changing the light grey color for the header and column where the row and column labels go?
I tried changing some of the colors in the pivot.css but that did not help.
Help on the above two will be very much appreciated.
As a suggestion or an enhancement will be the ability to change the Table Barcharts to different colors based on the values in the cells. Just like the heat map but instead of shades of one color different colors instead.
Thanks

Glad you like this library, and sorry I didn't reply to this sooner!
There is no way to change the colour of the bars in the Table Barchart renderer at the moment without modifying the code, although the header and column colours should be easy to change in pivot.css on lines 10 and 55.


machine capacity used

Hello, What is the capacity of the machine used (Ram) to training the model ?
I need advice on a platform that I could use to train the model taking into account the requirements.
I can't create a virtual environment on kaggle to take into account the requirements.

you can use google colaboratory. The RAM  should be enough or else you can change the batch size

python version 3.7

What is version of python used ?
Le lun. 13 juin 2022 à 10:20, Punyajoy Saha @.***> a
écrit :

Closed #12 https://github.com/hate-alert/HateXplain/issues/12 as
completed.
—
Reply to this email directly, view it on GitHub
https://github.com/hate-alert/HateXplain/issues/12#event-6794439496, or
unsubscribe
https://github.com/notifications/unsubscribe-auth/AQRTCMN3PY3HG5CXFIPGT6DVO34PPANCNFSM5O4F2XYQ
.
You are receiving this because you authored the thread.Message ID:
@.***>