open-index/open-npm huggingface dataset:
npm package: @ms-aria/tslint-config-aria
Description: A set of rules to standardize when writing TS code.
Author: Aria Engineering - Portal
Latest version: 4.2.0

# Aria TSLint configuration

The following are a set of guidelines that the Aria team uses when working with TypeScript. Most of these rules follow the standards
provided by both [tslint-eslint-rules](https://github.com/buzinas/tslint-eslint-rules) and [tslint:recommended](https://github.com/palantir/tslint/blob/master/src/configs/recommended.ts). Then, I have added some extra rules so that we are mostly compliant
with [AirBnB's config rules](https://github.com/progre/tslint-config-airbnb). I have left out rules as defined by [tslint-microsoft-contrib](https://github.com/Microsoft/tslint-microsoft-contrib) and [tslint-consistent-codestyle](https://www.npmjs.com/package/tslint-consistent-codestyle) as
we gained very little in adding them and paid a lot on increasing the size of this package.

## How to modify the rules

The following steps need to be taken into account:

1. Make the change in the `tslint.js` file.
2. Update the changes in the changelog. Mark breaking changes and non-breaking changes, or new features as appropriate.
3. Following semantic versioning rules, update the library version.

**Important**
After the PR is completed, update master and run the `npm publish` command to push the newest version to NPM.
npm package: @ms-cloudpack/app-server
Description: Internal app server for Cloudpack
Latest version: 0.20.66

# @ms-cloudpack/app-server

This package provides an app server for Cloudpack. The app server is an Express server which hosts the appropriate routes for the web app, primarily returning HTML content which loads resources from the bundle server. The app server can support whichever routes the app needs and also serve static paths.
npm package: @ms-cloudpack/bundler
Description: An abstraction to bundle source code.
Latest version: 0.27.28

# @ms-cloudpack/bundler

This library provides Cloudpack's implementation of an abstraction on bundling a package, assuming that the package is conformant.

Rather than directly depending on Webpack, rollup, or esbuild with large amounts of custom configuration, having an abstraction around bundling provides constraints around having common inputs/outputs.

This enforces the code follow consistent constraints, while also ensuring the output can be consumed in the browser or in node depending on supported environments.

Abstraction also allows us to use the right tool for the job. The right tool depends on priorities and capabilities. For dev builds we want the fastest tool, while for production we want optimal output.

## Details

The Cloudpack bundler abstraction is simple and constrained on purpose:

1. Consume a standard package (app or library) with a minimum set of requirements.
2. Emits standard ESM bundle.
3. Leverages package.json and convention as much as possible:

There are three output modes:

- library mode - produces a bundle of source which externalizes dependencies and is directly consumable by the target (browser or node), which can resolve the dependencies through an import map in the browser or through module resolution in node. The source is unminified.
- production mode - produces a bundle of minified source which includes dependencies and is also similarly consumed.
- development mode - like production mode, but not minified.
npm package: @ms-cloudpack/bundler-ori
Description: Cloudpack's wrapper for the ori bundler
Latest version: 0.3.33

# @ms-cloudpack/bundler-ori

Provides a Cloudpack bundler plugin around the [`oribuild`](https://www.npmjs.com/package/oribuild) package, which itself is a wrapper around esbuild+native plugins. This creates a really fast bundler inner loop pipeline for serving large enterprise web applications.
npm package: @ms-cloudpack/bundler-plugin-ori
Description: An abstraction to bundle source code using ori.
Latest version: 0.19.33
Deprecated: Replaced by @ms-cloudpack/bundler-ori

# @ms-cloudpack/bundler-plugin-ori

Provides a Cloudpack bundler plugin around the `@oribuild/api` package, which
itself is a wrapper around esbuild+native plugins. This creates a really fast
bundler inner loop pipeline for serving large enterprise web applications.
npm package: @ms-cloudpack/bundler-plugin-rollup
Description: A cloudpack plugin for abstracting rollup.
Latest version: 0.15.23
Deprecated: Replaced by @ms-cloudpack/bundler-rollup

# @ms-cloudpack/bundler-plugin-rollup

Provides a Cloudpack bundler abstraction around the Rollup bundler.

## Usage

### `async function bundlePackage(options)`

```tsx
import { bundlePackage } from '@ms-cloudpack/bundler';

async function start() {
  const result = await bundlePackage({
    packagePath: process.cwd(),
    outputPath: path.join(process.cwd(), 'dist'),
    outputType: 'library',
  });

  console.log(result);
}

start();
```
npm package: @ms-cloudpack/bundler-plugin-rspack
Description: A cloudpack plugin for abstracting rspack.
Latest version: 0.1.3
Deprecated: Replaced by @ms-cloudpack/bundler-rspack

# @ms-cloudpack/bundler-plugin-rspack

Provides a Cloudpack bundler abstraction around the Rspack bundler.

## Usage

### `async function bundlePackage(options)`

```tsx
import { bundlePackage } from '@ms-cloudpack/bundler';

async function start() {
  const result = await bundlePackage({
    packagePath: process.cwd(),
    outputPath: path.join(process.cwd(), 'dist'),
    outputType: 'library',
  });

  console.log(result);
}

start();
```
npm package: @ms-cloudpack/bundler-plugin-tests
Description: A set of reusable tests to validate bundler plugin output.
Latest version: 0.13.1
Deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

# @ms-cloudpack/bundler-plugin-tests

This package contains a set of reusable Jest tests for validating the output of a bundler plugin.

## APIs

### `createTests(options)`

Runs a set of standard jest tests for the given plugin.

Options:

- `bundler` (`Bundler`): The bundler plugin being tested
- `excluded` (`string[]`): Optional list of tests to skip
- `afterAll` (`() => void | Promise<void>`): Optional callback after tests are done
npm package: @ms-cloudpack/bundler-plugin-webpack
Description: A cloudpack plugin for abstracting webpack.
Latest version: 0.9.12
Deprecated: Replaced by @ms-cloudpack/bundler-webpack

# @ms-cloudpack/bundler-plugin-webpack

Provides a Cloudpack bundler abstraction around the Webpack bundler.

## Usage

### `async function bundlePackage(options)`

```tsx
import { bundlePackage } from '@ms-cloudpack/bundler';

async function start() {
  const result = await bundlePackage({
    packagePath: process.cwd(),
    outputPath: path.join(process.cwd(), 'dist'),
    outputType: 'library',
  });

  console.log(result);
}

start();
```
npm package: @ms-cloudpack/bundler-types
Description: TypeScript types for implementing a bundler abstraction. We keep these separate from the bundler package to eliminate circular package dependencies and ensure no major bumps happen with the contract.
Latest version: 0.25.2
Deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

# @ms-cloudpack/bundler-types

This library provides the typings for the bundle abstraction package (`@ms-cloudpack/bundler`). Bundler plugins can use this to implement the standard bundler plugin contract.

Having the typings in a separate package helps keep the dependency graph non-circular. Both the bundler and the plugins can refer to the types in the same direction, rather than keeping the typings in the `bundler` package which could cause a circular DAG.
npm package: @ms-cloudpack/common-types-browser
Description: Types for Cloudpack browser globals.
Latest version: 0.6.5

# @ms-cloudpack/common-types-browser

This package provides Cloudpack types that are specific to the browser environment. There are two ways to use this package.

## Import types directly

```ts
import type { PageSessionContext } from '@ms-cloudpack/common-types-browser';
```

This is useful for server code, since it **does not** define the `window.__cloudpack` global.

## Configure tsconfig.json to include the globals

This makes `window.__cloudpack` and `window.__pageEvents` available to your code. (You can combine this with importing individual types as needed.)

```json
{
  "compilerOptions": {
    "types": ["@ms-cloudpack/common-types-browser/global"]
  }
}
```
npm package: @ms-cloudpack/config-types
Description: TypeScript types for the Cloudpack Configuration. We keep these separate to eliminate circular package dependencies.
Latest version: 0.7.0
Deprecated: Types moved to @ms-cloudpack/common-types

# @ms-cloudpack/config-types

This library provides the typings for the Cloudpack Configuration.

Having the typings in a separate package helps keep the dependency graph
non-circular.
npm package: @ms-cloudpack/environment
Description: Environment-related utilities for Cloudpack.
Latest version: 0.1.1

# @ms-cloudpack/environment

Environment-related utilities for Cloudpack. This helps centralize `process.env` access to a single place.

### Development notes

This package is written in JS so it can be consumed by Cloudpack's internal scripts package `@ms-cloudpack/scripts`. Only `.d.ts` files are emitted to `lib`.

The package also builds with the `cloudpack-scripts` bin from `@ms-cloudpack/scripts` (via the repo root dependency on that package). Technically this is circular, but it won't be an issue in practice because the scripts package is also written in JS.
npm package: @ms-cloudpack/external-telemetry
Description: Reporting external telemetry which is not about of cloudpack internals.
Latest version: 0.5.193

# @ms-cloudpack/external-telemetry

A library for reporting external (non-Cloudpack) telemetry data relevant to Cloudpack workflows. Data will be reported to Application Insights using Open Telemetry standards and show up on our internal dashboards for monitoring the changes in timings and usage of existing scenarios while migrating to new Cloudpack-powered workflows.

Telemetry is only reported by this package if a connection string is configured (`telemetry.connectionString` in `cloudpack.config.json`, or `CLOUDPACK_TELEMETRY_CONNECTION_STRING` environment variable). It will only be sent to your own Application Insights instance referenced by the connection string, not to Microsoft.

## Example usage

1. Create a client:

```ts
import { reportExternalTelemetryEvent } from '@ms-cloudpack/external-telemetry';

await reportExternalTelemetryEvent({
  eventName: 'LEGACY-START',
  attributes: {
    'my-attribute': 'value',
  },
});
```
npm package: @ms-cloudpack/feature-flags
Description: Feature flags
Latest version: 0.1.1
Deprecated: Package no longer used

# @ms-cloudpack/feature-flags

This package is responsible for;

- Downloading and storing feature flags in a local cache folder at the repository level.
- Providing an interface for applications to check the status of a feature.

## Usage

```ts
import { getFeatureFlags } from '@ms-cloudpack/feature-flags';

const featureFlags = getFeatureFlags({ repositoryName: 'my-repository-name', applicationName: 'my-app-name' });

if (featureFlags['my-feature-flag']) {
  // do something new
} else {
  // keep doing the old thing
}
```
npm package: @ms-cloudpack/file-watcher
Description: A file watcher abstraction for use with Cloudpack.
Latest version: 0.4.34

# @ms-cloudpack/file-watcher

An abstraction on the file watching capabilities used in Cloudpack.

## Example usage

1. Create a watcher:

```ts
const watcher = createWatcher();
```

2. Subscribe to a particular package path using `watch`. (Returns an `unwatch` function.)

```ts
const unwatch = await watcher.watch({ path: 'path/to/package' }, () => console.log(`package changed`));
```

3. To dispose, call the returned `unwatch`, or call `watcher.dispose` to unsubscribe from all watchers.

```ts
// Dispose an individual watcher.
await unwatch();

// Dispose all watchers.
await watcher.dispose();
```

### `createWatcher` options

- `type` (`'default' | 'fork'`, optional): By default, this will create a watcher in the same thread. Use `type: 'fork'` to create the watcher in a forked process.
- `backend` (`'default' | 'parcel'`, optional): Choose the file watching backend.
  - `'default'`: Uses chokidar (default)
  - `'parcel'`: Uses @parcel/watcher for better performance
- `policies` (optional): Enable performance optimizations
  - `'shared-root'`: Multiplexes N package watches into 1 root watch (for monorepos with 100+ packages)
  - `'debounce'`: Batches rapid file changes into single notifications

### Shared Root Watcher for Large Monorepos

For optimal performance when watching many packages (100+), use `SharedRootWatcher` - an orchestrator that wraps any watcher:

```ts
import { SharedRootWatcher, createWatcher } from '@ms-cloudpack/file-watcher';

// Create underlying watcher (can be any backend)
const underlyingWatcher = createWatcher({ backend: 'default' });

// Wrap it with SharedRootWatcher orchestrator
const watcher = new SharedRootWatcher(underlyingWatcher, '/path/to/monorepo');

// Watch multiple packages efficiently (single OS watcher)
await watcher.watch({ path: '/path/to/monorepo/packages/pkg1' }, onPkg1Change);
await watcher.watch({ path: '/path/to/monorepo/packages/pkg2' }, onPkg2Change);
// ... 1000+ packages
```

This uses a single file system watcher at the root instead of creating one per package.

**With Parcel backend for maximum performance:**

```ts
const underlyingWatcher = createWatcher({ backend: 'parcel' });
const watcher = new SharedRootWatcher(underlyingWatcher, '/path/to/monorepo');
```

### `watcher.watch` options

- `path` (`string`): The absolute root path to be watched.
- `id` (`string`, optional): ID for the watch job (defaults to `path`). If you call `watch` twice using the same `id`, subsequent calls will be ignored.
- `watchPaths` (`string[]`, optional): Relative paths/globs from the root path. Currently, only negative globs (starting with `!`) are supported and will be used to ignore files. Positive globs are ignored - the watcher will watch all files in the root path by default. Defaults are under "@ms-cloudpack/path-utilities" in `sourceFilesGlobs`.
npm package: @ms-cloudpack/jest-path-snapshot
Description: Allows for taking snapshots of file system content given a file path.
Latest version: 0.1.125
Deprecated: Package no longer used

# @ms-cloudpack/jest-path-snapshot

Allows file trees and content to be written in jest snapshots.

## Usage

Initialize it in your test file:

```tsx
import { pathSnapshotSerializer, fsPath } from '@ms-cloudpack/jest-path-snapshot';

expect.addSnapshotSerializer(pathSnapshotSerializer(options));
```

Then use in your tests by wrapping your path in the `fsPath` helper and using the ordinary Jest snapshot api:

```jsx
const someOutputPath = path.join(os.tmpdir(), 'my-stuff');

describe('file-thing', () => {
  it('writes to the disk', () => {
    fileThing(someOutputPath);
    // wrap your string path in fsPath to identify it as a serialized path.
    expect(fsPath(someOutputPath)).toMatchInlineSnapshot();
  });
});
```

Example output:

```txt
Folder contents of "test-project":
a/
├─ c/
│  └─ test-json.json
└─ test-png.png
b/
├─ test-ts.ts
└─ test-tsx.tsx
test-txt.txt

a/c/test-json.json:
------------------
{}

b/test-ts.ts:
------------
'ts';

b/test-tsx.tsx:
--------------
'tsx';

test-txt.txt:
------------
txt
```

## Options

| Name                   | Type       | Default                              | Description                                                                                                                 |
| ---------------------- | ---------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------- |
| `includeSourceMatches` | `string[]` | `'**/*.{txt,?([cm])[jt]s?(x),json}'` | Array of globs to include contents in the snapshot (does not impact the path hierarchy tree).                               |
| `excludeSourceMatches` | `string[]` |                                      | Array of globs to exclude from snapshot, despite matching `includeSourceMatches` (does not impact the path hierarchy tree). |
npm package: @ms-cloudpack/json-utilities
Description: Helpers for reading/writing json files.
Latest version: 0.1.11

# @ms-cloudpack/json-utilities

Helpers for reading/writing json files.

## Usage

```js
import { readJson, writeJson } from '@ms-cloudpack/json-utilities';

async function start() {
  const result = (await readJSON(`path/to/file.json`)) || defaultValue;
}

const app = createExpressApp([5000, 5001], (app) => {
  // Set up routes.
  app.get('*', async (req, res) => {
    res.send(`<html>...</html>`);
  });
});

// Stop app when you're done.
app.close();
```
npm package: @ms-cloudpack/link-proxy
Description: A proxy to connect cloudpack link clients
Latest version: 0.2.88

# @ms-cloudpack/link-proxy

A package that provides a proxy for the Cloudpack API, allowing you to use the API in a browser environment.

## Details

A pre-made ESM bundle is distributed under `dist/browser-esm/lib`, and referenced in the `package.json` exports map using the `browser-esm` condition. Cloudpack recognizes this condition as a pre-made bundle, meaning that it can serve it without bundling it.
npm package: @ms-cloudpack/overlay
Description: The Cloudpack overlay UX
Latest version: 0.19.84

# @ms-cloudpack/overlay

This package contains the overlay UX for Cloudpack, which is added to each page served by a Cloudpack dev session.

## Details

A pre-made ESM bundle is distributed under `dist/browser-esm/lib`, and referenced in the `package.json` exports map using the `browser-esm` condition. Cloudpack recognizes this condition as a pre-made bundle, meaning that it can serve it without bundling it.

This package uses Preact instead of React for smaller bundle size.
npm package: @ms-cloudpack/package-overrides
Description: Provides overrides for package.json to polyfill missing parts, such as exports maps.
Latest version: 0.9.40
Deprecated: Package no longer used

# @ms-cloudpack/package-overrides

Provides package.json patches for packages, which allows for providing missing parts such as exports maps. The `@ms-cloudpack/package-utilities` package uses this package to fill in missing details for common packages.

## API

### `applyOverrides(definition: PackageJson): PackageJson`

Returns a new definition which merges the given definition and overrides (if available.)

## Adding overrides

Exports maps and other missing data are welcome to be added under the `src/packages/{packageName}/overrides.json` files. The format is simple:

```js
[
  {
    "version": "<1",     // semver range match,
    "overrides": { ... } // package.json definition merged on top of the definition.
  }
]
```

## Special cases

Sometimes overrides are required but specific to an application, and don't belong in this package. In these cases, you can provide your own per-package overrides in your application's `package.json` file:

```js
{
  "name": "my-app",
  "version": "1.0.0",

  "cloudpack": {
    "packageOverrides": {
      "react": [
        {
          "version": "^16",
          "overrides": { ... }
        }
      ]
    }
  }
}
```
npm package: @ms-cloudpack/remote-cache
Description: Manages syncing the local Cloudpack cached assets to/from a remote storage service.
Latest version: 0.11.75

# @ms-cloudpack/remote-cache

This package is a wrapper around the Azure Storage SDK that provides a simple interface for uploading and downloading files and folders to and from Azure Blob Storage in Cloudpack. It also includes a helper function for generating a SAS token for a storage account.
npm package: @ms-cloudpack/retry
Description: A retry manager for handling resilient operations with customizable retry policies i
Latest version: 0.1.3

# @ms-cloudpack/retry

This package has a RetryManager class that can be used to retry operations that may fail due to transient errors.

## Usage

```ts
import { RetryManager, type RetryPolicies } from '@ms-cloudpack/retry';

const policies: RetryPolicies[] = [
  {
    maxRetries: 1,
    handle: (error) => {
      return error instanceof Error && error.message.indexOf('The error that this policy is interested in') > -1;
    },
    wait: () => 0,
  },
];

const retryManager = new RetryManager(policies);

retryManager.retry(() => {
  // do something that may fail
});
```
npm package: @ms-cloudpack/storybook-builder
Description: Experimental Storybook builder using Cloudpack
Latest version: 0.7.89

# @ms-cloudpack/storybook-builder

Experimental storybook builder using Cloudpack.

## Installation

Install the builder with npm:

```bash
npm install @ms-cloudpack/storybook-builder --save-dev
```

or yarn:

```bash
yarn add @ms-cloudpack/storybook-builder --dev
```

## Configuration

Configure the builder in the Storybook [main configuration](https://storybook.js.org/docs/react/configure) file:

```ts
// .storybook/main.js

const config = {
  ...
  framework: '@storybook/your-framework',
  core: {
    builder: {
      name: '@ms-cloudpack/storybook-builder',
      options: {
        ...
      },
    },
    ...
  },
  ...
};

export default config;
```

### Customize Cloudpack config

The builder _will_ read your `cloudpack.config.json` file, though it may add some options in order to work correctly. Ensure to have the Cloudpack config in the CWD.

### Unsupported features

These are features that are not yet supported by the builder:

- React docgen
- MDX
npm package: @ms-cloudpack/storybook-react
Description: Framework for running Storybook with React and Cloudpack.
Latest version: 0.3.89

# @ms-cloudpack/storybook-react

`@ms-cloudpack/storybook-react` is an experimental Storybook framework. It simplifies the configuration of the Storybook by setting the builder `@ms-cloudpack/storybook-builder` and the renderer `@storybook/react`.

## Installation

Install the framework with npm:

```bash
npm install @ms-cloudpack/storybook-react --save-dev
```

or yarn:

```bash
yarn add @ms-cloudpack/storybook-react --dev
```

## Configuration

Configure the framework name in the Storybook [main configuration](https://storybook.js.org/docs/react/configure) file:

```ts
// .storybook/main.js

const config = {
  ...
  framework: {
    name: '@ms-cloudpack/storybook-react',
    options: {
      ...
    },
    ...
  },
  ...
};

export default config;
```

## Docs

- [Basics](https://storybook.js.org/docs/get-started/install)
- [Configurations](https://storybook.js.org/docs/react/configure)
- [Addons](https://storybook.js.org/docs/react/configure/storybook-addons)
npm package: @ms-cloudpack/task-reporter
Description: Helpers for logging tasks to the console.
Latest version: 0.21.0

# @ms-cloudpack/task-reporter

A library for standardizing how tasks are logged to the console.

## Example usage

1. Create a reporter:

```ts
const taskReporter = new TaskReporter({
  productName: `Foobar`,
  version: `1.2.3`,
  description: `running tasks with ${bold(`15`)} workers`,
  showStarted: false,
  showPending: true,
  showCompleted: true,
  showSummary: true,
  showTaskDetails: true,
});
```

2. Add tasks with the reporter `addTask` method:

```ts
const task = taskReporter.addTask(`build something`, /* initially idle */ true);

// When you are starting the task, you can call start:
try {
  task.start();
} finally {
  task.complete({ status: 'complete' /* etc */ });
}
```

3. You can use various formatting helpers to spice up the colorization and formatting of your logging:

```ts
// Fail example, with provide details:
import { bulletedList } from '@ms-cloudpack/task-reporter';

task.complete({
  status: 'fail',
  message: 'Reason',
  details: bulletedList(['Name: value', 'Errors:', ['sub-bullet things', 'etc'], 'Warnings', ['warn1', etc]]),
});
```

A variety of helper functions are available for formatting.

```ts
import { cyan, bold, red } from '@ms-cloudpack/task-reporter';

task.complete('fail', { message: cyan(bold(`I am an ${red(`error`)}`)) });
```

4. When all your tasks are completed, or if you encountered an exit-early scenario, call `reporter.complete('reason')` to end task logging. Any pending tasks will be marked as skipped, and running tasks will be marked as aborted.

```ts
process.on('SIGINT', () => {
  reporter.complete('User hit Ctrl-C');
  void reporter.dispose();
});

await doStuff();
reporter.complete(reason);
await reporter.dispose();
```
npm package: @ms-cloudpack/telemetry
Description: Helpers for reporting telemetry in Cloudpack.
Latest version: 0.11.75

# @ms-cloudpack/telemetry

A library for reporting Cloudpack telemetry to Application Insights using Open Telemetry standards.

Telemetry is only reported by the Cloudpack CLI if a connection string is configured (`telemetry.connectionString` in `cloudpack.config.json`, or `CLOUDPACK_TELEMETRY_CONNECTION_STRING` environment variable). It will only be sent to your own Application Insights instance referenced by the connection string, not to Microsoft.

Currently, this library only supports [Tracing](https://opentelemetry.io/docs/concepts/signals/traces/). Metrics and Logs can be added later when needed.

## Example usage

1. Create a client:

```ts
const telemetryClient = new TelemetryClient({
  serviceNamespace: 'cloudpack',
  serviceName: 'cli',
  productVersion: '1.2.3',
  instrumentationKey: '<Application insights Instrumentation Key>',
  logLevel: 'verbose',
});
```

2. Add shared attributes

```ts
telemetryClient.setSharedSpanAttribute('sessionId', 'my-session-id');
```

These attributes will get added to all spans.

3. Get the tracer

```ts
const tracer = telemetryClient.getTracer();
```

4. Create a span / add events / end the span

```ts
const span = tracer.createSpan('my-unit-of-work');
// do work
span.addEvent('my-event', { myCustomAttribute: 'my-custom-value' });

try {
  // do more work
} catch (err) {
  span.recordException(err);
}

// end the span when the unit-of-work completed.
span.end();
```

[Lear more about spans](https://opentelemetry.io/docs/instrumentation/js/instrumentation/#create-spans)

5. Shutdown TelemetryClient before application exists

```ts
telemetryClient.shutdown();
```

- This will force flush all the remaining data to remote servers and prevent more data to be collected.
- Make sure that all spans have been ended before shuting down the telemetry client
npm package: @ms-cloudpack/test-utilities
Description: Common test utilities for the Cloudpack repo.
Latest version: 0.5.0
Deprecated: Package no longer published

# @ms-cloudpack/test-utilities

Utilities for testing libraries within the Cloudpack repo.

## APIs

### `createTempDir(options)`

Creates a temporary directory and returns the normalized path.

This directory _should_ be deleted automatically when the program exits, but it's more reliable to include manual cleanup in your code.

Options:

- `prefix?: string`: Prefix for the temp directory (a random suffix will be added). Default is `cloudpack-test-`.

Example:

```js
import { createTempDir } from '@ms-cloudpack/test-utilities';

const testFolder = createTempDir({
  prefix: 'some-prefix-', // default is 'cloudpack-test-'
});
```

### `createTestFileStructure(files, options)`

Creates a test folder and populates it with content. For each key in `files`, create a test folder and write a file of that filename, where the content is the value.

Returns the path to the test folder.

Parameters:

- `files: Record<string, string | Record<string, unknown>>`: Mapping from file path to contents. String contents will be written as-is; objects will be written with `JSON.stringify`.
- `options` object (optional):
  - `testName?: string`: Test name to use in the temp directory name (`cloudpack-test-<testName>-`).
  - `parentDir?: string`: Absolute path to a parent directory for the test file structure (will be created if needed), to be used instead of creating a random temporary directory.
  - `links?: Record<string, string>`: Create these links in the temp directory. Keys are link paths and values are source paths (both relative).

Example:

```js
import { createTestFileStructure } from '@ms-cloudpack/test-utilities';

const testFolder = await createTestFileStructure({
  './package.json': { name: 'asdf' },
  './src/bar.ts': "export default 'hi';",
});

console.log(readJson(path.join(testFolder, 'package.json')));
```
npm package: @ms-cloudpack/worker-pool
Description: Worker and process pool helper
Latest version: 0.5.0

# @ms-cloudpack/worker-pool

Provides utilities for simplifying worker execution.

It can manage either [worker threads](https://nodejs.org/api/worker_threads.html) or [child processes](https://nodejs.org/api/child_process.html) depending on the `workerType` option.

## Usage

Code using the worker pool has two parts:

- **Host code** which creates the pool and enqueues work
- **Worker entry file**, a `.js` file which hosts the code to be executed within the worker

### ⚠️ Warning

For worker reuse to work properly, the method(s) being run **must not** have any async/scheduled code which continues running after the result is returned. Otherwise, if the scheduled code causes an error after the method returns, the error will either be swallowed (if no method was running in the worker at the time) or associated with the wrong method call (if another method call has been started).

If running arbitrary external code in a worker, it's recommended to overwrite all methods for async scheduling (`setTimeout` etc) with no-op versions.

Also be mindful of any cleanup of global state which might need to happen in between runs. This can be done with `afterEach` (see below).

### Setting up a worker entry

First, let's set up the worker entry that will execute work inside the worker. Use `initializeWorker` to set up your api surface:

`workerEntry.ts`:

```js
import { initializeWorker } from '@ms-cloudpack/worker-pool';
import { methodA, methodB } from './methods';

// Load any environmental side effects here.

// Then initialize the worker with the appropriate listeners and api dictionary.
initializeWorker({
  beforeEach: () => {...}, // optional
  afterEach: () => {...}, // optional
  methods: {
    methodA,
    methodB,
  },
});
```

### Setting up the pool

In the host where we want to execute things to asynchronously run in the pool of worker threads:

```js
import { WorkerPool } from '@ms-cloudpack/worker-pool';
import path from 'path';
import { fileURLToPath } from 'url';

// or use __dirname if not using ES modules
const dirname = path.dirname(fileURLToPath(import.meta.url));

const pool = new WorkerPool({
  entryPath: path.join(dirname, 'workerEntry.js'),
});
```

Worker threads are recommended due to their better performance. If the child operation specifically requires a new Node process with command line arguments or [custom options](https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options), use `workerType: 'process'`:

```js
const pool = new WorkerPool({
  entryPath: path.join(dirname, 'processEntry.js'),
  workerType: 'process',
  // fill in as needed
  childProcessArgs: [],
  childProcessOptions: {},
});
```

### Executing work

Work is executed from the pool created above:

```js
const result = await pool.execute({
  method: 'methodA',
  args: [arg1, arg2, etc],
});
```