From fc9c3439d9d7c041fe41105ffba0caaaf8ab1202 Mon Sep 17 00:00:00 2001 From: shulaoda Date: Fri, 23 Aug 2024 16:44:19 +0800 Subject: [PATCH 1/3] chore: use type PackageJson from type-fest --- cspell.config.cjs | 1 + packages/core/src/config.ts | 6 +- packages/core/src/types/external/typeFest.ts | 680 +++++++++++++++++++ packages/core/src/types/index.ts | 2 +- packages/core/src/types/utils.ts | 6 - packages/core/src/utils/extension.ts | 4 +- packages/core/src/utils/helper.ts | 4 +- 7 files changed, 689 insertions(+), 14 deletions(-) create mode 100644 packages/core/src/types/external/typeFest.ts delete mode 100644 packages/core/src/types/utils.ts diff --git a/cspell.config.cjs b/cspell.config.cjs index f7e434766..81686c741 100644 --- a/cspell.config.cjs +++ b/cspell.config.cjs @@ -18,6 +18,7 @@ module.exports = { 'node_modules', 'pnpm-lock.yaml', ], + words: ['parseable', 'opencollective'], flagWords: banWords, dictionaries: ['dictionary'], dictionaryDefinitions: [ diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index 952165746..f5fe83ed0 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -14,7 +14,7 @@ import type { AutoExternal, Format, LibConfig, - PkgJson, + PackageJson, RslibConfig, RslibConfigAsyncFn, RslibConfigExport, @@ -89,7 +89,7 @@ export async function loadConfig({ export const composeAutoExternalConfig = (options: { autoExternal: AutoExternal; - pkgJson?: PkgJson; + pkgJson?: PackageJson; userExternals?: NonNullable['externals']; }): RsbuildConfig => { const { autoExternal, pkgJson, userExternals } = options; @@ -242,7 +242,7 @@ const composeFormatConfig = (format: Format): RsbuildConfig => { const composeAutoExtensionConfig = ( config: LibConfig, autoExtension: boolean, - pkgJson?: PkgJson, + pkgJson?: PackageJson, ): { config: RsbuildConfig; jsExtension: string; diff --git a/packages/core/src/types/external/typeFest.ts b/packages/core/src/types/external/typeFest.ts new file mode 100644 index 000000000..47aeeb7d9 --- /dev/null +++ b/packages/core/src/types/external/typeFest.ts @@ -0,0 +1,680 @@ +/** + * The following code is modified based on + * https://github.com/sindresorhus/type-fest/blob/986fab/source/package-json.d.ts + * + * MIT OR CC0-1.0 Licensed + * https://github.com/sindresorhus/type-fest/blob/main/license-cc0 + */ + +/** + * Matches a JSON object. + * + * This type can be useful to enforce some input to be JSON-compatible or as a super-type to be extended from. Don't use this as a direct return type as the user would have to double-cast it: `jsonObject as unknown as CustomResponse`. Instead, you could extend your CustomResponse type from it to ensure your type only uses JSON-compatible types: `interface CustomResponse extends JsonObject { … }`. + * + * @category JSON + */ +type JsonObject = { [Key in string]: JsonValue } & { + [Key in string]?: JsonValue | undefined; +}; + +/** + * Matches a JSON array. + * + * @category JSON + */ +type JsonArray = JsonValue[] | readonly JsonValue[]; + +/** + * Matches any valid JSON primitive value. + * + * @category JSON + */ +type JsonPrimitive = string | number | boolean | null; + +/** + * Matches any valid JSON value. + * + * @category JSON + */ +type JsonValue = JsonPrimitive | JsonObject | JsonArray; + +/** + * Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). + * + * @category Type + */ +type Primitive = null | undefined | string | number | boolean | symbol | bigint; + +/** + * Allows creating a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union. + * + * Currently, when a union type of a primitive type is combined with literal types, TypeScript loses all information about the combined literals. Thus, when such type is used in an IDE with autocompletion, no suggestions are made for the declared literals. + * + * This type is a workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729). It will be removed as soon as it's not needed anymore. + * + * @example + * ``` + * // Before + * type Pet = 'dog' | 'cat' | string; + * const pet: Pet = ''; + * // Start typing in your TypeScript-enabled IDE. + * // You **will not** get auto-completion for `dog` and `cat` literals. + * + * // After + * type Pet2 = LiteralUnion<'dog' | 'cat', string>; + * const pet: Pet2 = ''; + * // You **will** get auto-completion for `dog` and `cat` literals. + * ``` + * + * @category Type + */ +type LiteralUnion = + | LiteralType + | (BaseType & Record); + +declare namespace PackageJson { + /** + A person who has been involved in creating or maintaining the package. + */ + export type Person = + | string + | { + name: string; + url?: string; + email?: string; + }; + + export type BugsLocation = + | string + | { + /** + The URL to the package's issue tracker. + */ + url?: string; + + /** + The email address to which issues should be reported. + */ + email?: string; + }; + + export type DirectoryLocations = { + [directoryType: string]: JsonValue | undefined; + + /** + Location for executable scripts. Sugar to generate entries in the `bin` property by walking the folder. + */ + bin?: string; + + /** + Location for Markdown files. + */ + doc?: string; + + /** + Location for example scripts. + */ + example?: string; + + /** + Location for the bulk of the library. + */ + lib?: string; + + /** + Location for man pages. Sugar to generate a `man` array by walking the folder. + */ + man?: string; + + /** + Location for test files. + */ + test?: string; + }; + + export type Scripts = { + /** + Run **before** the package is published (Also run on local `npm install` without any arguments). + */ + prepublish?: string; + + /** + Run both **before** the package is packed and published, and on local `npm install` without any arguments. This is run **after** `prepublish`, but **before** `prepublishOnly`. + */ + prepare?: string; + + /** + Run **before** the package is prepared and packed, **only** on `npm publish`. + */ + prepublishOnly?: string; + + /** + Run **before** a tarball is packed (on `npm pack`, `npm publish`, and when installing git dependencies). + */ + prepack?: string; + + /** + Run **after** the package is published. + */ + publish?: string; + + /** + Run **after** the package is installed. + */ + install?: string; + + /** + Run **after** the package is installed and after `install`. + */ + postinstall?: string; + + /** + Run **before** the package is uninstalled. + */ + uninstall?: string; + + /** + Run **before** bump the package version. + */ + version?: string; + + /** + Run with the `npm test` command, before `test`. + */ + pretest?: string; + + /** + Run with the `npm test` command. + */ + test?: string; + + /** + Run with the `npm stop` command. + */ + stop?: string; + + /** + Run with the `npm start` command. + */ + start?: string; + + /** + Run with the `npm restart` command. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided. + */ + restart?: string; + } & Partial>; + + /** + Dependencies of the package. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or Git URL. + */ + export type Dependency = Partial>; + + /** + A mapping of conditions and the paths to which they resolve. + */ + type ExportConditions = { + // eslint-disable-line @typescript-eslint/consistent-indexed-object-style + [condition: string]: Exports; + }; + + /** + Entry points of a module, optionally with conditions and subpath exports. + */ + export type Exports = + | null + | string + | Array + | ExportConditions; + + /** + Import map entries of a module, optionally with conditions and subpath imports. + */ + export type Imports = { + // eslint-disable-line @typescript-eslint/consistent-indexed-object-style + [key: `#${string}`]: Exports; + }; + + // eslint-disable-next-line @typescript-eslint/consistent-type-definitions + export interface NonStandardEntryPoints { + /** + An ECMAScript module ID that is the primary entry point to the program. + */ + module?: string; + + /** + A module ID with un-transpiled code that is the primary entry point to the program. + */ + esnext?: + | string + | { + [moduleName: string]: string | undefined; + main?: string; + browser?: string; + }; + + /** + A hint to JavaScript bundlers or component tools when packaging modules for client side use. + */ + browser?: string | Partial>; + + /** + Denote which files in your project are "pure" and therefore safe for Webpack to prune if unused. + + [Read more.](https://webpack.js.org/guides/tree-shaking/) + */ + sideEffects?: boolean | string[]; + } + + export type TypeScriptConfiguration = { + /** + Location of the bundled TypeScript declaration file. + */ + types?: string; + + /** + Version selection map of TypeScript. + */ + typesVersions?: Partial>>>; + + /** + Location of the bundled TypeScript declaration file. Alias of `types`. + */ + typings?: string; + }; + + /** + An alternative configuration for workspaces. + */ + export type WorkspaceConfig = { + /** + An array of workspace pattern strings which contain the workspace packages. + */ + packages?: WorkspacePattern[]; + + /** + Designed to solve the problem of packages which break when their `node_modules` are moved to the root workspace directory - a process known as hoisting. For these packages, both within your workspace, and also some that have been installed via `node_modules`, it is important to have a mechanism for preventing the default Yarn workspace behavior. By adding workspace pattern strings here, Yarn will resume non-workspace behavior for any package which matches the defined patterns. + + [Supported](https://classic.yarnpkg.com/blog/2018/02/15/nohoist/) by Yarn. + [Not supported](https://github.com/npm/rfcs/issues/287) by npm. + */ + nohoist?: WorkspacePattern[]; + }; + + /** + A workspace pattern points to a directory or group of directories which contain packages that should be included in the workspace installation process. + + The patterns are handled with [minimatch](https://github.com/isaacs/minimatch). + + @example + `docs` → Include the docs directory and install its dependencies. + `packages/*` → Include all nested directories within the packages directory, like `packages/cli` and `packages/core`. + */ + type WorkspacePattern = string; + + export type YarnConfiguration = { + /** + If your package only allows one version of a given dependency, and you’d like to enforce the same behavior as `yarn install --flat` on the command-line, set this to `true`. + + Note that if your `package.json` contains `"flat": true` and other packages depend on yours (e.g. you are building a library rather than an app), those other packages will also need `"flat": true` in their `package.json` or be installed with `yarn install --flat` on the command-line. + */ + flat?: boolean; + + /** + Selective version resolutions. Allows the definition of custom package versions inside dependencies without manual edits in the `yarn.lock` file. + */ + resolutions?: Dependency; + }; + + export type JSPMConfiguration = { + /** + JSPM configuration. + */ + jspm?: PackageJson; + }; + + /** + Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Containing standard npm properties. + */ + // eslint-disable-next-line @typescript-eslint/consistent-type-definitions + export interface PackageJsonStandard { + /** + The name of the package. + */ + name?: string; + + /** + Package version, parseable by [`node-semver`](https://github.com/npm/node-semver). + */ + version?: string; + + /** + Package description, listed in `npm search`. + */ + description?: string; + + /** + Keywords associated with package, listed in `npm search`. + */ + keywords?: string[]; + + /** + The URL to the package's homepage. + */ + homepage?: LiteralUnion<'.', string>; + + /** + The URL to the package's issue tracker and/or the email address to which issues should be reported. + */ + bugs?: BugsLocation; + + /** + The license for the package. + */ + license?: string; + + /** + The licenses for the package. + */ + licenses?: Array<{ + type?: string; + url?: string; + }>; + + author?: Person; + + /** + A list of people who contributed to the package. + */ + contributors?: Person[]; + + /** + A list of people who maintain the package. + */ + maintainers?: Person[]; + + /** + The files included in the package. + */ + files?: string[]; + + /** + Resolution algorithm for importing ".js" files from the package's scope. + + [Read more.](https://nodejs.org/api/esm.html#esm_package_json_type_field) + */ + type?: 'module' | 'commonjs'; + + /** + The module ID that is the primary entry point to the program. + */ + main?: string; + + /** + Subpath exports to define entry points of the package. + + [Read more.](https://nodejs.org/api/packages.html#subpath-exports) + */ + exports?: Exports; + + /** + Subpath imports to define internal package import maps that only apply to import specifiers from within the package itself. + + [Read more.](https://nodejs.org/api/packages.html#subpath-imports) + */ + imports?: Imports; + + /** + The executable files that should be installed into the `PATH`. + */ + bin?: string | Partial>; + + /** + Filenames to put in place for the `man` program to find. + */ + man?: string | string[]; + + /** + Indicates the structure of the package. + */ + directories?: DirectoryLocations; + + /** + Location for the code repository. + */ + repository?: + | string + | { + type: string; + url: string; + + /** + Relative path to package.json if it is placed in non-root directory (for example if it is part of a monorepo). + + [Read more.](https://github.com/npm/rfcs/blob/latest/implemented/0010-monorepo-subdirectory-declaration.md) + */ + directory?: string; + }; + + /** + Script commands that are run at various times in the lifecycle of the package. The key is the lifecycle event, and the value is the command to run at that point. + */ + scripts?: Scripts; + + /** + Is used to set configuration parameters used in package scripts that persist across upgrades. + */ + config?: JsonObject; + + /** + The dependencies of the package. + */ + dependencies?: Dependency; + + /** + Additional tooling dependencies that are not required for the package to work. Usually test, build, or documentation tooling. + */ + devDependencies?: Dependency; + + /** + Dependencies that are skipped if they fail to install. + */ + optionalDependencies?: Dependency; + + /** + Dependencies that will usually be required by the package user directly or via another dependency. + */ + peerDependencies?: Dependency; + + /** + Indicate peer dependencies that are optional. + */ + peerDependenciesMeta?: Partial>; + + /** + Package names that are bundled when the package is published. + */ + bundledDependencies?: string[]; + + /** + Alias of `bundledDependencies`. + */ + bundleDependencies?: string[]; + + /** + Engines that this package runs on. + */ + engines?: { + [EngineName in 'npm' | 'node' | string]?: string; + }; + + /** + @deprecated + */ + engineStrict?: boolean; + + /** + Operating systems the module runs on. + */ + os?: Array< + LiteralUnion< + | 'aix' + | 'darwin' + | 'freebsd' + | 'linux' + | 'openbsd' + | 'sunos' + | 'win32' + | '!aix' + | '!darwin' + | '!freebsd' + | '!linux' + | '!openbsd' + | '!sunos' + | '!win32', + string + > + >; + + /** + CPU architectures the module runs on. + */ + cpu?: Array< + LiteralUnion< + | 'arm' + | 'arm64' + | 'ia32' + | 'mips' + | 'mipsel' + | 'ppc' + | 'ppc64' + | 's390' + | 's390x' + | 'x32' + | 'x64' + | '!arm' + | '!arm64' + | '!ia32' + | '!mips' + | '!mipsel' + | '!ppc' + | '!ppc64' + | '!s390' + | '!s390x' + | '!x32' + | '!x64', + string + > + >; + + /** + If set to `true`, a warning will be shown if package is installed locally. Useful if the package is primarily a command-line application that should be installed globally. + + @deprecated + */ + preferGlobal?: boolean; + + /** + If set to `true`, then npm will refuse to publish it. + */ + private?: boolean; + + /** + A set of config values that will be used at publish-time. It's especially handy to set the tag, registry or access, to ensure that a given package is not tagged with 'latest', published to the global public registry or that a scoped module is private by default. + */ + publishConfig?: PublishConfig; + + /** + Describes and notifies consumers of a package's monetary support information. + + [Read more.](https://github.com/npm/rfcs/blob/latest/accepted/0017-add-funding-support.md) + */ + funding?: + | string + | { + /** + The type of funding. + */ + type?: LiteralUnion< + | 'github' + | 'opencollective' + | 'patreon' + | 'individual' + | 'foundation' + | 'corporation', + string + >; + + /** + The URL to the funding page. + */ + url: string; + }; + + /** + Used to configure [npm workspaces](https://docs.npmjs.com/cli/using-npm/workspaces) / [Yarn workspaces](https://classic.yarnpkg.com/docs/workspaces/). + + Workspaces allow you to manage multiple packages within the same repository in such a way that you only need to run your install command once in order to install all of them in a single pass. + + Please note that the top-level `private` property of `package.json` **must** be set to `true` in order to use workspaces. + */ + workspaces?: WorkspacePattern[] | WorkspaceConfig; + } + + /** + Type for [`package.json` file used by the Node.js runtime](https://nodejs.org/api/packages.html#nodejs-packagejson-field-definitions). + */ + export type NodeJsStandard = { + /** + Defines which package manager is expected to be used when working on the current project. It can set to any of the [supported package managers](https://nodejs.org/api/corepack.html#supported-package-managers), and will ensure that your teams use the exact same package manager versions without having to install anything else than Node.js. + + __This field is currently experimental and needs to be opted-in; check the [Corepack](https://nodejs.org/api/corepack.html) page for details about the procedure.__ + + @example + ```json + { + "packageManager": "@" + } + ``` + */ + packageManager?: string; + }; + + export type PublishConfig = { + /** + Additional, less common properties from the [npm docs on `publishConfig`](https://docs.npmjs.com/cli/v7/configuring-npm/package-json#publishconfig). + */ + [additionalProperties: string]: JsonValue | undefined; + + /** + When publishing scoped packages, the access level defaults to restricted. If you want your scoped package to be publicly viewable (and installable) set `--access=public`. The only valid values for access are public and restricted. Unscoped packages always have an access level of public. + */ + access?: 'public' | 'restricted'; + + /** + The base URL of the npm registry. + + Default: `'https://registry.npmjs.org/'` + */ + registry?: string; + + /** + The tag to publish the package under. + + Default: `'latest'` + */ + tag?: string; + }; +} + +/** + * Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Also includes types for fields used by other popular projects, like TypeScript and Yarn. + * + * @category File + */ +export type PackageJson = JsonObject & + PackageJson.NodeJsStandard & + PackageJson.PackageJsonStandard & + PackageJson.NonStandardEntryPoints & + PackageJson.TypeScriptConfiguration & + PackageJson.YarnConfiguration & + PackageJson.JSPMConfiguration; diff --git a/packages/core/src/types/index.ts b/packages/core/src/types/index.ts index 235e5fdbc..ad28bd987 100644 --- a/packages/core/src/types/index.ts +++ b/packages/core/src/types/index.ts @@ -1,2 +1,2 @@ export type * from './config'; -export type * from './utils'; +export type * from './external/typeFest'; diff --git a/packages/core/src/types/utils.ts b/packages/core/src/types/utils.ts deleted file mode 100644 index 8b3d31293..000000000 --- a/packages/core/src/types/utils.ts +++ /dev/null @@ -1,6 +0,0 @@ -export type PkgJson = { - dependencies?: Record; - peerDependencies?: Record; - devDependencies?: Record; - [key: string]: unknown; -}; diff --git a/packages/core/src/utils/extension.ts b/packages/core/src/utils/extension.ts index 7d514a9e9..681865436 100644 --- a/packages/core/src/utils/extension.ts +++ b/packages/core/src/utils/extension.ts @@ -1,9 +1,9 @@ -import type { Format, PkgJson } from '../types'; +import type { Format, PackageJson } from '../types'; import { logger } from './logger'; export const getDefaultExtension = (options: { format: Format; - pkgJson?: PkgJson; + pkgJson?: PackageJson; autoExtension: boolean; }): { jsExtension: string; diff --git a/packages/core/src/utils/helper.ts b/packages/core/src/utils/helper.ts index 387e20123..fca21645e 100644 --- a/packages/core/src/utils/helper.ts +++ b/packages/core/src/utils/helper.ts @@ -2,7 +2,7 @@ import fs from 'node:fs'; import fsP from 'node:fs/promises'; import path from 'node:path'; import color from 'picocolors'; -import type { PkgJson } from '../types'; +import type { PackageJson } from '../types'; import { logger } from './logger'; /** @@ -107,7 +107,7 @@ export async function calcLongestCommonPath( return lca; } -export const readPackageJson = (rootPath: string): undefined | PkgJson => { +export const readPackageJson = (rootPath: string): undefined | PackageJson => { const pkgJsonPath = path.join(rootPath, './package.json'); if (!fs.existsSync(pkgJsonPath)) { From 60e60fe1c4e133d497b87ec88fd13ebc4c9d8272 Mon Sep 17 00:00:00 2001 From: shulaoda Date: Fri, 23 Aug 2024 17:23:39 +0800 Subject: [PATCH 2/3] chore: follow the suggestion --- packages/core/src/types/external/typeFest.ts | 617 +++---------------- 1 file changed, 88 insertions(+), 529 deletions(-) diff --git a/packages/core/src/types/external/typeFest.ts b/packages/core/src/types/external/typeFest.ts index 47aeeb7d9..f1b2acb5c 100644 --- a/packages/core/src/types/external/typeFest.ts +++ b/packages/core/src/types/external/typeFest.ts @@ -38,633 +38,196 @@ type JsonPrimitive = string | number | boolean | null; */ type JsonValue = JsonPrimitive | JsonObject | JsonArray; +type Scripts = Partial>; + +type Dependency = Partial>; + /** - * Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). - * - * @category Type + * A mapping of conditions and the paths to which they resolve. */ -type Primitive = null | undefined | string | number | boolean | symbol | bigint; +type ExportConditions = { + // eslint-disable-line @typescript-eslint/consistent-indexed-object-style + [condition: string]: Exports; +}; /** - * Allows creating a union type by combining primitive types and literal types without sacrificing auto-completion in IDEs for the literal type part of the union. - * - * Currently, when a union type of a primitive type is combined with literal types, TypeScript loses all information about the combined literals. Thus, when such type is used in an IDE with autocompletion, no suggestions are made for the declared literals. - * - * This type is a workaround for [Microsoft/TypeScript#29729](https://github.com/Microsoft/TypeScript/issues/29729). It will be removed as soon as it's not needed anymore. - * - * @example - * ``` - * // Before - * type Pet = 'dog' | 'cat' | string; - * const pet: Pet = ''; - * // Start typing in your TypeScript-enabled IDE. - * // You **will not** get auto-completion for `dog` and `cat` literals. - * - * // After - * type Pet2 = LiteralUnion<'dog' | 'cat', string>; - * const pet: Pet2 = ''; - * // You **will** get auto-completion for `dog` and `cat` literals. - * ``` - * - * @category Type + * Entry points of a module, optionally with conditions and subpath exports. */ -type LiteralUnion = - | LiteralType - | (BaseType & Record); - -declare namespace PackageJson { - /** - A person who has been involved in creating or maintaining the package. - */ - export type Person = - | string - | { - name: string; - url?: string; - email?: string; - }; - - export type BugsLocation = - | string - | { - /** - The URL to the package's issue tracker. - */ - url?: string; - - /** - The email address to which issues should be reported. - */ - email?: string; - }; - - export type DirectoryLocations = { - [directoryType: string]: JsonValue | undefined; - - /** - Location for executable scripts. Sugar to generate entries in the `bin` property by walking the folder. - */ - bin?: string; - - /** - Location for Markdown files. - */ - doc?: string; - - /** - Location for example scripts. - */ - example?: string; - - /** - Location for the bulk of the library. - */ - lib?: string; - - /** - Location for man pages. Sugar to generate a `man` array by walking the folder. - */ - man?: string; - - /** - Location for test files. - */ - test?: string; - }; - - export type Scripts = { - /** - Run **before** the package is published (Also run on local `npm install` without any arguments). - */ - prepublish?: string; - - /** - Run both **before** the package is packed and published, and on local `npm install` without any arguments. This is run **after** `prepublish`, but **before** `prepublishOnly`. - */ - prepare?: string; - - /** - Run **before** the package is prepared and packed, **only** on `npm publish`. - */ - prepublishOnly?: string; - - /** - Run **before** a tarball is packed (on `npm pack`, `npm publish`, and when installing git dependencies). - */ - prepack?: string; - - /** - Run **after** the package is published. - */ - publish?: string; - - /** - Run **after** the package is installed. - */ - install?: string; - - /** - Run **after** the package is installed and after `install`. - */ - postinstall?: string; - - /** - Run **before** the package is uninstalled. - */ - uninstall?: string; - - /** - Run **before** bump the package version. - */ - version?: string; - - /** - Run with the `npm test` command, before `test`. - */ - pretest?: string; - - /** - Run with the `npm test` command. - */ - test?: string; - - /** - Run with the `npm stop` command. - */ - stop?: string; - - /** - Run with the `npm start` command. - */ - start?: string; - - /** - Run with the `npm restart` command. Note: `npm restart` will run the `stop` and `start` scripts if no `restart` script is provided. - */ - restart?: string; - } & Partial>; - - /** - Dependencies of the package. The version range is a string which has one or more space-separated descriptors. Dependencies can also be identified with a tarball or Git URL. - */ - export type Dependency = Partial>; - - /** - A mapping of conditions and the paths to which they resolve. - */ - type ExportConditions = { - // eslint-disable-line @typescript-eslint/consistent-indexed-object-style - [condition: string]: Exports; - }; +type Exports = + | null + | string + | Array + | ExportConditions; - /** - Entry points of a module, optionally with conditions and subpath exports. - */ - export type Exports = - | null - | string - | Array - | ExportConditions; +/** + * Import map entries of a module, optionally with conditions and subpath imports. + */ +type Imports = { + [key: `#${string}`]: Exports; +}; +interface NonStandardEntryPoints { /** - Import map entries of a module, optionally with conditions and subpath imports. - */ - export type Imports = { - // eslint-disable-line @typescript-eslint/consistent-indexed-object-style - [key: `#${string}`]: Exports; - }; - - // eslint-disable-next-line @typescript-eslint/consistent-type-definitions - export interface NonStandardEntryPoints { - /** An ECMAScript module ID that is the primary entry point to the program. */ - module?: string; - - /** - A module ID with un-transpiled code that is the primary entry point to the program. - */ - esnext?: - | string - | { - [moduleName: string]: string | undefined; - main?: string; - browser?: string; - }; - - /** - A hint to JavaScript bundlers or component tools when packaging modules for client side use. - */ - browser?: string | Partial>; + module?: string; - /** + /** Denote which files in your project are "pure" and therefore safe for Webpack to prune if unused. [Read more.](https://webpack.js.org/guides/tree-shaking/) */ - sideEffects?: boolean | string[]; - } - - export type TypeScriptConfiguration = { - /** - Location of the bundled TypeScript declaration file. - */ - types?: string; - - /** - Version selection map of TypeScript. - */ - typesVersions?: Partial>>>; - - /** - Location of the bundled TypeScript declaration file. Alias of `types`. - */ - typings?: string; - }; - - /** - An alternative configuration for workspaces. - */ - export type WorkspaceConfig = { - /** - An array of workspace pattern strings which contain the workspace packages. - */ - packages?: WorkspacePattern[]; - - /** - Designed to solve the problem of packages which break when their `node_modules` are moved to the root workspace directory - a process known as hoisting. For these packages, both within your workspace, and also some that have been installed via `node_modules`, it is important to have a mechanism for preventing the default Yarn workspace behavior. By adding workspace pattern strings here, Yarn will resume non-workspace behavior for any package which matches the defined patterns. - - [Supported](https://classic.yarnpkg.com/blog/2018/02/15/nohoist/) by Yarn. - [Not supported](https://github.com/npm/rfcs/issues/287) by npm. - */ - nohoist?: WorkspacePattern[]; - }; - - /** - A workspace pattern points to a directory or group of directories which contain packages that should be included in the workspace installation process. - - The patterns are handled with [minimatch](https://github.com/isaacs/minimatch). - - @example - `docs` → Include the docs directory and install its dependencies. - `packages/*` → Include all nested directories within the packages directory, like `packages/cli` and `packages/core`. - */ - type WorkspacePattern = string; - - export type YarnConfiguration = { - /** - If your package only allows one version of a given dependency, and you’d like to enforce the same behavior as `yarn install --flat` on the command-line, set this to `true`. - - Note that if your `package.json` contains `"flat": true` and other packages depend on yours (e.g. you are building a library rather than an app), those other packages will also need `"flat": true` in their `package.json` or be installed with `yarn install --flat` on the command-line. - */ - flat?: boolean; - - /** - Selective version resolutions. Allows the definition of custom package versions inside dependencies without manual edits in the `yarn.lock` file. - */ - resolutions?: Dependency; - }; - - export type JSPMConfiguration = { - /** - JSPM configuration. - */ - jspm?: PackageJson; - }; + sideEffects?: boolean | string[]; +} +/** + * Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Containing standard npm properties. + */ +interface PackageJsonStandard { /** - Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Containing standard npm properties. - */ - // eslint-disable-next-line @typescript-eslint/consistent-type-definitions - export interface PackageJsonStandard { - /** The name of the package. */ - name?: string; + name?: string; - /** + /** Package version, parseable by [`node-semver`](https://github.com/npm/node-semver). */ - version?: string; + version?: string; - /** + /** Package description, listed in `npm search`. */ - description?: string; + description?: string; - /** + /** Keywords associated with package, listed in `npm search`. */ - keywords?: string[]; - - /** - The URL to the package's homepage. - */ - homepage?: LiteralUnion<'.', string>; - - /** - The URL to the package's issue tracker and/or the email address to which issues should be reported. - */ - bugs?: BugsLocation; - - /** - The license for the package. - */ - license?: string; + keywords?: string[]; - /** + /** The licenses for the package. */ - licenses?: Array<{ - type?: string; - url?: string; - }>; - - author?: Person; - - /** - A list of people who contributed to the package. - */ - contributors?: Person[]; - - /** - A list of people who maintain the package. - */ - maintainers?: Person[]; + licenses?: Array<{ + type?: string; + url?: string; + }>; - /** + /** The files included in the package. */ - files?: string[]; + files?: string[]; - /** + /** Resolution algorithm for importing ".js" files from the package's scope. [Read more.](https://nodejs.org/api/esm.html#esm_package_json_type_field) */ - type?: 'module' | 'commonjs'; + type?: 'module' | 'commonjs'; - /** + /** The module ID that is the primary entry point to the program. */ - main?: string; + main?: string; - /** + /** Subpath exports to define entry points of the package. [Read more.](https://nodejs.org/api/packages.html#subpath-exports) */ - exports?: Exports; + exports?: Exports; - /** + /** Subpath imports to define internal package import maps that only apply to import specifiers from within the package itself. [Read more.](https://nodejs.org/api/packages.html#subpath-imports) */ - imports?: Imports; + imports?: Imports; - /** + /** The executable files that should be installed into the `PATH`. */ - bin?: string | Partial>; - - /** - Filenames to put in place for the `man` program to find. - */ - man?: string | string[]; - - /** - Indicates the structure of the package. - */ - directories?: DirectoryLocations; - - /** - Location for the code repository. - */ - repository?: - | string - | { - type: string; - url: string; - - /** - Relative path to package.json if it is placed in non-root directory (for example if it is part of a monorepo). - - [Read more.](https://github.com/npm/rfcs/blob/latest/implemented/0010-monorepo-subdirectory-declaration.md) - */ - directory?: string; - }; + bin?: string | Partial>; - /** + /** Script commands that are run at various times in the lifecycle of the package. The key is the lifecycle event, and the value is the command to run at that point. */ - scripts?: Scripts; + scripts?: Scripts; - /** + /** Is used to set configuration parameters used in package scripts that persist across upgrades. */ - config?: JsonObject; + config?: JsonObject; - /** + /** The dependencies of the package. */ - dependencies?: Dependency; + dependencies?: Dependency; - /** + /** Additional tooling dependencies that are not required for the package to work. Usually test, build, or documentation tooling. */ - devDependencies?: Dependency; - - /** - Dependencies that are skipped if they fail to install. - */ - optionalDependencies?: Dependency; + devDependencies?: Dependency; - /** + /** Dependencies that will usually be required by the package user directly or via another dependency. */ - peerDependencies?: Dependency; - - /** - Indicate peer dependencies that are optional. - */ - peerDependenciesMeta?: Partial>; - - /** - Package names that are bundled when the package is published. - */ - bundledDependencies?: string[]; - - /** - Alias of `bundledDependencies`. - */ - bundleDependencies?: string[]; + peerDependencies?: Dependency; - /** + /** Engines that this package runs on. */ - engines?: { - [EngineName in 'npm' | 'node' | string]?: string; - }; + engines?: { + [EngineName in 'npm' | 'node' | string]?: string; + }; - /** + /** @deprecated */ - engineStrict?: boolean; + engineStrict?: boolean; - /** - Operating systems the module runs on. - */ - os?: Array< - LiteralUnion< - | 'aix' - | 'darwin' - | 'freebsd' - | 'linux' - | 'openbsd' - | 'sunos' - | 'win32' - | '!aix' - | '!darwin' - | '!freebsd' - | '!linux' - | '!openbsd' - | '!sunos' - | '!win32', - string - > - >; - - /** - CPU architectures the module runs on. - */ - cpu?: Array< - LiteralUnion< - | 'arm' - | 'arm64' - | 'ia32' - | 'mips' - | 'mipsel' - | 'ppc' - | 'ppc64' - | 's390' - | 's390x' - | 'x32' - | 'x64' - | '!arm' - | '!arm64' - | '!ia32' - | '!mips' - | '!mipsel' - | '!ppc' - | '!ppc64' - | '!s390' - | '!s390x' - | '!x32' - | '!x64', - string - > - >; - - /** + /** If set to `true`, a warning will be shown if package is installed locally. Useful if the package is primarily a command-line application that should be installed globally. @deprecated */ - preferGlobal?: boolean; + preferGlobal?: boolean; - /** + /** If set to `true`, then npm will refuse to publish it. */ - private?: boolean; + private?: boolean; - /** + /** A set of config values that will be used at publish-time. It's especially handy to set the tag, registry or access, to ensure that a given package is not tagged with 'latest', published to the global public registry or that a scoped module is private by default. */ - publishConfig?: PublishConfig; - - /** - Describes and notifies consumers of a package's monetary support information. - - [Read more.](https://github.com/npm/rfcs/blob/latest/accepted/0017-add-funding-support.md) - */ - funding?: - | string - | { - /** - The type of funding. - */ - type?: LiteralUnion< - | 'github' - | 'opencollective' - | 'patreon' - | 'individual' - | 'foundation' - | 'corporation', - string - >; - - /** - The URL to the funding page. - */ - url: string; - }; - - /** - Used to configure [npm workspaces](https://docs.npmjs.com/cli/using-npm/workspaces) / [Yarn workspaces](https://classic.yarnpkg.com/docs/workspaces/). - - Workspaces allow you to manage multiple packages within the same repository in such a way that you only need to run your install command once in order to install all of them in a single pass. - - Please note that the top-level `private` property of `package.json` **must** be set to `true` in order to use workspaces. - */ - workspaces?: WorkspacePattern[] | WorkspaceConfig; - } + publishConfig?: PublishConfig; +} +type PublishConfig = { /** - Type for [`package.json` file used by the Node.js runtime](https://nodejs.org/api/packages.html#nodejs-packagejson-field-definitions). - */ - export type NodeJsStandard = { - /** - Defines which package manager is expected to be used when working on the current project. It can set to any of the [supported package managers](https://nodejs.org/api/corepack.html#supported-package-managers), and will ensure that your teams use the exact same package manager versions without having to install anything else than Node.js. - - __This field is currently experimental and needs to be opted-in; check the [Corepack](https://nodejs.org/api/corepack.html) page for details about the procedure.__ - - @example - ```json - { - "packageManager": "@" - } - ``` - */ - packageManager?: string; - }; - - export type PublishConfig = { - /** Additional, less common properties from the [npm docs on `publishConfig`](https://docs.npmjs.com/cli/v7/configuring-npm/package-json#publishconfig). */ - [additionalProperties: string]: JsonValue | undefined; + [additionalProperties: string]: JsonValue | undefined; - /** + /** When publishing scoped packages, the access level defaults to restricted. If you want your scoped package to be publicly viewable (and installable) set `--access=public`. The only valid values for access are public and restricted. Unscoped packages always have an access level of public. */ - access?: 'public' | 'restricted'; + access?: 'public' | 'restricted'; - /** + /** The base URL of the npm registry. Default: `'https://registry.npmjs.org/'` */ - registry?: string; + registry?: string; - /** + /** The tag to publish the package under. Default: `'latest'` */ - tag?: string; - }; -} + tag?: string; +}; /** * Type for [npm's `package.json` file](https://docs.npmjs.com/creating-a-package-json-file). Also includes types for fields used by other popular projects, like TypeScript and Yarn. @@ -672,9 +235,5 @@ declare namespace PackageJson { * @category File */ export type PackageJson = JsonObject & - PackageJson.NodeJsStandard & - PackageJson.PackageJsonStandard & - PackageJson.NonStandardEntryPoints & - PackageJson.TypeScriptConfiguration & - PackageJson.YarnConfiguration & - PackageJson.JSPMConfiguration; + PackageJsonStandard & + NonStandardEntryPoints; From 8cac7c0949e264d480bc70cd0ff5941250ab27df Mon Sep 17 00:00:00 2001 From: shulaoda Date: Sat, 24 Aug 2024 13:04:26 +0800 Subject: [PATCH 3/3] save --- examples/zero-configuration/README.md | 3 ++ examples/zero-configuration/package.json | 12 ++++++ examples/zero-configuration/src/index.ts | 1 + examples/zero-configuration/tsconfig.json | 6 +++ packages/core/src/config.ts | 29 +++++++++---- packages/core/src/types/config/index.ts | 8 ++++ packages/core/src/utils/helper.ts | 52 ++++++++++++++++++++++- pnpm-lock.yaml | 11 +++++ 8 files changed, 113 insertions(+), 9 deletions(-) create mode 100644 examples/zero-configuration/README.md create mode 100644 examples/zero-configuration/package.json create mode 100644 examples/zero-configuration/src/index.ts create mode 100644 examples/zero-configuration/tsconfig.json diff --git a/examples/zero-configuration/README.md b/examples/zero-configuration/README.md new file mode 100644 index 000000000..84f898498 --- /dev/null +++ b/examples/zero-configuration/README.md @@ -0,0 +1,3 @@ +# @examples/zero-configuration + +This example demonstrates how to use Rslib's zero configuration feature. diff --git a/examples/zero-configuration/package.json b/examples/zero-configuration/package.json new file mode 100644 index 000000000..46a66ba7f --- /dev/null +++ b/examples/zero-configuration/package.json @@ -0,0 +1,12 @@ +{ + "name": "@examples/zero-configuration", + "private": true, + "scripts": { + "build": "rslib build" + }, + "dependencies": {}, + "devDependencies": { + "@rslib/core": "workspace:*", + "typescript": "^5.5.4" + } +} diff --git a/examples/zero-configuration/src/index.ts b/examples/zero-configuration/src/index.ts new file mode 100644 index 000000000..97eb0c911 --- /dev/null +++ b/examples/zero-configuration/src/index.ts @@ -0,0 +1 @@ +console.log(123); diff --git a/examples/zero-configuration/tsconfig.json b/examples/zero-configuration/tsconfig.json new file mode 100644 index 000000000..d38eab65e --- /dev/null +++ b/examples/zero-configuration/tsconfig.json @@ -0,0 +1,6 @@ +{ + "compilerOptions": { + "strict": true + }, + "include": ["src/**/*"] +} diff --git a/packages/core/src/config.ts b/packages/core/src/config.ts index f5fe83ed0..a61fef8b4 100644 --- a/packages/core/src/config.ts +++ b/packages/core/src/config.ts @@ -25,6 +25,7 @@ import { getDefaultExtension } from './utils/extension'; import { calcLongestCommonPath, color, + getExportEntries, isObject, nodeBuiltInModules, readPackageJson, @@ -48,7 +49,10 @@ const findConfig = (basePath: string): string | undefined => { return DEFAULT_EXTENSIONS.map((ext) => basePath + ext).find(fs.existsSync); }; -const resolveConfigPath = (root: string, customConfig?: string): string => { +const resolveConfigPath = ( + root: string, + customConfig?: string, +): string | null => { if (customConfig) { const customConfigPath = isAbsolute(customConfig) ? customConfig @@ -65,7 +69,7 @@ const resolveConfigPath = (root: string, customConfig?: string): string => { return configFilePath; } - throw new Error(`${DEFAULT_CONFIG_NAME} not found in ${root}`); + return null; }; export async function loadConfig({ @@ -78,13 +82,22 @@ export async function loadConfig({ envMode?: string; }): Promise { const configFilePath = resolveConfigPath(cwd, path); - const { content } = await loadRsbuildConfig({ - cwd: dirname(configFilePath), - path: configFilePath, - envMode, - }); + if (configFilePath) { + const { content } = await loadRsbuildConfig({ + cwd: dirname(configFilePath), + path: configFilePath, + envMode, + }); + + return content as RslibConfig; + } + + const pkgJson = readPackageJson(cwd); + if (pkgJson) { + const exportEntries = getExportEntries(pkgJson); + } - return content as RslibConfig; + return {} as RslibConfig; } export const composeAutoExternalConfig = (options: { diff --git a/packages/core/src/types/config/index.ts b/packages/core/src/types/config/index.ts index df08a54f6..113269638 100644 --- a/packages/core/src/types/config/index.ts +++ b/packages/core/src/types/config/index.ts @@ -2,6 +2,14 @@ import type { RsbuildConfig } from '@rsbuild/core'; export type Format = 'esm' | 'cjs' | 'umd'; +export type PackageType = 'module' | 'commonjs'; + +export type ExportEntry = { + outputPath: string; + type: PackageType | 'types'; + from: string; +}; + export type EcmaScriptVersion = | 'esnext' | 'es5' diff --git a/packages/core/src/utils/helper.ts b/packages/core/src/utils/helper.ts index fca21645e..9bc787625 100644 --- a/packages/core/src/utils/helper.ts +++ b/packages/core/src/utils/helper.ts @@ -2,7 +2,7 @@ import fs from 'node:fs'; import fsP from 'node:fs/promises'; import path from 'node:path'; import color from 'picocolors'; -import type { PackageJson } from '../types'; +import type { ExportEntry, PackageJson, PackageType } from '../types'; import { logger } from './logger'; /** @@ -123,6 +123,56 @@ export const readPackageJson = (rootPath: string): undefined | PackageJson => { } }; +export const getExportEntries = (pkgJson: PackageJson): ExportEntry[] => { + const exportEntriesMap: Record = {}; + const packageType = pkgJson.type ?? 'commonjs'; + + const getFileType = (filePath: string): PackageType => { + if (filePath.endsWith('.mjs')) { + return 'module'; + } + + if (filePath.endsWith('.cjs')) { + return 'commonjs'; + } + + return packageType; + }; + + const addExportPath = ( + exportPathsMap: Record, + exportEntry: any, + ) => { + exportEntry.outputPath = path.normalize(exportEntry.outputPath); + + const { outputPath: exportPath, type } = exportEntry; + + const existingExportPath = exportPathsMap[exportPath]; + if (existingExportPath) { + if (existingExportPath.type !== type) { + throw new Error( + `Conflicting export types "${existingExportPath.type}" & "${type}" found for ${exportPath}`, + ); + } + + Object.assign(existingExportPath, exportEntry); + } else { + exportPathsMap[exportPath] = exportEntry; + } + }; + + if (pkgJson.main) { + const mainPath = pkgJson.main; + addExportPath(exportEntriesMap, { + outputPath: mainPath, + type: getFileType(mainPath), + from: 'main', + }); + } + + return Object.values(exportEntriesMap); +}; + export const isObject = (obj: unknown): obj is Record => Object.prototype.toString.call(obj) === '[object Object]'; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 916a50b2b..cbecf7421 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -145,6 +145,8 @@ importers: e2e/cases/dts/bundle/abort-on-error: {} + e2e/cases/dts/bundle/absolute-entry: {} + e2e/cases/dts/bundle/auto-extension: {} e2e/cases/dts/bundle/basic: {} @@ -187,6 +189,15 @@ importers: specifier: ^18.3.1 version: 18.3.1 + examples/zero-configuration: + devDependencies: + '@rslib/core': + specifier: workspace:* + version: link:../../packages/core + typescript: + specifier: ^5.5.4 + version: 5.5.4 + packages/core: dependencies: '@microsoft/api-extractor':