Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: support canonical module #4888

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ exports.type = function type(value) {
exports.stringify = function (value) {
var typeHint = canonicalType(value);

if (!~['object', 'array', 'function'].indexOf(typeHint)) {
if (!~['object', 'array', 'function', 'module'].indexOf(typeHint)) {
if (typeHint === 'buffer') {
var json = Buffer.prototype.toJSON.call(value);
// Based on the toJSON result
Expand Down Expand Up @@ -401,6 +401,12 @@ exports.canonicalize = function canonicalize(value, stack, typeHint) {
break;
}
/* falls through */
case 'module':
if (value[Symbol.toStringTag] === 'Module') {
canonicalizedObj = canonicalizedObj || {};
canonicalizedObj['[Symbol.toStringTag]'] = 'Module';
}
/* falls through */
case 'object':
canonicalizedObj = canonicalizedObj || {};
withStack(value, function () {
Expand Down
4 changes: 4 additions & 0 deletions test/unit/fixtures/module.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export default 123;

export const foo = 'abc';
export const bar = true;
18 changes: 18 additions & 0 deletions test/unit/utils.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
'use strict';

var utils = require('../../lib/utils');
const esmUtils = require('../../lib/nodejs/esm-utils');
const Path = require('node:path');
var sinon = require('sinon');

describe('lib/utils', function () {
Expand Down Expand Up @@ -288,6 +290,22 @@ describe('lib/utils', function () {
].join('\n');
expect(stringify(expected), 'to be', actual);
});

it('should represent modules', async function () {
const expected = await esmUtils.requireOrImport(
Path.join(__dirname, './fixtures/module.mjs')
);
const actual = [
'{',
' "[Symbol.toStringTag]": "Module"',
' "bar": true',
' "default": 123',
' "foo": "abc"',
'}'
].join('\n');

expect(stringify(expected), 'to be', actual);
});
});

it('should canonicalize the object', function () {
Expand Down