@dasf/dasf-messaging
Version:
Typescript bindings for the DASF RPC messaging protocol.
1,322 lines (1,285 loc) • 51.4 kB
JavaScript
var V = Object.defineProperty;
var H = (t, n, i) => n in t ? V(t, n, { enumerable: !0, configurable: !0, writable: !0, value: i }) : t[n] = i;
var c = (t, n, i) => H(t, typeof n != "symbol" ? n + "" : n, i);
var C = {}, A = {}, N = {}, q;
function x() {
return q || (q = 1, function(t) {
Object.defineProperty(t, "__esModule", { value: !0 }), function(n) {
n[n.DISABLE = 0] = "DISABLE", n[n.ENABLE = 1] = "ENABLE", n[n.LOGGING = 2] = "LOGGING";
}(t.OperationMode || (t.OperationMode = {})), function(n) {
n[n.CASE_STRICT = 1] = "CASE_STRICT", n[n.CASE_INSENSITIVE = 2] = "CASE_INSENSITIVE";
}(t.PropertyMatchingRule || (t.PropertyMatchingRule = {})), function(n) {
n[n.ALLOW_NULL = 1] = "ALLOW_NULL", n[n.ALLOW_OBJECT_NULL = 2] = "ALLOW_OBJECT_NULL", n[n.DISALLOW_NULL = 3] = "DISALLOW_NULL";
}(t.ValueCheckingMode || (t.ValueCheckingMode = {}));
}(N)), N;
}
var L = {}, G;
function B() {
if (G) return L;
G = 1, Object.defineProperty(L, "__esModule", { value: !0 });
var t = (
/** @class */
function() {
function i() {
}
return i.MAPPING_PROPERTY = "__jsonconvert__mapping__", i.MAPPER_PROPERTY = "__jsonconvert__mapper__", i.CLASS_IDENTIFIER = "__jsonconvert__class_identifier__", i;
}()
);
L.Settings = t;
var n = (
/** @class */
/* @__PURE__ */ function() {
function i() {
this.classPropertyName = "", this.jsonPropertyName = "", this.expectedJsonType = void 0, this.isOptional = !1, this.customConverter = null;
}
return i;
}()
);
return L.MappingOptions = n, L;
}
var M = {}, T;
function k() {
if (T) return M;
T = 1, Object.defineProperty(M, "__esModule", { value: !0 });
var t = (
/** @class */
/* @__PURE__ */ function() {
function n() {
}
return n;
}()
);
return M.Any = t, M;
}
var z;
function $() {
if (z) return A;
z = 1, Object.defineProperty(A, "__esModule", { value: !0 });
var t = x(), n = B(), i = k(), u = (
/** @class */
function() {
function a(e, r, s, o) {
this._operationMode = t.OperationMode.ENABLE, this._valueCheckingMode = t.ValueCheckingMode.ALLOW_OBJECT_NULL, this._ignorePrimitiveChecks = !1, this._propertyMatchingRule = t.PropertyMatchingRule.CASE_STRICT, this._ignoreRequiredCheck = !1, e !== void 0 && e in t.OperationMode && (this.operationMode = e), r !== void 0 && r in t.ValueCheckingMode && (this.valueCheckingMode = r), s !== void 0 && (this.ignorePrimitiveChecks = s), o !== void 0 && (this.propertyMatchingRule = o);
}
return Object.defineProperty(a.prototype, "operationMode", {
/**
* Determines how the JsonConvert class instance should operate.
*
* You may assign three different values:
* - OperationMode.DISABLE: json2typescript will be disabled, no type checking or mapping is done
* - OperationMode.ENABLE: json2typescript is enabled, but only errors are logged
* - OperationMode.LOGGING: json2typescript is enabled and detailed information is logged
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
get: function() {
return this._operationMode;
},
/**
* Determines how the JsonConvert class instance should operate.
*
* You may assign three different values:
* - OperationMode.DISABLE: json2typescript will be disabled, no type checking or mapping is done
* - OperationMode.ENABLE: json2typescript is enabled, but only errors are logged
* - OperationMode.LOGGING: json2typescript is enabled and detailed information is logged
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
set: function(e) {
e in t.OperationMode && (this._operationMode = e);
},
enumerable: !0,
configurable: !0
}), Object.defineProperty(a.prototype, "valueCheckingMode", {
/**
* Determines which types are allowed to be null.
*
* You may assign three different values:
* - ValueCheckingMode.ALLOW_NULL: all given values in the JSON are allowed to be null
* - ValueCheckingMode.ALLOW_OBJECT_NULL: objects in the JSON are allowed to be null, primitive types are not allowed to be null
* - ValueCheckingMode.DISALLOW_NULL: no null values are tolerated in the JSON
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
get: function() {
return this._valueCheckingMode;
},
/**
* Determines which types are allowed to be null.
*
* You may assign three different values:
* - ValueCheckingMode.ALLOW_NULL: all given values in the JSON are allowed to be null
* - ValueCheckingMode.ALLOW_OBJECT_NULL: objects in the JSON are allowed to be null, primitive types are not allowed to be null
* - ValueCheckingMode.DISALLOW_NULL: no null values are tolerated in the JSON
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
set: function(e) {
e in t.ValueCheckingMode && (this._valueCheckingMode = e);
},
enumerable: !0,
configurable: !0
}), Object.defineProperty(a.prototype, "ignorePrimitiveChecks", {
/**
* Determines whether primitive types should be checked.
* If true, it will be allowed to assign primitive to other primitive types.
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
get: function() {
return this._ignorePrimitiveChecks;
},
/**
* Determines whether primitive types should be checked.
* If true, it will be allowed to assign primitive to other primitive types.
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
set: function(e) {
this._ignorePrimitiveChecks = e;
},
enumerable: !0,
configurable: !0
}), Object.defineProperty(a.prototype, "propertyMatchingRule", {
/**
* Determines the rule of how JSON properties shall be matched with class properties during deserialization.
*
* You may assign the following values:
* - PropertyMatchingRule.CASE_STRICT: JSON properties need to match exactly the names in the decorators
* - PropertyMatchingRule.CASE_INSENSITIVE: JSON properties need to match names in the decorators, but names they are not case sensitive
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
get: function() {
return this._propertyMatchingRule;
},
/**
* Determines the rule of how JSON properties shall be matched with class properties during deserialization.
*
* You may assign the following values:
* - PropertyMatchingRule.CASE_STRICT: JSON properties need to match exactly the names in the decorators
* - PropertyMatchingRule.CASE_INSENSITIVE: JSON properties need to match names in the decorators, but names they are not case sensitive
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
set: function(e) {
e in t.PropertyMatchingRule && (this._propertyMatchingRule = e);
},
enumerable: !0,
configurable: !0
}), Object.defineProperty(a.prototype, "ignoreRequiredCheck", {
/**
* Determines whether the check for "required" properties should be ignored, making all
* mapped values optional, whether or not the isOptional property mapping parameter is set.
* If true, any missing properties (undefined) when serializing or deserializing will be
* ignored, as if they were marked optional.
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
get: function() {
return this._ignoreRequiredCheck;
},
/**
* Determines whether the check for "required" properties should be ignored, making all
* mapped values optional, whether or not the isOptional property mapping parameter is set.
* If true, any missing properties (undefined) when serializing or deserializing will be
* ignored, as if they were marked optional.
*
* @see https://www.npmjs.com/package/json2typescript full documentation
*/
set: function(e) {
this._ignoreRequiredCheck = e;
},
enumerable: !0,
configurable: !0
}), a.prototype.serialize = function(e, r) {
if (this.operationMode === t.OperationMode.DISABLE)
return e;
if (e instanceof Array)
return this.serializeArray(e, r);
if (typeof e == "object")
return this.serializeObject(e, r);
throw new Error(`Fatal error in JsonConvert. Passed parameter data in JsonConvert.serialize() is not in valid format (object or array).
`);
}, a.prototype.serializeObject = function(e, r) {
if (this.operationMode === t.OperationMode.DISABLE)
return e;
if (e === void 0)
throw new Error(`Fatal error in JsonConvert. Passed parameter instance in JsonConvert.serializeObject() is undefined. This is not a valid JSON format.
`);
if (e === null) {
if (this.valueCheckingMode === t.ValueCheckingMode.DISALLOW_NULL)
throw new Error(`Fatal error in JsonConvert. Passed parameter instance in JsonConvert.serializeObject() is undefined. You have specified to disallow null values.
`);
return e;
} else if (typeof e != "object" || e instanceof Array)
throw new Error(`Fatal error in JsonConvert. Passed parameter instance in JsonConvert.serializeObject() is not of type object.
`);
this.operationMode === t.OperationMode.LOGGING && (console.log("----------"), console.log("Receiving JavaScript instance:"), console.log(e));
var s = {}, o;
r ? o = new r() : o = e;
for (var p = 0, l = Object.keys(o); p < l.length; p++) {
var g = l[p];
try {
this.serializeObject_loopProperty(e, o, g, s);
} catch (d) {
throw this.operationMode === t.OperationMode.LOGGING && (console.log("Failed to serialize property:"), console.log(d), console.log("----------")), d;
}
}
return this.operationMode === t.OperationMode.LOGGING && (console.log("Returning JSON object:"), console.log(s), console.log("----------")), s;
}, a.prototype.serializeArray = function(e, r) {
if (this.operationMode === t.OperationMode.DISABLE)
return e;
if (e === void 0)
throw new Error(`Fatal error in JsonConvert. Passed parameter instanceArray in JsonConvert.serializeArray() is undefined. This is not a valid JSON format.
`);
if (e === null) {
if (this.valueCheckingMode === t.ValueCheckingMode.DISALLOW_NULL)
throw new Error(`Fatal error in JsonConvert. Passed parameter instanceArray in JsonConvert.serializeArray() is undefined. You have specified to disallow null values.
`);
return e;
} else if (typeof e != "object" || !(e instanceof Array))
throw new Error(`Fatal error in JsonConvert. Passed parameter instanceArray in JsonConvert.serializeArray() is not of type array.
`);
this.operationMode === t.OperationMode.LOGGING && (console.log("----------"), console.log("Receiving JavaScript array:"), console.log(e));
for (var s = [], o = 0, p = e; o < p.length; o++) {
var l = p[o];
s.push(this.serializeObject(l, r));
}
return this.operationMode === t.OperationMode.LOGGING && (console.log("Returning JSON array:"), console.log(s), console.log("----------")), s;
}, a.prototype.deserialize = function(e, r) {
if (this.operationMode === t.OperationMode.DISABLE)
return e;
if (e instanceof Array)
return this.deserializeArray(e, r);
if (typeof e == "object")
return this.deserializeObject(e, r);
throw new Error(`Fatal error in JsonConvert. Passed parameter json in JsonConvert.deserialize() is not in valid JSON format (object or array).
`);
}, a.prototype.deserializeObject = function(e, r) {
if (this.operationMode === t.OperationMode.DISABLE)
return e;
if (e === void 0)
throw new Error(`Fatal error in JsonConvert. Passed parameter jsonObject in JsonConvert.deserializeObject() is undefined. This is not a valid JSON format.
`);
if (e === null) {
if (this.valueCheckingMode === t.ValueCheckingMode.DISALLOW_NULL)
throw new Error(`Fatal error in JsonConvert. Passed parameter jsonObject in JsonConvert.deserializeObject() is undefined. You have specified to disallow null values.
`);
return e;
} else if (typeof e != "object" || e instanceof Array)
throw new Error(`Fatal error in JsonConvert. Passed parameter jsonObject in JsonConvert.deserializeObject() is not of type object.
`);
this.operationMode === t.OperationMode.LOGGING && (console.log("----------"), console.log("Receiving JSON object:"), console.log(e));
for (var s = new r(), o = 0, p = Object.keys(s); o < p.length; o++) {
var l = p[o];
try {
this.deserializeObject_loopProperty(s, l, e);
} catch (g) {
throw this.operationMode === t.OperationMode.LOGGING && (console.log("Failed to deserialize property:"), console.log(g), console.log("----------")), g;
}
}
return this.operationMode === t.OperationMode.LOGGING && (console.log("Returning CLASS instance:"), console.log(s), console.log("----------")), s;
}, a.prototype.deserializeArray = function(e, r) {
if (this.operationMode === t.OperationMode.DISABLE)
return e;
if (e === void 0)
throw new Error(`Fatal error in JsonConvert. Passed parameter jsonArray in JsonConvert.deserializeObject() is undefined. This is not a valid JSON format.
`);
if (e === null) {
if (this.valueCheckingMode === t.ValueCheckingMode.DISALLOW_NULL)
throw new Error(`Fatal error in JsonConvert. Passed parameter jsonArray in JsonConvert.deserializeObject() is undefined. You have specified to disallow null values.
`);
return e;
} else if (typeof e != "object" || !(e instanceof Array))
throw new Error(`Fatal error in JsonConvert. Passed parameter jsonArray in JsonConvert.deserializeArray() is not of type array.
`);
if (this.operationMode === t.OperationMode.DISABLE)
return e;
this.operationMode === t.OperationMode.LOGGING && (console.log("----------"), console.log("Receiving JSON array:"), console.log(e));
for (var s = [], o = 0, p = e; o < p.length; o++) {
var l = p[o];
s.push(this.deserializeObject(l, r));
}
return this.operationMode === t.OperationMode.LOGGING && (console.log("Returning array of CLASS instances:"), console.log(s), console.log("----------")), s;
}, a.prototype.serializeObject_loopProperty = function(e, r, s, o) {
var p = this.getClassPropertyMappingOptions(r, s);
if (p !== null) {
var l = p.jsonPropertyName, g = p.expectedJsonType, d = p.isOptional, m = p.customConverter, v = e[s];
if (typeof v > "u") {
if (d || this._ignoreRequiredCheck)
return;
throw new Error('Fatal error in JsonConvert. Failed to map the JavaScript instance of class "' + r[n.Settings.CLASS_IDENTIFIER] + '" to JSON because the defined class property "' + s + `" does not exist or is not defined:
Class property:
` + s + `
JSON property:
` + l + `
`);
}
if (!(d && v === null))
try {
o[l] = m !== null ? m.serialize(v) : this.verifyProperty(g, v, !0);
} catch (F) {
throw new Error('Fatal error in JsonConvert. Failed to map the JavaScript instance of class "' + r[n.Settings.CLASS_IDENTIFIER] + `" to JSON because of a type error.
Class property:
` + s + `
Class property value:
` + v + `
Expected type:
` + this.getExpectedType(g) + `
Runtime type:
` + this.getTrueType(v) + `
JSON property:
` + l + `
` + F.message + `
`);
}
}
}, a.prototype.deserializeObject_loopProperty = function(e, r, s) {
var o = this.getClassPropertyMappingOptions(e, r);
if (o !== null) {
var p = o.jsonPropertyName, l = o.expectedJsonType, g = o.isOptional, d = o.customConverter, m = void 0;
try {
m = this.getObjectValue(s, p);
} catch {
}
if (typeof m > "u") {
if (g || this._ignoreRequiredCheck)
return;
throw new Error('Fatal error in JsonConvert. Failed to map the JSON object to the class "' + e[n.Settings.CLASS_IDENTIFIER] + '" because the defined JSON property "' + p + `" does not exist:
Class property:
` + r + `
JSON property:
` + p + `
`);
}
if (!(g && m === null))
try {
e[r] = d !== null ? d.deserialize(m) : this.verifyProperty(l, m);
} catch (v) {
throw new Error('Fatal error in JsonConvert. Failed to map the JSON object to the class "' + e[n.Settings.CLASS_IDENTIFIER] + `" because of a type error.
Class property:
` + r + `
Expected type:
` + this.getExpectedType(l) + `
JSON property:
` + p + `
JSON type:
` + this.getJsonType(m) + `
JSON value:
` + JSON.stringify(m) + `
` + v.message + `
`);
}
}
}, a.prototype.getClassPropertyMappingOptions = function(e, r) {
var s = e[n.Settings.MAPPING_PROPERTY];
if (typeof s > "u")
return null;
for (var o = Object.getPrototypeOf(e); o != null; ) {
var p = o[n.Settings.CLASS_IDENTIFIER];
if (p) {
var l = p + "." + r;
if (typeof s[l] < "u")
return s[l];
}
o = Object.getPrototypeOf(o);
}
return null;
}, a.prototype.verifyProperty = function(e, r, s) {
if (e === i.Any || e === null || e === Object)
return r;
if (!(e instanceof Array) && !(r instanceof Array))
if (typeof e < "u" && e.prototype.hasOwnProperty(n.Settings.CLASS_IDENTIFIER)) {
if (r === null) {
if (this.valueCheckingMode !== t.ValueCheckingMode.DISALLOW_NULL)
return null;
throw new Error(" Reason: Given value is null.");
}
return s ? this.serializeObject(r, e) : this.deserializeObject(r, e);
} else if (e === i.Any || e === null || e === Object) {
if (r === null) {
if (this.valueCheckingMode !== t.ValueCheckingMode.DISALLOW_NULL)
return null;
throw new Error(" Reason: Given value is null.");
}
return r;
} else if (e === String || e === Number || e === Boolean) {
if (r === null) {
if (this.valueCheckingMode === t.ValueCheckingMode.ALLOW_NULL)
return null;
throw new Error(" Reason: Given value is null.");
}
if (
// primitive types match
e === String && typeof r == "string" || e === Number && typeof r == "number" || e === Boolean && typeof r == "boolean"
)
return r;
if (this.ignorePrimitiveChecks)
return r;
throw new Error(" Reason: Given object does not match the expected primitive type.");
} else
throw new Error(` Reason: Expected type is unknown. There might be multiple reasons for this:
- You are missing the decorator @JsonObject (for object mapping)
- You are missing the decorator @JsonConverter (for custom mapping) before your class definition
- Your given class is undefined in the decorator because of circular dependencies`);
if (e instanceof Array && r instanceof Array) {
var o = [];
if (r.length === 0)
return o;
if (e.length === 0)
return r;
for (var p = e.length < r.length, l = 0; l < r.length; l++)
p && l >= e.length && (e[l] = e[l - 1]), o[l] = this.verifyProperty(e[l], r[l], s);
return o;
}
if (e instanceof Array && r instanceof Object) {
var o = [];
if (r.length === 0)
return o;
if (e.length === 0)
return r;
var p = e.length < Object.keys(r).length, l = 0;
for (var g in r)
p && l >= e.length && (e[l] = e[l - 1]), o[g] = this.verifyProperty(e[l], r[g]), l++;
return o;
}
if (e instanceof Array) {
if (r === null) {
if (this.valueCheckingMode !== t.ValueCheckingMode.DISALLOW_NULL)
return null;
throw new Error(" Reason: Given value is null.");
}
throw new Error(" Reason: Expected type is array, but given value is non-array.");
}
throw r instanceof Array ? new Error(" Reason: Given value is array, but expected a non-array type.") : new Error(" Reason: Mapping failed because of an unknown error.");
}, a.prototype.getObjectValue = function(e, r) {
if (this.propertyMatchingRule === t.PropertyMatchingRule.CASE_INSENSITIVE) {
var s = Object.keys(e).reduce(function(o, p) {
return o[p.toLowerCase()] = p, o;
}, {});
r = s[r.toLowerCase()];
}
if (!(r in e))
throw new Error();
return e[r];
}, a.prototype.getExpectedType = function(e) {
var r = "";
if (e instanceof Array) {
r = "[";
for (var s = 0; s < e.length; s++)
s > 0 && (r += ","), r += this.getExpectedType(e[s]);
return r += "]", r;
} else
return e === i.Any || e === null || e === Object ? "any" : e === String || e === Boolean || e === Number ? new e().constructor.name.toLowerCase() : typeof e == "function" ? new e().constructor.name : e === void 0 ? "undefined" : "?????";
}, a.prototype.getJsonType = function(e) {
if (e === null)
return "null";
var r = "";
if (e instanceof Array) {
r = "[";
for (var s = 0; s < e.length; s++)
s > 0 && (r += ","), r += this.getJsonType(e[s]);
return r += "]", r;
} else
return typeof e;
}, a.prototype.getTrueType = function(e) {
return typeof e;
}, a;
}()
);
return A.JsonConvert = u, A;
}
var w = {}, U;
function Q() {
if (U) return w;
U = 1, Object.defineProperty(w, "__esModule", { value: !0 });
var t = B(), n = k();
function i(e) {
e[t.Settings.MAPPER_PROPERTY] = "";
}
w.JsonConverter = i;
function u(e) {
var r = "", s = function(p) {
p.prototype[t.Settings.CLASS_IDENTIFIER] = r.length > 0 ? r : p.name;
var l = p.prototype[t.Settings.MAPPING_PROPERTY];
if (l)
for (var g = Object.keys(l).filter(function(F) {
return F.indexOf(t.Settings.CLASS_IDENTIFIER + ".") === 0;
}), d = 0, m = g; d < m.length; d++) {
var v = m[d];
l[v.replace(t.Settings.CLASS_IDENTIFIER, p.prototype[t.Settings.CLASS_IDENTIFIER])] = l[v], delete l[v];
}
}, o = typeof e;
switch (o) {
// Decorator was @JsonObject(classId)
case "string":
return r = e, s;
// Decorator was @JsonObject
// Decorator was @JsonObject()
// Decorator was @JsonObject(123)
case "function":
case "undefined":
default:
throw new Error(`Fatal error in JsonConvert. It is mandatory to pass a string as parameter in the @JsonObject decorator.
Use @JsonObject(classId) where classId is a string.
`);
}
}
w.JsonObject = u;
function a() {
for (var e = [], r = 0; r < arguments.length; r++)
e[r] = arguments[r];
return function(s, o) {
var p = o, l = n.Any, g = !1;
switch (e.length) {
case 1:
if (e[0] === void 0)
throw new Error(`Fatal error in JsonConvert. It is not allowed to explicitly pass "undefined" as first parameter in the @JsonProperty decorator.
Class property:
` + o + `
Leave the decorator parameters empty if you do not wish to pass the first parameter.
`);
p = e[0];
break;
case 2:
if (e[0] === void 0)
throw new Error(`Fatal error in JsonConvert. It is not allowed to explicitly pass "undefined" as first parameter in the @JsonProperty decorator.
Class property:
` + o + `
Leave the decorator parameters empty if you do not wish to pass the first parameter.
`);
if (e[1] === void 0)
throw new Error(`Fatal error in JsonConvert. It is not allowed to explicitly pass "undefined" as second parameter in the @JsonProperty decorator.
Class property:
` + o + `
Use "Any" to allow any type. You can import this class from "json2typescript".
`);
p = e[0], l = e[1];
break;
case 3:
if (e[0] === void 0)
throw new Error(`Fatal error in JsonConvert. It is not allowed to explicitly pass "undefined" as first parameter in the @JsonProperty decorator.
Class property:
` + o + `
Leave the decorator parameters empty if you do not wish to pass the first parameter.
`);
if (e[1] === void 0)
throw new Error(`Fatal error in JsonConvert. It is not allowed to explicitly pass "undefined" as second parameter in the @JsonProperty decorator.
Class property:
` + o + `
Use "Any" to allow any type. You can import this class from "json2typescript".
`);
p = e[0], l = e[1], g = e[2];
break;
}
typeof s[t.Settings.MAPPING_PROPERTY] > "u" && (s[t.Settings.MAPPING_PROPERTY] = []);
var d = new t.MappingOptions();
if (d.classPropertyName = o, d.jsonPropertyName = p, d.isOptional = g || !1, typeof l < "u" && l !== null && typeof l[t.Settings.MAPPER_PROPERTY] < "u" ? d.customConverter = new l() : d.expectedJsonType = l, typeof s[t.Settings.MAPPING_PROPERTY][t.Settings.CLASS_IDENTIFIER + "." + o] > "u")
s[t.Settings.MAPPING_PROPERTY][t.Settings.CLASS_IDENTIFIER + "." + o] = d;
else
throw new Error(`Fatal error in JsonConvert. It is not allowed to add multiple decorators for the same property.
Class property:
` + o + `
`);
};
}
return w.JsonProperty = a, w;
}
var W;
function X() {
if (W) return C;
W = 1, Object.defineProperty(C, "__esModule", { value: !0 });
var t = $();
C.JsonConvert = t.JsonConvert;
var n = x();
C.ValueCheckingMode = n.ValueCheckingMode, C.OperationMode = n.OperationMode;
var i = Q();
C.JsonObject = i.JsonObject, C.JsonProperty = i.JsonProperty, C.JsonConverter = i.JsonConverter;
var u = k();
return C.Any = u.Any, C;
}
var h = X(), Z = Object.defineProperty, K = Object.getOwnPropertyDescriptor, f = (t, n, i, u) => {
for (var a = u > 1 ? void 0 : u ? K(n, i) : n, e = t.length - 1, r; e >= 0; e--)
(r = t[e]) && (a = (u ? r(n, i, a) : r(a)) || a);
return u && a && Z(n, i, a), a;
}, P = /* @__PURE__ */ ((t) => (t.Ping = "ping", t.Pong = "pong", t.Info = "info", t.ApiInfo = "api_info", t.Request = "request", t.Response = "response", t.Log = "log", t.Progress = "progress", t))(P || {}), D = /* @__PURE__ */ ((t) => (t.ResponseTopic = "response_topic", t.RequestContext = "requestContext", t.RequestMessageId = "requestMessageId", t.MessageType = "messageType", t.SourceTopic = "source_topic", t.Fragment = "fragment", t.NumFragments = "num_fragments", t.Status = "status", t))(D || {}), ee = /* @__PURE__ */ ((t) => (t.Success = "success", t.Error = "error", t.Running = "running", t))(ee || {});
let y = class {
constructor() {
c(this, "payload", "");
/** An identifier for the request to handle identify the response handler */
c(this, "context", "");
c(this, "properties");
}
static createMessage(t) {
const n = new y();
return n.properties = {}, n.properties.messageType = t, n;
}
/** Shortcut to create a request message
*
* This static method creates a :class:`DASFModuleRequest` with the
* :ref:`MessageType` `MessageType.Request`
*
* @param data - Optional data as javascript object that will be
* json-serialized and added as :attr:`payload` to the request.
*
* @returns The :class:`DASFModuleRequest` of type `MessageType.Request`
*/
static createRequestMessage(t) {
const n = y.createMessage(
"request"
/* Request */
);
return typeof t < "u" && (n.payload = btoa(JSON.stringify(t))), n;
}
/** Shortcut to create a Ping message
*
* This static method creates a :class:`DASFModuleRequest` with the
* :ref:`MessageType` `MessageType.Ping`
*
* @returns The :class:`DASFModuleRequest` of type `MessageType.Ping`
*/
static createPingMessage() {
return y.createMessage(
"ping"
/* Ping */
);
}
/** Shortcut to create a Pong message
*
* This static method creates a :class:`DASFModuleRequest` with the
* :ref:`MessageType` `MessageType.Pong`
*
* @returns The :class:`DASFModuleRequest` of type `MessageType.Pong`
*/
static createPongMessage() {
return y.createMessage(
"pong"
/* Pong */
);
}
/** Shortcut to create an Info message
*
* This static method creates a :class:`DASFModuleRequest` with the
* :ref:`MessageType` `MessageType.Info` to get the information on the
* backend module, see also :meth:`DASFConnection.getModuleInfo`
*
* @returns The :class:`DASFModuleRequest` of type `MessageType.Info`
*/
static createInfoMessage() {
return y.createMessage(
"info"
/* Info */
);
}
/** Shortcut to create an Info message
*
* This static method creates a :class:`DASFModuleRequest` with the
* :ref:`MessageType` `MessageType.Info` to get the information on the
* backend module, see also :meth:`DASFConnection.getApiInfo`
*
* @returns The :class:`DASFModuleRequest` of type `MessageType.ApiInfo`
*/
static createApiInfoMessage() {
return y.createMessage(
"api_info"
/* ApiInfo */
);
}
/** Shortcut to the the messagetype of the properties */
getMessageType() {
if (this.properties)
return this.properties.messageType;
throw new Error("Missing or empty message type property");
}
};
f([
h.JsonProperty("payload", String)
], y.prototype, "payload", 2);
f([
h.JsonProperty("properties", h.Any)
], y.prototype, "properties", 2);
y = f([
h.JsonObject("DASFModuleRequest")
], y);
let O = class {
constructor() {
c(this, "result", "");
c(this, "messageId", "");
c(this, "errorMsg", "");
c(this, "context", "");
}
isOk() {
return this.result == "ok";
}
};
f([
h.JsonProperty("result", String)
], O.prototype, "result", 2);
f([
h.JsonProperty("messageId", String, !0)
], O.prototype, "messageId", 2);
f([
h.JsonProperty("errorMsg", String, !0)
], O.prototype, "errorMsg", 2);
f([
h.JsonProperty("context", String, !0)
], O.prototype, "context", 2);
O = f([
h.JsonObject("DASFModuleRequestReceipt")
], O);
let J = class {
constructor(t) {
c(this, "messageId", "");
t && (this.messageId = t);
}
};
f([
h.JsonProperty("messageId", String)
], J.prototype, "messageId", 2);
J = f([
h.JsonObject("DASFAcknowledgment")
], J);
let R = class {
constructor() {
c(this, "messageId", "");
c(this, "payload", "");
c(this, "publishTime", "");
c(this, "properties");
}
/** Shortcut to the the messagetype of the properties */
getMessageType() {
if (this.properties) {
const t = this.properties.messageType;
if (t && t.trim().length > 0)
return t;
}
throw new Error("Missing or empty message type property");
}
/** Shortcut to the the request context of the properties */
getRequestContext() {
if (this.properties) {
const t = this.properties.requestContext;
if (t)
return t;
}
throw new Error("Missing or empty request context property");
}
/** Get the original id of the request */
getRequestMessageId() {
if (this.properties) {
const t = this.properties.requestMessageId;
if (t)
return t;
}
throw new Error("Missing or empty request messageId property");
}
/** Check if the response is fragmented or not. */
isFragmented() {
return this.properties != null && Object.prototype.hasOwnProperty.call(
this.properties,
"num_fragments"
/* NumFragments */
) && Object.prototype.hasOwnProperty.call(
this.properties,
"fragment"
/* Fragment */
);
}
/** Get the id of this fragment. */
getFragmentId() {
if (this.properties && this.isFragmented())
return this.properties.fragment;
throw new Error(
"Unable to request fragment id from unfragmented response."
);
}
/** Get the total number of fragments */
getNumberOfFragments() {
if (this.properties && this.isFragmented())
return this.properties.num_fragments;
throw new Error(
"Unable to request number of fragments from unfragmented response."
);
}
};
f([
h.JsonProperty("messageId", String)
], R.prototype, "messageId", 2);
f([
h.JsonProperty("payload", String)
], R.prototype, "payload", 2);
f([
h.JsonProperty("publishTime", String)
], R.prototype, "publishTime", 2);
f([
h.JsonProperty("properties")
], R.prototype, "properties", 2);
R = f([
h.JsonObject("DASFModuleResponse")
], R);
let S = class {
constructor() {
c(this, "report_type", "");
c(this, "report_id", "");
c(this, "step_message", "");
c(this, "steps", 0);
c(this, "status", "running");
c(this, "children");
}
hasError() {
return this.status == "error";
}
hasSuccess() {
return this.status == "success";
}
isRunning() {
return this.status == "running";
}
isComplete() {
return !this.isRunning();
}
};
f([
h.JsonProperty("report_type", String)
], S.prototype, "report_type", 2);
f([
h.JsonProperty("report_id", String)
], S.prototype, "report_id", 2);
f([
h.JsonProperty("step_message", String)
], S.prototype, "step_message", 2);
f([
h.JsonProperty("steps", Number)
], S.prototype, "steps", 2);
f([
h.JsonProperty("status", String)
], S.prototype, "status", 2);
f([
h.JsonProperty("children", [S])
], S.prototype, "children", 2);
S = f([
h.JsonObject("DASFProgressReport")
], S);
let b = class {
// dummy JsonSchemaConverter to make sure the json2typescript library does
// not complain
serialize(t) {
return JSON.stringify(t);
}
deserialize(t) {
return t;
}
};
b = f([
h.JsonConverter
], b);
let E = class {
constructor() {
c(this, "name", "");
c(this, "rpcSchema", {});
c(this, "returnSchema", {});
}
};
f([
h.JsonProperty("name", String)
], E.prototype, "name", 2);
f([
h.JsonProperty("rpc_schema", b)
], E.prototype, "rpcSchema", 2);
f([
h.JsonProperty("return_schema", b)
], E.prototype, "returnSchema", 2);
E = f([
h.JsonObject("FunctionApiInfo")
], E);
let I = class {
constructor() {
c(this, "name", "");
c(this, "rpcSchema", {});
c(this, "methods", []);
}
};
f([
h.JsonProperty("name", String)
], I.prototype, "name", 2);
f([
h.JsonProperty("rpc_schema", b)
], I.prototype, "rpcSchema", 2);
f([
h.JsonProperty("methods", [E])
], I.prototype, "methods", 2);
I = f([
h.JsonObject("ClassApiInfo")
], I);
let _ = class {
constructor() {
c(this, "classes", []);
c(this, "functions", []);
c(this, "rpcSchema", {});
}
};
f([
h.JsonProperty("classes", [I])
], _.prototype, "classes", 2);
f([
h.JsonProperty("functions", [E])
], _.prototype, "functions", 2);
f([
h.JsonProperty("rpc_schema", b)
], _.prototype, "rpcSchema", 2);
_ = f([
h.JsonObject("ModuleApiInfo")
], _);
class re {
/**
* @param urlBuilder - A builder for the consumer and producer websocket url
* @param onConnectionError - A callback for the case when no connection could be established
*/
constructor(n, i) {
c(this, "outgoingChannel");
c(this, "incomingChannel");
c(this, "DASFProducerURL");
c(this, "DASFConsumerURL");
c(this, "consumeTopic");
c(this, "jsonCoder");
c(this, "contextCounter", 0);
c(this, "responseResolvers", /* @__PURE__ */ new Map());
c(this, "progressCallbacks", /* @__PURE__ */ new Map());
c(this, "responseRejectHandler", /* @__PURE__ */ new Map());
c(this, "finishedContexts", /* @__PURE__ */ new Set());
c(this, "contextResponseFragments", /* @__PURE__ */ new Map());
c(this, "pendingRequests", []);
c(this, "waitingForPong", !1);
c(this, "connectionTimeout", 1e4);
// 10sec
c(this, "connectionError", "");
c(this, "onConnectionError");
c(this, "startedReconnectOutgoing", !0);
c(this, "startedReconnectIncoming", !0);
this.onConnectionError = i, this.consumeTopic = n.consumeTopic, this.DASFProducerURL = n.DASFProducerURL, this.DASFConsumerURL = n.DASFConsumerURL, this.jsonCoder = new h.JsonConvert(), this.connect(), setInterval(() => this.checkConnection(), this.connectionTimeout);
}
connect() {
this.startedReconnectIncoming = !0, this.startedReconnectOutgoing = !0, this.outgoingChannel = new WebSocket(this.DASFProducerURL), this.incomingChannel = new WebSocket(this.DASFConsumerURL), this.registerListener();
}
isConnected() {
return this.outgoingChannel && this.incomingChannel && this.outgoingChannel.readyState == WebSocket.OPEN && this.incomingChannel.readyState == WebSocket.OPEN;
}
isConnecting() {
return this.outgoingChannel && this.incomingChannel && this.outgoingChannel.readyState != WebSocket.OPEN && this.incomingChannel.readyState != WebSocket.OPEN;
}
/**
* Do something as soon as the websocket connection has been established
*
* This property returns a promise that resolves with the established
* connection. You can use this to do something right after the connection has
* been created.
*
* ```
* import { DASFConnection, WebsocketUrlBuilder } from '@dasf/dasf-messaging'
* const connection = new DASFConnection(
* new WebsocketUrlBuilder(
* 'ws://localhost:8080/ws',
* 'some-topic'
* )
* )
*
* // log to the console when the connection has been connected
* connection.connected.then(
* (connection: DASFConnection) => console.log("Websocket connection has been established.")
* ).catch(
* (error: Error) => console.log(error)
* )
* ```
*
*
*/
get connected() {
const n = (i, u) => {
this.hasConnectionError() ? u(new Error(this.connectionError)) : this.assureConnected() ? i(this) : setTimeout(() => n(i, u), 100);
};
return new Promise(n);
}
assureConnected() {
return this.isConnected() ? !0 : (this.startedReconnectIncoming || this.startedReconnectOutgoing || this.isConnecting() || this.connect(), !1);
}
hasPendingRequests() {
return this.pendingRequests.length > 0;
}
sendPendingRequests() {
if (this.hasPendingRequests()) {
const n = this.pendingRequests.shift();
this.outgoingChannel.send(JSON.stringify(n)), setTimeout(() => this.sendPendingRequests(), 200);
}
}
registerListener() {
const n = (i) => {
this.startedReconnectOutgoing = !1, this.startedReconnectIncoming = !1, !this.hasConnectionError() && this.isConnecting() && (this.connectionError = "Connection to " + i.target.url + " failed.", this.onConnectionError && this.onConnectionError(this.connectionError));
};
this.outgoingChannel.addEventListener("error", n), this.incomingChannel.addEventListener("error", n), this.outgoingChannel.addEventListener("open", () => {
this.startedReconnectOutgoing = !1, this.connectionError = "", this.outgoingChannel.addEventListener("message", (i) => {
const u = this.jsonCoder.deserializeObject(
JSON.parse(i.data),
O
);
if (!u.isOk()) {
console.error(u), this.responseResolvers.delete(u.context);
const a = this.responseRejectHandler.get(
u.context
);
a ? (this.responseRejectHandler.delete(u.context), a(new Error(u.errorMsg))) : console.error(
"received error receipt for an unknwon context: " + u.context
);
}
});
}), this.incomingChannel.addEventListener("open", () => {
this.startedReconnectIncoming = !1, this.connectionError = "", this.incomingChannel.addEventListener("message", (i) => {
var u;
try {
const a = JSON.parse(i.data), e = this.jsonCoder.deserializeObject(
a,
R
);
this.acknowledgeMessage(e);
const r = e.getRequestContext();
if (this.finishedContexts.has(r))
return;
if (e.getMessageType() == P.Progress) {
const s = this.jsonCoder.deserializeObject(
JSON.parse(atob(a.payload)),
S
), o = this.progressCallbacks.get(r);
o && o({
message: s,
props: e.properties
});
} else {
if (e.isFragmented())
if (this.contextResponseFragments.has(r)) {
let o = this.contextResponseFragments.get(r);
if (o)
if (o.push(e), o.length == e.getNumberOfFragments()) {
o = o.sort(
(l, g) => l.getFragmentId() - g.getFragmentId()
);
let p = "";
for (const l of o)
p += l.payload;
e.payload = p, this.contextResponseFragments.delete(r);
} else
return;
} else {
this.contextResponseFragments.set(r, [e]);
return;
}
const s = this.responseResolvers.get(r);
if (s) {
const o = this.responseRejectHandler.get(r);
if (this.responseResolvers.delete(r), this.progressCallbacks.delete(r), this.responseRejectHandler.delete(r), this.finishedContexts.add(r), e != null && e.properties && ((u = e.properties) == null ? void 0 : u.status) == "error") {
let p;
if (typeof e.payload < "u" ? p = new Error(atob(e.payload)) : p = new Error(
"Failed processing request " + r
), typeof o < "u")
o(p);
else
throw console.error(p), p;
} else
s(e);
} else
console.warn(
"received a response for an unknown context: " + r,
e
);
}
} catch (a) {
console.error(a);
}
});
});
}
checkConnection() {
if (this.waitingForPong && console.warn("Ping to backend module timed out."), this.startedReconnectOutgoing || this.startedReconnectIncoming)
return;
this.waitingForPong = !0;
const n = y.createPingMessage();
this.sendMessage(n).then(() => {
this.waitingForPong = !1, this.sendPendingRequests();
}).catch((i) => {
console.warn(i.errorMsg);
});
}
/** Send a request to the backend module and retrieve the response
*
* This high-level implementation of :meth:`sendMessage` takes an object and
* sends it as a :class:`DASFModuleRequest` of type
* :attr:`MessageType.Request` to the backend module (as soon as
* the websocket connection has been established). The result
* is a promise that resolves to the response of the backend module.
*
* **Example**
*
* ```
* import { DASFConnection, WebsocketUrlBuilder } from '@dasf/dasf-messaging'
* const connection = new DASFConnection(
* new WebsocketUrlBuilder(
* 'ws://localhost:8080/ws',
* 'some-topic'
* )
* )
*
* // send request via the connection and log the response
* connection.sendRequest({func_name: 'version_info'}).then(
* (response) => console.log(response)
* )
* ```
*
* @param data - The object that is sent as payload of the request to the
* backend module
* @param onProgress - A callback to use when we receive progress reports
* while processing the request in the backend module.
*
* @returns The promise resolving to the deserialized response of the backend
* module
*/
async sendRequest(n, i) {
const u = y.createRequestMessage(n);
return this.sendMessage(u, i).then(
(a) => a.properties && a.properties.status == "error" ? "Error: " + atob(a.payload) : JSON.parse(atob(a.payload))
);
}
/** Send a generic message to the backend module
*
* This low-level implementation takes a generic :class:`DASFModuleRequest`
* and sends it to the backend module (as soon as the websocket connection
* has been established). The result is a promise that resolves to the
* response of the backend module.
*
* @param requestMessage - The message you want to send
* @param onProgress - A callback to use when we receive progress reports
* while processing the request in the backend module.
*
* @returns The promise resolving to the response of the backend module
*/
async sendMessage(n, i) {
if (n.context = String(++this.contextCounter), !n.properties)
throw new Error("missing request properties");
n.properties[D.ResponseTopic] = this.consumeTopic, n.properties[D.RequestContext] = n.context;
const {
promise: u,
resolve: a,
reject: e
} = Promise.withResolvers();
return this.hasConnectionError() ? e(new Error(this.connectionError)) : (this.responseResolvers.set(n.context, a), this.responseRejectHandler.set(n.context, e), typeof i < "u" && this.progressCallbacks.set(n.context, i), this.connected.then((r) => {
const s = JSON.stringify(n);
r.outgoingChannel.send(s);
})), u;
}
acknowledgeMessage(n) {
const i = this.jsonCoder.serializeObject(
new J(n.messageId)
);
this.incomingChannel.send(JSON.stringify(i));
}
/** Close all connections
*
* This method closes the connections to the outgoing and incoming websocket.
*
* **Example**
*
* ```
* import { DASFConnection, WebsocketUrlBuilder } from '@dasf/dasf-messaging'
* const connection = new DASFConnection(
* new WebsocketUrlBuilder(
* 'ws://localhost:8080/ws',
* 'some-topic'
* )
* )
*
* // send request via the connection and log the response
* connection.sendRequest({func_name: 'version_info'}).then(
* (response) => {
* console.log(response)
* // close the connection upon receival
* connection.close()
* }
* )
*
* ```
*/
close() {
this.outgoingChannel.close(), this.incomingChannel.close();
}
/** Get information on requests for this module
*
* This method retrieves the JSONSchema representation for requests to this
* module. It is one large schema object that can be used to validate a
* request for the :func:`sendRequest` method.
*
* @returns A promise that resolves to the JSONSchema for a request to this topic
*/
getModuleInfo() {
return this.sendInfoRequest(
y.createInfoMessage(),
P.Info
);
}
/** Get api information for this backend module
*
* This method retrieves the api info, namely the individual JSONSchema
* representations for the functions and classes in the backend module.
* Different from :func:`getModuleInfo`, this method does not only provide a
* single JSONSchema, but rather one JSONSchema for each method/function in
* the backend module.
*
* @returns an object representing the api of the backend module.
*/
getApiInfo() {
return this.sendInfoRequest(
y.createApiInfoMessage(),
P.ApiInfo
);
}
sendInfoRequest(n, i = P.Info) {
const { promise: u, resolve: a, reject: e } = Promise.withResolvers();
return this.sendMessage(n).then((r) => {
if (r.properties)
try {
const s = JSON.parse(r.properties[i]);
i == P.ApiInfo ? a(this.jsonCoder.deserializeObject(s, _)) : a(s);
} catch (s) {
console.warn(
`Unable to retrieve backend module ${i}, got: `,
r.properties[i]
), e(s);
}
}), u;
}
hasConnectionError() {
return this.connectionError.length > 0;
}
}
class ne {
constructor(n, i, u = "", a = "") {
c(this, "topic");
c(this, "consumeTopic");
c(this, "DASFConsumerURL");
c(this, "DASFProducerURL");
this.topic = i, this.consumeTopic = this.generateConsumeTopic(i), this.DASFConsumerURL = (a || this.buildUrl(n, this.consumeTopic)) + "/" + this.generateSubscriptionPrefix(), this.DASFProducerURL = u || this.buildUrl(n, this.topic);
}
buildUrl(n, i) {
return n + "/" + i;
}
generateConsumeTopic(n) {
return n + "_" + this.generateRequestToken();
}
generateSubscriptionPrefix() {
return "web-frontend-" + (/* @__PURE__ */ new Date()).toISOString();
}
generateRequestToken() {
return Math.random().toString(16).slice(2);
}
}
const j = class j {
constructor(n, i, u, a, e = "ws") {
c(this, "topic");
c(this, "cons