mirror of
https://github.com/pezkuwichain/pezkuwi-dev.git
synced 2026-04-22 02:08:01 +00:00
Initial rebrand: @polkadot -> @pezkuwi (3 packages)
- Package namespace: @polkadot/dev -> @pezkuwi/dev - Repository: polkadot-js/dev -> pezkuwichain/pezkuwi-dev - Author: Pezkuwi Team <team@pezkuwichain.io> Packages: - @pezkuwi/dev (build tools, linting, CI scripts) - @pezkuwi/dev-test (test runner) - @pezkuwi/dev-ts (TypeScript build) Upstream: polkadot-js/dev v0.83.3
This commit is contained in:
@@ -0,0 +1,547 @@
|
||||
# @pezkuwi/dev
|
||||
|
||||
A collection of shared CI scripts and development environment (configuration, dependencies) used by [@pezkuwi](https://pezkuwi.js.org) projects.
|
||||
|
||||
# Scripts
|
||||
|
||||
## polkadot-ci-ghact-build
|
||||
|
||||
**Summary**:
|
||||
This script automates the continuous integration (CI) process for building, testing, versioning, and publishing packages in the repository. It handles tasks like cleaning the workspace, running tests, updating versions, publishing to npm, GitHub repositories, and Deno, and generating changelogs.
|
||||
|
||||
### CLI Arguments
|
||||
|
||||
- **`--skip-beta`**:
|
||||
Prevents incrementing the version to a beta release.
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-ci-ghact-build [options]
|
||||
```
|
||||
|
||||
## polkadot-ci-ghact-docs
|
||||
|
||||
**Summary**:
|
||||
This script generates documentation for the repository and deploys it to GitHub Pages. It ensures the documentation is built and published with the correct configuration.
|
||||
|
||||
### CLI Arguments
|
||||
|
||||
This script does not accept any CLI arguments.
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-ci-ghact-docs
|
||||
```
|
||||
|
||||
## polkadot-ci-ghpages-force
|
||||
|
||||
**Summary**:
|
||||
This script force-refreshes the `gh-pages` branch of the repository by creating a new orphan branch, resetting its contents, and pushing it to GitHub. It ensures a clean state for GitHub Pages deployment.
|
||||
|
||||
### CLI Arguments
|
||||
|
||||
This script does not accept any CLI arguments.
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-ci-ghpages-force
|
||||
```
|
||||
|
||||
## polkadot-dev-build-docs
|
||||
|
||||
**Summary**:
|
||||
This script prepares the documentation for building by copying the `docs` directory to a `build-docs` directory. If the `build-docs` directory already exists, it is cleared before copying.
|
||||
|
||||
### CLI Arguments
|
||||
|
||||
This script does not accept any CLI arguments.
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-dev-build-docs
|
||||
```
|
||||
|
||||
## polkadot-dev-build-ts
|
||||
|
||||
**Summary**:
|
||||
This script compiles TypeScript source files into JavaScript outputs using the specified compiler (`tsc`), prepares the build artifacts, rewrites imports for compatibility (e.g., for Deno), lints dependencies, and updates package metadata for distribution. It supports CommonJS, ESM, and Deno outputs, along with configuration validation and export mapping.
|
||||
|
||||
### CLI Arguments
|
||||
|
||||
- **`--compiler <type>`**: Specifies the compiler to use for TypeScript compilation.
|
||||
- Acceptable values: `tsc`
|
||||
- Default: `tsc`
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-dev-build-ts [options]
|
||||
```
|
||||
|
||||
## polkadot-dev-circular
|
||||
|
||||
**Summary**:
|
||||
This script checks the project for circular dependencies in TypeScript (`.ts`, `.tsx`) files using the `madge` library. It reports any detected circular dependencies and exits with an error if any are found.
|
||||
|
||||
### CLI Arguments
|
||||
|
||||
This script does not accept any CLI arguments.
|
||||
|
||||
```bash
|
||||
yarn polkadot-dev-circular
|
||||
```
|
||||
|
||||
## polkadot-dev-clean-build
|
||||
|
||||
**Summary**:
|
||||
This script removes build artifacts and temporary files from the repository. It targets directories like `build` and files such as `tsconfig.*.tsbuildinfo`, ensuring a clean workspace for fresh builds.
|
||||
|
||||
### CLI Arguments
|
||||
|
||||
This script does not accept any CLI arguments.
|
||||
|
||||
```bash
|
||||
yarn polkadot-dev-clean-build
|
||||
```
|
||||
|
||||
## polkadot-dev-contrib
|
||||
|
||||
**Summary**:
|
||||
This script generates a `CONTRIBUTORS` file by aggregating and listing all contributors to the repository based on the Git commit history. It excludes bot accounts and service-related commits (e.g., GitHub Actions, Travis CI). The output includes the number of contributions, contributor names, and their most recent commit hash.
|
||||
|
||||
### CLI Arguments
|
||||
|
||||
This script does not accept any CLI arguments.
|
||||
|
||||
```bash
|
||||
yarn polkadot-dev-contrib
|
||||
```
|
||||
|
||||
## polkadot-dev-copy-dir
|
||||
|
||||
**Summary**:
|
||||
This script copies directories from specified source paths to a destination path. It supports options to change the working directory and to flatten the directory structure during copying.
|
||||
|
||||
### CLI Arguments
|
||||
|
||||
- **`--cd <path>`**:
|
||||
Specifies a working directory to prepend to the source and destination paths.
|
||||
|
||||
- **`--flatten`**:
|
||||
Copies all files directly to the destination without preserving the source directory structure.
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-dev-copy-dir [options] <source>... <destination>
|
||||
```
|
||||
- `<source>`: One or more source directories to copy.
|
||||
- `<destination>`: Destination directory for the copied files.
|
||||
|
||||
## polkadot-dev-copy-to
|
||||
|
||||
**Summary**:
|
||||
This script copies the `build` output and `node_modules` of all packages in the repository to a specified destination directory. It ensures the destination `node_modules` folder exists and is up-to-date.
|
||||
|
||||
### CLI Arguments
|
||||
|
||||
- **`<destination>`**:
|
||||
Specifies the target directory where the `node_modules` folder resides.
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-dev-copy-to <destination>
|
||||
```
|
||||
|
||||
## polkadot-dev-deno-map
|
||||
|
||||
**Summary**:
|
||||
This script generates a `mod.ts` file and an `import_map.json` file for Deno compatibility. It exports all packages with a `mod.ts` file in their `src` directory and maps their paths for use in Deno.
|
||||
|
||||
### Outputs
|
||||
|
||||
- **`mod.ts`**:
|
||||
An auto-generated TypeScript module exporting all packages for Deno. If the file does not exist, it is created.
|
||||
|
||||
- **`import_map.json`**:
|
||||
A JSON file mapping package paths to their corresponding Deno-compatible build paths. If an `import_map.in.json` file exists, its mappings are merged into the output.
|
||||
|
||||
### CLI Arguments
|
||||
|
||||
This script does not accept any CLI arguments.
|
||||
|
||||
## polkadot-dev-run-lint
|
||||
|
||||
**Summary**:
|
||||
This script runs linting and TypeScript checks on the repository. It uses `eslint` for code linting and `tsc` for TypeScript type checking. Specific checks can be skipped using CLI arguments.
|
||||
|
||||
### CLI Arguments
|
||||
|
||||
- **`--skip-eslint`**:
|
||||
Skips running `eslint` during the linting process.
|
||||
|
||||
- **`--skip-tsc`**:
|
||||
Skips running the TypeScript (`tsc`) type checker.
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-dev-run-lint [options]
|
||||
```
|
||||
|
||||
## polkadot-dev-run-node-ts
|
||||
|
||||
**Summary**:
|
||||
This script executes a Node.js script with TypeScript support, using the `@pezkuwi/dev-ts/cached` loader by default. It dynamically handles global and local loaders and allows for additional Node.js flags to be passed.
|
||||
|
||||
### CLI Arguments
|
||||
|
||||
- `<script>`: The TypeScript file to execute.
|
||||
- `[args...]`: Arguments to pass to the executed script.
|
||||
- Node.js flags, such as `--require`, `--loader`, and `--import`, are also supported and processed as follows:
|
||||
- **Global loaders** (e.g., absolute or non-relative paths) are prioritized.
|
||||
- The TypeScript loader is inserted after global loaders.
|
||||
- **Local loaders** (e.g., relative paths starting with `.`) are appended last.
|
||||
|
||||
### Default Behavior
|
||||
|
||||
- Suppresses warnings using the `--no-warnings` flag.
|
||||
- Enables source maps with `--enable-source-maps`.
|
||||
- Uses the `@pezkuwi/dev-ts/cached` loader for TypeScript execution.
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-dev-run-node-ts <script> [nodeFlags...] [args...]
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- The execNodeTs function ensures correct ordering of loaders:
|
||||
1. Global loaders are added first.
|
||||
2. The default TypeScript loader is included.
|
||||
3. Local loaders are appended.
|
||||
- Global and local loaders can be mixed for flexible runtime configurations.
|
||||
|
||||
## polkadot-dev-run-test
|
||||
|
||||
**Summary**:
|
||||
This script runs test files in the repository, filtering by file extensions and optional path-based filters. It supports both Node.js and browser environments, custom flags, and development-specific configurations.
|
||||
|
||||
### CLI Arguments
|
||||
|
||||
- **`--dev-build`**:
|
||||
Enables development mode, using local development builds for dependencies and loaders.
|
||||
|
||||
- **`--env <environment>`**:
|
||||
Specifies the test environment.
|
||||
- Acceptable values: `node`, `browser`
|
||||
- Default: `node`
|
||||
|
||||
- **`--bail`**:
|
||||
Stops the test suite on the first failure.
|
||||
|
||||
- **`--console`**:
|
||||
Enables console output during tests.
|
||||
|
||||
- **`--logfile <file>`**:
|
||||
Specifies a log file to capture test output.
|
||||
|
||||
- **`--import <module>`**:
|
||||
Imports the specified module.
|
||||
|
||||
- **`--loader <loader>`**:
|
||||
Specifies a custom Node.js loader.
|
||||
|
||||
- **`--require <module>`**:
|
||||
Preloads the specified module.
|
||||
|
||||
- **Filters**:
|
||||
You can include or exclude specific test files by specifying path-based filters:
|
||||
- Include: `filter` (e.g., `utils`)
|
||||
- Exclude: `^filter` (e.g., `^utils`)
|
||||
|
||||
### Supported Test Files
|
||||
|
||||
The script searches for test files with the following extensions:
|
||||
- **File Types**: `.spec`, `.test`
|
||||
- **Languages**: `.ts`, `.tsx`, `.js`, `.jsx`, `.cjs`, `.mjs`
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-dev-run-test [options] [filters...]
|
||||
```
|
||||
|
||||
### Behavior
|
||||
|
||||
- **Filters:**
|
||||
Filters are applied to include or exclude test files based on their paths. Included filters take precedence, and excluded filters are applied afterward.
|
||||
|
||||
- **Execution:**
|
||||
The script dynamically loads the appropriate environment setup (node or browser) and runs the tests using @pezkuwi/dev-test.
|
||||
|
||||
- **Errors:**
|
||||
If no matching files are found, the script exits with a fatal error.
|
||||
|
||||
- **Development Mode:**
|
||||
In development mode, local build paths are used for test and TypeScript loaders.
|
||||
|
||||
## polkadot-dev-version
|
||||
|
||||
**Summary**:
|
||||
This script automates the version bump process for a package or a monorepo. It updates the `version` field in `package.json` files and synchronizes dependency versions across workspaces. It supports major, minor, patch, and pre-release version bumps.
|
||||
|
||||
### CLI Arguments
|
||||
|
||||
- `<type>`: The type of version bump to apply.
|
||||
- Acceptable values: `major`, `minor`, `patch`, `pre`
|
||||
- Required.
|
||||
|
||||
### Behavior
|
||||
|
||||
1. **Version Bump**:
|
||||
- Uses `yarn version` to bump the root package version based on the specified `<type>`.
|
||||
|
||||
2. **Synchronizes Dependencies**:
|
||||
- Updates all `dependencies`, `devDependencies`, `peerDependencies`, `optionalDependencies`, and `resolutions` across all workspace packages to match the new version where applicable.
|
||||
|
||||
3. **Handles `-x` Suffix**:
|
||||
- If the root package's version ends with `-x`, it is temporarily removed before the version bump and re-added afterward for pre-releases.
|
||||
|
||||
4. **Updates Workspaces**:
|
||||
- Loops through all `packages/*` directories to update their `package.json` files with the new version and aligned dependencies.
|
||||
|
||||
5. **Installs Updated Dependencies**:
|
||||
- Runs `yarn install` to apply dependency updates after bumping versions.
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-dev-version <type>
|
||||
```
|
||||
|
||||
## polkadot-dev-yarn-only
|
||||
|
||||
|
||||
**Summary**:
|
||||
This script ensures that `yarn` is being used as the package manager. It exits with an error if a different package manager (e.g., `npm`) is detected.
|
||||
|
||||
### Behavior
|
||||
|
||||
1. **Check for Yarn**:
|
||||
- Verifies that the `yarn` package manager is being used by inspecting the `npm_execpath` environment variable.
|
||||
|
||||
2. **Exit on Failure**:
|
||||
- If `yarn` is not detected, the script exits with a fatal error message explaining that `yarn` is required.
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-dev-yarn-only
|
||||
```
|
||||
|
||||
## polkadot-exec-eslint
|
||||
|
||||
**Summary**:
|
||||
This script runs the ESLint binary to lint JavaScript and TypeScript files in the project. It uses the ESLint installation local to the project.
|
||||
|
||||
### Behavior
|
||||
|
||||
1. **Import ESLint**:
|
||||
- Dynamically imports and executes the `eslint` binary from the local project's `node_modules`.
|
||||
|
||||
2. **Delegates to ESLint**:
|
||||
- The script acts as a wrapper around the `eslint` command, passing any arguments to it.
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-exec-eslint [eslint-arguments]
|
||||
```
|
||||
|
||||
Notes
|
||||
- This script ensures that the locally installed version of ESLint is used, avoiding conflicts with global installations.
|
||||
- All standard ESLint CLI options can be passed directly to the script.
|
||||
|
||||
## polkadot-exec-ghpages
|
||||
|
||||
**Summary**:
|
||||
This script acts as a wrapper for the `gh-pages` tool, which is used to publish content to a project's GitHub Pages branch.
|
||||
|
||||
### Behavior
|
||||
|
||||
1. **Import `gh-pages`**:
|
||||
- Dynamically imports the `gh-pages` binary from the local project's `node_modules`.
|
||||
|
||||
2. **Run `gh-pages`**:
|
||||
- Passes command-line arguments directly to the `gh-pages` tool to execute the desired publishing tasks.
|
||||
|
||||
3. **Output on Success**:
|
||||
- Logs `Published` to the console upon successful completion.
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-exec-ghpages [gh-pages-arguments]
|
||||
```
|
||||
|
||||
## polkadot-exec-ghrelease
|
||||
|
||||
**Summary**:
|
||||
This script is a wrapper for the `gh-release` tool, used to create GitHub releases directly from the command line.
|
||||
|
||||
### Behavior
|
||||
|
||||
1. **Import `gh-release`**:
|
||||
- Dynamically imports the `gh-release` binary from the local project's `node_modules`.
|
||||
|
||||
2. **Run `gh-release`**:
|
||||
- Executes the `gh-release` CLI with any provided arguments.
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-exec-ghrelease [gh-release-arguments]
|
||||
```
|
||||
|
||||
## polkadot-exec-node-test
|
||||
|
||||
**Summary**:
|
||||
This script is designed to execute Node.js tests using the `node:test` module. It includes support for diagnostic reporting, customizable logging, and execution controls like bail and timeout.
|
||||
|
||||
### Key Features:
|
||||
|
||||
1. **Custom Test Execution**:
|
||||
- Executes tests using the `node:test` framework.
|
||||
- Handles test results, diagnostic messages, and statistics.
|
||||
|
||||
2. **Real-time Feedback**:
|
||||
- Displays progress updates on the console with formatted outputs:
|
||||
- `·` for passed tests.
|
||||
- `x` for failed tests.
|
||||
- `>` for skipped tests.
|
||||
- `!` for todo tests.
|
||||
|
||||
3. **Logging and Debugging**:
|
||||
- Optionally logs errors to a specified file (`--logfile <filename>`).
|
||||
- Outputs detailed diagnostic information when `--console` is used.
|
||||
|
||||
4. **Command-line Options**:
|
||||
- `--bail`: Stops execution after the first test failure.
|
||||
- `--console`: Outputs diagnostic and error details to the console.
|
||||
- `--logfile <file>`: Appends error logs to the specified file.
|
||||
|
||||
5. **Error Reporting**:
|
||||
- Provides structured error output, including filenames, stack traces, and failure types.
|
||||
|
||||
6. **Timeout**:
|
||||
- Configures a default timeout of 1 hour to avoid indefinite hangs.
|
||||
|
||||
### CLI Options:
|
||||
|
||||
- `--bail`: Exit after the first test failure.
|
||||
- `--console`: Print diagnostic details to the console.
|
||||
- `--logfile <file>`: Write failure details to the specified log file.
|
||||
- `<files>`: Specify test files to run (supports glob patterns).
|
||||
|
||||
### Usage:
|
||||
|
||||
```bash
|
||||
yarn polkadot-exec-node-test [options] <files...>
|
||||
```
|
||||
|
||||
## polkadot-exec-rollup
|
||||
|
||||
**Summary**:
|
||||
This script serves as a wrapper for the Rollup CLI, allowing users to execute Rollup commands via Node.js. It simplifies access to the Rollup binary and forwards all provided arguments directly to the Rollup CLI.
|
||||
|
||||
### CLI Arguments
|
||||
|
||||
- **`--config <file>`**:
|
||||
Specifies the Rollup configuration file to use.
|
||||
|
||||
- **`--watch`**:
|
||||
Enables watch mode, automatically rebuilding the bundle on file changes.
|
||||
|
||||
- **`--input <file>`**:
|
||||
Specifies the input file for the build.
|
||||
|
||||
- **`--output <file>`**:
|
||||
Specifies the output file or directory for the build.
|
||||
|
||||
- **`--silent`**:
|
||||
Suppresses Rollup output logs.
|
||||
|
||||
Refer to the [Rollup CLI documentation](https://rollupjs.org/guide/en/#command-line-interface) for a full list of available options.
|
||||
|
||||
### Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-exec-rollup [options]
|
||||
```
|
||||
|
||||
## polkadot-exec-tsc
|
||||
|
||||
**Summary**:
|
||||
This script executes the TypeScript Compiler (TSC) directly by importing the TypeScript library, enabling developers to compile TypeScript files with the same options available in the native `tsc` CLI.
|
||||
|
||||
### Common Options
|
||||
|
||||
- **`--project <file>`**
|
||||
Use a specific `tsconfig.json` file for compilation.
|
||||
|
||||
- **`--watch`**
|
||||
Watch for file changes and recompile automatically.
|
||||
|
||||
- **`--outDir <directory>`**
|
||||
Specify an output directory for compiled files.
|
||||
|
||||
- **`--declaration`**
|
||||
Generate TypeScript declaration files (`.d.ts`).
|
||||
|
||||
- **`--strict`**
|
||||
Enable strict type-checking options.
|
||||
|
||||
Refer to the official [TypeScript Compiler Options](https://www.typescriptlang.org/tsconfig) for a complete list of supported options.
|
||||
|
||||
### CLI Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-exec-tsc [options]
|
||||
```
|
||||
|
||||
##
|
||||
|
||||
**Summary**:
|
||||
This script directly imports and executes the Webpack CLI, allowing developers to bundle JavaScript applications using Webpack with access to all CLI options provided by the `webpack-cli`.
|
||||
|
||||
## Common Options
|
||||
|
||||
- **`--config <path>`**
|
||||
Specify a path to the Webpack configuration file.
|
||||
|
||||
- **`--mode <mode>`**
|
||||
Set the mode for Webpack. Valid values are `development`, `production`, or `none`.
|
||||
|
||||
- **`--watch`**
|
||||
Watch files for changes and rebuild the bundle automatically.
|
||||
|
||||
- **`--entry <file>`**
|
||||
Specify the entry file for the application.
|
||||
|
||||
- **`--output <path>`**
|
||||
Set the directory or filename for the output bundle.
|
||||
|
||||
Refer to the official [Webpack CLI Options](https://webpack.js.org/api/cli/) for a complete list of supported options.
|
||||
|
||||
## CLI Usage
|
||||
|
||||
```bash
|
||||
yarn polkadot-exec-webpack [options]
|
||||
```
|
||||
@@ -0,0 +1,160 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// @ts-expect-error No definition for this one
|
||||
import eslintJs from '@eslint/js';
|
||||
import tsPlugin from '@typescript-eslint/eslint-plugin';
|
||||
import tsParser from '@typescript-eslint/parser';
|
||||
// @ts-expect-error No definition for this one
|
||||
import standardConfig from 'eslint-config-standard';
|
||||
import deprecationPlugin from 'eslint-plugin-deprecation';
|
||||
// @ts-expect-error No definition for this one
|
||||
import headerPlugin from 'eslint-plugin-header';
|
||||
// @ts-expect-error No definition for this one
|
||||
import importPlugin from 'eslint-plugin-import';
|
||||
// @ts-expect-error No definition for this one
|
||||
import importNewlinesPlugin from 'eslint-plugin-import-newlines';
|
||||
// @ts-expect-error No definition for this one
|
||||
import jestPlugin from 'eslint-plugin-jest';
|
||||
// @ts-expect-error No definition for this one
|
||||
import nPlugin from 'eslint-plugin-n';
|
||||
// @ts-expect-error No definition for this one
|
||||
import promisePlugin from 'eslint-plugin-promise';
|
||||
// @ts-expect-error No definition for this one
|
||||
import reactPlugin from 'eslint-plugin-react';
|
||||
// @ts-expect-error No definition for this one
|
||||
import reactHooksPlugin from 'eslint-plugin-react-hooks';
|
||||
// @ts-expect-error No definition for this one
|
||||
import simpleImportSortPlugin from 'eslint-plugin-simple-import-sort';
|
||||
// @ts-expect-error No definition for this one
|
||||
import sortDestructureKeysPlugin from 'eslint-plugin-sort-destructure-keys';
|
||||
import globals from 'globals';
|
||||
|
||||
import { overrideAll, overrideJs, overrideJsx, overrideSpec } from './eslint.rules.js';
|
||||
|
||||
const EXT_JS = ['.cjs', '.js', '.mjs'];
|
||||
const EXT_TS = ['.ts', '.tsx'];
|
||||
const EXT_ALL = [...EXT_JS, ...EXT_TS];
|
||||
|
||||
/**
|
||||
* @internal
|
||||
* Converts a list of EXT_* defined above to globs
|
||||
* @param {string[]} exts
|
||||
* @returns {string[]}
|
||||
*/
|
||||
function extsToGlobs (exts) {
|
||||
return exts.map((e) => `**/*${e}`);
|
||||
}
|
||||
|
||||
export default [
|
||||
{
|
||||
ignores: [
|
||||
'**/.github/',
|
||||
'**/.vscode/',
|
||||
'**/.yarn/',
|
||||
'**/build/',
|
||||
'**/build-*/',
|
||||
'**/coverage/'
|
||||
]
|
||||
},
|
||||
{
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.browser,
|
||||
...globals.node
|
||||
},
|
||||
parser: tsParser,
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
project: './tsconfig.eslint.json',
|
||||
sourceType: 'module',
|
||||
warnOnUnsupportedTypeScriptVersion: false
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
'@typescript-eslint': tsPlugin,
|
||||
deprecation: deprecationPlugin,
|
||||
header: headerPlugin,
|
||||
import: importPlugin,
|
||||
'import-newlines': importNewlinesPlugin,
|
||||
n: nPlugin,
|
||||
promise: promisePlugin,
|
||||
'simple-import-sort': simpleImportSortPlugin,
|
||||
'sort-destructure-keys': sortDestructureKeysPlugin
|
||||
},
|
||||
settings: {
|
||||
'import/extensions': EXT_ALL,
|
||||
'import/parsers': {
|
||||
'@typescript-eslint/parser': EXT_TS,
|
||||
espree: EXT_JS
|
||||
},
|
||||
'import/resolver': {
|
||||
node: {
|
||||
extensions: EXT_ALL
|
||||
},
|
||||
typescript: {
|
||||
project: './tsconfig.eslint.json'
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
files: extsToGlobs(EXT_ALL),
|
||||
rules: {
|
||||
...eslintJs.configs.recommended.rules,
|
||||
...standardConfig.rules,
|
||||
...tsPlugin.configs['recommended-type-checked'].rules,
|
||||
...tsPlugin.configs['stylistic-type-checked'].rules,
|
||||
...overrideAll
|
||||
}
|
||||
},
|
||||
{
|
||||
files: extsToGlobs(EXT_JS),
|
||||
rules: {
|
||||
...overrideJs
|
||||
}
|
||||
},
|
||||
{
|
||||
files: [
|
||||
'**/*.tsx',
|
||||
'**/use*.ts'
|
||||
],
|
||||
plugins: {
|
||||
react: reactPlugin,
|
||||
'react-hooks': reactHooksPlugin
|
||||
},
|
||||
rules: {
|
||||
...reactPlugin.configs.recommended.rules,
|
||||
...reactHooksPlugin.configs.recommended.rules,
|
||||
...overrideJsx
|
||||
},
|
||||
settings: {
|
||||
react: {
|
||||
version: 'detect'
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
files: [
|
||||
'**/*.spec.ts',
|
||||
'**/*.spec.tsx'
|
||||
],
|
||||
languageOptions: {
|
||||
globals: {
|
||||
...globals.jest
|
||||
}
|
||||
},
|
||||
plugins: {
|
||||
jest: jestPlugin
|
||||
},
|
||||
rules: {
|
||||
...jestPlugin.configs.recommended.rules,
|
||||
...overrideSpec
|
||||
},
|
||||
settings: {
|
||||
jest: {
|
||||
version: 27
|
||||
}
|
||||
}
|
||||
}
|
||||
];
|
||||
@@ -0,0 +1,214 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import JSON5 from 'json5';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import process from 'node:process';
|
||||
|
||||
const FIXME = {
|
||||
// This is in the new 6.0.0 and we should switch this on
|
||||
// at some point. For a first iteration we keep as-is
|
||||
'@typescript-eslint/prefer-nullish-coalescing': 'off'
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns a copyright header pattern (using tsconfig.base.json)
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
function getHeaderPattern () {
|
||||
const tsPath = path.join(process.cwd(), 'tsconfig.base.json');
|
||||
|
||||
if (!fs.existsSync(tsPath)) {
|
||||
throw new Error(`Unable to load ${tsPath}`);
|
||||
}
|
||||
|
||||
const tsConfig = JSON5.parse(fs.readFileSync(tsPath, 'utf-8'));
|
||||
|
||||
if (!tsConfig?.compilerOptions?.paths) {
|
||||
throw new Error(`Unable to extract compilerOptions.paths structure from ${tsPath}`);
|
||||
}
|
||||
|
||||
const paths = Object.keys(tsConfig.compilerOptions.paths);
|
||||
|
||||
if (!paths.length) {
|
||||
throw new Error(`No keys found in compilerOptions.paths from ${tsPath}`);
|
||||
}
|
||||
|
||||
const packages = paths.reduce((packages, k) => {
|
||||
const [pd, pk] = k.split('/');
|
||||
|
||||
if (pd !== '@polkadot' || !pk) {
|
||||
throw new Error(`Non @polkadot path in ${tsPath}`);
|
||||
}
|
||||
|
||||
return packages.length
|
||||
? `${packages}|${pk}`
|
||||
: pk;
|
||||
}, '');
|
||||
const fullyear = new Date().getFullYear();
|
||||
const years = [];
|
||||
|
||||
for (let i = 17, last = fullyear - 2000; i < last; i++) {
|
||||
years.push(`${i}`);
|
||||
}
|
||||
|
||||
return ` Copyright 20(${years.join('|')})(-${fullyear})? @polkadot/(${packages})`;
|
||||
}
|
||||
|
||||
export const overrideAll = {
|
||||
...FIXME,
|
||||
// the next 2 enforce isolatedModules & verbatimModuleSyntax
|
||||
'@typescript-eslint/consistent-type-exports': 'error',
|
||||
'@typescript-eslint/consistent-type-imports': 'error',
|
||||
'@typescript-eslint/dot-notation': 'error',
|
||||
'@typescript-eslint/indent': ['error', 2],
|
||||
'@typescript-eslint/no-non-null-assertion': 'error',
|
||||
// ts itself checks and ignores those starting with _, align the linting
|
||||
'@typescript-eslint/no-unused-vars': ['error', {
|
||||
args: 'all',
|
||||
argsIgnorePattern: '^_',
|
||||
caughtErrors: 'all',
|
||||
caughtErrorsIgnorePattern: '^_',
|
||||
destructuredArrayIgnorePattern: '^_',
|
||||
vars: 'all',
|
||||
varsIgnorePattern: '^_'
|
||||
}],
|
||||
'@typescript-eslint/type-annotation-spacing': 'error',
|
||||
'arrow-parens': ['error', 'always'],
|
||||
'brace-style': ['error', '1tbs'],
|
||||
curly: ['error', 'all'],
|
||||
'default-param-last': 'off', // conflicts with TS version
|
||||
'deprecation/deprecation': 'error',
|
||||
'dot-notation': 'off', // conflicts with TS version
|
||||
'func-style': ['error', 'declaration', {
|
||||
allowArrowFunctions: true
|
||||
}],
|
||||
// this does help with declarations, but also
|
||||
// applies to invocations, which is an issue...
|
||||
// 'function-paren-newline': ['error', 'never'],
|
||||
'function-call-argument-newline': ['error', 'consistent'],
|
||||
'header/header': ['error', 'line', [
|
||||
{ pattern: getHeaderPattern() },
|
||||
' SPDX-License-Identifier: Apache-2.0'
|
||||
], 2],
|
||||
'import-newlines/enforce': ['error', {
|
||||
forceSingleLine: true,
|
||||
items: 2048
|
||||
}],
|
||||
'import/export': 'error',
|
||||
'import/extensions': ['error', 'ignorePackages', {
|
||||
cjs: 'always',
|
||||
js: 'always',
|
||||
json: 'always',
|
||||
jsx: 'never',
|
||||
mjs: 'always',
|
||||
ts: 'never',
|
||||
tsx: 'never'
|
||||
}],
|
||||
'import/first': 'error',
|
||||
'import/newline-after-import': 'error',
|
||||
'import/no-duplicates': 'error',
|
||||
'import/order': 'off', // conflicts with simple-import-sort
|
||||
indent: 'off', // required as 'off' since typescript-eslint has own versions
|
||||
'no-extra-semi': 'error',
|
||||
'no-unused-vars': 'off',
|
||||
'no-use-before-define': 'off',
|
||||
'object-curly-newline': ['error', {
|
||||
ExportDeclaration: { minProperties: 2048 },
|
||||
ImportDeclaration: { minProperties: 2048 },
|
||||
ObjectPattern: { minProperties: 2048 }
|
||||
}],
|
||||
'padding-line-between-statements': [
|
||||
'error',
|
||||
{ blankLine: 'always', next: '*', prev: ['const', 'let', 'var'] },
|
||||
{ blankLine: 'any', next: ['const', 'let', 'var'], prev: ['const', 'let', 'var'] },
|
||||
{ blankLine: 'always', next: 'block-like', prev: '*' },
|
||||
{ blankLine: 'always', next: '*', prev: 'block-like' },
|
||||
{ blankLine: 'always', next: 'function', prev: '*' },
|
||||
{ blankLine: 'always', next: '*', prev: 'function' },
|
||||
{ blankLine: 'always', next: 'try', prev: '*' },
|
||||
{ blankLine: 'always', next: '*', prev: 'try' },
|
||||
{ blankLine: 'always', next: 'return', prev: '*' },
|
||||
{ blankLine: 'always', next: 'import', prev: '*' },
|
||||
{ blankLine: 'always', next: '*', prev: 'import' },
|
||||
{ blankLine: 'any', next: 'import', prev: 'import' }
|
||||
],
|
||||
semi: ['error', 'always'],
|
||||
'simple-import-sort/exports': 'error',
|
||||
'simple-import-sort/imports': ['error', {
|
||||
groups: [
|
||||
['^\u0000'], // all side-effects (0 at start)
|
||||
['\u0000$', '^@polkadot.*\u0000$', '^\\..*\u0000$'], // types (0 at end)
|
||||
// ['^node:'], // node
|
||||
['^[^/\\.]'], // non-polkadot
|
||||
['^@polkadot'], // polkadot
|
||||
['^\\.\\.(?!/?$)', '^\\.\\./?$', '^\\./(?=.*/)(?!/?$)', '^\\.(?!/?$)', '^\\./?$'] // local (. last)
|
||||
]
|
||||
}],
|
||||
'sort-destructure-keys/sort-destructure-keys': ['error', {
|
||||
caseSensitive: true
|
||||
}],
|
||||
'sort-keys': 'error',
|
||||
'spaced-comment': ['error', 'always', {
|
||||
block: {
|
||||
// pure export helpers
|
||||
markers: ['#__PURE__']
|
||||
},
|
||||
line: {
|
||||
// TS reference types
|
||||
markers: ['/ <reference']
|
||||
}
|
||||
}]
|
||||
};
|
||||
|
||||
export const overrideJsx = {
|
||||
'jsx-quotes': ['error', 'prefer-single'],
|
||||
// swap from recommended warning to error
|
||||
'react-hooks/exhaustive-deps': 'error',
|
||||
'react/jsx-closing-bracket-location': ['warn', 'tag-aligned'],
|
||||
'react/jsx-first-prop-new-line': ['warn', 'multiline-multiprop'],
|
||||
'react/jsx-fragments': 'error',
|
||||
'react/jsx-max-props-per-line': ['warn', {
|
||||
maximum: 1,
|
||||
when: 'always'
|
||||
}],
|
||||
'react/jsx-newline': ['error', {
|
||||
prevent: true
|
||||
}],
|
||||
'react/jsx-no-bind': 'error',
|
||||
'react/jsx-props-no-multi-spaces': 'error',
|
||||
'react/jsx-sort-props': ['warn', {
|
||||
noSortAlphabetically: false
|
||||
}],
|
||||
'react/jsx-tag-spacing': ['error', {
|
||||
afterOpening: 'never',
|
||||
beforeClosing: 'never',
|
||||
beforeSelfClosing: 'always',
|
||||
closingSlash: 'never'
|
||||
}],
|
||||
'react/prop-types': 'off' // this is a completely broken rule
|
||||
};
|
||||
|
||||
export const overrideJs = {
|
||||
'@typescript-eslint/explicit-function-return-type': 'off',
|
||||
'@typescript-eslint/no-unsafe-argument': 'off',
|
||||
'@typescript-eslint/no-unsafe-assignment': 'off',
|
||||
'@typescript-eslint/no-unsafe-call': 'off',
|
||||
'@typescript-eslint/no-unsafe-member-access': 'off',
|
||||
'@typescript-eslint/no-unsafe-return': 'off',
|
||||
'@typescript-eslint/no-var-requires': 'off',
|
||||
'@typescript-eslint/restrict-plus-operands': 'off',
|
||||
'@typescript-eslint/restrict-template-expressions': 'off'
|
||||
};
|
||||
|
||||
export const overrideSpec = {
|
||||
// in the specs we are a little less worried about
|
||||
// specific correctness, i.e. we can have dangling bits
|
||||
'@typescript-eslint/no-unsafe-call': 'off',
|
||||
'@typescript-eslint/no-unsafe-member-access': 'off',
|
||||
'jest/expect-expect': ['warn', {
|
||||
assertFunctionNames: ['assert', 'expect']
|
||||
}]
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
module.exports = {
|
||||
arrowParens: 'always',
|
||||
bracketSpacing: true,
|
||||
embeddedLanguageFormatting: 'off',
|
||||
endOfLine: 'lf',
|
||||
htmlWhitespaceSensitivity: 'ignore',
|
||||
jsxBracketSameLine: false,
|
||||
jsxSingleQuote: true,
|
||||
parser: 'typescript',
|
||||
printWidth: 2048,
|
||||
proseWrap: 'preserve',
|
||||
quoteProps: 'as-needed',
|
||||
requirePragma: true, // only on those files explicitly asked for
|
||||
semi: true,
|
||||
singleQuote: true,
|
||||
tabWidth: 2,
|
||||
trailingComma: 'none',
|
||||
useTabs: false
|
||||
};
|
||||
@@ -0,0 +1,113 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import pluginAlias from '@rollup/plugin-alias';
|
||||
import pluginCommonjs from '@rollup/plugin-commonjs';
|
||||
import pluginDynamicImportVars from '@rollup/plugin-dynamic-import-vars';
|
||||
import pluginInject from '@rollup/plugin-inject';
|
||||
import pluginJson from '@rollup/plugin-json';
|
||||
import { nodeResolve as pluginResolve } from '@rollup/plugin-node-resolve';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import pluginCleanup from 'rollup-plugin-cleanup';
|
||||
|
||||
/** @typedef {{ entries?: Record<string, string>; external: string[]; globals?: Record<string, string>; index?: string; inject?: Record<string, string>; pkg: string; }} BundleDef */
|
||||
/** @typedef {{ file: string; format: 'umd'; generatedCode: Record<string, unknown>; globals: Record<string, string>; inlineDynamicImports: true; intro: string; name: string; }} BundleOutput */
|
||||
/** @typedef {{ context: 'global'; external: string[]; input: string; output: BundleOutput; plugins: any[]; }} Bundle */
|
||||
|
||||
/**
|
||||
* @param {string} pkg
|
||||
* @returns {string}
|
||||
*/
|
||||
function sanitizePkg (pkg) {
|
||||
return pkg.replace('@polkadot/', '');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} input
|
||||
* @returns {string}
|
||||
*/
|
||||
function createName (input) {
|
||||
return `polkadot-${sanitizePkg(input)}`
|
||||
.toLowerCase()
|
||||
.replace(/[^a-zA-Z0-9]+(.)/g, (_, c) => c.toUpperCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} pkg
|
||||
* @param {string} [index]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function createInput (pkg, index) {
|
||||
const partialPath = `packages/${sanitizePkg(pkg)}/build`;
|
||||
|
||||
return `${partialPath}/${
|
||||
index ||
|
||||
fs.existsSync(path.join(process.cwd(), partialPath, 'bundle.js'))
|
||||
? 'bundle.js'
|
||||
: (
|
||||
JSON.parse(fs.readFileSync(path.join(process.cwd(), partialPath, 'package.json'), 'utf8')).browser ||
|
||||
'index.js'
|
||||
)
|
||||
}`;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} pkg
|
||||
* @param {string[]} external
|
||||
* @param {Record<string, string>} globals
|
||||
* @returns {BundleOutput}
|
||||
*/
|
||||
export function createOutput (pkg, external, globals) {
|
||||
const name = sanitizePkg(pkg);
|
||||
|
||||
return {
|
||||
file: `packages/${name}/build/bundle-polkadot-${name}.js`,
|
||||
format: 'umd',
|
||||
generatedCode: {
|
||||
constBindings: true
|
||||
},
|
||||
globals: external.reduce((all, p) => ({
|
||||
[p]: createName(p),
|
||||
...all
|
||||
}), { ...globals }),
|
||||
// combine multi-chunk builds with dynamic imports
|
||||
inlineDynamicImports: true,
|
||||
// this is a mini x-global, determine where our context lies
|
||||
intro: 'const global = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : window;',
|
||||
name: createName(pkg)
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {BundleDef} param0
|
||||
* @returns {Bundle}
|
||||
*/
|
||||
export function createBundle ({ entries = {}, external, globals = {}, index, inject = {}, pkg }) {
|
||||
return {
|
||||
// specify this (we define global in the output intro as globalThis || self || window)
|
||||
context: 'global',
|
||||
external,
|
||||
input: createInput(pkg, index),
|
||||
output: createOutput(pkg, external, globals),
|
||||
// NOTE The expect-error directives are due to rollup plugins, see
|
||||
// - https://github.com/rollup/plugins/issues/1488
|
||||
// - https://github.com/rollup/plugins/issues/1329
|
||||
plugins: [
|
||||
// @ts-expect-error See the linked rollup issues above
|
||||
pluginAlias({ entries }),
|
||||
// @ts-expect-error See the linked rollup issues above
|
||||
pluginJson(),
|
||||
// @ts-expect-error See the linked rollup issues above
|
||||
pluginCommonjs(),
|
||||
// @ts-expect-error See the linked rollup issues above
|
||||
pluginDynamicImportVars(),
|
||||
// @ts-expect-error See the linked rollup issues above
|
||||
pluginInject(inject),
|
||||
pluginResolve({ browser: true }),
|
||||
pluginCleanup()
|
||||
]
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
/**
|
||||
* There uses the strictest configs as the base
|
||||
* https://github.com/tsconfig/bases/blob/f674fa6cbca17062ff02511b02872f8729a597ec/bases/strictest.json
|
||||
*/
|
||||
"extends": "@tsconfig/strictest/tsconfig.json",
|
||||
"compilerOptions": {
|
||||
/**
|
||||
* Aligns with packages/dev/scripts/polkadot-dev-build-ts & packages/dev-ts/src/loader
|
||||
* (target here is specifically tied to the minimum supported Node version)
|
||||
*/
|
||||
"module": "nodenext",
|
||||
"moduleResolution": "nodenext",
|
||||
"target": "es2022",
|
||||
|
||||
/**
|
||||
* Specific compilation configs for polkadot-js projects as it is used
|
||||
* (we only compile *.d.ts via the tsc command-line)
|
||||
*/
|
||||
"declaration": true,
|
||||
"emitDeclarationOnly": true,
|
||||
"jsx": "preserve",
|
||||
"verbatimModuleSyntax": true,
|
||||
|
||||
/**
|
||||
* These appear in strictest, however we don't (yet) use them. For the most part it means
|
||||
* that we actually do have a large number of these lurking (especially on index checks)
|
||||
*/
|
||||
"exactOptionalPropertyTypes": false,
|
||||
"noUncheckedIndexedAccess": false,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
module.exports = {
|
||||
exclude: '**/*+(index|e2e|spec|types).ts',
|
||||
excludeExternals: true,
|
||||
excludeNotExported: true,
|
||||
excludePrivate: true,
|
||||
excludeProtected: true,
|
||||
hideGenerator: true,
|
||||
includeDeclarations: false,
|
||||
module: 'commonjs',
|
||||
moduleResolution: 'node',
|
||||
name: 'polkadot{.js}',
|
||||
out: 'docs',
|
||||
stripInternal: 'true',
|
||||
theme: 'markdown'
|
||||
};
|
||||
@@ -0,0 +1,107 @@
|
||||
{
|
||||
"author": "Jaco Greeff <jacogr@gmail.com>",
|
||||
"bugs": "https://github.com/pezkuwi/dev/issues",
|
||||
"description": "A collection of shared CI scripts and development environment used by @pezkuwi projects",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"homepage": "https://github.com/pezkuwi/dev/tree/master/packages/dev#readme",
|
||||
"license": "Apache-2.0",
|
||||
"name": "@pezkuwi/dev",
|
||||
"repository": {
|
||||
"directory": "packages/dev",
|
||||
"type": "git",
|
||||
"url": "https://github.com/pezkuwi/dev.git"
|
||||
},
|
||||
"sideEffects": false,
|
||||
"type": "module",
|
||||
"version": "0.84.2",
|
||||
"bin": {
|
||||
"polkadot-ci-ghact-build": "./scripts/polkadot-ci-ghact-build.mjs",
|
||||
"polkadot-ci-ghact-docs": "./scripts/polkadot-ci-ghact-docs.mjs",
|
||||
"polkadot-ci-ghpages-force": "./scripts/polkadot-ci-ghpages-force.mjs",
|
||||
"polkadot-dev-build-docs": "./scripts/polkadot-dev-build-docs.mjs",
|
||||
"polkadot-dev-build-ts": "./scripts/polkadot-dev-build-ts.mjs",
|
||||
"polkadot-dev-circular": "./scripts/polkadot-dev-circular.mjs",
|
||||
"polkadot-dev-clean-build": "./scripts/polkadot-dev-clean-build.mjs",
|
||||
"polkadot-dev-contrib": "./scripts/polkadot-dev-contrib.mjs",
|
||||
"polkadot-dev-copy-dir": "./scripts/polkadot-dev-copy-dir.mjs",
|
||||
"polkadot-dev-copy-to": "./scripts/polkadot-dev-copy-to.mjs",
|
||||
"polkadot-dev-deno-map": "./scripts/polkadot-dev-deno-map.mjs",
|
||||
"polkadot-dev-run-lint": "./scripts/polkadot-dev-run-lint.mjs",
|
||||
"polkadot-dev-run-node-ts": "./scripts/polkadot-dev-run-node-ts.mjs",
|
||||
"polkadot-dev-run-test": "./scripts/polkadot-dev-run-test.mjs",
|
||||
"polkadot-dev-version": "./scripts/polkadot-dev-version.mjs",
|
||||
"polkadot-dev-yarn-only": "./scripts/polkadot-dev-yarn-only.mjs",
|
||||
"polkadot-exec-eslint": "./scripts/polkadot-exec-eslint.mjs",
|
||||
"polkadot-exec-ghpages": "./scripts/polkadot-exec-ghpages.mjs",
|
||||
"polkadot-exec-ghrelease": "./scripts/polkadot-exec-ghrelease.mjs",
|
||||
"polkadot-exec-node-test": "./scripts/polkadot-exec-node-test.mjs",
|
||||
"polkadot-exec-rollup": "./scripts/polkadot-exec-rollup.mjs",
|
||||
"polkadot-exec-tsc": "./scripts/polkadot-exec-tsc.mjs",
|
||||
"polkadot-exec-webpack": "./scripts/polkadot-exec-webpack.mjs"
|
||||
},
|
||||
"exports": {
|
||||
"./config/eslint": "./config/eslint.js",
|
||||
"./config/prettier.cjs": "./config/prettier.cjs",
|
||||
"./config/tsconfig.json": "./config/tsconfig.json",
|
||||
"./rootJs/dynamic.mjs": "./src/rootJs/dynamic.mjs",
|
||||
"./rootJs/testJson.json": "./src/rootJs/testJson.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@eslint/js": "^8.56.0",
|
||||
"@pezkuwi/dev-test": "^0.84.2",
|
||||
"@pezkuwi/dev-ts": "^0.84.2",
|
||||
"@rollup/plugin-alias": "^5.1.1",
|
||||
"@rollup/plugin-commonjs": "^25.0.8",
|
||||
"@rollup/plugin-dynamic-import-vars": "^2.1.5",
|
||||
"@rollup/plugin-inject": "^5.0.5",
|
||||
"@rollup/plugin-json": "^6.1.0",
|
||||
"@rollup/plugin-node-resolve": "^15.3.1",
|
||||
"@tsconfig/strictest": "^2.0.2",
|
||||
"@typescript-eslint/eslint-plugin": "^6.19.1",
|
||||
"@typescript-eslint/parser": "^6.19.1",
|
||||
"eslint": "^8.56.0",
|
||||
"eslint-config-standard": "^17.1.0",
|
||||
"eslint-import-resolver-node": "^0.3.9",
|
||||
"eslint-import-resolver-typescript": "^3.6.1",
|
||||
"eslint-plugin-deprecation": "^2.0.0",
|
||||
"eslint-plugin-header": "^3.1.1",
|
||||
"eslint-plugin-import": "^2.29.1",
|
||||
"eslint-plugin-import-newlines": "^1.3.4",
|
||||
"eslint-plugin-jest": "^27.6.3",
|
||||
"eslint-plugin-n": "^16.6.2",
|
||||
"eslint-plugin-promise": "^6.1.1",
|
||||
"eslint-plugin-react": "^7.33.2",
|
||||
"eslint-plugin-react-hooks": "^4.6.0",
|
||||
"eslint-plugin-simple-import-sort": "^10.0.0",
|
||||
"eslint-plugin-sort-destructure-keys": "^1.5.0",
|
||||
"espree": "^9.6.1",
|
||||
"gh-pages": "^6.1.1",
|
||||
"gh-release": "^7.0.2",
|
||||
"globals": "^13.24.0",
|
||||
"json5": "^2.2.3",
|
||||
"madge": "^6.1.0",
|
||||
"rollup": "^4.9.6",
|
||||
"rollup-plugin-cleanup": "^3.2.1",
|
||||
"tslib": "^2.7.0",
|
||||
"typescript": "^5.5.4",
|
||||
"webpack": "^5.89.0",
|
||||
"webpack-cli": "^5.1.4",
|
||||
"webpack-dev-server": "^4.15.1",
|
||||
"webpack-merge": "^5.10.0",
|
||||
"webpack-subresource-integrity": "^5.2.0-rc.1",
|
||||
"yargs": "^17.7.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/react": "^14.1.2",
|
||||
"@types/node": "^20.11.5",
|
||||
"@types/react": "^18.2.48",
|
||||
"@types/react-dom": "^18.2.18",
|
||||
"@types/yargs": "^17.0.32",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-is": "^18.2.0",
|
||||
"styled-components": "^6.1.8"
|
||||
}
|
||||
}
|
||||
+540
@@ -0,0 +1,540 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import process from 'node:process';
|
||||
import yargs from 'yargs';
|
||||
|
||||
import { copyDirSync, copyFileSync, denoCreateDir, execGit, execPm, execSync, exitFatal, GITHUB_REPO, GITHUB_TOKEN_URL, gitSetup, logBin, mkdirpSync, rimrafSync, topoSort } from './util.mjs';
|
||||
|
||||
/** @typedef {Record<string, any>} ChangelogMap */
|
||||
|
||||
logBin('polkadot-ci-ghact-build');
|
||||
|
||||
const DENO_REPO = 'polkadot-js/build-deno.land';
|
||||
const BUND_REPO = 'polkadot-js/build-bundle';
|
||||
|
||||
const repo = `${GITHUB_TOKEN_URL}/${GITHUB_REPO}.git`;
|
||||
const denoRepo = `${GITHUB_TOKEN_URL}/${DENO_REPO}.git`;
|
||||
const bundRepo = `${GITHUB_TOKEN_URL}/${BUND_REPO}.git`;
|
||||
const bundClone = 'build-bundle-clone';
|
||||
const denoClone = 'build-deno-clone';
|
||||
|
||||
let withDeno = false;
|
||||
let withBund = false;
|
||||
let withNpm = false;
|
||||
|
||||
/** @type {string[]} */
|
||||
const shouldDeno = [];
|
||||
/** @type {string[]} */
|
||||
const shouldBund = [];
|
||||
|
||||
const argv = await yargs(process.argv.slice(2))
|
||||
.options({
|
||||
'skip-beta': {
|
||||
description: 'Do not increment as beta',
|
||||
type: 'boolean'
|
||||
}
|
||||
})
|
||||
.strict()
|
||||
.argv;
|
||||
|
||||
/**
|
||||
* Removes a specific file, returning true if found, false otherwise
|
||||
*
|
||||
* @param {string} file
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function rmFile (file) {
|
||||
if (fs.existsSync(file)) {
|
||||
rimrafSync(file);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the path of the root package.json
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
function npmGetJsonPath () {
|
||||
return path.resolve(process.cwd(), 'package.json');
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves the contents of the root package.json
|
||||
*
|
||||
* @returns {{ name: string; version: string; versions?: { npm?: string; git?: string } }}
|
||||
*/
|
||||
function npmGetJson () {
|
||||
return JSON.parse(
|
||||
fs.readFileSync(npmGetJsonPath(), 'utf8')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the contents of the root package.json
|
||||
*
|
||||
* @param {any} json
|
||||
*/
|
||||
function npmSetJson (json) {
|
||||
fs.writeFileSync(npmGetJsonPath(), `${JSON.stringify(json, null, 2)}\n`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieved the current version included in package.json
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
function npmGetVersion () {
|
||||
return npmGetJson().version;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the current to have an -x version specifier (aka beta)
|
||||
*/
|
||||
function npmAddVersionX () {
|
||||
const json = npmGetJson();
|
||||
|
||||
if (!json.version.endsWith('-x')) {
|
||||
json.version = json.version + '-x';
|
||||
npmSetJson(json);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the current -x version specifier (aka beta)
|
||||
*/
|
||||
function npmDelVersionX () {
|
||||
const json = npmGetJson();
|
||||
|
||||
if (json.version.endsWith('-x')) {
|
||||
json.version = json.version.replace('-x', '');
|
||||
npmSetJson(json);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the {versions: { npm, git } } fields in package.json
|
||||
*/
|
||||
function npmSetVersionFields () {
|
||||
const json = npmGetJson();
|
||||
|
||||
if (!json.versions) {
|
||||
json.versions = {};
|
||||
}
|
||||
|
||||
json.versions.git = json.version;
|
||||
|
||||
if (!json.version.endsWith('-x')) {
|
||||
json.versions.npm = json.version;
|
||||
}
|
||||
|
||||
npmSetJson(json);
|
||||
rmFile('.123current');
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the npm token in the home directory
|
||||
*/
|
||||
function npmSetup () {
|
||||
const registry = 'registry.npmjs.org';
|
||||
|
||||
fs.writeFileSync(path.join(os.homedir(), '.npmrc'), `//${registry}/:_authToken=${process.env['NPM_TOKEN']}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes the current package
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
function npmPublish () {
|
||||
if (fs.existsSync('.skip-npm') || !withNpm) {
|
||||
return;
|
||||
}
|
||||
|
||||
['LICENSE', 'package.json']
|
||||
.filter((file) => !fs.existsSync(path.join(process.cwd(), 'build', file)))
|
||||
.forEach((file) => copyFileSync(file, 'build'));
|
||||
|
||||
process.chdir('build');
|
||||
|
||||
const tag = npmGetVersion().includes('-') ? '--tag beta' : '';
|
||||
let count = 1;
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
execSync(`npm publish --quiet --access public ${tag}`);
|
||||
|
||||
break;
|
||||
} catch {
|
||||
if (count < 5) {
|
||||
const end = Date.now() + 15000;
|
||||
|
||||
console.error(`Publish failed on attempt ${count}/5. Retrying in 15s`);
|
||||
count++;
|
||||
|
||||
while (Date.now() < end) {
|
||||
// just spin our wheels
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
process.chdir('..');
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a map of changelog entries
|
||||
*
|
||||
* @param {string[][]} parts
|
||||
* @param {ChangelogMap} result
|
||||
* @returns {ChangelogMap}
|
||||
*/
|
||||
function createChangelogMap (parts, result = {}) {
|
||||
for (let i = 0, count = parts.length; i < count; i++) {
|
||||
const [n, ...e] = parts[i];
|
||||
|
||||
if (!result[n]) {
|
||||
if (e.length) {
|
||||
result[n] = createChangelogMap([e]);
|
||||
} else {
|
||||
result[n] = { '': {} };
|
||||
}
|
||||
} else {
|
||||
if (e.length) {
|
||||
createChangelogMap([e], result[n]);
|
||||
} else {
|
||||
result[n][''] = {};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an array of changelog entries
|
||||
*
|
||||
* @param {ChangelogMap} map
|
||||
* @returns {string[]}
|
||||
*/
|
||||
function createChangelogArr (map) {
|
||||
const result = [];
|
||||
const entries = Object.entries(map);
|
||||
|
||||
for (let i = 0, count = entries.length; i < count; i++) {
|
||||
const [name, imap] = entries[i];
|
||||
|
||||
if (name) {
|
||||
if (imap['']) {
|
||||
result.push(name);
|
||||
}
|
||||
|
||||
const inner = createChangelogArr(imap);
|
||||
|
||||
if (inner.length === 1) {
|
||||
result.push(`${name}-${inner[0]}`);
|
||||
} else if (inner.length) {
|
||||
result.push(`${name}-{${inner.join(', ')}}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds changelog entries
|
||||
*
|
||||
* @param {string[]} changelog
|
||||
* @returns {string}
|
||||
*/
|
||||
function addChangelog (changelog) {
|
||||
const [version, ...names] = changelog;
|
||||
const entry = `${
|
||||
createChangelogArr(
|
||||
createChangelogMap(
|
||||
names
|
||||
.sort()
|
||||
.map((n) => n.split('-'))
|
||||
)
|
||||
).join(', ')
|
||||
} ${version}`;
|
||||
const newInfo = `## master\n\n- ${entry}\n`;
|
||||
|
||||
if (!fs.existsSync('CHANGELOG.md')) {
|
||||
fs.writeFileSync('CHANGELOG.md', `# CHANGELOG\n\n${newInfo}`);
|
||||
} else {
|
||||
const md = fs.readFileSync('CHANGELOG.md', 'utf-8');
|
||||
|
||||
fs.writeFileSync('CHANGELOG.md', md.includes('## master\n\n')
|
||||
? md.replace('## master\n\n', newInfo)
|
||||
: md.replace('# CHANGELOG\n\n', `# CHANGELOG\n\n${newInfo}\n`)
|
||||
);
|
||||
}
|
||||
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} repo
|
||||
* @param {string} clone
|
||||
* @param {string[]} names
|
||||
*/
|
||||
function commitClone (repo, clone, names) {
|
||||
if (names.length) {
|
||||
process.chdir(clone);
|
||||
|
||||
const entry = addChangelog(names);
|
||||
|
||||
gitSetup();
|
||||
execGit('add --all .');
|
||||
execGit(`commit --no-status --quiet -m "${entry}"`);
|
||||
execGit(`push ${repo}`, true);
|
||||
|
||||
process.chdir('..');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes a specific package to polkadot-js bundles
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
function bundlePublishPkg () {
|
||||
const { name, version } = npmGetJson();
|
||||
const dirName = name.split('/')[1];
|
||||
const bundName = `bundle-polkadot-${dirName}.js`;
|
||||
const srcPath = path.join('build', bundName);
|
||||
const dstDir = path.join('../..', bundClone);
|
||||
|
||||
if (!fs.existsSync(srcPath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`\n *** bundle ${name}`);
|
||||
|
||||
if (shouldBund.length === 0) {
|
||||
shouldBund.push(version);
|
||||
}
|
||||
|
||||
shouldBund.push(dirName);
|
||||
|
||||
rimrafSync(path.join(dstDir, bundName));
|
||||
copyFileSync(srcPath, dstDir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes all packages to polkadot-js bundles
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
function bundlePublish () {
|
||||
const { version } = npmGetJson();
|
||||
|
||||
if (!withBund && version.includes('-')) {
|
||||
return;
|
||||
}
|
||||
|
||||
execGit(`clone ${bundRepo} ${bundClone}`, true);
|
||||
|
||||
loopFunc(bundlePublishPkg);
|
||||
|
||||
commitClone(bundRepo, bundClone, shouldBund);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes a specific package to Deno
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
function denoPublishPkg () {
|
||||
const { name, version } = npmGetJson();
|
||||
|
||||
if (fs.existsSync('.skip-deno') || !fs.existsSync('build-deno')) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`\n *** deno ${name}`);
|
||||
|
||||
const dirName = denoCreateDir(name);
|
||||
const denoPath = `../../${denoClone}/${dirName}`;
|
||||
|
||||
if (shouldDeno.length === 0) {
|
||||
shouldDeno.push(version);
|
||||
}
|
||||
|
||||
shouldDeno.push(dirName);
|
||||
|
||||
rimrafSync(denoPath);
|
||||
mkdirpSync(denoPath);
|
||||
|
||||
copyDirSync('build-deno', denoPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Publishes all packages to Deno
|
||||
*
|
||||
* @returns {void}
|
||||
*/
|
||||
function denoPublish () {
|
||||
const { version } = npmGetJson();
|
||||
|
||||
if (!withDeno && version.includes('-')) {
|
||||
return;
|
||||
}
|
||||
|
||||
execGit(`clone ${denoRepo} ${denoClone}`, true);
|
||||
|
||||
loopFunc(denoPublishPkg);
|
||||
|
||||
commitClone(denoRepo, denoClone, shouldDeno);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves flags based on current specifications
|
||||
*/
|
||||
function getFlags () {
|
||||
withDeno = rmFile('.123deno');
|
||||
withBund = rmFile('.123bundle');
|
||||
withNpm = rmFile('.123npm');
|
||||
}
|
||||
|
||||
/**
|
||||
* Bumps the current version, also applying to all sub-packages
|
||||
*/
|
||||
function verBump () {
|
||||
const { version: currentVersion, versions } = npmGetJson();
|
||||
const [version, tag] = currentVersion.split('-');
|
||||
const [,, patch] = version.split('.');
|
||||
const lastVersion = versions?.npm || currentVersion;
|
||||
|
||||
if (argv['skip-beta'] || patch === '0') {
|
||||
// don't allow beta versions
|
||||
execPm('polkadot-dev-version patch');
|
||||
withNpm = true;
|
||||
} else if (tag || currentVersion === lastVersion) {
|
||||
// if we don't want to publish, add an X before passing
|
||||
if (!withNpm) {
|
||||
npmAddVersionX();
|
||||
} else {
|
||||
npmDelVersionX();
|
||||
}
|
||||
|
||||
// beta version, just continue the stream of betas
|
||||
execPm('polkadot-dev-version pre');
|
||||
} else {
|
||||
// manually set, got for publish
|
||||
withNpm = true;
|
||||
}
|
||||
|
||||
// always ensure we have made some changes, so we can commit
|
||||
npmSetVersionFields();
|
||||
rmFile('.123trigger');
|
||||
|
||||
execPm('polkadot-dev-contrib');
|
||||
execGit('add --all .');
|
||||
}
|
||||
|
||||
/**
|
||||
* Commits and pushes the current version on git
|
||||
*/
|
||||
function gitPush () {
|
||||
const version = npmGetVersion();
|
||||
let doGHRelease = false;
|
||||
|
||||
if (process.env['GH_RELEASE_GITHUB_API_TOKEN']) {
|
||||
const changes = fs.readFileSync('CHANGELOG.md', 'utf8');
|
||||
|
||||
if (changes.includes(`## ${version}`)) {
|
||||
doGHRelease = true;
|
||||
} else if (version.endsWith('.1')) {
|
||||
exitFatal(`Unable to release, no CHANGELOG entry for ${version}`);
|
||||
}
|
||||
}
|
||||
|
||||
execGit('add --all .');
|
||||
|
||||
if (fs.existsSync('docs/README.md')) {
|
||||
execGit('add --all -f docs');
|
||||
}
|
||||
|
||||
// add the skip checks for GitHub ...
|
||||
execGit(`commit --no-status --quiet -m "[CI Skip] ${version.includes('-x') ? 'bump' : 'release'}/${version.includes('-') ? 'beta' : 'stable'} ${version}
|
||||
|
||||
|
||||
skip-checks: true"`);
|
||||
|
||||
// Make sure the release commit is on top of the latest master
|
||||
execGit(`pull --rebase ${repo} master`);
|
||||
|
||||
// Now push normally
|
||||
execGit(`push ${repo} HEAD:${process.env['GITHUB_REF']}`, true);
|
||||
|
||||
if (doGHRelease) {
|
||||
const files = process.env['GH_RELEASE_FILES']
|
||||
? `--assets ${process.env['GH_RELEASE_FILES']}`
|
||||
: '';
|
||||
|
||||
execPm(`polkadot-exec-ghrelease --draft ${files} --yes`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loops through the packages/* (or root), executing the supplied
|
||||
* function for each package found
|
||||
*
|
||||
* @param {() => unknown} fn
|
||||
*/
|
||||
function loopFunc (fn) {
|
||||
if (fs.existsSync('packages')) {
|
||||
const dirs = fs
|
||||
.readdirSync('packages')
|
||||
.filter((dir) => {
|
||||
const pkgDir = path.join(process.cwd(), 'packages', dir);
|
||||
|
||||
return fs.statSync(pkgDir).isDirectory() &&
|
||||
fs.existsSync(path.join(pkgDir, 'package.json')) &&
|
||||
fs.existsSync(path.join(pkgDir, 'build'));
|
||||
});
|
||||
|
||||
topoSort(dirs)
|
||||
.forEach((dir) => {
|
||||
process.chdir(path.join('packages', dir));
|
||||
fn();
|
||||
process.chdir('../..');
|
||||
});
|
||||
} else {
|
||||
fn();
|
||||
}
|
||||
}
|
||||
|
||||
// first do infrastructure setup
|
||||
gitSetup();
|
||||
npmSetup();
|
||||
|
||||
// get flags immediate, then adjust
|
||||
getFlags();
|
||||
verBump();
|
||||
|
||||
// perform the actual CI build
|
||||
execPm('polkadot-dev-clean-build');
|
||||
execPm('lint');
|
||||
execPm('test');
|
||||
execPm('build');
|
||||
|
||||
// publish to all GH repos
|
||||
gitPush();
|
||||
denoPublish();
|
||||
bundlePublish();
|
||||
|
||||
// publish to npm
|
||||
loopFunc(npmPublish);
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { execPm, GITHUB_REPO, GITHUB_TOKEN_URL, gitSetup, logBin } from './util.mjs';
|
||||
|
||||
const repo = `${GITHUB_TOKEN_URL}/${GITHUB_REPO}.git`;
|
||||
|
||||
logBin('polkadot-ci-ghact-docs');
|
||||
|
||||
gitSetup();
|
||||
|
||||
execPm('run docs');
|
||||
execPm(`polkadot-exec-ghpages --dotfiles --repo ${repo} --dist ${process.env['GH_PAGES_SRC']} --dest .`, true);
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import fs from 'node:fs';
|
||||
|
||||
import { execGit, logBin } from './util.mjs';
|
||||
|
||||
logBin('polkadot-ci-ghpages-force');
|
||||
|
||||
// ensure we are on master
|
||||
execGit('checkout master');
|
||||
|
||||
// checkout latest
|
||||
execGit('fetch');
|
||||
execGit('checkout gh-pages');
|
||||
execGit('pull');
|
||||
execGit('checkout --orphan gh-pages-temp');
|
||||
|
||||
// ignore relevant files
|
||||
fs.writeFileSync('.gitignore', `
|
||||
.github/
|
||||
.vscode/
|
||||
.yarn/
|
||||
build/
|
||||
coverage/
|
||||
node_modules/
|
||||
packages/
|
||||
test/
|
||||
NOTES.md
|
||||
`);
|
||||
|
||||
// add
|
||||
execGit('add -A');
|
||||
execGit('commit -am "refresh history"');
|
||||
|
||||
// danger, force new
|
||||
execGit('branch -D gh-pages');
|
||||
execGit('branch -m gh-pages');
|
||||
execGit('push -f origin gh-pages');
|
||||
|
||||
// switch to master
|
||||
execGit('checkout master');
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { copyDirSync, logBin, rimrafSync } from './util.mjs';
|
||||
|
||||
logBin('polkadot-dev-build-docs');
|
||||
|
||||
let docRoot = path.join(process.cwd(), 'docs');
|
||||
|
||||
if (fs.existsSync(docRoot)) {
|
||||
docRoot = path.join(process.cwd(), 'build-docs');
|
||||
|
||||
rimrafSync(docRoot);
|
||||
copyDirSync(path.join(process.cwd(), 'docs'), docRoot);
|
||||
}
|
||||
+1518
File diff suppressed because it is too large
Load Diff
+29
@@ -0,0 +1,29 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// @ts-expect-error For scripts we don't include @types/* definitions
|
||||
import madge from 'madge';
|
||||
|
||||
import { exitFatal, logBin } from './util.mjs';
|
||||
|
||||
logBin('polkadot-dev-circular');
|
||||
|
||||
const res = await madge('./', { fileExtensions: ['ts', 'tsx'] });
|
||||
|
||||
/** @type {string[][]} */
|
||||
const circular = res.circular();
|
||||
|
||||
if (!circular.length) {
|
||||
process.stdout.write('No circular dependency found!\n');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const err = `Failed with ${circular.length} circular dependencies`;
|
||||
const all = circular
|
||||
.map((files, idx) => `${(idx + 1).toString().padStart(4)}: ${files.join(' > ')}`)
|
||||
.join('\n');
|
||||
|
||||
process.stdout.write(`\n${err}:\n\n${all}\n\n`);
|
||||
|
||||
exitFatal(err);
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { logBin, PATHS_BUILD, rimrafSync } from './util.mjs';
|
||||
|
||||
const PKGS = path.join(process.cwd(), 'packages');
|
||||
const DIRS = PATHS_BUILD.map((d) => `build${d}`);
|
||||
|
||||
logBin('polkadot-dev-clean-build');
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*
|
||||
* Retrieves all the files containing tsconfig.*.tsbuildinfo contained withing the directory
|
||||
*
|
||||
* @param {string} dir
|
||||
* @returns {string[]}
|
||||
*/
|
||||
function getPaths (dir) {
|
||||
if (!fs.existsSync(dir)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return fs
|
||||
.readdirSync(dir)
|
||||
.reduce((all, p) => {
|
||||
if (p.startsWith('tsconfig.') && p.endsWith('.tsbuildinfo')) {
|
||||
all.push(path.join(dir, p));
|
||||
}
|
||||
|
||||
return all;
|
||||
}, DIRS.map((p) => path.join(dir, p)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*
|
||||
* Removes all the specified directories
|
||||
*
|
||||
* @param {string[]} dirs
|
||||
*/
|
||||
function cleanDirs (dirs) {
|
||||
dirs.forEach((d) => rimrafSync(d));
|
||||
}
|
||||
|
||||
cleanDirs(getPaths(process.cwd()));
|
||||
|
||||
if (fs.existsSync(PKGS)) {
|
||||
cleanDirs(getPaths(PKGS));
|
||||
cleanDirs(
|
||||
fs
|
||||
.readdirSync(PKGS)
|
||||
.map((f) => path.join(PKGS, f))
|
||||
.filter((f) => fs.statSync(f).isDirectory())
|
||||
.reduce((/** @type {string[]} */ res, d) => res.concat(getPaths(d)), [])
|
||||
);
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import fs from 'node:fs';
|
||||
|
||||
import { execGit, logBin, mkdirpSync } from './util.mjs';
|
||||
|
||||
const tmpDir = 'packages/build';
|
||||
const tmpFile = `${tmpDir}/CONTRIBUTORS`;
|
||||
|
||||
logBin('polkadot-dev-contrib');
|
||||
|
||||
mkdirpSync(tmpDir);
|
||||
execGit(`shortlog master -e -n -s > ${tmpFile}`);
|
||||
|
||||
fs.writeFileSync(
|
||||
'CONTRIBUTORS',
|
||||
Object
|
||||
.entries(
|
||||
fs
|
||||
.readFileSync(tmpFile, 'utf-8')
|
||||
.split('\n')
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => !!l)
|
||||
.reduce((/** @type {Record<string, { count: number; name: string; }>} */ all, line) => {
|
||||
const [c, e] = line.split('\t');
|
||||
const count = parseInt(c, 10);
|
||||
const [name, rest] = e.split(' <');
|
||||
const isExcluded = (
|
||||
['GitHub', 'Travis CI'].some((n) => name.startsWith(n)) ||
|
||||
['>', 'action@github.com>'].some((e) => rest === e) ||
|
||||
[name, rest].some((n) => n.includes('[bot]'))
|
||||
);
|
||||
|
||||
if (!isExcluded) {
|
||||
let [email] = rest.split('>');
|
||||
|
||||
if (!all[email]) {
|
||||
email = Object.keys(all).find((k) =>
|
||||
name.includes(' ') &&
|
||||
all[k].name === name
|
||||
) || email;
|
||||
}
|
||||
|
||||
if (all[email]) {
|
||||
all[email].count += count;
|
||||
} else {
|
||||
all[email] = { count, name };
|
||||
}
|
||||
}
|
||||
|
||||
return all;
|
||||
}, {})
|
||||
)
|
||||
.sort((a, b) => {
|
||||
const diff = b[1].count - a[1].count;
|
||||
|
||||
return diff === 0
|
||||
? a[1].name.localeCompare(b[1].name)
|
||||
: diff;
|
||||
})
|
||||
.map(([email, { count, name }], i) => {
|
||||
execGit(`log master -1 --author=${email} > ${tmpFile}-${i}`);
|
||||
|
||||
const commit = fs
|
||||
.readFileSync(`${tmpFile}-${i}`, 'utf-8')
|
||||
.split('\n')[4]
|
||||
.trim();
|
||||
|
||||
return `${`${count}`.padStart(8)}\t${name.padEnd(30)}\t${commit}`;
|
||||
})
|
||||
.join('\n')
|
||||
);
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { copyDirSync, exitFatal, logBin } from './util.mjs';
|
||||
|
||||
const argv = process.argv.slice(2);
|
||||
const args = [];
|
||||
let cd = '';
|
||||
let flatten = false;
|
||||
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
switch (argv[i]) {
|
||||
case '--cd':
|
||||
cd = argv[++i];
|
||||
break;
|
||||
case '--flatten':
|
||||
flatten = true;
|
||||
break;
|
||||
default:
|
||||
args.push(argv[i]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const sources = args.slice(0, args.length - 1);
|
||||
const dest = args[args.length - 1];
|
||||
|
||||
logBin('polkadot-dev-copy-dir');
|
||||
|
||||
if (!sources || !dest) {
|
||||
exitFatal('Expected at least one <source>... and one <destination> argument');
|
||||
}
|
||||
|
||||
sources.forEach((src) =>
|
||||
copyDirSync(
|
||||
cd
|
||||
? `${cd}/${src}`
|
||||
: src,
|
||||
cd
|
||||
? `${cd}/${dest}${flatten ? '' : `/${src}`}`
|
||||
: `${dest}${flatten ? '' : `/${src}`}`
|
||||
)
|
||||
);
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { copyDirSync, execPm, exitFatal, logBin, mkdirpSync, rimrafSync } from './util.mjs';
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
logBin('polkadot-dev-copy-to');
|
||||
|
||||
if (args.length !== 1) {
|
||||
exitFatal('Expected one <destination> argument');
|
||||
}
|
||||
|
||||
const dest = path.join(process.cwd(), '..', args[0], 'node_modules');
|
||||
|
||||
if (!fs.existsSync(dest)) {
|
||||
exitFatal('Destination node_modules folder does not exist');
|
||||
}
|
||||
|
||||
// build to ensure we actually have latest
|
||||
execPm('build');
|
||||
|
||||
// map across what is available and copy it
|
||||
fs
|
||||
.readdirSync('packages')
|
||||
.map((dir) => {
|
||||
const pkgPath = path.join(process.cwd(), 'packages', dir);
|
||||
|
||||
return [pkgPath, path.join(pkgPath, 'package.json')];
|
||||
})
|
||||
.filter(([, jsonPath]) => fs.existsSync(jsonPath))
|
||||
.map(([pkgPath, json]) => [JSON.parse(fs.readFileSync(json, 'utf8')).name, pkgPath])
|
||||
.forEach(([name, pkgPath]) => {
|
||||
console.log(`*** Copying ${name} to ${dest}`);
|
||||
|
||||
const outDest = path.join(dest, name);
|
||||
|
||||
// remove the destination
|
||||
rimrafSync(outDest);
|
||||
|
||||
// create the root
|
||||
mkdirpSync(outDest);
|
||||
|
||||
// copy the build output
|
||||
copyDirSync(path.join(pkgPath, 'build'), outDest);
|
||||
|
||||
// copy node_modules, as available
|
||||
copyDirSync(path.join(pkgPath, 'node_modules'), path.join(outDest, 'node_modules'));
|
||||
});
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import fs from 'node:fs';
|
||||
|
||||
import { DENO_POL_PRE } from './util.mjs';
|
||||
|
||||
const [e, i] = fs
|
||||
.readdirSync('packages')
|
||||
.filter((p) => fs.existsSync(`packages/${p}/src/mod.ts`))
|
||||
.sort()
|
||||
.reduce((/** @type {[string[], Record<String, string>]} */ [e, i], p) => {
|
||||
e.push(`export * as ${p.replace(/-/g, '_')} from '${DENO_POL_PRE}/${p}/mod.ts';`);
|
||||
i[`${DENO_POL_PRE}/${p}/`] = `./packages/${p}/build-deno/`;
|
||||
|
||||
return [e, i];
|
||||
}, [[], {}]);
|
||||
|
||||
if (!fs.existsSync('mod.ts')) {
|
||||
fs.writeFileSync('mod.ts', `// Copyright 2017-${new Date().getFullYear()} @polkadot/dev authors & contributors\n// SPDX-License-Identifier: Apache-2.0\n\n// auto-generated via polkadot-dev-deno-map, do not edit\n\n// This is a Deno file, so we can allow .ts imports
|
||||
/* eslint-disable import/extensions */\n\n${e.join('\n')}\n`);
|
||||
}
|
||||
|
||||
if (fs.existsSync('import_map.in.json')) {
|
||||
const o = JSON.parse(fs.readFileSync('import_map.in.json', 'utf-8'));
|
||||
|
||||
Object
|
||||
.entries(o.imports)
|
||||
.forEach(([k, v]) => {
|
||||
i[k] = v;
|
||||
});
|
||||
}
|
||||
|
||||
fs.writeFileSync('import_map.json', JSON.stringify({ imports: i }, null, 2));
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import process from 'node:process';
|
||||
import yargs from 'yargs';
|
||||
|
||||
import { __dirname, execPm, GITHUB_REPO, logBin } from './util.mjs';
|
||||
|
||||
const TS_CONFIG_BUILD = true;
|
||||
|
||||
logBin('polkadot-dev-run-lint');
|
||||
|
||||
// Since yargs can also be a promise, we just relax the type here completely
|
||||
const argv = await yargs(process.argv.slice(2))
|
||||
.options({
|
||||
'skip-eslint': {
|
||||
description: 'Skips running eslint',
|
||||
type: 'boolean'
|
||||
},
|
||||
'skip-tsc': {
|
||||
description: 'Skips running tsc',
|
||||
type: 'boolean'
|
||||
}
|
||||
})
|
||||
.strict()
|
||||
.argv;
|
||||
|
||||
if (!argv['skip-eslint']) {
|
||||
// We don't want to run with fix on CI
|
||||
const extra = GITHUB_REPO
|
||||
? ''
|
||||
: '--fix';
|
||||
|
||||
execPm(`polkadot-exec-eslint ${extra} ${process.cwd()}`);
|
||||
}
|
||||
|
||||
if (!argv['skip-tsc']) {
|
||||
execPm(`polkadot-exec-tsc --noEmit --emitDeclarationOnly false --pretty${TS_CONFIG_BUILD ? ' --project tsconfig.build.json' : ''}`);
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { execNodeTs, logBin } from './util.mjs';
|
||||
|
||||
logBin('polkadot-run-node-ts');
|
||||
|
||||
execNodeTs(process.argv.slice(2).join(' '));
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import process from 'node:process';
|
||||
|
||||
import { execNodeTs, exitFatal, exitFatalEngine, importPath, logBin, readdirSync } from './util.mjs';
|
||||
|
||||
// A & B are just helpers here and in the errors below
|
||||
const EXT_A = ['spec', 'test'];
|
||||
const EXT_B = ['ts', 'tsx', 'js', 'jsx', 'cjs', 'mjs'];
|
||||
|
||||
// The actual extensions we are looking for
|
||||
const EXTS = EXT_A.reduce((/** @type {string[]} */ exts, s) => exts.concat(...EXT_B.map((e) => `.${s}.${e}`)), []);
|
||||
|
||||
logBin('polkadot-dev-run-test');
|
||||
|
||||
exitFatalEngine();
|
||||
|
||||
const cmd = [];
|
||||
const nodeFlags = [];
|
||||
const filters = [];
|
||||
|
||||
/** @type {Record<string, string[]>} */
|
||||
const filtersExcl = {};
|
||||
/** @type {Record<string, string[]>} */
|
||||
const filtersIncl = {};
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
let testEnv = 'node';
|
||||
let isDev = false;
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
switch (args[i]) {
|
||||
// when running inside a dev environment, specifically @polkadot/dev
|
||||
case '--dev-build':
|
||||
isDev = true;
|
||||
break;
|
||||
|
||||
// environment, not passed-through
|
||||
case '--env':
|
||||
if (!['browser', 'node'].includes(args[++i])) {
|
||||
throw new Error(`Invalid --env ${args[i]}, expected 'browser' or 'node'`);
|
||||
}
|
||||
|
||||
testEnv = args[i];
|
||||
break;
|
||||
|
||||
// internal flags with no params
|
||||
case '--bail':
|
||||
case '--console':
|
||||
cmd.push(args[i]);
|
||||
break;
|
||||
|
||||
// internal flags, with params
|
||||
case '--logfile':
|
||||
cmd.push(args[i]);
|
||||
cmd.push(args[++i]);
|
||||
break;
|
||||
|
||||
// node flags that could have additional params
|
||||
case '--import':
|
||||
case '--loader':
|
||||
case '--require':
|
||||
nodeFlags.push(args[i]);
|
||||
nodeFlags.push(args[++i]);
|
||||
break;
|
||||
|
||||
// any other non-flag arguments are passed-through
|
||||
default:
|
||||
if (args[i].startsWith('-')) {
|
||||
throw new Error(`Unknown flag ${args[i]} found`);
|
||||
}
|
||||
|
||||
filters.push(args[i]);
|
||||
|
||||
if (args[i].startsWith('^')) {
|
||||
const key = args[i].slice(1);
|
||||
|
||||
if (filtersIncl[key]) {
|
||||
delete filtersIncl[key];
|
||||
} else {
|
||||
filtersExcl[key] = key.split(/[\\/]/);
|
||||
}
|
||||
} else {
|
||||
const key = args[i];
|
||||
|
||||
if (filtersExcl[key]) {
|
||||
delete filtersExcl[key];
|
||||
} else {
|
||||
filtersIncl[key] = key.split(/[\\/]/);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} parts
|
||||
* @param {Record<string, string[]>} filters
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function applyFilters (parts, filters) {
|
||||
return Object
|
||||
.values(filters)
|
||||
.some((filter) =>
|
||||
parts
|
||||
.map((_, i) => i)
|
||||
.filter((i) =>
|
||||
filter[0].startsWith(':')
|
||||
? parts[i].includes(filter[0].slice(1))
|
||||
: filter.length === 1
|
||||
? parts[i].startsWith(filter[0])
|
||||
: parts[i] === filter[0]
|
||||
)
|
||||
.some((start) =>
|
||||
filter.every((f, i) =>
|
||||
parts[start + i] && (
|
||||
f.startsWith(':')
|
||||
? parts[start + i].includes(f.slice(1))
|
||||
: i === (filter.length - 1)
|
||||
? parts[start + i].startsWith(f)
|
||||
: parts[start + i] === f
|
||||
)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const files = readdirSync('packages', EXTS).filter((file) => {
|
||||
const parts = file.split(/[\\/]/);
|
||||
let isIncluded = true;
|
||||
|
||||
if (Object.keys(filtersIncl).length) {
|
||||
isIncluded = applyFilters(parts, filtersIncl);
|
||||
}
|
||||
|
||||
if (isIncluded && Object.keys(filtersExcl).length) {
|
||||
isIncluded = !applyFilters(parts, filtersExcl);
|
||||
}
|
||||
|
||||
return isIncluded;
|
||||
});
|
||||
|
||||
if (files.length === 0) {
|
||||
exitFatal(`No files matching *.{${EXT_A.join(', ')}}.{${EXT_B.join(', ')}} found${filters.length ? ` (filtering on ${filters.join(', ')})` : ''}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const allFlags = `${importPath('@polkadot/dev/scripts/polkadot-exec-node-test.mjs')} ${[...cmd, ...files].join(' ')}`;
|
||||
|
||||
nodeFlags.push('--require');
|
||||
nodeFlags.push(
|
||||
isDev
|
||||
? `./packages/dev-test/build/cjs/${testEnv}.js`
|
||||
: `@polkadot/dev-test/${testEnv}`
|
||||
);
|
||||
|
||||
execNodeTs(allFlags, nodeFlags, false, isDev ? './packages/dev-ts/build/testCached.js' : '@polkadot/dev-ts/testCached');
|
||||
} catch {
|
||||
process.exit(1);
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import yargs from 'yargs';
|
||||
|
||||
import { execPm, exitFatal, logBin } from './util.mjs';
|
||||
|
||||
/** @typedef {{ dependencies?: Record<string, string>; devDependencies?: Record<string, string>; peerDependencies?: Record<string, string>; optionalDependencies?: Record<string, string>; resolutions?: Record<string, string>; name?: string; stableVersion?: string; version: string; }} PkgJson */
|
||||
|
||||
const TYPES = ['major', 'minor', 'patch', 'pre'];
|
||||
|
||||
const [type] = (
|
||||
await yargs(process.argv.slice(2))
|
||||
.demandCommand(1)
|
||||
.argv
|
||||
)._;
|
||||
|
||||
if (typeof type !== 'string' || !TYPES.includes(type)) {
|
||||
exitFatal(`Invalid version bump "${type}", expected one of ${TYPES.join(', ')}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Record<string, string>} dependencies
|
||||
* @param {string[]} others
|
||||
* @param {string} version
|
||||
* @returns {Record<string, string>}
|
||||
*/
|
||||
function updateDependencies (dependencies, others, version) {
|
||||
return Object
|
||||
.entries(dependencies)
|
||||
.sort((a, b) => a[0].localeCompare(b[0]))
|
||||
.reduce((/** @type {Record<string, string>} */ result, [key, value]) => {
|
||||
result[key] = others.includes(key) && value !== '*'
|
||||
? value.startsWith('^')
|
||||
? `^${version}`
|
||||
: version
|
||||
: value;
|
||||
|
||||
return result;
|
||||
}, {});
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {[string, PkgJson]}
|
||||
*/
|
||||
function readCurrentPkgJson () {
|
||||
const rootPath = path.join(process.cwd(), 'package.json');
|
||||
const rootJson = JSON.parse(fs.readFileSync(rootPath, 'utf8'));
|
||||
|
||||
return [rootPath, rootJson];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} path
|
||||
* @param {unknown} json
|
||||
*/
|
||||
function writePkgJson (path, json) {
|
||||
fs.writeFileSync(path, `${JSON.stringify(json, null, 2)}\n`);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} version
|
||||
* @param {string[]} others
|
||||
* @param {string} pkgPath
|
||||
* @param {Record<String, any>} json
|
||||
*/
|
||||
function updatePackage (version, others, pkgPath, json) {
|
||||
const updated = Object
|
||||
.keys(json)
|
||||
.reduce((/** @type {Record<String, unknown>} */ result, key) => {
|
||||
if (key === 'version') {
|
||||
result[key] = version;
|
||||
} else if (['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies', 'resolutions'].includes(key)) {
|
||||
result[key] = updateDependencies(json[key], others, version);
|
||||
} else if (key !== 'stableVersion') {
|
||||
result[key] = json[key];
|
||||
}
|
||||
|
||||
return result;
|
||||
}, {});
|
||||
|
||||
writePkgJson(pkgPath, updated);
|
||||
}
|
||||
|
||||
function removeX () {
|
||||
const [rootPath, json] = readCurrentPkgJson();
|
||||
|
||||
if (!json.version?.endsWith('-x')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
json.version = json.version.replace('-x', '');
|
||||
writePkgJson(rootPath, json);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function addX () {
|
||||
const [rootPath, json] = readCurrentPkgJson();
|
||||
|
||||
if (json.version.endsWith('-x')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
json.version = json.version + '-x';
|
||||
writePkgJson(rootPath, json);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
logBin('polkadot-dev-version');
|
||||
|
||||
const isX = removeX();
|
||||
|
||||
execPm(`version ${type === 'pre' ? 'prerelease' : type}`);
|
||||
|
||||
if (isX && type === 'pre') {
|
||||
addX();
|
||||
}
|
||||
|
||||
const [rootPath, rootJson] = readCurrentPkgJson();
|
||||
|
||||
updatePackage(rootJson.version, [], rootPath, rootJson);
|
||||
|
||||
// yarn workspaces does an OOM, manual looping takes ages
|
||||
if (fs.existsSync('packages')) {
|
||||
const packages = fs
|
||||
.readdirSync('packages')
|
||||
.map((dir) => path.join(process.cwd(), 'packages', dir, 'package.json'))
|
||||
.filter((pkgPath) => fs.existsSync(pkgPath))
|
||||
.map((pkgPath) => [pkgPath, JSON.parse(fs.readFileSync(pkgPath, 'utf8'))]);
|
||||
const others = packages.map(([, json]) => json.name);
|
||||
|
||||
packages.forEach(([pkgPath, json]) => {
|
||||
updatePackage(rootJson.version, others, pkgPath, json);
|
||||
});
|
||||
}
|
||||
|
||||
execPm('install');
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import process from 'node:process';
|
||||
|
||||
import { exitFatalYarn } from './util.mjs';
|
||||
|
||||
exitFatalYarn();
|
||||
|
||||
process.exit(0);
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { importRelative } from './util.mjs';
|
||||
|
||||
await importRelative('eslint', 'eslint/bin/eslint.js');
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { importRelative } from './util.mjs';
|
||||
|
||||
const ghp = await importRelative('gh-pages', 'gh-pages/bin/gh-pages.js');
|
||||
|
||||
await ghp.default(process.argv);
|
||||
|
||||
console.log('Published');
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { importRelative } from './util.mjs';
|
||||
|
||||
await importRelative('gh-release', 'gh-release/bin/cli.js');
|
||||
+368
@@ -0,0 +1,368 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// For Node 18, earliest usable is 18.14:
|
||||
//
|
||||
// - node:test added in 18.0,
|
||||
// - run method exposed in 18.9,
|
||||
// - mock in 18.13,
|
||||
// - diagnostics changed in 18.14
|
||||
//
|
||||
// Node 16 is not supported:
|
||||
//
|
||||
// - node:test added is 16.17,
|
||||
// - run method exposed in 16.19,
|
||||
// - mock not available
|
||||
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import process from 'node:process';
|
||||
import { run } from 'node:test';
|
||||
import { isMainThread, parentPort, Worker, workerData } from 'node:worker_threads';
|
||||
|
||||
// NOTE error should be defined as "Error", however the @types/node definitions doesn't include all
|
||||
/** @typedef {{ file?: string; message?: string; }} DiagStat */
|
||||
/** @typedef {{ details: { type: string; duration_ms: number; error: { message: string; failureType: unknown; stack: string; cause: { code: number; message: string; stack: string; generatedMessage?: any; }; code: number; } }; file?: string; name: string; testNumber: number; nesting: number; }} FailStat */
|
||||
/** @typedef {{ details: { duration_ms: number }; name: string; }} PassStat */
|
||||
/** @typedef {{ diag: DiagStat[]; fail: FailStat[]; pass: PassStat[]; skip: unknown[]; todo: unknown[]; total: number; [key: string]: any; }} Stats */
|
||||
|
||||
console.time('\t elapsed :');
|
||||
|
||||
const WITH_DEBUG = false;
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
/** @type {string[]} */
|
||||
const files = [];
|
||||
|
||||
/** @type {Stats} */
|
||||
const stats = {
|
||||
diag: [],
|
||||
fail: [],
|
||||
pass: [],
|
||||
skip: [],
|
||||
todo: [],
|
||||
total: 0
|
||||
};
|
||||
/** @type {string | null} */
|
||||
let logFile = null;
|
||||
/** @type {number} */
|
||||
let startAt = 0;
|
||||
/** @type {boolean} */
|
||||
let bail = false;
|
||||
/** @type {boolean} */
|
||||
let toConsole = false;
|
||||
/** @type {number} */
|
||||
let progressRowCount = 0;
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (args[i] === '--bail') {
|
||||
bail = true;
|
||||
} else if (args[i] === '--console') {
|
||||
toConsole = true;
|
||||
} else if (args[i] === '--logfile') {
|
||||
logFile = args[++i];
|
||||
} else {
|
||||
files.push(args[i]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*
|
||||
* Performs an indent of the line (and containing lines) with the specific count
|
||||
*
|
||||
* @param {number} count
|
||||
* @param {string} str
|
||||
* @param {string} start
|
||||
* @returns {string}
|
||||
*/
|
||||
function indent (count, str = '', start = '') {
|
||||
let pre = '\n';
|
||||
|
||||
switch (count) {
|
||||
case 0:
|
||||
break;
|
||||
|
||||
case 1:
|
||||
pre += '\t';
|
||||
break;
|
||||
|
||||
case 2:
|
||||
pre += '\t\t';
|
||||
break;
|
||||
|
||||
default:
|
||||
pre += '\t\t\t';
|
||||
break;
|
||||
}
|
||||
|
||||
pre += ' ';
|
||||
|
||||
return `${pre}${start}${
|
||||
str
|
||||
.split('\n')
|
||||
.map((l) => l.trim())
|
||||
.join(`${pre}${start ? ' '.padStart(start.length, ' ') : ''}`)
|
||||
}\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {FailStat} r
|
||||
* @return {string | undefined}
|
||||
*/
|
||||
function getFilename (r) {
|
||||
if (r.file?.includes('.spec.') || r.file?.includes('.test.')) {
|
||||
return r.file;
|
||||
}
|
||||
|
||||
if (r.details.error.cause.stack) {
|
||||
const stack = r.details.error.cause.stack
|
||||
.split('\n')
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => l.startsWith('at ') && (l.includes('.spec.') || l.includes('.test.')))
|
||||
.map((l) => l.match(/\(.*:\d\d?:\d\d?\)$/)?.[0])
|
||||
.map((l) => l?.replace('(', '')?.replace(')', ''));
|
||||
|
||||
if (stack.length) {
|
||||
return stack[0];
|
||||
}
|
||||
}
|
||||
|
||||
return r.file;
|
||||
}
|
||||
|
||||
function complete () {
|
||||
process.stdout.write('\n');
|
||||
|
||||
let logError = '';
|
||||
|
||||
stats.fail.forEach((r) => {
|
||||
WITH_DEBUG && console.error(JSON.stringify(r, null, 2));
|
||||
|
||||
let item = '';
|
||||
|
||||
item += indent(1, [getFilename(r), r.name].filter((s) => !!s).join('\n'), 'x ');
|
||||
item += indent(2, `${r.details.error.failureType} / ${r.details.error.code}${r.details.error.cause.code && r.details.error.cause.code !== r.details.error.code ? ` / ${r.details.error.cause.code}` : ''}`);
|
||||
|
||||
if (r.details.error.cause.message) {
|
||||
item += indent(2, r.details.error.cause.message);
|
||||
}
|
||||
|
||||
logError += item;
|
||||
|
||||
if (r.details.error.cause.stack) {
|
||||
item += indent(2, r.details.error.cause.stack);
|
||||
}
|
||||
|
||||
process.stdout.write(item);
|
||||
});
|
||||
|
||||
if (logFile && logError) {
|
||||
try {
|
||||
fs.appendFileSync(path.join(process.cwd(), logFile), logError);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
console.log();
|
||||
console.log('\t passed ::', stats.pass.length);
|
||||
console.log('\t failed ::', stats.fail.length);
|
||||
console.log('\t skipped ::', stats.skip.length);
|
||||
console.log('\t todo ::', stats.todo.length);
|
||||
console.log('\t total ::', stats.total);
|
||||
console.timeEnd('\t elapsed :');
|
||||
console.log();
|
||||
|
||||
// The full error information can be quite useful in the case of overall failures
|
||||
if ((stats.fail.length || toConsole) && stats.diag.length) {
|
||||
/** @type {string | undefined} */
|
||||
let lastFilename = '';
|
||||
|
||||
stats.diag.forEach((r) => {
|
||||
WITH_DEBUG && console.error(JSON.stringify(r, null, 2));
|
||||
|
||||
if (typeof r === 'string') {
|
||||
console.log(r); // Node.js <= 18.14
|
||||
} else if (r.file && r.file.includes('@polkadot/dev/scripts')) {
|
||||
// Ignore internal diagnostics
|
||||
} else {
|
||||
if (lastFilename !== r.file) {
|
||||
lastFilename = r.file;
|
||||
|
||||
console.log(lastFilename ? `\n${lastFilename}::\n` : '\n');
|
||||
}
|
||||
|
||||
// Edge case: We don't need additional noise that is not useful.
|
||||
if (!r.message?.split(' ').includes('tests')) {
|
||||
console.log(`\t${r.message?.split('\n').join('\n\t')}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (toConsole) {
|
||||
stats.pass.forEach((r) => {
|
||||
console.log(`pass ${r.name} ${r.details.duration_ms} ms`);
|
||||
});
|
||||
|
||||
console.log();
|
||||
|
||||
stats.fail.forEach((r) => {
|
||||
console.log(`fail ${r.name}`);
|
||||
});
|
||||
|
||||
console.log();
|
||||
}
|
||||
|
||||
if (stats.total === 0) {
|
||||
console.error('FATAL: No tests executed');
|
||||
console.error();
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
process.exit(stats.fail.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the progress in real-time as data is passed from the worker.
|
||||
*
|
||||
* @param {string} symbol
|
||||
*/
|
||||
function printProgress (symbol) {
|
||||
if (!progressRowCount) {
|
||||
progressRowCount = 0;
|
||||
}
|
||||
|
||||
if (!startAt) {
|
||||
startAt = performance.now();
|
||||
}
|
||||
|
||||
// If starting a new row, calculate and print the elapsed time
|
||||
if (progressRowCount === 0) {
|
||||
const now = performance.now();
|
||||
const elapsed = (now - startAt) / 1000;
|
||||
const minutes = Math.floor(elapsed / 60);
|
||||
const seconds = elapsed - minutes * 60;
|
||||
|
||||
process.stdout.write(
|
||||
`${`${minutes}:${seconds.toFixed(3).padStart(6, '0')}`.padStart(11)} `
|
||||
);
|
||||
}
|
||||
|
||||
// Print the symbol with formatting
|
||||
process.stdout.write(symbol);
|
||||
|
||||
progressRowCount++;
|
||||
|
||||
// Add spaces for readability
|
||||
if (progressRowCount % 10 === 0) {
|
||||
process.stdout.write(' '); // Double space every 10 symbols
|
||||
} else if (progressRowCount % 5 === 0) {
|
||||
process.stdout.write(' '); // Single space every 5 symbols
|
||||
}
|
||||
|
||||
// If the row reaches 100 symbols, start a new row
|
||||
if (progressRowCount >= 100) {
|
||||
process.stdout.write('\n');
|
||||
progressRowCount = 0;
|
||||
}
|
||||
}
|
||||
|
||||
async function runParallel () {
|
||||
const MAX_WORKERS = Math.min(os.cpus().length, files.length);
|
||||
const chunks = Math.ceil(files.length / MAX_WORKERS);
|
||||
|
||||
try {
|
||||
// Create and manage worker threads
|
||||
const results = await Promise.all(
|
||||
Array.from({ length: MAX_WORKERS }, (_, i) => {
|
||||
const fileSubset = files.slice(i * chunks, (i + 1) * chunks);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const worker = new Worker(new URL(import.meta.url), {
|
||||
workerData: { files: fileSubset }
|
||||
});
|
||||
|
||||
worker.on('message', (message) => {
|
||||
if (message.type === 'progress') {
|
||||
printProgress(message.data);
|
||||
} else if (message.type === 'result') {
|
||||
resolve(message.data);
|
||||
}
|
||||
});
|
||||
|
||||
worker.on('error', reject);
|
||||
worker.on('exit', (code) => {
|
||||
if (code !== 0) {
|
||||
reject(new Error(`Worker stopped with exit code ${code}`));
|
||||
}
|
||||
});
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
// Aggregate results from workers
|
||||
results.forEach((result) => {
|
||||
Object.keys(stats).forEach((key) => {
|
||||
if (Array.isArray(stats[key])) {
|
||||
stats[key] = stats[key].concat(result[key]);
|
||||
} else if (typeof stats[key] === 'number') {
|
||||
stats[key] += result[key];
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
complete();
|
||||
} catch (err) {
|
||||
console.error('Error during parallel execution:', err);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
if (isMainThread) {
|
||||
console.time('\tElapsed:');
|
||||
runParallel().catch((err) => console.error(err));
|
||||
} else {
|
||||
run({ files: workerData.files, timeout: 3_600_000 })
|
||||
.on('data', () => undefined)
|
||||
.on('end', () => parentPort && parentPort.postMessage(stats))
|
||||
.on('test:coverage', () => undefined)
|
||||
.on('test:diagnostic', (/** @type {DiagStat} */data) => {
|
||||
stats.diag.push(data);
|
||||
parentPort && parentPort.postMessage({ data: stats, type: 'result' });
|
||||
})
|
||||
.on('test:fail', (/** @type {FailStat} */ data) => {
|
||||
const statFail = structuredClone(data);
|
||||
|
||||
if (data.details.error.cause?.stack) {
|
||||
statFail.details.error.cause.stack = data.details.error.cause.stack;
|
||||
}
|
||||
|
||||
stats.fail.push(statFail);
|
||||
stats.total++;
|
||||
parentPort && parentPort.postMessage({ data: 'x', type: 'progress' });
|
||||
|
||||
if (bail) {
|
||||
complete();
|
||||
}
|
||||
})
|
||||
.on('test:pass', (data) => {
|
||||
const symbol = typeof data.skip !== 'undefined' ? '>' : typeof data.todo !== 'undefined' ? '!' : '·';
|
||||
|
||||
if (symbol === '>') {
|
||||
stats.skip.push(data);
|
||||
} else if (symbol === '!') {
|
||||
stats.todo.push(data);
|
||||
} else {
|
||||
stats.pass.push(data);
|
||||
}
|
||||
|
||||
stats.total++;
|
||||
parentPort && parentPort.postMessage({ data: symbol, type: 'progress' });
|
||||
})
|
||||
.on('test:plan', () => undefined)
|
||||
.on('test:start', () => undefined);
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { execViaNode } from './util.mjs';
|
||||
|
||||
execViaNode('rollup', 'rollup/dist/bin/rollup');
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { importDirect } from './util.mjs';
|
||||
|
||||
await importDirect('tsc', 'typescript/lib/tsc.js');
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import { importDirect } from './util.mjs';
|
||||
|
||||
await importDirect('webpack', 'webpack-cli/bin/cli.js');
|
||||
@@ -0,0 +1,540 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import cp from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import process from 'node:process';
|
||||
import url from 'node:url';
|
||||
|
||||
/** @internal logging */
|
||||
const BLANK = ''.padStart(75);
|
||||
|
||||
/** CJS/ESM compatible __dirname */
|
||||
export const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
|
||||
|
||||
/** Deno prefix for externals */
|
||||
export const DENO_EXT_PRE = 'https://esm.sh';
|
||||
|
||||
/** Deno prefix for built-ins */
|
||||
export const DENO_LND_PRE = 'https://deno.land';
|
||||
|
||||
/** Deno prefix for the polkadot package */
|
||||
export const DENO_POL_PRE = `${DENO_LND_PRE}/x/polkadot`;
|
||||
|
||||
/** The GH user that we use for actions */
|
||||
export const GITHUB_USER = 'github-actions[bot]';
|
||||
|
||||
/** The GH email for actions */
|
||||
export const GITHUB_MAIL = '41898282+github-actions[bot]@users.noreply.github.com';
|
||||
|
||||
/** The GH repo link */
|
||||
export const GITHUB_REPO = process.env['GITHUB_REPOSITORY'];
|
||||
|
||||
/** The GH token */
|
||||
export const GITHUB_TOKEN = process.env['GH_PAT'];
|
||||
|
||||
/** The GH repo URL */
|
||||
export const GITHUB_TOKEN_URL = `https://${GITHUB_TOKEN}@github.com`;
|
||||
|
||||
/** Paths that we generally building to (catch-all for possible usages) */
|
||||
export const PATHS_BUILD = ['', '-cjs', '-esm'].reduce((r, a) => r.concat(['', '-babel', '-esbuild', '-swc', '-tsc'].map((b) => `${b}${a}`)), ['-deno', '-docs', '-loader', '-wasm']).sort();
|
||||
|
||||
/** Paths that are generally excluded from source operations */
|
||||
export const PATHS_EXCL = ['node_modules', ...PATHS_BUILD.map((e) => `build${e}`)];
|
||||
|
||||
/**
|
||||
* Copy a file to a target dir
|
||||
*
|
||||
* @param {string | string[]} src
|
||||
* @param {string} destDir
|
||||
**/
|
||||
export function copyFileSync (src, destDir) {
|
||||
if (Array.isArray(src)) {
|
||||
src.forEach((s) => copyFileSync(s, destDir));
|
||||
} else {
|
||||
fs.copyFileSync(src, path.join(destDir, path.basename(src)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively copies a directory to a target dir
|
||||
*
|
||||
* @param {string | string[]} src
|
||||
* @param {string} dest
|
||||
* @param {string[]} [include]
|
||||
* @param {string[]} [exclude]
|
||||
**/
|
||||
export function copyDirSync (src, dest, include, exclude) {
|
||||
if (Array.isArray(src)) {
|
||||
src.forEach((s) => copyDirSync(s, dest, include, exclude));
|
||||
} else if (!fs.existsSync(src)) {
|
||||
// it doesn't exist, so we have nothing to copy
|
||||
} else if (!fs.statSync(src).isDirectory()) {
|
||||
exitFatal(`Source ${src} should be a directory`);
|
||||
} else {
|
||||
mkdirpSync(dest);
|
||||
|
||||
fs
|
||||
.readdirSync(src)
|
||||
.forEach((file) => {
|
||||
const srcPath = path.join(src, file);
|
||||
|
||||
if (fs.statSync(srcPath).isDirectory()) {
|
||||
copyDirSync(srcPath, path.join(dest, file), include, exclude);
|
||||
} else if (!include?.length || include.some((e) => file.endsWith(e))) {
|
||||
if (!exclude || !exclude.some((e) => file.endsWith(e))) {
|
||||
copyFileSync(srcPath, dest);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a deno directory name
|
||||
*
|
||||
* @param {string} name
|
||||
* @returns {string}
|
||||
**/
|
||||
export function denoCreateDir (name) {
|
||||
// aligns with name above - since we have sub-paths, we only return
|
||||
// the actual path inside packages/* (i.e. the last part of the name)
|
||||
return name.replace('@polkadot/', '');
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*
|
||||
* Adjusts the engine setting, highest of current and requested
|
||||
*
|
||||
* @param {string} [a]
|
||||
* @param {string} [b]
|
||||
* @returns {number}
|
||||
*/
|
||||
export function engineVersionCmp (a, b) {
|
||||
const aVer = engineVersionSplit(a);
|
||||
const bVer = engineVersionSplit(b);
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
if (aVer[i] < bVer[i]) {
|
||||
return -1;
|
||||
} else if (aVer[i] > bVer[i]) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*
|
||||
* Splits a engines version, i.e. >=xx(.yy) into
|
||||
* the major/minor/patch parts
|
||||
*
|
||||
* @param {string} [ver]
|
||||
* @returns {[number, number, number]}
|
||||
*/
|
||||
export function engineVersionSplit (ver) {
|
||||
const parts = (ver || '>=0')
|
||||
.replace('v', '') // process.version returns v18.14.0
|
||||
.replace('>=', '') // engines have >= prefix
|
||||
.split('.')
|
||||
.map((e) => e.trim());
|
||||
|
||||
return [parseInt(parts[0] || '0', 10), parseInt(parts[1] || '0', 10), parseInt(parts[2] || '0', 10)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Process execution
|
||||
*
|
||||
* @param {string} cmd
|
||||
* @param {boolean} [noLog]
|
||||
**/
|
||||
export function execSync (cmd, noLog) {
|
||||
const exec = cmd
|
||||
.replace(/ {2}/g, ' ')
|
||||
.trim();
|
||||
|
||||
if (!noLog) {
|
||||
logBin(exec, true);
|
||||
}
|
||||
|
||||
cp.execSync(exec, { stdio: 'inherit' });
|
||||
}
|
||||
|
||||
/**
|
||||
* Node execution with ts support
|
||||
*
|
||||
* @param {string} cmd
|
||||
* @param {string[]} [nodeFlags]
|
||||
* @param {boolean} [noLog]
|
||||
* @param {string} [loaderPath]
|
||||
**/
|
||||
export function execNodeTs (cmd, nodeFlags = [], noLog, loaderPath = '@polkadot/dev-ts/cached') {
|
||||
const loadersGlo = [];
|
||||
const loadersLoc = [];
|
||||
const otherFlags = [];
|
||||
|
||||
for (let i = 0; i < nodeFlags.length; i++) {
|
||||
const flag = nodeFlags[i];
|
||||
|
||||
if (['--import', '--loader', '--require'].includes(flag)) {
|
||||
const arg = nodeFlags[++i];
|
||||
|
||||
// We split the loader arguments based on type in execSync. The
|
||||
// split here is to extract the various provided types:
|
||||
//
|
||||
// 1. Global loaders are added first, then
|
||||
// 2. Our specific dev-ts loader is added, then
|
||||
// 3. Any provided local loaders are added
|
||||
//
|
||||
// The ordering requirement here is driven from the use of global
|
||||
// loaders inside the apps repo (specifically extensionless), while
|
||||
// ensuring we don't break local loader usage in the wasm repo
|
||||
if (arg.startsWith('.')) {
|
||||
loadersLoc.push(flag);
|
||||
loadersLoc.push(arg);
|
||||
} else {
|
||||
loadersGlo.push(flag);
|
||||
loadersGlo.push(arg);
|
||||
}
|
||||
} else {
|
||||
otherFlags.push(flag);
|
||||
}
|
||||
}
|
||||
|
||||
execSync(`${process.execPath} ${otherFlags.join(' ')} --no-warnings --enable-source-maps ${loadersGlo.join(' ')} --loader ${loaderPath} ${loadersLoc.join(' ')} ${cmd}`, noLog);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the git command
|
||||
*
|
||||
* @param {string} cmd
|
||||
* @param {boolean} [noLog]
|
||||
**/
|
||||
export function execGit (cmd, noLog) {
|
||||
execSync(`git ${cmd}`, noLog);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute the package manager (yarn by default)
|
||||
*
|
||||
* @param {string} cmd
|
||||
* @param {boolean} [noLog]
|
||||
**/
|
||||
export function execPm (cmd, noLog) {
|
||||
// It could be possible to extends this to npm/pnpm, but the package manager
|
||||
// arguments are not quite the same between them, so we may need to do mangling
|
||||
// and adjust to convert yarn-isms to the specific target.
|
||||
//
|
||||
// Instead of defaulting here, we could possibly use process.env['npm_execpath']
|
||||
// to determine the package manager which would work in most (???) cases where the
|
||||
// top-level has been executed via a package manager and the env is set - no bets
|
||||
// atm for what happens when execSync/fork is used
|
||||
//
|
||||
// TL;DR Not going to spend effort on this, but quite possibly there is an avenue
|
||||
// to support other package managers, aka pick-your-poison
|
||||
execSync(`yarn ${cmd}`, noLog);
|
||||
}
|
||||
|
||||
/**
|
||||
* Node binary execution
|
||||
*
|
||||
* @param {string} name
|
||||
* @param {string} cmd
|
||||
**/
|
||||
export function execViaNode (name, cmd) {
|
||||
logBin(name);
|
||||
|
||||
execSync(`${importPath(cmd)} ${process.argv.slice(2).join(' ')}`, true);
|
||||
}
|
||||
|
||||
/** A consistent setup for git variables */
|
||||
export function gitSetup () {
|
||||
execGit(`config user.name "${GITHUB_USER}"`);
|
||||
execGit(`config user.email "${GITHUB_MAIL}"`);
|
||||
|
||||
execGit('config push.default simple');
|
||||
execGit('config merge.ours.driver true');
|
||||
|
||||
execGit('checkout master');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an absolute import path into node_modules from a
|
||||
* <this module> module name
|
||||
*
|
||||
* @param {string} req
|
||||
* @returns {string}
|
||||
**/
|
||||
export function importPath (req) {
|
||||
return path.join(process.cwd(), 'node_modules', req);
|
||||
}
|
||||
|
||||
/**
|
||||
* Do an async import
|
||||
*
|
||||
* @param {string} bin
|
||||
* @param {string} req
|
||||
* @returns {Promise<any>}
|
||||
**/
|
||||
export async function importDirect (bin, req) {
|
||||
logBin(bin);
|
||||
|
||||
try {
|
||||
const mod = await import(req);
|
||||
|
||||
return mod;
|
||||
} catch (/** @type {any} */ error) {
|
||||
exitFatal(`Error importing ${req}`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Do a relative async import
|
||||
*
|
||||
* @param {string} bin
|
||||
* @param {string} req
|
||||
* @returns {Promise<any>}
|
||||
**/
|
||||
export function importRelative (bin, req) {
|
||||
return importDirect(bin, importPath(req));
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs the binary name with the calling args
|
||||
*
|
||||
* @param {string} bin
|
||||
* @param {boolean} [noArgs]
|
||||
*/
|
||||
export function logBin (bin, noArgs) {
|
||||
const extra = noArgs
|
||||
? ''
|
||||
: process.argv.slice(2).join(' ');
|
||||
|
||||
console.log(`$ ${bin} ${extra}`.replace(/ {2}/g, ' ').trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* Do a mkdirp (no global support, native)
|
||||
*
|
||||
* @param {string} dir
|
||||
**/
|
||||
export function mkdirpSync (dir) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete the ful path (no glob support)
|
||||
*
|
||||
* @param {string} dir
|
||||
**/
|
||||
export function rimrafSync (dir) {
|
||||
if (fs.existsSync(dir)) {
|
||||
fs.rmSync(dir, { force: true, recursive: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively reads a directory, making a list of the matched extensions
|
||||
*
|
||||
* @param {string} src
|
||||
* @param {string[]} extensions
|
||||
* @param {string[]} [files]
|
||||
**/
|
||||
export function readdirSync (src, extensions, files = []) {
|
||||
if (!fs.statSync(src).isDirectory()) {
|
||||
exitFatal(`Source ${src} should be a directory`);
|
||||
}
|
||||
|
||||
fs
|
||||
.readdirSync(src)
|
||||
.forEach((file) => {
|
||||
const srcPath = path.join(src, file);
|
||||
|
||||
if (fs.statSync(srcPath).isDirectory()) {
|
||||
if (!PATHS_EXCL.includes(file)) {
|
||||
readdirSync(srcPath, extensions, files);
|
||||
}
|
||||
} else if (extensions.some((e) => file.endsWith(e))) {
|
||||
files.push(srcPath);
|
||||
}
|
||||
});
|
||||
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prints the fatal error message and exit with a non-zero return code
|
||||
*
|
||||
* @param {string} message
|
||||
* @param {Error} [error]
|
||||
* @returns {never}
|
||||
**/
|
||||
export function exitFatal (message, error) {
|
||||
console.error();
|
||||
console.error('FATAL:', message);
|
||||
|
||||
if (error) {
|
||||
console.error();
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
console.error();
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks for Node version with a fatal exit code
|
||||
*/
|
||||
export function exitFatalEngine () {
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf-8'));
|
||||
|
||||
if (engineVersionCmp(process.version, pkg.engines?.node) === -1) {
|
||||
console.error(
|
||||
`${BLANK}\n FATAL: At least Node version ${pkg.engines.node} is required for development.\n${BLANK}`
|
||||
);
|
||||
|
||||
console.error(`
|
||||
Technical explanation: For a development environment all projects in
|
||||
the @polkadot famility uses node:test in their operation. Currently the
|
||||
minimum required version of Node is thus set at the first first version
|
||||
with operational support, hence this limitation. Additionally only LTS
|
||||
Node versions are supported.
|
||||
|
||||
LTS Node versions are detailed on https://nodejs.dev/en/about/releases/
|
||||
|
||||
`);
|
||||
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks for yarn usage with a fatal exit code
|
||||
*/
|
||||
export function exitFatalYarn () {
|
||||
if (!process.env['npm_execpath']?.includes('yarn')) {
|
||||
console.error(
|
||||
`${BLANK}\n FATAL: The use of yarn is required, install via npm is not supported.\n${BLANK}`
|
||||
);
|
||||
console.error(`
|
||||
Technical explanation: All the projects in the @polkadot' family use
|
||||
yarn specific configs and assume yarn for build operations and locks.
|
||||
|
||||
If yarn is not available, you can get it from https://yarnpkg.com/
|
||||
|
||||
`);
|
||||
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Topological sort of dependencies. It handles circular deps by placing them at the end
|
||||
* of the sorted array from circular dep with the smallest vertices to the greatest vertices.
|
||||
*
|
||||
* Credit to: https://gist.github.com/shinout/1232505 (Parts of this were used as a starting point for the structure of the topoSort)
|
||||
*
|
||||
* @param {string[]} dirs
|
||||
*/
|
||||
export function topoSort (dirs) {
|
||||
/** @type {Record<string, Node>} */
|
||||
const nodes = {};
|
||||
/** @type {string[]} */
|
||||
const sorted = [];
|
||||
/** @type {Record<string, boolean>} */
|
||||
const visited = {};
|
||||
/** @type {Record<string, Node>} */
|
||||
const circular = {};
|
||||
|
||||
if (dirs.length === 1) {
|
||||
return dirs;
|
||||
}
|
||||
|
||||
class Node {
|
||||
/** @param {string} id */
|
||||
constructor (id) {
|
||||
this.id = id;
|
||||
/** @type {string[]} */
|
||||
this.vertices = [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {*} key
|
||||
* @param {string[]} ancestors
|
||||
* @returns
|
||||
*/
|
||||
function cb (key, ancestors) {
|
||||
const node = nodes[key];
|
||||
const id = node.id;
|
||||
|
||||
if (visited[key]) {
|
||||
return;
|
||||
}
|
||||
|
||||
ancestors.push(id);
|
||||
visited[key] = true;
|
||||
|
||||
node.vertices.forEach((i) => {
|
||||
if (ancestors.indexOf(i) >= 0) {
|
||||
console.log('CIRCULAR: closed chain : ' + i + ' is in ' + id);
|
||||
|
||||
if (nodes[id].vertices.includes(i)) {
|
||||
circular[id] = nodes[id];
|
||||
}
|
||||
|
||||
circular[i] = nodes[i];
|
||||
}
|
||||
|
||||
cb(i.toString(), ancestors.map((v) => v));
|
||||
});
|
||||
|
||||
if (!circular[id]) {
|
||||
sorted.push(id);
|
||||
}
|
||||
}
|
||||
|
||||
// Build edges
|
||||
const edges = dirs.map((dir) => {
|
||||
const json = fs.readFileSync(path.join('packages', dir, 'package.json'), 'utf8');
|
||||
const deps = JSON.parse(json).dependencies;
|
||||
|
||||
return dirs
|
||||
.filter((d) => d !== dir && deps && Object.keys(deps).includes(`@polkadot/${d}`))
|
||||
.map((d) => [dir, d]);
|
||||
}).flat();
|
||||
|
||||
edges.forEach((v) => {
|
||||
const from = v[0]; const to = v[1];
|
||||
|
||||
if (!nodes[from]) {
|
||||
nodes[from] = new Node(from);
|
||||
}
|
||||
|
||||
if (!nodes[to]) {
|
||||
nodes[to] = new Node(to);
|
||||
}
|
||||
|
||||
nodes[from].vertices.push(to);
|
||||
});
|
||||
|
||||
const keys = Object.keys(nodes);
|
||||
|
||||
for (const key of keys) {
|
||||
cb(key, []);
|
||||
}
|
||||
|
||||
const circularSorted = Object.keys(circular)
|
||||
.sort((a, b) => circular[a].vertices.length < circular[b].vertices.length ? -1 : 1);
|
||||
|
||||
const flattenedEdges = edges.flat();
|
||||
// Packages that have no edges
|
||||
/** @type {string[]} */
|
||||
const standAlones = dirs.filter((d) => !flattenedEdges.includes(d));
|
||||
|
||||
return sorted.concat(circularSorted).concat(standAlones);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"module": "commonjs"
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
module.exports = { foo: 'bar' };
|
||||
@@ -0,0 +1,4 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export default [];
|
||||
@@ -0,0 +1,6 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export {};
|
||||
|
||||
throw new Error('@polkadot/dev is not meant to be imported via root. Rather if provides a set of shared dependencies, a collection of scripts, base configs and some loaders accessed via the scripts. It is only meant to be used as a shared resource by all @polkadot/* projects');
|
||||
@@ -0,0 +1,12 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import './index.js';
|
||||
|
||||
import rollupAlias from '@rollup/plugin-alias';
|
||||
import eslint from 'eslint/use-at-your-own-risk';
|
||||
import nodeCrypto from 'node:crypto';
|
||||
|
||||
console.log(' eslint::', typeof eslint !== 'undefined');
|
||||
console.log(' nodeCrypto::', typeof nodeCrypto !== 'undefined');
|
||||
console.log('rollupAlias::', typeof rollupAlias !== 'undefined');
|
||||
@@ -0,0 +1,6 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Do not edit, auto-generated by @polkadot/dev
|
||||
|
||||
export const packageInfo = { name: '@polkadot/dev', path: 'auto', type: 'auto', version: '0.84.2' };
|
||||
@@ -0,0 +1,6 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export * from './rootJs/index.js';
|
||||
|
||||
export const TEST_PURE = /*#__PURE__*/ 'testRoot';
|
||||
@@ -0,0 +1,14 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import type * as testRoot from './root.js';
|
||||
|
||||
// NOTE We don't use ts-expect-error here since the build folder may or may
|
||||
// not exist (so the error may or may not be there)
|
||||
//
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore This should only run against the compiled ouput, where this should exist
|
||||
import testRootBuild from '../build/cjs/root.js';
|
||||
import { runTests } from './rootTests.js';
|
||||
|
||||
runTests(testRootBuild as unknown as typeof testRoot);
|
||||
@@ -0,0 +1,159 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
/// <reference types="@polkadot/dev-test/globals.d.ts" />
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import * as testRoot from './root.js';
|
||||
import { runTests } from './rootTests.js';
|
||||
|
||||
runTests(testRoot);
|
||||
|
||||
describe('as-built output checks', (): void => {
|
||||
const buildRoot = path.join(process.cwd(), 'packages/dev/build');
|
||||
const buildFiles = fs.readdirSync(buildRoot);
|
||||
|
||||
describe('build outputs', (): void => {
|
||||
it('does not contain the *.spec.ts/js files', (): void => {
|
||||
expect(
|
||||
buildFiles.filter((f) => f.includes('.spec.'))
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not contain the rootRust folder', (): void => {
|
||||
expect(
|
||||
buildFiles.filter((f) => f.includes('rootRust'))
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it('has the static files copied (non-duplicated)', (): void => {
|
||||
expect(
|
||||
fs.existsSync(path.join(buildRoot, 'rootStatic/kusama.svg'))
|
||||
).toBe(true);
|
||||
expect(
|
||||
fs.existsSync(path.join(buildRoot, 'cjs/rootStatic/kusama.svg'))
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('does not have stand-alone d.ts files copied', (): void => {
|
||||
expect(
|
||||
fs.existsSync(path.join(buildRoot, 'rootJs/test.json.d.ts'))
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('does have cjs + d.ts files copied', (): void => {
|
||||
expect(
|
||||
fs.existsSync(path.join(process.cwd(), 'packages/dev-test/build/globals.d.ts'))
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('code generation', (): void => {
|
||||
const jsIdx = {
|
||||
cjs: fs.readFileSync(path.join(buildRoot, 'cjs/rootJs/index.js'), { encoding: 'utf-8' }),
|
||||
esm: fs.readFileSync(path.join(buildRoot, 'rootJs/index.js'), { encoding: 'utf-8' })
|
||||
} as const;
|
||||
const idxTypes = Object.keys(jsIdx) as (keyof typeof jsIdx)[];
|
||||
|
||||
describe('numeric seperators', (): void => {
|
||||
idxTypes.forEach((type) =>
|
||||
it(`does not conatin them & has the value in ${type}`, (): void => {
|
||||
expect(
|
||||
jsIdx[type].includes('123_456_789n')
|
||||
).toBe(false);
|
||||
expect(
|
||||
jsIdx[type].includes('123456789n')
|
||||
).toBe(true);
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
describe('dynamic imports', (): void => {
|
||||
idxTypes.forEach((type) =>
|
||||
it(`contains import(...) in ${type}`, (): void => {
|
||||
expect(
|
||||
jsIdx[type].includes("const { sum } = await import('@polkadot/dev/rootJs/dynamic.mjs');")
|
||||
).toBe(true);
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
describe('type assertions', (): void => {
|
||||
idxTypes.forEach((type) =>
|
||||
it(`contains import(...) in ${type}`, (): void => {
|
||||
expect(
|
||||
jsIdx[type].includes(
|
||||
type === 'cjs'
|
||||
? 'require("@polkadot/dev/rootJs/testJson.json")'
|
||||
// eslint-disable-next-line no-useless-escape
|
||||
: "import testJson from '@pezkuwi/dev/rootJs/testJson.json' assert { type: \'json\' };"
|
||||
)
|
||||
).toBe(true);
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('commonjs', (): void => {
|
||||
const cjsRoot = path.join(buildRoot, 'cjs');
|
||||
|
||||
it('contains commonjs package.js inside cjs', (): void => {
|
||||
expect(
|
||||
fs
|
||||
.readFileSync(path.join(cjsRoot, 'package.json'), { encoding: 'utf-8' })
|
||||
.includes('"type": "commonjs"')
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('contains cjs/sample.js', (): void => {
|
||||
expect(
|
||||
fs
|
||||
.readFileSync(path.join(cjsRoot, 'sample.js'), { encoding: 'utf-8' })
|
||||
.includes("module.exports = { foo: 'bar' };")
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deno', (): void => {
|
||||
const denoRoot = path.join(process.cwd(), 'packages/dev/build-deno');
|
||||
const denoMod = fs.readFileSync(path.join(denoRoot, 'mod.ts'), 'utf-8');
|
||||
|
||||
it('has *.ts imports', (): void => {
|
||||
expect(
|
||||
denoMod.includes("import './index.ts';")
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('has node: imports', (): void => {
|
||||
expect(
|
||||
denoMod.includes("import nodeCrypto from 'node:crypto';")
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('has deno.land/x imports', (): void => {
|
||||
expect(
|
||||
fs
|
||||
.readFileSync(path.join(denoRoot, 'rootJs/augmented.ts'))
|
||||
.includes("declare module 'https://deno.land/x/polkadot/dev/types.ts' {")
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
// See https://github.com/denoland/deno/issues/18557
|
||||
// NOTE: When available, the toBe(false) should be toBe(true)
|
||||
describe.todo('npm: prefixes', (): void => {
|
||||
it('has npm: imports', (): void => {
|
||||
expect(
|
||||
/import rollupAlias from 'npm:@rollup\/plugin-alias@\^\d\d?\.\d\d?\.\d\d?';/.test(denoMod)
|
||||
).toBe(false); // true);
|
||||
});
|
||||
|
||||
it('has npm: imports with paths', (): void => {
|
||||
expect(
|
||||
/import eslint from 'npm:eslint@\^\d\d?\.\d\d?\.\d\d?\/use-at-your-own-risk';/.test(denoMod)
|
||||
).toBe(false); // true);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export class Clazz {
|
||||
#something = 123_456_789;
|
||||
|
||||
readonly and: number;
|
||||
|
||||
static staticProperty = 'foobar';
|
||||
static staticFunction = (): string|null => Clazz.staticProperty;
|
||||
|
||||
/**
|
||||
* @param and the number we should and with
|
||||
*/
|
||||
constructor (and: number) {
|
||||
this.and = and;
|
||||
this.#something = this.#something & and;
|
||||
}
|
||||
|
||||
get something (): number {
|
||||
return this.#something;
|
||||
}
|
||||
|
||||
async doAsync (): Promise<boolean> {
|
||||
const res = await new Promise<boolean>((resolve) => resolve(true));
|
||||
|
||||
console.log(res);
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @description Sets something to something
|
||||
* @param something The addition
|
||||
*/
|
||||
setSomething = (something?: number): number => {
|
||||
this.#something = (something ?? 123_456) & this.and;
|
||||
|
||||
return this.#something;
|
||||
};
|
||||
|
||||
toString (): string {
|
||||
return `something=${this.#something}`;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
/// <reference types="@polkadot/dev-test/globals.d.ts" />
|
||||
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import { strict as assert } from 'node:assert';
|
||||
import React from 'react';
|
||||
|
||||
import Jsx from './Jsx.js';
|
||||
|
||||
describe('react testing', () => {
|
||||
it('shows the children when the checkbox is checked', () => {
|
||||
const testMessage = 'Test Message';
|
||||
|
||||
render(<Jsx>{testMessage}</Jsx>);
|
||||
|
||||
assert.equal(screen.queryByText(testMessage), null);
|
||||
|
||||
fireEvent.click(screen.getByLabelText(/show/i));
|
||||
|
||||
assert.notEqual(screen.getByText(testMessage), null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
// Adapted from https://github.com/testing-library/react-testing-library#basic-example
|
||||
|
||||
import type { Props } from './JsxChild.js';
|
||||
|
||||
import React, { useCallback, useState } from 'react';
|
||||
import { styled } from 'styled-components';
|
||||
|
||||
import Child from './JsxChild.js';
|
||||
|
||||
function Hidden ({ children, className }: Props): React.ReactElement<Props> {
|
||||
const [isMessageVisible, setMessageVisibility] = useState(false);
|
||||
|
||||
const onShow = useCallback(
|
||||
(e: React.ChangeEvent<HTMLInputElement>) =>
|
||||
setMessageVisibility(e.target.checked),
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<StyledDiv className={className}>
|
||||
<label htmlFor='toggle'>Show Message</label>
|
||||
<input
|
||||
checked={isMessageVisible}
|
||||
id='toggle'
|
||||
onChange={onShow}
|
||||
type='checkbox'
|
||||
/>
|
||||
{isMessageVisible && (
|
||||
<>
|
||||
{children}
|
||||
<Child label='hello' />
|
||||
</>
|
||||
)}
|
||||
</StyledDiv>
|
||||
);
|
||||
}
|
||||
|
||||
const StyledDiv = styled.div`
|
||||
background: red;
|
||||
`;
|
||||
|
||||
export default React.memo(Hidden);
|
||||
@@ -0,0 +1,20 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import React from 'react';
|
||||
|
||||
export interface Props {
|
||||
children?: React.ReactNode;
|
||||
className?: string;
|
||||
label?: string;
|
||||
}
|
||||
|
||||
function Child ({ children, className, label }: Props): React.ReactElement<Props> {
|
||||
return (
|
||||
<div className={className}>
|
||||
{label || ''}{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default React.memo(Child);
|
||||
@@ -0,0 +1,13 @@
|
||||
// Auto-generated via `yarn polkadot-types-from-chain`, do not edit
|
||||
/* eslint-disable */
|
||||
|
||||
/** This tests augmentation outputs, e.g. as used in the polkadot-js/api */
|
||||
|
||||
export interface Something {
|
||||
bar: string;
|
||||
foo: string;
|
||||
}
|
||||
|
||||
declare module '@polkadot/dev/types' {
|
||||
const blah: string;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
/**
|
||||
* Returns the sum of 2 numbers
|
||||
*
|
||||
* @param {number} a
|
||||
* @param {number} b
|
||||
* @returns {number}
|
||||
*/
|
||||
export function sum (a, b) {
|
||||
return a + b;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
/** This should appear as-is in the output with: 1. extension added, 2. augmented.d.ts correct */
|
||||
import './augmented.js';
|
||||
|
||||
/** This import should appear as-in in the ouput (cjs without asserts) */
|
||||
import testJson from '@pezkuwi/dev/rootJs/testJson.json' assert { type: 'json' };
|
||||
|
||||
/** Double double work, i.e. re-exports */
|
||||
export { Clazz } from './Clazz.js';
|
||||
|
||||
/** Function to ensure that BigInt does not have the Babel Math.pow() transform */
|
||||
export function bigIntExp (): bigint {
|
||||
// 123_456n * 137_858_491_849n
|
||||
return 123_456_789n * (13n ** 10n);
|
||||
}
|
||||
|
||||
/** Function to ensure that dynamic imports work */
|
||||
export async function dynamic (a: number, b: number): Promise<number> {
|
||||
// NOTE we go via this path so it points to the same location in both ESM
|
||||
// and CJS output (a './dynamic' import would be different otherwise)
|
||||
const { sum } = await import('@polkadot/dev/rootJs/dynamic.mjs');
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||
return sum(a, b);
|
||||
}
|
||||
|
||||
/** Function to ensure we have json correctly imported */
|
||||
export function json (): string {
|
||||
return testJson.test.json;
|
||||
}
|
||||
|
||||
/** Check support for the ?? operator */
|
||||
export function jsOpExp (a?: number): number {
|
||||
const defaults = {
|
||||
a: 42,
|
||||
b: 43,
|
||||
c: 44
|
||||
};
|
||||
|
||||
return a ?? defaults.a;
|
||||
}
|
||||
|
||||
/** This is an actual check to ensure PURE is all-happy */
|
||||
export const pureOpExp = /*#__PURE__*/ jsOpExp();
|
||||
|
||||
const fooA = 1;
|
||||
const fooB = 2;
|
||||
const fooC = 3;
|
||||
const fooD = 4;
|
||||
|
||||
export { fooA, fooB, fooC, fooD };
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
/** This file should not be in the compiled output */
|
||||
|
||||
declare module './testJson.json' {
|
||||
declare let contents: { test: { json: 'works' } };
|
||||
export default contents;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"test": {
|
||||
"json": "works"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
/// this should not appear in the final output
|
||||
@@ -0,0 +1 @@
|
||||
/// this should not appear in the final output
|
||||
@@ -0,0 +1,8 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
import * as testRoot from './root.js';
|
||||
import { runTests } from './rootTests.js';
|
||||
|
||||
/** This is run against the sources */
|
||||
runTests(testRoot);
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 441 441"><defs><style>.cls-1{stroke:#000;stroke-miterlimit:10;}.cls-2{fill:#fff;}</style></defs><title>kusama-ksm-logo</title><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><rect class="cls-1" x="0.5" y="0.5" width="440" height="440"/><path class="cls-2" d="M373.6,127.4c-5.2-4.1-11.4-9.7-22.7-11.1-10.6-1.4-21.4,5.7-28.7,10.4s-21.1,18.5-26.8,22.7-20.3,8.1-43.8,22.2-115.7,73.3-115.7,73.3l24,.3-107,55.1H63.6L48.2,312s13.6,3.6,25-3.6v3.3s127.4-50.2,152-37.2l-15,4.4c1.3,0,25.5,1.6,25.5,1.6a34.34,34.34,0,0,0,15.4,24.8c14.6,9.6,14.9,14.9,14.9,14.9s-7.6,3.1-7.6,7c0,0,11.2-3.4,21.6-3.1a82.64,82.64,0,0,1,19.5,3.1s-.8-4.2-10.9-7-20.1-13.8-25-19.8a28,28,0,0,1-4.1-27.4c3.5-9.1,15.7-14.1,40.9-27.1,29.7-15.4,36.5-26.8,40.7-35.7s10.4-26.6,13.9-34.9c4.4-10.7,9.8-16.4,14.3-19.8s24.5-10.9,24.5-10.9S378.5,131.3,373.6,127.4Z"/></g></g></svg>
|
||||
|
After Width: | Height: | Size: 912 B |
@@ -0,0 +1,60 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
/// <reference types="@polkadot/dev-test/globals.d.ts" />
|
||||
|
||||
/* global describe, expect, it */
|
||||
|
||||
import type * as testRoot from './root.js';
|
||||
|
||||
export function runTests ({ Clazz, TEST_PURE, bigIntExp, dynamic, jsOpExp, json }: typeof testRoot): void {
|
||||
describe('Clazz', (): void => {
|
||||
it('has staticProperty', (): void => {
|
||||
expect(Clazz.staticProperty).toBe('foobar');
|
||||
});
|
||||
|
||||
it('creates an instance with get/set', (): void => {
|
||||
const c = new Clazz(456);
|
||||
|
||||
expect(c.something).toBe(123_456_789 & 456);
|
||||
|
||||
c.setSomething(123);
|
||||
|
||||
expect(c.something).toBe(123 & 456);
|
||||
});
|
||||
});
|
||||
|
||||
describe('TEST_PURE', (): void => {
|
||||
it('should have the correct value', (): void => {
|
||||
expect(TEST_PURE).toBe('testRoot');
|
||||
});
|
||||
});
|
||||
|
||||
describe('dynamic()', (): void => {
|
||||
it('should allow dynamic import usage', async (): Promise<void> => {
|
||||
expect(await dynamic(5, 37)).toBe(42);
|
||||
});
|
||||
});
|
||||
|
||||
describe('bigIntExp()', (): void => {
|
||||
it('should return the correct value', (): void => {
|
||||
expect(bigIntExp()).toBe(123_456_789n * 137_858_491_849n);
|
||||
});
|
||||
});
|
||||
|
||||
describe('jsOpExp', (): void => {
|
||||
it('handles 0 ?? 42 correctly', (): void => {
|
||||
expect(jsOpExp(0)).toBe(0);
|
||||
});
|
||||
|
||||
it('handles undefined ?? 42 correctly', (): void => {
|
||||
expect(jsOpExp()).toBe(42);
|
||||
});
|
||||
});
|
||||
|
||||
describe('json()', (): void => {
|
||||
it('should return the correct value', (): void => {
|
||||
expect(json()).toBe('works');
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Copyright 2017-2025 @polkadot/dev authors & contributors
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
export type EchoString = string;
|
||||
|
||||
export type BlahType = number;
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "..",
|
||||
"outDir": "./build",
|
||||
"rootDir": "./src"
|
||||
},
|
||||
"exclude": [
|
||||
"**/mod.ts",
|
||||
"**/*.spec.ts",
|
||||
"**/*.spec.tsx"
|
||||
],
|
||||
"include": [
|
||||
"src/**/*",
|
||||
"src/**/*.json"
|
||||
],
|
||||
"references": []
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "..",
|
||||
"outDir": "./build",
|
||||
"rootDir": "./config",
|
||||
"emitDeclarationOnly": false,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"config/**/*"
|
||||
],
|
||||
"references": []
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "..",
|
||||
"outDir": "./build",
|
||||
"rootDir": "./scripts",
|
||||
"emitDeclarationOnly": false,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"scripts/**/*"
|
||||
],
|
||||
"references": []
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": "..",
|
||||
"outDir": "./build",
|
||||
"rootDir": "./src",
|
||||
"emitDeclarationOnly": false,
|
||||
"noEmit": true
|
||||
},
|
||||
"include": [
|
||||
"**/*.spec.ts",
|
||||
"**/*.spec.tsx"
|
||||
],
|
||||
"references": [
|
||||
{ "path": "../dev/tsconfig.build.json" },
|
||||
{ "path": "../dev-test/tsconfig.build.json" }
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user