open-index/open-npm huggingface dataset:
npm package: @rukmanamreza/apollo-datasource-graphql
Description: Create Apollo DataSource to connect to a GraphQL API
Author: Kristy Miller
Latest version: 1.3.2

# apollo-datasource-graphql

Forked from https://www.npmjs.com/package/apollo-datasource-graphql with below changes:
- Fix error messages
- Add timeout

Connect your GraphQL server to an existing GraphQL API using DataSources.

**Note: This is designed to work with  [Apollo Server 2.0](https://www.apollographql.com/docs/apollo-server/whats-new.html) and [Data Sources](https://www.apollographql.com/docs/apollo-server/features/data-sources.html)**

## GraphQL Data Source

### Install

```
yarn add apollo-datasource-graphql
```

or

```
npm i apollo-datasource-graphql --save
```

### Usage

Define a data source by extending the `GraphQLDataSource` class. You can then implement the queries and mutations that your resolvers require.


```javascript
import { GraphQLDataSource } from 'apollo-datasource-graphql';
import { gql } from 'apollo-server-express';

const CRAFT_BEERS = gql`
  query {
    craftBeers {
      name
      style
      abv
      brewery {
        name
      }
    }
  }
`;

export class CraftBeerGraphQLAPI extends GraphQLDataSource {
  baseURL = 'https//craft-beer-api.example/graphql';

  async getCraftBeers() {
    try {
      const response = await this.query(CRAFT_BEERS);

      return response.data.craftBeers;
    } catch (error) {
      console.error(error);
    }
  }
}
```

### GraphQL Operations

The `query` and `mutation` methods on the `GraphQLDataSource` make a request to the GraphQL server. Both accepts a second parameter, `options`, which can be used to pass variables, context, etc.

```javascript
async searchCraftBeerByName(name) {
  try {
    const response = await this.query(CRAFT_BEERS, {
      variables: {
        name,
      },
    });

    return response.data.craftBeer;
  } catch (error) {
    console.error(error);
  }
}
```

|Parameter   |Description   |Required|
|---|---|---|
|graphQLDocument|A GraphQL document|true|
|options|An object that defines options to pass with the GraphQL request|false|


|Options   |Description   |Required|
|---|---|---|
|variables|A GraphQL document|false|
|operationName|A string name of the query if it is named, otherwise it is null|false|
|context|Metadata to be passed between Apollo Links|false|
|extensions|A map to store extensions data to be sent to the server|false|

### Intercepting Operations

You can intercept the request to set headers on an outgoing request. Since Apollo Data Sources have access to GraphQL context, you can store a user token or other information you need to have available when making a request.

Add the method `willSendRequest` to your class which will receive the `request` object. Here, you can modify the request to meet your needs.

```javascript
  willSendRequest(request) {
    const { accessToken } = this.context;

    if (!request.headers) {
      request.headers = {};
    }

    request.headers.authorization = accessToken;
  }
```

## TODO

- [x] Complete README
- [x] Mutation method
- [ ] Test Suite
- [ ] Request caching
npm package: @rula/feathers-authentication-cas
Description: A Central Authentication Service (CAS) strategy for @feathersjs/authentication using Passport.
Author: David Quast
Latest version: 2.0.0

> A Central Authentication Service (CAS) strategy for @feathersjs/authentication using Passport.

## Installation

```
npm install @rula/feathers-authentication-cas --save
```

**Note:** This is only compatible with `feathers-authentication^1.x`.

## Example

```js
const feathers = require('@feathersjs/feathers');
const authentication = require('feathers-authentication');
const jwt = require('feathers-authentication-jwt');
const cas = require('@rula/feathers-authentication-cas');

const app = feathers();

//Setup authentication
app.configure(authentication(settings));
app.configure(jwt());
app.configure(cas({
  casUrl: "https://cas.example.com",
  serviceBaseUrl: "http://localhost:8080",
  servicePath: "/login/validate",
  version: "3.0",
  useSAML: false,
  path: "/login",
  failureRedirect: "/login",
  successRedirect: "/",
  propertyMap: {
    isFromNewLogin: "newLogin",
    longTermAuthenticationRequestTokenUsed: "longAuth"
  }
}));
```

Now starting the test server `npm start` and opening a browser to
`localhost:8080/login` should redirect to your CAS login provider. Upon 
successful login, you will be redirected back to `/` while being logged in and
any futher page authentication can be done with the JWT.

## License

Copyright (c) 2018

Licensed under the [MIT license](LICENSE)
npm package: @rula/loopback-component-cas
Description: Loopback component used to add CAS authentication via Passport.  Similar to `loopback-component-passport`.
Author: Ryerson University Library
Latest version: 1.0.4

# loopback-component-cas

This module provides integration between [LoopBack](http://loopback.io) and [Passport](http://passportjs.org) to support Central Authentication Service (CAS) login for LoopBack applications.

It is based off `loopback-component-passport` and has been created to work
in situations when only CAS authentication is deired.  It does not support a number of the features (e.g. account linking) that are provided by `loopback-component-passport`.

## Installation

`npm install --save @rula/loopback-component-cas`
npm package: @rula/passport-cas
Description: A Passport authentication strategy that works with the Central Authentication Service (CAS) single sign-on protocol.
Author: Ryerson University Library
Latest version: 1.0.1

# passport-cas

[Passport](http://passportjs.org/) authentication strategy using a Central
Authentication Strategy ([CAS](https://wiki.jasig.org/display/CAS/Home)) server.
Supports CAS protocol versions 1.0, 2.0 and 3.0.

```
npm install @rula/passport-cas
```

### Configure Strategy

Minimum configuration requires the CAS url and service parameters to be defined.

```
passport.use(new (require('passport-cas').Strategy) ({
  casUrl: 'http://cas.example.com',
  serviveUrl: `http://localhost:3000'
}, function(req, user, done) {
  User.findOne({username: user.username}, function(err, user) {
    if (err) {
      return done(err);
    }
    if (!user) {
      return done(null, false, {message: "Unknown user'});
    }
    return done(null, user);
  });
}));
```

### Authenticate Requests

Using the Express Passport middleware as an example:

```
exports.casLogin = function(req, res, next) {
  passport.authenticate('cas', function (err, user, info) {
    if (err) {
      return next(err);
    }

    if (!user) {
      req.session.messages = info.message;
      return res.redirect('/');
    }

    req.logIn(user, function (err) {
      if (err) {
        return next(err);
      }

      req.session.messages = '';
      return res.redirect('/');
    });
  })(req, res, next);
};
```
npm package: @rula/web-components
Description: A collection of web components created for use in various Ryerson University Library projects.
Author: Ryerson University Library and Archives
Latest version: 1.6.6
Deprecated: This package is no longer in development and has been superseeded by @ryelib/web-components

[![Codacy Badge](https://api.codacy.com/project/badge/Grade/6bb17d1d19e240f0a354d76d079c68d7)](https://www.codacy.com/project/ryersonlibrary/web-components/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=ryersonlibrary/web-components&amp;utm_campaign=Badge_Grade_Dashboard)

# RULA Web Components

A collection of web components built using the StencilJS compiler.  These components are still in the early stages of development and are subject to changes.

## Using

### Node Modules

* Run ```npm install @rula/web-components --save```
* Put a script tag in the page head similar to ```<script src='node_modules/@rula/web-components/dist/rula.js'></script>```
* Use the components anywhere in your site.

### In another StencilJS app

* Run ```npm install @rula/web-components --save```
* Include the ```import '@rula/web-components';``` in part of the app structure.
* Use the components in your StencilJS app JSX.

## Components

Currently there are two components, `map` and `map-editor`.  Both serve the basic function of displaying a collection of elements on a map.  The editor adds additional functionality by allowing editing, adding and removing elements.
npm package: @rulaicd-lining/egg-sequelize-ts
Description: egg Sequelize typescript plugin
Author: jtyjty99999, stone-lyl, ZeekoZhu, rulaicd-lining
Latest version: 0.2.4

# egg-sequelize-ts

**注意：这个项目已经不再维护或更新。可能存在安全漏洞或与当前技术栈不兼容的风险。请考虑使用其他更现代的解决方案。**


## 更改
插件只是将 `egg-sequelize` 中的 sequelize 替换为 sequelize-typescript, 同时保证用户在 egg.js 创建的项目中使用 `egg-sequelize` 的方法尽量一致，在使用时的不同，我将下面一一阐述。 其他内容部分请查看 [egg-sequelize]('https://github.com/eggjs/egg-sequelize')。
此插件已在生产项目中得到实践。

## 目的
能让使用 `typescript` 编写的 egg.js 项目中能够使用 sequelize方法，并同时得到egg.js所赋予的功能。

## 安装
```bash
$ npm i --save egg-sequelize-ts
$ yarn add egg-sequelize-ts
```

## 配置
- Enable plugin in `config/plugin.js`
- 在 `config/plugin.js` 文件中引入 `egg-sequelize-ts` 组件

``` js
exports.sequelize = {
    enable: true,
    package: 'egg-sequelize-ts'
}
```

- Edit your own configurations in `conif/config.{env}.js`
在 `conif/config.{env}.js` 中编写 sequelize 配置

```js
    config.sequelize = {
        dialect: 'mysql',
        host: '127.0.0.1',
        port: 3306,
        database: 'database'
    };
```

## 例子
分别以 model/user.js 和 service/user.js 举例说明
> note 注意我们都是从 `sequelize-typescript` 中导出类名，方法，属性等。

```js
// app/model/user.js

/**
 * @desc 用户表
 */
import { AutoIncrement, Column, DataType, Model, PrimaryKey, Table } from 'sequelize-typescript';
@Table({
    modelName: 'user'
})
export class User extends Model<User> {

    @PrimaryKey
    @AutoIncrement
    @Column({
        type: DataType.INTEGER(11),
        comment: '用户ID',
        comment: 'user id'
    })
    id: number;

    @Column({
        comment: '用户姓名',
    })
    name: string;

    @Column({
        comment: '用户邮箱'
    })
    email: string;

    @Column({
        comment: '用户手机号码'
    })
    phone: string;

    @Column({
        field: 'created_at'
    })
    createdAt: Date;

    @Column({
        field: 'updated_at'
    })
    updatedAt: Date;
};
export default () => User;

```

```js
// app/service/user.js
import { Service } from 'egg';
import { Sequelize } from 'sequelize-typescript';

class UserService extends Service {
  async index() {
    const { or } = Sequelize.Op;
    const users = await this.ctx.model.User.findOne({
        where: {
            [or]: [
                { name, phone },
                { id }
            ]
        }
    });
    this.ctx.body = users;
  }
}
```
npm package: @rule.js/access-mate-elasticsearch
Description: Convert access-mate policies to elasticsearch filters.
Author: Jonathan Boudreau
Latest version: 0.17.1

# Access Mate: Elasticsearch Converter
Convert [Access-Mate][access-mate] access control lists to Elasticsearch
filters.

Usage:
```javascript
const AccessMate = require('@rule.js/access-mate')
const toElasticsearch = require('@rule.js/access-mate-elasticsearch')

const policies = AccessMate.policySet()
	.allow()
	.name('view any todo')
	.target('todo')
	.action('read')
	.condition()
	.true('subject.admin')
	.end()

	.allow()
	.name('read own todos')
	.target('todo')
	.action('read')
	.condition()
	.propsEqual('resource.owner', 'subject.id')
	.end()

	.deny()
	.name('read private todos')
	.target('todo')
	.action('read')
	.condition()
	.true('resource.private')
	.end()

	.end()

const filter = toElasticsearch(policies, {
	target: 'todo',
	action: 'read',
	subject: {
		id: 1,
		admin: false
	},
	environment: {}
})

console.log(JSON.stringify(filter, null, 2))
```

Would print the following:
```json
{
  "bool": {
    "should": [
      {
        "bool": {
          "must": [
            {
              "match_none": {}
            }
          ]
        }
      },
      {
        "bool": {
          "should": [
            {
              "bool": {
                "must": [
                  {
                    "term": {
                      "owner": 1
                    }
                  }
                ]
              }
            },
            {
              "bool": {
                "must_not": {
                  "bool": {
                    "must": [
                      {
                        "term": {
                          "private": true
                        }
                      }
                    ]
                  }
                }
              }
            }
          ]
        }
      }
    ]
  }
}
```

[access-mate]: https://github.com/AGhost-7/rule.js/tree/master/packages/access-mate
npm package: @rule.js/contextualize
Description: Serializable object assertions.
Author: Jonathan Boudreau
Latest version: 0.17.1

## Rule.js: Contextualize
The idea behind this module is to allow to bind properties on
every call done to a `Rule` object as though the property was
present on every object you're testing against. This allows,
for example, one to use the elasticsearch generator _with_
user login data. For example:

```javascript
const Rule = require('@rule.js/core').extend({
	contextualize: require('@rule.js/contextualize'),
	elasticsearch: require('@rule.js/elasticsearch')
})

const condition = Rule()
	.propEqual('user.name', 'creator')

const query = condition
	.contextualize({
		user: {
			name: 'foobar'
		}
	})
	.elasticsearch()

```

The `query` variable would then contain an elasticsearch query which looks
like the following:
```json
{
	"term": {
		"creator": "foobar"
	}
}
```
npm package: @rule.js/elasticsearch
Description: Serializable object assertions.
Author: Jonathan Boudreau
Latest version: 0.17.1

## Rule.js: Elasticsearch converter
Convert the `Rule` object into an elasticsearch query.

```javascript
const ruleElasticsearch = require('@rule.js/elasticsearch')()
const Rule = require('@rule.js/core').extend({}, {
	elasticsearch: ruleElasticsearch
})

Rule()
	.or()
		.and().equal('name', 'foobar').gt('age', 20).end()
		.lt('age', 10)
	.end()
	.elasticsearch()
```

Outputs:
```json
{
  "bool": {
    "must": [
      {
        "bool": {
          "should": [
            {
              "bool": {
                "must": [
                  {
                    "term": {
                      "name": "foobar"
                    }
                  },
                  {
                    "range": {
                      "age": {
                        "gt": 20
                      }
                    }
                  }
                ]
              }
            },
            {
              "range": {
                "age": {
                  "lt": 10
                }
              }
            }
          ]
        }
      }
    ]
  }
}
```
npm package: @rule.js/expression
Description: A simple language for expressing business rules.
Author: Jonathan Boudreau
Latest version: 0.17.2

## Rule.js: Expression Language
A simple language for expressing business rules.

### API
This module exports a single function. The function accepts an optional
constructor for the `@rule.js/core` module.

Example:
```js
const Rule = require('@rule.js/core').extend({}, {
	elasticsearch: require('@rule.js/elasticsearch')
})
const ruleExpression = require('@rule.js/expression')(Rule)

const rule = ruleExpression('"name" equal "sample"')
const query = rule.elasticsearch()

// query:
// {
//   "bool": {
//     "must": [
//       {
//         "term": {
//           "name": "sample"
//         }
//       }
//     ]
//   }
// }
```

### Language
The language is meant to be easy enough for non-programmers to pick up. There
are no functions or other more complex constructs.

#### Literals
There are currently only two types of literals: strings and booleans. Strings
_must_ always be double quoted. To place a double quote inside of a string, an
escape sequence must be used (`\"`).

Valid:
- `"hello"`
- `"this is \"a quote\""`
- `"this is a backslash: \\"`

Invalid:
- `'single quotes'`
- `"hello "quotes""`

#### Comparison Operators

##### `equal`
Tests if the key is equal to the given property.

Example:
```
"enabled" equal true
```

##### `not equal`
Compares if the key is not equal to the given property.

Example:
```
"status" not equal "disabled"
```

##### `is empty`
Tests if the given key is empty.

Example:
```
"quantity" is empty
```

##### `is not empty`
Inversion of the `is empty` operator.

Example:
```
"quantity" is not empty
```

##### `any`
Tests if the key is equal any of the given values.

Example:
```
"status" any ("open", "draft")
```

##### `not any`
Test if the given key is not equal any of the specified values.

Example:
```
"status" not any ("pending", "new")
```

##### `contains`
Test if the key contains the given value.

Example:
```
"hobbies" contains "Guitar"
```

##### `not contains`
Inverse of the contains operator.

Example:
```
"hobbies" not contains "Guitar"
```

##### `greater than`
Test if the key is less than the specified value.

Example:
```
"age" less than 21
```

##### `less than`
Test if the key is greater than the specified value.

Example:
```
"income" greater than 55374.19
```

#### Logical Operators

##### `and`
Combines two rules together. If one of them is false, the result from the
operator will be false.

Example:
```
"quantity" is not empty and "status" not equal "disabled"
```

##### `or`
Combines two rules togther. If one of them is truthful, the result from the
operator will be true.

Example:
```
"quantity" is empty or "status" equal "disabled"
```

You can mix logical operators together. For example:

```
"quantity" is empty or "status" is empty and "owner" is empty
```

#### Keys
You can do deep lookups with the following:

```
"person"."name" equal "Rick"
```
npm package: @rule.js/knex
Description: Serializable object assertions.
Author: Jonathan Boudreau
Latest version: 0.17.1

# Rule.js: KnexJs Module
Use your rule.js conditions with KnexJs!

Example:

```js
const Rule = require('@rule.js/core').extend({}, {
	knex: require('@rule.js/knex')()
})

const knex = require('knex')({ client: 'pg' })

knex('user')
	.select()
	.where(function() {
		Rule().equal('name', 'Joe Pass').knex(this)
	})
```

**Note**: This module automatically converts keys to snake case. If you don't
want it to do this, you can override it with:

```js
const Rule = require('@rule.js/core').extend({}, {
	knex: require('@rule.js/knex')(function(key) { return key })
})
```
npm package: @rulebased/cli
Description: Harness CLI - audit, init, recommend harness engineering setup for AI agents
Latest version: 1.2.0

# @rulebased/cli

CLI for harness engineering — audit, score, init, recommend, and eval-log.

Part of [@rulebased/harness](https://github.com/rulebased-io/harness).

## Usage

```bash
npx @rulebased/cli audit          # Audit harness coverage (34 checks, 0-100 score)
npx @rulebased/cli score          # Per-category detailed score report
npx @rulebased/cli init           # Initialize harness structure
npx @rulebased/cli recommend      # Recommend missing harness elements
npx @rulebased/cli eval-log       # Evaluate conversation log compliance
```

### Options

```
--json        JSON output (audit, score, recommend)
--force       Overwrite existing files (init)
--preset      Preset name: standard | minimal (init)
--file        Transcript file path (eval-log)
--short       Short output (audit)
```

## License

MIT
npm package: @rulebased/core
Description: Harness auditor, recommender, initializer - core logic for AI agent harness engineering
Latest version: 1.2.0

# @rulebased/core

Core logic for harness engineering auditing, recommendations, and initialization.

Part of [@rulebased/harness](https://github.com/rulebased-io/harness).

## API

```typescript
import { audit, formatReport, formatScore } from "@rulebased/core/auditor";
import { recommend, formatRecommendations } from "@rulebased/core/recommender";
import { initHarness } from "@rulebased/core/initializer";
import { parseTranscript, computeStats } from "@rulebased/core/transcript";
import { evaluateLog, formatLogEval } from "@rulebased/core/log-evaluator";
```

### audit(projectPath)

Runs 34 checks based on [OpenAI Codex harness standards](https://openai.com/index/unlocking-the-codex-harness/) and returns a scored report.

### recommend(report)

Generates prioritized recommendations from an audit report.

### initHarness(projectPath, options?)

Creates AGENTS.md, CLAUDE.md, specs/, tasks/, .harness.json in the target project.

### parseTranscript(filePath) / evaluateLog(stats)

Parses Claude Code JSONL transcripts and evaluates session compliance.

## License

MIT
npm package: @rulebricks/api
Description: Rulebricks API – Node SDK
Author: Rulebricks
Latest version: 0.1.5

![Banner](banner.png)

<p>
    <a href="https://www.npmjs.com/package/@rulebricks/api" alt="npm shield">
        <img src="https://img.shields.io/npm/v/@rulebricks/api" /></a>
    <a href="https://github.com/rulebricks/node-sdk" alt="License">
        <img src="https://img.shields.io/github/license/rulebricks/node-sdk" /></a>
</p>

## Documentation

The Rulebricks Node.js library provides convenient access to the Rulebricks API from JavaScript/TypeScript.

## Documentation

API reference documentation is available [here](https://rulebricks.com/docs).

## Installation

```
npm install --save @rulebricks/api
# or
yarn add @rulebricks/api
```

## Usage

```typescript
import { RulebricksClient } from '@rulebricks/api';

const rulebricks = new RulebricksClient({
  apiKey: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
  environment: 'https://rulebricks.com',
});

rulebricks.rules.solve('tJOCd8XXXX', {
  customer_id: 'anc39as3',
  purchase_history: ['t-shirt', 'mug'],,
  account_age_days: 4,
  last_purchase_days_ago: 3,
  email_subscription: false,
}, {
  // Request options (Optional, leave empty for default values)
  // timeoutInSeconds: 10, (Optional: Use this to override the default timeout in seconds)
  // maxRetries: 3, (Optional: Use this to override the default number of retries)
}).then((result) => {
  console.log(result);
}).catch((err) => {
  console.error(err);
});
```

## Handling errors

When the API returns a non-success status code (4xx or 5xx response), a subclass of `RulebricksApiError` will be thrown:

```ts
try {
    // ...
} catch (err) {
    if (err instanceof RulebricksApiError) {
        console.log(err.statusCode); // 400
        console.log(err.message); // "BadRequestError"
        console.log(err.body); // list of errors
    }
}
```

Error codes are as followed:

| Status Code | Error Type            |
| ----------- | --------------------- |
| 400         | `BadRequestError`     |
| 429         | `RateLimitError`      |
| 500         | `InternalServerError` |

## Contributing

This library is generated programmatically. We suggest [opening an issue](https://github.com/rulebricks/node-sdk/issues) to discuss any issues or feature requests with us.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE.txt) file for details.
npm package: @rulebricks/cli
Description: CLI for deploying and managing private Rulebricks instances
Author: Rulebricks
Latest version: 2.1.5

![Banner](./banner.png)

The Rulebricks CLI is a management utility that automates the creation and maintenance of private Rulebricks clusters, helping you deploy Rulebricks in customizable, high-throughput configurations on AWS, GCP, or Azure.

You can choose how much you would like the CLI to automate for you– use it to generate valid configuration values, automate infrastructure provisioning (via Terraform), software deployment (via Helm), or all of the above.

## Installation

```bash
npm install -g @rulebricks/cli
```

## Prerequisites

You must have a valid **Rulebricks license key**
to deploy using this CLI. You will be
requested for this key during project
configuration.

Rulebricks requires TLS. You will require either external-dns on your cluster to automatically add DNS records, or you will need **access** to manually add **DNS records** for the subdomain(s) where you would like to access your private deployment from.

Finally, you will need to have the following tools installed and ready on your machine:

- **Node.js** >= 20
- **kubectl** - Kubernetes CLI
- **Helm** >= 3.0
- **Terraform** >= 1.0 (for infrastructure provisioning)
- Cloud CLI (`aws`, `gcloud`, or `az`) configured for your provider

## Quick Start

```bash
# Configuration wizard (generates values.yaml)
rulebricks init

# Provision and/or deploy to your cluster
rulebricks deploy my-deployment
```

## Main Commands

| Command                     | Description                            |
| --------------------------- | -------------------------------------- |
| `rulebricks init`           | Interactive setup wizard               |
| `rulebricks deploy [name]`  | Deploy to Kubernetes                   |
| `rulebricks upgrade [name]` | Upgrade to a new version               |
| `rulebricks destroy [name]` | Remove a deployment                    |
| `rulebricks status [name]`  | Show deployment health                 |
| `rulebricks logs [name]`    | Inspect services                       |
| `rulebricks open [name]`    | Open the generated configuration files |

Use `rulebricks -h` to explore all commands, and add `-h` to any command to learn more about a particular command's options.

## Notes

There are a uniquely wide variety of customization options this CLI makes available (multi-cloud, hybrid vs. self-hosted database deployment, custom email templates, etc.), and not all combinations have been validated.

If you encounter any issue deploying your private Rulebricks cluster, please [email us](mailto:support@rulebricks.com) or [open an issue](https://github.com/rulebricks/cli/issues) and we will follow up promptly. If you are particularly familiar with helm/k8s, you are also free to review generated values.yaml files and reconcile them with our [Helm chart](https://github.com/rulebricks/helm).
npm package: @rulebricks/sdk
Description: Rulebricks API – Node SDK
Author: Rulebricks
Latest version: 2.5.4

![Banner](banner.png)

<p>
    <a href="https://www.npmjs.com/package/@rulebricks/sdk" alt="npm shield">
        <img src="https://img.shields.io/npm/v/@rulebricks/sdk" /></a>
    <a href="https://github.com/rulebricks/node-sdk" alt="License">
        <img src="https://img.shields.io/github/license/rulebricks/node-sdk" /></a>
</p>

## Documentation

Find detailed examples of using this SDK in our [examples repository](https://github.com/rulebricks/examples).
General API reference documentation is available on our User Guide [here](https://rulebricks.com/docs).

## Installation

```
npm install --save @rulebricks/sdk
# or
yarn add @rulebricks/sdk
```

## Usage

```typescript
import { RulebricksClient } from "@rulebricks/sdk";
import "dotenv/config";

// Initialize the Rulebricks client
const rb = new RulebricksClient({
  environment: process.env.RULEBRICKS_ENVIRONMENT || "https://rulebricks.com/api/v1",
  apiKey:
    process.env.RULEBRICKS_API_KEY || "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
});

rb.rules.solve('tJOCd8XXXX', {
  customer_id: 'anc39as3',
  purchase_history: ['t-shirt', 'mug'],,
  account_age_days: 4,
  last_purchase_days_ago: 3,
  email_subscription: false,
}, {
  // Request options (Optional, leave empty for default values)
  // timeoutInSeconds: 10, (Optional: Use this to override the default timeout in seconds)
  // maxRetries: 3, (Optional: Use this to override the default number of retries)
}).then((result) => {
  console.log(result);
}).catch((err) => {
  console.error(err);
});
```

## Handling errors

When the API returns a non-success status code (4xx or 5xx response), a subclass of `RulebricksApiError` will be thrown:

```ts
try {
    // ...
} catch (err) {
    if (err instanceof RulebricksApiError) {
        console.log(err.statusCode); // 400
        console.log(err.message); // "BadRequestError"
        console.log(err.body); // list of errors
    }
}
```

Error codes are as followed:

| Status Code | Error Type            |
| ----------- | --------------------- |
| 400         | `BadRequestError`     |
| 429         | `RateLimitError`      |
| 500         | `InternalServerError` |

## Contributing

This library is generated programmatically. We suggest [opening an issue](https://github.com/rulebricks/node-sdk/issues) to discuss any issues or feature requests with us.

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE.txt) file for details.
npm package: @rulecms/client
Description: RuleCMS client library for pulling content from RuleCMS backend.
Author: RuleCMS
Latest version: 0.3.0

# RuleCMS Client Library

This project is generated by [create-ts-fast](https://github.com/yangshun/create-ts-fast), a tool for scaffolding npm libraries written in TypeScript.

## Directory walkthrough

The project has the following files and directories:

```
├── .github/workflows/ci.yml
├── dist
├── src
│   ├── __tests__
│   └── index.ts
├── package.json
├── README.md
├── tsconfig.json
├── tsup.config.ts
└── vitest.config.ts
```

- `src`: Contains source code
  - `__tests__`: Directory containing tests. Code within `__tests__` will be ignored during build
  - `index.ts`: Main file
- `package.json`: Self explanatory
- `README.md`: Project's README file. Contents will be displayed on the package homepage on npmjs.com and repo homepage of github.com
- `tsconfig.json`: Base TypeScript config. Used when developing
- `tsup.config.json`: tsup config. Refer to its [documentation for customization](https://tsup.egoist.dev/#using-custom-configuration)
- `vitest.config.ts`: Vitest config. Refer to its [documentation for customization](https://vitest.dev/config/)
- `dist`: Directory containing generated files. The contents of this directory is published
- `.github/workflows/ci.yml`: GitHub action that runs typechecks, tests and build

## Next steps

1. Implement your library within `src`. Add tests if you take pride in being a developer
2. Modify `package.json` – update `name`, `version`, `author` and any other relevant fields
3. Update `README.md`
4. `npm publish`. You will have to login to npm if you aren't already logged in
5. Profit!

## Commands

- `npm run typecheck`: Checks code within `src` for TypeScript issues. No artifacts are generated
- `npm test`: Single test run using Vitest
- `npm run test:watch`: Watch mode. Runs all test suites and reruns them when there are changes
- `npm run build`: Compiles `src` into CommonJS and ES modules (along with TypeScript declaration files) into the `dist` directory
- `npm run verify`: Run typechecks + tests + build. Suitable when developing and in CI environments to ensure all checks are valid
- `npm run clean`: Deletes the `dist` directory
npm package: @ruleenginejs/compiler
Description: Rule engine compiler
Author: Nikolay Naumenkov
Latest version: 1.0.6

# @ruleenginejs/compiler

## Installation

```bash
npm install @ruleenginejs/compiler
```

## Usage

### Compile module

```js
const { compile } = require("@ruleenginejs/compiler");

const pipeline = compile(input, { runtimeModule: "@ruleenginejs/runtime" });
pipeline.execute();
```

### Generate code

```js
const { generateCode } = require("@ruleenginejs/compiler");

const code = generateCode(input, { runtimeModule: "@ruleenginejs/runtime" });
```

## License

Licensed under the [MIT License](./LICENSE).
npm package: @ruleenginejs/debug
Description: Rule engine debug
Author: Nikolay Naumenkov
Latest version: 1.0.6

# @ruleenginejs/debug

## Installation

```bash
npm install @ruleenginejs/debug
```

## Usage

```js
const debug = require("@ruleenginejs/debug")("ruleengine");

const pipeline = new Pipeline();
const logger = debug(pipeline);
await pipeline.execute();

logger.destroy();
```

### Run example

```bash
DEBUG=ruleengine node example/base.js
```

## License

Licensed under the [MIT License](./LICENSE).
npm package: @ruleenginejs/editor
Description: Rule Engine Editor
Author: Nikolay Naumenkov
Latest version: 1.2.8

# ruleengine-editor [![npm version](https://badge.fury.io/js/%40ruleenginejs%2Feditor.svg)](https://badge.fury.io/js/%40ruleenginejs%2Feditor)

> Pipeline editor made in node graph written in Vue 3.0

## Installation

```bash
npm install @ruleenginejs/editor @ruleenginejs/ui
```

Add Icons

```bash
npm install @vscode/codicons
```

In your code
```javascript
import "@vscode/codicons/dist/codicon.css"
```

## Usage

```javascript
import { createApp } from 'vue'
import App from './App.vue'
import RuleEngineEditor from "@ruleenginejs/editor"
// Add css styles
import "@ruleenginejs/ui/dist/normalize.css"
import "@ruleenginejs/ui/dist/style.css"
import "@ruleenginejs/ui/dist/dark.theme.css"
import "@ruleenginejs/editor/dist/style.css"

const app = createApp(App)

app.use(RuleEngineEditor)

app.mount('#app')
```

In your templates

```html
<v-editor value="editor value..." />
```

Example editor value

```json
{
  "title": "Title",
  "description": "Description",
  "steps": [
    {
      "id": 1,
      "type": "start",
      "connect": [
        {
          "stepId": 2,
          "dstInPort": "port1"
        }
      ],
      "canvas": {
        "position": [50, 50]
      }
    },
    {
      "id": 2,
      "type": "single",
      "name": "Example step",
      "props": {
        "a": 1,
        "b": 2
      },
      "handlerFile": "./handler.js",
      "ports": {
        "in": ["port1"],
        "out": ["port2"]
      },
      "connect": [
        {
          "stepId": 3
        }
      ],
      "canvas": {
        "position": [150, 50],
        "color": "#1795D4"
      }
    },
    {
      "id": 3,
      "type": "end",
      "canvas": {
        "position": [600, 150]
      }
    }
  ]
}
```

## License

Licensed under the [MIT License](./LICENSE).
npm package: @ruleenginejs/express
Description: Rule engine express middleware
Author: Nikolay Naumenkov
Latest version: 1.0.6

# @ruleenginejs/express

## Installation

```bash
npm install @ruleenginejs/express
```

## Usage

```js
const express = require("express");
const ruleEngine = require("@ruleenginejs/express");

const app = express();

app.use("/rules/:id", ruleEngine({
  "rule": require("./pipeline")
}))

app.listen(8080);
```

## Documentation

### Custom id param

```js
app.use("/rules/:ruleId", ruleEngine(rules, {
  idParam: "ruleId"
})
```

### Enable debug

```js
app.use("/rules/:id", ruleEngine(rules, {
  debug: app.get("env") === "development"
})
```

## License

Licensed under the [MIT License](./LICENSE).
npm package: @ruleenginejs/props-parser
Description: Props Parser
Author: Nikolay Naumenkov
Latest version: 1.0.3

# @ruleenginejs/props-parser

## Installation

```bash
npm install @ruleenginejs/props-parser
```

## Usage

### file.js

```js
// @prop('foo', 'string')
// @prop('foo', 'string', '1')
// @prop('bar', 'string', ['a', 'b', 'c'], 'b')
// @prop('baz', 'boolean', true)
export default (context, next) => {
  next();
}
```

### app.js

```js
const propsParser = require('@ruleenginejs/props-parser');
const fs = require('fs');

const contents = fs.readFileSync('file.js', 'utf8');
console.log(propsParser.parse(contents));

/*
[
  {
    type: 'string',
    prop: 'foo'
  },
  {
    type: 'string',
    prop: 'foo',
    default: '1'
  },
  {
    type: 'string',
    prop: 'bar',
    default: 'b',
    enum: ['a', 'b', 'c']
  },
  {
    type: 'boolean',
    prop: 'baz',
    default: true
  }
]
*/
```

## License

Licensed under the [MIT License](./LICENSE).
npm package: @ruleenginejs/rollup-plugin-rule
Description: Rollup plugin for compile rule files
Author: Nikolay Naumenkov
Latest version: 1.0.4

# @ruleenginejs/rollup-plugin-rule

> Compile rule files to javascript.

## Installation

```bash
npm install -D @ruleenginejs/rollup-plugin-rule
```

### Add Runtime

```bash
npm install @ruleenginejs/runtime
```

## Usage

```js
// rollup.config.js
import rule from '@ruleenginejs/rollup-plugin-rule';

export default {
  input: './main.js',
  plugins: [
    rule()
  ]
}
```

```js
// main.js
import rule from "./bar.rule";

rule.execute();
```

## Options

|                Name                 |        Type         |                   Default                    | Description                                                |
| :---------------------------------: | :-----------------: | :------------------------------------------: | :--------------------------------------------------------- |
|      **`checkSchema`**              |    `{Boolean}`      |                    `true`                    | Enables/disables the validation scheme for the rule files  |
|      **`runtimeModule`**            |    `{String}`       |         `'@ruleenginejs/runtime'`            | Runtime module name                                        |
|      **`moduleBaseDir`**            |    `{String}`       |                  `undefined`                 | Base path for import modules in rule files                 |
|        **`esModule`**               |    `{Boolean}`      |                    `true`                    | Enable/disable ES modules syntax                           |

## License

Licensed under the [MIT License](./LICENSE).
npm package: @ruleenginejs/rule-loader
Description: Rule loader for webpack
Author: Nikolay Naumenkov
Latest version: 1.0.7

# @ruleenginejs/rule-loader

> Rule loader for webpack.

## Installation

```bash
npm install -D @ruleenginejs/rule-loader
```

### Add Runtime

```bash
npm install @ruleenginejs/runtime
```

## Usage

### Config

#### webpack.config.js

```js
module.exports = {
  module: {
    rules: [
      {
        test: /\.rule$/,
        use: '@ruleenginejs/rule-loader'
      }
    ]
  }
};
```

#### App.js

```js
import rule from "./bar.rule";

rule.execute();
```

## Options

|                Name                 |        Type         |                   Default                    | Description                                                |
| :---------------------------------: | :-----------------: | :------------------------------------------: | :--------------------------------------------------------- |
|      **`checkSchema`**              |    `{Boolean}`      |                    `true`                    | Enables/disables the validation scheme for the rule files  |
|      **`runtimeModule`**            |    `{String}`       |         `'@ruleenginejs/runtime'`            | Runtime module name                                        |
|     **`moduleBaseDir`**             |    `{String}`       |                  `undefined`                 | Base path for import modules in rule files                 |
|     **`esModule`**                  |    `{Boolean}`      |                    `true`                    | Enable/disable ES modules syntax                           |

## License

Licensed under the [MIT License](./LICENSE).
npm package: @ruleenginejs/ruleengine-editor
Description: Rule Engine Editor
Author: Nikolay Naumenkov
Latest version: 1.2.0
Deprecated: This package is deprecated, please use @ruleenginejs/editor https://www.npmjs.com/package/@ruleenginejs/editor

# ruleengine-editor

> Pipeline editor made in node graph written in Vue 3.0

## Installation

```bash
npm install @ruleenginejs/ruleengine-editor
```

Add [codicons](https://github.com/microsoft/vscode-codicons)

```bash
npm install @vscode/codicons
```

In your code
```javascript
import "@vscode/codicons/dist/codicon.css"
```

## Usage

```javascript
import { createApp } from 'vue'
import App from './App.vue'
import RuleEngineEditor from "@ruleenginejs/ruleengine-editor"
// Add css styles
import "@ruleenginejs/ruleengine-ui/dist/normalize.css"
import "@ruleenginejs/ruleengine-ui/dist/dark.theme.css"
import "@ruleenginejs/ruleengine-editor/dist/style.css"

const app = createApp(App)

app.use(RuleEngineEditor)

app.mount('#app')
```

In your templates

```html
<v-editor value="editor value..." />
```

Example editor value

```json
{
  "title": "Title",
  "description": "Description",
  "steps": [
    {
      "id": 1,
      "type": "start",
      "connect": [
        {
          "stepId": 2,
          "dstInPort": "port1"
        }
      ],
      "canvas": {
        "position": [50, 50]
      }
    },
    {
      "id": 2,
      "type": "single",
      "name": "Example step",
      "props": {
        "a": 1,
        "b": 2
      },
      "handlerFile": "./handler.js",
      "ports": {
        "in": ["port1"],
        "out": ["port2"]
      },
      "connect": [
        {
          "stepId": 3
        }
      ],
      "canvas": {
        "position": [150, 50],
        "color": "#1795D4"
      }
    },
    {
      "id": 3,
      "type": "end",
      "canvas": {
        "position": [600, 150]
      }
    }
  ]
}
```

## License

Licensed under the [MIT License](./LICENSE).
npm package: @ruleenginejs/runtime
Description: Rule engine runtime
Author: Nikolay Naumenkov
Latest version: 1.0.6

# @ruleenginejs/runtime

## Installation

```bash
npm install @ruleenginejs/runtime
```

## Usage

```js
const {
  Pipeline,
  StartStep,
  EndStep,
  SingleStep,
  CompositeStep
} = require("@ruleenginejs/runtime");

const pipeline = new Pipeline();
const start = new StartStep();
const end = new EndStep();
const step = new SingleStep({
  handler: (context, next) => {
    next();
  }
});

start.connectTo(step);
step.connectTo(end);

pipeline.add(start, end, step);

const context = {};
pipeline.execute(context).catch(e => console.error(e));
```

## Documentation

### Step handlers

```js
handler: (context, next) => {
  next();
}
```

```js
handler: (context, port, next) => {
  next();
}
```

```js
handler: (context, port, props, next) => {
  next();
}
```

```js
handler: (err, context, port, props, next) => {
  next();
}
```

### Pipeline events

- `execute_start`
- `execute_error`
- `execute_end`
- `step_begin`
- `step_end`
- `step_error`

## License

Licensed under the [MIT License](./LICENSE).
npm package: @ruleenginejs/schema
Description: Rule engine schema
Author: Nikolay Naumenkov
Latest version: 1.0.6

# @ruleenginejs/schema

## Installation

```bash
npm install @ruleenginejs/schema
```

## Usage

```js
const schema = require("@ruleenginejs/schema")
const validate = schema(schema.SCHEMAS.PIPELINE)

if (!validate(data)) console.log(validate.errors)
```

## Schemas
- [pipeline-schema.json](./schema/pipeline-schema.json)

## License

Licensed under the [MIT License](./LICENSE).