fix
This commit is contained in:
Vendored
+19
File diff suppressed because one or more lines are too long
Vendored
+96
@@ -0,0 +1,96 @@
|
||||
import { Socket } from "./RPCSocketServer";
|
||||
declare type rpcType = 'hook' | 'unhook' | 'call';
|
||||
declare type visibility = 'public' | 'private';
|
||||
export declare type Outcome = "Success" | "Error";
|
||||
export declare class Response {
|
||||
message?: string | undefined;
|
||||
constructor(message?: string | undefined);
|
||||
}
|
||||
export declare class SuccessResponse extends Response {
|
||||
result: Outcome;
|
||||
constructor(message?: string);
|
||||
}
|
||||
export declare class ErrorResponse extends Response {
|
||||
result: Outcome;
|
||||
constructor(message?: string);
|
||||
}
|
||||
export declare class SubscriptionResponse extends SuccessResponse {
|
||||
uid: string;
|
||||
constructor(uid: string, message?: string);
|
||||
}
|
||||
export declare type UnhookFunction = (uid: string) => Promise<SuccessResponse | ErrorResponse>;
|
||||
export declare type callbackFunction = (...args: any[]) => Promise<SubscriptionResponse | ErrorResponse>;
|
||||
export declare type AsyncFunction = (...args: any[]) => Promise<any>;
|
||||
export interface RPCExporter {
|
||||
name: string;
|
||||
exportRPCs(): socketioRPC[];
|
||||
}
|
||||
declare type baseRPC = {
|
||||
type: rpcType;
|
||||
name: string;
|
||||
visibility: visibility;
|
||||
};
|
||||
declare type hookRPC = baseRPC & {
|
||||
type: 'hook';
|
||||
func: callbackFunction;
|
||||
unhook: UnhookFunction;
|
||||
};
|
||||
declare type unhookRPC = baseRPC & {
|
||||
type: 'unhook';
|
||||
func: UnhookFunction;
|
||||
};
|
||||
declare type callRPC = baseRPC & {
|
||||
type: 'call';
|
||||
func: (...args: any[]) => Promise<any>;
|
||||
};
|
||||
export declare type socketioRPC = callRPC | unhookRPC | hookRPC;
|
||||
export declare type baseInfo = {
|
||||
owner: string;
|
||||
argNames: string[];
|
||||
};
|
||||
declare type HookInfo = baseRPC & baseInfo & {
|
||||
type: 'hook';
|
||||
generator: (socket: any) => callbackFunction;
|
||||
unhook: UnhookFunction;
|
||||
};
|
||||
declare type UnhookInfo = baseRPC & baseInfo & {
|
||||
type: 'unhook';
|
||||
func: UnhookFunction;
|
||||
};
|
||||
declare type CallInfo = baseRPC & baseInfo & {
|
||||
type: 'call';
|
||||
func: AsyncFunction;
|
||||
};
|
||||
declare type RpcInfo = HookInfo | UnhookInfo | CallInfo;
|
||||
export declare type ExtendedRpcInfo = RpcInfo & {
|
||||
uniqueName: string;
|
||||
};
|
||||
export declare const rpcToRpcinfo: (rpc: socketioRPC, owner: string) => RpcInfo;
|
||||
export declare const rpcHooker: (socket: Socket, owner: string, RPCs: socketioRPC[], makeUnique?: boolean) => ExtendedRpcInfo[];
|
||||
declare type OnFunction = (type: 'error' | 'close', f: (e?: any) => void) => Socket;
|
||||
export declare type Socket = {
|
||||
port: number;
|
||||
hook: (rpcname: string, ...args: any[]) => Socket;
|
||||
unhook: (rpcname: string) => Socket;
|
||||
call: (rpcname: string, ...args: any[]) => Promise<any>;
|
||||
fire: (rpcname: string, ...args: any[]) => Promise<any>;
|
||||
on: OnFunction;
|
||||
destroy: () => void;
|
||||
close: () => void;
|
||||
};
|
||||
export declare type RPCSocketConf = {
|
||||
connectionHandler: (socket: Socket) => void;
|
||||
errorHandler: (socket: Socket) => (error: any) => void;
|
||||
closeHandler: (socket: Socket) => () => void;
|
||||
};
|
||||
export declare class RPCSocketServer {
|
||||
private port;
|
||||
private rpcExporters;
|
||||
private conf;
|
||||
private io;
|
||||
private wsServer;
|
||||
constructor(port: number, rpcExporters?: RPCExporter[], conf?: RPCSocketConf);
|
||||
private startWebsocket;
|
||||
protected initApis(socket: any): void;
|
||||
}
|
||||
export {};
|
||||
@@ -0,0 +1,152 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const http = require("http");
|
||||
const bsock = require("bsock");
|
||||
const uuid = require("uuid/v4");
|
||||
/* Responses */
|
||||
class Response {
|
||||
constructor(message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
exports.Response = Response;
|
||||
class SuccessResponse extends Response {
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.result = "Success";
|
||||
}
|
||||
}
|
||||
exports.SuccessResponse = SuccessResponse;
|
||||
class ErrorResponse extends Response {
|
||||
constructor(message = "Unknown error") {
|
||||
super(message);
|
||||
this.result = "Error";
|
||||
}
|
||||
}
|
||||
exports.ErrorResponse = ErrorResponse;
|
||||
class SubscriptionResponse extends SuccessResponse {
|
||||
constructor(uid, message) {
|
||||
super(message);
|
||||
this.uid = uid;
|
||||
}
|
||||
}
|
||||
exports.SubscriptionResponse = SubscriptionResponse;
|
||||
exports.rpcToRpcinfo = (rpc, owner) => {
|
||||
switch (rpc.type) {
|
||||
case "call":
|
||||
return {
|
||||
owner: owner,
|
||||
argNames: extractArgs(rpc.func),
|
||||
type: rpc.type,
|
||||
visibility: rpc.visibility,
|
||||
name: rpc.name,
|
||||
func: rpc.func,
|
||||
};
|
||||
case "unhook":
|
||||
return {
|
||||
owner: owner,
|
||||
argNames: extractArgs(rpc.func),
|
||||
type: rpc.type,
|
||||
visibility: rpc.visibility,
|
||||
name: rpc.name,
|
||||
func: rpc.func,
|
||||
};
|
||||
case "hook":
|
||||
const generator = hookGenerator(rpc);
|
||||
return {
|
||||
owner: owner,
|
||||
argNames: extractArgs(generator(undefined)),
|
||||
type: rpc.type,
|
||||
visibility: rpc.visibility,
|
||||
name: rpc.name,
|
||||
unhook: rpc.unhook,
|
||||
generator: generator,
|
||||
};
|
||||
}
|
||||
};
|
||||
exports.rpcHooker = (socket, owner, RPCs, makeUnique = true) => {
|
||||
const suffix = makeUnique ? "-" + uuid().substr(0, 4) : "";
|
||||
return RPCs.map(rpc => exports.rpcToRpcinfo(rpc, owner))
|
||||
.map(info => {
|
||||
const ret = info;
|
||||
ret.uniqueName = info.name + suffix;
|
||||
switch (info.type) {
|
||||
case "hook":
|
||||
socket.hook(ret.uniqueName, info.generator(socket));
|
||||
break;
|
||||
default:
|
||||
socket.hook(ret.uniqueName, info.func);
|
||||
}
|
||||
socket.on('close', () => socket.unhook(info.name));
|
||||
return ret;
|
||||
});
|
||||
};
|
||||
const hookGenerator = (rpc) => {
|
||||
const argsArr = extractArgs(rpc.func);
|
||||
argsArr.pop();
|
||||
const args = argsArr.join(',');
|
||||
return eval(`(socket) => async (` + args + `) => {
|
||||
const res = await rpc.func(` + args + (args.length !== 0 ? ',' : '') + ` (x) => {
|
||||
socket.call(res.uid, x)
|
||||
})
|
||||
if(res.result == 'Success'){
|
||||
socket.on('close', async () => {
|
||||
const unhookRes = await rpc.unhook(res.uid)
|
||||
console.log("Specific close handler for", rpc.name, res.uid, unhookRes)
|
||||
})
|
||||
|
||||
}
|
||||
return res
|
||||
}`);
|
||||
};
|
||||
const extractArgs = (f) => {
|
||||
let fn = String(f);
|
||||
let args = fn.substr(0, fn.indexOf(")"));
|
||||
args = args.substr(fn.indexOf("(") + 1);
|
||||
let ret = args.split(",");
|
||||
return ret;
|
||||
};
|
||||
class RPCSocketServer {
|
||||
constructor(port, rpcExporters = [], conf = {
|
||||
errorHandler: (socket) => (error) => { socket.destroy(); console.error(error); },
|
||||
closeHandler: (socket) => () => { console.log("Socket closing"); },
|
||||
connectionHandler: (socket) => { console.log("New websocket connection in port " + socket.port); }
|
||||
}) {
|
||||
this.port = port;
|
||||
this.rpcExporters = rpcExporters;
|
||||
this.conf = conf;
|
||||
this.io = bsock.createServer();
|
||||
this.wsServer = http.createServer();
|
||||
this.startWebsocket();
|
||||
}
|
||||
startWebsocket() {
|
||||
try {
|
||||
this.io.attach(this.wsServer);
|
||||
this.io.on('socket', (socket) => {
|
||||
socket.on('error', this.conf.errorHandler(socket));
|
||||
socket.on('close', this.conf.closeHandler(socket));
|
||||
this.initApis(socket);
|
||||
});
|
||||
this.wsServer.listen(this.port);
|
||||
}
|
||||
catch (e) {
|
||||
//@ts-ignore
|
||||
this.errorHandler(undefined)("Unable to connect to socket");
|
||||
}
|
||||
}
|
||||
initApis(socket) {
|
||||
const adminRPCs = [
|
||||
{
|
||||
name: 'info',
|
||||
type: 'call',
|
||||
visibility: 'private',
|
||||
func: async () => rpcInfos
|
||||
}
|
||||
];
|
||||
const rpcInfos = [
|
||||
...exports.rpcHooker(socket, "Admin", adminRPCs, false),
|
||||
...this.rpcExporters.flatMap(exporter => exports.rpcHooker(socket, exporter.name, exporter.exportRPCs()))
|
||||
];
|
||||
}
|
||||
}
|
||||
exports.RPCSocketServer = RPCSocketServer;
|
||||
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
declare type RPCReceiver = {
|
||||
[RPCGroup in string]: any;
|
||||
};
|
||||
/**
|
||||
* Dynamic library to communicate with FrontblockService remotely
|
||||
*
|
||||
* This will be automatically injected into the webpages served by FrontblockService
|
||||
* Will ask it's service for available RPCs and parse them into methods of this object
|
||||
* for convenient access.
|
||||
*/
|
||||
export declare class RPCaller implements RPCReceiver {
|
||||
private socket;
|
||||
constructor(port: number, server: string, tls?: boolean);
|
||||
connect(): Promise<void>;
|
||||
info(): Promise<any>;
|
||||
private callGenerator;
|
||||
private hookGenerator;
|
||||
private unhookGenerator;
|
||||
}
|
||||
export {};
|
||||
@@ -0,0 +1,71 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
var bsock = require('bsock');
|
||||
//fix args with defaults like "force = true" -> "force"
|
||||
function stripAfterEquals(str) {
|
||||
return str.split("=")[0];
|
||||
}
|
||||
/**
|
||||
* Dynamic library to communicate with FrontblockService remotely
|
||||
*
|
||||
* This will be automatically injected into the webpages served by FrontblockService
|
||||
* Will ask it's service for available RPCs and parse them into methods of this object
|
||||
* for convenient access.
|
||||
*/
|
||||
class RPCaller {
|
||||
constructor(port, server, tls = false) {
|
||||
this.socket = bsock.connect(port, server, tls);
|
||||
}
|
||||
async connect() {
|
||||
const info = await this.info();
|
||||
info.forEach(i => {
|
||||
let f;
|
||||
switch (i.type) {
|
||||
case 'call':
|
||||
f = this.callGenerator(i.uniqueName, i.argNames);
|
||||
break;
|
||||
case 'hook':
|
||||
f = this.hookGenerator(i.uniqueName, i.argNames);
|
||||
break;
|
||||
case 'unhook':
|
||||
f = this.unhookGenerator(i.uniqueName, i.argNames);
|
||||
break;
|
||||
}
|
||||
if (this[i.owner] == null)
|
||||
this[i.owner] = {};
|
||||
this[i.owner][i.name] = f;
|
||||
this[i.owner][i.name].bind(this);
|
||||
});
|
||||
}
|
||||
async info() {
|
||||
return await this.socket.call('info');
|
||||
}
|
||||
callGenerator(fnName, fnArgs) {
|
||||
const headerArgs = fnArgs.join(",");
|
||||
const argParams = fnArgs.map(stripAfterEquals).join(",");
|
||||
return eval('( () => async (' + headerArgs + ') => { return await this.socket.call("' + fnName + '", ' + argParams + ')} )()');
|
||||
}
|
||||
hookGenerator(fnName, fnArgs) {
|
||||
const headerArgs = fnArgs.join(",");
|
||||
const argParams = fnArgs.map(stripAfterEquals).join(",");
|
||||
return eval(`( () => async (` + headerArgs + (headerArgs.length !== 0 ? "," : "") + ` callback) => {
|
||||
const r = await this.socket.call("` + fnName + `", ` + argParams + `)
|
||||
if(r.uid != null){
|
||||
this.socket.hook(res.uid, callback)
|
||||
}
|
||||
return res
|
||||
} )()`);
|
||||
}
|
||||
unhookGenerator(fnName, fnArgs) {
|
||||
const headerArgs = fnArgs.join(",");
|
||||
const argParams = fnArgs.map(stripAfterEquals).join(",");
|
||||
if (fnArgs.length != 1)
|
||||
console.error("UnhookFunction", fnName, "specified more than one argument: (" + headerArgs + ")");
|
||||
return eval(`( () => async (` + headerArgs + `) => {
|
||||
const r = await this.socket.call("` + fnName + `", ` + argParams + `)
|
||||
this.socket.unhook(` + argParams + `)
|
||||
return res
|
||||
} )()`);
|
||||
}
|
||||
}
|
||||
exports.RPCaller = RPCaller;
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -0,0 +1,19 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const RPCSocketServer_1 = require("../src/backend/RPCSocketServer");
|
||||
//@ts-ignore
|
||||
const RPCaller_1 = require("../src/frontend/RPCaller");
|
||||
new RPCSocketServer_1.RPCSocketServer(20000, [{
|
||||
name: "HelloWorldRPCGroup",
|
||||
exportRPCs: () => [{
|
||||
type: 'call',
|
||||
name: 'echo',
|
||||
func: async (s) => s,
|
||||
visibility: 'private'
|
||||
}]
|
||||
}]);
|
||||
const caller = new RPCaller_1.RPCaller(20000, 'localhost');
|
||||
caller.connect().then(_ => {
|
||||
caller.info().then(console.log);
|
||||
caller["HelloWorldRPCGroup"].echo("x").then(console.log);
|
||||
});
|
||||
+1
@@ -0,0 +1 @@
|
||||
../uuid/bin/uuid
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
Robert Kieffer <robert@broofa.com>
|
||||
Christoph Tavan <dev@tavan.de>
|
||||
AJ ONeal <coolaj86@gmail.com>
|
||||
Vincent Voyer <vincent@zeroload.net>
|
||||
Roman Shtylman <shtylman@gmail.com>
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
|
||||
|
||||
### [3.3.3](https://github.com/kelektiv/node-uuid/compare/v3.3.2...v3.3.3) (2019-08-19)
|
||||
|
||||
<a name="3.3.2"></a>
|
||||
## [3.3.2](https://github.com/kelektiv/node-uuid/compare/v3.3.1...v3.3.2) (2018-06-28)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* typo ([305d877](https://github.com/kelektiv/node-uuid/commit/305d877))
|
||||
|
||||
|
||||
|
||||
<a name="3.3.1"></a>
|
||||
## [3.3.1](https://github.com/kelektiv/node-uuid/compare/v3.3.0...v3.3.1) (2018-06-28)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* fix [#284](https://github.com/kelektiv/node-uuid/issues/284) by setting function name in try-catch ([f2a60f2](https://github.com/kelektiv/node-uuid/commit/f2a60f2))
|
||||
|
||||
|
||||
|
||||
<a name="3.3.0"></a>
|
||||
# [3.3.0](https://github.com/kelektiv/node-uuid/compare/v3.2.1...v3.3.0) (2018-06-22)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* assignment to readonly property to allow running in strict mode ([#270](https://github.com/kelektiv/node-uuid/issues/270)) ([d062fdc](https://github.com/kelektiv/node-uuid/commit/d062fdc))
|
||||
* fix [#229](https://github.com/kelektiv/node-uuid/issues/229) ([c9684d4](https://github.com/kelektiv/node-uuid/commit/c9684d4))
|
||||
* Get correct version of IE11 crypto ([#274](https://github.com/kelektiv/node-uuid/issues/274)) ([153d331](https://github.com/kelektiv/node-uuid/commit/153d331))
|
||||
* mem issue when generating uuid ([#267](https://github.com/kelektiv/node-uuid/issues/267)) ([c47702c](https://github.com/kelektiv/node-uuid/commit/c47702c))
|
||||
|
||||
### Features
|
||||
|
||||
* enforce Conventional Commit style commit messages ([#282](https://github.com/kelektiv/node-uuid/issues/282)) ([cc9a182](https://github.com/kelektiv/node-uuid/commit/cc9a182))
|
||||
|
||||
|
||||
<a name="3.2.1"></a>
|
||||
## [3.2.1](https://github.com/kelektiv/node-uuid/compare/v3.2.0...v3.2.1) (2018-01-16)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* use msCrypto if available. Fixes [#241](https://github.com/kelektiv/node-uuid/issues/241) ([#247](https://github.com/kelektiv/node-uuid/issues/247)) ([1fef18b](https://github.com/kelektiv/node-uuid/commit/1fef18b))
|
||||
|
||||
|
||||
|
||||
<a name="3.2.0"></a>
|
||||
# [3.2.0](https://github.com/kelektiv/node-uuid/compare/v3.1.0...v3.2.0) (2018-01-16)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* remove mistakenly added typescript dependency, rollback version (standard-version will auto-increment) ([09fa824](https://github.com/kelektiv/node-uuid/commit/09fa824))
|
||||
* use msCrypto if available. Fixes [#241](https://github.com/kelektiv/node-uuid/issues/241) ([#247](https://github.com/kelektiv/node-uuid/issues/247)) ([1fef18b](https://github.com/kelektiv/node-uuid/commit/1fef18b))
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* Add v3 Support ([#217](https://github.com/kelektiv/node-uuid/issues/217)) ([d94f726](https://github.com/kelektiv/node-uuid/commit/d94f726))
|
||||
|
||||
|
||||
# [3.1.0](https://github.com/kelektiv/node-uuid/compare/v3.1.0...v3.0.1) (2017-06-17)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* (fix) Add .npmignore file to exclude test/ and other non-essential files from packing. (#183)
|
||||
* Fix typo (#178)
|
||||
* Simple typo fix (#165)
|
||||
|
||||
### Features
|
||||
* v5 support in CLI (#197)
|
||||
* V5 support (#188)
|
||||
|
||||
|
||||
# 3.0.1 (2016-11-28)
|
||||
|
||||
* split uuid versions into separate files
|
||||
|
||||
|
||||
# 3.0.0 (2016-11-17)
|
||||
|
||||
* remove .parse and .unparse
|
||||
|
||||
|
||||
# 2.0.0
|
||||
|
||||
* Removed uuid.BufferClass
|
||||
|
||||
|
||||
# 1.4.0
|
||||
|
||||
* Improved module context detection
|
||||
* Removed public RNG functions
|
||||
|
||||
|
||||
# 1.3.2
|
||||
|
||||
* Improve tests and handling of v1() options (Issue #24)
|
||||
* Expose RNG option to allow for perf testing with different generators
|
||||
|
||||
|
||||
# 1.3.0
|
||||
|
||||
* Support for version 1 ids, thanks to [@ctavan](https://github.com/ctavan)!
|
||||
* Support for node.js crypto API
|
||||
* De-emphasizing performance in favor of a) cryptographic quality PRNGs where available and b) more manageable code
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2010-2016 Robert Kieffer and other contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+293
@@ -0,0 +1,293 @@
|
||||
<!--
|
||||
-- This file is auto-generated from README_js.md. Changes should be made there.
|
||||
-->
|
||||
|
||||
# uuid [](http://travis-ci.org/kelektiv/node-uuid) #
|
||||
|
||||
Simple, fast generation of [RFC4122](http://www.ietf.org/rfc/rfc4122.txt) UUIDS.
|
||||
|
||||
Features:
|
||||
|
||||
* Support for version 1, 3, 4 and 5 UUIDs
|
||||
* Cross-platform
|
||||
* Uses cryptographically-strong random number APIs (when available)
|
||||
* Zero-dependency, small footprint (... but not [this small](https://gist.github.com/982883))
|
||||
|
||||
[**Deprecation warning**: The use of `require('uuid')` is deprecated and will not be
|
||||
supported after version 3.x of this module. Instead, use `require('uuid/[v1|v3|v4|v5]')` as shown in the examples below.]
|
||||
|
||||
## Quickstart - CommonJS (Recommended)
|
||||
|
||||
```shell
|
||||
npm install uuid
|
||||
```
|
||||
|
||||
Then generate your uuid version of choice ...
|
||||
|
||||
Version 1 (timestamp):
|
||||
|
||||
```javascript
|
||||
const uuidv1 = require('uuid/v1');
|
||||
uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-8bad-9b1deb4d3b7d'
|
||||
|
||||
```
|
||||
|
||||
Version 3 (namespace):
|
||||
|
||||
```javascript
|
||||
const uuidv3 = require('uuid/v3');
|
||||
|
||||
// ... using predefined DNS namespace (for domain names)
|
||||
uuidv3('hello.example.com', uuidv3.DNS); // ⇨ '9125a8dc-52ee-365b-a5aa-81b0b3681cf6'
|
||||
|
||||
// ... using predefined URL namespace (for, well, URLs)
|
||||
uuidv3('http://example.com/hello', uuidv3.URL); // ⇨ 'c6235813-3ba4-3801-ae84-e0a6ebb7d138'
|
||||
|
||||
// ... using a custom namespace
|
||||
//
|
||||
// Note: Custom namespaces should be a UUID string specific to your application!
|
||||
// E.g. the one here was generated using this modules `uuid` CLI.
|
||||
const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
|
||||
uuidv3('Hello, World!', MY_NAMESPACE); // ⇨ 'e8b5a51d-11c8-3310-a6ab-367563f20686'
|
||||
|
||||
```
|
||||
|
||||
Version 4 (random):
|
||||
|
||||
```javascript
|
||||
const uuidv4 = require('uuid/v4');
|
||||
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
|
||||
|
||||
```
|
||||
|
||||
Version 5 (namespace):
|
||||
|
||||
```javascript
|
||||
const uuidv5 = require('uuid/v5');
|
||||
|
||||
// ... using predefined DNS namespace (for domain names)
|
||||
uuidv5('hello.example.com', uuidv5.DNS); // ⇨ 'fdda765f-fc57-5604-a269-52a7df8164ec'
|
||||
|
||||
// ... using predefined URL namespace (for, well, URLs)
|
||||
uuidv5('http://example.com/hello', uuidv5.URL); // ⇨ '3bbcee75-cecc-5b56-8031-b6641c1ed1f1'
|
||||
|
||||
// ... using a custom namespace
|
||||
//
|
||||
// Note: Custom namespaces should be a UUID string specific to your application!
|
||||
// E.g. the one here was generated using this modules `uuid` CLI.
|
||||
const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
|
||||
uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681'
|
||||
|
||||
```
|
||||
|
||||
## Quickstart - Browser-ready Versions
|
||||
|
||||
Browser-ready versions of this module are available via [wzrd.in](https://github.com/jfhbrook/wzrd.in).
|
||||
|
||||
For version 1 uuids:
|
||||
|
||||
```html
|
||||
<script src="http://wzrd.in/standalone/uuid%2Fv1@latest"></script>
|
||||
<script>
|
||||
uuidv1(); // -> v1 UUID
|
||||
</script>
|
||||
```
|
||||
|
||||
For version 3 uuids:
|
||||
|
||||
```html
|
||||
<script src="http://wzrd.in/standalone/uuid%2Fv3@latest"></script>
|
||||
<script>
|
||||
uuidv3('http://example.com/hello', uuidv3.URL); // -> v3 UUID
|
||||
</script>
|
||||
```
|
||||
|
||||
For version 4 uuids:
|
||||
|
||||
```html
|
||||
<script src="http://wzrd.in/standalone/uuid%2Fv4@latest"></script>
|
||||
<script>
|
||||
uuidv4(); // -> v4 UUID
|
||||
</script>
|
||||
```
|
||||
|
||||
For version 5 uuids:
|
||||
|
||||
```html
|
||||
<script src="http://wzrd.in/standalone/uuid%2Fv5@latest"></script>
|
||||
<script>
|
||||
uuidv5('http://example.com/hello', uuidv5.URL); // -> v5 UUID
|
||||
</script>
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
### Version 1
|
||||
|
||||
```javascript
|
||||
const uuidv1 = require('uuid/v1');
|
||||
|
||||
// Incantations
|
||||
uuidv1();
|
||||
uuidv1(options);
|
||||
uuidv1(options, buffer, offset);
|
||||
```
|
||||
|
||||
Generate and return a RFC4122 v1 (timestamp-based) UUID.
|
||||
|
||||
* `options` - (Object) Optional uuid state to apply. Properties may include:
|
||||
|
||||
* `node` - (Array) Node id as Array of 6 bytes (per 4.1.6). Default: Randomly generated ID. See note 1.
|
||||
* `clockseq` - (Number between 0 - 0x3fff) RFC clock sequence. Default: An internally maintained clockseq is used.
|
||||
* `msecs` - (Number) Time in milliseconds since unix Epoch. Default: The current time is used.
|
||||
* `nsecs` - (Number between 0-9999) additional time, in 100-nanosecond units. Ignored if `msecs` is unspecified. Default: internal uuid counter is used, as per 4.2.1.2.
|
||||
|
||||
* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written.
|
||||
* `offset` - (Number) Starting index in `buffer` at which to begin writing.
|
||||
|
||||
Returns `buffer`, if specified, otherwise the string form of the UUID
|
||||
|
||||
Note: The default [node id](https://tools.ietf.org/html/rfc4122#section-4.1.6) (the last 12 digits in the UUID) is generated once, randomly, on process startup, and then remains unchanged for the duration of the process.
|
||||
|
||||
Example: Generate string UUID with fully-specified options
|
||||
|
||||
```javascript
|
||||
const v1options = {
|
||||
node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab],
|
||||
clockseq: 0x1234,
|
||||
msecs: new Date('2011-11-01').getTime(),
|
||||
nsecs: 5678
|
||||
};
|
||||
uuidv1(v1options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab'
|
||||
|
||||
```
|
||||
|
||||
Example: In-place generation of two binary IDs
|
||||
|
||||
```javascript
|
||||
// Generate two ids in an array
|
||||
const arr = new Array();
|
||||
uuidv1(null, arr, 0); // ⇨ [ 44, 94, 164, 192, 64, 103, 17, 233, 146, 52, 155, 29, 235, 77, 59, 125 ]
|
||||
uuidv1(null, arr, 16); // ⇨ [ 44, 94, 164, 192, 64, 103, 17, 233, 146, 52, 155, 29, 235, 77, 59, 125, 44, 94, 164, 193, 64, 103, 17, 233, 146, 52, 155, 29, 235, 77, 59, 125 ]
|
||||
|
||||
```
|
||||
|
||||
### Version 3
|
||||
|
||||
```javascript
|
||||
const uuidv3 = require('uuid/v3');
|
||||
|
||||
// Incantations
|
||||
uuidv3(name, namespace);
|
||||
uuidv3(name, namespace, buffer);
|
||||
uuidv3(name, namespace, buffer, offset);
|
||||
```
|
||||
|
||||
Generate and return a RFC4122 v3 UUID.
|
||||
|
||||
* `name` - (String | Array[]) "name" to create UUID with
|
||||
* `namespace` - (String | Array[]) "namespace" UUID either as a String or Array[16] of byte values
|
||||
* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written.
|
||||
* `offset` - (Number) Starting index in `buffer` at which to begin writing. Default = 0
|
||||
|
||||
Returns `buffer`, if specified, otherwise the string form of the UUID
|
||||
|
||||
Example:
|
||||
|
||||
```javascript
|
||||
uuidv3('hello world', MY_NAMESPACE); // ⇨ '042ffd34-d989-321c-ad06-f60826172424'
|
||||
|
||||
```
|
||||
|
||||
### Version 4
|
||||
|
||||
```javascript
|
||||
const uuidv4 = require('uuid/v4')
|
||||
|
||||
// Incantations
|
||||
uuidv4();
|
||||
uuidv4(options);
|
||||
uuidv4(options, buffer, offset);
|
||||
```
|
||||
|
||||
Generate and return a RFC4122 v4 UUID.
|
||||
|
||||
* `options` - (Object) Optional uuid state to apply. Properties may include:
|
||||
* `random` - (Number[16]) Array of 16 numbers (0-255) to use in place of randomly generated values
|
||||
* `rng` - (Function) Random # generator function that returns an Array[16] of byte values (0-255)
|
||||
* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written.
|
||||
* `offset` - (Number) Starting index in `buffer` at which to begin writing.
|
||||
|
||||
Returns `buffer`, if specified, otherwise the string form of the UUID
|
||||
|
||||
Example: Generate string UUID with predefined `random` values
|
||||
|
||||
```javascript
|
||||
const v4options = {
|
||||
random: [
|
||||
0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea,
|
||||
0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36
|
||||
]
|
||||
};
|
||||
uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836'
|
||||
|
||||
```
|
||||
|
||||
Example: Generate two IDs in a single buffer
|
||||
|
||||
```javascript
|
||||
const buffer = new Array();
|
||||
uuidv4(null, buffer, 0); // ⇨ [ 155, 29, 235, 77, 59, 125, 75, 173, 155, 221, 43, 13, 123, 61, 203, 109 ]
|
||||
uuidv4(null, buffer, 16); // ⇨ [ 155, 29, 235, 77, 59, 125, 75, 173, 155, 221, 43, 13, 123, 61, 203, 109, 27, 157, 107, 205, 187, 253, 75, 45, 155, 93, 171, 141, 251, 189, 75, 237 ]
|
||||
|
||||
```
|
||||
|
||||
### Version 5
|
||||
|
||||
```javascript
|
||||
const uuidv5 = require('uuid/v5');
|
||||
|
||||
// Incantations
|
||||
uuidv5(name, namespace);
|
||||
uuidv5(name, namespace, buffer);
|
||||
uuidv5(name, namespace, buffer, offset);
|
||||
```
|
||||
|
||||
Generate and return a RFC4122 v5 UUID.
|
||||
|
||||
* `name` - (String | Array[]) "name" to create UUID with
|
||||
* `namespace` - (String | Array[]) "namespace" UUID either as a String or Array[16] of byte values
|
||||
* `buffer` - (Array | Buffer) Array or buffer where UUID bytes are to be written.
|
||||
* `offset` - (Number) Starting index in `buffer` at which to begin writing. Default = 0
|
||||
|
||||
Returns `buffer`, if specified, otherwise the string form of the UUID
|
||||
|
||||
Example:
|
||||
|
||||
```javascript
|
||||
uuidv5('hello world', MY_NAMESPACE); // ⇨ '9f282611-e0fd-5650-8953-89c8e342da0b'
|
||||
|
||||
```
|
||||
|
||||
## Command Line
|
||||
|
||||
UUIDs can be generated from the command line with the `uuid` command.
|
||||
|
||||
```shell
|
||||
$ uuid
|
||||
ddeb27fb-d9a0-4624-be4d-4615062daed4
|
||||
|
||||
$ uuid v1
|
||||
02d37060-d446-11e7-a9fa-7bdae751ebe1
|
||||
```
|
||||
|
||||
Type `uuid --help` for usage details
|
||||
|
||||
## Testing
|
||||
|
||||
```shell
|
||||
npm test
|
||||
```
|
||||
|
||||
----
|
||||
Markdown generated from [README_js.md](README_js.md) by [](https://github.com/broofa/runmd)
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env node
|
||||
var assert = require('assert');
|
||||
|
||||
function usage() {
|
||||
console.log('Usage:');
|
||||
console.log(' uuid');
|
||||
console.log(' uuid v1');
|
||||
console.log(' uuid v3 <name> <namespace uuid>');
|
||||
console.log(' uuid v4');
|
||||
console.log(' uuid v5 <name> <namespace uuid>');
|
||||
console.log(' uuid --help');
|
||||
console.log('\nNote: <namespace uuid> may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC4122');
|
||||
}
|
||||
|
||||
var args = process.argv.slice(2);
|
||||
|
||||
if (args.indexOf('--help') >= 0) {
|
||||
usage();
|
||||
process.exit(0);
|
||||
}
|
||||
var version = args.shift() || 'v4';
|
||||
|
||||
switch (version) {
|
||||
case 'v1':
|
||||
var uuidV1 = require('../v1');
|
||||
console.log(uuidV1());
|
||||
break;
|
||||
|
||||
case 'v3':
|
||||
var uuidV3 = require('../v3');
|
||||
|
||||
var name = args.shift();
|
||||
var namespace = args.shift();
|
||||
assert(name != null, 'v3 name not specified');
|
||||
assert(namespace != null, 'v3 namespace not specified');
|
||||
|
||||
if (namespace == 'URL') namespace = uuidV3.URL;
|
||||
if (namespace == 'DNS') namespace = uuidV3.DNS;
|
||||
|
||||
console.log(uuidV3(name, namespace));
|
||||
break;
|
||||
|
||||
case 'v4':
|
||||
var uuidV4 = require('../v4');
|
||||
console.log(uuidV4());
|
||||
break;
|
||||
|
||||
case 'v5':
|
||||
var uuidV5 = require('../v5');
|
||||
|
||||
var name = args.shift();
|
||||
var namespace = args.shift();
|
||||
assert(name != null, 'v5 name not specified');
|
||||
assert(namespace != null, 'v5 namespace not specified');
|
||||
|
||||
if (namespace == 'URL') namespace = uuidV5.URL;
|
||||
if (namespace == 'DNS') namespace = uuidV5.DNS;
|
||||
|
||||
console.log(uuidV5(name, namespace));
|
||||
break;
|
||||
|
||||
default:
|
||||
usage();
|
||||
process.exit(1);
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
var v1 = require('./v1');
|
||||
var v4 = require('./v4');
|
||||
|
||||
var uuid = v4;
|
||||
uuid.v1 = v1;
|
||||
uuid.v4 = v4;
|
||||
|
||||
module.exports = uuid;
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Convert array of 16 byte values to UUID string format of the form:
|
||||
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
|
||||
*/
|
||||
var byteToHex = [];
|
||||
for (var i = 0; i < 256; ++i) {
|
||||
byteToHex[i] = (i + 0x100).toString(16).substr(1);
|
||||
}
|
||||
|
||||
function bytesToUuid(buf, offset) {
|
||||
var i = offset || 0;
|
||||
var bth = byteToHex;
|
||||
// join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
|
||||
return ([bth[buf[i++]], bth[buf[i++]],
|
||||
bth[buf[i++]], bth[buf[i++]], '-',
|
||||
bth[buf[i++]], bth[buf[i++]], '-',
|
||||
bth[buf[i++]], bth[buf[i++]], '-',
|
||||
bth[buf[i++]], bth[buf[i++]], '-',
|
||||
bth[buf[i++]], bth[buf[i++]],
|
||||
bth[buf[i++]], bth[buf[i++]],
|
||||
bth[buf[i++]], bth[buf[i++]]]).join('');
|
||||
}
|
||||
|
||||
module.exports = bytesToUuid;
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
/*
|
||||
* Browser-compatible JavaScript MD5
|
||||
*
|
||||
* Modification of JavaScript MD5
|
||||
* https://github.com/blueimp/JavaScript-MD5
|
||||
*
|
||||
* Copyright 2011, Sebastian Tschan
|
||||
* https://blueimp.net
|
||||
*
|
||||
* Licensed under the MIT license:
|
||||
* https://opensource.org/licenses/MIT
|
||||
*
|
||||
* Based on
|
||||
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
|
||||
* Digest Algorithm, as defined in RFC 1321.
|
||||
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
|
||||
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
|
||||
* Distributed under the BSD License
|
||||
* See http://pajhome.org.uk/crypt/md5 for more info.
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
function md5(bytes) {
|
||||
if (typeof(bytes) == 'string') {
|
||||
var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
|
||||
bytes = new Array(msg.length);
|
||||
for (var i = 0; i < msg.length; i++) bytes[i] = msg.charCodeAt(i);
|
||||
}
|
||||
|
||||
return md5ToHexEncodedArray(
|
||||
wordsToMd5(
|
||||
bytesToWords(bytes)
|
||||
, bytes.length * 8)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Convert an array of little-endian words to an array of bytes
|
||||
*/
|
||||
function md5ToHexEncodedArray(input) {
|
||||
var i;
|
||||
var x;
|
||||
var output = [];
|
||||
var length32 = input.length * 32;
|
||||
var hexTab = '0123456789abcdef';
|
||||
var hex;
|
||||
|
||||
for (i = 0; i < length32; i += 8) {
|
||||
x = (input[i >> 5] >>> (i % 32)) & 0xFF;
|
||||
|
||||
hex = parseInt(hexTab.charAt((x >>> 4) & 0x0F) + hexTab.charAt(x & 0x0F), 16);
|
||||
|
||||
output.push(hex);
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
/*
|
||||
* Calculate the MD5 of an array of little-endian words, and a bit length.
|
||||
*/
|
||||
function wordsToMd5(x, len) {
|
||||
/* append padding */
|
||||
x[len >> 5] |= 0x80 << (len % 32);
|
||||
x[(((len + 64) >>> 9) << 4) + 14] = len;
|
||||
|
||||
var i;
|
||||
var olda;
|
||||
var oldb;
|
||||
var oldc;
|
||||
var oldd;
|
||||
var a = 1732584193;
|
||||
var b = -271733879;
|
||||
var c = -1732584194;
|
||||
|
||||
var d = 271733878;
|
||||
|
||||
for (i = 0; i < x.length; i += 16) {
|
||||
olda = a;
|
||||
oldb = b;
|
||||
oldc = c;
|
||||
oldd = d;
|
||||
|
||||
a = md5ff(a, b, c, d, x[i], 7, -680876936);
|
||||
d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
|
||||
c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
|
||||
b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
|
||||
a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
|
||||
d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
|
||||
c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
|
||||
b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
|
||||
a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
|
||||
d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
|
||||
c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
|
||||
b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
|
||||
a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
|
||||
d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
|
||||
c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
|
||||
b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
|
||||
|
||||
a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
|
||||
d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
|
||||
c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
|
||||
b = md5gg(b, c, d, a, x[i], 20, -373897302);
|
||||
a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
|
||||
d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
|
||||
c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
|
||||
b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
|
||||
a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
|
||||
d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
|
||||
c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
|
||||
b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
|
||||
a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
|
||||
d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
|
||||
c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
|
||||
b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
|
||||
|
||||
a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
|
||||
d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
|
||||
c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
|
||||
b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
|
||||
a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
|
||||
d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
|
||||
c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
|
||||
b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
|
||||
a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
|
||||
d = md5hh(d, a, b, c, x[i], 11, -358537222);
|
||||
c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
|
||||
b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
|
||||
a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
|
||||
d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
|
||||
c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
|
||||
b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
|
||||
|
||||
a = md5ii(a, b, c, d, x[i], 6, -198630844);
|
||||
d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
|
||||
c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
|
||||
b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
|
||||
a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
|
||||
d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
|
||||
c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
|
||||
b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
|
||||
a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
|
||||
d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
|
||||
c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
|
||||
b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
|
||||
a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
|
||||
d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
|
||||
c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
|
||||
b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
|
||||
|
||||
a = safeAdd(a, olda);
|
||||
b = safeAdd(b, oldb);
|
||||
c = safeAdd(c, oldc);
|
||||
d = safeAdd(d, oldd);
|
||||
}
|
||||
return [a, b, c, d];
|
||||
}
|
||||
|
||||
/*
|
||||
* Convert an array bytes to an array of little-endian words
|
||||
* Characters >255 have their high-byte silently ignored.
|
||||
*/
|
||||
function bytesToWords(input) {
|
||||
var i;
|
||||
var output = [];
|
||||
output[(input.length >> 2) - 1] = undefined;
|
||||
for (i = 0; i < output.length; i += 1) {
|
||||
output[i] = 0;
|
||||
}
|
||||
var length8 = input.length * 8;
|
||||
for (i = 0; i < length8; i += 8) {
|
||||
output[i >> 5] |= (input[(i / 8)] & 0xFF) << (i % 32);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
/*
|
||||
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
|
||||
* to work around bugs in some JS interpreters.
|
||||
*/
|
||||
function safeAdd(x, y) {
|
||||
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
|
||||
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
|
||||
return (msw << 16) | (lsw & 0xFFFF);
|
||||
}
|
||||
|
||||
/*
|
||||
* Bitwise rotate a 32-bit number to the left.
|
||||
*/
|
||||
function bitRotateLeft(num, cnt) {
|
||||
return (num << cnt) | (num >>> (32 - cnt));
|
||||
}
|
||||
|
||||
/*
|
||||
* These functions implement the four basic operations the algorithm uses.
|
||||
*/
|
||||
function md5cmn(q, a, b, x, s, t) {
|
||||
return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
|
||||
}
|
||||
function md5ff(a, b, c, d, x, s, t) {
|
||||
return md5cmn((b & c) | ((~b) & d), a, b, x, s, t);
|
||||
}
|
||||
function md5gg(a, b, c, d, x, s, t) {
|
||||
return md5cmn((b & d) | (c & (~d)), a, b, x, s, t);
|
||||
}
|
||||
function md5hh(a, b, c, d, x, s, t) {
|
||||
return md5cmn(b ^ c ^ d, a, b, x, s, t);
|
||||
}
|
||||
function md5ii(a, b, c, d, x, s, t) {
|
||||
return md5cmn(c ^ (b | (~d)), a, b, x, s, t);
|
||||
}
|
||||
|
||||
module.exports = md5;
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
'use strict';
|
||||
|
||||
var crypto = require('crypto');
|
||||
|
||||
function md5(bytes) {
|
||||
if (typeof Buffer.from === 'function') {
|
||||
// Modern Buffer API
|
||||
if (Array.isArray(bytes)) {
|
||||
bytes = Buffer.from(bytes);
|
||||
} else if (typeof bytes === 'string') {
|
||||
bytes = Buffer.from(bytes, 'utf8');
|
||||
}
|
||||
} else {
|
||||
// Pre-v4 Buffer API
|
||||
if (Array.isArray(bytes)) {
|
||||
bytes = new Buffer(bytes);
|
||||
} else if (typeof bytes === 'string') {
|
||||
bytes = new Buffer(bytes, 'utf8');
|
||||
}
|
||||
}
|
||||
|
||||
return crypto.createHash('md5').update(bytes).digest();
|
||||
}
|
||||
|
||||
module.exports = md5;
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
// Unique ID creation requires a high quality random # generator. In the
|
||||
// browser this is a little complicated due to unknown quality of Math.random()
|
||||
// and inconsistent support for the `crypto` API. We do the best we can via
|
||||
// feature-detection
|
||||
|
||||
// getRandomValues needs to be invoked in a context where "this" is a Crypto
|
||||
// implementation. Also, find the complete implementation of crypto on IE11.
|
||||
var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
|
||||
(typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
|
||||
|
||||
if (getRandomValues) {
|
||||
// WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
|
||||
var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
|
||||
|
||||
module.exports = function whatwgRNG() {
|
||||
getRandomValues(rnds8);
|
||||
return rnds8;
|
||||
};
|
||||
} else {
|
||||
// Math.random()-based (RNG)
|
||||
//
|
||||
// If all else fails, use Math.random(). It's fast, but is of unspecified
|
||||
// quality.
|
||||
var rnds = new Array(16);
|
||||
|
||||
module.exports = function mathRNG() {
|
||||
for (var i = 0, r; i < 16; i++) {
|
||||
if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
|
||||
rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
|
||||
}
|
||||
|
||||
return rnds;
|
||||
};
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
// Unique ID creation requires a high quality random # generator. In node.js
|
||||
// this is pretty straight-forward - we use the crypto API.
|
||||
|
||||
var crypto = require('crypto');
|
||||
|
||||
module.exports = function nodeRNG() {
|
||||
return crypto.randomBytes(16);
|
||||
};
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
// Adapted from Chris Veness' SHA1 code at
|
||||
// http://www.movable-type.co.uk/scripts/sha1.html
|
||||
'use strict';
|
||||
|
||||
function f(s, x, y, z) {
|
||||
switch (s) {
|
||||
case 0: return (x & y) ^ (~x & z);
|
||||
case 1: return x ^ y ^ z;
|
||||
case 2: return (x & y) ^ (x & z) ^ (y & z);
|
||||
case 3: return x ^ y ^ z;
|
||||
}
|
||||
}
|
||||
|
||||
function ROTL(x, n) {
|
||||
return (x << n) | (x>>> (32 - n));
|
||||
}
|
||||
|
||||
function sha1(bytes) {
|
||||
var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
|
||||
var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
|
||||
|
||||
if (typeof(bytes) == 'string') {
|
||||
var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
|
||||
bytes = new Array(msg.length);
|
||||
for (var i = 0; i < msg.length; i++) bytes[i] = msg.charCodeAt(i);
|
||||
}
|
||||
|
||||
bytes.push(0x80);
|
||||
|
||||
var l = bytes.length/4 + 2;
|
||||
var N = Math.ceil(l/16);
|
||||
var M = new Array(N);
|
||||
|
||||
for (var i=0; i<N; i++) {
|
||||
M[i] = new Array(16);
|
||||
for (var j=0; j<16; j++) {
|
||||
M[i][j] =
|
||||
bytes[i * 64 + j * 4] << 24 |
|
||||
bytes[i * 64 + j * 4 + 1] << 16 |
|
||||
bytes[i * 64 + j * 4 + 2] << 8 |
|
||||
bytes[i * 64 + j * 4 + 3];
|
||||
}
|
||||
}
|
||||
|
||||
M[N - 1][14] = ((bytes.length - 1) * 8) /
|
||||
Math.pow(2, 32); M[N - 1][14] = Math.floor(M[N - 1][14]);
|
||||
M[N - 1][15] = ((bytes.length - 1) * 8) & 0xffffffff;
|
||||
|
||||
for (var i=0; i<N; i++) {
|
||||
var W = new Array(80);
|
||||
|
||||
for (var t=0; t<16; t++) W[t] = M[i][t];
|
||||
for (var t=16; t<80; t++) {
|
||||
W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
|
||||
}
|
||||
|
||||
var a = H[0];
|
||||
var b = H[1];
|
||||
var c = H[2];
|
||||
var d = H[3];
|
||||
var e = H[4];
|
||||
|
||||
for (var t=0; t<80; t++) {
|
||||
var s = Math.floor(t/20);
|
||||
var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;
|
||||
e = d;
|
||||
d = c;
|
||||
c = ROTL(b, 30) >>> 0;
|
||||
b = a;
|
||||
a = T;
|
||||
}
|
||||
|
||||
H[0] = (H[0] + a) >>> 0;
|
||||
H[1] = (H[1] + b) >>> 0;
|
||||
H[2] = (H[2] + c) >>> 0;
|
||||
H[3] = (H[3] + d) >>> 0;
|
||||
H[4] = (H[4] + e) >>> 0;
|
||||
}
|
||||
|
||||
return [
|
||||
H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff,
|
||||
H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff,
|
||||
H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff,
|
||||
H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff,
|
||||
H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff
|
||||
];
|
||||
}
|
||||
|
||||
module.exports = sha1;
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
'use strict';
|
||||
|
||||
var crypto = require('crypto');
|
||||
|
||||
function sha1(bytes) {
|
||||
if (typeof Buffer.from === 'function') {
|
||||
// Modern Buffer API
|
||||
if (Array.isArray(bytes)) {
|
||||
bytes = Buffer.from(bytes);
|
||||
} else if (typeof bytes === 'string') {
|
||||
bytes = Buffer.from(bytes, 'utf8');
|
||||
}
|
||||
} else {
|
||||
// Pre-v4 Buffer API
|
||||
if (Array.isArray(bytes)) {
|
||||
bytes = new Buffer(bytes);
|
||||
} else if (typeof bytes === 'string') {
|
||||
bytes = new Buffer(bytes, 'utf8');
|
||||
}
|
||||
}
|
||||
|
||||
return crypto.createHash('sha1').update(bytes).digest();
|
||||
}
|
||||
|
||||
module.exports = sha1;
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
var bytesToUuid = require('./bytesToUuid');
|
||||
|
||||
function uuidToBytes(uuid) {
|
||||
// Note: We assume we're being passed a valid uuid string
|
||||
var bytes = [];
|
||||
uuid.replace(/[a-fA-F0-9]{2}/g, function(hex) {
|
||||
bytes.push(parseInt(hex, 16));
|
||||
});
|
||||
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function stringToBytes(str) {
|
||||
str = unescape(encodeURIComponent(str)); // UTF8 escape
|
||||
var bytes = new Array(str.length);
|
||||
for (var i = 0; i < str.length; i++) {
|
||||
bytes[i] = str.charCodeAt(i);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
module.exports = function(name, version, hashfunc) {
|
||||
var generateUUID = function(value, namespace, buf, offset) {
|
||||
var off = buf && offset || 0;
|
||||
|
||||
if (typeof(value) == 'string') value = stringToBytes(value);
|
||||
if (typeof(namespace) == 'string') namespace = uuidToBytes(namespace);
|
||||
|
||||
if (!Array.isArray(value)) throw TypeError('value must be an array of bytes');
|
||||
if (!Array.isArray(namespace) || namespace.length !== 16) throw TypeError('namespace must be uuid string or an Array of 16 byte values');
|
||||
|
||||
// Per 4.3
|
||||
var bytes = hashfunc(namespace.concat(value));
|
||||
bytes[6] = (bytes[6] & 0x0f) | version;
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
||||
|
||||
if (buf) {
|
||||
for (var idx = 0; idx < 16; ++idx) {
|
||||
buf[off+idx] = bytes[idx];
|
||||
}
|
||||
}
|
||||
|
||||
return buf || bytesToUuid(bytes);
|
||||
};
|
||||
|
||||
// Function#name is not settable on some platforms (#270)
|
||||
try {
|
||||
generateUUID.name = name;
|
||||
} catch (err) {
|
||||
}
|
||||
|
||||
// Pre-defined namespaces, per Appendix C
|
||||
generateUUID.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
|
||||
generateUUID.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
|
||||
|
||||
return generateUUID;
|
||||
};
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
{
|
||||
"_from": "uuid",
|
||||
"_id": "uuid@3.3.3",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-pW0No1RGHgzlpHJO1nsVrHKpOEIxkGg1xB+v0ZmdNH5OAeAwzAVrCnI2/6Mtx+Uys6iaylxa+D3g4j63IKKjSQ==",
|
||||
"_location": "/uuid",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "tag",
|
||||
"registry": true,
|
||||
"raw": "uuid",
|
||||
"name": "uuid",
|
||||
"escapedName": "uuid",
|
||||
"rawSpec": "",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "latest"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"#USER",
|
||||
"/"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.3.tgz",
|
||||
"_shasum": "4568f0216e78760ee1dbf3a4d2cf53e224112866",
|
||||
"_spec": "uuid",
|
||||
"_where": "/home/cake/rpclib",
|
||||
"bin": {
|
||||
"uuid": "./bin/uuid"
|
||||
},
|
||||
"browser": {
|
||||
"./lib/rng.js": "./lib/rng-browser.js",
|
||||
"./lib/sha1.js": "./lib/sha1-browser.js",
|
||||
"./lib/md5.js": "./lib/md5-browser.js"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/kelektiv/node-uuid/issues"
|
||||
},
|
||||
"bundleDependencies": false,
|
||||
"commitlint": {
|
||||
"extends": [
|
||||
"@commitlint/config-conventional"
|
||||
]
|
||||
},
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Robert Kieffer",
|
||||
"email": "robert@broofa.com"
|
||||
},
|
||||
{
|
||||
"name": "Christoph Tavan",
|
||||
"email": "dev@tavan.de"
|
||||
},
|
||||
{
|
||||
"name": "AJ ONeal",
|
||||
"email": "coolaj86@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "Vincent Voyer",
|
||||
"email": "vincent@zeroload.net"
|
||||
},
|
||||
{
|
||||
"name": "Roman Shtylman",
|
||||
"email": "shtylman@gmail.com"
|
||||
}
|
||||
],
|
||||
"deprecated": false,
|
||||
"description": "RFC4122 (v1, v4, and v5) UUIDs",
|
||||
"devDependencies": {
|
||||
"@commitlint/cli": "8.1.0",
|
||||
"@commitlint/config-conventional": "8.1.0",
|
||||
"eslint": "6.2.0",
|
||||
"husky": "3.0.4",
|
||||
"mocha": "6.2.0",
|
||||
"runmd": "1.2.1",
|
||||
"standard-version": "7.0.0"
|
||||
},
|
||||
"homepage": "https://github.com/kelektiv/node-uuid#readme",
|
||||
"keywords": [
|
||||
"uuid",
|
||||
"guid",
|
||||
"rfc4122"
|
||||
],
|
||||
"license": "MIT",
|
||||
"name": "uuid",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/kelektiv/node-uuid.git"
|
||||
},
|
||||
"scripts": {
|
||||
"commitmsg": "commitlint -E HUSKY_GIT_PARAMS",
|
||||
"md": "runmd --watch --output=README.md README_js.md",
|
||||
"prepare": "runmd --output=README.md README_js.md",
|
||||
"release": "standard-version",
|
||||
"test": "mocha test/test.js"
|
||||
},
|
||||
"version": "3.3.3"
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
var rng = require('./lib/rng');
|
||||
var bytesToUuid = require('./lib/bytesToUuid');
|
||||
|
||||
// **`v1()` - Generate time-based UUID**
|
||||
//
|
||||
// Inspired by https://github.com/LiosK/UUID.js
|
||||
// and http://docs.python.org/library/uuid.html
|
||||
|
||||
var _nodeId;
|
||||
var _clockseq;
|
||||
|
||||
// Previous uuid creation time
|
||||
var _lastMSecs = 0;
|
||||
var _lastNSecs = 0;
|
||||
|
||||
// See https://github.com/broofa/node-uuid for API details
|
||||
function v1(options, buf, offset) {
|
||||
var i = buf && offset || 0;
|
||||
var b = buf || [];
|
||||
|
||||
options = options || {};
|
||||
var node = options.node || _nodeId;
|
||||
var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
|
||||
|
||||
// node and clockseq need to be initialized to random values if they're not
|
||||
// specified. We do this lazily to minimize issues related to insufficient
|
||||
// system entropy. See #189
|
||||
if (node == null || clockseq == null) {
|
||||
var seedBytes = rng();
|
||||
if (node == null) {
|
||||
// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
|
||||
node = _nodeId = [
|
||||
seedBytes[0] | 0x01,
|
||||
seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
|
||||
];
|
||||
}
|
||||
if (clockseq == null) {
|
||||
// Per 4.2.2, randomize (14 bit) clockseq
|
||||
clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
|
||||
}
|
||||
}
|
||||
|
||||
// UUID timestamps are 100 nano-second units since the Gregorian epoch,
|
||||
// (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
|
||||
// time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
|
||||
// (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
|
||||
var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
|
||||
|
||||
// Per 4.2.1.2, use count of uuid's generated during the current clock
|
||||
// cycle to simulate higher resolution clock
|
||||
var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
|
||||
|
||||
// Time since last uuid creation (in msecs)
|
||||
var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
|
||||
|
||||
// Per 4.2.1.2, Bump clockseq on clock regression
|
||||
if (dt < 0 && options.clockseq === undefined) {
|
||||
clockseq = clockseq + 1 & 0x3fff;
|
||||
}
|
||||
|
||||
// Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
|
||||
// time interval
|
||||
if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
|
||||
nsecs = 0;
|
||||
}
|
||||
|
||||
// Per 4.2.1.2 Throw error if too many uuids are requested
|
||||
if (nsecs >= 10000) {
|
||||
throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
|
||||
}
|
||||
|
||||
_lastMSecs = msecs;
|
||||
_lastNSecs = nsecs;
|
||||
_clockseq = clockseq;
|
||||
|
||||
// Per 4.1.4 - Convert from unix epoch to Gregorian epoch
|
||||
msecs += 12219292800000;
|
||||
|
||||
// `time_low`
|
||||
var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
|
||||
b[i++] = tl >>> 24 & 0xff;
|
||||
b[i++] = tl >>> 16 & 0xff;
|
||||
b[i++] = tl >>> 8 & 0xff;
|
||||
b[i++] = tl & 0xff;
|
||||
|
||||
// `time_mid`
|
||||
var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
|
||||
b[i++] = tmh >>> 8 & 0xff;
|
||||
b[i++] = tmh & 0xff;
|
||||
|
||||
// `time_high_and_version`
|
||||
b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
|
||||
b[i++] = tmh >>> 16 & 0xff;
|
||||
|
||||
// `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
|
||||
b[i++] = clockseq >>> 8 | 0x80;
|
||||
|
||||
// `clock_seq_low`
|
||||
b[i++] = clockseq & 0xff;
|
||||
|
||||
// `node`
|
||||
for (var n = 0; n < 6; ++n) {
|
||||
b[i + n] = node[n];
|
||||
}
|
||||
|
||||
return buf ? buf : bytesToUuid(b);
|
||||
}
|
||||
|
||||
module.exports = v1;
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
var v35 = require('./lib/v35.js');
|
||||
var md5 = require('./lib/md5');
|
||||
|
||||
module.exports = v35('v3', 0x30, md5);
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
var rng = require('./lib/rng');
|
||||
var bytesToUuid = require('./lib/bytesToUuid');
|
||||
|
||||
function v4(options, buf, offset) {
|
||||
var i = buf && offset || 0;
|
||||
|
||||
if (typeof(options) == 'string') {
|
||||
buf = options === 'binary' ? new Array(16) : null;
|
||||
options = null;
|
||||
}
|
||||
options = options || {};
|
||||
|
||||
var rnds = options.random || (options.rng || rng)();
|
||||
|
||||
// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
|
||||
rnds[6] = (rnds[6] & 0x0f) | 0x40;
|
||||
rnds[8] = (rnds[8] & 0x3f) | 0x80;
|
||||
|
||||
// Copy bytes to buffer, if provided
|
||||
if (buf) {
|
||||
for (var ii = 0; ii < 16; ++ii) {
|
||||
buf[i + ii] = rnds[ii];
|
||||
}
|
||||
}
|
||||
|
||||
return buf || bytesToUuid(rnds);
|
||||
}
|
||||
|
||||
module.exports = v4;
|
||||
+3
@@ -0,0 +1,3 @@
|
||||
var v35 = require('./lib/v35.js');
|
||||
var sha1 = require('./lib/sha1');
|
||||
module.exports = v35('v5', 0x50, sha1);
|
||||
Generated
+5
@@ -3944,6 +3944,11 @@
|
||||
"integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=",
|
||||
"dev": true
|
||||
},
|
||||
"uuid": {
|
||||
"version": "3.3.3",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.3.tgz",
|
||||
"integrity": "sha512-pW0No1RGHgzlpHJO1nsVrHKpOEIxkGg1xB+v0ZmdNH5OAeAwzAVrCnI2/6Mtx+Uys6iaylxa+D3g4j63IKKjSQ=="
|
||||
},
|
||||
"v8-compile-cache": {
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.0.3.tgz",
|
||||
|
||||
+6
-3
@@ -2,9 +2,11 @@
|
||||
"name": "rpclib",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
"build": "npm run clean; npm run tsc; npm run webpack",
|
||||
"tsc": "tsc",
|
||||
"webpack": "webpack --config src/frontend/webpack.prod.js --progress --colors",
|
||||
"clean": "rm -rf lib"
|
||||
},
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
@@ -19,6 +21,7 @@
|
||||
"webpack-cli": "^3.3.5"
|
||||
},
|
||||
"dependencies": {
|
||||
"bsock": "^0.1.9"
|
||||
"bsock": "^0.1.9",
|
||||
"uuid": "^3.3.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,49 @@
|
||||
import { SubscriptionResponse, SuccessResponse, ErrorResponse } from "../../../../vendor/generic/Types";
|
||||
import http = require('http');
|
||||
import bsock = require('bsock');
|
||||
|
||||
import * as uuid from "uuid/v4"
|
||||
import { Socket } from "./RPCSocketServer"
|
||||
|
||||
type rpcType = 'hook' | 'unhook' | 'call'
|
||||
type visibility = 'public' | 'private'
|
||||
|
||||
export type Outcome = "Success" | "Error"
|
||||
|
||||
/* Responses */
|
||||
export class Response{
|
||||
constructor(
|
||||
public message?:string
|
||||
){}
|
||||
}
|
||||
|
||||
export class SuccessResponse extends Response{
|
||||
result:Outcome = "Success"
|
||||
|
||||
constructor(
|
||||
message?:string
|
||||
){
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
export class ErrorResponse extends Response{
|
||||
result:Outcome = "Error"
|
||||
|
||||
constructor(
|
||||
message: string = "Unknown error"
|
||||
){
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
export class SubscriptionResponse extends SuccessResponse{
|
||||
constructor(
|
||||
public uid: string,
|
||||
message?:string
|
||||
){
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
export type UnhookFunction = (uid:string) => Promise<SuccessResponse | ErrorResponse>
|
||||
export type callbackFunction = (...args) => Promise<SubscriptionResponse | ErrorResponse>
|
||||
export type AsyncFunction = (...args) => Promise<any>
|
||||
@@ -98,7 +136,7 @@ export const rpcToRpcinfo = (rpc : socketioRPC, owner: string):RpcInfo => {
|
||||
}
|
||||
}
|
||||
|
||||
export const rpcHooker = (socket, owner:string, RPCs: socketioRPC[], makeUnique = true):ExtendedRpcInfo[] => {
|
||||
export const rpcHooker = (socket: Socket, owner:string, RPCs: socketioRPC[], makeUnique = true):ExtendedRpcInfo[] => {
|
||||
const suffix = makeUnique?"-"+uuid().substr(0,4):""
|
||||
return RPCs.map(rpc => rpcToRpcinfo(rpc, owner))
|
||||
.map(info => {
|
||||
@@ -137,10 +175,79 @@ const hookGenerator = (rpc:hookRPC): HookInfo['generator'] => {
|
||||
}`)
|
||||
}
|
||||
|
||||
function extractArgs(f:Function):string[]{
|
||||
const extractArgs = (f:Function):string[] => {
|
||||
let fn = String(f)
|
||||
let args = fn.substr(0, fn.indexOf(")"))
|
||||
args = args.substr(fn.indexOf("(")+1)
|
||||
let ret = args.split(",")
|
||||
return ret
|
||||
}
|
||||
|
||||
|
||||
type OnFunction = (type: 'error' | 'close', f: (e?:any)=>void) => Socket
|
||||
|
||||
export type Socket = {
|
||||
port: number
|
||||
hook: (rpcname: string, ...args: any[]) => Socket
|
||||
unhook: (rpcname:string) => Socket
|
||||
call: (rpcname:string, ...args: any[]) => Promise<any>
|
||||
fire: (rpcname:string, ...args: any[]) => Promise<any>
|
||||
on: OnFunction
|
||||
destroy: ()=>void
|
||||
close: ()=>void
|
||||
}
|
||||
|
||||
export type RPCSocketConf = {
|
||||
connectionHandler: (socket:Socket) => void
|
||||
errorHandler: (socket:Socket) => (error:any) => void
|
||||
closeHandler: (socket:Socket) => () => void
|
||||
}
|
||||
|
||||
export class RPCSocketServer{
|
||||
|
||||
private io = bsock.createServer()
|
||||
private wsServer = http.createServer()
|
||||
|
||||
constructor(
|
||||
private port:number,
|
||||
private rpcExporters: RPCExporter[] = [],
|
||||
private conf: RPCSocketConf = {
|
||||
errorHandler: (socket:Socket) => (error:any) => { socket.destroy(); console.error(error) },
|
||||
closeHandler: (socket:Socket) => () => { console.log("Socket closing") },
|
||||
connectionHandler: (socket:Socket) => { console.log("New websocket connection in port "+socket.port) }
|
||||
}
|
||||
){
|
||||
this.startWebsocket()
|
||||
}
|
||||
|
||||
private startWebsocket(){
|
||||
try{
|
||||
this.io.attach(this.wsServer)
|
||||
this.io.on('socket', (socket:Socket) => {
|
||||
socket.on('error', this.conf.errorHandler(socket))
|
||||
socket.on('close', this.conf.closeHandler(socket))
|
||||
this.initApis(socket)
|
||||
})
|
||||
this.wsServer.listen(this.port)
|
||||
}catch(e){
|
||||
//@ts-ignore
|
||||
this.errorHandler(undefined)("Unable to connect to socket")
|
||||
}
|
||||
}
|
||||
|
||||
protected initApis(socket){
|
||||
const adminRPCs:socketioRPC[] = [
|
||||
{
|
||||
name: 'info',
|
||||
type: 'call',
|
||||
visibility: 'private',
|
||||
func: async () => rpcInfos
|
||||
}
|
||||
]
|
||||
|
||||
const rpcInfos:ExtendedRpcInfo[] = [
|
||||
...rpcHooker(socket, "Admin", adminRPCs, false),
|
||||
...this.rpcExporters.flatMap(exporter => rpcHooker(socket, exporter.name, exporter.exportRPCs()))
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import { parseSubResponse, parseResponse } from "frontblock-generic/Types";
|
||||
import { ExtendedRpcInfo, UnhookFunction, callbackFunction, AsyncFunction } from "frontblock-generic/RPC";
|
||||
import { ExtendedRpcInfo, UnhookFunction, callbackFunction, AsyncFunction } from "../backend/RPCSocketServer";
|
||||
var bsock = require('bsock')
|
||||
|
||||
//fix args with defaults like "force = true" -> "force"
|
||||
@@ -7,6 +6,10 @@ function stripAfterEquals(str:string){
|
||||
return str.split("=")[0]
|
||||
}
|
||||
|
||||
type RPCReceiver = {
|
||||
[RPCGroup in string]: any
|
||||
}
|
||||
|
||||
/**
|
||||
* Dynamic library to communicate with FrontblockService remotely
|
||||
*
|
||||
@@ -14,20 +17,14 @@ function stripAfterEquals(str:string){
|
||||
* Will ask it's service for available RPCs and parse them into methods of this object
|
||||
* for convenient access.
|
||||
*/
|
||||
export class RPCallable{
|
||||
export class RPCaller implements RPCReceiver{
|
||||
private socket
|
||||
|
||||
constructor(){
|
||||
this.socket = bsock.connect(20000, 'localhost', false/*tls*/)
|
||||
this.init()
|
||||
constructor(port:number, server: string, tls: boolean = false){
|
||||
this.socket = bsock.connect(port, server, tls)
|
||||
}
|
||||
|
||||
// need this-context for eval-magic below
|
||||
// DO NOT REMOVE. They're not really unused
|
||||
private parseSubResponse = parseSubResponse
|
||||
private parseResponse = parseResponse
|
||||
|
||||
private async init(){
|
||||
async connect(){
|
||||
const info:ExtendedRpcInfo[] = await this.info()
|
||||
info.forEach(i => {
|
||||
let f: any
|
||||
@@ -64,8 +61,7 @@ export class RPCallable{
|
||||
const argParams = fnArgs.map(stripAfterEquals).join(",")
|
||||
return eval( `( () => async (`+headerArgs+(headerArgs.length!==0?",":"")+` callback) => {
|
||||
const r = await this.socket.call("`+fnName+`", `+argParams+`)
|
||||
const res = await this.parseSubResponse(r);
|
||||
if(res.uid != null){
|
||||
if(r.uid != null){
|
||||
this.socket.hook(res.uid, callback)
|
||||
}
|
||||
return res
|
||||
@@ -80,12 +76,9 @@ export class RPCallable{
|
||||
|
||||
return eval( `( () => async (`+headerArgs+`) => {
|
||||
const r = await this.socket.call("`+fnName+`", `+argParams+`)
|
||||
const res = await this.parseResponse(r)
|
||||
this.socket.unhook(`+argParams+`)
|
||||
return res
|
||||
} )()` )
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
window['rpc'] = new RPCallable()
|
||||
@@ -4,10 +4,10 @@ const TerserPlugin = require('terser-webpack-plugin');
|
||||
module.exports = {
|
||||
mode: 'production',
|
||||
target: "web",
|
||||
entry: path.resolve(__dirname, 'module.ts'),
|
||||
entry: path.resolve(__dirname, 'RPCaller.ts'),
|
||||
output: {
|
||||
path: path.resolve(__dirname, '../../dist'),
|
||||
filename: 'FrontendPlugin.js',
|
||||
path: path.resolve(__dirname, '../../lib'),
|
||||
filename: 'RPCaller.min.js',
|
||||
libraryTarget: 'commonjs',
|
||||
},
|
||||
resolve: {
|
||||
@@ -30,11 +30,5 @@ module.exports = {
|
||||
],
|
||||
},
|
||||
externals: {
|
||||
'@angular/core': '@angular/core',
|
||||
'@angular/common': '@angular/common',
|
||||
'@angular/router': '@angular/router',
|
||||
'@angular/animations': '@angular/animations',
|
||||
'@angular/forms': '@angular/forms',
|
||||
'@clr/angular': '@clr/angular'
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { RPCSocketServer } from '../src/backend/RPCSocketServer'
|
||||
//@ts-ignore
|
||||
import {RPCaller} from '../src/frontend/RPCaller'
|
||||
|
||||
new RPCSocketServer(20000, [{
|
||||
name: "HelloWorldRPCGroup",
|
||||
exportRPCs: () => [{
|
||||
type: 'call',
|
||||
name: 'echo',
|
||||
func: async (s:string) => s,
|
||||
visibility: 'private'
|
||||
}]
|
||||
}] )
|
||||
|
||||
const caller = new RPCaller(20000, 'localhost')
|
||||
caller.connect().then(_ => {
|
||||
caller.info().then(console.log)
|
||||
caller["HelloWorldRPCGroup"].echo("x").then(console.log)
|
||||
})
|
||||
+2
-2
@@ -9,6 +9,6 @@
|
||||
"strict": true,
|
||||
"experimentalDecorators": true
|
||||
},
|
||||
"include": ["src/backend/**/*"],
|
||||
"exclude": ["node_modules", "**/__tests__/*"],
|
||||
"include": ["src/backend/**/*", "test/**/*"],
|
||||
"exclude": ["node_modules", "**/__tests__/*", "src/frontend/**/*"]
|
||||
}
|
||||
Reference in New Issue
Block a user