Skip to content
/ jewire Public

Access private functions, variables and classes from CommonJS modules . Enable named exports with relative paths identical to CommonJS require. Clone objects at runtime to remove false negatives in expect.toStrictEqual

License

Notifications You must be signed in to change notification settings

nktnet1/jewire

Repository files navigation

Jewire

pipeline   codecov   Maintainability   Snyk Security   GitHub top language

NPM Version   install size   Depfu Dependencies   FOSSA Status   NPM License   GitHub issues

Quality Gate Status   Codacy Badge   DeepSource   codebeat badge   GitHub stars

Downloads Total   Downloads Yearly   Downloads Monthly   Downloads Weekly   Downloads Daily


Access private functions, variables and classes from CommonJS modules

Enable named exports with relative paths identical to CommonJS require

Clone objects at runtime to remove false negatives in expect.toStrictEqual

Try with Replit


1. Installation

npm install jewire

2. Usage

Try with Replit.

jewire(relativePath, options);
Examples (click to view)

Importing from the same directory

const { privateVariable, privateFunction } = jewire('private-module');

Importing .cjs file from a different directory

const { privateFunction  } = jewire('../src/private-module.cjs');

Using a different basePath

const { privateFunction } = jewire(
  'private-module',
  { basePath: process.cwd() }
);

Using a different clone function from the default clone.objectClone:

const { privateFunction } = jewire(
  'private-module',
  { objectClone: (obj) => JSON.parse(JSON.stringify(obj)) }
);

2.1. Parameter: relativePath

Path to the module relative to the current file, similar to CommonJS require. For example,

  • '../animals/cats.js'
  • './common.cjs'
  • 'minimal'
    • jewire will look for './minimal.js' before './minimal.cjs'

Note that option.basePath can be provided to alter this behaviour.

2.2. Parameter: options

Option Description Example Default
basePath Absolute path to the module's directory
process.cwd()
__dirname
objectClone Cloning function to apply to any objects or arrays that are global symbols, function return values or class method return values.
o => JSON.parse(
  JSON.stringify(
    o
  )
)
objectClone
(see clone.ts)

2.3. Return Object

All named exports, including globally defined variables, functions and classes are returned as keys within an object.

Additionally, the returned object contains the key __jewireContext__ with the values being another object with the following properties:

  1. rewire: the return value of rewire(modulePath). Please refer to the documentation for rewire for further details.

  2. hiddenExportInfo: An object containing information about all hidden exports, of the form:

    {
      symbols: {
        variables: string[],
        functions: string[],
        classes: string[],
      }
      ast: ASTProgram, // Abstract Syntax Tree from Meriyah parser
      code: string, // return value of fs.readFileSync(filePath)
    }
  3. jewireGetter: the internal function used by jewire to retrieve objects. It has the same prototype as rewireModule.__get__, although objects are deep cloned using either jewire's default clone function or, if provided, options.objectClone.

2.4. Errors

If an unknown file path is provided, the given file is empty or the module contains invalid code such as syntax errors, a default Error object is thrown.

3. License

Massachusetts Institute of Technology (MIT)
Copyright (c) 2023 Khiet Tam Nguyen

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the “Software”),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

FOSSA Status

4. Limitations

As this library uses rewire under the hood, it has the same limitations in that it can only import CommonJS modules. Please see the limitations as described in the rewire module.

5. Caveats

5.1. Purpose

jewire is a niche library designed to automark private functions in the submitted code of students using the Jest testing framework during the first 2 weeks of their studies in COMP1531 Software Engineering Fundamentals.

This is because npm and module imports/exports are not introduced until week 3, when students are considered to be more familiar with JavaScript as a programming language.

5.2. Rationale

jewire aims to simplify the process of using rewire by removing the need to provide a file extension and absolute path, abstracting getter and setter methods and enabling relative module imports similar to CommonJS require.

This process requires reading the module twice - once to parse into an Abstract Syntax Tree using the Meriyah parser, and another from rewire as rewire's interface does not enable reusing the file content.

5.3. Rewire and Jest

Jewire reclones objects at runtime to allow the return values of rewired functions and class methods to be compared using Jest's expect.toStrictEqual matcher, which in the rewire module would yield "Received: serializes to the same string".

The cause is Jest's utilisation of node:vm under the hood, which creates its own temporary context that overrides global classes such as Array, Error and Date to extend functionalities. These global classes differ from those that are returned from rewire's private functions, as depicted in the following GitHub issues made by @geogezlei:

For further details and explanation about this problem, please visit Manuel Spigolon's article about the use of the instanceof operator in Jest.

About

Access private functions, variables and classes from CommonJS modules . Enable named exports with relative paths identical to CommonJS require. Clone objects at runtime to remove false negatives in expect.toStrictEqual

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published