Repository: karen-irc/option-t
Pull request #1413 (2022-08-31 08:06:26)

Add the test to load commonjs files generated into cjs/


Patch:
diff --git a/.github/workflows/_ci.yaml b/.github/workflows/_ci.yaml
index e4b8b3ee..65e2430c 100644
--- a/.github/workflows/_ci.yaml
+++ b/.github/workflows/_ci.yaml
@@ -117,7 +117,7 @@ jobs:
               env:
                   CI: true
 
-    test_esmodule_path_rewrite:
+    test_module_path_rewrite:
         needs: [install_dependencies]
         runs-on: ubuntu-latest
         container: node:${{ matrix.node-version }}-bullseye
@@ -132,7 +132,7 @@ jobs:
             - uses: actions/checkout@v3
             - uses: ./.github/actions/prepare_ci
 
-            - run: make test_esmodule_path_rewrite -j
+            - run: make test_module_path_rewrite -j
               env:
                   CI: true
 
diff --git a/Makefile b/Makefile
index f60d5d5c..0e91de95 100644
--- a/Makefile
+++ b/Makefile
@@ -198,13 +198,13 @@ test_distribution_contain_all: build
 run_test_distribution_contain_all:
 	$(NODE_BIN) $(CURDIR)/tools/test_package_contains_expected_all.mjs --target $(DIST_DIR)
 
-.PHONY: test_esmodule_path_rewrite
-test_esmodule_path_rewrite: build
-	$(MAKE) run_test_esmodule_path_rewrite -C $(CURDIR)
+.PHONY: test_module_path_rewrite
+test_module_path_rewrite: build
+	$(MAKE) run_test_module_path_rewrite -C $(CURDIR)
 
-.PHONY: run_test_esmodule_path_rewrite
-run_test_esmodule_path_rewrite:
-	$(NODE_BIN) $(CURDIR)/tools/test_esmodule_path_rewrite.mjs --target $(DIST_DIR)
+.PHONY: run_test_module_path_rewrite
+run_test_module_path_rewrite:
+	$(NODE_BIN) $(CURDIR)/tools/test_path_rewrite.mjs --target $(DIST_DIR)
 
 .PHONY: test_package_install
 test_package_install: build __run_install_package
@@ -257,7 +257,7 @@ prepublish: ## Run some commands for 'npm run prepublish'
 	$(MAKE) clean -C $(CURDIR)
 	$(MAKE) build -C $(CURDIR)
 	$(MAKE) test_distribution_contain_all -C $(CURDIR)
-	$(MAKE) run_test_esmodule_path_rewrite -C $(CURDIR)
+	$(MAKE) run_test_module_path_rewrite -C $(CURDIR)
 
 .PHONY: publish
 publish: copy_npmrc_to_project_root ## Run some commands for 'npm publish'
diff --git a/tools/babel/babel-plugin-modify-ext.mjs b/tools/babel/babel-plugin-add-ext-suffix.mjs
similarity index 66%
rename from tools/babel/babel-plugin-modify-ext.mjs
rename to tools/babel/babel-plugin-add-ext-suffix.mjs
index a8da18a4..793c8feb 100644
--- a/tools/babel/babel-plugin-modify-ext.mjs
+++ b/tools/babel/babel-plugin-add-ext-suffix.mjs
@@ -1,19 +1,9 @@
 import * as assert from 'node:assert/strict';
-import * as nodePath from 'node:path';
 
 function withExtension(extension, name) {
     return `${name}${extension}`;
 }
 
-function replaceLastExtensionWith(oldExtension, newExtension, name) {
-    assert.ok(oldExtension.startsWith('.'));
-    assert.ok(newExtension.startsWith('.'));
-
-    const pattern = new RegExp(`${oldExtension}$`, 'u');
-    const replaced = name.replace(pattern, newExtension);
-    return replaced;
-}
-
 function rewriter(t, path, state, declarationFactory) {
     const option = state.opts;
     const extension = option.extension;
@@ -31,19 +21,10 @@ function rewriter(t, path, state, declarationFactory) {
     }
 
     const specifiers = node.specifiers;
-    const filepathValue = source.value;
-    const currentExt = nodePath.extname(filepathValue);
 
-    let newLiteral;
-    if (currentExt === '') {
-        // this file path value does not have any extension.
-        newLiteral = withExtension(extension, filepathValue);
-    } else {
-        newLiteral = replaceLastExtensionWith(currentExt, extension, filepathValue);
-    }
-
-    const newSource = t.stringLiteral(newLiteral);
+    const newSource = t.stringLiteral(withExtension(extension, source.value));
     const declaration = declarationFactory(specifiers, newSource);
+
     path.replaceWith(declaration);
 }
 
diff --git a/tools/babel/babelrc.cjs.mjs b/tools/babel/babelrc.cjs.mjs
index 7fc2ddf9..9d6e93a6 100644
--- a/tools/babel/babelrc.cjs.mjs
+++ b/tools/babel/babelrc.cjs.mjs
@@ -8,7 +8,7 @@ export default {
         }],
     ],
     'plugins': [
-        ['./babel-plugin-modify-ext.mjs', {
+        ['./babel-plugin-add-ext-suffix.mjs', {
             extension: '.cjs',
         }],
         ['@babel/plugin-transform-modules-commonjs', {
diff --git a/tools/babel/babelrc.mjs.pathrewiter.mjs b/tools/babel/babelrc.mjs.pathrewiter.mjs
index 38238347..f1486e4b 100644
--- a/tools/babel/babelrc.mjs.pathrewiter.mjs
+++ b/tools/babel/babelrc.mjs.pathrewiter.mjs
@@ -1,6 +1,6 @@
 export default {
     'plugins': [
-        ['./babel-plugin-modify-ext.mjs', {
+        ['./babel-plugin-add-ext-suffix.mjs', {
             extension: '.mjs',
         }],
     ],


Test patch:
diff --git a/tools/test_esmodule_path_rewrite.mjs b/tools/test_path_rewrite.mjs
similarity index 52%
rename from tools/test_esmodule_path_rewrite.mjs
rename to tools/test_path_rewrite.mjs
index b02bbe45..f9dccde2 100644
--- a/tools/test_esmodule_path_rewrite.mjs
+++ b/tools/test_path_rewrite.mjs
@@ -1,4 +1,5 @@
 import * as assert from 'node:assert/strict';
+import { createRequire } from 'node:module';
 import * as fs from 'node:fs/promises';
 import * as path from 'node:path';
 import { fileURLToPath } from 'node:url';
@@ -35,6 +36,26 @@ async function testAllowToLoadFileAsESM(expectedSet) {
     assert.deepStrictEqual([], hasError, 'Unexpected files which could not load as ES Module');
 }
 
+async function testAllowToLoadFileAsCommonJs(expectedSet) {
+    const require = createRequire(THIS_FILENAME);
+
+    const hasError = [];
+    const susccess = [];
+    for (const filename of expectedSet) {
+        try {
+            require(filename);
+            expectedSet.delete(filename);
+        }
+        catch (e) {
+            hasError.push(filename);
+            console.error(e);
+        }
+    }
+
+    assert.deepStrictEqual([], susccess, 'Should be success to load all CommonJS');
+    assert.deepStrictEqual([], hasError, 'Unexpected files which could not load as CommonJS');
+}
+
 function parseCliOptions() {
     const options = {
         target: {
@@ -67,17 +88,34 @@ function parseCliOptions() {
     const files = parseJSON(json);
     assert.notStrictEqual(files, null, 'Fail to parse the file list snapshot');
 
-    const mjsInEsmDir = Object.keys(files).filter((filename) => {
-        return filename.endsWith('.mjs') && (filename.startsWith('esm/') || filename.startsWith('lib/'));
-    });
+    {
+        const mjsInEsmDir = Object.keys(files).filter((filename) => {
+            return filename.endsWith('.mjs') && filename.startsWith('esm/');
+        });
+
+        const EXPECTED_FILE_SET = new Set(mjsInEsmDir.map((filename) => {
+            const fullpath = path.resolve(OUTDIR, filename);
+            return fullpath;
+        }));
+        assert.notStrictEqual(EXPECTED_FILE_SET.size, 0, 'The expected file list must not be empty');
 
-    const EXPECTED_FILE_SET = new Set(mjsInEsmDir.map((filename) => {
-        const fullpath = path.resolve(OUTDIR, filename);
-        return fullpath;
-    }));
-    assert.notStrictEqual(EXPECTED_FILE_SET.size, 0, 'The expected file list must not be empty');
+        await testAllowToLoadFileAsESM(EXPECTED_FILE_SET);
+    }
+
+    {
+        const cjsInCjsDir = Object.keys(files).filter((filename) => {
+            return filename.endsWith('.cjs') && filename.startsWith('cjs/');
+        });
+
+        const EXPECTED_FILE_SET = new Set(cjsInCjsDir.map((filename) => {
+            const fullpath = path.resolve(OUTDIR, filename);
+            return fullpath;
+        }));
+        assert.notStrictEqual(EXPECTED_FILE_SET.size, 0, 'The expected file list must not be empty');
+
+        await testAllowToLoadFileAsCommonJs(EXPECTED_FILE_SET);
+    }
 
-    await testAllowToLoadFileAsESM(EXPECTED_FILE_SET);
 })().catch((e) => {
     console.error(e);
     process.exit(1);