@intentius/chant 0.124.16 → 0.124.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/dist/cli/commands/check-lexicon-plugin.d.ts.map +1 -1
  2. package/dist/cli/commands/check-lexicon-plugin.js +2 -1
  3. package/dist/cli/commands/lint.d.ts.map +1 -1
  4. package/dist/cli/commands/lint.js +3 -2
  5. package/dist/components/discover.d.ts.map +1 -1
  6. package/dist/components/discover.js +2 -1
  7. package/dist/config-sandbox.d.ts.map +1 -1
  8. package/dist/config-sandbox.js +5 -1
  9. package/dist/discovery/import.d.ts.map +1 -1
  10. package/dist/discovery/import.js +2 -1
  11. package/dist/discovery/sandbox/driver.d.ts.map +1 -1
  12. package/dist/discovery/sandbox/driver.js +8 -3
  13. package/dist/lexicon-module.d.ts.map +1 -1
  14. package/dist/lexicon-module.js +4 -3
  15. package/dist/lint/policy-import.d.ts.map +1 -1
  16. package/dist/lint/policy-import.js +2 -1
  17. package/dist/lint/rule-loader.d.ts.map +1 -1
  18. package/dist/lint/rule-loader.js +2 -1
  19. package/dist/module-interop.d.ts +20 -0
  20. package/dist/module-interop.d.ts.map +1 -0
  21. package/dist/module-interop.js +39 -0
  22. package/dist/op/discover.d.ts.map +1 -1
  23. package/dist/op/discover.js +3 -2
  24. package/dist/wave-runtime.mjs +174 -174
  25. package/dist/workspace/lineage-migrations.d.ts.map +1 -1
  26. package/dist/workspace/lineage-migrations.js +2 -1
  27. package/package.json +1 -1
  28. package/src/cli/commands/check-lexicon-plugin.ts +2 -1
  29. package/src/cli/commands/lint.ts +3 -2
  30. package/src/cli/compiled-cli.e2e.test.ts +42 -1
  31. package/src/components/discover.ts +2 -1
  32. package/src/config-sandbox.ts +5 -1
  33. package/src/discovery/import.ts +2 -1
  34. package/src/discovery/sandbox/driver.ts +8 -3
  35. package/src/lexicon-module.ts +4 -3
  36. package/src/lint/policy-import.ts +2 -1
  37. package/src/lint/rule-loader.ts +2 -1
  38. package/src/module-interop.test.ts +65 -0
  39. package/src/module-interop.ts +39 -0
  40. package/src/op/discover.ts +3 -2
  41. package/src/workspace/lineage-migrations.ts +2 -1
@@ -1 +1 @@
1
- {"version":3,"file":"lineage-migrations.d.ts","sourceRoot":"","sources":["../../src/workspace/lineage-migrations.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAKH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,KAAK,OAAO,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,EAA6F,KAAK,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAG5I,mFAAmF;AACnF,eAAO,MAAM,cAAc,sBAAsB,CAAC;AAUlD,4EAA4E;AAC5E,QAAA,MAAM,UAAU;;;;;;;;;;;;;;;;;;;;;0BAWd,CAAC;AACH,MAAM,MAAM,aAAa,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,UAAU,CAAC,CAAC;AAEvD,mEAAmE;AACnE,QAAA,MAAM,UAAU;;;;;;;;;;;;;;6BAKd,CAAC;AACH,MAAM,MAAM,cAAc,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,UAAU,CAAC,CAAC;AAUxD,QAAA,MAAM,eAAe;;IAEnB,qEAAqE;;;;QAInE,iGAAiG;;QAEjG,yCAAyC;;;IAG3C,0DAA0D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;kBAW1D,CAAC;AACH,MAAM,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,CAAC;AAExD,qBAAa,cAAe,SAAQ,SAAS;IAClC,IAAI,SAAoB;CAClC;AAED,MAAM,WAAW,eAAe;IAC9B,SAAS,EAAE,SAAS,CAAC;IACrB,qEAAqE;IACrE,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE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MAAM,EAAE,MAAM,CAAC,CAAA;CAAE,CAsCvJ;AAID,MAAM,WAAW,aAAa;IAC5B,6BAA6B;IAC7B,KAAK,EAAE,eAAe,EAAE,CAAC;IACzB,IAAI,EAAE,OAAO,GAAG,IAAI,CAAC;IACrB,EAAE,EAAE,OAAO,GAAG,IAAI,CAAC;CACpB;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,GAAG,SAAS,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,aAAa,CA4D9I;AAID,MAAM,WAAW,mBAAmB;IAClC,mDAAmD;IACnD,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,OAAO,CAAC;IACjB,4EAA4E;IAC5E,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC7B,+EAA+E;IAC/E,SAAS,EAAE,OAAO,CAAC;IACnB,4DAA4D;IAC5D,OAAO,EAAE,MAAM,CAAC;IAChB,yGAAyG;IACzG,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;CAC7C;AAED,kFAAkF;AAClF,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,eAAe,EAAE,EAAE,SAAS,EAAE,OAAO,GAAG,IAAI,CAOpF;AAED,qFAAqF;AACrF,wBAAsB,YAAY,CAAC,CAAC,EAAE,eAAe,EAAE,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CA6B/F"}
@@ -25,6 +25,7 @@ import { z } from "zod";
25
25
  import { LockError } from "./lineage-lock.js";
26
26
  import { compareVersions, formatVersion, parseVersion, satisfies, validateRange, VersionRangeError } from "./lineage-version.js";
27
27
  import { ensureTypeScriptLoader } from "../ts-loader.js";
28
+ import { esModuleNamespace } from "../module-interop.js";
28
29
  /** Where a template keeps its migrations, relative to the template's directory. */
29
30
  export const MIGRATIONS_DIR = ".chant/migrations";
30
31
  const RelPath = z
@@ -232,7 +233,7 @@ export async function runMigration(m, opts) {
232
233
  writeFileSync(abs, data);
233
234
  }
234
235
  ensureTypeScriptLoader();
235
- const mod = (await import(pathToFileURL(file).href));
236
+ const mod = esModuleNamespace((await import(pathToFileURL(file).href)));
236
237
  if (typeof mod.default !== "function")
237
238
  throw new MigrationError(`${migration.id}: ${body.module} has no default export function`);
238
239
  await mod.default({ dir: opts.dir });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@intentius/chant",
3
- "version": "0.124.16",
3
+ "version": "0.124.17",
4
4
  "description": "Declarative infrastructure-as-code toolkit — TypeScript on Node.js",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://intentius.io/chant",
@@ -24,6 +24,7 @@ import { isAbsolute, join, resolve } from "path";
24
24
  import { pathToFileURL } from "url";
25
25
  import { isLexiconPlugin, type LexiconPlugin } from "../../lexicon";
26
26
  import { ensureTypeScriptLoader } from "../../ts-loader";
27
+ import { esModuleNamespace } from "../../module-interop";
27
28
 
28
29
  export interface LoadedLexicon {
29
30
  /** The plugin, when the package exported one. */
@@ -78,7 +79,7 @@ export async function loadLexiconFromDir(dir: string): Promise<LoadedLexicon> {
78
79
  let mod: Record<string, unknown>;
79
80
  try {
80
81
  ensureTypeScriptLoader();
81
- mod = (await import(pathToFileURL(entry).href)) as Record<string, unknown>;
82
+ mod = esModuleNamespace((await import(pathToFileURL(entry).href)) as Record<string, unknown>);
82
83
  } catch (error) {
83
84
  return { entry, error: `import failed: ${error instanceof Error ? error.message : String(error)}` };
84
85
  }
@@ -34,6 +34,7 @@ import { getProvenance } from "../../provenance";
34
34
  import { runLexiconPostSynthChecks } from "./build";
35
35
  import { armSandboxPolicyExecution, runProjectPolicies } from "../../lint/policy-sandbox";
36
36
  import { ensureTypeScriptLoader } from "../../ts-loader";
37
+ import { esModuleNamespace } from "../../module-interop";
37
38
 
38
39
  // Import config loader
39
40
  import { loadConfig, resolveRulesForFile, resolveConfiguredSeverity, findProjectRoot } from "../../lint/config";
@@ -92,7 +93,7 @@ export async function loadPluginRules(
92
93
  let mod: Record<string, unknown>;
93
94
  try {
94
95
  ensureTypeScriptLoader();
95
- mod = await import(resolved);
96
+ mod = esModuleNamespace(await import(resolved));
96
97
  } catch (err) {
97
98
  throw new Error(
98
99
  `Failed to load plugin "${pluginPath}": ${err instanceof Error ? err.message : String(err)}`,
@@ -595,7 +596,7 @@ async function runOpCheckDiagnostics(
595
596
  for (const filePath of opFiles) {
596
597
  try {
597
598
  ensureTypeScriptLoader();
598
- const mod: unknown = await import(filePath);
599
+ const mod: unknown = esModuleNamespace(await import(filePath));
599
600
  const entity = (mod as { default?: unknown }).default;
600
601
  if (!entity || typeof entity !== "object") continue;
601
602
  const opConfig = (entity as { props?: unknown }).props as { name?: unknown; phases?: unknown } | undefined;
@@ -13,7 +13,7 @@
13
13
  */
14
14
 
15
15
  import { execFileSync, spawnSync } from "node:child_process";
16
- import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
16
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
17
17
  import { tmpdir } from "node:os";
18
18
  import { join, resolve } from "node:path";
19
19
  import { afterAll, beforeAll, describe, expect, test } from "vitest";
@@ -24,6 +24,7 @@ const version = (JSON.parse(readFileSync(join(coreRoot, "package.json"), "utf-8"
24
24
 
25
25
  let scratch: string;
26
26
  let project: string;
27
+ let cjsProject: string;
27
28
  let waves: string;
28
29
  let chant: string;
29
30
  let tracer: string;
@@ -87,6 +88,22 @@ beforeAll(() => {
87
88
  );
88
89
  chant = join(project, "node_modules", ".bin", "chant");
89
90
 
91
+ // The same project with no package.json at all, so nothing above the config
92
+ // says "type": "module" and tsx compiles chant.config.ts as CommonJS (#3897).
93
+ cjsProject = join(scratch, "cjs-project");
94
+ mkdirSync(join(cjsProject, "src"), { recursive: true });
95
+ symlinkSync(join(project, "node_modules"), join(cjsProject, "node_modules"), "dir");
96
+ writeFileSync(join(cjsProject, "chant.config.ts"), readFileSync(join(project, "chant.config.ts"), "utf-8"));
97
+ // The source reaches the lexicon through a module outside src/, so the
98
+ // fallback scan of src/ imports finds no lexicon: only the config names it.
99
+ mkdirSync(join(cjsProject, "lib"));
100
+ writeFileSync(join(cjsProject, "lib", "render.ts"), `export * from "@intentius/chant-lexicon-render";\n`);
101
+ writeFileSync(
102
+ join(cjsProject, "src", "infra.ts"),
103
+ `import { Postgres, Render } from "../lib/render";\n` +
104
+ `export const db = new Postgres({ name: "e2e-db", plan: "free", version: "16", region: Render.Region });\n`,
105
+ );
106
+
90
107
  // A waves spec whose plan writes a fixed digest and whose apply does nothing,
91
108
  // in a repository with the history `run wave` reads its gate policy from.
92
109
  waves = join(scratch, "waves");
@@ -162,4 +179,28 @@ describe("the installed chant CLI (#3878)", () => {
162
179
  rmSync(join(project, "src", "made.ts"));
163
180
  }
164
181
  });
182
+
183
+ describe("a chant.config.ts tsx compiles as CommonJS (#3897)", () => {
184
+ test("build reads the config's lexicons", () => {
185
+ const r = run(cjsProject, ["build", "src", "-o", "out/render.json"]);
186
+ expect(r.status, r.stderr).toBe(0);
187
+ const built = JSON.parse(readFileSync(join(cjsProject, "out", "render.json"), "utf-8")) as Record<string, { body?: { name?: string } }>;
188
+ expect(built.db?.body?.name).toBe("e2e-db");
189
+ });
190
+
191
+ test("build --sandbox reads the config's lexicons in the child", () => {
192
+ const r = run(cjsProject, ["build", "src", "--sandbox", "-o", "out/sandbox.json"]);
193
+ expect(r.status, r.stderr).toBe(0);
194
+ const built = JSON.parse(readFileSync(join(cjsProject, "out", "sandbox.json"), "utf-8")) as Record<string, { body?: { name?: string } }>;
195
+ expect(built.db?.body?.name).toBe("e2e-db");
196
+ });
197
+
198
+ test("graph --format ir finds the lexicon's entities", () => {
199
+ const r = run(cjsProject, ["graph", "src", "--format", "ir"]);
200
+ expect(r.status, r.stderr).toBe(0);
201
+ expect(r.stderr).not.toMatch(/could not load the project's lexicons/);
202
+ const ir = JSON.parse(r.stdout) as { nodes: Array<Record<string, unknown>> };
203
+ expect(ir.nodes.length).toBeGreaterThan(0);
204
+ });
205
+ });
165
206
  });
@@ -51,6 +51,7 @@ import { hasDiscoveryMarkerSync } from "../discovery/files";
51
51
  import { resolveDiscoveryGlobs } from "../config";
52
52
  import { walkDiscovery, workspaceMemberDirs } from "../discovery/walk";
53
53
  import { ensureTypeScriptLoader } from "../ts-loader";
54
+ import { esModuleNamespace } from "../module-interop";
54
55
 
55
56
  /** One discovered component, paired with the file it was exported from. */
56
57
  export interface DiscoveredComponent {
@@ -214,7 +215,7 @@ async function importAndCollectComponents(
214
215
  // a bare "." path) would otherwise be treated by `import()` as a bare
215
216
  // package specifier and fail with "Cannot find package 'x.component.ts'".
216
217
  ensureTypeScriptLoader();
217
- const exports = await import(pathToFileURL(resolve(filePath)).href);
218
+ const exports = esModuleNamespace(await import(pathToFileURL(resolve(filePath)).href));
218
219
  modules.push({ file: filePath, exports });
219
220
  } catch (err) {
220
221
  importErrors.push(new DiscoveryError(filePath, err instanceof Error ? err.message : String(err), "import"));
@@ -1,5 +1,6 @@
1
1
  import { dirname } from "node:path";
2
2
  import { importConfigModule, requireConfigModule, type ConfigModuleNamespace } from "./config-import";
3
+ import { esModuleNamespace } from "./module-interop";
3
4
 
4
5
  /**
5
6
  * chant #1113 — decides WHERE a project's `chant.config.ts` is evaluated.
@@ -84,7 +85,10 @@ export function resetSandboxConfigEvaluationForTests(): void {
84
85
  * evaluated, never how its result is read.
85
86
  */
86
87
  export function selectConfigExport(namespace: ConfigModuleNamespace): unknown {
87
- return namespace.default ?? namespace.config ?? namespace;
88
+ // A config tsx compiled as CommonJS arrives as `{ default: module.exports }`
89
+ // under a native import (#3897); read the module's own namespace instead.
90
+ const ns = esModuleNamespace(namespace);
91
+ return ns.default ?? ns.config ?? ns;
88
92
  }
89
93
 
90
94
  /**
@@ -1,5 +1,6 @@
1
1
  import { DiscoveryError } from "../errors";
2
2
  import { ensureTypeScriptLoader } from "../ts-loader";
3
+ import { esModuleNamespace } from "../module-interop";
3
4
 
4
5
  /**
5
6
  * Modules whose evaluation threw, and the error each threw with (#2368).
@@ -59,7 +60,7 @@ export async function importModule(
59
60
 
60
61
  try {
61
62
  ensureTypeScriptLoader();
62
- return await import(path);
63
+ return esModuleNamespace(await import(path));
63
64
  } catch (error) {
64
65
  const message =
65
66
  error instanceof Error ? error.message : "Unknown import error";
@@ -59,6 +59,8 @@ const POST_SYNTH_MODULE = join(dirname(DISCOVERY_DIR), "lint", "post-synth.ts");
59
59
  // file, so the driver's `setBuildParams` call below mutates the one object
60
60
  // every bundled import observes.
61
61
  const PARAMS_MODULE = join(dirname(DISCOVERY_DIR), "params.ts");
62
+ // #3897: a project file tsx compiled as CommonJS reads as its own namespace.
63
+ const INTEROP_MODULE = join(dirname(DISCOVERY_DIR), "module-interop.ts");
62
64
 
63
65
  export interface GenerateDriverOptions {
64
66
  /** Absolute paths to the run-fallback files this build decided NOT to fold — see `discover()`'s fold/taint loop in `../index.ts`. */
@@ -130,6 +132,7 @@ export function generateDriverSource(options: GenerateDriverOptions): string {
130
132
  `import { classifyChildError } from ${lit(CHILD_ERRORS_MODULE)};`,
131
133
  `import { getProvenance } from ${lit(PROVENANCE_MODULE)};`,
132
134
  `import { setBuildParams } from ${lit(PARAMS_MODULE)};`,
135
+ `import { esModuleNamespace } from ${lit(INTEROP_MODULE)};`,
133
136
  `import { writeSync } from "node:fs";`,
134
137
  ``,
135
138
  `const BUILD_ROOT = ${lit(buildRoot)};`,
@@ -181,7 +184,7 @@ export function generateDriverSource(options: GenerateDriverOptions): string {
181
184
  lines.push(
182
185
  ` importing = ${lit(file)};`,
183
186
  ` try {`,
184
- ` const mod = await import(${lit(file)});`,
187
+ ` const mod = esModuleNamespace(await import(${lit(file)}));`,
185
188
  ` modules.push({ file: ${lit(file)}, exports: mod });`,
186
189
  ` } catch (err) {`,
187
190
  ` errors.push(classifyChildError(${lit(file)}, err).toJSON());`,
@@ -261,6 +264,7 @@ export function generateConfigDriverSource(configPath: string): string {
261
264
  return [
262
265
  `import { classifyChildError } from ${lit(CHILD_ERRORS_MODULE)};`,
263
266
  `import { scanConfigWireSafety } from ${lit(CONFIG_WIRE_MODULE)};`,
267
+ `import { esModuleNamespace } from ${lit(INTEROP_MODULE)};`,
264
268
  `import { writeSync } from "node:fs";`,
265
269
  ``,
266
270
  ...sendFunctionSource(),
@@ -268,7 +272,7 @@ export function generateConfigDriverSource(configPath: string): string {
268
272
  `async function main() {`,
269
273
  ` let namespace;`,
270
274
  ` try {`,
271
- ` namespace = await import(${lit(configPath)});`,
275
+ ` namespace = esModuleNamespace(await import(${lit(configPath)}));`,
272
276
  ` } catch (err) {`,
273
277
  ` await send({ kind: "chant-config", ok: false, error: classifyChildError(${lit(configPath)}, err).toJSON() });`,
274
278
  ` return;`,
@@ -337,6 +341,7 @@ export function generatePolicyDriverSource(policyPaths: readonly string[]): stri
337
341
  `import { classifyChildError } from ${lit(CHILD_ERRORS_MODULE)};`,
338
342
  `import { decodePolicyBuildResult, scanPolicyDiagnostics, PolicyWireError } from ${lit(POLICY_WIRE_MODULE)};`,
339
343
  `import { runPostSynthChecks, isPostSynthCheck } from ${lit(POST_SYNTH_MODULE)};`,
344
+ `import { esModuleNamespace } from ${lit(INTEROP_MODULE)};`,
340
345
  `import { writeSync } from "node:fs";`,
341
346
  ``,
342
347
  ...sendFunctionSource(),
@@ -382,7 +387,7 @@ export function generatePolicyDriverSource(policyPaths: readonly string[]): stri
382
387
  for (const policyPath of policyPaths) {
383
388
  lines.push(
384
389
  ` try {`,
385
- ` const mod = await import(${lit(policyPath)});`,
390
+ ` const mod = esModuleNamespace(await import(${lit(policyPath)}));`,
386
391
  ` for (const value of Object.values(mod)) {`,
387
392
  ` if (isPostSynthCheck(value)) checks.push(guard(value, ${lit(policyPath)}));`,
388
393
  ` }`,
@@ -28,6 +28,7 @@ import { createRequire } from "node:module";
28
28
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
29
29
  import { pathToFileURL } from "node:url";
30
30
  import { ensureTypeScriptLoader } from "./ts-loader";
31
+ import { esModuleNamespace } from "./module-interop";
31
32
 
32
33
  /**
33
34
  * One `lexicons` entry: a package-backed name, or a name plus the module that
@@ -181,7 +182,7 @@ export async function importLexiconModule(name: string): Promise<Record<string,
181
182
  if (path === undefined) return undefined;
182
183
  try {
183
184
  ensureTypeScriptLoader();
184
- return (await import(path)) as Record<string, unknown>;
185
+ return esModuleNamespace((await import(path)) as Record<string, unknown>);
185
186
  } catch (err) {
186
187
  throw new Error(
187
188
  `lexicon "${name}" is declared with module ${path}, which could not be loaded: ` +
@@ -262,12 +263,12 @@ export function resolveFromProject(spec: string, fromDir: string = process.cwd()
262
263
  export async function importLexiconPackage(spec: string, fromDir: string = process.cwd()): Promise<Record<string, unknown>> {
263
264
  try {
264
265
  ensureTypeScriptLoader();
265
- return (await import(spec)) as Record<string, unknown>;
266
+ return esModuleNamespace((await import(spec)) as Record<string, unknown>);
266
267
  } catch (err) {
267
268
  const pkg = packageNameOf(spec);
268
269
  if (pkg === undefined || !isPackageNotFound(err, pkg)) throw err;
269
270
  const resolved = resolveFromProject(spec, fromDir);
270
271
  if (resolved === undefined) throw err;
271
- return (await import(pathToFileURL(resolved).href)) as Record<string, unknown>;
272
+ return esModuleNamespace((await import(pathToFileURL(resolved).href)) as Record<string, unknown>);
272
273
  }
273
274
  }
@@ -24,6 +24,7 @@
24
24
  */
25
25
 
26
26
  import { ensureTypeScriptLoader } from "../ts-loader";
27
+ import { esModuleNamespace } from "../module-interop";
27
28
 
28
29
  /** Whether this process must run project policy modules inside the sandbox boundary instead of here. */
29
30
  let armed = false;
@@ -69,5 +70,5 @@ export async function importPolicyModule(policyPath: string): Promise<PolicyModu
69
70
  );
70
71
  }
71
72
  ensureTypeScriptLoader();
72
- return (await import(policyPath)) as PolicyModuleNamespace;
73
+ return esModuleNamespace((await import(policyPath)) as PolicyModuleNamespace);
73
74
  }
@@ -2,6 +2,7 @@ import { readdirSync, existsSync } from "fs";
2
2
  import { dirname, join, resolve } from "path";
3
3
  import type { LintRule } from "./rule";
4
4
  import { ensureTypeScriptLoader } from "../ts-loader";
5
+ import { esModuleNamespace } from "../module-interop";
5
6
 
6
7
  /**
7
8
  * Type guard to check if a value conforms to the LintRule interface.
@@ -84,7 +85,7 @@ export async function loadLocalRules(projectDir: string): Promise<LintRule[]> {
84
85
  let mod: Record<string, unknown>;
85
86
  try {
86
87
  ensureTypeScriptLoader();
87
- mod = await import(filePath);
88
+ mod = esModuleNamespace(await import(filePath));
88
89
  } catch (err) {
89
90
  throw new Error(
90
91
  `Failed to load rule file "${file}": ${err instanceof Error ? err.message : String(err)}`,
@@ -0,0 +1,65 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import { selectConfigExport } from "./config-sandbox";
3
+ import { esModuleNamespace } from "./module-interop";
4
+
5
+ /** What node's native import() hands back for a CommonJS module tsx compiled from `export default`. */
6
+ function commonJsNamespace(exports: Record<string, unknown>): Record<string, unknown> {
7
+ const moduleExports: Record<string, unknown> = { ...exports };
8
+ Object.defineProperty(moduleExports, "__esModule", { value: true });
9
+ return { ...exports, default: moduleExports };
10
+ }
11
+
12
+ describe("esModuleNamespace (#3897)", () => {
13
+ test("a CommonJS __esModule namespace reads as the module's own exports", () => {
14
+ const config = { lexicons: ["terraform"] };
15
+ const helper = () => 1;
16
+ const ns = esModuleNamespace(commonJsNamespace({ default: config, helper }));
17
+ expect(ns.default).toBe(config);
18
+ expect(ns.helper).toBe(helper);
19
+ expect(Object.keys(ns)).not.toContain("__esModule");
20
+ });
21
+
22
+ test("a CommonJS module with no default export has none after unwrapping", () => {
23
+ const ns = esModuleNamespace(commonJsNamespace({ config: { lexicons: ["aws"] } }));
24
+ expect(ns.default).toBeUndefined();
25
+ expect(ns.config).toEqual({ lexicons: ["aws"] });
26
+ });
27
+
28
+ test("an enumerable __esModule marker is left out too", () => {
29
+ const ns = esModuleNamespace({ default: { __esModule: true, default: 1 } });
30
+ expect(ns).toEqual({ default: 1 });
31
+ });
32
+
33
+ test("an ES module whose default export has a default key is unchanged", () => {
34
+ const namespace = { default: { default: { lexicons: ["aws"] } } };
35
+ expect(esModuleNamespace(namespace)).toBe(namespace);
36
+ });
37
+
38
+ test("a default without the marker set to true is unchanged", () => {
39
+ const namespace = { default: { __esModule: "yes", default: 1 } };
40
+ expect(esModuleNamespace(namespace)).toBe(namespace);
41
+ const primitive = { default: 3 };
42
+ expect(esModuleNamespace(primitive)).toBe(primitive);
43
+ const empty = {};
44
+ expect(esModuleNamespace(empty)).toBe(empty);
45
+ });
46
+ });
47
+
48
+ describe("selectConfigExport (#3897)", () => {
49
+ test("a config tsx compiled as CommonJS selects the config object, not {default: config}", () => {
50
+ const config = { lexicons: ["terraform"], terraform: { roots: { estate: { dir: "estate" } } } };
51
+ expect(selectConfigExport(commonJsNamespace({ default: config }))).toBe(config);
52
+ });
53
+
54
+ test("an ES module config that legitimately has a default key keeps it", () => {
55
+ const config = { default: { lexicons: ["aws"] }, lexicons: ["aws"] };
56
+ expect(selectConfigExport({ default: config })).toBe(config);
57
+ });
58
+
59
+ test("a require()d CommonJS config still selects its default", () => {
60
+ const config = { lexicons: ["aws"] };
61
+ const moduleExports: Record<string, unknown> = { default: config };
62
+ Object.defineProperty(moduleExports, "__esModule", { value: true });
63
+ expect(selectConfigExport(moduleExports)).toBe(config);
64
+ });
65
+ });
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The namespace a project module was authored with, whichever module format
3
+ * tsx compiled it to (#3897).
4
+ *
5
+ * A `.ts` file with no `"type": "module"` `package.json` above it is compiled
6
+ * by tsx as CommonJS: `exports.default = ...` plus a non-enumerable
7
+ * `__esModule: true` marker. The compiled CLI loads project files with a
8
+ * native `import()`, and Node hands a CommonJS module back as a namespace
9
+ * whose `default` is the whole `module.exports`. So `export default x` arrives
10
+ * as `namespace.default.default`. Under the source CLI tsx's ESM loader sits
11
+ * in front of the `import()` and does this interop itself, which is why the
12
+ * nesting only showed up once the CLI ran compiled (#3879).
13
+ *
14
+ * When `namespace.default` carries the `__esModule` marker, the module's real
15
+ * namespace is that exports object: this returns a copy of it with the marker
16
+ * left out. Anything else, including an ES module whose default export is an
17
+ * object that happens to have a `default` key, is returned unchanged.
18
+ */
19
+ export function esModuleNamespace<T extends Record<string, unknown>>(namespace: T): T {
20
+ // `in` before the read: a vitest factory mock throws on reading an export
21
+ // it does not define, and most modules have no `default` at all.
22
+ if (namespace === null || typeof namespace !== "object" || !("default" in namespace)) return namespace;
23
+ const exported = namespace.default;
24
+ if (!isCommonJsEsModule(exported)) return namespace;
25
+ const unwrapped: Record<string, unknown> = {};
26
+ for (const key of Object.keys(exported)) {
27
+ if (key !== "__esModule") unwrapped[key] = exported[key];
28
+ }
29
+ return unwrapped as T;
30
+ }
31
+
32
+ /** A CommonJS `module.exports` that a compiler marked as an ES module. */
33
+ function isCommonJsEsModule(value: unknown): value is Record<string, unknown> {
34
+ return (
35
+ value !== null &&
36
+ (typeof value === "object" || typeof value === "function") &&
37
+ (value as { __esModule?: unknown }).__esModule === true
38
+ );
39
+ }
@@ -7,6 +7,7 @@ import { hasDiscoveryMarkerSync } from "../discovery/files";
7
7
  import { resolveDiscoveryGlobs } from "../config";
8
8
  import { isStewardDeclaration, type StewardDeclaration } from "./steward";
9
9
  import { ensureTypeScriptLoader } from "../ts-loader";
10
+ import { esModuleNamespace } from "../module-interop";
10
11
 
11
12
  export interface DiscoveredOp {
12
13
  config: OpConfig;
@@ -152,7 +153,7 @@ export async function discoverOps(opts?: { cwd?: string }): Promise<OpDiscoveryR
152
153
  for (const filePath of files) {
153
154
  try {
154
155
  ensureTypeScriptLoader();
155
- const mod = (await import(filePath)) as Record<string, unknown>;
156
+ const mod = esModuleNamespace((await import(filePath)) as Record<string, unknown>);
156
157
  const exported = opsExportedBy(mod);
157
158
 
158
159
  // A file may hold a steward and no Op (#2731): the steward sits beside
@@ -223,7 +224,7 @@ export async function discoverStewards(opts?: { cwd?: string }): Promise<Steward
223
224
  let mod: Record<string, unknown>;
224
225
  try {
225
226
  ensureTypeScriptLoader();
226
- mod = (await import(filePath)) as Record<string, unknown>;
227
+ mod = esModuleNamespace((await import(filePath)) as Record<string, unknown>);
227
228
  } catch (err) {
228
229
  errors.push(`${filePath}: ${err instanceof Error ? err.message : String(err)}`);
229
230
  continue;
@@ -26,6 +26,7 @@ import { z } from "zod";
26
26
  import { LockError, type Lineage } from "./lineage-lock";
27
27
  import { compareVersions, formatVersion, parseVersion, satisfies, validateRange, VersionRangeError, type Version } from "./lineage-version";
28
28
  import { ensureTypeScriptLoader } from "../ts-loader";
29
+ import { esModuleNamespace } from "../module-interop";
29
30
 
30
31
  /** Where a template keeps its migrations, relative to the template's directory. */
31
32
  export const MIGRATIONS_DIR = ".chant/migrations";
@@ -283,7 +284,7 @@ export async function runMigration(m: LoadedMigration, opts: RunMigrationOptions
283
284
  writeFileSync(abs, data);
284
285
  }
285
286
  ensureTypeScriptLoader();
286
- const mod = (await import(pathToFileURL(file).href)) as { default?: unknown };
287
+ const mod = esModuleNamespace((await import(pathToFileURL(file).href)) as { default?: unknown });
287
288
  if (typeof mod.default !== "function") throw new MigrationError(`${migration.id}: ${body.module} has no default export function`);
288
289
  await (mod.default as (ctx: { dir: string }) => unknown)({ dir: opts.dir });
289
290
  } else {