diff --git a/.changeset/vite-config-internal-declarations.md b/.changeset/vite-config-internal-declarations.md new file mode 100644 index 00000000..fc8c8a30 --- /dev/null +++ b/.changeset/vite-config-internal-declarations.md @@ -0,0 +1,5 @@ +--- +'@tanstack/vite-config': minor +--- + +Add the `internalDeclarations` option. It writes one more set of ESM declarations with `stripInternal: false` to `dist/internal` (or `dist/`), so packages in the same workspace can read members tagged `@internal` through a custom export condition while the published `dist/esm` and `dist/cjs` declarations stay trimmed. diff --git a/docs/vite.md b/docs/vite.md index 4fa4e836..964266e3 100644 --- a/docs/vite.md +++ b/docs/vite.md @@ -89,3 +89,60 @@ export default mergeConfig( }), ) ``` + +### Internal declarations + +With `stripInternal: true` in the tsconfig, members tagged `/** @internal */` are removed from the emitted declarations. A package in the same workspace that reads one of those members then fails to type-check, because it resolves the trimmed declarations in `dist`. The `internalDeclarations` option writes one more set of declarations with `stripInternal: false`, which only those packages resolve: + +```ts +tanstackViteConfig({ + entry: './src/index.ts', + srcDir: './src', + // writes dist/internal; use { dir: 'internal-types' } for dist/internal-types + internalDeclarations: true, +}) +``` + +The set has the same layout and import extensions as `dist/esm`, and `dist/esm` and `dist/cjs` stay exactly as they are without the option. It is ESM only (`.d.ts`). `beforeWriteDeclarationFile` runs for these files too. The extra set costs one more TypeScript program per build. + +`@tanstack/vite-config` does not edit `package.json`. Point a custom condition at the set, nested inside `types` so that `types` stays the first key, under both `import` and `require`: + +```json +{ + "exports": { + ".": { + "import": { + "types": { + "tanstack-internal": "./dist/internal/index.d.ts", + "default": "./dist/esm/index.d.ts" + }, + "default": "./dist/esm/index.js" + }, + "require": { + "types": { + "tanstack-internal": "./dist/internal/index.d.ts", + "default": "./dist/cjs/index.d.cts" + }, + "default": "./dist/cjs/index.cjs" + } + } + }, + "files": ["dist/esm", "dist/cjs"] +} +``` + +Wire the condition under every branch that has types. If a program resolves the untrimmed declarations through `import` and the trimmed ones through `require`, it sees two declarations of the same class, and a class with `private` members is then not assignable to itself (`TS2322: Types have separate declarations of a private property`). Since both branches point at the same `.d.ts` files, a CommonJS file that resolves them reads ESM declarations. TypeScript 6.0 accepts that with `module: nodenext`. With `node16`, or on TypeScript 5.6, it reports `TS1479`. + +Then add the condition to the tsconfig of the packages that should see the internal members. `customConditions` needs `moduleResolution` set to `bundler`, `node16` or `nodenext`: + +```json +{ + "compilerOptions": { + "customConditions": ["tanstack-internal"] + } +} +``` + +Put it in a base tsconfig that only those packages extend. A root tsconfig that apps, examples or benchmarks also extend would show them the internal members too. + +Keep the internal set out of the published package, as in the `files` field above. The published `exports` still names `dist/internal`, but TypeScript falls back to the `default` types when that file is missing, so a consumer who sets the condition gets the trimmed declarations. You can ship the set by adding `dist/internal` to `files`, but that is risky: with project references, a referenced project resolves imports with its own `customConditions`. A project without the condition that references one with it loads both sets and fails with the same `TS2322`. diff --git a/integrations/internal-declarations-consumer/package.json b/integrations/internal-declarations-consumer/package.json new file mode 100644 index 00000000..d9139bd8 --- /dev/null +++ b/integrations/internal-declarations-consumer/package.json @@ -0,0 +1,47 @@ +{ + "name": "@tanstack/integration-internal-declarations-consumer", + "version": "1.0.0", + "private": true, + "type": "module", + "exports": { + ".": { + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + } + }, + "./package.json": "./package.json" + }, + "main": "dist/cjs/index.cjs", + "module": "dist/esm/index.js", + "types": "dist/esm/index.d.ts", + "files": [ + "dist" + ], + "scripts": { + "build": "vite build", + "test:build": "vitest && publint --strict" + }, + "nx": { + "targets": { + "build": { + "dependsOn": [ + "^build" + ] + } + } + }, + "dependencies": { + "@tanstack/integration-internal-declarations": "workspace:*" + }, + "devDependencies": { + "@tanstack/vite-config": "workspace:*", + "typescript": "catalog:", + "vite": "catalog:", + "vitest": "catalog:" + } +} diff --git a/integrations/internal-declarations-consumer/src/index.ts b/integrations/internal-declarations-consumer/src/index.ts new file mode 100644 index 00000000..6a5ed2bf --- /dev/null +++ b/integrations/internal-declarations-consumer/src/index.ts @@ -0,0 +1,14 @@ +import { Router } from '@tanstack/integration-internal-declarations' +import { extraInternal } from '@tanstack/integration-internal-declarations/extra' +import type { Match } from '@tanstack/integration-internal-declarations' + +// Reads members that are tagged `@internal` in the library. +export function pendingCount(router: Router): number { + return router._pending.size +} + +export function strictParams(match: Match): Record { + return match._strictParams +} + +export const extraName: string = extraInternal diff --git a/integrations/internal-declarations-consumer/tests/mixed/cjs.cts b/integrations/internal-declarations-consumer/tests/mixed/cjs.cts new file mode 100644 index 00000000..108bf4aa --- /dev/null +++ b/integrations/internal-declarations-consumer/tests/mixed/cjs.cts @@ -0,0 +1,7 @@ +import { Router } from '@tanstack/integration-internal-declarations' +import type { router as esmRouter } from './esm.mjs' + +// Fails with "Types have separate declarations of a private property" if this +// file resolved a different declaration file for `Router` than `esm.mts`. +export const router: Router = {} as typeof esmRouter +export const pending: number = router._pending.size diff --git a/integrations/internal-declarations-consumer/tests/mixed/esm.mts b/integrations/internal-declarations-consumer/tests/mixed/esm.mts new file mode 100644 index 00000000..3640ceb3 --- /dev/null +++ b/integrations/internal-declarations-consumer/tests/mixed/esm.mts @@ -0,0 +1,4 @@ +import { Router } from '@tanstack/integration-internal-declarations' + +export const router: Router = new Router('/') +export const pending: number = router._pending.size diff --git a/integrations/internal-declarations-consumer/tests/types.test.ts b/integrations/internal-declarations-consumer/tests/types.test.ts new file mode 100644 index 00000000..440c2e1b --- /dev/null +++ b/integrations/internal-declarations-consumer/tests/types.test.ts @@ -0,0 +1,55 @@ +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import ts from 'typescript' +import { describe, expect, it } from 'vitest' + +const __dirname = dirname(fileURLToPath(import.meta.url)) +const rootDir = resolve(__dirname, '..') + +function typeCheck( + customConditions: Array, + rootNames: Array = [`${rootDir}/src/index.ts`], + overrides: ts.CompilerOptions = {}, +) { + const { config } = ts.readConfigFile( + `${rootDir}/tsconfig.json`, + ts.sys.readFile, + ) + const { options } = ts.parseJsonConfigFileContent(config, ts.sys, rootDir) + const program = ts.createProgram(rootNames, { + ...options, + ...overrides, + customConditions, + }) + return ts + .getPreEmitDiagnostics(program) + .map((diagnostic) => + ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'), + ) +} + +describe('check a sibling that reads @internal members', () => { + it('should type-check with the custom condition', () => { + expect(typeCheck(['tanstack-internal'])).toEqual([]) + }) + + it('should fail to type-check without the custom condition', () => { + expect(typeCheck([])).toEqual([ + `Module '"@tanstack/integration-internal-declarations/extra"' has no exported member 'extraInternal'.`, + `Property '_pending' does not exist on type 'Router'.`, + `Property '_strictParams' does not exist on type 'Match'.`, + ]) + }) + + it('should load one declaration tree for ESM and CJS files', () => { + const mixed = [ + `${rootDir}/tests/mixed/esm.mts`, + `${rootDir}/tests/mixed/cjs.cts`, + ] + const nodeNext = { + module: ts.ModuleKind.NodeNext, + moduleResolution: ts.ModuleResolutionKind.NodeNext, + } + expect(typeCheck(['tanstack-internal'], mixed, nodeNext)).toEqual([]) + }) +}) diff --git a/integrations/internal-declarations-consumer/tsconfig.json b/integrations/internal-declarations-consumer/tsconfig.json new file mode 100644 index 00000000..f432f03d --- /dev/null +++ b/integrations/internal-declarations-consumer/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "target": "ES2020", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "useDefineForClassFields": true, + "module": "ESNext", + + /* Bundler mode */ + "moduleResolution": "bundler", + "customConditions": ["tanstack-internal"], + "resolveJsonModule": true, + "allowImportingTsExtensions": true, + + /* Linting */ + "strict": true, + "noFallthroughCasesInSwitch": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noEmit": true, + "isolatedModules": true, + "skipLibCheck": true + }, + "include": ["src", "tests", "vite.config.ts"] +} diff --git a/integrations/internal-declarations-consumer/vite.config.ts b/integrations/internal-declarations-consumer/vite.config.ts new file mode 100644 index 00000000..061cbb34 --- /dev/null +++ b/integrations/internal-declarations-consumer/vite.config.ts @@ -0,0 +1,17 @@ +import { tanstackViteConfig } from '@tanstack/vite-config' +import { defineConfig, mergeConfig } from 'vitest/config' + +const config = defineConfig({ + test: { + name: 'internal-declarations-consumer-integration', + watch: false, + }, +}) + +export default mergeConfig( + config, + tanstackViteConfig({ + entry: './src/index.ts', + srcDir: './src', + }), +) diff --git a/integrations/internal-declarations/package.json b/integrations/internal-declarations/package.json new file mode 100644 index 00000000..a2aff100 --- /dev/null +++ b/integrations/internal-declarations/package.json @@ -0,0 +1,57 @@ +{ + "name": "@tanstack/integration-internal-declarations", + "version": "1.0.0", + "private": true, + "type": "module", + "exports": { + ".": { + "import": { + "types": { + "tanstack-internal": "./dist/internal/index.d.ts", + "default": "./dist/esm/index.d.ts" + }, + "default": "./dist/esm/index.js" + }, + "require": { + "types": { + "tanstack-internal": "./dist/internal/index.d.ts", + "default": "./dist/cjs/index.d.cts" + }, + "default": "./dist/cjs/index.cjs" + } + }, + "./extra": { + "import": { + "types": { + "tanstack-internal": "./dist/internal/extra.d.ts", + "default": "./dist/esm/extra.d.ts" + }, + "default": "./dist/esm/extra.js" + }, + "require": { + "types": { + "tanstack-internal": "./dist/internal/extra.d.ts", + "default": "./dist/cjs/extra.d.cts" + }, + "default": "./dist/cjs/extra.cjs" + } + }, + "./package.json": "./package.json" + }, + "main": "dist/cjs/index.cjs", + "module": "dist/esm/index.js", + "types": "dist/esm/index.d.ts", + "files": [ + "dist/esm", + "dist/cjs" + ], + "scripts": { + "build": "vite build", + "test:build": "vitest && publint --strict" + }, + "devDependencies": { + "@tanstack/vite-config": "workspace:*", + "vite": "catalog:", + "vitest": "catalog:" + } +} diff --git a/integrations/internal-declarations/snap/cjs/extra.cjs b/integrations/internal-declarations/snap/cjs/extra.cjs new file mode 100644 index 00000000..78f21f99 --- /dev/null +++ b/integrations/internal-declarations/snap/cjs/extra.cjs @@ -0,0 +1,12 @@ +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +//#region src/extra.ts +function matchId(match) { + return match.id; +} +/** @internal */ +var extraInternal = "extra"; +//#endregion +exports.extraInternal = extraInternal; +exports.matchId = matchId; + +//# sourceMappingURL=extra.cjs.map \ No newline at end of file diff --git a/integrations/internal-declarations/snap/cjs/extra.cjs.map b/integrations/internal-declarations/snap/cjs/extra.cjs.map new file mode 100644 index 00000000..85cd3c82 --- /dev/null +++ b/integrations/internal-declarations/snap/cjs/extra.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"extra.cjs","names":[],"sources":["../../src/extra.ts"],"sourcesContent":["import type { Match } from './index'\n\nexport function matchId(match: Match): string {\n return match.id\n}\n\n/** @internal */\nexport const extraInternal = 'extra'\n"],"mappings":";;AAEA,SAAgB,QAAQ,OAAsB;CAC5C,OAAO,MAAM;AACf;;AAGA,IAAa,gBAAgB"} \ No newline at end of file diff --git a/integrations/internal-declarations/snap/cjs/extra.d.cts b/integrations/internal-declarations/snap/cjs/extra.d.cts new file mode 100644 index 00000000..d0c91d05 --- /dev/null +++ b/integrations/internal-declarations/snap/cjs/extra.d.cts @@ -0,0 +1,2 @@ +import { Match } from './index.cjs'; +export declare function matchId(match: Match): string; diff --git a/integrations/internal-declarations/snap/cjs/index.cjs b/integrations/internal-declarations/snap/cjs/index.cjs new file mode 100644 index 00000000..fa225880 --- /dev/null +++ b/integrations/internal-declarations/snap/cjs/index.cjs @@ -0,0 +1,32 @@ +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +const require_paths = require("./nested/paths.cjs"); +//#region src/index.ts +var Router = class { + basepath; + seen = 0; + /** @internal */ + _pending = /* @__PURE__ */ new Map(); + constructor(basepath) { + this.basepath = basepath; + } + resolve(path) { + this.seen++; + return require_paths.joinPaths(this.basepath, path); + } + /** @internal */ + _commit(match) { + this._pending.set(match.id, match); + } +}; +/** @internal */ +function createMatch(id) { + return { + id, + _strictParams: {} + }; +} +//#endregion +exports.Router = Router; +exports.createMatch = createMatch; + +//# sourceMappingURL=index.cjs.map \ No newline at end of file diff --git a/integrations/internal-declarations/snap/cjs/index.cjs.map b/integrations/internal-declarations/snap/cjs/index.cjs.map new file mode 100644 index 00000000..f271c44f --- /dev/null +++ b/integrations/internal-declarations/snap/cjs/index.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.cjs","names":["joinPaths"],"sources":["../../src/index.ts"],"sourcesContent":["import { joinPaths } from './nested/paths'\n\nexport interface Match {\n id: string\n /** @internal */\n _strictParams: Record\n}\n\nexport class Router {\n basepath: string\n private seen = 0\n /** @internal */\n _pending = new Map()\n\n constructor(basepath: string) {\n this.basepath = basepath\n }\n\n resolve(path: string): string {\n this.seen++\n return joinPaths(this.basepath, path)\n }\n\n /** @internal */\n _commit(match: Match): void {\n this._pending.set(match.id, match)\n }\n}\n\n/** @internal */\nexport function createMatch(id: string): Match {\n return { id, _strictParams: {} }\n}\n"],"mappings":";;;AAQA,IAAa,SAAb,MAAoB;CAClB;CACA,OAAe;;CAEf,2BAAW,IAAI,IAAmB;CAElC,YAAY,UAAkB;EAC5B,KAAK,WAAW;CAClB;CAEA,QAAQ,MAAsB;EAC5B,KAAK;EACL,OAAOA,cAAAA,UAAU,KAAK,UAAU,IAAI;CACtC;;CAGA,QAAQ,OAAoB;EAC1B,KAAK,SAAS,IAAI,MAAM,IAAI,KAAK;CACnC;AACF;;AAGA,SAAgB,YAAY,IAAmB;CAC7C,OAAO;EAAE;EAAI,eAAe,CAAC;CAAE;AACjC"} \ No newline at end of file diff --git a/integrations/internal-declarations/snap/cjs/index.d.cts b/integrations/internal-declarations/snap/cjs/index.d.cts new file mode 100644 index 00000000..76a66758 --- /dev/null +++ b/integrations/internal-declarations/snap/cjs/index.d.cts @@ -0,0 +1,9 @@ +export interface Match { + id: string; +} +export declare class Router { + basepath: string; + private seen; + constructor(basepath: string); + resolve(path: string): string; +} diff --git a/integrations/internal-declarations/snap/cjs/nested/paths.cjs b/integrations/internal-declarations/snap/cjs/nested/paths.cjs new file mode 100644 index 00000000..726bd251 --- /dev/null +++ b/integrations/internal-declarations/snap/cjs/nested/paths.cjs @@ -0,0 +1,8 @@ +//#region src/nested/paths.ts +function joinPaths(...paths) { + return paths.join("/").replace(/\/{2,}/g, "/"); +} +//#endregion +exports.joinPaths = joinPaths; + +//# sourceMappingURL=paths.cjs.map \ No newline at end of file diff --git a/integrations/internal-declarations/snap/cjs/nested/paths.cjs.map b/integrations/internal-declarations/snap/cjs/nested/paths.cjs.map new file mode 100644 index 00000000..323c1c9c --- /dev/null +++ b/integrations/internal-declarations/snap/cjs/nested/paths.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"paths.cjs","names":[],"sources":["../../../src/nested/paths.ts"],"sourcesContent":["export function joinPaths(...paths: Array): string {\n return paths.join('/').replace(/\\/{2,}/g, '/')\n}\n"],"mappings":";AAAA,SAAgB,UAAU,GAAG,OAA8B;CACzD,OAAO,MAAM,KAAK,GAAG,CAAC,CAAC,QAAQ,WAAW,GAAG;AAC/C"} \ No newline at end of file diff --git a/integrations/internal-declarations/snap/cjs/nested/paths.d.cts b/integrations/internal-declarations/snap/cjs/nested/paths.d.cts new file mode 100644 index 00000000..b4cc319a --- /dev/null +++ b/integrations/internal-declarations/snap/cjs/nested/paths.d.cts @@ -0,0 +1 @@ +export declare function joinPaths(...paths: Array): string; diff --git a/integrations/internal-declarations/snap/esm/extra.d.ts b/integrations/internal-declarations/snap/esm/extra.d.ts new file mode 100644 index 00000000..73741f22 --- /dev/null +++ b/integrations/internal-declarations/snap/esm/extra.d.ts @@ -0,0 +1,2 @@ +import { Match } from './index.js'; +export declare function matchId(match: Match): string; diff --git a/integrations/internal-declarations/snap/esm/extra.js b/integrations/internal-declarations/snap/esm/extra.js new file mode 100644 index 00000000..598babeb --- /dev/null +++ b/integrations/internal-declarations/snap/esm/extra.js @@ -0,0 +1,10 @@ +//#region src/extra.ts +function matchId(match) { + return match.id; +} +/** @internal */ +var extraInternal = "extra"; +//#endregion +export { extraInternal, matchId }; + +//# sourceMappingURL=extra.js.map \ No newline at end of file diff --git a/integrations/internal-declarations/snap/esm/extra.js.map b/integrations/internal-declarations/snap/esm/extra.js.map new file mode 100644 index 00000000..0b97b9d0 --- /dev/null +++ b/integrations/internal-declarations/snap/esm/extra.js.map @@ -0,0 +1 @@ +{"version":3,"file":"extra.js","names":[],"sources":["../../src/extra.ts"],"sourcesContent":["import type { Match } from './index'\n\nexport function matchId(match: Match): string {\n return match.id\n}\n\n/** @internal */\nexport const extraInternal = 'extra'\n"],"mappings":";AAEA,SAAgB,QAAQ,OAAsB;CAC5C,OAAO,MAAM;AACf;;AAGA,IAAa,gBAAgB"} \ No newline at end of file diff --git a/integrations/internal-declarations/snap/esm/index.d.ts b/integrations/internal-declarations/snap/esm/index.d.ts new file mode 100644 index 00000000..76a66758 --- /dev/null +++ b/integrations/internal-declarations/snap/esm/index.d.ts @@ -0,0 +1,9 @@ +export interface Match { + id: string; +} +export declare class Router { + basepath: string; + private seen; + constructor(basepath: string); + resolve(path: string): string; +} diff --git a/integrations/internal-declarations/snap/esm/index.js b/integrations/internal-declarations/snap/esm/index.js new file mode 100644 index 00000000..373135ba --- /dev/null +++ b/integrations/internal-declarations/snap/esm/index.js @@ -0,0 +1,30 @@ +import { joinPaths } from "./nested/paths.js"; +//#region src/index.ts +var Router = class { + basepath; + seen = 0; + /** @internal */ + _pending = /* @__PURE__ */ new Map(); + constructor(basepath) { + this.basepath = basepath; + } + resolve(path) { + this.seen++; + return joinPaths(this.basepath, path); + } + /** @internal */ + _commit(match) { + this._pending.set(match.id, match); + } +}; +/** @internal */ +function createMatch(id) { + return { + id, + _strictParams: {} + }; +} +//#endregion +export { Router, createMatch }; + +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/integrations/internal-declarations/snap/esm/index.js.map b/integrations/internal-declarations/snap/esm/index.js.map new file mode 100644 index 00000000..8eecf670 --- /dev/null +++ b/integrations/internal-declarations/snap/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["import { joinPaths } from './nested/paths'\n\nexport interface Match {\n id: string\n /** @internal */\n _strictParams: Record\n}\n\nexport class Router {\n basepath: string\n private seen = 0\n /** @internal */\n _pending = new Map()\n\n constructor(basepath: string) {\n this.basepath = basepath\n }\n\n resolve(path: string): string {\n this.seen++\n return joinPaths(this.basepath, path)\n }\n\n /** @internal */\n _commit(match: Match): void {\n this._pending.set(match.id, match)\n }\n}\n\n/** @internal */\nexport function createMatch(id: string): Match {\n return { id, _strictParams: {} }\n}\n"],"mappings":";;AAQA,IAAa,SAAb,MAAoB;CAClB;CACA,OAAe;;CAEf,2BAAW,IAAI,IAAmB;CAElC,YAAY,UAAkB;EAC5B,KAAK,WAAW;CAClB;CAEA,QAAQ,MAAsB;EAC5B,KAAK;EACL,OAAO,UAAU,KAAK,UAAU,IAAI;CACtC;;CAGA,QAAQ,OAAoB;EAC1B,KAAK,SAAS,IAAI,MAAM,IAAI,KAAK;CACnC;AACF;;AAGA,SAAgB,YAAY,IAAmB;CAC7C,OAAO;EAAE;EAAI,eAAe,CAAC;CAAE;AACjC"} \ No newline at end of file diff --git a/integrations/internal-declarations/snap/esm/nested/paths.d.ts b/integrations/internal-declarations/snap/esm/nested/paths.d.ts new file mode 100644 index 00000000..b4cc319a --- /dev/null +++ b/integrations/internal-declarations/snap/esm/nested/paths.d.ts @@ -0,0 +1 @@ +export declare function joinPaths(...paths: Array): string; diff --git a/integrations/internal-declarations/snap/esm/nested/paths.js b/integrations/internal-declarations/snap/esm/nested/paths.js new file mode 100644 index 00000000..9f6f262f --- /dev/null +++ b/integrations/internal-declarations/snap/esm/nested/paths.js @@ -0,0 +1,8 @@ +//#region src/nested/paths.ts +function joinPaths(...paths) { + return paths.join("/").replace(/\/{2,}/g, "/"); +} +//#endregion +export { joinPaths }; + +//# sourceMappingURL=paths.js.map \ No newline at end of file diff --git a/integrations/internal-declarations/snap/esm/nested/paths.js.map b/integrations/internal-declarations/snap/esm/nested/paths.js.map new file mode 100644 index 00000000..1f25b37e --- /dev/null +++ b/integrations/internal-declarations/snap/esm/nested/paths.js.map @@ -0,0 +1 @@ +{"version":3,"file":"paths.js","names":[],"sources":["../../../src/nested/paths.ts"],"sourcesContent":["export function joinPaths(...paths: Array): string {\n return paths.join('/').replace(/\\/{2,}/g, '/')\n}\n"],"mappings":";AAAA,SAAgB,UAAU,GAAG,OAA8B;CACzD,OAAO,MAAM,KAAK,GAAG,CAAC,CAAC,QAAQ,WAAW,GAAG;AAC/C"} \ No newline at end of file diff --git a/integrations/internal-declarations/snap/internal/extra.d.ts b/integrations/internal-declarations/snap/internal/extra.d.ts new file mode 100644 index 00000000..cd670bc3 --- /dev/null +++ b/integrations/internal-declarations/snap/internal/extra.d.ts @@ -0,0 +1,4 @@ +import { Match } from './index.js'; +export declare function matchId(match: Match): string; +/** @internal */ +export declare const extraInternal = "extra"; diff --git a/integrations/internal-declarations/snap/internal/index.d.ts b/integrations/internal-declarations/snap/internal/index.d.ts new file mode 100644 index 00000000..b47c1e32 --- /dev/null +++ b/integrations/internal-declarations/snap/internal/index.d.ts @@ -0,0 +1,17 @@ +export interface Match { + id: string; + /** @internal */ + _strictParams: Record; +} +export declare class Router { + basepath: string; + private seen; + /** @internal */ + _pending: Map; + constructor(basepath: string); + resolve(path: string): string; + /** @internal */ + _commit(match: Match): void; +} +/** @internal */ +export declare function createMatch(id: string): Match; diff --git a/integrations/internal-declarations/snap/internal/nested/paths.d.ts b/integrations/internal-declarations/snap/internal/nested/paths.d.ts new file mode 100644 index 00000000..b4cc319a --- /dev/null +++ b/integrations/internal-declarations/snap/internal/nested/paths.d.ts @@ -0,0 +1 @@ +export declare function joinPaths(...paths: Array): string; diff --git a/integrations/internal-declarations/src/extra.ts b/integrations/internal-declarations/src/extra.ts new file mode 100644 index 00000000..85b6f74d --- /dev/null +++ b/integrations/internal-declarations/src/extra.ts @@ -0,0 +1,8 @@ +import type { Match } from './index' + +export function matchId(match: Match): string { + return match.id +} + +/** @internal */ +export const extraInternal = 'extra' diff --git a/integrations/internal-declarations/src/index.ts b/integrations/internal-declarations/src/index.ts new file mode 100644 index 00000000..6005abab --- /dev/null +++ b/integrations/internal-declarations/src/index.ts @@ -0,0 +1,33 @@ +import { joinPaths } from './nested/paths' + +export interface Match { + id: string + /** @internal */ + _strictParams: Record +} + +export class Router { + basepath: string + private seen = 0 + /** @internal */ + _pending = new Map() + + constructor(basepath: string) { + this.basepath = basepath + } + + resolve(path: string): string { + this.seen++ + return joinPaths(this.basepath, path) + } + + /** @internal */ + _commit(match: Match): void { + this._pending.set(match.id, match) + } +} + +/** @internal */ +export function createMatch(id: string): Match { + return { id, _strictParams: {} } +} diff --git a/integrations/internal-declarations/src/nested/paths.ts b/integrations/internal-declarations/src/nested/paths.ts new file mode 100644 index 00000000..d36afa4a --- /dev/null +++ b/integrations/internal-declarations/src/nested/paths.ts @@ -0,0 +1,3 @@ +export function joinPaths(...paths: Array): string { + return paths.join('/').replace(/\/{2,}/g, '/') +} diff --git a/integrations/internal-declarations/tests/build.test.ts b/integrations/internal-declarations/tests/build.test.ts new file mode 100644 index 00000000..79ed79f3 --- /dev/null +++ b/integrations/internal-declarations/tests/build.test.ts @@ -0,0 +1,129 @@ +import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { tanstackViteConfig } from '@tanstack/vite-config' +import { build, mergeConfig } from 'vite' +import { afterAll, describe, expect, it } from 'vitest' +import type { Options } from '@tanstack/vite-config' + +const __dirname = dirname(fileURLToPath(import.meta.url)) +const rootDir = resolve(__dirname, '..') +const distDir = `${rootDir}/dist` + +const listFiles = (dir: string) => + readdirSync(dir, { recursive: true, withFileTypes: true }) + .filter((entry) => entry.isFile()) + .map((entry) => join(entry.parentPath, entry.name).slice(dir.length + 1)) + .sort() + +const readDeclarations = (dir: string) => + Object.fromEntries( + listFiles(dir) + .filter((file) => /\.d\.c?ts$/.test(file)) + .map((file) => [file, readFileSync(join(dir, file), 'utf8')]), + ) + +const tempDirs: Array = [] + +afterAll(() => { + tempDirs.forEach((dir) => rmSync(dir, { recursive: true, force: true })) +}) + +/** Builds the fixture with `options` into a temporary directory. */ +async function buildVariant(options: Partial) { + const outDir = mkdtempSync(join(tmpdir(), 'tanstack-internal-declarations-')) + tempDirs.push(outDir) + await build( + mergeConfig( + { root: rootDir, configFile: false, logLevel: 'silent' }, + tanstackViteConfig({ + entry: ['./src/index.ts', './src/extra.ts'], + srcDir: './src', + tsconfigPath: './tsconfig.build.json', + outDir, + ...options, + }), + ), + ) + return outDir +} + +describe('check internal declarations build output', () => { + it('should build the same output', async () => { + for (const file of listFiles(distDir)) { + await expect( + readFileSync(`${distDir}/${file}`, 'utf8'), + ).toMatchFileSnapshot(`${rootDir}/snap/${file}`) + } + expect(listFiles(distDir)).toEqual(listFiles(`${rootDir}/snap`)) + }) + + it('should keep @internal members only in the internal declarations', () => { + const internal = readDeclarations(`${distDir}/internal`) + expect(Object.keys(internal)).toEqual([ + 'extra.d.ts', + 'index.d.ts', + 'nested/paths.d.ts', + ]) + expect(internal['index.d.ts']).toContain('_pending: Map;') + expect(internal['index.d.ts']).toContain('_strictParams') + expect(internal['index.d.ts']).toContain('createMatch') + expect(internal['extra.d.ts']).toContain('extraInternal') + expect(internal['extra.d.ts']).toContain("from './index.js'") + + for (const dir of ['esm', 'cjs']) { + for (const content of Object.values( + readDeclarations(`${distDir}/${dir}`), + )) { + expect(content).not.toMatch( + /@internal|_pending|_strictParams|createMatch|extraInternal/, + ) + } + } + }) + + it('should not change the other output when the option is off', async () => { + const outDir = await buildVariant({ internalDeclarations: false }) + + expect(listFiles(outDir)).toEqual( + listFiles(distDir).filter((file) => !file.startsWith('internal/')), + ) + // Source maps hold paths relative to the output directory, so only + // compare the code and declarations. + for (const file of listFiles(outDir).filter((f) => !f.endsWith('.map'))) { + expect(readFileSync(join(outDir, file), 'utf8'), file).toBe( + readFileSync(join(distDir, file), 'utf8'), + ) + } + }) + + it('should write to a custom directory without CJS output', async () => { + const outDir = await buildVariant({ + cjs: false, + internalDeclarations: { dir: 'types-internal' }, + }) + + expect(readdirSync(outDir).sort()).toEqual(['esm', 'types-internal']) + expect(readDeclarations(`${outDir}/types-internal`)).toEqual( + readDeclarations(`${distDir}/internal`), + ) + expect(readDeclarations(`${outDir}/esm`)).toEqual( + readDeclarations(`${distDir}/esm`), + ) + }) + + it('should match the ESM declarations when the tsconfig keeps @internal', async () => { + const outDir = await buildVariant({ + tsconfigPath: undefined, + internalDeclarations: true, + }) + + expect(readDeclarations(`${outDir}/internal`)).toEqual( + readDeclarations(`${distDir}/internal`), + ) + expect(readDeclarations(`${outDir}/esm`)).toEqual( + readDeclarations(`${distDir}/internal`), + ) + }) +}) diff --git a/integrations/internal-declarations/tsconfig.build.json b/integrations/internal-declarations/tsconfig.build.json new file mode 100644 index 00000000..1fdd6eb2 --- /dev/null +++ b/integrations/internal-declarations/tsconfig.build.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "rootDir": "./src", + "stripInternal": true + }, + "include": ["src"] +} diff --git a/integrations/internal-declarations/tsconfig.json b/integrations/internal-declarations/tsconfig.json new file mode 100644 index 00000000..2aea2a99 --- /dev/null +++ b/integrations/internal-declarations/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "target": "ES2020", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "useDefineForClassFields": true, + "module": "ESNext", + + /* Bundler mode */ + "moduleResolution": "bundler", + "resolveJsonModule": true, + "allowImportingTsExtensions": true, + + /* Linting */ + "strict": true, + "noFallthroughCasesInSwitch": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noEmit": true, + "isolatedModules": true, + "skipLibCheck": true + }, + "include": ["src", "tests", "vite.config.ts"] +} diff --git a/integrations/internal-declarations/vite.config.ts b/integrations/internal-declarations/vite.config.ts new file mode 100644 index 00000000..e2c85081 --- /dev/null +++ b/integrations/internal-declarations/vite.config.ts @@ -0,0 +1,19 @@ +import { tanstackViteConfig } from '@tanstack/vite-config' +import { defineConfig, mergeConfig } from 'vitest/config' + +const config = defineConfig({ + test: { + name: 'internal-declarations-integration', + watch: false, + }, +}) + +export default mergeConfig( + config, + tanstackViteConfig({ + entry: ['./src/index.ts', './src/extra.ts'], + srcDir: './src', + tsconfigPath: './tsconfig.build.json', + internalDeclarations: true, + }), +) diff --git a/packages/vite-config/src/index.ts b/packages/vite-config/src/index.ts index dc197fef..c0ff97cd 100644 --- a/packages/vite-config/src/index.ts +++ b/packages/vite-config/src/index.ts @@ -30,9 +30,19 @@ function ensureImportFileExtension({ return content } +function getInternalDeclarationsDir(options: Options, outDir: string) { + const internal = options.internalDeclarations + if (!internal) { + return undefined + } + const dir = (internal === true ? undefined : internal.dir) ?? 'internal' + return `${outDir}/${dir}` +} + export const tanstackViteConfig = (options: Options): UserConfig => { const outDir = options.outDir ?? 'dist' const cjs = options.cjs ?? true + const internalDeclarationsDir = getInternalDeclarationsDir(options, outDir) return defineConfig({ resolve: { @@ -106,6 +116,35 @@ export const tanstackViteConfig = (options: Options): UserConfig => { }, }) : undefined, + // Same as the ESM declarations, but without `stripInternal`, so that + // members tagged `@internal` stay in. Meant for workspace siblings that + // resolve it through a custom export condition. + internalDeclarationsDir + ? dts({ + outDirs: internalDeclarationsDir, + entryRoot: options.srcDir, + include: options.srcDir, + exclude: options.exclude, + tsconfigPath: options.tsconfigPath, + compilerOptions: { + module: 99, // ESNext + declarationMap: false, + stripInternal: false, + }, + beforeWriteFile: (filePath, content) => { + content = + options.beforeWriteDeclarationFile?.(filePath, content) || + content + return { + filePath, + content: ensureImportFileExtension({ + content, + extension: 'js', + }), + } + }, + }) + : undefined, ], build: { outDir, diff --git a/packages/vite-config/src/types.ts b/packages/vite-config/src/types.ts index 88c7d6bc..2e24453a 100644 --- a/packages/vite-config/src/types.ts +++ b/packages/vite-config/src/types.ts @@ -15,6 +15,12 @@ export type Options = { externalDeps?: Array /** Dependencies to bundle. Will be passed to the except argument of `vite-plugin-externalize-deps` */ bundledDeps?: Array + /** + * Also emit ESM declarations with `stripInternal: false` to `${outDir}/internal`, + * or to `${outDir}/${dir}`, for packages that resolve them through a custom + * export condition. Defaults to `false`. + */ + internalDeclarations?: boolean | { dir?: string } /** Hook called prior to writing each declaration file; allows to transform the content */ beforeWriteDeclarationFile?: (filePath: string, content: string) => string } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e26c5b79..6c38a7dc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -365,6 +365,37 @@ importers: specifier: 'catalog:' version: 6.0.2 + integrations/internal-declarations: + devDependencies: + '@tanstack/vite-config': + specifier: workspace:* + version: link:../../packages/vite-config + vite: + specifier: 'catalog:' + version: 8.3.5(@types/node@24.19.2)(jiti@2.7.0)(yaml@2.9.1) + vitest: + specifier: 'catalog:' + version: 5.0.5(@types/node@24.19.2)(jsdom@29.1.1)(vite@8.3.5(@types/node@24.19.2)(jiti@2.7.0)(yaml@2.9.1)) + + integrations/internal-declarations-consumer: + dependencies: + '@tanstack/integration-internal-declarations': + specifier: workspace:* + version: link:../internal-declarations + devDependencies: + '@tanstack/vite-config': + specifier: workspace:* + version: link:../../packages/vite-config + typescript: + specifier: 'catalog:' + version: 6.0.2 + vite: + specifier: 'catalog:' + version: 8.3.5(@types/node@24.19.2)(jiti@2.7.0)(yaml@2.9.1) + vitest: + specifier: 'catalog:' + version: 5.0.5(@types/node@24.19.2)(jsdom@29.1.1)(vite@8.3.5(@types/node@24.19.2)(jiti@2.7.0)(yaml@2.9.1)) + integrations/react: dependencies: '@tanstack/query-core':