@nhtio/vite-plugins 1.20251213.0 → 1.20261021.0

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.
package/README.md CHANGED
@@ -3,3 +3,46 @@
3
3
  Preconfigured Commonly Used Vite Plugins
4
4
 
5
5
  For more information, see the [official documentation](https://vite-plugins.nht.io)
6
+
7
+ ## Package-private declaration imports (`dtsComplex`)
8
+
9
+ `dtsComplex` defaults to `internalImports: 'relative'`, preserving its existing
10
+ extensionless relative declaration output. For ESM packages consumed with
11
+ NodeNext, Node16 or bundler resolution, opt in to package-private imports:
12
+
13
+ ```typescript
14
+ import { dtsComplex } from "@nhtio/vite-plugins/dts_complex";
15
+
16
+ dtsComplex({
17
+ internalImports: "subpath",
18
+ subpathPrefix: "#types", // default; must start with #, not end with / or contain *
19
+ });
20
+ ```
21
+
22
+ Internal declaration references (including aliases, directory indexes, ambient
23
+ files and bundled dependencies) then use paths such as `#types/private/mixin` or
24
+ `#types/utils/index`, without extensions. External and published package-name
25
+ self-references remain unchanged. The build fails if any relative import/export
26
+ or import-type specifier remains in an emitted declaration.
27
+
28
+ Subpath mode also emits `dts-imports.json` at the output root:
29
+
30
+ ```json
31
+ { "#types/*": { "types": "./*.d.ts" } }
32
+ ```
33
+
34
+ Merge this manifest into the `imports` field of the **published** package.json,
35
+ next to the output declarations (the plugin does not write package.json):
36
+
37
+ ```typescript
38
+ const imports = JSON.parse(await readFile("dist/dts-imports.json", "utf8"));
39
+ const publishedPackage = {
40
+ ...packageJson,
41
+ imports: { ...packageJson.imports, ...imports },
42
+ };
43
+ await writeFile("dist/package.json", JSON.stringify(publishedPackage, null, 2));
44
+ ```
45
+
46
+ Publish the declaration tree unchanged alongside that package.json. A custom
47
+ `subpathPrefix`, for example `#internal`, changes both the references and manifest
48
+ key. This mapping is for declaration types only, not runtime JavaScript imports.
package/dts.d.ts CHANGED
@@ -47,3 +47,10 @@ export declare interface PackageJson {
47
47
  }
48
48
 
49
49
  export { }
50
+
51
+
52
+ declare module 'fixture-external' {
53
+ interface External {
54
+ augmented: string;
55
+ }
56
+ }
package/dts_complex.d.ts CHANGED
@@ -19,8 +19,10 @@ import { Plugin } from 'vite';
19
19
  * (e.g., `bundled_vendor_name.d.ts`) and referenced from your main declarations, rather than
20
20
  * being inlined.
21
21
  *
22
- * 4. **Path Alias Resolution**: All import/export paths are resolved to relative paths, eliminating
23
- * the need for consumers to configure `paths` in their `tsconfig.json`.
22
+ * 4. **Path Alias Resolution**: All import/export paths are resolved to relative paths by default,
23
+ * eliminating the need for consumers to configure `paths` in their `tsconfig.json`. Set
24
+ * `internalImports: 'subpath'` to emit package-private `#types/...` references and a
25
+ * `dts-imports.json` manifest for the published package's `imports` field.
24
26
  *
25
27
  * ## Pre-Rolled vs Bundled Dependencies
26
28
  *
@@ -75,7 +77,10 @@ import { Plugin } from 'vite';
75
77
  * preRolledDependencies: ['@nhtio/encoder'],
76
78
  * // Custom paths
77
79
  * tsConfigJsonPath: './tsconfig.build.json',
78
- * packageJsonPath: './package.json'
80
+ * packageJsonPath: './package.json',
81
+ * // Emits #types/... references plus dts-imports.json for package.json imports.
82
+ * internalImports: 'subpath',
83
+ * subpathPrefix: '#types'
79
84
  * })
80
85
  * ]
81
86
  * })
@@ -125,6 +130,16 @@ export declare interface Options {
125
130
  * If the dependency is not already included in `bundledDependencies`, it will be treated as if it were.
126
131
  */
127
132
  preRolledDependencies?: Array<string | RegExp>;
133
+ /**
134
+ * Controls how references to declarations emitted by this package are written. `relative` preserves the legacy extensionless relative paths; `subpath` uses package-private imports.
135
+ * @default 'relative'
136
+ */
137
+ internalImports?: 'relative' | 'subpath';
138
+ /**
139
+ * Package-private import prefix used when `internalImports` is `subpath`. It must start with `#`, not end in `/`, and not contain `*`.
140
+ * @default '#types'
141
+ */
142
+ subpathPrefix?: string;
128
143
  /**
129
144
  * Activate additional debug output information
130
145
  */
@@ -136,3 +151,10 @@ export declare interface Options {
136
151
  }
137
152
 
138
153
  export { }
154
+
155
+
156
+ declare module 'fixture-external' {
157
+ interface External {
158
+ augmented: string;
159
+ }
160
+ }
package/dts_complex.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { d } from "./index-C3j0_U_i.mjs";
1
+ import { d } from "./index-Crhrknhq.mjs";
2
2
  export {
3
3
  d as dtsComplex
4
4
  };
@@ -335484,6 +335484,8 @@ const defaultOptions = {
335484
335484
  nodeModulesPath: "./node_modules",
335485
335485
  bundledDependencies: [],
335486
335486
  preRolledDependencies: [],
335487
+ internalImports: "relative",
335488
+ subpathPrefix: "#types",
335487
335489
  debug: false,
335488
335490
  traceResolution: false
335489
335491
  };
@@ -335543,6 +335545,14 @@ const unpluginFactory = (options2) => {
335543
335545
  defaultOptions,
335544
335546
  options2 || {}
335545
335547
  );
335548
+ const { error: optionsError } = validator.object({
335549
+ internalImports: validator.string().valid("relative", "subpath").required(),
335550
+ subpathPrefix: validator.string().regex(/^#(?!.*\*)(?!.*\/$).*/).required()
335551
+ }).validate({
335552
+ internalImports: mergedOptions.internalImports,
335553
+ subpathPrefix: mergedOptions.subpathPrefix
335554
+ });
335555
+ if (optionsError) throw new Error(optionsError.message);
335546
335556
  const runtimeConfiguration = {
335547
335557
  entries: /* @__PURE__ */ new Map(),
335548
335558
  entryFileNameToEntryName: /* @__PURE__ */ new Map(),
@@ -335884,7 +335894,7 @@ const unpluginFactory = (options2) => {
335884
335894
  outDir: runtimeConfiguration.tempDirPath
335885
335895
  }
335886
335896
  };
335887
- const tmpDirProgram = ts.createProgram(tmpDirProgramConfig);
335897
+ let tmpDirProgram = ts.createProgram(tmpDirProgramConfig);
335888
335898
  const seenVendorLibPaths = /* @__PURE__ */ new Map();
335889
335899
  const seenPreBundledVendorLibSourceFiles = /* @__PURE__ */ new Map();
335890
335900
  const seeVendorLibPath = (node, sourceFilePath) => {
@@ -336052,14 +336062,45 @@ const unpluginFactory = (options2) => {
336052
336062
  console.log("[dts_complex] tmpDirRootNames sample (first 5):");
336053
336063
  Array.from(tmpDirRootNames).slice(0, 5).forEach((p) => console.log(" ", p));
336054
336064
  }
336065
+ if (mergedOptions.internalImports === "subpath") {
336066
+ for (const path2 of Object.values(rollupResults)) {
336067
+ if (path2) tmpDirRootNames.add(path2);
336068
+ }
336069
+ tmpDirProgram = ts.createProgram({
336070
+ ...tmpDirProgramConfig,
336071
+ rootNames: Array.from(tmpDirRootNames)
336072
+ });
336073
+ }
336055
336074
  const tmpDirTypeChecker = tmpDirProgram.getTypeChecker();
336056
336075
  const tmpDirTransformer = (context) => (sourceFile) => {
336057
336076
  const computeRelativePath = (targetPath) => {
336077
+ const withoutExtension = targetPath.replace(/\\/g, "/").replace(/\.(d\.ts|ts|tsx|cts|mts|js|jsx|cjs|mjs)$/, "");
336078
+ if (mergedOptions.internalImports === "subpath") {
336079
+ return `${mergedOptions.subpathPrefix}/${relative(
336080
+ runtimeConfiguration.tempDirPath,
336081
+ withoutExtension
336082
+ ).replace(/\\/g, "/")}`;
336083
+ }
336058
336084
  let relativeSpec = relative(dirname(sourceFile.fileName), targetPath).replace(/\\/g, "/").replace(/\.(d\.ts|ts|tsx|cts|mts|js|jsx|cjs|mjs)$/, "");
336059
336085
  if (!relativeSpec.startsWith(".")) relativeSpec = `./${relativeSpec}`;
336060
336086
  return relativeSpec;
336061
336087
  };
336088
+ const resolveRelativeSpecifier = (moduleName) => {
336089
+ if (!moduleName.startsWith("./") && !moduleName.startsWith("../")) return void 0;
336090
+ const candidate = resolve(dirname(sourceFile.fileName), moduleName);
336091
+ const targets = [candidate, `${candidate}.d.ts`, join(candidate, "index.d.ts")];
336092
+ const target = targets.find((path2) => tmpDirRootNames.has(path2));
336093
+ return target ? computeRelativePath(target) : void 0;
336094
+ };
336062
336095
  const resolveModuleSpecifier = (moduleName, moduleSpecifierNode) => {
336096
+ if (mergedOptions.internalImports === "subpath") {
336097
+ const packageName = runtimeConfiguration.packageJson.name;
336098
+ if (packageName && (moduleName === packageName || moduleName.startsWith(`${packageName}/`))) {
336099
+ return void 0;
336100
+ }
336101
+ const relativePath = resolveRelativeSpecifier(moduleName);
336102
+ if (relativePath) return relativePath;
336103
+ }
336063
336104
  if (isBundledVendorLib(moduleName)) {
336064
336105
  const defPath = rollupResults[moduleName];
336065
336106
  return defPath ? computeRelativePath(defPath) : void 0;
@@ -336075,7 +336116,7 @@ const unpluginFactory = (options2) => {
336075
336116
  console.log("[dts_complex] From file:", sourceFile.fileName);
336076
336117
  console.log("[dts_complex] Symbol target:", targetFile);
336077
336118
  }
336078
- if (targetFile.startsWith(runtimeConfiguration.tempDirPath) && targetFile.endsWith(".d.ts")) {
336119
+ if (targetFile.startsWith(runtimeConfiguration.tempDirPath) && targetFile.endsWith(".d.ts") && (mergedOptions.internalImports !== "subpath" || tmpDirRootNames.has(targetFile))) {
336079
336120
  const result = computeRelativePath(targetFile);
336080
336121
  if (runtimeConfiguration.debug) {
336081
336122
  console.log("[dts_complex] -> Using temp .d.ts:", result);
@@ -336168,7 +336209,7 @@ const unpluginFactory = (options2) => {
336168
336209
  if (newPath) {
336169
336210
  const newLiteral = ts.factory.createStringLiteral(newPath);
336170
336211
  const newLiteralType = ts.factory.createLiteralTypeNode(newLiteral);
336171
- return ts.factory.updateImportTypeNode(
336212
+ const updated = ts.factory.updateImportTypeNode(
336172
336213
  node,
336173
336214
  newLiteralType,
336174
336215
  node.attributes,
@@ -336176,6 +336217,7 @@ const unpluginFactory = (options2) => {
336176
336217
  node.typeArguments,
336177
336218
  node.isTypeOf
336178
336219
  );
336220
+ return mergedOptions.internalImports === "subpath" ? ts.visitEachChild(updated, visitor, context) : updated;
336179
336221
  }
336180
336222
  }
336181
336223
  }
@@ -336211,6 +336253,33 @@ const unpluginFactory = (options2) => {
336211
336253
  }
336212
336254
  }
336213
336255
  logger.succeed(`Fixed import and export references in generated declaration files`);
336256
+ if (mergedOptions.internalImports === "subpath") {
336257
+ const relativeSpecifiers = [];
336258
+ for (const absolutePath of tmpDirRootNames) {
336259
+ const source = ts.createSourceFile(
336260
+ absolutePath,
336261
+ await readFile(absolutePath, "utf-8"),
336262
+ ts.ScriptTarget.Latest
336263
+ );
336264
+ const visit = (node) => {
336265
+ const specifier = ts.isImportDeclaration(node) || ts.isExportDeclaration(node) ? node.moduleSpecifier : ts.isImportTypeNode(node) && ts.isLiteralTypeNode(node.argument) ? node.argument.literal : void 0;
336266
+ if (specifier && ts.isStringLiteral(specifier) && /^(\.\/|\.\.\/)/.test(specifier.text)) {
336267
+ relativeSpecifiers.push(
336268
+ `${relative(runtimeConfiguration.tempDirPath, absolutePath)}: ${specifier.text}`
336269
+ );
336270
+ }
336271
+ ts.forEachChild(node, visit);
336272
+ };
336273
+ visit(source);
336274
+ }
336275
+ if (relativeSpecifiers.length) {
336276
+ await cleanup();
336277
+ return this.error(
336278
+ `subpath imports left relative declaration specifiers:
336279
+ ${relativeSpecifiers.join("\n")}`
336280
+ );
336281
+ }
336282
+ }
336214
336283
  logger.info("Adding type definitions to the build output");
336215
336284
  logger.start("Generating Typescript Definition Files");
336216
336285
  const finalDirents = await readdir(runtimeConfiguration.tempDirPath, {
@@ -336246,6 +336315,18 @@ const unpluginFactory = (options2) => {
336246
336315
  return this.error(`Failed to add type definitions to the build output: ${String(e2)}`);
336247
336316
  }
336248
336317
  }
336318
+ if (mergedOptions.internalImports === "subpath") {
336319
+ const manifest = `${JSON.stringify({ [`${mergedOptions.subpathPrefix}/*`]: { types: "./*.d.ts" } }, null, 2)}
336320
+ `;
336321
+ this.emitFile({
336322
+ type: "asset",
336323
+ name: "dts-imports.json",
336324
+ needsCodeReference: false,
336325
+ originalFileName: "dts-imports.json",
336326
+ fileName: "dts-imports.json",
336327
+ source: manifest
336328
+ });
336329
+ }
336249
336330
  await cleanup();
336250
336331
  logger.succeed(`Generated Typescript Definition Files`);
336251
336332
  },
@@ -336259,4 +336340,4 @@ const dtsComplex = /* @__PURE__ */ createVitePlugin(unpluginFactory);
336259
336340
  export {
336260
336341
  dtsComplex as d
336261
336342
  };
336262
- //# sourceMappingURL=index-C3j0_U_i.mjs.map
336343
+ //# sourceMappingURL=index-Crhrknhq.mjs.map