Skip to content

Destructuring and prototype with ESM builds #183

@M3kH

Description

@M3kH

When consuming orga you can stubble in such error.

    TypeError: Cannot read properties of undefined (reading 'level')

      160 |       snapshot = {
      161 |         stack: [...stack],
    > 162 |         level: this.level,
          |                     ^
      163 |         attributes: { ...this.attributes },
      164 |         savePoint: lexer.save(),
      165 |       }

      at save (src/parse/context.ts:162:21)
      at drawer (src/parse/drawer.ts:7:3)
      at Object.parse (src/parse/index.ts:132:23)
      at Object.parse (src/index.ts:21:10)
      at src/__tests__/index.test.ts:87:18

The culprit of this issue is when we use this in an object that gets destructured during the consume phase.

An example is the usage of this in packages/orga/src/parse/context.ts which gets destructured here.

The issue is not currently visible in this repository because seems to mainly happen when ESM is enable.

How to reproduce it
An easy way to reproduce it is change the following line:

 {
-  "extends": "../../tsconfig.base.json",
+  "extends": "../../tsconfig.esm.json",
   "compilerOptions": {
     "rootDir": "./src",
     "outDir": "./dist"

And run the test.

Additional thoughts
I believe the right way to solve it is by making sure of not destructuring when relay on scope.
Since this plain JavaScript also fails:

const obj = {
  foo: function () {
    return this.bar;
  },

  get bar() {
    return "hello";
  },
};

const a = (p) => p.foo();
const b = ({ foo }) => foo();

console.log(a(obj));
console.log(b(obj));

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions