siroc
Version:
Zero-config build tooling for Node
391 lines (381 loc) • 15.8 kB
TypeScript
import { Consola } from 'consola';
import execa from 'execa';
import { MkdistOptions } from 'mkdist';
import { RollupOptions, OutputOptions, RollupBuild } from 'rollup';
import { Replacement } from '@rollup/plugin-replace';
import { RollupNodeResolveOptions } from '@rollup/plugin-node-resolve';
import { Options } from 'rollup-plugin-esbuild';
declare const glob: (pattern: string) => Promise<string[]>;
declare const sortObjectKeys: <T>(obj: Record<string, T>) => {
[k: string]: T;
};
declare const tryJSON: <T = unknown>(id: string) => T | undefined;
declare const tryRequire: <T = unknown>(id: string) => unknown;
declare type RequireProperties<T, R extends keyof T> = Omit<T, R> & Required<Pick<T, R>>;
declare const ensureUnique: <T>(items: T[]) => T[];
declare const groupBy: <T extends Record<string, any>, K extends keyof T>(collection: T[], key: K) => Record<T[K], T[]>;
declare type ExcludeNullable<T extends Record<string, any>> = {
[P in keyof T]: NonNullable<T[P]>;
};
declare const includeDefinedProperties: <T extends Record<string, any>>(options: T) => ExcludeNullable<T>;
declare type NonFalsy<T> = T extends null | undefined | false ? never : T;
declare const includeIf: <T, I>(test: T, itemFactory: (outcome: NonFalsy<T>) => I) => I[];
declare const runInParallel: <T, R extends unknown>(items: Iterable<T>, cb: (item: T, index: number) => R | Promise<R>) => Promise<PromiseSettledResult<R>[]>;
declare const asArray: <T>(item: T | T[] | undefined) => T[];
/**
* A “person” is an object with a “name” field and optionally “url” and “email”. Or you can shorten that all into a single string, and npm will parse it for you.
*/
declare type PackageJsonPerson = string | {
name: string;
email?: string;
url?: string;
};
interface Repository {
type: string;
url: string;
/**
* If the `package.json` for your package is not in the root directory (for example if it is part of a monorepo), you can specify the directory in which it lives:
*/
directory?: string;
}
interface PackageJson {
/**
* The name is what your thing is called.
* Some rules:
- The name must be less than or equal to 214 characters. This includes the scope for scoped packages.
- The name can’t start with a dot or an underscore.
- New packages must not have uppercase letters in the name.
- The name ends up being part of a URL, an argument on the command line, and a folder name. Therefore, the name can’t contain any non-URL-safe characters.
*/
name?: string;
/**
* Version must be parseable by `node-semver`, which is bundled with npm as a dependency. (`npm install semver` to use it yourself.)
*/
version?: string;
/**
* Put a description in it. It’s a string. This helps people discover your package, as it’s listed in `npm search`.
*/
description?: string;
/**
* Put keywords in it. It’s an array of strings. This helps people discover your package as it’s listed in `npm search`.
*/
keywords?: string[];
/**
* The url to the project homepage.
*/
homepage?: string;
/**
* The url to your project’s issue tracker and / or the email address to which issues should be reported. These are helpful for people who encounter issues with your package.
*/
bugs?: string | {
url?: string;
email?: string;
};
/**
* You should specify a license for your package so that people know how they are permitted to use it, and any restrictions you’re placing on it.
*/
licence?: string;
/**
* Specify the place where your code lives. This is helpful for people who want to contribute. If the git repo is on GitHub, then the `npm docs` command will be able to find you.
* For GitHub, GitHub gist, Bitbucket, or GitLab repositories you can use the same shortcut syntax you use for npm install:
*/
repository?: string | Repository;
/**
* If you set `"private": true` in your package.json, then npm will refuse to publish it.
*/
private?: boolean;
/**
* The “author” is one person.
*/
author?: PackageJsonPerson;
/**
* “contributors” is an array of people.
*/
contributors?: PackageJsonPerson[];
/**
* The optional `files` field is an array of file patterns that describes the entries to be included when your package is installed as a dependency. File patterns follow a similar syntax to `.gitignore`, but reversed: including a file, directory, or glob pattern (`*`, `**\/*`, and such) will make it so that file is included in the tarball when it’s packed. Omitting the field will make it default to `["*"]`, which means it will include all files.
*/
files?: string[];
/**
* The main field is a module ID that is the primary entry point to your program. That is, if your package is named `foo`, and a user installs it, and then does `require("foo")`, then your main module’s exports object will be returned.
* This should be a module ID relative to the root of your package folder.
* For most modules, it makes the most sense to have a main script and often not much else.
*/
main?: string;
/**
* If your module is meant to be used client-side the browser field should be used instead of the main field. This is helpful to hint users that it might rely on primitives that aren’t available in Node.js modules. (e.g. window)
*/
browser?: string;
/**
* A map of command name to local file name. On install, npm will symlink that file into `prefix/bin` for global installs, or `./node_modules/.bin/` for local installs.
*/
bin?: string | Record<string, string>;
/**
* Specify either a single file or an array of filenames to put in place for the `man` program to find.
*/
man?: string | string[];
/**
* Dependencies are specified in a simple object that maps a package name to a version range. 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.
*/
dependencies?: Record<string, string>;
/**
* If someone is planning on downloading and using your module in their program, then they probably don’t want or need to download and build the external test or documentation framework that you use.
* In this case, it’s best to map these additional items in a `devDependencies` object.
*/
devDependencies?: Record<string, string>;
/**
* If a dependency can be used, but you would like npm to proceed if it cannot be found or fails to install, then you may put it in the `optionalDependencies` object. This is a map of package name to version or url, just like the `dependencies` object. The difference is that build failures do not cause installation to fail.
*/
optionalDependencies?: Record<string, string>;
/**
* In some cases, you want to express the compatibility of your package with a host tool or library, while not necessarily doing a `require` of this host. This is usually referred to as a plugin. Notably, your module may be exposing a specific interface, expected and specified by the host documentation.
*/
peerDependencies?: Record<string, string>;
/**
* TypeScript typings, typically ending by .d.ts
*/
types?: string;
typings?: string;
/**
* Non-Standard Node.js alternate entry-point to main.
* An initial implementation for supporting CJS packages (from main), and use module for ESM modules.
*/
module?: string;
/**
* Make main entry-point be loaded as an ESM module, support "export" syntax instead of "require"
*
* Docs:
* - https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_package_json_type_field
*
* @default 'commonjs'
* @since Node.js v14
*/
type?: 'module' | 'commonjs';
/**
* Alternate and extensible alternative to "main" entry point.
*
* When using `{type: "module"}`, any ESM module file MUST end with `.mjs` extension.
*
* Docs:
* - https://nodejs.org/docs/latest-v14.x/api/esm.html#esm_exports_sugar
*
* @default 'commonjs'
* @since Node.js v14
*/
exports?: string | Record<'import' | 'require' | '.' | 'node' | 'browser' | string, string | Record<'import' | 'require' | string, string>>;
workspaces?: string[];
}
interface DefaultPackageOptions {
/**
* The root directory of the package
* @default process.cwd()
*/
rootDir: string;
/**
* Whether to build this package when `siroc build` is run.
* @default true
*/
build: boolean;
/**
* An extra suffix to append to built-package names
* @default ''
*/
suffix: string;
/**
* `siroc` provides a number of hooks to modify customisation of the build process
*/
hooks: PackageHooks;
/**
* `siroc` allows adding custom commands.
*/
commands: PackageCommands;
/**
* Packages that depend on other monorepo packages.
*/
linkedDependencies?: string[];
/**
* If you want to specify `package.json` contents inline (e.g. `require('./another/package.json')`).
* By default siroc will read the `package.json` in the current directory.
*/
pkg?: PackageJson;
/**
* Any additional rollup options.
*/
rollup?: BuildConfigOptions & RollupOptions;
/**
* Any options to pass to mkdist.
*/
mkdist?: Omit<MkdistOptions, 'rootDir' | 'srcDir' | 'distDir'>;
/**
* Whether to sort your `package.json` on build
*/
sortDependencies?: boolean;
/**
* The indent to use when writing `package.json`
* @default ` `
*/
pkgIndent?: string;
}
declare type SirocOptions = Partial<DefaultPackageOptions>;
/**
* @deprecated
*/
declare type PackageOptions = SirocOptions;
declare const defineSirocConfig: (options: SirocOptions) => Partial<DefaultPackageOptions>;
interface BuildOptions {
dev?: boolean;
watch?: boolean;
shouldWatch?: boolean;
override?: BuildOverride;
}
declare class Package {
options: DefaultPackageOptions;
logger: Consola;
pkg: RequireProperties<PackageJson, 'name' | 'version'>;
constructor(options?: SirocOptions);
loadPackageJSON(): this['pkg'];
loadPackageJSON(parse: false): string;
/**
* Resolve path relative to this package
*/
resolvePath(...pathSegments: string[]): string;
/**
* Load options from the `siroc.config.js` in the package directory
*/
loadConfig(): void;
/**
* Call hooks defined in config file
*/
callHook<H extends keyof PackageHookOptions>(name: H, options: PackageHookOptions[H]): Promise<void>;
/**
* Return a new package in a directory relative to the current package
*/
load(relativePath: string, opts?: SirocOptions): Package;
/**
* Write updated `package.json`
*/
writePackage(): Promise<void>;
/**
* A version string unique to the current git commit and date
*/
get version(): string;
/**
* Add suffix to all dependencies and set new version
*/
suffixAndVersion(): void;
/**
* Synchronise version across all packages in monorepo
*/
syncLinkedDependencies(): void;
publish(tag?: string): void;
/**
* Synchronise fields from another package to this package
*/
copyFieldsFrom(source: Package, fields?: Array<keyof PackageJson>): void;
setBinaryPermissions(): Promise<void>;
createBinaryStubs(): Promise<void>;
createStub(path: string | undefined, cjs?: boolean): Promise<void>;
createStubs(): Promise<[void, void, void, void]>;
/**
* Copy files from another package's directory
*/
copyFilesFrom(source: Package, files: string[]): Promise<void>;
/**
* Sort `package.json` and sort package dependencies alphabetically (if enabled in options)
*/
autoFix(): void;
/**
* Sort package depndencies alphabetically by object key
*/
sortDependencies(): void;
execInteractive(command: string): execa.ExecaChildProcess<string>;
get exports(): string[];
get folderExports(): string[];
/**
* Execute command in the package root directory
*/
exec(command: string, { silent }?: {
silent?: boolean | undefined;
}): {
signal: string | undefined;
stdout: string;
stderr: string;
};
resolveEntrypoint(path?: string | undefined): string | undefined;
resolveEntrypointFolder(path?: string | undefined): string | undefined;
parsePerson(person: string): {
name: string;
email: string;
url: string;
};
get contributors(): {
name: string;
email?: string | undefined;
url?: string | undefined;
}[];
/**
* The main package entrypoint (source)
*/
get entrypoint(): string | undefined;
/**
* An array of built package binary paths and their entrypoints
* @returns an array of tuples of the binary and its corresponding entrypoint
*/
get binaries(): [string, string | undefined][];
/**
* Return the child packages of this workspace (or, if there are no workspaces specified, just this package)
* @param packageNames If package names are provided, these will serve to limit the packages that are returned
*/
getWorkspacePackages(packageNames?: string[]): Promise<Package[]>;
get shortCommit(): string;
get branch(): string;
get lastGitTag(): string;
}
interface BuildConfigOptions extends RollupOptions {
rootDir?: string;
replace?: Record<string, Replacement>;
alias?: {
[find: string]: string;
};
dev?: boolean;
/**
* Explicit externals
*/
externals?: (string | RegExp)[];
resolve?: RollupNodeResolveOptions;
input?: string;
esbuildOptions?: Options;
}
interface BuildOverride {
input: string;
output: string;
format: OutputOptions['format'];
}
declare function regexpForPackage(name: string): RegExp;
declare function getRollupConfig({ input, replace, alias, externals, dev, resolve: resolveOptions, plugins, esbuildOptions, ...options }: BuildConfigOptions, pkg?: Package, override?: BuildOverride): RollupOptions[];
declare const logRollupConfig: (pkg: Package, config: RollupOptions[]) => void;
declare type Hook<T> = {
(pkg: Package, options: T): Promise<void> | void;
};
declare type Hooks<T extends Record<string, any>> = {
[P in keyof T]?: Hook<T[P]> | Array<Hook<T[P]>>;
};
declare type PackageHookOptions = {
'build:extend': {
config: RequireProperties<BuildConfigOptions, 'alias' | 'replace'>;
};
'build:extendRollup': {
rollupConfig: RollupOptions[];
};
'build:done': {
bundle: RollupBuild;
};
};
declare type PackageHooks = Hooks<PackageHookOptions>;
declare type PackageCommands = Record<string, (pkg: Package) => void | Promise<void>>;
/**
* Remove folders for build destinations
*/
declare function removeBuildFolders(pkg: Package): Promise<void>;
declare const build: (pkg: Package, { watch: shouldWatch, dev, override }?: BuildOptions) => Promise<void>;
export { BuildConfigOptions, BuildOptions, BuildOverride, DefaultPackageOptions, Hook, Hooks, Package, PackageCommands, PackageHookOptions, PackageHooks, PackageJson, PackageJsonPerson, PackageOptions, Repository, RequireProperties, SirocOptions, asArray, build, defineSirocConfig, ensureUnique, getRollupConfig, glob, groupBy, includeDefinedProperties, includeIf, logRollupConfig, regexpForPackage, removeBuildFolders, runInParallel, sortObjectKeys, tryJSON, tryRequire };