@daml/types
Version:
Primitive types of the Daml language and their serialization.
438 lines • 16.3 kB
JavaScript
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Map = exports.emptyMap = exports.TextMap = exports.Optional = exports.ContractId = exports.Date = exports.List = exports.Party = exports.Time = exports.Text = exports.Decimal = exports.Numeric = exports.Int = exports.Bool = exports.Unit = exports.lookupTemplate = exports.templateIdWithPackageId = exports.registerTemplate = void 0;
exports.assembleTemplate = assembleTemplate;
exports.assembleInterface = assembleInterface;
exports.memo = memo;
exports.lazyMemo = lazyMemo;
// Copyright (c) 2024 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
var jtv = __importStar(require("@mojotech/json-type-validation"));
var lodash_1 = __importDefault(require("lodash"));
var InterfaceBrand = Symbol();
var FromTemplateBrand = Symbol();
function toInterfaceMixin() {
return {
toInterface: function (_, cid) {
return cid;
},
unsafeFromInterface: function (_, cid) {
return cid;
},
};
}
/**
* @internal
*/
function assembleTemplate(template) {
var _interfaces = []; // eslint-disable-line @typescript-eslint/no-unused-vars
for (var _i = 1 // eslint-disable-line @typescript-eslint/no-unused-vars
; _i < arguments.length // eslint-disable-line @typescript-eslint/no-unused-vars
; _i++ // eslint-disable-line @typescript-eslint/no-unused-vars
) {
_interfaces[_i - 1] = arguments[_i]; // eslint-disable-line @typescript-eslint/no-unused-vars
}
return __assign(__assign({}, toInterfaceMixin()), template);
}
/**
* @internal
*/
function assembleInterface(templateId, decoderSource, choices) {
return __assign({ templateId: templateId, sdkVersion: "2.10.3",
// `Interface<I> &` is a phantom intersection
decoder: lazyMemo(function () { return decoderSource().decoder; }), keyDecoder: jtv.succeed(undefined) }, choices);
}
/**
* @internal
*/
var registeredTemplates = {};
/**
* @internal
*/
var registerTemplate = function (template, packageSpecifiers) {
if (packageSpecifiers === void 0) { packageSpecifiers = []; }
var aliases = packageSpecifiers.map((0, exports.templateIdWithPackageId)(template));
new Set([template.templateId].concat(aliases)).forEach(function (templateId) {
if (templateId in registeredTemplates) {
console.warn("Trying to re-register template ".concat(templateId, "."));
}
else {
registeredTemplates[templateId] = template;
console.debug("Registered template ".concat(templateId, "."));
}
});
};
exports.registerTemplate = registerTemplate;
/**
* @internal
*/
var templateIdWithPackageId = function (t) {
return function (pkgId) {
return [pkgId].concat(t.templateId.split(":").slice(1)).join(":");
};
};
exports.templateIdWithPackageId = templateIdWithPackageId;
/**
* @internal
*/
var lookupTemplate = function (templateId) {
var template = registeredTemplates[templateId];
if (template === undefined) {
throw Error("Failed to look up template ".concat(templateId, ". Make sure your @daml/types version agrees with the used Daml SDK version."));
}
return template;
};
exports.lookupTemplate = lookupTemplate;
/**
* @internal Turn a thunk into a memoized version of itself. The memoized thunk
* invokes the original thunk only on its first invocation and caches the result
* for later uses. We use this to implement a version of `jtv.lazy` with
* memoization.
*/
function memo(thunk) {
var memoized = function () {
var cache = thunk();
memoized = function () { return cache; };
return cache;
};
// NOTE(MH): Since we change `memoized` when the resultung thunk is invoked
// for the first time, we need to return it "by reference". Thus, we return
// a closure which contains a reference to `memoized`.
return function () { return memoized(); };
}
/**
* @internal Variation of `jtv.lazy` which memoizes the computed decoder on its
* first invocation.
*/
function lazyMemo(mkDecoder) {
return jtv.lazy(memo(mkDecoder));
}
/**
* Companion object of the [[Unit]] type.
*/
exports.Unit = {
decoder: jtv.object({}),
encode: function (t) { return t; },
};
/**
* Companion object of the [[Bool]] type.
*/
exports.Bool = {
decoder: jtv.boolean(),
encode: function (b) { return b; },
};
/**
* Companion object of the [[Int]] type.
*/
exports.Int = {
decoder: jtv.string(),
encode: function (i) { return i; },
};
/**
* Companion function of the [[Numeric]] type.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
var Numeric = function (_) { return ({
decoder: jtv.string(),
encode: function (n) { return n; },
}); };
exports.Numeric = Numeric;
/**
* Companion object of the [[Decimal]] type.
*/
exports.Decimal = (0, exports.Numeric)(10);
/**
* Companion object of the [[Text]] type.
*/
exports.Text = {
decoder: jtv.string(),
encode: function (t) { return t; },
};
/**
* Companion object of the [[Time]] type.
*/
exports.Time = {
decoder: jtv.string(),
encode: function (t) { return t; },
};
/**
* Companion object of the [[Party]] type.
*/
exports.Party = {
decoder: jtv.string(),
encode: function (p) { return p; },
};
/**
* Companion object of the [[List]] type.
*/
var List = function (t) { return ({
decoder: jtv.array(t.decoder),
encode: function (l) { return l.map(function (element) { return t.encode(element); }); },
}); };
exports.List = List;
/**
* Companion object of the [[Date]] type.
*/
exports.Date = {
decoder: jtv.string(),
encode: function (d) { return d; },
};
/**
* Used to `brand` [[ContractId]].
*/
var ContractIdBrand = Symbol();
/**
* Companion object of the [[ContractId]] type.
*/
var ContractId = function (_t) { return ({
decoder: jtv.string(),
encode: function (c) { return c; },
}); };
exports.ContractId = ContractId;
/**
* This class does the actual work behind the [[Optional]] companion function. In addition to
* implementing the [[Serializable]] interface it also stores the [[Serializable]] instance of the
* payload of the [[Optional]] and uses it to provide a decoder for the [[OptionalInner]] type.
*
* @typeparam T The type of the optionally present value.
*/
var OptionalWorker = /** @class */ (function () {
function OptionalWorker(payload) {
if (payload instanceof OptionalWorker) {
var payloadInnerDecoder = payload.innerDecoder;
this.innerDecoder = jtv.oneOf(jtv.constant([]), jtv.tuple([payloadInnerDecoder]));
this.encode = function (o) {
if (o === null) {
// Top-level enclosing Optional where the type argument is also
// Optional and we represent None.
return null;
}
else {
// The current type is Optional<Optional<...>> and the current value
// is Some x. Therefore the nested value is represented as [] for
// x = None or as [y] for x = Some y. In both cases mapping the
// encoder of the type parameter does the right thing.
return o.map(function (nested) { return payload.encode(nested); });
}
};
}
else {
// NOTE(MH): `T` is not of the form `Optional<U>` here and hence `null`
// does not extend `T`. Thus, `OptionalInner<T> = T`.
this.innerDecoder = payload.decoder;
this.encode = function (o) {
if (o === null) {
// This branch is only reached if we are at the top-level and the
// entire type is a non-nested Optional, i.e. Optional<U> where U is
// not Optional. Recursive calls from the other branch would stop
// before reaching this case, as nested None are empty lists and
// never null.
return null;
}
else {
return payload.encode(o);
}
};
}
this.decoder = jtv
.optional(jtv.oneOf(jtv.constant(null), this.innerDecoder))
.map(function (x) { return (x === undefined ? null : x); });
}
return OptionalWorker;
}());
/**
* Companion function of the [[Optional]] type.
*/
var Optional = function (t) {
return new OptionalWorker(t);
};
exports.Optional = Optional;
/**
* Companion object of the [[TextMap]] type.
*/
var TextMap = function (t) { return ({
decoder: jtv.dict(t.decoder),
encode: function (tm) {
var out = {};
Object.keys(tm).forEach(function (k) {
out[k] = t.encode(tm[k]);
});
return out;
},
}); };
exports.TextMap = TextMap;
function it(arr) {
var i;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
i = 0;
_a.label = 1;
case 1:
if (!(i < arr.length)) return [3 /*break*/, 4];
return [4 /*yield*/, lodash_1.default.cloneDeep(arr[i])];
case 2:
_a.sent();
_a.label = 3;
case 3:
i++;
return [3 /*break*/, 1];
case 4: return [2 /*return*/, undefined];
}
});
}
// This code assumes that the decoder is only ever used in decoding values
// straight from the API responses, and said raw responses are never reused
// afterwards. This should be enforced by this class not being exported and the
// daml-ledger module not letting raw JSON responses escape without going
// through this.
//
// Without that assumption, the constructor would need to deep-copy its kvs
// argument.
var MapImpl = /** @class */ (function () {
function MapImpl(kvs) {
// sorting done so that generic object deep comparison would find equal
// maps equal (as defined by jest's expect().toEqual())
this._kvs = lodash_1.default.sortBy(kvs, function (kv) { return JSON.stringify(kv[0]); });
this._keys = this._kvs.map(function (e) { return e[0]; });
this._values = this._kvs.map(function (e) { return e[1]; });
}
MapImpl.prototype._idx = function (k) {
return this._keys.findIndex(function (l) { return lodash_1.default.isEqual(k, l); });
};
MapImpl.prototype.has = function (k) {
return this._idx(k) !== -1;
};
MapImpl.prototype.get = function (k) {
return lodash_1.default.cloneDeep(this._values[this._idx(k)]);
};
MapImpl.prototype.set = function (k, v) {
if (this.has(k)) {
var cpy = this._kvs.slice();
cpy[this._idx(k)] = lodash_1.default.cloneDeep([k, v]);
return new MapImpl(cpy);
}
else {
var head = lodash_1.default.cloneDeep([[k, v]]);
return new MapImpl(head.concat(this._kvs));
}
};
MapImpl.prototype.delete = function (k) {
var i = this._idx(k);
if (i !== -1) {
return new MapImpl(this._kvs.slice(0, i).concat(this._kvs.slice(i + 1)));
}
else {
return this;
}
};
MapImpl.prototype.keys = function () {
return it(this._keys);
};
MapImpl.prototype.values = function () {
return it(this._values);
};
MapImpl.prototype.entries = function () {
return it(this._kvs);
};
MapImpl.prototype.entriesArray = function () {
return lodash_1.default.cloneDeep(this._kvs);
};
MapImpl.prototype.forEach = function (f, u) {
var g = u ? f.bind(u) : f;
for (var _i = 0, _a = this._kvs; _i < _a.length; _i++) {
var _b = _a[_i], k = _b[0], v = _b[1];
g(v, k, this);
}
};
return MapImpl;
}());
var emptyMap = function () { return new MapImpl([]); };
exports.emptyMap = emptyMap;
/**
* Companion function of the [[GenMap]] type.
*/
var Map = function (kd, vd) { return ({
decoder: jtv
.array(jtv.tuple([kd.decoder, vd.decoder]))
.map(function (kvs) { return new MapImpl(kvs); }),
encode: function (m) {
return m.entriesArray().map(function (e) { return [kd.encode(e[0]), vd.encode(e[1])]; });
},
}); };
exports.Map = Map;
//# sourceMappingURL=index.js.map