open-index/open-npm huggingface dataset:
npm package: @microature/publisher-npm-plugin
Description: NPM publishing plugin for @microature/publisher
Author: MicroWise Development
Latest version: 0.1.0

# @microature/publisher-npm-plugin

NPM publishing plugin for [@microature/publisher](https://gitlab.com/microature/publisher).

## Installation

```bash
npm install @microature/publisher-npm-plugin
```

## Usage

```typescript
import { NpmPublishPlugin } from '@microature/publisher-npm-plugin'
import { Publisher } from '@microature/publisher'

const publisher = new Publisher({
  plugins: {
    npm: new NpmPublishPlugin()
  }
})

// Plugin will be automatically used for npm publishing
```

## Configuration

The plugin accepts the following configuration options:

```typescript
{
  registry?: string    // Custom npm registry (default: https://registry.npmjs.org)
  token?: string      // NPM authentication token
  access?: 'public' | 'restricted'  // Package access level
}
```

## Features

- ✅ Automatic package.json generation
- ✅ Project building before publishing
- ✅ Tarball creation and validation
- ✅ Branch-specific package naming
- ✅ Scoped package support
- ✅ Custom registry support
- ✅ Authentication token support

## Branch Strategy

- **main branch**: Publishes as `package-name@version`
- **other branches**: Publishes as `package-name-branch@version` with branch tag

## Requirements

- Node.js >= 18.0.0
- npm CLI installed
- Valid package.json in project root (for existing projects)

## License

MIT
npm package: @microature/publisher-npm-release-plugin
Description: NPM release asset plugin for @microature/publisher - uploads npm packages to git releases
Author: MicroWise Development
Latest version: 0.1.0

# @microature/publisher-npm-release-plugin

NPM release asset plugin for [@microature/publisher](https://gitlab.com/microature/publisher). 

**Purpose**: Uploads NPM packages (.tgz) to git releases as downloadable assets, not to npm registry.

## Installation

```bash
npm install @microature/publisher-npm-release-plugin
```

## Usage

```typescript
import { Publisher } from '@microature/publisher'
import { NpmReleasePlugin } from '@microature/publisher-npm-release-plugin'

const publisher = new Publisher(config)

// Register the plugin
const npmReleasePlugin = new NpmReleasePlugin()
publisher.registerPlugin('npm-assets', npmReleasePlugin)

// Plugin will automatically:
// 1. Detect version from package.json
// 2. Build project (if build script exists)
// 3. Create .tgz package
// 4. Upload to git release as asset
```

## What This Plugin Does

### Version Detection
- Reads `package.json → version` field
- Suggests git tag name (e.g., `v1.2.3`)

### Asset Preparation
- Runs `npm run build` (if script exists)
- Runs `npm run prepublishOnly` (if script exists)  
- Creates `.tgz` package with `npm pack`

### Release Upload
- Uploads `.tgz` file to GitLab/GitHub release as asset
- Users can download and install with: `npm install <asset-url>`

## Configuration

```typescript
{
  gitHosting: {
    type: 'gitlab',  // or 'github'
    token: 'your-gitlab-token',
    projectId: 'project-id',     // for GitLab
    apiUrl: 'https://gitlab.com' // optional, for self-hosted
  }
}
```

## Features

- ✅ Automatic version detection from `package.json`
- ✅ Project building before packaging
- ✅ NPM tarball creation
- ✅ GitLab release asset upload
- ✅ GitHub support (planned)
- ✅ Cleanup of temporary files

## Package Flow

1. **Detect**: Read version from `package.json`
2. **Build**: Run build scripts if they exist
3. **Package**: Create `.tgz` with `npm pack`
4. **Upload**: Attach to git release as downloadable asset
5. **Cleanup**: Remove temporary `.tgz` file

## Difference from NPM Publishing

This plugin **does NOT**:
- ❌ Publish to npm registry
- ❌ Require npm authentication
- ❌ Use `npm publish`

This plugin **does**:
- ✅ Create git release assets
- ✅ Enable git-based package distribution
- ✅ Allow installation via direct URLs

## Installation from Git Release

Users can install packages directly from git releases:

```bash
# Download from release assets
npm install https://gitlab.com/org/project/-/releases/v1.2.3/downloads/package-1.2.3.tgz
```

## Requirements

- Node.js >= 18.0.0
- Git repository with remote configured
- GitLab or GitHub API access

## License

MIT
npm package: @microature/publisher-release-notes-plugin
Description: Release notes generation plugin for @microature/publisher
Author: MicroWise Development
Latest version: 0.4.0

# @microature/publisher-release-notes-plugin

Release notes generation plugin for [@microature/publisher](https://gitlab.com/microature/publisher).

## Installation

```bash
npm install @microature/publisher-release-notes-plugin
```

## Usage

```typescript
import { ReleaseNotesPlugin } from '@microature/publisher-release-notes-plugin'

const plugin = new ReleaseNotesPlugin()

// Generate release notes from commit messages
const releaseNotes = await plugin.generateReleaseNotes(
  [
    'feat: add new user authentication system',
    'fix: resolve memory leak in data processing',
    'docs: update API documentation'
  ],
  {
    version: '1.2.0',
    currentTag: 'v1.2.0',
    previousTag: 'v1.1.0',
    repository: 'https://gitlab.com/your-org/your-project'
  }
)

console.log(releaseNotes)
```

## Configuration

The plugin accepts the following configuration options:

```typescript
interface ReleaseNotesConfig {
  preset?: string                    // Conventional changelog preset (default: 'angular')
  template?: string                  // Custom template
  includeBreakingChanges?: boolean   // Include breaking changes section (default: true)
  includeDeprecations?: boolean      // Include deprecations (default: true)
  customSections?: Array<{           // Custom sections
    title: string
    match: (commit: any) => boolean
  }>
}
```

## Features

- ✅ Conventional commits support
- ✅ Breaking changes detection
- ✅ Categorized changelog sections
- ✅ Multiple preset support (Angular, Atom, etc.)
- ✅ Custom templates
- ✅ Scoped commit support
- ✅ Fallback for non-conventional commits

## Generated Sections

- **⚠️ BREAKING CHANGES** - Breaking changes
- **✨ Features** - New features (`feat:`)
- **🐛 Bug Fixes** - Bug fixes (`fix:`)
- **⚡ Performance Improvements** - Performance improvements (`perf:`)
- **📚 Documentation** - Documentation changes (`docs:`)
- **🔨 Code Refactoring** - Refactoring (`refactor:`)
- **✅ Tests** - Test changes (`test:`)
- **📋 Other Changes** - Other commits

## Examples

### Basic Usage

```typescript
const plugin = new ReleaseNotesPlugin()
const notes = await plugin.generateReleaseNotes(commits, context)
```

### With Custom Configuration

```typescript
const notes = await plugin.generateReleaseNotes(
  commits,
  context,
  {
    preset: 'atom',
    includeBreakingChanges: true,
    customSections: [
      {
        title: 'Security',
        match: (commit) => commit.type === 'security'
      }
    ]
  }
)
```

### Check for Breaking Changes

```typescript
const hasBreaking = plugin.hasBreakingChanges(commits)
if (hasBreaking) {
  // Handle major version bump
}
```

## Requirements

- Node.js >= 18.0.0

## License

MIT
npm package: @microbackend/plugin-apollo-server-express
Description: Micro-backend Apollo Express GraphQL server plugin
Author: Hai Pham
Latest version: 1.0.1

# @microbackend/plugin-apollo-server-express

Microbackend plugin to add core support for
[Apollo Server Express](https://www.npmjs.com/package/apollo-server-express).

## Dependency

- [@microbackend/plugin-graphql-core](https://www.npmjs.com/package/@microbackend/plugin-graphql-core).
- [@microbackend/plugin-express](https://www.npmjs.com/package/@microbackend/plugin-express).

## Installation

```shell
npx microbackend plugin add @microbackend/plugin-apollo-server-express
```

## Usage

### Configuration

The plugin extends the `IMicrobackendConfig` from `@microbackend/plugin-core`
to allow configuring the Apollo Server via the `apolloServerExpress` property:

```typescript
import { MicrobackendConfig } from "@microbackend/plugin-core";
import gql from "graphql-tag";

export default class Config extends MicrobackendConfig {
  get config(): MicrobackendConfig["config"] {
    return {
      apolloServerExpress: {
        /** Apollo Server configurations */
      },
    };
  }
}
```

The supported configuration options can be found in the
[Apollo Server Express docs](https://www.apollographql.com/docs/apollo-server/integrations/middleware/#apollo-server-express).
npm package: @microbackend/plugin-env-vars
Description: Micro-backend environment variables plugin
Author: Hai Pham
Latest version: 1.0.1

# @microbackend/plugin-env-vars

Microbackend plugin to inject environment variables into `process.env`.

## Installation

```shell
npx microbackend plugin add @microbackend/plugin-env-vars
```

## Usage

```typescript
import createPluginConfig from "@microbackend/plugin-core/build/webpack.build";

await createPluginConfig({
  pluginOptions: {
    "@microbackend/plugin-env-vars": {
      additionalEnvVariables: { ENV_2: "2" },
      dumpToProcessEnv2: true,
      requiredEnvVariables: ["ENV_1", "ENV_2"],
    },
  },
});
```

The above configuration does the following:

- Extract the environment variables in `env.${environment}`, where `environment`
  is determined by `NODE_ENV`. For example, if `NODE_ENV` is `development`,
  the values in `env.development` will be used.
- Extract additional variables passed to `additionalEnvVariables`.
- Check that the keys specified to `requiredEnvVariables` point to valid
  environment variable values. If they do not, an error will be thrown. This is
  useful for compile-time checks against missing environment variables.
- Inject all the collected variables into `process.env` using `DefinePlugin`,
  which can be accessed during runtime using `process.env.ENV1`
  (`const { ENV_1 } = process.env` will not work).
- If `dumpToProcessEnv2` is specified, dump all environment variables to
  `process.env2` as well. This is useful during development when we want to
  view all currently available variables (e.g. `console.log(process.env2)`).
npm package: @microbackend/plugin-express
Description: Micro-backend express.js plugin
Author: Hai Pham
Latest version: 1.0.1

# @microbackend/plugin-express

Microbackend plugin for [express.js](https://www.npmjs.com/package/express).

## Installation

This plugin is automatically included if you had initialized a microbackend
project with:

```shell
npx microbackend init --template express
```

To install it as a standalone dependency:

```shell
npx microbackend plugin add @microbackend/plugin-express
```

## Usage

For illustration purposes, create the following files in your project:

- `src/extension/express/route/route1.ts`:

```typescript
import { IMicrobackendInitFunction } from "@microbackend/plugin-express";

export default ((): IMicrobackendRouteCreator => {
  return () => {
    return {
      handler: async (_req, res) => {
        res.json({ value: 1 });
      },
      method: "get",
      route: "/route1",
    };
  };
})();
```

- `src/extension/express/route/middleware1.ts`:

```typescript
import { IMicrobackendMiddlewareCreator } from "@microbackend/plugin-express";

export default ((): IMicrobackendMiddlewareCreator => {
  return () => {
    return {
      handler: (req, _res, next) => {
        console.log(req);
        next();
      },
    };
  };
})();
```

Then, in your main application entry file:

```typescript
import { createExpressApplication } from "@microbackend/plugin-express";
import express from "express";

export default createExpressApplication().then((app) => {
  app.use(((err, _req, res, _next) => {
    res.status(err.status || 500).json({ error: err.message });
  }) as express.ErrorRequestHandler);

  const port = process.env["PORT"] || 3001;

  app.listen(port, () => {
    console.log("Started example server on port", port);
  });
});
```

Now, your Express app will automatically have a middleware that logs all requests,
and a request handler registered for route `/route1`.

In short, the extension patterns supported by this plugin are:

- `IMicrobackendRouteCreator`, supported by `extension/express/route`: A
  function type that creates an Express route. The `handler` option can either
  be a function or an `express.Router` instance.

- `IMicrobackendMiddlewareCreator`, supported by `extension/express/middleware`:
  A function type that creates an Express middleware.

For more information on extension patterns, please have a look at
[`@microbackend/plugin-core`](https://www.npmjs.com/package/@microbackend/plugin-core).
npm package: @microbackend/plugin-firebase
Description: Micro-backend Firebase plugin
Author: Hai Pham
Latest version: 1.0.1

# @microbackend/plugin-firebase

Microbackend plugin to add support for
[firebase](https://www.npmjs.com/package/firebase-admin).

## Installation

```shell
npx microbackend plugin add @microbackend/plugin-firebase
```

## Usage

```typescript
import createPluginConfig from "@microbackend/plugin-core/build/webpack.build";

await createPluginConfig({
  pluginOptions: {
    "@microbackend/plugin-firebase": {
      serviceAccountEnvVariable: "CUSTOM_GOOGLE_SERVICE_ACCOUNT",
      serviceAccountPath: path.resolve(
        "credential",
        "google_service_account.json"
      ),
    },
  },
});
```

If not provided, `serviceAccountEnvVariable` defaults to
`GOOGLE_SERVICE_ACCOUNT_CREDENTIALS`.

The above configuration does the following steps:

- Read the service account file specified by `serviceAccountPath`.
- Store the service account credentials in the environment variable specified
  by `serviceAccountEnvVariable`, which can then be accessed during runtime like
  this: `process.env["CUSTOM_GOOGLE_SERVICE_ACCOUNT"]`.

The plugin creates an extension on `app` to expose a `firebaseAdmin` property
using the service account credentials.

```typescript
app.use((req, res, next) => {
  const firebaseAuth = req.app.firebaseAdmin.auth();
  /** Perform auth */
  next();
});
```

For more information on how to use the firebase Node.js SDK, please read its
[documentation](https://www.npmjs.com/package/firebase-admin).
npm package: @microbackend/plugin-googleapis
Description: Micro-backend googleapis plugin
Author: Hai Pham
Latest version: 1.0.1

# @microbackend/plugin-googleapis

Microbackend plugin to add support for
[googleapis](https://www.npmjs.com/package/googleapis).

## Installation

```shell
npx microbackend plugin add @microbackend/plugin-googleapis
```

## Usage

```typescript
import createPluginConfig from "@microbackend/plugin-core/build/webpack.build";

await createPluginConfig({
  pluginOptions: {
    "@microbackend/plugin-googleapis": {
      credentialsEnvVariable: "CUSTOM_GOOGLE_OAUTH2_CREDENTIALS",
      credentialsPath: path.resolve(
        "credential",
        "google_oauth_credentials.json"
      ),
      tokenEnvVariable: "CUSTOM_GOOGLE_OAUTH2_TOKEN",
      tokenPath: path.resolve("credential", "google_oauth_token.json"),
    },
  },
});
```

If not provided:

- `credentialsEnvVariable` defaults to `GOOGLE_OAUTH2_CREDENTIALS`.
- `tokenEnvVariable` defaults to `GOOGLE_OAUTH2_TOKEN`.

The above configuration does the following steps:

- Read the Google OAuth2 credentials file specified by `credentialsPath`.
- Store the OAuth2 credentials in the environment variable specified by
  `credentialsEnvVariable`, which can then be accessed during runtime like
  this: `process.env["CUSTOM_GOOGLE_OAUTH2_CREDENTIALS"]`.
- Read the Google OAuth2 token file specified by `tokenPath`.
- Store the token contents in the environment variable specified by
  `tokenEnvVariable`, which can then be accessed during runtime like this:
  `process.env["CUSTOM_GOOGLE_OAUTH2_TOKEN"]`.

The plugin creates an extension on `app` to expose a `googleOAuth2Client`
property using the credentials and token.

For more information on how to use the googleapis Node.js SDK, please read its
[documentation](https://www.npmjs.com/package/googleapis).

### Acquiring a Google OAuth2 token

In order to construct the Google OAuth2 client, we need to first acquire a
Google OAuth2 token, like so:

```javascript
// @ts-check
const {
  authorizeGoogle,
} = require("@haipham/javascript-helper-google-build-utils");

(async () => {
  await authorizeGoogle({
    credentialPath: {{credentialsPath}},
    tokenPath: {{tokenPath}},
    scopes: [
      "https://www.googleapis.com/auth/gmail.compose",
      "https://www.googleapis.com/auth/gmail.send",
    ],
  });
})();
```
npm package: @microbackend/plugin-graphql-core
Description: Micro-backend core GraphQL plugin
Author: Hai Pham
Latest version: 1.0.1

# @microbackend/plugin-graphql-core

Microbackend plugin to add core support for GraphQL, without any specific
server implementation.

## Installation

```shell
npx microbackend plugin add @microbackend/plugin-graphql-core
```

## Usage

### Directive

Define new directives under `src/extension/graphql/directive`:

- Using `MicrobackendSchemaTransformer`:

```typescript
// extension/graphql/directive/always_return_3.ts
import { getDirective, MapperKind, mapSchema } from "@graphql-tools/utils";
import { MicrobackendSchemaTransformer } from "@microbackend/plugin-graphql-core";
import gql from "graphql-tag";

export default class AlwaysReturn3 extends MicrobackendSchemaTransformer {
  get transformer(): MicrobackendSchemaTransformer["transformer"] {
    return ({ schema }) => {
      return mapSchema(schema, {
        [MapperKind.OBJECT_FIELD]: (fieldConfig) => {
          const directive = getDirective(
            schema,
            fieldConfig,
            this.args.directiveName
          );

          if (directive != null) {
            fieldConfig.resolve = async () => {
              return 3;
            };

            return fieldConfig;
          }

          return undefined;
        },
      });
    };
  }

  get typeDefs() {
    return gql`
    directive @${this.args.directiveName} on FIELD_DEFINITION
    `;
  }
}
```

- Using `IMicrobackendSchemaTransformerCreator`:

```typescript
// extension/graphql/directive/always_return_1.ts
import { getDirective, MapperKind, mapSchema } from "@graphql-tools/utils";
import gql from "graphql-tag";
import { IMicrobackendSchemaTransformerCreator } from "@microbackend/plugin-graphql-core";

export default ((): IMicrobackendSchemaTransformerCreator => {
  return ({ directiveName }) => {
    return {
      transformer: ({ schema }) => {
        return mapSchema(schema, {
          [MapperKind.OBJECT_FIELD]: (fieldConfig) => {
            const directive = getDirective(schema, fieldConfig, directiveName);

            if (directive != null) {
              fieldConfig.resolve = async () => {
                return 1;
              };

              return fieldConfig;
            }

            return undefined;
          },
        });
      },
      typeDefs: gql`
      directive @${directiveName} on FIELD_DEFINITION
      `,
    };
  };
})();
```

These directives will be loaded at runtime automatically; the names of the
directive files shall become the names of the directives themselves, like so:

```graphql
extend type Query {
  test1: Int! @always_return_1;
  test2: Int! @always_return_3;
}
```
npm package: @microbackend/plugin-hmr
Description: Micro-backend hot-module-reload plugin
Author: Hai Pham
Latest version: 1.0.1

# @microbackend/plugin-hmr

Microbackend plugin to add hot module reloading in development.

## Installation

```shell
npx microbackend plugin add @microbackend/plugin-hmr
```

## Usage

```typescript
import createPluginConfig from "@microbackend/plugin-core/build/webpack.build";

await createPluginConfig({
  pluginOptions: {
    "@microbackend/plugin-hmr": {
      isEnabled: true,
      scriptsToRunOnBuildEnd: ["npx nodemon"],
    },
  },
});
```

Both of the above plugin options are optional. After integrating this plugin,
running `webpack --watch` will start the application in watch mode, and reload
it whenever there are code changes.
npm package: @microbackend/plugin-http
Description: Micro-backend HTTP plugin
Author: Hai Pham
Latest version: 1.0.1

# @microbackend/plugin-http

Microbackend plugin to define common types for HTTP requests.

## Installation

```shell
npx microbackend plugin add @microbackend/plugin-http
```

## Usage

This plugin simply serves to enhance other plugins' typing support, so there is
no need to interact with it manually.
npm package: @microbackend/plugin-serverless-aws
Description: Micro-backend AWS serverless plugin
Author: Hai Pham
Latest version: 1.0.1

# @microbackend/plugin-serverless-aws

Microbackend plugin to add support for the
[serverless framework](https://www.npmjs.com/package/serverless).

## Installation

```shell
npx microbackend plugin add @microbackend/plugin-serverless-aws
```

## Usage

### Serverful/Serverless switch

```typescript
import createPluginConfig from "@microbackend/plugin-core/build/webpack.build";

await createPluginConfig({
  pluginOptions: {
    "@microbackend/plugin-serverless-aws": {
      isEnabled: process.env["INFRASTRUCTURE"] === "serverless",
      serverfulConfig: {
        entry: path.resolve("src", "index.ts"),
        mode: "development",
        output: { path: path.join(__dirname, "build"), filename: "index.js" },
      },
      serverlessConfig: {},
    },
  },
});
```

This plugin allows running the application in both serverful and serverless
modes, depending on whether `isEnabled` is true or false. In the entry file,
we will need to make some modification to the server start code:

```typescript
import { createExpressApp } from "@microbackend/plugin-express";
import startServerfulApp from "@microbackend/plugin-serverless-aws";
import express from "express";
import { Server } from "http";

let server: Server;

export const handler = startServerfulApp({
  getApp: () => {
    return createExpressApp().then((app) => {
      app.get("/", (...[, res]) => {
        res.sendStatus(204);
      });

      app.use(((err, _req, res, _next) => {
        res.status(err.status || 500).json({ error: err.message });
      }) as express.ErrorRequestHandler);

      return app;
    });
  },
  startApp: async ({ app }) => {
    const port = process.env["PORT"] || 3001;

    server = app.listen(port, () => {
      console.log("Started example server on port", port);
    });
  },
});
```

The `startServerfulApp` function abstracts away the work needed to switch
between serverful and serverless. We can then add some scripts to our
`package.json`:

```json
{
  "scripts": {
    "build": "webpack",
    "build:sls": "cross-env INFRASTRUCTURE=serverless sls package",
    "deploy": "cross-env INFRASTRUCTURE=serverless sls deploy",
    "start": "webpack --watch",
    "start:sls": "cross-env INFRASTRUCTURE=serverless sls invoke local--function core"
  }
}
```

In the above example, the serverful/serverless switch is determined using the
`process.env["INFRASTRUCTURE"]` flag, but it is up to us how we want to
implement it.

### Configuration generation

Running:

```shell
npx microbackend gen
```

will generate a `serverless.yml` file in the current project directory, if
there is not yet an existing file. It serves as a base for you to add on, and
is not meant to be an one-size-fits-all configuration.
npm package: @microbackend/plugin-type-graphql
Description: Micro-backend type-graphql plugin
Author: Hai Pham
Latest version: 1.0.1

# @microbackend/plugin-type-graphql

Microbackend plugin to add core support for [TypeGraphQL](https://typegraphql.com),
without any specific server implementation.

## Dependency

- [@microbackend/plugin-graphql-core](https://www.npmjs.com/package/@microbackend/plugin-graphql-core).

## Installation

```shell
npx microbackend plugin add @microbackend/plugin-type-graphql
```

## Usage

The [extension patterns](https://github.com/protoman92/microbackend/tree/main/package/plugin_core#extension-patterns) supported by this plugin are:

- TypeGraphQL Resolvers, supported by `extension/type_graphql/resolver`: Classes
  that are marked as `Resolver` and consumed by TypeGraphQL to generate
  GraphQL schema and resolvers.

### Resolver

Define new resolvers under `src/extension/type_graphql/resolver` using
TypeGraphQL decorators:

```typescript
// extension/type_graphql/resolver/common.ts
import { Directive, ObjectType, Query, Resolver } from "type-graphql";

@ObjectType()
export class Test {}

@Resolver(() => Test)
export class TestResolver {
  @Directive("@custom_directive")
  @Query(() => Number)
  async test(): Promise<number> {
    return 1;
  }
}
```

These resolvers will be loaded at runtime automatically and added to
TypeGraphQL's configuration. For more information on how to use TypeGraphQL
itself, please refer to its [official documentation](https://typegraphql.com).
npm package: @microbackend/plugin-typescript
Description: Micro-backend Typescript plugin
Author: Hai Pham
Latest version: 1.0.1

# @microbackend/plugin-typescript

Microbackend plugin to add TypeScript support to the project.

## Installation

```shell
npx microbackend plugin add @microbackend/plugin-typescript
```

## Usage

```typescript
import createPluginConfig from "@microbackend/plugin-core/build/webpack.build";

await createPluginConfig({
  pluginOptions: {
    "@microbackend/plugin-typescript": {
      enableTsConfigPaths: true,
      tsconfigPathsOptions: {},
    },
  },
});
```

Both of the above plugin options are optional. After integrating this plugin,
TypeScript files will be loaded using `ts-loader`, and `TsconfigPathsPlugin`
can be integrated to allow absolute imports using tsconfig's `baseUrl` and
`paths` compiler options.
npm package: @microbit/makecode-embed
Description: <a href="https://microbit-foundation.github.io/makecode-embed/" class="typedoc-ignore">This documentation is best viewed on the documentation site rather than GitHub or NPM package site.</a>
Author: Matt Hillsdon
Latest version: 0.5.0

# MakeCode Embed

<a href="https://microbit-foundation.github.io/makecode-embed/" class="typedoc-ignore">This documentation is best viewed on the documentation site rather than GitHub or NPM package site.</a>

This is a React/JavaScript library for embedding Microsoft MakeCode as an iframe.

It is intended to be used by other Micro:bit Educational Foundation projects
that need to embed MakeCode and, when the API stabilises, to be useful to others
who embed MakeCode.

- [StoryBook demo of the components](https://makecode-embed.pages.dev/)

## Usage

- [React usage documentation](docs/react.md)
- [VanillaJS usage documentation](docs/vanilla.md)

## License

This software is under the MIT open source license.

[SPDX-License-Identifier: MIT](LICENSE.md)

We use dependencies via the NPM registry as specified by the package.json file under common Open Source licenses.

The MakeCode/PXT types are derived from the [Microsoft MakeCode/PXT repository](https://github.com/Microsoft/pxt) as of 954d72b3a763608ca6f484807f511591ce48691a under a MIT license.

Full details of each package can be found by running `license-checker`:

```bash
$ npx license-checker --direct --summary --production
```

Omit the flags as desired to obtain more detail.

## Code of Conduct

Trust, partnership, simplicity and passion are our core values we live and
breathe in our daily work life and within our projects. Our open-source
projects are no exception. We have an active community which spans the globe
and we welcome and encourage participation and contributions to our projects
by everyone. We work to foster a positive, open, inclusive and supportive
environment and trust that our community respects the micro:bit code of
conduct. Please see our [code of conduct](https://microbit.org/safeguarding/)
which outlines our expectations for all those that participate in our
community and details on how to report any concerns and what would happen
should breaches occur.
npm package: @microbit/microbit-fs
Description: Manipulate files in a micro:bit MicroPython Intel Hex file.
Author: Micro:bit Educational Foundation
Latest version: 0.10.0

# micro:bit MicroPython Filesystem

[![GitHub Actions](https://github.com/microbit-foundation/microbit-fs/actions/workflows/build.yml/badge.svg)](https://github.com/microbit-foundation/microbit-fs/actions/workflows/build.yml)

A TypeScript library to manipulate the micro:bit MicroPython filesystem.

<img width="50%" alt="microbit-fs logo" src="https://user-images.githubusercontent.com/29712657/53014294-fb95e700-343f-11e9-856e-d70af8870c0c.png">

## Documentation

The docs can be found in
[https://microbit-foundation.github.io/microbit-fs/](https://microbit-foundation.github.io/microbit-fs/).

## npm Package

To add this package to your project:

```
npm install @microbit/microbit-fs
```

## License

This software is under the MIT open source license.

[SPDX-License-Identifier: MIT](LICENSE.md)

## Code of Conduct

Trust, partnership, simplicity and passion are our core values we live and
breathe in our daily work life and within our projects. Our open-source
projects are no exception. We have an active community which spans the globe
and we welcome and encourage participation and contributions to our projects
by everyone. We work to foster a positive, open, inclusive and supportive
environment and trust that our community respects the micro:bit code of
conduct. Please see our [code of conduct](https://microbit.org/safeguarding/)
which outlines our expectations for all those that participate in our
community and details on how to report any concerns and what would happen
should breaches occur.
npm package: @microbit/microbit-universal-hex
Description: Create micro:bit Universal Hexes.
Author: Micro:bit Educational Foundation
Latest version: 0.2.2

# micro:bit Universal Hex TypeScript Library

<img width="30%" alt="microbit-universal-hex logo" src="docs/img/microbit-uh-logo.png" align="right">

[![CircleCI](https://circleci.com/gh/microbit-foundation/microbit-universal-hex.svg?style=svg)](https://circleci.com/gh/microbit-foundation/microbit-universal-hex)

TypeScript/JavaScript library to create micro:bit Universal Hex files for
micro:bit.

The Universal Hex file format was created to be able to contain the binary data
for micro:bit V1 and V2 boards in a single file, so that it works in all
versions of the micro:bit.

## Documentation

The documentation can be found in
https://microbit-foundation.github.io/microbit-universal-hex/.

## npm Package

To add this package to your project:

```
npm install @microbit/microbit-universal-hex
```

## Web Tool

<img width="18%" alt="microbit-universal-hex logo" src="docs/img/web-tool-screenshot.png" align="left">

An implementation example can be found in the
[docs/examples/webtool.html](docs/examples/webtool.html) file. This web tool can
generate a Universal Hex from two Intel Hex files.

It can be accessed online on this URL:
https://tech.microbit.org/software/universal-hex-creator/

## License

This software is under the MIT open source license.

[SPDX-License-Identifier: MIT](LICENSE.md)
npm package: @microbit/ml-header-generator
Description: A simple TS script to generate a header blob for the ML runner
Author: Micro:bit Educational Foundation
Latest version: 0.4.3

# ML Model Header Generator

## Instructions

Install dependencies:

```bash
npm install
```

Change the header data in `input.data.ts and run the script:

```bash
npm run start
```

The data converted as a C array and DeviceScript hex template literal
will be printed to console.
npm package: @microbit/python-editor-embed
Description: <a href="https://microbit-foundation.github.io/python-editor-embed/" class="typedoc-ignore">This documentation is best viewed on the documentation site rather than GitHub or NPM package site.</a>
Author: Micro:bit Educational Foundation
Latest version: 0.2.0

# Python Editor Embed

<a href="https://microbit-foundation.github.io/python-editor-embed/" class="typedoc-ignore">This documentation is best viewed on the documentation site rather than GitHub or NPM package site.</a>

This is a React/JavaScript library for embedding micro:bit Python Editor as an iframe.

It is intended to be used by other Micro:bit Educational Foundation projects
that need to embed Python Editor and, when the API stabilises, to be useful to others who embed Python Editor.

- [StoryBook demo of the components](https://python-editor-embed.pages.dev/)

## Usage

- [React usage documentation](docs/react.md)
- [VanillaJS usage documentation](docs/vanilla.md)

## License

This software is under the MIT open source license.

[SPDX-License-Identifier: MIT](LICENSE.md)

We use dependencies via the NPM registry as specified by the package.json file under common Open Source licenses.

Full details of each package can be found by running `license-checker`:

```bash
$ npx license-checker --direct --summary --production
```

Omit the flags as desired to obtain more detail.

## Code of Conduct

Trust, partnership, simplicity and passion are our core values we live and
breathe in our daily work life and within our projects. Our open-source
projects are no exception. We have an active community which spans the globe
and we welcome and encourage participation and contributions to our projects
by everyone. We work to foster a positive, open, inclusive and supportive
environment and trust that our community respects the micro:bit code of
conduct. Please see our [code of conduct](https://microbit.org/safeguarding/)
which outlines our expectations for all those that participate in our
community and details on how to report any concerns and what would happen
should breaches occur.
npm package: @microbit/smoothie
Description: Smoothie Charts: smooooooth JavaScript charts for realtime streaming data
Author: Joe Walnes
Latest version: 1.37.0-microbit.2

# Heads up

This is a fork of [smoothie](https://github.com/joewalnes/smoothie) for micro:bit CreateAI. It's otherwise unsupported by the Foundation. Changes:

- Added support for the `lineDash` property (charts using a fixed y-axis and linear interpolation only).

# Original documentation

[![npm version](https://img.shields.io/npm/v/smoothie.svg)](https://www.npmjs.com/package/smoothie)

*Smoothie Charts* is a really small charting library designed for _live
streaming data_. I built it to reduce the headaches I was getting from
watching charts jerkily updating every second.

See [http://smoothiecharts.org](http://smoothiecharts.org)

---

### Getting Started

*   [Hello world example](http://smoothiecharts.org/examples/example1.html)
*   [Another example (server CPU usage)](http://smoothiecharts.org/examples/server-load.html)
*   [Another example (responsive layout)](http://smoothiecharts.org/examples/responsive.html)
*   [Tutorial](http://smoothiecharts.org/tutorial.html)
*   [Interactive builder](http://smoothiecharts.org/builder/)
*   Just the JavaScript: [smoothie.js](http://github.com/joewalnes/smoothie/raw/master/smoothie.js)
*   Full distribution (docs and examples): [zip](http://github.com/joewalnes/smoothie/zipball/master) or [tgz](http://github.com/joewalnes/smoothie/tarball/master)
*   Repository: `git clone git@github.com:joewalnes/smoothie.git`
*   Bower: `bower install smoothie`
*   NPM: `npm install smoothie`
*   Yarn: `yarn add smoothie`
*   [Introducing Smoothie Charts](http://joewalnes.com/2010/08/10/introducing-smoothie-charts/) (blog entry)

---

### Example

Given a `<canvas>`:

```html
<canvas id="chart" width="400" height="100"></canvas>
```

Create a time series and chart with code resembling:

```js
// Create a time series
var series = new TimeSeries();

// Find the canvas
var canvas = document.getElementById('chart');

// Create the chart
var chart = new SmoothieChart();
chart.addTimeSeries(series, { strokeStyle: 'rgba(0, 255, 0, 1)' });
chart.streamTo(canvas, 500);
```

Then, add data to your time series and it will be displayed on the chart:

```js
// Randomly add a data point every 500ms
setInterval(function() {
    series.append(Date.now(), Math.random() * 10000);
}, 500);
```

---

### Questions

For help, use the [Smoothie Charts Google Group](http://groups.google.com/group/smoothie-charts).

---

[License](http://smoothiecharts.org/LICENSE.txt) (MIT)

- [Joe Walnes](https://joewalnes.com/)
- [Drew Noakes](https://drewnoakes.com/)
npm package: @microbitsclub/microbits-client
Description: Microbits API client
Author: Microbits
Latest version: 0.3.0

# Microbits Typescript Client

Wrapper around the Microbits HTTP API.

## Installation

```
npm install @microbitsclub/microbits-client
```

## Configuration

[Get your merchant ID and API key](https://microbits.club/a/signin?redirect=https%3A%2F%2Fmicrobits.club%2Fa%2Fdevelopers).

## Usage

Create a `MicrobitsClient` instance.

```typescript
const microbits = new MicrobitsClient({
    merchantId: '<your_merchant_id>',
    apiKey: '<your_api_key>',
});
```

Create a `RequestHandlerConfig` object.

```typescript
interface Ctx {
    request: FastifyRequest;
    reply: FastifyReply;
}

const microbitsConfig: RequestHandlerConfig<Ctx> = {
    microbits,
    getUserSessionIdCookie(ctx, name) {
        return ctx.request.cookies[name];
    },
    setUserSessionIdCookie(ctx, name, userSessionId) {
        ctx.reply.setCookie(name, userSessionId, {
            path: '/',
            maxAge: 60 * 60 * 24 * 7,
            secure: true,
            httpOnly: false,
        });
    },
};
```

`getUserSessionIdCookie` must return the value of the named cookie.

`setUserSessionIdCookie` must set the value of the named cookie to `userSessionId`. The cookie must **not** be HttpOnly in order for the client paywall to be able to access it.

Create configured request handlers.

```typescript
const clientRequestHandler = getClientRequestHandler<Ctx>(microbitsConfig);
const paywallRequestHandler = getContentRequestHandler<Ctx>(microbitsConfig);
```

Forward GET requests to the client and paywall request handlers.

```typescript
fastify.route({
    method: 'GET',
    url: `${DEFAULTS.MERCHANT_ROUTE_PREFIX}/*`,
    async handler(request, reply) {
        const result = await microbitsClientRequestHandler({ request, reply }, request.url);
        reply.send(result);
    },
});
```

```typescript
fastify.route({
    method: 'GET',
    url: '/story/:storyId',
    async handler(request, reply) {
        const result = await microbitsPaywallRequestHandler({ request, reply }, request.url);

        if (result.type === 'error') {
            reply.status(result.error.statusCode);
            reply.send(result.error.message);
            return;
        }

        if (result.ok.type === 'serve-content') {
            const { storyId } = request.params as { storyId: string };

            const story = stories.find(x => x.id === storyId);

            if (story === undefined) {
                reply.status(404);
            } else {
                reply.status(200);
                reply.send(story);
            }
        } else {
            reply.status(204);
            reply.send(result.ok.contentUrl);
        }
    },
});
```

Here we assume that there is a single group URL paywall for the path `/story`.

TODO hard paywall
npm package: @microbitsclub/paywall-react
Description: React wrapper for Microbits paywalls
Author: Microbits
Latest version: 0.3.0

# Microbits Paywall for React

Renders a popup paywall for paywalled microbits content.

## Installation

```
npm install @microbitsclub/paywall-react
```

## Configuration

[Get your merchant ID](https://microbits.club/a/signin?redirect=https%3A%2F%2Fmicrobits.club%2Fa%2Fdevelopers).

## Usage

Create a `PaywallPopoverConfig` instance. 

```typescript
import { stringifyUrl } from '@microbitsclub/paywall-react/dist/src/url';

const paywallPopoverConfig: PaywallPopoverConfig = {
    merchantId: '<your_merchant_id>',

    // Compute the final URL for paywalled content.
    getContentUrl(path, query) {
        return stringifyUrl({
            proto: 'http',
            hostname: 'localhost',
            port: 3000,
            ...path,
            query,
        });
    },
    
    // Compute the final URL for requests to your server. These requests are
    // handled by @microbitsclub/microbits-client request handlers.
    getServerUrl: (path, query) => {
        return stringifyUrl({
            proto: 'http',
            hostname: 'localhost',
            port: 7000,
            ...path,
            query,
        });
    },
};
```

Wrap your React components with `PaywallPopoverProvider` wherever a popover paywall should be displayed.

```typescript
const App: FC<AppProps> = props => {
    return (
        <PaywallPopoverProvider config={paywallPopoverConfig}>
            <StoryList>
                {props.stories.map(({ id, title }) => (
                    <StoryCard key={id} id={id} title={title} />
                ))}
            </StoryList>
        </PaywallPopoverProvider>
    );
}
```

Intercept link clicks and use the `attempNavigateToContent` hook API.

```typescript
const StoryCard: FC<StoryCardProps> = props => {
    const contentUrl = `/story/${props.id}`;
    const popoverPaywall = usePaywallPopover();

    const handleClick = useCallback<MouseEventHandler>(
        e => {
            // Prevent the default action
            e.preventDefault();

            // Handle the attempted navigation
            popoverPaywall.attempNavigateToContent(contentUrl);
        },
        [contentUrl, popoverPaywall]
    );

    return (
        <StoryLinkBox>
            <a href={contentUrl} onClick={handleClick}>{props.title}</a>
        </StoryLinkBox>
    );
}
```