# amps

> AMPS JavaScript Client Library

Latest version **5.3.4-0.378635.60b2fcc** (published 2024-05-17) · SEE LICENSE IN LICENSE license · 0 weekly downloads

## Install

```sh
npm install amps
pnpm add amps
yarn add amps
bun add amps
```

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities.

Warnings: low downloads; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 5.3.4-0.378635.60b2fcc |
| Published | 2024-05-17 |
| First published | 2017-05-08 |
| Weekly downloads | 0 |
| License | SEE LICENSE IN LICENSE |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 2 |
| Unpacked size | 1.4 MB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | 60East Technologies Inc. |
| Maintainers | 60east |

## Links

- npm: https://www.npmjs.com/package/amps
- Homepage: http://www.crankuptheamps.com/
- Issues: https://support.crankuptheamps.com/
- npm.io page: https://npm.io/package/amps

## Dependencies (2)

- [websocket](https://npm.io/package/websocket.md) 1.0.35
- [es6-promise](https://npm.io/package/es6-promise.md) ^3.2.1

## Recent versions

- 5.3.4-0.378635.60b2fcc (latest) — 2024-05-17
- 9.9.9-9.373745.60b2fcc (beta) — 2024-05-15
- 9.9.9-9.119412.4170b07 — 2024-02-12
- 9.9.9-9.65495.1871969 — 2024-01-23
- 9.9.9-9.65298.1871969 — 2024-01-23
- 5.3.3-1.341463.3178107 — 2022-05-04
- 9.9.9-9.341184.1d9225b — 2022-05-04
- 5.3.3-0.270116.30a8532 — 2022-04-08
- 9.9.9-9.265065.30a8532 — 2022-04-07
- 9.9.9-9.265019.936db23 — 2022-04-06
- 9.9.9-9.220837.27db105 — 2022-03-21
- 9.9.9-9.799715.c785972 — 2021-10-19
- 9.9.9-9.796992.d300665 — 2021-10-18
- 5.3.2-0.751550.05a2849 — 2020-10-01
- 9.9.9-9.751309.05a2849 — 2020-09-30
- … 55 more at https://npm.io/package/amps/versions

## README

## AMPS JavaScript Client


##### *powerful. fast. easy.*

The AMPS JavaScript Client lets you write cross-platform messaging applications for both web apps working in a browser,
as well as server-side applications that use Node.js. It uses the power of WebSocket technology combined with
the asynchronous nature of JavaScript.
<br><br>


### Installation

The client can be installed using NPM or manually downloaded from the releases page.

```bash
npm install --save amps
```


### Quick Start

Once the client is downloaded, it can be used in your JavaScript/TypeScript projects:

**Node.js**:
```javascript
const { Client } = require('amps');
console.log(Client.version());
```


**TypeScript**
```typescript
// NPM installation: Import everything at once
import * as amps from 'amps';
console.log(amps.Client.version());

// or

// NPM installation: This way the final bundle can be smaller
import { Client, Command } from 'amps';
console.log(Client.version());

// Manual installation (don't forget to add a typing reference):
/// <reference path="./amps.d.ts" />
import * as amps from './amps';
import { Client, Command } from './amps';
```


**Application that uses AMD modules**:
```javascript
define(['dist/amps'], amps => {
    console.log(amps.Client.version());
});
```


**Global import in Browser:**
```html
<!-- Optional import, provides support for obsolete browsers like IE11 -->
<script src="es6-promise.min.js"></script>
<script src="amps.js"></script>
```


You are now ready to use AMPS in your project!
Here are a few JavaScript examples to get you started:
<br><br>

#### EXAMPLE 1: CONNECT AND SUBSCRIBE

```javascript
import { Client } from 'amps';


(async () => {
  const client = new Client('my-application');

  try {
    await client.connect('ws://localhost:9100/amps/json');

    // Connected, let's subscribe to a topic now
    const subscriptionId = await client.subscribe(
        message => console.log(message.data),
        'orders'
    );

    // Once we subscribed, the subscriptionId is returned
    console.log(subscriptionId);

    client.publish('orders', {order: 'Tesla 3', qty: 10});
  }
  catch (err) {
    // This can be either a connection error or a subscription error
    console.log(err);
  }
})();
```

In this example, we connect to an AMPS server running locally and initiate a subscription to the "orders" topic.
As new orders are posted, the message handler is invoked with each message, and prints the data of each order to
the console:

```javascript
const onMessage = message => console.log('message: ', message);

// ... in asynchronous context
try {
  // subscribe for the first topic
  await client.subscribe(onMessage, 'orders');

  // second subscription
  await client.subscribe(onMessage, 'reservations');

  // third subscription
  await client.subscribe(onMessage, 'notifications');
}
catch (err) {
  // if any subscription failed, the error will end up here
  console.error('subscription error:', err);
}
``` 
Since every command (except publish()) is asynchronous and returns a Promise object, it is very easy
to chain commands and handle errors.
<br><br>


#### EXAMPLE 2: PUBLISH A MESSAGE

```javascript
// ... in asynchronous context
try {
  const client = new Client('publish-example');
  await client.connect('ws://localhost:9100/amps/xml');
  client.publish('messages', '<hi>Hello, world!</hi>');
}
catch (err) {
  console.log(err);
}
```

With AMPS, publishing is simple, as shown in this example. We connect to an AMPS server running locally, and publish a
single message to the `messages` topic. To simply publish a message, there is no need to predeclare the topic or
configure complex routing. Any subscription that has asked for XML messages on the `messages` topic will receive
the message.
<br><br>


#### EXAMPLE 3: DISCONNECT HANDLING

```javascript
import { Client } from 'amps';


// simple sleep/pause async function
const sleep = interval => new Promise(resolve => setTimeout(resolve, interval));

// Assign an error handler that will handle general error such as disconnects
const client = new Client('my-app').errorHandler(async err => {
    // Error handler is only called if an error occurred after
    // a successful connection has been established.
    client.disconnect();

    // wait for 5 seconds before attempting to connect
    console.error(err, 'Reconnecting after 5 seconds...');
    await sleep(5000);

    reconnect();
});

async function reconnect() {
    try {
      await client.connect('wss://localhost:9100/amps/json');

      // connected, let's subscribe
      try {
        await client.subscribe(message => console.log('message: ', message), 'orders');
      }
      catch (err) {
        console.error('Subscription error: ', err);
      }
    }
    catch (err) {
      console.error('Connection error: ', err);
      await sleep(5000);
      reconnect();
    }
}

// Begin by connecting and subscribing
reconnect();
```

In this example, we need to be subscribed to the "orders" topic, even if connectivity to our AMPS server is temporarily
interrupted. We use a reconnect function to enable recovery from a connection error.
When AMPS detects a connection error, the reconnect function is called from **errorHandler** to re-establish connection,
and our onConnect method subscribes to the topic again once a successful connection is made. Notice that the
**errorHandler** is only called after a successful connection has been established, otherwise a connection error is
caught by the `catch` callback of the **connect** Promise.
<br><br>


#### EXAMPLE 4: QUERY THE CONTENTS OF A "SOW" TOPIC

State-of-the-World ("SOW") topics in AMPS combine the power of a database table with the performance of a
publish-subscribe system. Use the AMPS JavaScript client to query the contents of a SOW topic.

```javascript
// ... in asynchronous context
try {
  const client = new Client('my-application');
  await client.connect('ws://localhost:9100/amps/json');
  await client.sow(
      message => {
        if (message.header.command() == 'sow') {
            console.log(message.data);
        }
      },
      'orders',
      "/symbol='ROL'",
      {
          batchSize: 100,
          timeout: 5000
      }
  );
}
catch (err) {
  console.error('Error: ', err);
}
```

This example queries for all orders for the symbol `ROL`, and simply prints the messages to the console.
<br><br>


#### EXAMPLE 5: COMMAND INTERFACE

Even though AMPS clients provide the above named convenience methods for core AMPS functionality,
you can use the Command object to customize the messages that AMPS sends. This is useful for more advanced
scenarios where you need precise control over the message, or in cases where you need to use an earlier version of
the client to communicate with a more recent version of AMPS, or in cases where a named method is not available.

```javascript
// ... in asynchronous context
try {
  const client = new Client('my-application');
  await client.connect('ws://localhost:9100/amps/json')

  const subCmd = new Command('subscribe').topic('messages').filter('/id > 20');
  await client.execute(subCmd, message => console.log('message: ', message.data));
}
catch (err) {
  console.error('Error: ', err);
}
```

This example provides the subscription to a 'messages' topic with a filter applied.
<br><br>



### AMPS Server Configuration for Websockets

To configure AMPS for Websocket support, you need to specify the following Transport:

```html
<Transports>
    <Transport>
        <Name>json-websocket</Name>
        <Type>tcp</Type>
        <Protocol>websocket</Protocol>
        <InetAddr>9100</InetAddr>
        <MessageType>json</MessageType>
    </Transport>
</Transports>
```

With the above configuration, **AMPS** will listen for incoming Websocket connections on port **9100** and will support
the `json` message type. To use TLS/SSL, you'd specify a `Certificate` and `PrivateKey` (and optionally the Ciphers):

```html
<Transport>
    <Name>json-websocket-secure</Name>
    <Type>tcp</Type>
    <Protocol>websocket</Protocol>
    <InetAddr>9443</InetAddr>
    <MessageType>json</MessageType>
    <Certificate>./cert.pem</Certificate>
    <PrivateKey>./key.pem</PrivateKey>
    <Ciphers>HIGH:!aNULL:!MD5:@STRENGTH</Ciphers>
</Transport>
```
You can read more about it in the AMPS User Guide.


#### Authentication

Starting from **5.2.0.0**, AMPS provides a new option for websocket protocol: **WWWAuthenticate**. This option provides
a flexible way of setting up authentication for the JavaScript client.

The option can have the following values:
* Negotiate (Kerberos)
* NTLM
* Basic realm="Secure Area" (Basic Auth)

When using **Negotiate** or **NTLM**, you don't have to do anything from the JavaScript client, it's automatically
handled by browser/environment. In case of using **Basic Auth** (we recommend using **wss** in this scenario), you'll
need to set a URI of the form `wss://user:password@ip:port/amps/json`.

<br>
By default, no authentication is performed until the 'logon' command is performed after connection.

<br>
In order to enable authentication for AMPS JavaScript client, you need to specify the following settings:

1. Add a protocol in the `Protocols` section of the config:
```xml
<Protocol>
    <Name>websocket-portal</Name>
    <Module>websocket</Module>
    <WWWAuthenticate>Basic realm="Secure Area"</WWWAuthenticate> <!-- Basic Auth -->
    <WWWAuthenticate>Negotiate</WWWAuthenticate> <!-- Kerberos-->
    <WWWAuthenticate>NTLM</WWWAuthenticate> <!-- NTLM -->
</Protocol>
```

2. Specify a transport in the `Transports` section of the config that will be used for the JavaScript client:
```xml
<Transport>
    <Name>websocket-auth</Name>
    <Type>tcp</Type>
    <Protocol>websocket-portal</Protocol>
    <InetAddr>9002</InetAddr>
</Transport>
```
<br><br>



#### EVERYTHING YOU NEED
If you need more help getting started, the 60East Technologies support and services team is ready to provide the
support you need to help you CRANK UP THE AMPS.
<br><br>

---
_Source: https://npm.io/package/amps · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
