diff --git a/README.md b/README.md index 53f9e6375..feeb4fa40 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ [![npm](https://img.shields.io/badge/npm-1.0.0%E2%80%93beta.16-blue.svg)](https://www.npmjs.com/package/@jcubic/lips) ![1.0.0 Complete](https://img.shields.io/github/milestones/progress-percent/jcubic/lips/1?label=1.0.0%20Complete) [![Build and test](https://github.com/jcubic/lips/actions/workflows/build.yaml/badge.svg?branch=devel&event=push)](https://github.com/jcubic/lips/actions/workflows/build.yaml) -[![Coverage Status](https://coveralls.io/repos/github/jcubic/lips/badge.svg?branch=devel&96a495af5daf6e4d457fdf676ebdc1ba)](https://coveralls.io/github/jcubic/lips?branch=devel) +[![Coverage Status](https://coveralls.io/repos/github/jcubic/lips/badge.svg?branch=devel&27bf4fb65e05b7570ad966f858c29bcc)](https://coveralls.io/github/jcubic/lips?branch=devel) [![Join Gitter Chat](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/jcubic/lips) ![NPM Download Count](https://img.shields.io/npm/dm/@jcubic/lips) ![JSDelivr Download count](https://img.shields.io/jsdelivr/npm/hm/@jcubic/lips) diff --git a/dist/lips.js b/dist/lips.js index 89dc6e9bf..8d0573593 100644 --- a/dist/lips.js +++ b/dist/lips.js @@ -31,7 +31,7 @@ * Copyright (c) 2014-present, Facebook, Inc. * released under MIT license * - * build: Wed, 06 Sep 2023 20:32:14 +0000 + * build: Fri, 10 Nov 2023 16:25:41 +0000 */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : @@ -1439,7 +1439,7 @@ * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ - Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; @@ -1449,7 +1449,7 @@ kMaxLength(); function kMaxLength () { - return Buffer.TYPED_ARRAY_SUPPORT + return Buffer$1.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } @@ -1458,14 +1458,14 @@ if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } - if (Buffer.TYPED_ARRAY_SUPPORT) { + if (Buffer$1.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length); - that.__proto__ = Buffer.prototype; + that.__proto__ = Buffer$1.prototype; } else { // Fallback: Return an object instance of the Buffer class if (that === null) { - that = new Buffer(length); + that = new Buffer$1(length); } that.length = length; } @@ -1483,9 +1483,9 @@ * The `Uint8Array` prototype remains unmodified. */ - function Buffer (arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length) + function Buffer$1 (arg, encodingOrOffset, length) { + if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { + return new Buffer$1(arg, encodingOrOffset, length) } // Common case. @@ -1500,11 +1500,11 @@ return from(this, arg, encodingOrOffset, length) } - Buffer.poolSize = 8192; // not used by this implementation + Buffer$1.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype; + Buffer$1._augment = function (arr) { + arr.__proto__ = Buffer$1.prototype; return arr }; @@ -1532,13 +1532,13 @@ * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ - Buffer.from = function (value, encodingOrOffset, length) { + Buffer$1.from = function (value, encodingOrOffset, length) { return from(null, value, encodingOrOffset, length) }; - if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype; - Buffer.__proto__ = Uint8Array; + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + Buffer$1.prototype.__proto__ = Uint8Array.prototype; + Buffer$1.__proto__ = Uint8Array; } function assertSize (size) { @@ -1569,14 +1569,14 @@ * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ - Buffer.alloc = function (size, fill, encoding) { + Buffer$1.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) }; function allocUnsafe (that, size) { assertSize(size); that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer.TYPED_ARRAY_SUPPORT) { + if (!Buffer$1.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0; } @@ -1587,13 +1587,13 @@ /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ - Buffer.allocUnsafe = function (size) { + Buffer$1.allocUnsafe = function (size) { return allocUnsafe(null, size) }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - Buffer.allocUnsafeSlow = function (size) { + Buffer$1.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) }; @@ -1602,7 +1602,7 @@ encoding = 'utf8'; } - if (!Buffer.isEncoding(encoding)) { + if (!Buffer$1.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } @@ -1649,10 +1649,10 @@ array = new Uint8Array(array, byteOffset, length); } - if (Buffer.TYPED_ARRAY_SUPPORT) { + if (Buffer$1.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array; - that.__proto__ = Buffer.prototype; + that.__proto__ = Buffer$1.prototype; } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array); @@ -1699,12 +1699,12 @@ } return length | 0 } - Buffer.isBuffer = isBuffer; + Buffer$1.isBuffer = isBuffer; function internalIsBuffer (b) { return !!(b != null && b._isBuffer) } - Buffer.compare = function compare (a, b) { + Buffer$1.compare = function compare (a, b) { if (!internalIsBuffer(a) || !internalIsBuffer(b)) { throw new TypeError('Arguments must be Buffers') } @@ -1727,7 +1727,7 @@ return 0 }; - Buffer.isEncoding = function isEncoding (encoding) { + Buffer$1.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': @@ -1746,13 +1746,13 @@ } }; - Buffer.concat = function concat (list, length) { + Buffer$1.concat = function concat (list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { - return Buffer.alloc(0) + return Buffer$1.alloc(0) } var i; @@ -1763,7 +1763,7 @@ } } - var buffer = Buffer.allocUnsafe(length); + var buffer = Buffer$1.allocUnsafe(length); var pos = 0; for (i = 0; i < list.length; ++i) { var buf = list[i]; @@ -1819,7 +1819,7 @@ } } } - Buffer.byteLength = byteLength; + Buffer$1.byteLength = byteLength; function slowToString (encoding, start, end) { var loweredCase = false; @@ -1893,7 +1893,7 @@ // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. - Buffer.prototype._isBuffer = true; + Buffer$1.prototype._isBuffer = true; function swap (b, n, m) { var i = b[n]; @@ -1901,7 +1901,7 @@ b[m] = i; } - Buffer.prototype.swap16 = function swap16 () { + Buffer$1.prototype.swap16 = function swap16 () { var len = this.length; if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') @@ -1912,7 +1912,7 @@ return this }; - Buffer.prototype.swap32 = function swap32 () { + Buffer$1.prototype.swap32 = function swap32 () { var len = this.length; if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') @@ -1924,7 +1924,7 @@ return this }; - Buffer.prototype.swap64 = function swap64 () { + Buffer$1.prototype.swap64 = function swap64 () { var len = this.length; if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') @@ -1938,20 +1938,20 @@ return this }; - Buffer.prototype.toString = function toString () { + Buffer$1.prototype.toString = function toString () { var length = this.length | 0; if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) }; - Buffer.prototype.equals = function equals (b) { + Buffer$1.prototype.equals = function equals (b) { if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true - return Buffer.compare(this, b) === 0 + return Buffer$1.compare(this, b) === 0 }; - Buffer.prototype.inspect = function inspect () { + Buffer$1.prototype.inspect = function inspect () { var str = ''; var max = INSPECT_MAX_BYTES; if (this.length > 0) { @@ -1961,7 +1961,7 @@ return '' }; - Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!internalIsBuffer(target)) { throw new TypeError('Argument must be a Buffer') } @@ -2060,7 +2060,7 @@ // Normalize val if (typeof val === 'string') { - val = Buffer.from(val, encoding); + val = Buffer$1.from(val, encoding); } // Finally, search either indexOf (if dir is true) or lastIndexOf @@ -2072,7 +2072,7 @@ return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer.TYPED_ARRAY_SUPPORT && + if (Buffer$1.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) @@ -2142,15 +2142,15 @@ return -1 } - Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 }; - Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) }; - Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) }; @@ -2201,7 +2201,7 @@ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } - Buffer.prototype.write = function write (string, offset, length, encoding) { + Buffer$1.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8'; @@ -2273,7 +2273,7 @@ } }; - Buffer.prototype.toJSON = function toJSON () { + Buffer$1.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) @@ -2426,7 +2426,7 @@ return res } - Buffer.prototype.slice = function slice (start, end) { + Buffer$1.prototype.slice = function slice (start, end) { var len = this.length; start = ~~start; end = end === undefined ? len : ~~end; @@ -2448,12 +2448,12 @@ if (end < start) end = start; var newBuf; - if (Buffer.TYPED_ARRAY_SUPPORT) { + if (Buffer$1.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer.prototype; + newBuf.__proto__ = Buffer$1.prototype; } else { var sliceLen = end - start; - newBuf = new Buffer(sliceLen, undefined); + newBuf = new Buffer$1(sliceLen, undefined); for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start]; } @@ -2470,7 +2470,7 @@ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } - Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2485,7 +2485,7 @@ return val }; - Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) { @@ -2501,22 +2501,22 @@ return val }; - Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); return this[offset] }; - Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return this[offset] | (this[offset + 1] << 8) }; - Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); return (this[offset] << 8) | this[offset + 1] }; - Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return ((this[offset]) | @@ -2525,7 +2525,7 @@ (this[offset + 3] * 0x1000000) }; - Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] * 0x1000000) + @@ -2534,7 +2534,7 @@ this[offset + 3]) }; - Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2552,7 +2552,7 @@ return val }; - Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0; byteLength = byteLength | 0; if (!noAssert) checkOffset(offset, byteLength, this.length); @@ -2570,25 +2570,25 @@ return val }; - Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length); if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) }; - Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset] | (this[offset + 1] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length); var val = this[offset + 1] | (this[offset] << 8); return (val & 0x8000) ? val | 0xFFFF0000 : val }; - Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset]) | @@ -2597,7 +2597,7 @@ (this[offset + 3] << 24) }; - Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return (this[offset] << 24) | @@ -2606,22 +2606,22 @@ (this[offset + 3]) }; - Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read$1(this, offset, true, 23, 4) }; - Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length); return read$1(this, offset, false, 23, 4) }; - Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read$1(this, offset, true, 52, 8) }; - Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length); return read$1(this, offset, false, 52, 8) }; @@ -2632,7 +2632,7 @@ if (offset + ext > buf.length) throw new RangeError('Index out of range') } - Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2651,7 +2651,7 @@ return offset + byteLength }; - Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; byteLength = byteLength | 0; @@ -2670,11 +2670,11 @@ return offset + byteLength }; - Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); this[offset] = (value & 0xff); return offset + 1 }; @@ -2687,11 +2687,11 @@ } } - Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer.TYPED_ARRAY_SUPPORT) { + if (Buffer$1.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2700,11 +2700,11 @@ return offset + 2 }; - Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer.TYPED_ARRAY_SUPPORT) { + if (Buffer$1.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2720,11 +2720,11 @@ } } - Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer.TYPED_ARRAY_SUPPORT) { + if (Buffer$1.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24); this[offset + 2] = (value >>> 16); this[offset + 1] = (value >>> 8); @@ -2735,11 +2735,11 @@ return offset + 4 }; - Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer.TYPED_ARRAY_SUPPORT) { + if (Buffer$1.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2750,7 +2750,7 @@ return offset + 4 }; - Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2773,7 +2773,7 @@ return offset + byteLength }; - Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value; offset = offset | 0; if (!noAssert) { @@ -2796,21 +2796,21 @@ return offset + byteLength }; - Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); if (value < 0) value = 0xff + value + 1; this[offset] = (value & 0xff); return offset + 1 }; - Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer.TYPED_ARRAY_SUPPORT) { + if (Buffer$1.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); } else { @@ -2819,11 +2819,11 @@ return offset + 2 }; - Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer.TYPED_ARRAY_SUPPORT) { + if (Buffer$1.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8); this[offset + 1] = (value & 0xff); } else { @@ -2832,11 +2832,11 @@ return offset + 2 }; - Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer.TYPED_ARRAY_SUPPORT) { + if (Buffer$1.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff); this[offset + 1] = (value >>> 8); this[offset + 2] = (value >>> 16); @@ -2847,12 +2847,12 @@ return offset + 4 }; - Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value; offset = offset | 0; if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); if (value < 0) value = 0xffffffff + value + 1; - if (Buffer.TYPED_ARRAY_SUPPORT) { + if (Buffer$1.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24); this[offset + 1] = (value >>> 16); this[offset + 2] = (value >>> 8); @@ -2876,11 +2876,11 @@ return offset + 4 } - Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) }; - Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) }; @@ -2892,16 +2892,16 @@ return offset + 8 } - Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) }; - Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer.prototype.copy = function copy (target, targetStart, start, end) { + Buffer$1.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0; if (!end && end !== 0) end = this.length; if (targetStart >= target.length) targetStart = target.length; @@ -2933,7 +2933,7 @@ for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start]; } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start]; @@ -2953,7 +2953,7 @@ // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) - Buffer.prototype.fill = function fill (val, start, end, encoding) { + Buffer$1.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { @@ -2973,7 +2973,7 @@ if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { @@ -3002,7 +3002,7 @@ } else { var bytes = internalIsBuffer(val) ? val - : utf8ToBytes(new Buffer(val, encoding).toString()); + : utf8ToBytes(new Buffer$1(val, encoding).toString()); var len = bytes.length; for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len]; @@ -3178,1501 +3178,2296 @@ return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) } - let decoder; - try { - decoder = new TextDecoder(); - } catch(error) {} - let src; - let srcEnd; - let position$1 = 0; - const RECORD_TAG_ID = 0x69; - const STOP_CODE = {}; - let currentDecoder = {}; - let currentStructures; - let srcString; - let srcStringStart = 0; - let srcStringEnd = 0; - let referenceMap; - let currentExtensions = []; - let dataView; - let restoreMapsAsObject; - let defaultOptions = { - useRecords: false, - mapsAsObjects: true - }; - let sequentialMode = false; - - class Decoder { - constructor(options) { - if (options) { - if (options.useRecords === false && options.mapsAsObjects === undefined) - options.mapsAsObjects = true; - if (options.getStructures && !options.structures) - (options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures - } - Object.assign(this, options); - } - decode(source, end) { - if (src) { - // re-entrant execution, save the state and restore it after we do this decode - return saveState(() => { - clearSource(); - return this ? this.decode(source, end) : Decoder.prototype.decode.call(defaultOptions, source, end) - }) - } - srcEnd = end > -1 ? end : source.length; - position$1 = 0; - srcStringEnd = 0; - srcString = null; - src = source; - // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend - // technique for getting data from a database where it can be copied into an existing buffer instead of creating - // new ones - dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength)); - if (this) { - currentDecoder = this; - if (this.structures) { - currentStructures = this.structures; - return checkedRead() - } else if (!currentStructures || currentStructures.length > 0) { - currentStructures = []; - } - } else { - currentDecoder = defaultOptions; - if (!currentStructures || currentStructures.length > 0) - currentStructures = []; - } - return checkedRead() - } - decodeMultiple(source, forEach) { - let values, lastPosition = 0; - try { - let size = source.length; - sequentialMode = true; - let value = this ? this.decode(source, size) : defaultDecoder.decode(source, size); - if (forEach) { - forEach(value); - while(position$1 < size) { - lastPosition = position$1; - if (forEach(checkedRead()) === false) { - return - } - } - } - else { - values = [ value ]; - while(position$1 < size) { - lastPosition = position$1; - values.push(checkedRead()); - } - return values - } - } catch(error) { - error.lastPosition = lastPosition; - error.values = values; - throw error - } finally { - sequentialMode = false; - clearSource(); - } - } - } - function checkedRead() { - try { - let result = read(); - if (position$1 == srcEnd) { - // finished reading this source, cleanup references - currentStructures = null; - src = null; - if (referenceMap) - referenceMap = null; - } else if (position$1 > srcEnd) { - // over read - let error = new Error('Unexpected end of CBOR data'); - error.incomplete = true; - throw error - } else if (!sequentialMode) { - throw new Error('Data read, but end of buffer not reached') - } - // else more to read, but we are reading sequentially, so don't clear source yet - return result - } catch(error) { - clearSource(); - if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer')) { - error.incomplete = true; - } - throw error - } - } - - function read() { - let token = src[position$1++]; - let majorType = token >> 5; - token = token & 0x1f; - if (token > 0x17) { - switch (token) { - case 0x18: - token = src[position$1++]; - break - case 0x19: - if (majorType == 7) { - return getFloat16() - } - token = dataView.getUint16(position$1); - position$1 += 2; - break - case 0x1a: - if (majorType == 7) { - let value = dataView.getFloat32(position$1); - if (currentDecoder.useFloat32 > 2) { - // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved - let multiplier = mult10[((src[position$1] & 0x7f) << 1) | (src[position$1 + 1] >> 7)]; - position$1 += 4; - return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier - } - position$1 += 4; - return value - } - token = dataView.getUint32(position$1); - position$1 += 4; - break - case 0x1b: - if (majorType == 7) { - let value = dataView.getFloat64(position$1); - position$1 += 8; - return value - } - if (currentDecoder.uint64AsNumber) - return src[position$1++] * 0x100000000000000 + src[position$1++] * 0x1000000000000 + src[position$1++] * 0x10000000000 + src[position$1++] * 0x100000000 + - src[position$1++] * 0x1000000 + (src[position$1++] << 16) + (src[position$1++] << 8) + src[position$1++] - token = dataView.getBigUint64(position$1); - position$1 += 8; - break - case 0x1f: - // indefinite length - switch(majorType) { - case 2: // byte string - case 3: // text string - case 4: // array - let array = []; - let value, i = 0; - while ((value = read()) != STOP_CODE) { - array[i++] = value; - } - return majorType == 4 ? array : majorType == 3 ? array.join('') : Buffer.concat(array) - case 5: // map - let key; - if (currentDecoder.mapsAsObjects) { - let object = {}; - while ((key = readKey()) != STOP_CODE) - object[key] = read(); - return object - } else { - if (restoreMapsAsObject) { - currentDecoder.mapsAsObjects = true; - restoreMapsAsObject = false; - } - let map = new Map(); - while ((key = read()) != STOP_CODE) - map.set(key, read()); - return map - } - case 7: - return STOP_CODE - default: - throw new Error('Invalid major type for indefinite length ' + majorType) - } - default: - throw new Error('Unknown token ' + token) - } - } - switch (majorType) { - case 0: // positive int - return token - case 1: // negative int - return ~token - case 2: // buffer - return readBin(token) - case 3: // string - if (srcStringEnd >= position$1) { - return srcString.slice(position$1 - srcStringStart, (position$1 += token) - srcStringStart) - } - if (srcStringEnd == 0 && srcEnd < 140 && token < 32) { - // for small blocks, avoiding the overhead of the extract call is helpful - let string = token < 16 ? shortStringInJS(token) : longStringInJS(token); - if (string != null) - return string - } - return readFixedString(token) - case 4: // array - let array = new Array(token); - for (let i = 0; i < token; i++) { - array[i] = read(); - } - return array - case 5: // map - if (currentDecoder.mapsAsObjects) { - let object = {}; - for (let i = 0; i < token; i++) { - object[readKey()] = read(); - } - return object - } else { - if (restoreMapsAsObject) { - currentDecoder.mapsAsObjects = true; - restoreMapsAsObject = false; - } - let map = new Map(); - for (let i = 0; i < token; i++) { - map.set(read(), read()); - } - return map - } - case 6: // extension - if ((token >> 8) == RECORD_TAG_ID) { // record structures - let structure = currentStructures[token & 0xff]; - if (structure) { - if (!structure.read) - structure.read = createStructureReader(structure); - return structure.read() - } else if (currentDecoder.getStructures) { - let updatedStructures = saveState(() => { - // save the state in case getStructures modifies our buffer - src = null; - return currentDecoder.getStructures() - }); - if (currentStructures === true) - currentDecoder.structures = currentStructures = updatedStructures; - else - currentStructures.splice.apply(currentStructures, [0, updatedStructures.length].concat(updatedStructures)); - structure = currentStructures[token & 0xff]; - if (structure) { - if (!structure.read) - structure.read = createStructureReader(structure); - return structure.read() - } else - return token - } else - return token - } else { - let extension = currentExtensions[token]; - if (extension) { - if (extension.handlesRead) - return extension(read) - else - return extension(read()) - } - else - return new Tag(read()) - } - case 7: // fixed value - switch (token) { - case 0x14: return false - case 0x15: return true - case 0x16: return null - case 0x17: return; // undefined - case 0x1f: - default: - throw new Error('Unknown token ' + token) - } - default: // negative int - if (isNaN(token)) { - let error = new Error('Unexpected end of CBOR data'); - error.incomplete = true; - throw error - } - throw new Error('Unknown CBOR token ' + token) - } - } - const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/; - function createStructureReader(structure) { - let l = structure.length; - function readObject() { - // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function - if (readObject.count++ > 2) { - this.read = (new Function('a', 'r', 'return function(){a();return {' + structure.map(key => validName.test(key) ? key + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '}}'))(readArrayHeader, read); - return this.read() - } - readArrayHeader(); - let object = {}; - for (let i = 0; i < l; i++) { - let key = structure[i]; - object[key] = read(); - } - return object - } - readObject.count = 0; - return readObject - } - - function readArrayHeader(expectedLength) { - // consume the array header, TODO: check expected length - let token = src[position$1++]; - //let majorType = token >> 5 - token = token & 0x1f; - if (token > 0x17) { - switch (token) { - case 0x18: position$1++; - break - case 0x19: position$1 += 2; - break - case 0x1a: position$1 += 4; - } - } - } - - let readFixedString = readStringJS; - function readStringJS(length) { - let result; - if (length < 16) { - if (result = shortStringInJS(length)) - return result - } - if (length > 64 && decoder) - return decoder.decode(src.subarray(position$1, position$1 += length)) - const end = position$1 + length; - const units = []; - result = ''; - while (position$1 < end) { - const byte1 = src[position$1++]; - if ((byte1 & 0x80) === 0) { - // 1 byte - units.push(byte1); - } else if ((byte1 & 0xe0) === 0xc0) { - // 2 bytes - const byte2 = src[position$1++] & 0x3f; - units.push(((byte1 & 0x1f) << 6) | byte2); - } else if ((byte1 & 0xf0) === 0xe0) { - // 3 bytes - const byte2 = src[position$1++] & 0x3f; - const byte3 = src[position$1++] & 0x3f; - units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3); - } else if ((byte1 & 0xf8) === 0xf0) { - // 4 bytes - const byte2 = src[position$1++] & 0x3f; - const byte3 = src[position$1++] & 0x3f; - const byte4 = src[position$1++] & 0x3f; - let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4; - if (unit > 0xffff) { - unit -= 0x10000; - units.push(((unit >>> 10) & 0x3ff) | 0xd800); - unit = 0xdc00 | (unit & 0x3ff); - } - units.push(unit); - } else { - units.push(byte1); - } - - if (units.length >= 0x1000) { - result += fromCharCode.apply(String, units); - units.length = 0; - } - } - - if (units.length > 0) { - result += fromCharCode.apply(String, units); - } - - return result - } - let fromCharCode = String.fromCharCode; - function longStringInJS(length) { - let start = position$1; - let bytes = new Array(length); - for (let i = 0; i < length; i++) { - const byte = src[position$1++]; - if ((byte & 0x80) > 0) { - position$1 = start; - return - } - bytes[i] = byte; - } - return fromCharCode.apply(String, bytes) - } - function shortStringInJS(length) { - if (length < 4) { - if (length < 2) { - if (length === 0) - return '' - else { - let a = src[position$1++]; - if ((a & 0x80) > 1) { - position$1 -= 1; - return - } - return fromCharCode(a) - } - } else { - let a = src[position$1++]; - let b = src[position$1++]; - if ((a & 0x80) > 0 || (b & 0x80) > 0) { - position$1 -= 2; - return - } - if (length < 3) - return fromCharCode(a, b) - let c = src[position$1++]; - if ((c & 0x80) > 0) { - position$1 -= 3; - return - } - return fromCharCode(a, b, c) - } - } else { - let a = src[position$1++]; - let b = src[position$1++]; - let c = src[position$1++]; - let d = src[position$1++]; - if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) { - position$1 -= 4; - return - } - if (length < 6) { - if (length === 4) - return fromCharCode(a, b, c, d) - else { - let e = src[position$1++]; - if ((e & 0x80) > 0) { - position$1 -= 5; - return - } - return fromCharCode(a, b, c, d, e) - } - } else if (length < 8) { - let e = src[position$1++]; - let f = src[position$1++]; - if ((e & 0x80) > 0 || (f & 0x80) > 0) { - position$1 -= 6; - return - } - if (length < 7) - return fromCharCode(a, b, c, d, e, f) - let g = src[position$1++]; - if ((g & 0x80) > 0) { - position$1 -= 7; - return - } - return fromCharCode(a, b, c, d, e, f, g) - } else { - let e = src[position$1++]; - let f = src[position$1++]; - let g = src[position$1++]; - let h = src[position$1++]; - if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) { - position$1 -= 8; - return - } - if (length < 10) { - if (length === 8) - return fromCharCode(a, b, c, d, e, f, g, h) - else { - let i = src[position$1++]; - if ((i & 0x80) > 0) { - position$1 -= 9; - return - } - return fromCharCode(a, b, c, d, e, f, g, h, i) - } - } else if (length < 12) { - let i = src[position$1++]; - let j = src[position$1++]; - if ((i & 0x80) > 0 || (j & 0x80) > 0) { - position$1 -= 10; - return - } - if (length < 11) - return fromCharCode(a, b, c, d, e, f, g, h, i, j) - let k = src[position$1++]; - if ((k & 0x80) > 0) { - position$1 -= 11; - return - } - return fromCharCode(a, b, c, d, e, f, g, h, i, j, k) - } else { - let i = src[position$1++]; - let j = src[position$1++]; - let k = src[position$1++]; - let l = src[position$1++]; - if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) { - position$1 -= 12; - return - } - if (length < 14) { - if (length === 12) - return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l) - else { - let m = src[position$1++]; - if ((m & 0x80) > 0) { - position$1 -= 13; - return - } - return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m) - } - } else { - let m = src[position$1++]; - let n = src[position$1++]; - if ((m & 0x80) > 0 || (n & 0x80) > 0) { - position$1 -= 14; - return - } - if (length < 15) - return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n) - let o = src[position$1++]; - if ((o & 0x80) > 0) { - position$1 -= 15; - return - } - return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) - } - } - } - } - } - - function readBin(length) { - return currentDecoder.copyBuffers ? - // specifically use the copying slice (not the node one) - Uint8Array.prototype.slice.call(src, position$1, position$1 += length) : - src.subarray(position$1, position$1 += length) - } - - function getFloat16() { - let byte0 = src[position$1++]; - let byte1 = src[position$1++]; - let half = (byte0 << 8) + byte1; - let exp = (half >> 10) & 0x1f; - let mant = half & 0x3ff; - let val; - if (exp == 0) val = Math.exp(mant, -24); - else if (exp != 31) val = Math.exp(mant + 1024, exp - 25); - else val = mant == 0 ? Infinity : NaN; - return half & 0x8000 ? -val : val - } - - let keyCache = new Array(4096); - function readKey() { - let length = src[position$1++]; - if (length >= 0x60 && length < 0x78) { - // fixstr, potentially use key cache - length = length - 0x60; - if (srcStringEnd >= position$1) // if it has been extracted, must use it (and faster anyway) - return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart) - else if (!(srcStringEnd == 0 && srcEnd < 180)) - return readFixedString(length) - } else { // not cacheable, go back and do a standard read - position$1--; - return read() - } - let key = ((length << 5) ^ (length > 1 ? dataView.getUint16(position$1) : length > 0 ? src[position$1] : 0)) & 0xfff; - let entry = keyCache[key]; - let checkPosition = position$1; - let end = position$1 + length - 3; - let chunk; - let i = 0; - if (entry && entry.bytes == length) { - while (checkPosition < end) { - chunk = dataView.getUint32(checkPosition); - if (chunk != entry[i++]) { - checkPosition = 0x70000000; - break - } - checkPosition += 4; - } - end += 3; - while (checkPosition < end) { - chunk = src[checkPosition++]; - if (chunk != entry[i++]) { - checkPosition = 0x70000000; - break - } - } - if (checkPosition === end) { - position$1 = checkPosition; - return entry.string - } - end -= 3; - checkPosition = position$1; - } - entry = []; - keyCache[key] = entry; - entry.bytes = length; - while (checkPosition < end) { - chunk = dataView.getUint32(checkPosition); - entry.push(chunk); - checkPosition += 4; - } - end += 3; - while (checkPosition < end) { - chunk = src[checkPosition++]; - entry.push(chunk); - } - // for small blocks, avoiding the overhead of the extract call is helpful - let string = length < 16 ? shortStringInJS(length) : longStringInJS(length); - if (string != null) - return entry.string = string - return entry.string = readFixedString(length) - } - - class Tag { - constructor(value) { - this.value = value; - } - } - - let glbl = typeof window == 'object' ? window : global$1; - - currentExtensions[0] = (dateString) => { - // string date extension - return new Date(dateString) - }; - - currentExtensions[1] = (epochSec) => { - // numeric date extension - return new Date(epochSec * 1000) - }; - - currentExtensions[2] = (buffer) => { - // bigint extension - return new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength).getBigUint64(0) - }; - - currentExtensions[3] = (buffer) => { - // negative bigint extension - return BigInt(-1) - (new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength).getBigUint64(0)) - }; - - // the registration of the record definition extension (tag 105) - const recordDefinition = () => { - let definition = read(); - let structure = definition[0]; - let id = definition[1]; - currentStructures[id & 0xff] = structure; - structure.read = createStructureReader(structure); - let object = {}; - for (let i = 2,l = definition.length; i < l; i++) { - let key = structure[i - 2]; - object[key] = definition[i]; - } - return object - }; - - recordDefinition.handlesRead = true; - currentExtensions[RECORD_TAG_ID] = recordDefinition; - - currentExtensions[27] = (data) => { // http://cbor.schmorp.de/generic-object - return (glbl[data[0]] || Error)(data[1], data[2]) - }; - - currentExtensions[40009] = (id) => { - // id extension (for structured clones) - if (!referenceMap) - referenceMap = new Map(); - let token = src[position$1]; - let target; - // TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read - // ahead past references to record structure definitions - if ((token >> 5) == 4) - target = []; - else - target = {}; - - let refEntry = { target }; // a placeholder object - referenceMap.set(id, refEntry); - let targetProperties = read(); // read the next value as the target object to id - if (refEntry.used) // there is a cycle, so we have to assign properties to original target - return Object.assign(target, targetProperties) - refEntry.target = targetProperties; // the placeholder wasn't used, replace with the deserialized one - return targetProperties // no cycle, can just use the returned read object - }; - - currentExtensions[40010] = (id) => { - // pointer extension (for structured clones) - let refEntry = referenceMap.get(id); - refEntry.used = true; - return refEntry.target - }; - - currentExtensions[258] = (array) => new Set(array); // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md - (currentExtensions[259] = (read) => { - // https://github.com/shanewholloway/js-cbor-codec/blob/master/docs/CBOR-259-spec - // for decoding as a standard Map - if (currentDecoder.mapsAsObjects) { - currentDecoder.mapsAsObjects = false; - restoreMapsAsObject = true; - } - return read() - }).handlesRead = true; - - - const typedArrays = ['Uint8', 'Uint8Clamped', 'Uint16', 'Uint32', 'BigUint64','Int8', 'Int16', 'Int32', 'BigInt64', 'Float32', 'Float64'].map(type => type + 'Array'); - const typedArrayTags = [64, 68, 69, 70, 71, 72, 77, 78, 79, 81, 82]; - for (let i = 0; i < typedArrays.length; i++) { - registerTypedArray(typedArrays[i], typedArrayTags[i]); - } - function registerTypedArray(typedArrayName, tag) { - currentExtensions[tag] = (buffer) => { - if (!typedArrayName) - throw new Error('Could not find typed array for code ' + typeCode) - // we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned - return new glbl[typedArrayName](Uint8Array.prototype.slice.call(buffer, 0).buffer) - }; - } - - function saveState(callback) { - let savedSrcEnd = srcEnd; - let savedPosition = position$1; - let savedSrcStringStart = srcStringStart; - let savedSrcStringEnd = srcStringEnd; - let savedSrcString = srcString; - let savedReferenceMap = referenceMap; - // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow) - let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed - let savedStructures = currentStructures; - let savedDecoder = currentDecoder; - let savedSequentialMode = sequentialMode; - let value = callback(); - srcEnd = savedSrcEnd; - position$1 = savedPosition; - srcStringStart = savedSrcStringStart; - srcStringEnd = savedSrcStringEnd; - srcString = savedSrcString; - referenceMap = savedReferenceMap; - src = savedSrc; - sequentialMode = savedSequentialMode; - currentStructures = savedStructures; - currentDecoder = savedDecoder; - dataView = new DataView(src.buffer, src.byteOffset, src.byteLength); - return value - } - function clearSource() { - src = null; - referenceMap = null; - currentStructures = null; - } - - function addExtension$1(extension) { - currentExtensions[extension.tag] = extension.decode; - } - - let mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding - for (let i = 0; i < 256; i++) { - mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103)); - } - let defaultDecoder = new Decoder({ useRecords: false }); - defaultDecoder.decode; + let decoder; + try { + decoder = new TextDecoder(); + } catch(error) {} + let src; + let srcEnd; + let position$1 = 0; + const LEGACY_RECORD_INLINE_ID = 105; + const RECORD_DEFINITIONS_ID = 0xdffe; + const RECORD_INLINE_ID = 0xdfff; // temporary first-come first-serve tag // proposed tag: 0x7265 // 're' + const BUNDLED_STRINGS_ID = 0xdff9; + const PACKED_REFERENCE_TAG_ID = 6; + const STOP_CODE = {}; + let currentDecoder = {}; + let currentStructures; + let srcString; + let srcStringStart = 0; + let srcStringEnd = 0; + let bundledStrings$1; + let referenceMap; + let currentExtensions = []; + let currentExtensionRanges = []; + let packedValues; + let dataView; + let restoreMapsAsObject; + let defaultOptions = { + useRecords: false, + mapsAsObjects: true + }; + let sequentialMode = false; + let inlineObjectReadThreshold = 2; + // no-eval build + try { + new Function(''); + } catch(error) { + // if eval variants are not supported, do not create inline object readers ever + inlineObjectReadThreshold = Infinity; + } + + + + class Decoder { + constructor(options) { + if (options) { + if ((options.keyMap || options._keyMap) && !options.useRecords) { + options.useRecords = false; + options.mapsAsObjects = true; + } + if (options.useRecords === false && options.mapsAsObjects === undefined) + options.mapsAsObjects = true; + if (options.getStructures) + options.getShared = options.getStructures; + if (options.getShared && !options.structures) + (options.structures = []).uninitialized = true; // this is what we use to denote an uninitialized structures + if (options.keyMap) { + this.mapKey = new Map(); + for (let [k,v] of Object.entries(options.keyMap)) this.mapKey.set(v,k); + } + } + Object.assign(this, options); + } + /* + decodeKey(key) { + return this.keyMap + ? Object.keys(this.keyMap)[Object.values(this.keyMap).indexOf(key)] || key + : key + } + */ + decodeKey(key) { + return this.keyMap ? this.mapKey.get(key) || key : key + } + + encodeKey(key) { + return this.keyMap && this.keyMap.hasOwnProperty(key) ? this.keyMap[key] : key + } + + encodeKeys(rec) { + if (!this._keyMap) return rec + let map = new Map(); + for (let [k,v] of Object.entries(rec)) map.set((this._keyMap.hasOwnProperty(k) ? this._keyMap[k] : k), v); + return map + } + + decodeKeys(map) { + if (!this._keyMap || map.constructor.name != 'Map') return map + if (!this._mapKey) { + this._mapKey = new Map(); + for (let [k,v] of Object.entries(this._keyMap)) this._mapKey.set(v,k); + } + let res = {}; + //map.forEach((v,k) => res[Object.keys(this._keyMap)[Object.values(this._keyMap).indexOf(k)] || k] = v) + map.forEach((v,k) => res[safeKey(this._mapKey.has(k) ? this._mapKey.get(k) : k)] = v); + return res + } + + mapDecode(source, end) { + + let res = this.decode(source); + if (this._keyMap) { + //Experiemntal support for Optimised KeyMap decoding + switch (res.constructor.name) { + case 'Array': return res.map(r => this.decodeKeys(r)) + //case 'Map': return this.decodeKeys(res) + } + } + return res + } + + decode(source, end) { + if (src) { + // re-entrant execution, save the state and restore it after we do this decode + return saveState(() => { + clearSource(); + return this ? this.decode(source, end) : Decoder.prototype.decode.call(defaultOptions, source, end) + }) + } + srcEnd = end > -1 ? end : source.length; + position$1 = 0; + srcStringEnd = 0; + srcString = null; + bundledStrings$1 = null; + src = source; + // this provides cached access to the data view for a buffer if it is getting reused, which is a recommend + // technique for getting data from a database where it can be copied into an existing buffer instead of creating + // new ones + try { + dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength)); + } catch(error) { + // if it doesn't have a buffer, maybe it is the wrong type of object + src = null; + if (source instanceof Uint8Array) + throw error + throw new Error('Source must be a Uint8Array or Buffer but was a ' + ((source && typeof source == 'object') ? source.constructor.name : typeof source)) + } + if (this instanceof Decoder) { + currentDecoder = this; + packedValues = this.sharedValues && + (this.pack ? new Array(this.maxPrivatePackedValues || 16).concat(this.sharedValues) : + this.sharedValues); + if (this.structures) { + currentStructures = this.structures; + return checkedRead() + } else if (!currentStructures || currentStructures.length > 0) { + currentStructures = []; + } + } else { + currentDecoder = defaultOptions; + if (!currentStructures || currentStructures.length > 0) + currentStructures = []; + packedValues = null; + } + return checkedRead() + } + decodeMultiple(source, forEach) { + let values, lastPosition = 0; + try { + let size = source.length; + sequentialMode = true; + let value = this ? this.decode(source, size) : defaultDecoder.decode(source, size); + if (forEach) { + if (forEach(value) === false) { + return + } + while(position$1 < size) { + lastPosition = position$1; + if (forEach(checkedRead()) === false) { + return + } + } + } + else { + values = [ value ]; + while(position$1 < size) { + lastPosition = position$1; + values.push(checkedRead()); + } + return values + } + } catch(error) { + error.lastPosition = lastPosition; + error.values = values; + throw error + } finally { + sequentialMode = false; + clearSource(); + } + } + } + function checkedRead() { + try { + let result = read(); + if (bundledStrings$1) { + if (position$1 >= bundledStrings$1.postBundlePosition) { + let error = new Error('Unexpected bundle position'); + error.incomplete = true; + throw error + } + // bundled strings to skip past + position$1 = bundledStrings$1.postBundlePosition; + bundledStrings$1 = null; + } + + if (position$1 == srcEnd) { + // finished reading this source, cleanup references + currentStructures = null; + src = null; + if (referenceMap) + referenceMap = null; + } else if (position$1 > srcEnd) { + // over read + let error = new Error('Unexpected end of CBOR data'); + error.incomplete = true; + throw error + } else if (!sequentialMode) { + throw new Error('Data read, but end of buffer not reached') + } + // else more to read, but we are reading sequentially, so don't clear source yet + return result + } catch(error) { + clearSource(); + if (error instanceof RangeError || error.message.startsWith('Unexpected end of buffer')) { + error.incomplete = true; + } + throw error + } + } + + function read() { + let token = src[position$1++]; + let majorType = token >> 5; + token = token & 0x1f; + if (token > 0x17) { + switch (token) { + case 0x18: + token = src[position$1++]; + break + case 0x19: + if (majorType == 7) { + return getFloat16() + } + token = dataView.getUint16(position$1); + position$1 += 2; + break + case 0x1a: + if (majorType == 7) { + let value = dataView.getFloat32(position$1); + if (currentDecoder.useFloat32 > 2) { + // this does rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved + let multiplier = mult10[((src[position$1] & 0x7f) << 1) | (src[position$1 + 1] >> 7)]; + position$1 += 4; + return ((multiplier * value + (value > 0 ? 0.5 : -0.5)) >> 0) / multiplier + } + position$1 += 4; + return value + } + token = dataView.getUint32(position$1); + position$1 += 4; + break + case 0x1b: + if (majorType == 7) { + let value = dataView.getFloat64(position$1); + position$1 += 8; + return value + } + if (majorType > 1) { + if (dataView.getUint32(position$1) > 0) + throw new Error('JavaScript does not support arrays, maps, or strings with length over 4294967295') + token = dataView.getUint32(position$1 + 4); + } else if (currentDecoder.int64AsNumber) { + token = dataView.getUint32(position$1) * 0x100000000; + token += dataView.getUint32(position$1 + 4); + } else + token = dataView.getBigUint64(position$1); + position$1 += 8; + break + case 0x1f: + // indefinite length + switch(majorType) { + case 2: // byte string + case 3: // text string + throw new Error('Indefinite length not supported for byte or text strings') + case 4: // array + let array = []; + let value, i = 0; + while ((value = read()) != STOP_CODE) { + array[i++] = value; + } + return majorType == 4 ? array : majorType == 3 ? array.join('') : Buffer$1.concat(array) + case 5: // map + let key; + if (currentDecoder.mapsAsObjects) { + let object = {}; + if (currentDecoder.keyMap) while((key = read()) != STOP_CODE) object[safeKey(currentDecoder.decodeKey(key))] = read(); + else while ((key = read()) != STOP_CODE) object[safeKey(key)] = read(); + return object + } else { + if (restoreMapsAsObject) { + currentDecoder.mapsAsObjects = true; + restoreMapsAsObject = false; + } + let map = new Map(); + if (currentDecoder.keyMap) while((key = read()) != STOP_CODE) map.set(currentDecoder.decodeKey(key), read()); + else while ((key = read()) != STOP_CODE) map.set(key, read()); + return map + } + case 7: + return STOP_CODE + default: + throw new Error('Invalid major type for indefinite length ' + majorType) + } + default: + throw new Error('Unknown token ' + token) + } + } + switch (majorType) { + case 0: // positive int + return token + case 1: // negative int + return ~token + case 2: // buffer + return readBin(token) + case 3: // string + if (srcStringEnd >= position$1) { + return srcString.slice(position$1 - srcStringStart, (position$1 += token) - srcStringStart) + } + if (srcStringEnd == 0 && srcEnd < 140 && token < 32) { + // for small blocks, avoiding the overhead of the extract call is helpful + let string = token < 16 ? shortStringInJS(token) : longStringInJS(token); + if (string != null) + return string + } + return readFixedString(token) + case 4: // array + let array = new Array(token); + //if (currentDecoder.keyMap) for (let i = 0; i < token; i++) array[i] = currentDecoder.decodeKey(read()) + //else + for (let i = 0; i < token; i++) array[i] = read(); + return array + case 5: // map + if (currentDecoder.mapsAsObjects) { + let object = {}; + if (currentDecoder.keyMap) for (let i = 0; i < token; i++) object[safeKey(currentDecoder.decodeKey(read()))] = read(); + else for (let i = 0; i < token; i++) object[safeKey(read())] = read(); + return object + } else { + if (restoreMapsAsObject) { + currentDecoder.mapsAsObjects = true; + restoreMapsAsObject = false; + } + let map = new Map(); + if (currentDecoder.keyMap) for (let i = 0; i < token; i++) map.set(currentDecoder.decodeKey(read()),read()); + else for (let i = 0; i < token; i++) map.set(read(), read()); + return map + } + case 6: // extension + if (token >= BUNDLED_STRINGS_ID) { + let structure = currentStructures[token & 0x1fff]; // check record structures first + // At some point we may provide an option for dynamic tag assignment with a range like token >= 8 && (token < 16 || (token > 0x80 && token < 0xc0) || (token > 0x130 && token < 0x4000)) + if (structure) { + if (!structure.read) structure.read = createStructureReader(structure); + return structure.read() + } + if (token < 0x10000) { + if (token == RECORD_INLINE_ID) { // we do a special check for this so that we can keep the + // currentExtensions as densely stored array (v8 stores arrays densely under about 3000 elements) + let length = readJustLength(); + let id = read(); + let structure = read(); + recordDefinition(id, structure); + let object = {}; + if (currentDecoder.keyMap) for (let i = 2; i < length; i++) { + let key = currentDecoder.decodeKey(structure[i - 2]); + object[safeKey(key)] = read(); + } + else for (let i = 2; i < length; i++) { + let key = structure[i - 2]; + object[safeKey(key)] = read(); + } + return object + } + else if (token == RECORD_DEFINITIONS_ID) { + let length = readJustLength(); + let id = read(); + for (let i = 2; i < length; i++) { + recordDefinition(id++, read()); + } + return read() + } else if (token == BUNDLED_STRINGS_ID) { + return readBundleExt() + } + if (currentDecoder.getShared) { + loadShared(); + structure = currentStructures[token & 0x1fff]; + if (structure) { + if (!structure.read) + structure.read = createStructureReader(structure); + return structure.read() + } + } + } + } + let extension = currentExtensions[token]; + if (extension) { + if (extension.handlesRead) + return extension(read) + else + return extension(read()) + } else { + let input = read(); + for (let i = 0; i < currentExtensionRanges.length; i++) { + let value = currentExtensionRanges[i](token, input); + if (value !== undefined) + return value + } + return new Tag(input, token) + } + case 7: // fixed value + switch (token) { + case 0x14: return false + case 0x15: return true + case 0x16: return null + case 0x17: return; // undefined + case 0x1f: + default: + let packedValue = (packedValues || getPackedValues())[token]; + if (packedValue !== undefined) + return packedValue + throw new Error('Unknown token ' + token) + } + default: // negative int + if (isNaN(token)) { + let error = new Error('Unexpected end of CBOR data'); + error.incomplete = true; + throw error + } + throw new Error('Unknown CBOR token ' + token) + } + } + const validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/; + function createStructureReader(structure) { + function readObject() { + // get the array size from the header + let length = src[position$1++]; + //let majorType = token >> 5 + length = length & 0x1f; + if (length > 0x17) { + switch (length) { + case 0x18: + length = src[position$1++]; + break + case 0x19: + length = dataView.getUint16(position$1); + position$1 += 2; + break + case 0x1a: + length = dataView.getUint32(position$1); + position$1 += 4; + break + default: + throw new Error('Expected array header, but got ' + src[position$1 - 1]) + } + } + // This initial function is quick to instantiate, but runs slower. After several iterations pay the cost to build the faster function + let compiledReader = this.compiledReader; // first look to see if we have the fast compiled function + while(compiledReader) { + // we have a fast compiled object literal reader + if (compiledReader.propertyCount === length) + return compiledReader(read) // with the right length, so we use it + compiledReader = compiledReader.next; // see if there is another reader with the right length + } + if (this.slowReads++ >= inlineObjectReadThreshold) { // create a fast compiled reader + let array = this.length == length ? this : this.slice(0, length); + compiledReader = currentDecoder.keyMap + ? new Function('r', 'return {' + array.map(k => currentDecoder.decodeKey(k)).map(k => validName.test(k) ? safeKey(k) + ':r()' : ('[' + JSON.stringify(k) + ']:r()')).join(',') + '}') + : new Function('r', 'return {' + array.map(key => validName.test(key) ? safeKey(key) + ':r()' : ('[' + JSON.stringify(key) + ']:r()')).join(',') + '}'); + if (this.compiledReader) + compiledReader.next = this.compiledReader; // if there is an existing one, we store multiple readers as a linked list because it is usually pretty rare to have multiple readers (of different length) for the same structure + compiledReader.propertyCount = length; + this.compiledReader = compiledReader; + return compiledReader(read) + } + let object = {}; + if (currentDecoder.keyMap) for (let i = 0; i < length; i++) object[safeKey(currentDecoder.decodeKey(this[i]))] = read(); + else for (let i = 0; i < length; i++) { + object[safeKey(this[i])] = read(); + } + return object + } + structure.slowReads = 0; + return readObject + } + + function safeKey(key) { + return key === '__proto__' ? '__proto_' : key + } + + let readFixedString = readStringJS; + function readStringJS(length) { + let result; + if (length < 16) { + if (result = shortStringInJS(length)) + return result + } + if (length > 64 && decoder) + return decoder.decode(src.subarray(position$1, position$1 += length)) + const end = position$1 + length; + const units = []; + result = ''; + while (position$1 < end) { + const byte1 = src[position$1++]; + if ((byte1 & 0x80) === 0) { + // 1 byte + units.push(byte1); + } else if ((byte1 & 0xe0) === 0xc0) { + // 2 bytes + const byte2 = src[position$1++] & 0x3f; + units.push(((byte1 & 0x1f) << 6) | byte2); + } else if ((byte1 & 0xf0) === 0xe0) { + // 3 bytes + const byte2 = src[position$1++] & 0x3f; + const byte3 = src[position$1++] & 0x3f; + units.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3); + } else if ((byte1 & 0xf8) === 0xf0) { + // 4 bytes + const byte2 = src[position$1++] & 0x3f; + const byte3 = src[position$1++] & 0x3f; + const byte4 = src[position$1++] & 0x3f; + let unit = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4; + if (unit > 0xffff) { + unit -= 0x10000; + units.push(((unit >>> 10) & 0x3ff) | 0xd800); + unit = 0xdc00 | (unit & 0x3ff); + } + units.push(unit); + } else { + units.push(byte1); + } + + if (units.length >= 0x1000) { + result += fromCharCode.apply(String, units); + units.length = 0; + } + } + + if (units.length > 0) { + result += fromCharCode.apply(String, units); + } + + return result + } + let fromCharCode = String.fromCharCode; + function longStringInJS(length) { + let start = position$1; + let bytes = new Array(length); + for (let i = 0; i < length; i++) { + const byte = src[position$1++]; + if ((byte & 0x80) > 0) { + position$1 = start; + return + } + bytes[i] = byte; + } + return fromCharCode.apply(String, bytes) + } + function shortStringInJS(length) { + if (length < 4) { + if (length < 2) { + if (length === 0) + return '' + else { + let a = src[position$1++]; + if ((a & 0x80) > 1) { + position$1 -= 1; + return + } + return fromCharCode(a) + } + } else { + let a = src[position$1++]; + let b = src[position$1++]; + if ((a & 0x80) > 0 || (b & 0x80) > 0) { + position$1 -= 2; + return + } + if (length < 3) + return fromCharCode(a, b) + let c = src[position$1++]; + if ((c & 0x80) > 0) { + position$1 -= 3; + return + } + return fromCharCode(a, b, c) + } + } else { + let a = src[position$1++]; + let b = src[position$1++]; + let c = src[position$1++]; + let d = src[position$1++]; + if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) { + position$1 -= 4; + return + } + if (length < 6) { + if (length === 4) + return fromCharCode(a, b, c, d) + else { + let e = src[position$1++]; + if ((e & 0x80) > 0) { + position$1 -= 5; + return + } + return fromCharCode(a, b, c, d, e) + } + } else if (length < 8) { + let e = src[position$1++]; + let f = src[position$1++]; + if ((e & 0x80) > 0 || (f & 0x80) > 0) { + position$1 -= 6; + return + } + if (length < 7) + return fromCharCode(a, b, c, d, e, f) + let g = src[position$1++]; + if ((g & 0x80) > 0) { + position$1 -= 7; + return + } + return fromCharCode(a, b, c, d, e, f, g) + } else { + let e = src[position$1++]; + let f = src[position$1++]; + let g = src[position$1++]; + let h = src[position$1++]; + if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) { + position$1 -= 8; + return + } + if (length < 10) { + if (length === 8) + return fromCharCode(a, b, c, d, e, f, g, h) + else { + let i = src[position$1++]; + if ((i & 0x80) > 0) { + position$1 -= 9; + return + } + return fromCharCode(a, b, c, d, e, f, g, h, i) + } + } else if (length < 12) { + let i = src[position$1++]; + let j = src[position$1++]; + if ((i & 0x80) > 0 || (j & 0x80) > 0) { + position$1 -= 10; + return + } + if (length < 11) + return fromCharCode(a, b, c, d, e, f, g, h, i, j) + let k = src[position$1++]; + if ((k & 0x80) > 0) { + position$1 -= 11; + return + } + return fromCharCode(a, b, c, d, e, f, g, h, i, j, k) + } else { + let i = src[position$1++]; + let j = src[position$1++]; + let k = src[position$1++]; + let l = src[position$1++]; + if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) { + position$1 -= 12; + return + } + if (length < 14) { + if (length === 12) + return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l) + else { + let m = src[position$1++]; + if ((m & 0x80) > 0) { + position$1 -= 13; + return + } + return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m) + } + } else { + let m = src[position$1++]; + let n = src[position$1++]; + if ((m & 0x80) > 0 || (n & 0x80) > 0) { + position$1 -= 14; + return + } + if (length < 15) + return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n) + let o = src[position$1++]; + if ((o & 0x80) > 0) { + position$1 -= 15; + return + } + return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) + } + } + } + } + } + + function readBin(length) { + return currentDecoder.copyBuffers ? + // specifically use the copying slice (not the node one) + Uint8Array.prototype.slice.call(src, position$1, position$1 += length) : + src.subarray(position$1, position$1 += length) + } + let f32Array = new Float32Array(1); + let u8Array = new Uint8Array(f32Array.buffer, 0, 4); + function getFloat16() { + let byte0 = src[position$1++]; + let byte1 = src[position$1++]; + let exponent = (byte0 & 0x7f) >> 2; + if (exponent === 0x1f) { // specials + if (byte1 || (byte0 & 3)) + return NaN; + return (byte0 & 0x80) ? -Infinity : Infinity; + } + if (exponent === 0) { // sub-normals + // significand with 10 fractional bits and divided by 2^14 + let abs = (((byte0 & 3) << 8) | byte1) / (1 << 24); + return (byte0 & 0x80) ? -abs : abs + } + + u8Array[3] = (byte0 & 0x80) | // sign bit + ((exponent >> 1) + 56); // 4 of 5 of the exponent bits, re-offset-ed + u8Array[2] = ((byte0 & 7) << 5) | // last exponent bit and first two mantissa bits + (byte1 >> 3); // next 5 bits of mantissa + u8Array[1] = byte1 << 5; // last three bits of mantissa + u8Array[0] = 0; + return f32Array[0]; + } + + new Array(4096); + + class Tag { + constructor(value, tag) { + this.value = value; + this.tag = tag; + } + } + + currentExtensions[0] = (dateString) => { + // string date extension + return new Date(dateString) + }; + + currentExtensions[1] = (epochSec) => { + // numeric date extension + return new Date(Math.round(epochSec * 1000)) + }; + + currentExtensions[2] = (buffer) => { + // bigint extension + let value = BigInt(0); + for (let i = 0, l = buffer.byteLength; i < l; i++) { + value = BigInt(buffer[i]) + value << BigInt(8); + } + return value + }; + + currentExtensions[3] = (buffer) => { + // negative bigint extension + return BigInt(-1) - currentExtensions[2](buffer) + }; + currentExtensions[4] = (fraction) => { + // best to reparse to maintain accuracy + return +(fraction[1] + 'e' + fraction[0]) + }; + + currentExtensions[5] = (fraction) => { + // probably not sufficiently accurate + return fraction[1] * Math.exp(fraction[0] * Math.log(2)) + }; + + // the registration of the record definition extension + const recordDefinition = (id, structure) => { + id = id - 0xe000; + let existingStructure = currentStructures[id]; + if (existingStructure && existingStructure.isShared) { + (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure; + } + currentStructures[id] = structure; + + structure.read = createStructureReader(structure); + }; + currentExtensions[LEGACY_RECORD_INLINE_ID] = (data) => { + let length = data.length; + let structure = data[1]; + recordDefinition(data[0], structure); + let object = {}; + for (let i = 2; i < length; i++) { + let key = structure[i - 2]; + object[safeKey(key)] = data[i]; + } + return object + }; + currentExtensions[14] = (value) => { + if (bundledStrings$1) + return bundledStrings$1[0].slice(bundledStrings$1.position0, bundledStrings$1.position0 += value) + return new Tag(value, 14) + }; + currentExtensions[15] = (value) => { + if (bundledStrings$1) + return bundledStrings$1[1].slice(bundledStrings$1.position1, bundledStrings$1.position1 += value) + return new Tag(value, 15) + }; + let glbl = { Error, RegExp }; + currentExtensions[27] = (data) => { // http://cbor.schmorp.de/generic-object + return (glbl[data[0]] || Error)(data[1], data[2]) + }; + const packedTable = (read) => { + if (src[position$1++] != 0x84) + throw new Error('Packed values structure must be followed by a 4 element array') + let newPackedValues = read(); // packed values + packedValues = packedValues ? newPackedValues.concat(packedValues.slice(newPackedValues.length)) : newPackedValues; + packedValues.prefixes = read(); + packedValues.suffixes = read(); + return read() // read the rump + }; + packedTable.handlesRead = true; + currentExtensions[51] = packedTable; + + currentExtensions[PACKED_REFERENCE_TAG_ID] = (data) => { // packed reference + if (!packedValues) { + if (currentDecoder.getShared) + loadShared(); + else + return new Tag(data, PACKED_REFERENCE_TAG_ID) + } + if (typeof data == 'number') + return packedValues[16 + (data >= 0 ? 2 * data : (-2 * data - 1))] + throw new Error('No support for non-integer packed references yet') + }; + + // The following code is an incomplete implementation of http://cbor.schmorp.de/stringref + // the real thing would need to implemennt more logic to populate the stringRefs table and + // maintain a stack of stringRef "namespaces". + // + // currentExtensions[25] = (id) => { + // return stringRefs[id] + // } + // currentExtensions[256] = (read) => { + // stringRefs = [] + // try { + // return read() + // } finally { + // stringRefs = null + // } + // } + // currentExtensions[256].handlesRead = true + + currentExtensions[28] = (read) => { + // shareable http://cbor.schmorp.de/value-sharing (for structured clones) + if (!referenceMap) { + referenceMap = new Map(); + referenceMap.id = 0; + } + let id = referenceMap.id++; + let token = src[position$1]; + let target; + // TODO: handle Maps, Sets, and other types that can cycle; this is complicated, because you potentially need to read + // ahead past references to record structure definitions + if ((token >> 5) == 4) + target = []; + else + target = {}; + + let refEntry = { target }; // a placeholder object + referenceMap.set(id, refEntry); + let targetProperties = read(); // read the next value as the target object to id + if (refEntry.used) // there is a cycle, so we have to assign properties to original target + return Object.assign(target, targetProperties) + refEntry.target = targetProperties; // the placeholder wasn't used, replace with the deserialized one + return targetProperties // no cycle, can just use the returned read object + }; + currentExtensions[28].handlesRead = true; + + currentExtensions[29] = (id) => { + // sharedref http://cbor.schmorp.de/value-sharing (for structured clones) + let refEntry = referenceMap.get(id); + refEntry.used = true; + return refEntry.target + }; + + currentExtensions[258] = (array) => new Set(array); // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md + (currentExtensions[259] = (read) => { + // https://github.com/shanewholloway/js-cbor-codec/blob/master/docs/CBOR-259-spec + // for decoding as a standard Map + if (currentDecoder.mapsAsObjects) { + currentDecoder.mapsAsObjects = false; + restoreMapsAsObject = true; + } + return read() + }).handlesRead = true; + function combine(a, b) { + if (typeof a === 'string') + return a + b + if (a instanceof Array) + return a.concat(b) + return Object.assign({}, a, b) + } + function getPackedValues() { + if (!packedValues) { + if (currentDecoder.getShared) + loadShared(); + else + throw new Error('No packed values available') + } + return packedValues + } + const SHARED_DATA_TAG_ID = 0x53687264; // ascii 'Shrd' + currentExtensionRanges.push((tag, input) => { + if (tag >= 225 && tag <= 255) + return combine(getPackedValues().prefixes[tag - 224], input) + if (tag >= 28704 && tag <= 32767) + return combine(getPackedValues().prefixes[tag - 28672], input) + if (tag >= 1879052288 && tag <= 2147483647) + return combine(getPackedValues().prefixes[tag - 1879048192], input) + if (tag >= 216 && tag <= 223) + return combine(input, getPackedValues().suffixes[tag - 216]) + if (tag >= 27647 && tag <= 28671) + return combine(input, getPackedValues().suffixes[tag - 27639]) + if (tag >= 1811940352 && tag <= 1879048191) + return combine(input, getPackedValues().suffixes[tag - 1811939328]) + if (tag == SHARED_DATA_TAG_ID) {// we do a special check for this so that we can keep the currentExtensions as densely stored array (v8 stores arrays densely under about 3000 elements) + return { + packedValues: packedValues, + structures: currentStructures.slice(0), + version: input, + } + } + if (tag == 55799) // self-descriptive CBOR tag, just return input value + return input + }); + + const isLittleEndianMachine$1 = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1; + const typedArrays = [Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, + typeof BigUint64Array == 'undefined' ? { name:'BigUint64Array' } : BigUint64Array, Int8Array, Int16Array, Int32Array, + typeof BigInt64Array == 'undefined' ? { name:'BigInt64Array' } : BigInt64Array, Float32Array, Float64Array]; + const typedArrayTags = [64, 68, 69, 70, 71, 72, 77, 78, 79, 85, 86]; + for (let i = 0; i < typedArrays.length; i++) { + registerTypedArray(typedArrays[i], typedArrayTags[i]); + } + function registerTypedArray(TypedArray, tag) { + let dvMethod = 'get' + TypedArray.name.slice(0, -5); + let bytesPerElement; + if (typeof TypedArray === 'function') + bytesPerElement = TypedArray.BYTES_PER_ELEMENT; + else + TypedArray = null; + for (let littleEndian = 0; littleEndian < 2; littleEndian++) { + if (!littleEndian && bytesPerElement == 1) + continue + let sizeShift = bytesPerElement == 2 ? 1 : bytesPerElement == 4 ? 2 : 3; + currentExtensions[littleEndian ? tag : (tag - 4)] = (bytesPerElement == 1 || littleEndian == isLittleEndianMachine$1) ? (buffer) => { + if (!TypedArray) + throw new Error('Could not find typed array for code ' + tag) + // we have to always slice/copy here to get a new ArrayBuffer that is word/byte aligned + return new TypedArray(Uint8Array.prototype.slice.call(buffer, 0).buffer) + } : buffer => { + if (!TypedArray) + throw new Error('Could not find typed array for code ' + tag) + let dv = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); + let elements = buffer.length >> sizeShift; + let ta = new TypedArray(elements); + let method = dv[dvMethod]; + for (let i = 0; i < elements; i++) { + ta[i] = method.call(dv, i << sizeShift, littleEndian); + } + return ta + }; + } + } + + function readBundleExt() { + let length = readJustLength(); + let bundlePosition = position$1 + read(); + for (let i = 2; i < length; i++) { + // skip past bundles that were already read + let bundleLength = readJustLength(); // this will increment position, so must add to position afterwards + position$1 += bundleLength; + } + let dataPosition = position$1; + position$1 = bundlePosition; + bundledStrings$1 = [readStringJS(readJustLength()), readStringJS(readJustLength())]; + bundledStrings$1.position0 = 0; + bundledStrings$1.position1 = 0; + bundledStrings$1.postBundlePosition = position$1; + position$1 = dataPosition; + return read() + } + + function readJustLength() { + let token = src[position$1++] & 0x1f; + if (token > 0x17) { + switch (token) { + case 0x18: + token = src[position$1++]; + break + case 0x19: + token = dataView.getUint16(position$1); + position$1 += 2; + break + case 0x1a: + token = dataView.getUint32(position$1); + position$1 += 4; + break + } + } + return token + } + + function loadShared() { + if (currentDecoder.getShared) { + let sharedData = saveState(() => { + // save the state in case getShared modifies our buffer + src = null; + return currentDecoder.getShared() + }) || {}; + let updatedStructures = sharedData.structures || []; + currentDecoder.sharedVersion = sharedData.version; + packedValues = currentDecoder.sharedValues = sharedData.packedValues; + if (currentStructures === true) + currentDecoder.structures = currentStructures = updatedStructures; + else + currentStructures.splice.apply(currentStructures, [0, updatedStructures.length].concat(updatedStructures)); + } + } + + function saveState(callback) { + let savedSrcEnd = srcEnd; + let savedPosition = position$1; + let savedSrcStringStart = srcStringStart; + let savedSrcStringEnd = srcStringEnd; + let savedSrcString = srcString; + let savedReferenceMap = referenceMap; + let savedBundledStrings = bundledStrings$1; + + // TODO: We may need to revisit this if we do more external calls to user code (since it could be slow) + let savedSrc = new Uint8Array(src.slice(0, srcEnd)); // we copy the data in case it changes while external data is processed + let savedStructures = currentStructures; + let savedDecoder = currentDecoder; + let savedSequentialMode = sequentialMode; + let value = callback(); + srcEnd = savedSrcEnd; + position$1 = savedPosition; + srcStringStart = savedSrcStringStart; + srcStringEnd = savedSrcStringEnd; + srcString = savedSrcString; + referenceMap = savedReferenceMap; + bundledStrings$1 = savedBundledStrings; + src = savedSrc; + sequentialMode = savedSequentialMode; + currentStructures = savedStructures; + currentDecoder = savedDecoder; + dataView = new DataView(src.buffer, src.byteOffset, src.byteLength); + return value + } + function clearSource() { + src = null; + referenceMap = null; + currentStructures = null; + } + + function addExtension$1(extension) { + currentExtensions[extension.tag] = extension.decode; + } + + const mult10 = new Array(147); // this is a table matching binary exponents to the multiplier to determine significant digit rounding + for (let i = 0; i < 256; i++) { + mult10[i] = +('1e' + Math.floor(45.15 - i * 0.30103)); + } + let defaultDecoder = new Decoder({ useRecords: false }); + defaultDecoder.decode; defaultDecoder.decodeMultiple; - let textEncoder; - try { - textEncoder = new TextEncoder(); - } catch (error) {} - let extensions, extensionClasses; - const hasNodeBuffer = typeof Buffer !== 'undefined'; - const ByteArrayAllocate = hasNodeBuffer ? Buffer.allocUnsafeSlow : Uint8Array; - const ByteArray = hasNodeBuffer ? Buffer : Uint8Array; - const RECORD_STARTING_ID_PREFIX = 0x69; // tag 105/0x69 - const MAX_STRUCTURES = 0x100; - const MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000; - let target; - let targetView; - let position = 0; - let safeEnd; - const RECORD_SYMBOL = Symbol('record-id'); - class Encoder extends Decoder { - constructor(options) { - super(options); - this.offset = 0; - let start; - let sharedStructures; - let hasSharedUpdate; - let structures; - let referenceMap; - let lastSharedStructuresLength = 0; - let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position, maxBytes) { - return target.utf8Write(string, position, maxBytes) - } : (textEncoder && textEncoder.encodeInto) ? - function(string, position) { - return textEncoder.encodeInto(string, target.subarray(position)).written - } : false; - - let encoder = this; - let maxSharedStructures = 64; - let isSequential = options && options.sequential; - if (isSequential) { - maxSharedStructures = 0; - this.structures = []; - } - let recordIdsToRemove = []; - let transitionsCount = 0; - let serializationsSinceTransitionRebuild = 0; - if (this.structures && this.structures.length > maxSharedStructures) { - throw new Error('Too many shared structures') - } - - this.encode = function(value) { - if (!target) { - target = new ByteArrayAllocate(8192); - targetView = new DataView(target.buffer, 0, 8192); - position = 0; - } - safeEnd = target.length - 10; - if (safeEnd - position < 0x800) { - // don't start too close to the end, - target = new ByteArrayAllocate(target.length); - targetView = new DataView(target.buffer, 0, target.length); - safeEnd = target.length - 10; - position = 0; - } - start = position; - referenceMap = encoder.structuredClone ? new Map() : null; - sharedStructures = encoder.structures; - if (sharedStructures) { - if (sharedStructures.uninitialized) - encoder.structures = sharedStructures = encoder.getStructures(); - let sharedStructuresLength = sharedStructures.length; - if (sharedStructuresLength > maxSharedStructures && !isSequential) - sharedStructuresLength = maxSharedStructures; - if (!sharedStructures.transitions) { - // rebuild our structure transitions - sharedStructures.transitions = Object.create(null); - for (let i = 0; i < sharedStructuresLength; i++) { - let keys = sharedStructures[i]; - if (!keys) - continue - let nextTransition, transition = sharedStructures.transitions; - for (let i =0, l = keys.length; i < l; i++) { - let key = keys[i]; - nextTransition = transition[key]; - if (!nextTransition) { - nextTransition = transition[key] = Object.create(null); - } - transition = nextTransition; - } - transition[RECORD_SYMBOL] = i; - } - lastSharedStructuresLength = sharedStructures.length; - } - if (!isSequential) - sharedStructures.nextId = sharedStructuresLength; - } - if (hasSharedUpdate) - hasSharedUpdate = false; - structures = sharedStructures || []; - try { - encode(value); - encoder.offset = position; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially - if (referenceMap && referenceMap.idsToInsert) { - position += referenceMap.idsToInsert.length * 8; - if (position > safeEnd) - makeRoom(position); - encoder.offset = position; - let serialized = insertIds(target.subarray(start, position), referenceMap.idsToInsert); - referenceMap = null; - return serialized - } - return target.subarray(start, position) // position can change if we call encode again in saveStructures, so we get the buffer now - } finally { - if (sharedStructures) { - if (serializationsSinceTransitionRebuild < 10) - serializationsSinceTransitionRebuild++; - if (transitionsCount > 10000) { - // force a rebuild occasionally after a lot of transitions so it can get cleaned up - sharedStructures.transitions = null; - serializationsSinceTransitionRebuild = 0; - transitionsCount = 0; - if (recordIdsToRemove.length > 0) - recordIdsToRemove = []; - } else if (recordIdsToRemove.length > 0 && !isSequential) { - for (let i = 0, l = recordIdsToRemove.length; i < l; i++) { - recordIdsToRemove[i][RECORD_SYMBOL] = undefined; - } - recordIdsToRemove = []; - } - if (hasSharedUpdate && encoder.saveStructures) { - if (encoder.structures.length > maxSharedStructures) { - encoder.structures = encoder.structures.slice(0, maxSharedStructures); - } - - if (encoder.saveStructures(encoder.structures, lastSharedStructuresLength) === false) { - // get updated structures and try again if the update failed - encoder.structures = encoder.getStructures() || []; - return encoder.encode(value) - } - lastSharedStructuresLength = encoder.structures.length; - } - } - } - }; - const encode = (value) => { - if (position > safeEnd) - target = makeRoom(position); - - var type = typeof value; - var length; - if (type === 'string') { - let strLength = value.length; - let headerSize; - // first we estimate the header size, so we can write to the correct location - if (strLength < 0x20) { - headerSize = 1; - } else if (strLength < 0x100) { - headerSize = 2; - } else if (strLength < 0x10000) { - headerSize = 3; - } else { - headerSize = 5; - } - let maxBytes = strLength * 3; - if (position + maxBytes > safeEnd) - target = makeRoom(position + maxBytes); - - if (strLength < 0x40 || !encodeUtf8) { - let i, c1, c2, strPosition = position + headerSize; - for (i = 0; i < strLength; i++) { - c1 = value.charCodeAt(i); - if (c1 < 0x80) { - target[strPosition++] = c1; - } else if (c1 < 0x800) { - target[strPosition++] = c1 >> 6 | 0xc0; - target[strPosition++] = c1 & 0x3f | 0x80; - } else if ( - (c1 & 0xfc00) === 0xd800 && - ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00 - ) { - c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff); - i++; - target[strPosition++] = c1 >> 18 | 0xf0; - target[strPosition++] = c1 >> 12 & 0x3f | 0x80; - target[strPosition++] = c1 >> 6 & 0x3f | 0x80; - target[strPosition++] = c1 & 0x3f | 0x80; - } else { - target[strPosition++] = c1 >> 12 | 0xe0; - target[strPosition++] = c1 >> 6 & 0x3f | 0x80; - target[strPosition++] = c1 & 0x3f | 0x80; - } - } - length = strPosition - position - headerSize; - } else { - length = encodeUtf8(value, position + headerSize, maxBytes); - } - - if (length < 0x18) { - target[position++] = 0x60 | length; - } else if (length < 0x100) { - if (headerSize < 2) { - target.copyWithin(position + 2, position + 1, position + 1 + length); - } - target[position++] = 0x78; - target[position++] = length; - } else if (length < 0x10000) { - if (headerSize < 3) { - target.copyWithin(position + 3, position + 2, position + 2 + length); - } - target[position++] = 0x79; - target[position++] = length >> 8; - target[position++] = length & 0xff; - } else { - if (headerSize < 5) { - target.copyWithin(position + 5, position + 3, position + 3 + length); - } - target[position++] = 0x7a; - targetView.setUint32(position, length); - position += 4; - } - position += length; - } else if (type === 'number') { - if (value >>> 0 === value) {// positive integer, 32-bit or less - // positive uint - if (value < 0x18) { - target[position++] = value; - } else if (value < 0x100) { - target[position++] = 0x18; - target[position++] = value; - } else if (value < 0x10000) { - target[position++] = 0x19; - target[position++] = value >> 8; - target[position++] = value & 0xff; - } else { - target[position++] = 0x1a; - targetView.setUint32(position, value); - position += 4; - } - } else if (value >> 0 === value) { // negative integer - if (value >= -0x18) { - target[position++] = 0x1f - value; - } else if (value >= -0x100) { - target[position++] = 0x38; - target[position++] = ~value; - } else if (value >= -0x10000) { - target[position++] = 0x39; - targetView.setUint16(position, ~value); - position += 2; - } else { - target[position++] = 0x3a; - targetView.setUint32(position, ~value); - position += 4; - } - } else { - let useFloat32; - if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) { - target[position++] = 0xfa; - targetView.setFloat32(position, value); - let xShifted; - if (useFloat32 < 4 || - // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved - ((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) { - position += 4; - return - } else - position--; // move back into position for writing a double - } - target[position++] = 0xfb; - targetView.setFloat64(position, value); - position += 8; - } - } else if (type === 'object') { - if (!value) - target[position++] = 0xf6; - else { - if (referenceMap) { - let referee = referenceMap.get(value); - if (referee) { - if (!referee.id) { - let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []); - referee.id = idsToInsert.push(referee); - } - target[position++] = 0xd9; - target[position++] = 40010 >> 8; - target[position++] = 40010 & 0xff; - target[position++] = 0x1a; // uint32 - targetView.setUint32(position, referee.id); - position += 4; - return - } else - referenceMap.set(value, { offset: position - start }); - } - let constructor = value.constructor; - if (constructor === Object) { - writeObject(value, true); - } else if (constructor === Array) { - length = value.length; - if (length < 0x18) { - target[position++] = 0x80 | length; - } else { - writeArrayHeader(length); - } - for (let i = 0; i < length; i++) { - encode(value[i]); - } - } else if (constructor === Map) { - if (this.mapsAsObjects ? this.useTag259ForMaps !== false : this.useTag259ForMaps) { - // use Tag 259 (https://github.com/shanewholloway/js-cbor-codec/blob/master/docs/CBOR-259-spec--explicit-maps.md) for maps if the user wants it that way - target[position++] = 0xd9; - target[position++] = 1; - target[position++] = 3; - } - length = value.size; - if (length < 0x18) { - target[position++] = 0xa0 | length; - } else if (length < 0x100) { - target[position++] = 0xb8; - target[position++] = length; - } else if (length < 0x10000) { - target[position++] = 0xb9; - target[position++] = length >> 8; - target[position++] = length & 0xff; - } else { - target[position++] = 0xba; - targetView.setUint32(position, length); - position += 4; - } - for (let [ key, entryValue ] of value) { - encode(key); - encode(entryValue); - } - } else { - for (let i = 0, l = extensions.length; i < l; i++) { - let extensionClass = extensionClasses[i]; - if (value instanceof extensionClass) { - let extension = extensions[i]; - let tag = extension.tag; - if (tag < 0x18) { - target[position++] = 0xc0 | tag; - } else if (tag < 0x100) { - target[position++] = 0xd8; - target[position++] = tag; - } else if (tag < 0x10000) { - target[position++] = 0xd9; - target[position++] = tag >> 8; - target[position++] = tag & 0xff; - } else if (tag > -1) { - target[position++] = 0xda; - targetView.setUint32(position, tag); - position += 4; - } // else undefined, don't write tag - extension.encode.call(this, value, encode, makeRoom); - return - } - } - if (value[Symbol.iterator]) { - target[position++] = 0x9f; // indefinite length array - for (let entry of value) { - encode(entry); - } - target[position++] = 0xff; // stop-code - return - } - // no extension found, write as object - writeObject(value, !value.hasOwnProperty); // if it doesn't have hasOwnProperty, don't do hasOwnProperty checks - } - } - } else if (type === 'boolean') { - target[position++] = value ? 0xf5 : 0xf4; - } else if (type === 'bigint') { - if (value < (BigInt(1)<= 0) { - // use an unsigned int as long as it fits - target[position++] = 0x1b; - targetView.setBigUint64(position, value); - } else if (value > -(BigInt(1)< { - // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects) - let keys = Object.keys(object); - let length = keys.length; - if (length < 0x18) { - target[position++] = 0xa0 | length; - } else if (length < 0x100) { - target[position++] = 0xb8; - target[position++] = length; - } else if (length < 0x10000) { - target[position++] = 0xb9; - target[position++] = length >> 8; - target[position++] = length & 0xff; - } else { - target[position++] = 0xba; - targetView.setUint32(position, length); - position += 4; - } - let key; - for (let i = 0; i < length; i++) { - encode(key = keys[i]); - encode(object[key]); - } - } : - (object, safePrototype) => { - target[position++] = 0xb9; // always use map 16, so we can preallocate and set the length afterwards - let objectOffset = position - start; - position += 2; - let size = 0; - for (let key in object) { - if (safePrototype || object.hasOwnProperty(key)) { - encode(key); - encode(object[key]); - size++; - } - } - target[objectOffset++ + start] = size >> 8; - target[objectOffset + start] = size & 0xff; - } : - - /* sharedStructures ? // For highly stable structures, using for-in can a little bit faster - (object, safePrototype) => { - let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null)) - let objectOffset = position++ - start - let wroteKeys - for (let key in object) { - if (safePrototype || object.hasOwnProperty(key)) { - nextTransition = transition[key] - if (!nextTransition) { - nextTransition = transition[key] = Object.create(null) - nextTransition.__keys__ = (transition.__keys__ || []).concat([key]) - /*let keys = Object.keys(object) - if - let size = 0 - let startBranch = transition.__keys__ ? transition.__keys__.length : 0 - for (let i = 0, l = keys.length; i++) { - let key = keys[i] - size += key.length << 2 - if (i >= startBranch) { - nextTransition = nextTransition[key] = Object.create(null) - nextTransition.__keys__ = keys.slice(0, i + 1) - } - } - makeRoom(position + size) - nextTransition = transition[key] - target.copy(target, ) - objectOffset - } - transition = nextTransition - encode(object[key]) - } - } - let id = transition.id - if (!id) { - id = transition.id = structures.push(transition.__keys__) + 63 - if (sharedStructures.onUpdate) - sharedStructures.onUpdate(id, transition.__keys__) - } - target[objectOffset + start] = id - }*/ - (object) => { - let keys = Object.keys(object); - let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null)); - let newTransitions = 0; - let length = keys.length; - for (let i =0; i < length; i++) { - let key = keys[i]; - nextTransition = transition[key]; - if (!nextTransition) { - nextTransition = transition[key] = Object.create(null); - newTransitions++; - } - transition = nextTransition; - } - let recordId = transition[RECORD_SYMBOL]; - if (recordId !== undefined) { - target[position++] = 0xd9; // tag two byte - target[position++] = RECORD_STARTING_ID_PREFIX; - target[position++] = recordId; - } else { - recordId = structures.nextId++; - if (!recordId) { - recordId = 0; - structures.nextId = 1; - } - if (recordId >= MAX_STRUCTURES) {// cycle back around - structures.nextId = (recordId = maxSharedStructures) + 1; - } - transition[RECORD_SYMBOL] = recordId; - structures[recordId] = keys; - if (sharedStructures && sharedStructures.length <= maxSharedStructures) { - target[position++] = 0xd9; // tag two byte - target[position++] = RECORD_STARTING_ID_PREFIX; - target[position++] = recordId; // tag number - hasSharedUpdate = true; - } else { - target[position++] = 0xd8; - target[position++] = RECORD_STARTING_ID_PREFIX; - if (newTransitions) - transitionsCount += serializationsSinceTransitionRebuild * newTransitions; - // record the removal of the id, we can maintain our shared structure - if (recordIdsToRemove.length >= MAX_STRUCTURES - maxSharedStructures) - recordIdsToRemove.shift()[RECORD_SYMBOL] = undefined; // we are cycling back through, and have to remove old ones - recordIdsToRemove.push(transition); - if (length < 0x16) - target[position++] = 0x82 + length; // array header, length of values + 2 - else - writeArrayHeader(length + 2); - encode(keys); - target[position++] = 0x19; // uint16 - target[position++] = RECORD_STARTING_ID_PREFIX; - target[position++] = recordId; - // now write the values - for (let i =0; i < length; i++) - encode(object[keys[i]]); - return - } - } - if (length < 0x18) { // write the array header - target[position++] = 0x80 | length; - } else { - writeArrayHeader(length); - } - for (let i =0; i < length; i++) - encode(object[keys[i]]); - }; - const makeRoom = (end) => { - let newSize; - if (end > 0x1000000) { - // special handling for really large buffers - if ((end - start) > MAX_BUFFER_SIZE) - throw new Error('Encoded buffer would be larger than maximum buffer size') - newSize = Math.min(MAX_BUFFER_SIZE, - Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x1000000) / 0x1000) * 0x1000); - } else // faster handling for smaller buffers - newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12; - let newBuffer = new ByteArrayAllocate(newSize); - targetView = new DataView(newBuffer.buffer, 0, newSize); - if (target.copy) - target.copy(newBuffer, 0, start, end); - else - newBuffer.set(target.slice(start, end)); - position -= start; - start = 0; - safeEnd = newBuffer.length - 10; - return target = newBuffer - }; - } - useBuffer(buffer) { - // this means we are finished using our own buffer and we can write over it safely - target = buffer; - targetView = new DataView(target.buffer, target.byteOffset, target.byteLength); - position = 0; - } - } - - function writeArrayHeader(length) { - if (length < 0x100) { - target[position++] = 0x98; - target[position++] = length; - } else if (length < 0x10000) { - target[position++] = 0x99; - target[position++] = length >> 8; - target[position++] = length & 0xff; - } else { - target[position++] = 0x9a; - targetView.setUint32(position, length); - position += 4; - } - } - - extensionClasses = [ Date, Set, Error, RegExp, ArrayBuffer, ByteArray, - Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, BigUint64Array, Int8Array, Int16Array, Int32Array, BigInt64Array, - Float32Array, Float64Array]; - - //Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/ - extensions = [{ - tag: 1, - encode(date, encode) { - let seconds = date.getTime() / 1000; - if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) { - // Timestamp 32 - target[position++] = 0x1a; - targetView.setUint32(position, seconds); - position += 4; - } else { - // Timestamp float64 - target[position++] = 0xfb; - targetView.setFloat64(position, seconds); - position += 8; - } - } - }, { - tag: 258, // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md - encode(set, encode) { - let array = Array.from(set); - encode(array); - } - }, { - tag: 27, // http://cbor.schmorp.de/generic-object - encode(error, encode) { - encode([ error.name, error.message ]); - } - }, { - tag: 27, // http://cbor.schmorp.de/generic-object - encode(regex, encode) { - encode([ 'RegExp', regex.source, regex.flags ]); - } - }, { - encode(arrayBuffer, encode, makeRoom) { - writeBuffer(arrayBuffer, makeRoom); - } - }, { - encode(arrayBuffer, encode, makeRoom) { - writeBuffer(arrayBuffer, makeRoom); - } - }, typedArrayEncoder(64), - typedArrayEncoder(68), - typedArrayEncoder(69), - typedArrayEncoder(70), - typedArrayEncoder(71), - typedArrayEncoder(72), - typedArrayEncoder(77), - typedArrayEncoder(78), - typedArrayEncoder(79), - typedArrayEncoder(81), - typedArrayEncoder(82)]; - - function typedArrayEncoder(tag) { - return { - tag: tag, - encode: function writeExtBuffer(typedArray, encode) { - let length = typedArray.byteLength; - let offset = typedArray.byteOffset || 0; - let buffer = typedArray.buffer || typedArray; - encode(hasNodeBuffer ? Buffer.from(buffer, offset, length) : - new Uint8Array(buffer, offset, length)); - } - } - } - function writeBuffer(buffer, makeRoom) { - let length = buffer.byteLength; - if (length < 0x18) { - target[position++] = 0x40 + length; - } else if (length < 0x100) { - target[position++] = 0x58; - target[position++] = length; - } else if (length < 0x10000) { - target[position++] = 0x59; - target[position++] = length >> 8; - target[position++] = length & 0xff; - } else { - target[position++] = 0x5a; - targetView.setUint32(position, length); - position += 4; - } - if (position + length >= target.length) { - makeRoom(position + length); - } - target.set(buffer, position); - position += length; - } - - function insertIds(serialized, idsToInsert) { - // insert the ids that need to be referenced for structured clones - let nextId; - let distanceToMove = idsToInsert.length * 8; - let lastEnd = serialized.length - distanceToMove; - idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1); - while (nextId = idsToInsert.pop()) { - let offset = nextId.offset; - let id = nextId.id; - serialized.copyWithin(offset + distanceToMove, offset, lastEnd); - distanceToMove -= 8; - let position = offset + distanceToMove; - serialized[position++] = 0xd9; - serialized[position++] = 40009 >> 8; - serialized[position++] = 40009 & 0xff; - serialized[position++] = 0x1a; // uint32 - serialized[position++] = id >> 24; - serialized[position++] = (id >> 16) & 0xff; - serialized[position++] = (id >> 8) & 0xff; - serialized[position++] = id & 0xff; - lastEnd = offset; - } - return serialized - } - - function addExtension(extension) { - if (extension.Class) { - if (!extension.encode) - throw new Error('Extension has no encode function') - extensionClasses.unshift(extension.Class); - extensions.unshift(extension); - } - addExtension$1(extension); - } - let defaultEncoder = new Encoder({ useRecords: false }); + let textEncoder; + try { + textEncoder = new TextEncoder(); + } catch (error) {} + let extensions, extensionClasses; + const Buffer = typeof globalThis === 'object' && globalThis.Buffer; + const hasNodeBuffer = typeof Buffer !== 'undefined'; + const ByteArrayAllocate = hasNodeBuffer ? Buffer.allocUnsafeSlow : Uint8Array; + const ByteArray = hasNodeBuffer ? Buffer : Uint8Array; + const MAX_STRUCTURES = 0x100; + const MAX_BUFFER_SIZE = hasNodeBuffer ? 0x100000000 : 0x7fd00000; + let throwOnIterable; + let target; + let targetView; + let position = 0; + let safeEnd; + let bundledStrings = null; + const MAX_BUNDLE_SIZE = 0xf000; + const hasNonLatin = /[\u0080-\uFFFF]/; + const RECORD_SYMBOL = Symbol('record-id'); + class Encoder extends Decoder { + constructor(options) { + super(options); + this.offset = 0; + let start; + let sharedStructures; + let hasSharedUpdate; + let structures; + let referenceMap; + options = options || {}; + let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string, position, maxBytes) { + return target.utf8Write(string, position, maxBytes) + } : (textEncoder && textEncoder.encodeInto) ? + function(string, position) { + return textEncoder.encodeInto(string, target.subarray(position)).written + } : false; + + let encoder = this; + let hasSharedStructures = options.structures || options.saveStructures; + let maxSharedStructures = options.maxSharedStructures; + if (maxSharedStructures == null) + maxSharedStructures = hasSharedStructures ? 128 : 0; + if (maxSharedStructures > 8190) + throw new Error('Maximum maxSharedStructure is 8190') + let isSequential = options.sequential; + if (isSequential) { + maxSharedStructures = 0; + } + if (!this.structures) + this.structures = []; + if (this.saveStructures) + this.saveShared = this.saveStructures; + let samplingPackedValues, packedObjectMap, sharedValues = options.sharedValues; + let sharedPackedObjectMap; + if (sharedValues) { + sharedPackedObjectMap = Object.create(null); + for (let i = 0, l = sharedValues.length; i < l; i++) { + sharedPackedObjectMap[sharedValues[i]] = i; + } + } + let recordIdsToRemove = []; + let transitionsCount = 0; + let serializationsSinceTransitionRebuild = 0; + + this.mapEncode = function(value, encodeOptions) { + // Experimental support for premapping keys using _keyMap instad of keyMap - not optiimised yet) + if (this._keyMap && !this._mapped) { + //console.log('encoding ', value) + switch (value.constructor.name) { + case 'Array': + value = value.map(r => this.encodeKeys(r)); + break + //case 'Map': + // value = this.encodeKeys(value) + // break + } + //this._mapped = true + } + return this.encode(value, encodeOptions) + }; + + this.encode = function(value, encodeOptions) { + if (!target) { + target = new ByteArrayAllocate(8192); + targetView = new DataView(target.buffer, 0, 8192); + position = 0; + } + safeEnd = target.length - 10; + if (safeEnd - position < 0x800) { + // don't start too close to the end, + target = new ByteArrayAllocate(target.length); + targetView = new DataView(target.buffer, 0, target.length); + safeEnd = target.length - 10; + position = 0; + } else if (encodeOptions === REUSE_BUFFER_MODE) + position = (position + 7) & 0x7ffffff8; // Word align to make any future copying of this buffer faster + start = position; + if (encoder.useSelfDescribedHeader) { + targetView.setUint32(position, 0xd9d9f700); // tag two byte, then self-descriptive tag + position += 3; + } + referenceMap = encoder.structuredClone ? new Map() : null; + if (encoder.bundleStrings && typeof value !== 'string') { + bundledStrings = []; + bundledStrings.size = Infinity; // force a new bundle start on first string + } else + bundledStrings = null; + + sharedStructures = encoder.structures; + if (sharedStructures) { + if (sharedStructures.uninitialized) { + let sharedData = encoder.getShared() || {}; + encoder.structures = sharedStructures = sharedData.structures || []; + encoder.sharedVersion = sharedData.version; + let sharedValues = encoder.sharedValues = sharedData.packedValues; + if (sharedValues) { + sharedPackedObjectMap = {}; + for (let i = 0, l = sharedValues.length; i < l; i++) + sharedPackedObjectMap[sharedValues[i]] = i; + } + } + let sharedStructuresLength = sharedStructures.length; + if (sharedStructuresLength > maxSharedStructures && !isSequential) + sharedStructuresLength = maxSharedStructures; + if (!sharedStructures.transitions) { + // rebuild our structure transitions + sharedStructures.transitions = Object.create(null); + for (let i = 0; i < sharedStructuresLength; i++) { + let keys = sharedStructures[i]; + //console.log('shared struct keys:', keys) + if (!keys) + continue + let nextTransition, transition = sharedStructures.transitions; + for (let j = 0, l = keys.length; j < l; j++) { + if (transition[RECORD_SYMBOL] === undefined) + transition[RECORD_SYMBOL] = i; + let key = keys[j]; + nextTransition = transition[key]; + if (!nextTransition) { + nextTransition = transition[key] = Object.create(null); + } + transition = nextTransition; + } + transition[RECORD_SYMBOL] = i | 0x100000; + } + } + if (!isSequential) + sharedStructures.nextId = sharedStructuresLength; + } + if (hasSharedUpdate) + hasSharedUpdate = false; + structures = sharedStructures || []; + packedObjectMap = sharedPackedObjectMap; + if (options.pack) { + let packedValues = new Map(); + packedValues.values = []; + packedValues.encoder = encoder; + packedValues.maxValues = options.maxPrivatePackedValues || (sharedPackedObjectMap ? 16 : Infinity); + packedValues.objectMap = sharedPackedObjectMap || false; + packedValues.samplingPackedValues = samplingPackedValues; + findRepetitiveStrings(value, packedValues); + if (packedValues.values.length > 0) { + target[position++] = 0xd8; // one-byte tag + target[position++] = 51; // tag 51 for packed shared structures https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt + writeArrayHeader(4); + let valuesArray = packedValues.values; + encode(valuesArray); + writeArrayHeader(0); // prefixes + writeArrayHeader(0); // suffixes + packedObjectMap = Object.create(sharedPackedObjectMap || null); + for (let i = 0, l = valuesArray.length; i < l; i++) { + packedObjectMap[valuesArray[i]] = i; + } + } + } + throwOnIterable = encodeOptions & THROW_ON_ITERABLE; + try { + if (throwOnIterable) + return; + encode(value); + if (bundledStrings) { + writeBundles(start, encode); + } + encoder.offset = position; // update the offset so next serialization doesn't write over our buffer, but can continue writing to same buffer sequentially + if (referenceMap && referenceMap.idsToInsert) { + position += referenceMap.idsToInsert.length * 2; + if (position > safeEnd) + makeRoom(position); + encoder.offset = position; + let serialized = insertIds(target.subarray(start, position), referenceMap.idsToInsert); + referenceMap = null; + return serialized + } + if (encodeOptions & REUSE_BUFFER_MODE) { + target.start = start; + target.end = position; + return target + } + return target.subarray(start, position) // position can change if we call encode again in saveShared, so we get the buffer now + } finally { + if (sharedStructures) { + if (serializationsSinceTransitionRebuild < 10) + serializationsSinceTransitionRebuild++; + if (sharedStructures.length > maxSharedStructures) + sharedStructures.length = maxSharedStructures; + if (transitionsCount > 10000) { + // force a rebuild occasionally after a lot of transitions so it can get cleaned up + sharedStructures.transitions = null; + serializationsSinceTransitionRebuild = 0; + transitionsCount = 0; + if (recordIdsToRemove.length > 0) + recordIdsToRemove = []; + } else if (recordIdsToRemove.length > 0 && !isSequential) { + for (let i = 0, l = recordIdsToRemove.length; i < l; i++) { + recordIdsToRemove[i][RECORD_SYMBOL] = undefined; + } + recordIdsToRemove = []; + //sharedStructures.nextId = maxSharedStructures + } + } + if (hasSharedUpdate && encoder.saveShared) { + if (encoder.structures.length > maxSharedStructures) { + encoder.structures = encoder.structures.slice(0, maxSharedStructures); + } + // we can't rely on start/end with REUSE_BUFFER_MODE since they will (probably) change when we save + let returnBuffer = target.subarray(start, position); + if (encoder.updateSharedData() === false) + return encoder.encode(value) // re-encode if it fails + return returnBuffer + } + if (encodeOptions & RESET_BUFFER_MODE) + position = start; + } + }; + this.findCommonStringsToPack = () => { + samplingPackedValues = new Map(); + if (!sharedPackedObjectMap) + sharedPackedObjectMap = Object.create(null); + return (options) => { + let threshold = options && options.threshold || 4; + let position = this.pack ? options.maxPrivatePackedValues || 16 : 0; + if (!sharedValues) + sharedValues = this.sharedValues = []; + for (let [ key, status ] of samplingPackedValues) { + if (status.count > threshold) { + sharedPackedObjectMap[key] = position++; + sharedValues.push(key); + hasSharedUpdate = true; + } + } + while (this.saveShared && this.updateSharedData() === false) {} + samplingPackedValues = null; + } + }; + const encode = (value) => { + if (position > safeEnd) + target = makeRoom(position); + + var type = typeof value; + var length; + if (type === 'string') { + if (packedObjectMap) { + let packedPosition = packedObjectMap[value]; + if (packedPosition >= 0) { + if (packedPosition < 16) + target[position++] = packedPosition + 0xe0; // simple values, defined in https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt + else { + target[position++] = 0xc6; // tag 6 defined in https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt + if (packedPosition & 1) + encode((15 - packedPosition) >> 1); + else + encode((packedPosition - 16) >> 1); + } + return + /* } else if (packedStatus.serializationId != serializationId) { + packedStatus.serializationId = serializationId + packedStatus.count = 1 + if (options.sharedPack) { + let sharedCount = packedStatus.sharedCount = (packedStatus.sharedCount || 0) + 1 + if (shareCount > (options.sharedPack.threshold || 5)) { + let sharedPosition = packedStatus.position = packedStatus.nextSharedPosition + hasSharedUpdate = true + if (sharedPosition < 16) + target[position++] = sharedPosition + 0xc0 + + } + } + } // else any in-doc incrementation?*/ + } else if (samplingPackedValues && !options.pack) { + let status = samplingPackedValues.get(value); + if (status) + status.count++; + else + samplingPackedValues.set(value, { + count: 1, + }); + } + } + let strLength = value.length; + if (bundledStrings && strLength >= 4 && strLength < 0x400) { + if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) { + let extStart; + let maxBytes = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10; + if (position + maxBytes > safeEnd) + target = makeRoom(position + maxBytes); + target[position++] = 0xd9; // tag 16-bit + target[position++] = 0xdf; // tag 0xdff9 + target[position++] = 0xf9; + // TODO: If we only have one bundle with any string data, only write one string bundle + target[position++] = bundledStrings.position ? 0x84 : 0x82; // array of 4 or 2 elements depending on if we write bundles + target[position++] = 0x1a; // 32-bit unsigned int + extStart = position - start; + position += 4; // reserve for writing bundle reference + if (bundledStrings.position) { + writeBundles(start, encode); // write the last bundles + } + bundledStrings = ['', '']; // create new ones + bundledStrings.size = 0; + bundledStrings.position = extStart; + } + let twoByte = hasNonLatin.test(value); + bundledStrings[twoByte ? 0 : 1] += value; + target[position++] = twoByte ? 0xce : 0xcf; + encode(strLength); + return + } + let headerSize; + // first we estimate the header size, so we can write to the correct location + if (strLength < 0x20) { + headerSize = 1; + } else if (strLength < 0x100) { + headerSize = 2; + } else if (strLength < 0x10000) { + headerSize = 3; + } else { + headerSize = 5; + } + let maxBytes = strLength * 3; + if (position + maxBytes > safeEnd) + target = makeRoom(position + maxBytes); + + if (strLength < 0x40 || !encodeUtf8) { + let i, c1, c2, strPosition = position + headerSize; + for (i = 0; i < strLength; i++) { + c1 = value.charCodeAt(i); + if (c1 < 0x80) { + target[strPosition++] = c1; + } else if (c1 < 0x800) { + target[strPosition++] = c1 >> 6 | 0xc0; + target[strPosition++] = c1 & 0x3f | 0x80; + } else if ( + (c1 & 0xfc00) === 0xd800 && + ((c2 = value.charCodeAt(i + 1)) & 0xfc00) === 0xdc00 + ) { + c1 = 0x10000 + ((c1 & 0x03ff) << 10) + (c2 & 0x03ff); + i++; + target[strPosition++] = c1 >> 18 | 0xf0; + target[strPosition++] = c1 >> 12 & 0x3f | 0x80; + target[strPosition++] = c1 >> 6 & 0x3f | 0x80; + target[strPosition++] = c1 & 0x3f | 0x80; + } else { + target[strPosition++] = c1 >> 12 | 0xe0; + target[strPosition++] = c1 >> 6 & 0x3f | 0x80; + target[strPosition++] = c1 & 0x3f | 0x80; + } + } + length = strPosition - position - headerSize; + } else { + length = encodeUtf8(value, position + headerSize, maxBytes); + } + + if (length < 0x18) { + target[position++] = 0x60 | length; + } else if (length < 0x100) { + if (headerSize < 2) { + target.copyWithin(position + 2, position + 1, position + 1 + length); + } + target[position++] = 0x78; + target[position++] = length; + } else if (length < 0x10000) { + if (headerSize < 3) { + target.copyWithin(position + 3, position + 2, position + 2 + length); + } + target[position++] = 0x79; + target[position++] = length >> 8; + target[position++] = length & 0xff; + } else { + if (headerSize < 5) { + target.copyWithin(position + 5, position + 3, position + 3 + length); + } + target[position++] = 0x7a; + targetView.setUint32(position, length); + position += 4; + } + position += length; + } else if (type === 'number') { + if (!this.alwaysUseFloat && value >>> 0 === value) {// positive integer, 32-bit or less + // positive uint + if (value < 0x18) { + target[position++] = value; + } else if (value < 0x100) { + target[position++] = 0x18; + target[position++] = value; + } else if (value < 0x10000) { + target[position++] = 0x19; + target[position++] = value >> 8; + target[position++] = value & 0xff; + } else { + target[position++] = 0x1a; + targetView.setUint32(position, value); + position += 4; + } + } else if (!this.alwaysUseFloat && value >> 0 === value) { // negative integer + if (value >= -0x18) { + target[position++] = 0x1f - value; + } else if (value >= -0x100) { + target[position++] = 0x38; + target[position++] = ~value; + } else if (value >= -0x10000) { + target[position++] = 0x39; + targetView.setUint16(position, ~value); + position += 2; + } else { + target[position++] = 0x3a; + targetView.setUint32(position, ~value); + position += 4; + } + } else { + let useFloat32; + if ((useFloat32 = this.useFloat32) > 0 && value < 0x100000000 && value >= -0x80000000) { + target[position++] = 0xfa; + targetView.setFloat32(position, value); + let xShifted; + if (useFloat32 < 4 || + // this checks for rounding of numbers that were encoded in 32-bit float to nearest significant decimal digit that could be preserved + ((xShifted = value * mult10[((target[position] & 0x7f) << 1) | (target[position + 1] >> 7)]) >> 0) === xShifted) { + position += 4; + return + } else + position--; // move back into position for writing a double + } + target[position++] = 0xfb; + targetView.setFloat64(position, value); + position += 8; + } + } else if (type === 'object') { + if (!value) + target[position++] = 0xf6; + else { + if (referenceMap) { + let referee = referenceMap.get(value); + if (referee) { + target[position++] = 0xd8; + target[position++] = 29; // http://cbor.schmorp.de/value-sharing + target[position++] = 0x19; // 16-bit uint + if (!referee.references) { + let idsToInsert = referenceMap.idsToInsert || (referenceMap.idsToInsert = []); + referee.references = []; + idsToInsert.push(referee); + } + referee.references.push(position - start); + position += 2; // TODO: also support 32-bit + return + } else + referenceMap.set(value, { offset: position - start }); + } + let constructor = value.constructor; + if (constructor === Object) { + writeObject(value, true); + } else if (constructor === Array) { + length = value.length; + if (length < 0x18) { + target[position++] = 0x80 | length; + } else { + writeArrayHeader(length); + } + for (let i = 0; i < length; i++) { + encode(value[i]); + } + } else if (constructor === Map) { + if (this.mapsAsObjects ? this.useTag259ForMaps !== false : this.useTag259ForMaps) { + // use Tag 259 (https://github.com/shanewholloway/js-cbor-codec/blob/master/docs/CBOR-259-spec--explicit-maps.md) for maps if the user wants it that way + target[position++] = 0xd9; + target[position++] = 1; + target[position++] = 3; + } + length = value.size; + if (length < 0x18) { + target[position++] = 0xa0 | length; + } else if (length < 0x100) { + target[position++] = 0xb8; + target[position++] = length; + } else if (length < 0x10000) { + target[position++] = 0xb9; + target[position++] = length >> 8; + target[position++] = length & 0xff; + } else { + target[position++] = 0xba; + targetView.setUint32(position, length); + position += 4; + } + if (encoder.keyMap) { + for (let [ key, entryValue ] of value) { + encode(encoder.encodeKey(key)); + encode(entryValue); + } + } else { + for (let [ key, entryValue ] of value) { + encode(key); + encode(entryValue); + } + } + } else { + for (let i = 0, l = extensions.length; i < l; i++) { + let extensionClass = extensionClasses[i]; + if (value instanceof extensionClass) { + let extension = extensions[i]; + let tag = extension.tag; + if (tag == undefined) + tag = extension.getTag && extension.getTag.call(this, value); + if (tag < 0x18) { + target[position++] = 0xc0 | tag; + } else if (tag < 0x100) { + target[position++] = 0xd8; + target[position++] = tag; + } else if (tag < 0x10000) { + target[position++] = 0xd9; + target[position++] = tag >> 8; + target[position++] = tag & 0xff; + } else if (tag > -1) { + target[position++] = 0xda; + targetView.setUint32(position, tag); + position += 4; + } // else undefined, don't write tag + extension.encode.call(this, value, encode, makeRoom); + return + } + } + if (value[Symbol.iterator]) { + if (throwOnIterable) { + let error = new Error('Iterable should be serialized as iterator'); + error.iteratorNotHandled = true; + throw error; + } + target[position++] = 0x9f; // indefinite length array + for (let entry of value) { + encode(entry); + } + target[position++] = 0xff; // stop-code + return + } + if (value[Symbol.asyncIterator] || isBlob(value)) { + let error = new Error('Iterable/blob should be serialized as iterator'); + error.iteratorNotHandled = true; + throw error; + } + if (this.useToJSON && value.toJSON) { + const json = value.toJSON(); + // if for some reason value.toJSON returns itself it'll loop forever + if (json !== value) + return encode(json) + } + + // no extension found, write as object + writeObject(value, !value.hasOwnProperty); // if it doesn't have hasOwnProperty, don't do hasOwnProperty checks + } + } + } else if (type === 'boolean') { + target[position++] = value ? 0xf5 : 0xf4; + } else if (type === 'bigint') { + if (value < (BigInt(1)<= 0) { + // use an unsigned int as long as it fits + target[position++] = 0x1b; + targetView.setBigUint64(position, value); + } else if (value > -(BigInt(1)< { + // this method is slightly slower, but generates "preferred serialization" (optimally small for smaller objects) + let keys = Object.keys(object); + let vals = Object.values(object); + let length = keys.length; + if (length < 0x18) { + target[position++] = 0xa0 | length; + } else if (length < 0x100) { + target[position++] = 0xb8; + target[position++] = length; + } else if (length < 0x10000) { + target[position++] = 0xb9; + target[position++] = length >> 8; + target[position++] = length & 0xff; + } else { + target[position++] = 0xba; + targetView.setUint32(position, length); + position += 4; + } + if (encoder.keyMap) { + for (let i = 0; i < length; i++) { + encode(encoder.encodeKey(keys[i])); + encode(vals[i]); + } + } else { + for (let i = 0; i < length; i++) { + encode(keys[i]); + encode(vals[i]); + } + } + } : + (object, safePrototype) => { + target[position++] = 0xb9; // always use map 16, so we can preallocate and set the length afterwards + let objectOffset = position - start; + position += 2; + let size = 0; + if (encoder.keyMap) { + for (let key in object) if (safePrototype || object.hasOwnProperty(key)) { + encode(encoder.encodeKey(key)); + encode(object[key]); + size++; + } + } else { + for (let key in object) if (safePrototype || object.hasOwnProperty(key)) { + encode(key); + encode(object[key]); + size++; + } + } + target[objectOffset++ + start] = size >> 8; + target[objectOffset + start] = size & 0xff; + } : + (object, safePrototype) => { + let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null)); + let newTransitions = 0; + let length = 0; + let parentRecordId; + let keys; + if (this.keyMap) { + keys = Object.keys(object).map(k => this.encodeKey(k)); + length = keys.length; + for (let i = 0; i < length; i++) { + let key = keys[i]; + nextTransition = transition[key]; + if (!nextTransition) { + nextTransition = transition[key] = Object.create(null); + newTransitions++; + } + transition = nextTransition; + } + } else { + for (let key in object) if (safePrototype || object.hasOwnProperty(key)) { + nextTransition = transition[key]; + if (!nextTransition) { + if (transition[RECORD_SYMBOL] & 0x100000) {// this indicates it is a brancheable/extendable terminal node, so we will use this record id and extend it + parentRecordId = transition[RECORD_SYMBOL] & 0xffff; + } + nextTransition = transition[key] = Object.create(null); + newTransitions++; + } + transition = nextTransition; + length++; + } + } + let recordId = transition[RECORD_SYMBOL]; + if (recordId !== undefined) { + recordId &= 0xffff; + target[position++] = 0xd9; + target[position++] = (recordId >> 8) | 0xe0; + target[position++] = recordId & 0xff; + } else { + if (!keys) + keys = transition.__keys__ || (transition.__keys__ = Object.keys(object)); + if (parentRecordId === undefined) { + recordId = structures.nextId++; + if (!recordId) { + recordId = 0; + structures.nextId = 1; + } + if (recordId >= MAX_STRUCTURES) {// cycle back around + structures.nextId = (recordId = maxSharedStructures) + 1; + } + } else { + recordId = parentRecordId; + } + structures[recordId] = keys; + if (recordId < maxSharedStructures) { + target[position++] = 0xd9; + target[position++] = (recordId >> 8) | 0xe0; + target[position++] = recordId & 0xff; + transition = structures.transitions; + for (let i = 0; i < length; i++) { + if (transition[RECORD_SYMBOL] === undefined || (transition[RECORD_SYMBOL] & 0x100000)) + transition[RECORD_SYMBOL] = recordId; + transition = transition[keys[i]]; + } + transition[RECORD_SYMBOL] = recordId | 0x100000; // indicates it is a extendable terminal + hasSharedUpdate = true; + } else { + transition[RECORD_SYMBOL] = recordId; + targetView.setUint32(position, 0xd9dfff00); // tag two byte, then record definition id + position += 3; + if (newTransitions) + transitionsCount += serializationsSinceTransitionRebuild * newTransitions; + // record the removal of the id, we can maintain our shared structure + if (recordIdsToRemove.length >= MAX_STRUCTURES - maxSharedStructures) + recordIdsToRemove.shift()[RECORD_SYMBOL] = undefined; // we are cycling back through, and have to remove old ones + recordIdsToRemove.push(transition); + writeArrayHeader(length + 2); + encode(0xe000 + recordId); + encode(keys); + if (safePrototype === null) return; // special exit for iterator + for (let key in object) + if (safePrototype || object.hasOwnProperty(key)) + encode(object[key]); + return + } + } + if (length < 0x18) { // write the array header + target[position++] = 0x80 | length; + } else { + writeArrayHeader(length); + } + if (safePrototype === null) return; // special exit for iterator + for (let key in object) + if (safePrototype || object.hasOwnProperty(key)) + encode(object[key]); + }; + const makeRoom = (end) => { + let newSize; + if (end > 0x1000000) { + // special handling for really large buffers + if ((end - start) > MAX_BUFFER_SIZE) + throw new Error('Encoded buffer would be larger than maximum buffer size') + newSize = Math.min(MAX_BUFFER_SIZE, + Math.round(Math.max((end - start) * (end > 0x4000000 ? 1.25 : 2), 0x400000) / 0x1000) * 0x1000); + } else // faster handling for smaller buffers + newSize = ((Math.max((end - start) << 2, target.length - 1) >> 12) + 1) << 12; + let newBuffer = new ByteArrayAllocate(newSize); + targetView = new DataView(newBuffer.buffer, 0, newSize); + if (target.copy) + target.copy(newBuffer, 0, start, end); + else + newBuffer.set(target.slice(start, end)); + position -= start; + start = 0; + safeEnd = newBuffer.length - 10; + return target = newBuffer + }; + let chunkThreshold = 100; + let continuedChunkThreshold = 1000; + this.encodeAsIterable = function(value, options) { + return startEncoding(value, options, encodeObjectAsIterable); + }; + this.encodeAsAsyncIterable = function(value, options) { + return startEncoding(value, options, encodeObjectAsAsyncIterable); + }; + + function* encodeObjectAsIterable(object, iterateProperties, finalIterable) { + let constructor = object.constructor; + if (constructor === Object) { + let useRecords = encoder.useRecords !== false; + if (useRecords) + writeObject(object, null); // write the record identifier + else + writeEntityLength(Object.keys(object).length, 0xa0); + for (let key in object) { + let value = object[key]; + if (!useRecords) encode(key); + if (value && typeof value === 'object') { + if (iterateProperties[key]) + yield* encodeObjectAsIterable(value, iterateProperties[key]); + else + yield* tryEncode(value, iterateProperties, key); + } else encode(value); + } + } else if (constructor === Array) { + let length = object.length; + writeArrayHeader(length); + for (let i = 0; i < length; i++) { + let value = object[i]; + if (value && (typeof value === 'object' || position - start > chunkThreshold)) { + if (iterateProperties.element) + yield* encodeObjectAsIterable(value, iterateProperties.element); + else + yield* tryEncode(value, iterateProperties, 'element'); + } else encode(value); + } + } else if (object[Symbol.iterator]) { + target[position++] = 0x9f; // start indefinite array + for (let value of object) { + if (value && (typeof value === 'object' || position - start > chunkThreshold)) { + if (iterateProperties.element) + yield* encodeObjectAsIterable(value, iterateProperties.element); + else + yield* tryEncode(value, iterateProperties, 'element'); + } else encode(value); + } + target[position++] = 0xff; // stop byte + } else if (isBlob(object)){ + writeEntityLength(object.size, 0x40); // encode as binary data + yield target.subarray(start, position); + yield object; // directly return blobs, they have to be encoded asynchronously + restartEncoding(); + } else if (object[Symbol.asyncIterator]) { + target[position++] = 0x9f; // start indefinite array + yield target.subarray(start, position); + yield object; // directly return async iterators, they have to be encoded asynchronously + restartEncoding(); + target[position++] = 0xff; // stop byte + } else { + encode(object); + } + if (finalIterable && position > start) yield target.subarray(start, position); + else if (position - start > chunkThreshold) { + yield target.subarray(start, position); + restartEncoding(); + } + } + function* tryEncode(value, iterateProperties, key) { + let restart = position - start; + try { + encode(value); + if (position - start > chunkThreshold) { + yield target.subarray(start, position); + restartEncoding(); + } + } catch (error) { + if (error.iteratorNotHandled) { + iterateProperties[key] = {}; + position = start + restart; // restart our position so we don't have partial data from last encode + yield* encodeObjectAsIterable.call(this, value, iterateProperties[key]); + } else throw error; + } + } + function restartEncoding() { + chunkThreshold = continuedChunkThreshold; + encoder.encode(null, THROW_ON_ITERABLE); // restart encoding + } + function startEncoding(value, options, encodeIterable) { + if (options && options.chunkThreshold) // explicitly specified chunk sizes + chunkThreshold = continuedChunkThreshold = options.chunkThreshold; + else // we start with a smaller threshold to get initial bytes sent quickly + chunkThreshold = 100; + if (value && typeof value === 'object') { + encoder.encode(null, THROW_ON_ITERABLE); // start encoding + return encodeIterable(value, encoder.iterateProperties || (encoder.iterateProperties = {}), true); + } + return [encoder.encode(value)]; + } + + async function* encodeObjectAsAsyncIterable(value, iterateProperties) { + for (let encodedValue of encodeObjectAsIterable(value, iterateProperties, true)) { + let constructor = encodedValue.constructor; + if (constructor === ByteArray || constructor === Uint8Array) + yield encodedValue; + else if (isBlob(encodedValue)) { + let reader = encodedValue.stream().getReader(); + let next; + while (!(next = await reader.read()).done) { + yield next.value; + } + } else if (encodedValue[Symbol.asyncIterator]) { + for await (let asyncValue of encodedValue) { + restartEncoding(); + if (asyncValue) + yield* encodeObjectAsAsyncIterable(asyncValue, iterateProperties.async || (iterateProperties.async = {})); + else yield encoder.encode(asyncValue); + } + } else { + yield encodedValue; + } + } + } + } + useBuffer(buffer) { + // this means we are finished using our own buffer and we can write over it safely + target = buffer; + targetView = new DataView(target.buffer, target.byteOffset, target.byteLength); + position = 0; + } + clearSharedData() { + if (this.structures) + this.structures = []; + if (this.sharedValues) + this.sharedValues = undefined; + } + updateSharedData() { + let lastVersion = this.sharedVersion || 0; + this.sharedVersion = lastVersion + 1; + let structuresCopy = this.structures.slice(0); + let sharedData = new SharedData(structuresCopy, this.sharedValues, this.sharedVersion); + let saveResults = this.saveShared(sharedData, + existingShared => (existingShared && existingShared.version || 0) == lastVersion); + if (saveResults === false) { + // get updated structures and try again if the update failed + sharedData = this.getShared() || {}; + this.structures = sharedData.structures || []; + this.sharedValues = sharedData.packedValues; + this.sharedVersion = sharedData.version; + this.structures.nextId = this.structures.length; + } else { + // restore structures + structuresCopy.forEach((structure, i) => this.structures[i] = structure); + } + // saveShared may fail to write and reload, or may have reloaded to check compatibility and overwrite saved data, either way load the correct shared data + return saveResults + } + } + function writeEntityLength(length, majorValue) { + if (length < 0x18) + target[position++] = majorValue | length; + else if (length < 0x100) { + target[position++] = majorValue | 0x18; + target[position++] = length; + } else if (length < 0x10000) { + target[position++] = majorValue | 0x19; + target[position++] = length >> 8; + target[position++] = length & 0xff; + } else { + target[position++] = majorValue | 0x1a; + targetView.setUint32(position, length); + position += 4; + } + + } + class SharedData { + constructor(structures, values, version) { + this.structures = structures; + this.packedValues = values; + this.version = version; + } + } + + function writeArrayHeader(length) { + if (length < 0x18) + target[position++] = 0x80 | length; + else if (length < 0x100) { + target[position++] = 0x98; + target[position++] = length; + } else if (length < 0x10000) { + target[position++] = 0x99; + target[position++] = length >> 8; + target[position++] = length & 0xff; + } else { + target[position++] = 0x9a; + targetView.setUint32(position, length); + position += 4; + } + } + + const BlobConstructor = typeof Blob === 'undefined' ? function(){} : Blob; + function isBlob(object) { + if (object instanceof BlobConstructor) + return true; + let tag = object[Symbol.toStringTag]; + return tag === 'Blob' || tag === 'File'; + } + function findRepetitiveStrings(value, packedValues) { + switch(typeof value) { + case 'string': + if (value.length > 3) { + if (packedValues.objectMap[value] > -1 || packedValues.values.length >= packedValues.maxValues) + return + let packedStatus = packedValues.get(value); + if (packedStatus) { + if (++packedStatus.count == 2) { + packedValues.values.push(value); + } + } else { + packedValues.set(value, { + count: 1, + }); + if (packedValues.samplingPackedValues) { + let status = packedValues.samplingPackedValues.get(value); + if (status) + status.count++; + else + packedValues.samplingPackedValues.set(value, { + count: 1, + }); + } + } + } + break + case 'object': + if (value) { + if (value instanceof Array) { + for (let i = 0, l = value.length; i < l; i++) { + findRepetitiveStrings(value[i], packedValues); + } + + } else { + let includeKeys = !packedValues.encoder.useRecords; + for (var key in value) { + if (value.hasOwnProperty(key)) { + if (includeKeys) + findRepetitiveStrings(key, packedValues); + findRepetitiveStrings(value[key], packedValues); + } + } + } + } + break + case 'function': console.log(value); + } + } + const isLittleEndianMachine = new Uint8Array(new Uint16Array([1]).buffer)[0] == 1; + extensionClasses = [ Date, Set, Error, RegExp, Tag, ArrayBuffer, + Uint8Array, Uint8ClampedArray, Uint16Array, Uint32Array, + typeof BigUint64Array == 'undefined' ? function() {} : BigUint64Array, Int8Array, Int16Array, Int32Array, + typeof BigInt64Array == 'undefined' ? function() {} : BigInt64Array, + Float32Array, Float64Array, SharedData ]; + + //Object.getPrototypeOf(Uint8Array.prototype).constructor /*TypedArray*/ + extensions = [{ // Date + tag: 1, + encode(date, encode) { + let seconds = date.getTime() / 1000; + if ((this.useTimestamp32 || date.getMilliseconds() === 0) && seconds >= 0 && seconds < 0x100000000) { + // Timestamp 32 + target[position++] = 0x1a; + targetView.setUint32(position, seconds); + position += 4; + } else { + // Timestamp float64 + target[position++] = 0xfb; + targetView.setFloat64(position, seconds); + position += 8; + } + } + }, { // Set + tag: 258, // https://github.com/input-output-hk/cbor-sets-spec/blob/master/CBOR_SETS.md + encode(set, encode) { + let array = Array.from(set); + encode(array); + } + }, { // Error + tag: 27, // http://cbor.schmorp.de/generic-object + encode(error, encode) { + encode([ error.name, error.message ]); + } + }, { // RegExp + tag: 27, // http://cbor.schmorp.de/generic-object + encode(regex, encode) { + encode([ 'RegExp', regex.source, regex.flags ]); + } + }, { // Tag + getTag(tag) { + return tag.tag + }, + encode(tag, encode) { + encode(tag.value); + } + }, { // ArrayBuffer + encode(arrayBuffer, encode, makeRoom) { + writeBuffer(arrayBuffer, makeRoom); + } + }, { // Uint8Array + getTag(typedArray) { + if (typedArray.constructor === Uint8Array) { + if (this.tagUint8Array || hasNodeBuffer && this.tagUint8Array !== false) + return 64; + } // else no tag + }, + encode(typedArray, encode, makeRoom) { + writeBuffer(typedArray, makeRoom); + } + }, + typedArrayEncoder(68, 1), + typedArrayEncoder(69, 2), + typedArrayEncoder(70, 4), + typedArrayEncoder(71, 8), + typedArrayEncoder(72, 1), + typedArrayEncoder(77, 2), + typedArrayEncoder(78, 4), + typedArrayEncoder(79, 8), + typedArrayEncoder(85, 4), + typedArrayEncoder(86, 8), + { + encode(sharedData, encode) { // write SharedData + let packedValues = sharedData.packedValues || []; + let sharedStructures = sharedData.structures || []; + if (packedValues.values.length > 0) { + target[position++] = 0xd8; // one-byte tag + target[position++] = 51; // tag 51 for packed shared structures https://www.potaroo.net/ietf/ids/draft-ietf-cbor-packed-03.txt + writeArrayHeader(4); + let valuesArray = packedValues.values; + encode(valuesArray); + writeArrayHeader(0); // prefixes + writeArrayHeader(0); // suffixes + packedObjectMap = Object.create(sharedPackedObjectMap || null); + for (let i = 0, l = valuesArray.length; i < l; i++) { + packedObjectMap[valuesArray[i]] = i; + } + } + if (sharedStructures) { + targetView.setUint32(position, 0xd9dffe00); + position += 3; + let definitions = sharedStructures.slice(0); + definitions.unshift(0xe000); + definitions.push(new Tag(sharedData.version, 0x53687264)); + encode(definitions); + } else + encode(new Tag(sharedData.version, 0x53687264)); + } + }]; + function typedArrayEncoder(tag, size) { + if (!isLittleEndianMachine && size > 1) + tag -= 4; // the big endian equivalents are 4 less + return { + tag: tag, + encode: function writeExtBuffer(typedArray, encode) { + let length = typedArray.byteLength; + let offset = typedArray.byteOffset || 0; + let buffer = typedArray.buffer || typedArray; + encode(hasNodeBuffer ? Buffer.from(buffer, offset, length) : + new Uint8Array(buffer, offset, length)); + } + } + } + function writeBuffer(buffer, makeRoom) { + let length = buffer.byteLength; + if (length < 0x18) { + target[position++] = 0x40 + length; + } else if (length < 0x100) { + target[position++] = 0x58; + target[position++] = length; + } else if (length < 0x10000) { + target[position++] = 0x59; + target[position++] = length >> 8; + target[position++] = length & 0xff; + } else { + target[position++] = 0x5a; + targetView.setUint32(position, length); + position += 4; + } + if (position + length >= target.length) { + makeRoom(position + length); + } + // if it is already a typed array (has an ArrayBuffer), use that, but if it is an ArrayBuffer itself, + // must wrap it to set it. + target.set(buffer.buffer ? buffer : new Uint8Array(buffer), position); + position += length; + } + + function insertIds(serialized, idsToInsert) { + // insert the ids that need to be referenced for structured clones + let nextId; + let distanceToMove = idsToInsert.length * 2; + let lastEnd = serialized.length - distanceToMove; + idsToInsert.sort((a, b) => a.offset > b.offset ? 1 : -1); + for (let id = 0; id < idsToInsert.length; id++) { + let referee = idsToInsert[id]; + referee.id = id; + for (let position of referee.references) { + serialized[position++] = id >> 8; + serialized[position] = id & 0xff; + } + } + while (nextId = idsToInsert.pop()) { + let offset = nextId.offset; + serialized.copyWithin(offset + distanceToMove, offset, lastEnd); + distanceToMove -= 2; + let position = offset + distanceToMove; + serialized[position++] = 0xd8; + serialized[position++] = 28; // http://cbor.schmorp.de/value-sharing + lastEnd = offset; + } + return serialized + } + function writeBundles(start, encode) { + targetView.setUint32(bundledStrings.position + start, position - bundledStrings.position - start + 1); // the offset to bundle + let writeStrings = bundledStrings; + bundledStrings = null; + encode(writeStrings[0]); + encode(writeStrings[1]); + } + + function addExtension(extension) { + if (extension.Class) { + if (!extension.encode) + throw new Error('Extension has no encode function') + extensionClasses.unshift(extension.Class); + extensions.unshift(extension); + } + addExtension$1(extension); + } + let defaultEncoder = new Encoder({ useRecords: false }); defaultEncoder.encode; + defaultEncoder.encodeAsIterable; + defaultEncoder.encodeAsAsyncIterable; + const REUSE_BUFFER_MODE = 512; + const RESET_BUFFER_MODE = 1024; + const THROW_ON_ITERABLE = 2048; var lzjbPack = {}; @@ -5004,7 +5799,7 @@ * The rationalize algorithm is by Per M.A. Bothner, Alan Bawden and Marc Feeley. * source: Kawa, C-Gambit * - * Build time: Wed, 06 Sep 2023 20:32:14 +0000 + * Build time: Fri, 10 Nov 2023 16:25:41 +0000 */ var _excluded = ["token"], _excluded2 = ["stderr", "stdin", "stdout", "command_line"]; @@ -14685,7 +15480,7 @@ } return read; - }(), "(read [string])\n\n This function, if used with a string, will parse it and\n return the LIPS code, if there is any. If called without an\n input, it will read a string from standard input (using\n the browser's prompt or a user defined input method) and\n calls itself with that string. This function can be used\n together with `eval` to evaluate code from a string."), + }(), "(read [string])\n\n This function, if used with a string, will parse it and\n return the LIPS code, if there is any. If called with a\n port, it will parse the next item from the port. If called\n without an input, it will read a string from standard input\n (using the browser's prompt or a user defined input method)\n and calls itself with that string. This function can be used\n together with `eval` to evaluate code from a string."), // ------------------------------------------------------------------ pprint: doc('pprint', function pprint(arg) { if (arg instanceof Pair) { @@ -14696,7 +15491,7 @@ } global_env.get('newline').call(global_env); - }, "(pprint expression)\n\n This function will pretty print its input. If it is called\n with a non-list, it will just call the print function on its\n input."), + }, "(pprint expression)\n\n This function will pretty print its input to stdout. If it is called\n with a non-list, it will just call the print function on its\n input."), // ------------------------------------------------------------------ print: doc('print', function print() { var display = global_env.get('display'); @@ -14710,7 +15505,7 @@ display.call(global_env, arg); newline.call(global_env); }); - }, "(print . args)\n\n This function converts each input into a string and prints\n the result to the standard output. (by default it's the\n console but it can be defined in user code) This function\n calls `newline` after printing each input."), + }, "(print . args)\n\n This function converts each input into a string and prints\n the result to the standard output (by default it's the\n console but it can be defined in user code). This function\n calls `(newline)` after printing each input."), // ------------------------------------------------------------------ format: doc('format', function format(str) { for (var _len20 = arguments.length, args = new Array(_len20 > 1 ? _len20 - 1 : 0), _key20 = 1; _key20 < _len20; _key20++) { @@ -14764,7 +15559,7 @@ var value = global_env.get('repr')(arg); port.write.call(global_env, value); - }, "(display string [port])\n\n This function outputs the string to the standard output or\n the port if given."), + }, "(display string [port])\n\n This function outputs the string to the standard output or\n the port if given. No newline."), // ------------------------------------------------------------------ 'display-error': doc('display-error', function error() { var port = internal(this, 'stderr'); @@ -14777,7 +15572,7 @@ var value = args.map(repr).join(' '); port.write.call(global_env, value); global_env.get('newline')(port); - }, "(display-error . args)\n\n Display an error message."), + }, "(display-error . args)\n\n Display an error message on stderr."), // ------------------------------------------------------------------ '%same-functions': doc('%same-functions', function (a, b) { if (!is_function(a)) { @@ -14842,7 +15637,7 @@ // ------------------------------------------------------------------ cons: doc('cons', function cons(car, cdr) { return new Pair(car, cdr); - }, "(cons left right)\n\n This function returns a new list with the first appended\n before the second."), + }, "(cons left right)\n\n This function returns a new list with the first appended\n before the second. If the second is not a list cons will\n return a dotted pair."), // ------------------------------------------------------------------ car: doc('car', function car(list) { typecheck('car', list, 'pair'); @@ -14950,7 +15745,7 @@ ref.set(symbol, value); }); - }), "(set! name value)\n\n Macro that can be used to set the value of the variable (mutate)\n it search the scope chain until it finds first non emtpy slot and set it."), + }), "(set! name value)\n\n Macro that can be used to set the value of the variable or slot (mutate it).\n set! searches the scope chain until it finds first non emtpy slot and sets it."), // ------------------------------------------------------------------ 'unset!': doc(new Macro('set!', function (code) { if (!(code.car instanceof LSymbol)) { @@ -14963,23 +15758,23 @@ if (ref) { delete ref.__env__[symbol.__name__]; } - }), "(unset! name)\n\n Function delete specified name from environment."), + }), "(unset! name)\n\n Function to delete the specified name from environment.\n Trying to access the name afterwards will error."), // ------------------------------------------------------------------ 'set-car!': doc('set-car!', function (slot, value) { typecheck('set-car!', slot, 'pair'); slot.car = value; - }, "(set-car! obj value)\n\n Function that set car (head) of the list/pair to specified value.\n It can destroy the list. Old value is lost."), + }, "(set-car! obj value)\n\n Function that sets the car (first item) of the list/pair to specified value.\n The old value is lost."), // ------------------------------------------------------------------ 'set-cdr!': doc('set-cdr!', function (slot, value) { typecheck('set-cdr!', slot, 'pair'); slot.cdr = value; - }, "(set-cdr! obj value)\n\n Function that set cdr (tail) of the list/pair to specified value.\n It can destroy the list. Old value is lost."), + }, "(set-cdr! obj value)\n\n Function that sets the cdr (tail) of the list/pair to specified value.\n It will destroy the list. The old tail is lost."), // ------------------------------------------------------------------ 'empty?': doc('empty?', function (x) { return typeof x === 'undefined' || x === _nil; - }, "(empty? object)\n\n Function return true if value is undfined empty list."), + }, "(empty? object)\n\n Function that returns #t if value is nil (an empty list) or undefined."), // ------------------------------------------------------------------ - gensym: doc('gensym', gensym, "(gensym)\n\n Function generate unique symbol, to use with macros as meta name."), + gensym: doc('gensym', gensym, "(gensym)\n\n Generates a unique symbol that is not bound anywhere,\n to use with macros as meta name."), // ------------------------------------------------------------------ load: doc('load', function load(file, env) { typecheck('load', file, 'string'); @@ -15128,7 +15923,7 @@ }).then(function () {})["finally"](function () { global_env.set(PATH, module_path); }); - }, "(load filename)\n (load filename environment)\n\n Function fetch the file and evaluate its content as LIPS code,\n If second argument is provided and it's environment the evaluation\n will happen in that environment."), + }, "(load filename)\n (load filename environment)\n\n Fetches the file (from disk or network) and evaluates its content as LIPS code.\n If the second argument is provided and it's an environment the evaluation\n will happen in that environment."), // ------------------------------------------------------------------ 'do': doc(new Macro('do', /*#__PURE__*/function () { var _ref30 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee19(code, _ref31) { @@ -15287,7 +16082,7 @@ return function (_x15, _x16) { return _ref30.apply(this, arguments); }; - }()), "(do (( )) (test expression) . body)\n\n Iteration macro that evaluate the expression body in scope of the variables.\n On each loop it increase the variables according to next expression and runs\n test to check if the loop should continue. If test is single called, the macro\n will not return anything. If the test is pair of expression and value the\n macro will return that value after finish."), + }()), "(do (( )) (test return) . body)\n\n Iteration macro that evaluates the expression body in scope of the variables.\n On each loop it changes the variables according to the expression and runs\n test to check if the loop should continue. If test is a single value, the macro\n will return undefined. If the test is a pair of expressions the macro will evaluate\n and return the second expression after the loop exits."), // ------------------------------------------------------------------ 'if': doc(new Macro('if', function (code, _ref32) { var dynamic_scope = _ref32.dynamic_scope, @@ -15326,7 +16121,7 @@ }); return unpromise(cond, resolve); - }), "(if cond true-expr false-expr)\n\n Macro evaluate condition expression and if the value is true, it\n evaluate and return true expression if not it evaluate and return\n false expression"), + }), "(if cond true-expr false-expr)\n\n Macro that evaluates cond expression and if the value is true, it\n evaluates and returns true-expression, if not it evaluates and returns\n false-expression."), // ------------------------------------------------------------------ 'let-env': new Macro('let-env', function (code) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; @@ -15348,19 +16143,19 @@ error: error }); }); - }, "(let-env env . body)\n\n Special macro that evaluate body in context of given environment\n object."), + }, "(let-env env . body)\n\n Special macro that evaluates body in context of given environment\n object."), // ------------------------------------------------------------------ - 'letrec': doc(let_macro(Symbol["for"]('letrec')), "(letrec ((a value-a) (b value-b)) body)\n\n Macro that creates new environment, then evaluate and assign values to\n names and then evaluate the body in context of that environment.\n Values are evaluated sequentialy and next value can access to\n previous values/names."), + 'letrec': doc(let_macro(Symbol["for"]('letrec')), "(letrec ((a value-a) (b value-b) ...) . body)\n\n Macro that creates a new environment, then evaluates and assigns values to\n names and then evaluates the body in context of that environment.\n Values are evaluated sequentialy and the next value can access the\n previous values/names."), // --------------------------------------------------------------------- - 'letrec*': doc(let_macro(Symbol["for"]('letrec')), "(letrec* ((a value-a) (b value-b)) body)\n\n Same as letrec but the order of execution of the binding is guaranteed,\n so use can use recursive code as well as reference previous binding.\n In LIPS both letrec and letrec* behave the same."), + 'letrec*': doc(let_macro(Symbol["for"]('letrec')), "(letrec* ((a value-a) (b value-b) ...) . body)\n\n Same as letrec but the order of execution of the binding is guaranteed,\n so you can use recursive code as well as referencing the previous binding.\n\n In LIPS both letrec and letrec* behave the same."), // --------------------------------------------------------------------- - 'let*': doc(let_macro(Symbol["for"]('let*')), "(let* ((a value-a) (b value-b)) body)\n\n Macro similar to `let` but next argument get environment\n from previous let variable, so they you can define one variable,\n and use in next argument."), + 'let*': doc(let_macro(Symbol["for"]('let*')), "(let* ((a value-a) (b value-b) ...) . body)\n\n Macro similar to `let`, but the subsequent bindings after the first\n are evaluated in the environment including the previous let variables,\n so you can define one variable, and use it in the next's definition."), // --------------------------------------------------------------------- - 'let': doc(let_macro(Symbol["for"]('let')), "(let ((a value-a) (b value-b)) body)\n\n Macro that creates new environment, then evaluate and assign values to\n names and then evaluate the body in context of that environment.\n Values are evaluated sequentialy but you can't access\n previous values/names when next are evaluated. You can only get them\n from body of let expression."), + 'let': doc(let_macro(Symbol["for"]('let')), "(let ((a value-a) (b value-b) ...) . body)\n\n Macro that creates a new environment, then evaluates and assigns values to\n names, and then evaluates the body in context of that environment.\n Values are evaluated sequentialy but you can't access previous values/names\n when the next are evaluated. You can only get them in the body of the let expression.\n (If you want to define multiple variables and use them in each other's definitions,\n use `let*`.)"), // ------------------------------------------------------------------ 'begin*': doc(pararel('begin*', function (values) { return values.pop(); - }), "(begin* . expr)\n\n This macro is parallel version of begin. It evaluate each expression and\n if it's a promise it will evaluate it in parallel and return value\n of last expression."), + }), "(begin* . body)\n\n This macro is a parallel version of begin. It evaluates each expression\n in the body and if it's a promise it will await it in parallel and return \n the value of the last expression (i.e. it uses Promise.all())."), // ------------------------------------------------------------------ 'begin': doc(new Macro('begin', function (code, options) { var args = Object.assign({}, options); @@ -15386,7 +16181,7 @@ return result; } }(); - }), "(begin . args)\n\n Macro runs list of expression and return valuate of the list one.\n It can be used in place where you can only have single exression,\n like if expression."), + }), "(begin . args)\n\n Macro that runs a list of expressions in order and returns the value\n of the last one. It can be used in places where you can only have a\n single expression, like (if)."), // ------------------------------------------------------------------ 'ignore': new Macro('ignore', function (code, _ref33) { var dynamic_scope = _ref33.dynamic_scope, @@ -15401,7 +16196,7 @@ } _evaluate(new Pair(new LSymbol('begin'), code), args); - }, "(ignore expression)\n\n Macro that will evaluate expression and swallow any promises that may\n be created. It wil run and ignore any value that may be returned by\n expression. The code should have side effects and/or when it's promise\n it should resolve to undefined."), + }, "(ignore . body)\n\n Macro that will evaluate the expression and swallow any promises that may\n be created. It wil discard any value that may be returned by the last body\n expression. The code should have side effects and/or when it's promise\n it should resolve to undefined."), // ------------------------------------------------------------------ 'call/cc': doc(Macro.defmacro('call/cc', function (code) { var eval_args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; @@ -15415,7 +16210,7 @@ return result(new Continuation(null)); } }); - }), "(call/cc proc)\n\n TODO"), + }), "(call/cc proc)\n\n Call-with-current-continuation.\n\n NOT SUPPORED BY LIPS RIGHT NOW"), // ------------------------------------------------------------------ define: doc(Macro.defmacro('define', function (code, eval_args) { var env = this; @@ -15465,7 +16260,7 @@ env.set(code.car, value, __doc__, true); }); - }), "(define name expression)\n (define name expression \"doc string\")\n (define (function-name . args) body)\n\n Macro for defining values. It can be used to define variables,\n or function. If first argument is list it will create function\n with name beeing first element of the list. The macro evalute\n code `(define function (lambda args body))`"), + }), "(define name expression)\n (define name expression \"doc string\")\n (define (function-name . args) . body)\n\n Macro for defining values. It can be used to define variables,\n or functions. If the first argument is list it will create a function\n with name being first element of the list. This form expands to\n `(define function-name (lambda args body))`"), // ------------------------------------------------------------------ 'set-obj!': doc('set-obj!', function (obj, key, value) { var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; @@ -15498,11 +16293,11 @@ value: _value4 })); } - }, "(set-obj! obj key value)\n (set-obj! obj key value props)\n\n Function set property of JavaScript object. Props should be vector of pairs,\n passed to Object.defineProperty."), + }, "(set-obj! obj key value)\n (set-obj! obj key value props)\n\n Function set a property of a JavaScript object. props should be a vector of pairs,\n passed to Object.defineProperty."), // ------------------------------------------------------------------ 'null-environment': doc('null-environment', function () { return global_env.inherit('null'); - }, "(null-environment)\n\n Function return new base environment with std lib."), + }, "(null-environment)\n\n Returns a clean environment with only the standard library."), // ------------------------------------------------------------------ 'values': doc('values', function values() { for (var _len22 = arguments.length, args = new Array(_len22), _key22 = 0; _key22 < _len22; _key22++) { @@ -15510,7 +16305,7 @@ } return Values(args); - }, "(values a1 a2 ...)\n\n If called with more then one elment it will create special\n Values object that can be used in call-with-values function"), + }, "(values a1 a2 ...)\n\n If called with more then one elment it will create a special\n Values object that can be used in the call-with-values function."), // ------------------------------------------------------------------ 'call-with-values': doc('call-with-values', function (producer, consumer) { typecheck('call-with-values', producer, 'function', 1); @@ -15522,7 +16317,7 @@ } return consumer(maybe); - }, "(call-with-values producer consumer)\n\n Calls its producer argument with no values and a continuation that,\n when passed some values, calls the consumer procedure with those\n values as arguments."), + }, "(call-with-values producer consumer)\n\n Calls the producer procedure with no arguments, then calls the\n consumer procedure with the returned value as an argument -- unless\n the returned value is a special Values object created by (values), if it is\n the values are unpacked and the consumer is called with multiple arguments."), // ------------------------------------------------------------------ 'current-environment': doc('current-environment', function () { if (this.__name__ === '__frame__') { @@ -15530,11 +16325,11 @@ } return this; - }, "(current-environment)\n\n Function return current environement."), + }, "(current-environment)\n\n Function that returns the current environement (they're first-class objects!)"), // ------------------------------------------------------------------ 'parent.frame': doc('parent.frame', function () { return user_env; - }, "(parent.frame)\n\n Return parent environment if called from inside function.\n If no parent frame found it return nil."), + }, "(parent.frame)\n\n Returns the parent environment if called from inside a function.\n If no parent frame can be found it returns nil."), // ------------------------------------------------------------------ 'eval': doc('eval', function (code, env) { var _this23 = this; @@ -15555,7 +16350,7 @@ } } }); - }, "(eval expr)\n (eval expr environment)\n\n Function evalute LIPS Scheme code."), + }, "(eval expr)\n (eval expr environment)\n\n Function that evalutes LIPS Scheme code. If the second argument is provided\n it will be the environment that the code is evaluated in."), // ------------------------------------------------------------------ lambda: new Macro('lambda', function (code) { var _ref34 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, @@ -15670,7 +16465,7 @@ return doc(set_fn_length(lambda, length), __doc__, true); - }, "(lambda (a b) body)\n (lambda args body)\n (lambda (a b . rest) body)\n\n Macro lambda create new anonymous function, if first element of the body\n is string and there is more elements it will be documentation, that can\n be read using (help fn)"), + }, "(lambda (a b) body)\n (lambda args body)\n (lambda (a b . rest) body)\n\n The lambda macro creates a new anonymous function. If the first element of\n the body is a string and there is more elements the string is used as the\n documentation string, that can be read using (help fn)."), 'macroexpand': new Macro('macroexpand', macro_expand()), 'macroexpand-1': new Macro('macroexpand-1', macro_expand(true)), // ------------------------------------------------------------------ @@ -15751,7 +16546,7 @@ makro_instance.__code__ = new Pair(new LSymbol('define-macro'), macro); this.set(name, makro_instance); } - }), "(define-macro (name . args) body)\n\n Meta macro, macro that create new macros, if return value is list structure\n it will be evaluated when macro is invoked. You can use quasiquote ` and\n unquote , and unquote-splicing ,@ inside to create expression that will be\n evaluated on runtime. Macros works like this: if you pass any expression to\n macro the arguments will not be evaluated unless macro itself evaluate it.\n Because of this macro can manipulate expression (arguments) as lists."), + }), "(define-macro (name . args) body)\n\n The meta-macro, that creates new macros. If the return value is a list structure\n it will be evaluated where the macro is invoked from. You can use quasiquote ` and\n unquote , and unquote-splicing ,@ inside to create an expression that will be\n evaluated at runtime. Macros works like this: if you pass any expression to a\n macro the arguments will not be evaluated unless the macro's body explicitly\n calls (eval) on it. Because of this a macro can manipulate the expression (arguments)\n as lists."), // ------------------------------------------------------------------ 'syntax-rules': new Macro('syntax-rules', function (macro, options) { var dynamic_scope = options.dynamic_scope, @@ -15892,17 +16687,17 @@ }, env); syntax.__code__ = macro; return syntax; - }, "(syntax-rules () (pattern expression) ...)\n\n Base of Hygienic macro, it will return new syntax expander\n that works like lisp macros."), + }, "(syntax-rules () (pattern expression) ...)\n\n Base of hygienic macros, it will return a new syntax expander\n that works like Lisp macros."), // ------------------------------------------------------------------ quote: doc(new Macro('quote', function (arg) { return quote(arg.car); - }), "(quote expression)\n\n Macro that return single lips expression as data (it don't evaluate its\n argument). It will return list of pairs if put in front of lips code.\n And if put in fron of symbol it will return that symbol not value\n associated with that name."), + }), "(quote expression) or 'expression\n\n Macro that returns a single LIPS expression as data (it won't evaluate the\n argument). It will return a list if put in front of LIPS code.\n And if put in front of a symbol it will return the symbol itself, not the value\n bound to that name."), 'unquote-splicing': doc('unquote-splicing', function () { throw new Error("You can't call `unquote-splicing` outside of quasiquote"); - }, "(unquote-splicing code)\n\n Special form to be used in quasiquote macro, parser is processing special\n characters ,@ and create call to this pseudo function. It can be used\n to evalute expression inside and return the value without parenthesis.\n the value will be joined to the output list structure."), + }, "(unquote-splicing code) or ,@code\n\n Special form used in the quasiquote macro. It evaluates the expression inside and\n splices the list into quasiquote's result. If it is not the last element of the expression,\n the computed value must be a pair."), 'unquote': doc('unquote', function () { throw new Error("You can't call `unquote` outside of quasiquote"); - }, "(unquote code)\n\n Special form to be used in quasiquote macro, parser is processing special\n characters , and create call to this pseudo function. It can be used\n to evalute expression inside and return the value, the output is inserted\n into list structure created by queasiquote."), + }, "(unquote code) or ,code\n\n Special form used in the quasiquote macro. It evaluates the expression inside and\n substitutes the value into quasiquote's result."), // ------------------------------------------------------------------ quasiquote: Macro.defmacro('quasiquote', function (arg, env) { var dynamic_scope = env.dynamic_scope, @@ -16265,12 +17060,12 @@ clear(value); return quote(value); }); - }, "(quasiquote list ,value ,@value)\n\n Similar macro to `quote` but inside it you can use special\n expressions unquote abbreviated to , that will evaluate expresion inside\n and return its value or unquote-splicing abbreviated to ,@ that will\n evaluate expression but return value without parenthesis (it will join)\n the list with its value. Best used with macros but it can be used outside"), + }, "(quasiquote list)\n\n Similar macro to `quote` but inside it you can use special\n expressions (unquote x) abbreviated to ,x that will evaluate x\n and insert its value verbatim or (unquote-splicing x) abbreviated to ,@x that will\n evaluate x and splice the value into the result. Best used with macros but it can be used outside."), // ------------------------------------------------------------------ clone: doc('clone', function clone(list) { typecheck('clone', list, 'pair'); return list.clone(); - }, "(clone list)\n\n Function return clone of the list."), + }, "(clone list)\n\n Function that returns a clone of the list, that does not share any pairs\n with the original, so the clone can be safely mutated without affecting the original."), // ------------------------------------------------------------------ append: doc('append', function append() { var _global_env$get; @@ -16287,7 +17082,7 @@ return item; }); return (_global_env$get = global_env.get('append!')).call.apply(_global_env$get, [this].concat(_toConsumableArray(items))); - }, "(append item ...)\n\n Function will create new list with eac argument appended to the end.\n It will always return new list and not modify it's arguments."), + }, "(append item ...)\n\n Function that creates a new list with each argument appended end-to-end.\n It will always return a new list and not modify its arguments."), // ------------------------------------------------------------------ 'append!': doc('append!', function () { var is_list = global_env.get('list?'); @@ -16317,7 +17112,7 @@ return acc.append(item); }, _nil); - }, "(append! arg1 ...)\n\n Destructive version of append, it modify the list in place. It return\n new list where each argument is appened to the end. It may modify\n lists added as arguments."), + }, "(append! arg1 ...)\n\n Destructive version of append, it can modify the lists in place. It returns\n a new list where each argument is appened to the end. It may modify\n lists added as arguments."), // ------------------------------------------------------------------ reverse: doc('reverse', function reverse(arg) { typecheck('reverse', arg, ['array', 'pair', 'nil']); @@ -16334,7 +17129,7 @@ } else { return arg.reverse(); } - }, "(reverse list)\n\n Function will reverse the list or array. If value is not a list\n or array it will throw exception."), + }, "(reverse list)\n\n Function that reverses the list or array. If value is not a list\n or array it will error."), // ------------------------------------------------------------------ nth: doc('nth', function nth(index, obj) { typecheck('nth', index, 'number'); @@ -16359,7 +17154,7 @@ } else { throw new Error(typeErrorMessage('nth', type(obj), 'array or pair', 2)); } - }, "(nth index obj)\n\n Function return nth element of the list or array. If used with different\n value it will throw exception"), + }, "(nth index obj)\n\n Function that returns the nth element of the list or array.\n If used with a non-indexable value it will error."), // ------------------------------------------------------------------ list: doc('list', function list() { for (var _len26 = arguments.length, args = new Array(_len26), _key26 = 0; _key26 < _len26; _key26++) { @@ -16369,14 +17164,14 @@ return args.reverse().reduce(function (list, item) { return new Pair(item, list); }, _nil); - }, "(list . args)\n\n Function create new list out of its arguments."), + }, "(list . args)\n\n Function that creates a new list out of its arguments."), // ------------------------------------------------------------------ substring: doc('substring', function substring(string, start, end) { typecheck('substring', string, 'string'); typecheck('substring', start, 'number'); typecheck('substring', end, ['number', 'undefined']); return string.substring(start.valueOf(), end && end.valueOf()); - }, "(substring string start end)\n\n Function return part of the string starting at start ending with end."), + }, "(substring string start end)\n\n Function that returns the slice of the string starting at start and ending with end."), // ------------------------------------------------------------------ concat: doc('concat', function concat() { for (var _len27 = arguments.length, args = new Array(_len27), _key27 = 0; _key27 < _len27; _key27++) { @@ -16387,48 +17182,48 @@ return typecheck('concat', arg, 'string', i + 1); }); return args.join(''); - }, "(concat . strings)\n\n Function create new string by joining its arguments"), + }, "(concat . strings)\n\n Function that creates a new string by joining its arguments."), // ------------------------------------------------------------------ join: doc('join', function join(separator, list) { typecheck('join', separator, 'string'); typecheck('join', list, ['pair', 'nil']); return global_env.get('list->array')(list).join(separator); - }, "(join separator list)\n\n Function return string by joining elements of the list"), + }, "(join separator list)\n\n Function that returns a string by joining elements of the list using separator."), // ------------------------------------------------------------------ split: doc('split', function split(separator, string) { typecheck('split', separator, ['regex', 'string']); typecheck('split', string, 'string'); return global_env.get('array->list')(string.split(separator)); - }, "(split separator string)\n\n Function create list by splitting string by separatar that can\n be a string or regular expression."), + }, "(split separator string)\n\n Function that creates a list by splitting string by separator which can\n be a string or regular expression."), // ------------------------------------------------------------------ replace: doc('replace', function replace(pattern, replacement, string) { typecheck('replace', pattern, ['regex', 'string']); typecheck('replace', replacement, ['string', 'function']); typecheck('replace', string, 'string'); return string.replace(pattern, replacement); - }, "(replace pattern replacement string)\n\n Function change pattern to replacement inside string. Pattern can be string\n or regex and replacement can be function or string."), + }, "(replace pattern replacement string)\n\n Function that changes pattern to replacement inside string. Pattern can be a string\n or regex and replacement can be function or string. See Javascript String.replace()."), // ------------------------------------------------------------------ match: doc('match', function match(pattern, string) { typecheck('match', pattern, ['regex', 'string']); typecheck('match', string, 'string'); var m = string.match(pattern); return m ? global_env.get('array->list')(m) : false; - }, "(match pattern string)\n\n function return match object from JavaScript as list or #f if not match."), + }, "(match pattern string)\n\n Function that returns a match object from JavaScript as a list or #f if no match."), // ------------------------------------------------------------------ search: doc('search', function search(pattern, string) { typecheck('search', pattern, ['regex', 'string']); typecheck('search', string, 'string'); return string.search(pattern); - }, "(search pattern string)\n\n Function return first found index of the pattern inside a string"), + }, "(search pattern string)\n\n Function that returns the first found index of the pattern inside a string."), // ------------------------------------------------------------------ repr: doc('repr', function repr(obj, quote) { return toString(obj, quote); - }, "(repr obj)\n\n Function return string LIPS representation of an object as string."), + }, "(repr obj)\n\n Function that returns a LIPS code representation of the object as a string."), // ------------------------------------------------------------------ 'escape-regex': doc('escape-regex', function (string) { typecheck('escape-regex', string, 'string'); return escape_regex(string.valueOf()); - }, "(escape-regex string)\n\n Function return new string where all special operators used in regex,\n are escaped with slash so they can be used in RegExp constructor\n to match literal string"), + }, "(escape-regex string)\n\n Function that returns a new string where all special operators used in regex,\n are escaped with backslashes so they can be used in the RegExp constructor\n to match a literal string."), // ------------------------------------------------------------------ env: doc('env', function env(env) { env = env || this; @@ -16447,7 +17242,7 @@ } return result; - }, "(env)\n (env obj)\n\n Function return list of values (functions, macros and variables)\n inside environment and it's parents."), + }, "(env)\n (env obj)\n\n Function that returns a list of names (functions, macros and variables)\n that are bound in the current environment or one of its parents."), // ------------------------------------------------------------------ 'new': doc('new', function (obj) { for (var _len28 = arguments.length, args = new Array(_len28 > 1 ? _len28 - 1 : 0), _key28 = 1; _key28 < _len28; _key28++) { @@ -16459,34 +17254,34 @@ }))); return instance; - }, "(new obj . args)\n\n Function create new JavaScript instance of an object."), + }, "(new obj . args)\n\n Function that creates new JavaScript instance of an object."), // ------------------------------------------------------------------ - 'typecheck': doc(typecheck, "(typecheck label value type [position])\n\n Function check type and throw exception if type don't match.\n Type can be string or list of strings. Position optional argument\n is used to created proper error message."), + 'typecheck': doc(typecheck, "(typecheck label value type [position])\n\n Checks the type of value and errors if the type is not one allowed.\n Type can be string or list of strings. The position optional argument\n is used to create a proper error message for the nth argument of function calls."), // ------------------------------------------------------------------ 'unset-special!': doc('unset-special!', function (symbol) { typecheck('remove-special!', symbol, 'string'); delete specials.remove(symbol.valueOf()); - }, "(unset-special! name)\n\n Function remove special symbol from parser. Added by `set-special!`,\n name must be a string."), + }, "(unset-special! name)\n\n Function that removes a special symbol from parser added by `set-special!`,\n name must be a string."), // ------------------------------------------------------------------ 'set-special!': doc('set-special!', function (seq, name) { var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : specials.LITERAL; typecheck('set-special!', seq, 'string', 1); typecheck('set-special!', name, 'symbol', 2); specials.append(seq.valueOf(), name, type); - }, "(set-special! symbol name [type])\n\n Add special symbol to the list of transforming operators by the parser.\n e.g.: `(add-special! \"#\" 'x)` will allow to use `#(1 2 3)` and it will be\n transformed into (x (1 2 3)) so you can write x macro that will process\n the list. 3rd argument is optional and it can be constant value\n lips.specials.SPLICE if this constant is used it will transform\n `#(1 2 3)` into (x 1 2 3) that is required by # that define vectors."), + }, "(set-special! symbol name [type])\n\n Add a special symbol to the list of transforming operators by the parser.\n e.g.: `(add-special! \"#\" 'x)` will allow to use `#(1 2 3)` and it will be\n transformed into (x (1 2 3)) so you can write x macro that will process\n the list. 3rd argument is optional, and it can be one of two values:\n lips.specials.LITERAL, which is the default behavior, or\n lips.specials.SPLICE which causes the value to be unpacked into the expression.\n This can be used for e.g. to make `#(1 2 3)` into (x 1 2 3) that is needed\n by # that defines vectors."), // ------------------------------------------------------------------ 'get': get, '.': get, // ------------------------------------------------------------------ - 'unbind': doc(unbind, "(unbind fn)\n\n Function remove bidning from function so you can get props from it."), + 'unbind': doc(unbind, "(unbind fn)\n\n Function that removes the weak 'this' binding from a function so you\n can get properties from the actual function object."), // ------------------------------------------------------------------ - type: doc(type, "(type object)\n\n Function return type of an object as string."), + type: doc(type, "(type object)\n\n Function that returns the type of an object as string."), // ------------------------------------------------------------------ 'debugger': doc('debugger', function () { /* eslint-disable */ debugger; /* eslint-enable */ - }, "(debugger)\n\n Function stop JavaScript code in debugger."), + }, "(debugger)\n\n Function that triggers the JavaScript debugger (e.g. the browser devtools)\n using the \"debugger;\" statement. If a debugger is not running this\n function does nothing."), // ------------------------------------------------------------------ 'in': doc('in', function (a, b) { if (a instanceof LSymbol || a instanceof LString || a instanceof LNumber) { @@ -16494,19 +17289,19 @@ } return a in unbox(b); - }, "(in key value)\n\n Function use is in operator to check if value is in object."), + }, "(in key value)\n\n Function that uses the Javascript \"in\" operator to check if key is\n a valid property in the value."), // ------------------------------------------------------------------ 'instanceof': doc('instanceof', function (type, obj) { return obj instanceof unbind(type); - }, "(instanceof type obj)\n\n Function check of object is instance of object."), + }, "(instanceof type obj)\n\n Predicate that tests if the obj is an instance of type."), // ------------------------------------------------------------------ - 'prototype?': doc('prototype?', is_prototype, "(prototype? obj)\n\n Function check if value is JavaScript Object prototype."), + 'prototype?': doc('prototype?', is_prototype, "(prototype? obj)\n\n Predicate that tests if value is a valid JavaScript prototype,\n i.e. calling (new) with it will not throw ' is not a constructor'."), // ------------------------------------------------------------------ 'macro?': doc('macro?', function (obj) { return obj instanceof Macro; - }, "(macro? expression)\n\n Function check if value is a macro."), + }, "(macro? expression)\n\n Predicate that tests if value is a macro."), // ------------------------------------------------------------------ - 'function?': doc('function?', is_function, "(function? expression)\n\n Function check if value is a function."), + 'function?': doc('function?', is_function, "(function? expression)\n\n Predicate that tests if value is a callable function."), // ------------------------------------------------------------------ 'real?': doc('real?', function (value) { if (type(value) !== 'number') { @@ -16518,57 +17313,57 @@ } return LNumber.isFloat(value); - }, "(real? number)\n\n Function check if value is real number."), + }, "(real? number)\n\n Predicate that tests if value is a real number (not complex)."), // ------------------------------------------------------------------ 'number?': doc('number?', function (x) { return Number.isNaN(x) || LNumber.isNumber(x); - }, "(number? expression)\n\n Function check if value is a number or NaN value."), + }, "(number? expression)\n\n Predicate that tests if value is a number or NaN value."), // ------------------------------------------------------------------ 'string?': doc('string?', function (obj) { return LString.isString(obj); - }, "(string? expression)\n\n Function check if value is a string."), + }, "(string? expression)\n\n Predicate that tests if value is a string."), // ------------------------------------------------------------------ 'pair?': doc('pair?', function (obj) { return obj instanceof Pair; - }, "(pair? expression)\n\n Function check if value is a pair or list structure."), + }, "(pair? expression)\n\n Predicate that tests if value is a pair or list structure."), // ------------------------------------------------------------------ 'regex?': doc('regex?', function (obj) { return obj instanceof RegExp; - }, "(regex? expression)\n\n Function check if value is regular expression."), + }, "(regex? expression)\n\n Predicate that tests if value is a regular expression."), // ------------------------------------------------------------------ 'null?': doc('null?', function (obj) { return is_null(obj); - }, "(null? expression)\n\n Function check if value is nulish."), + }, "(null? expression)\n\n Predicate that tests if value is null-ish (i.e. undefined, nil, or Javascript null)."), // ------------------------------------------------------------------ 'boolean?': doc('boolean?', function (obj) { return typeof obj === 'boolean'; - }, "(boolean? expression)\n\n Function check if value is boolean."), + }, "(boolean? expression)\n\n Predicate that tests if value is a boolean (#t or #f)."), // ------------------------------------------------------------------ 'symbol?': doc('symbol?', function (obj) { return obj instanceof LSymbol; - }, "(symbol? expression)\n\n Function check if value is LIPS symbol"), + }, "(symbol? expression)\n\n Predicate that tests if value is a LIPS symbol."), // ------------------------------------------------------------------ 'array?': doc('array?', function (obj) { return obj instanceof Array; - }, "(array? expression)\n\n Function check if value is an arrray."), + }, "(array? expression)\n\n Predicate that tests if value is an arrray."), // ------------------------------------------------------------------ 'object?': doc('object?', function (obj) { return obj !== _nil && obj !== null && !(obj instanceof LCharacter) && !(obj instanceof RegExp) && !(obj instanceof LString) && !(obj instanceof Pair) && !(obj instanceof LNumber) && _typeof(obj) === 'object' && !(obj instanceof Array); - }, "(object? expression)\n\n Function check if value is an plain object."), + }, "(object? expression)\n\n Predicate that tests if value is an plain object (not another LIPS type)."), // ------------------------------------------------------------------ flatten: doc('flatten', function flatten(list) { typecheck('flatten', list, 'pair'); return list.flatten(); - }, "(flatten list)\n\n Return shallow list from tree structure (pairs)."), + }, "(flatten list)\n\n Returns a shallow list from tree structure (pairs)."), // ------------------------------------------------------------------ 'array->list': doc('array->list', function (array) { typecheck('array->list', array, 'array'); return Pair.fromArray(array); - }, "(array->list array)\n\n Function convert JavaScript array to LIPS list."), + }, "(array->list array)\n\n Function that converts a JavaScript array to a LIPS cons list."), // ------------------------------------------------------------------ - 'tree->array': doc('tree->array', to_array('tree->array', true), "(tree->array list)\n\n Function convert LIPS list structure into JavaScript array."), + 'tree->array': doc('tree->array', to_array('tree->array', true), "(tree->array list)\n\n Function that converts a LIPS cons tree structure into a JavaScript array."), // ------------------------------------------------------------------ - 'list->array': doc('list->array', to_array('list->array'), "(list->array list)\n\n Function convert LIPS list into JavaScript array."), + 'list->array': doc('list->array', to_array('list->array'), "(list->array list)\n\n Function that converts a LIPS list into a JavaScript array."), // ------------------------------------------------------------------ apply: doc('apply', function apply(fn) { for (var _len29 = arguments.length, args = new Array(_len29 > 1 ? _len29 - 1 : 0), _key29 = 1; _key29 < _len29; _key29++) { @@ -16580,7 +17375,7 @@ typecheck('apply', last, ['pair', 'nil'], args.length + 2); args = args.concat(global_env.get('list->array').call(this, last)); return fn.apply(this, prepare_fn_args(fn, args)); - }, "(apply fn list)\n\n Function that call function with list of arguments."), + }, "(apply fn list)\n\n Function that calls fn with the list of arguments."), // ------------------------------------------------------------------ length: doc('length', function length(obj) { if (!obj || obj === _nil) { @@ -16594,7 +17389,7 @@ if ("length" in obj) { return obj.length; } - }, "(length expression)\n\n Function return length of the object, the object can be list\n or any object that have length property."), + }, "(length expression)\n\n Function that returns the length of the object. The object can be a LIPS\n list or any object that has a \"length\" property. Returns undefined if the\n length could not be found."), // ------------------------------------------------------------------ 'string->number': doc('string->number', function (arg) { var radix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; @@ -16620,7 +17415,7 @@ } return false; - }, "(string->number number [radix])\n\n Function convert string to number."), + }, "(string->number number [radix])\n\n Function that parses a string into a number."), // ------------------------------------------------------------------ 'try': doc(new Macro('try', function (code, _ref39) { var _this24 = this; @@ -16695,14 +17490,14 @@ _next(result, resolve); } }); - }), "(try expr (catch (e) code))\n (try expr (catch (e) code) (finally code))\n (try expr (finally code))\n\n Macro execute user code and catch exception. If catch is provided\n it's executed when expression expr throw error. If finally is provide\n it's always executed at the end."), + }), "(try expr (catch (e) code))\n (try expr (catch (e) code) (finally code))\n (try expr (finally code))\n\n Macro that executes expr and catches any exceptions thrown. If catch is provided\n it's executed when an error is thown. If finally is provided it's always executed\n at the end."), // ------------------------------------------------------------------ 'raise': doc('raise', function (obj) { throw obj; - }, "(raise obj)\n\n Throws new exception with given object."), + }, "(raise obj)\n\n Throws the object verbatim (no wrapping an a new Error)."), 'throw': doc('throw', function (message) { throw new Error(message); - }, "(throw string)\n\n Throws new expection."), + }, "(throw string)\n\n Throws a new exception."), // ------------------------------------------------------------------ find: doc('find', function find(arg, list) { typecheck('find', arg, ['regex', 'function']); @@ -16720,7 +17515,7 @@ return find(arg, list.cdr); }); - }, "(find fn list)\n (find regex list)\n\n Higher order Function find first value for which function return true.\n If called with regex it will create matcher function."), + }, "(find fn list)\n (find regex list)\n\n Higher-order function that finds the first value for which fn return true.\n If called with a regex it will create a matcher function."), // ------------------------------------------------------------------ 'for-each': doc('for-each', function (fn) { var _global_env$get2; @@ -16742,7 +17537,7 @@ if (is_promise(ret)) { return ret.then(function () {}); } - }, "(for-each fn . lists)\n\n Higher order function that call function `fn` by for each\n value of the argument. If you provide more then one list as argument\n it will take each value from each list and call `fn` function\n with that many argument as number of list arguments."), + }, "(for-each fn . lists)\n\n Higher-order function that calls function `fn` on each\n value of the argument. If you provide more than one list\n it will take each value from each list and call `fn` function\n with that many arguments as number of list arguments."), // ------------------------------------------------------------------ map: doc('map', function map(fn) { var _this25 = this; @@ -16784,7 +17579,7 @@ return new Pair(head, rest); }); }); - }, "(map fn . lists)\n\n Higher order function that call function `fn` by for each\n value of the argument. If you provide more then one list as argument\n it will take each value from each list and call `fn` function\n with that many argument as number of list arguments. The return\n values of the function call is acumulated in result list and\n returned by the call to map."), + }, "(map fn . lists)\n\n Higher-order function that calls function `fn` with each\n value of the list. If you provide more then one list as argument\n it will take each value from each list and call `fn` function\n with that many argument as number of list arguments. The return\n values of the fn calls are acumulated in a result list and\n returned by map."), // ------------------------------------------------------------------ 'list?': doc('list?', function (obj) { var node = obj; @@ -16804,7 +17599,7 @@ node = node.cdr; } - }, "(list? obj)\n\n Function test if value is proper linked list structure.\n The car of each pair can be any value. It return false on cycles.\""), + }, "(list? obj)\n\n Predicate that tests if value is a proper linked list structure.\n The car of each pair can be any value. It returns false on cyclic lists.\""), // ------------------------------------------------------------------ some: doc('some', function some(fn, list) { typecheck('some', fn, 'function'); @@ -16817,7 +17612,7 @@ return value || some(fn, list.cdr); }); } - }, "(some fn list)\n\n Higher order function that call argument on each element of the list.\n It stops when function fn return true for a value if so it will\n return true. If none of the values give true, the function return false"), + }, "(some fn list)\n\n Higher-order function that calls fn on each element of the list.\n It stops and returns true when fn returns true for a value.\n If none of the values give true, some will return false.\n Analagous to Python any(map(fn, list))."), // ------------------------------------------------------------------ fold: doc('fold', fold('fold', function (fold, fn, init) { for (var _len32 = arguments.length, lists = new Array(_len32 > 3 ? _len32 - 3 : 0), _key32 = 3; _key32 < _len32; _key32++) { @@ -16843,7 +17638,7 @@ return l.car; })).concat([value])); }); - }), "(fold fn init . lists)\n\n Function fold is reverse of the reduce. it call function `fn`\n on each elements of the list and return single value.\n e.g. it call (fn a1 b1 (fn a2 b2 (fn a3 b3 '())))\n for: (fold fn '() alist blist)"), + }), "(fold fn init . lists)\n\n Function fold is left-to-right reversal of reduce. It call `fn`\n on each pair of elements of the list and returns a single value.\n e.g. it computes (fn 'a 'x (fn 'b 'y (fn 'c 'z 'foo)))\n for: (fold fn 'foo '(a b c) '(x y z))"), // ------------------------------------------------------------------ pluck: doc('pluck', function pluck() { for (var _len33 = arguments.length, keys = new Array(_len33), _key33 = 0; _key33 < _len33; _key33++) { @@ -16871,7 +17666,7 @@ }); return result; }; - }, "(pluck . string)\n\n If called with single string it will return function that will return\n key from object. If called with more then one argument function will\n return new object by taking all properties from given object."), + }, "(pluck . strings)\n\n If called with a single string it will return a function that when\n called with an object will return that key from the object.\n If called with more then one string the returned function will\n create a new object by copying all properties from the given object."), // ------------------------------------------------------------------ reduce: doc('reduce', fold('reduce', function (reduce, fn, init) { var _this26 = this; @@ -16898,7 +17693,7 @@ return l.cdr; })))); }); - }), "(reduce fn init list . lists)\n\n Higher order function take each element of the list and call\n the function with result of previous call or init and next element\n on the list until each element is processed and return single value\n as result of last call to `fn` function.\n e.g. it call (fn a3 b3 (fn a2 b2 (fn a1 b1 init)))\n for (reduce fn init alist blist)"), + }), "(reduce fn init list . lists)\n\n Higher-order function that takes each element of the list and calls\n the fn with result of previous call or init and the next element\n of the list until each element is processed, and returns a single value\n as result of last call to `fn` function.\n e.g. it computes (fn 'c 'z (fn 'b 'y (fn 'a 'x 'foo)))\n for: (reduce fn 'foo '(a b c) '(x y z))"), // ------------------------------------------------------------------ filter: doc('filter', function filter(arg, list) { typecheck('filter', arg, ['regex', 'function']); @@ -16922,11 +17717,11 @@ var item = array[i]; return unpromise(fn(item), next); }(0); - }, "(filter fn list)\n (filter regex list)\n\n Higher order function that call `fn` for each element of the list\n and return list for only those elements for which funtion return\n true value. If called with regex it will create matcher function."), + }, "(filter fn list)\n (filter regex list)\n\n Higher-order function that calls `fn` for each element of the list\n and return a new list for only those elements for which fn returns\n a truthy value. If called with a regex it will create a matcher function."), // ------------------------------------------------------------------ - compose: doc(compose, "(compose . fns)\n\n Higher order function and create new function that apply all functions\n From right to left and return it's value. Reverse of compose.\n e.g.:\n ((compose (curry + 2) (curry * 3)) 3)\n 11"), - pipe: doc(pipe, "(pipe . fns)\n\n Higher order function and create new function that apply all functions\n From left to right and return it's value. Reverse of compose.\n e.g.:\n ((pipe (curry + 2) (curry * 3)) 3)\n 15"), - curry: doc(curry, "(curry fn . args)\n\n Higher order function that create curried version of the function.\n The result function will have parially applied arguments and it\n will keep returning functions until all arguments are added\n\n e.g.:\n (define (add a b c d) (+ a b c d))\n (define add1 (curry add 1))\n (define add12 (add 2))\n (display (add12 3 4))"), + compose: doc(compose, "(compose . fns)\n\n Higher-order function that creates a new function that applies all functions\n from right to left and returns the last value. Reverse of pipe.\n e.g.:\n ((compose (curry + 2) (curry * 3)) 10) --> (+ 2 (* 3 10)) --> 32"), + pipe: doc(pipe, "(pipe . fns)\n\n Higher-order function that creates a new function that applies all functions\n from left to right and returns the last value. Reverse of compose.\n e.g.:\n ((pipe (curry + 2) (curry * 3)) 10) --> (* 3 (+ 2 10)) --> 36"), + curry: doc(curry, "(curry fn . args)\n\n Higher-order function that creates a curried version of the function.\n The result function will have parially applied arguments and it\n will keep returning one-argument functions until all arguments are provided,\n then it calls the original function with the accumulated arguments.\n\n e.g.:\n (define (add a b c d) (+ a b c d))\n (define add1 (curry add 1))\n (define add12 (add 2))\n (display (add12 3 4))"), // ------------------------------------------------------------------ // Numbers // ------------------------------------------------------------------ @@ -16939,7 +17734,7 @@ return args.reduce(function (result, item) { return result.gcd(item); }); - }, "(gcd n1 n2 ...)\n\n Function return the greatest common divisor of their arguments."), + }, "(gcd n1 n2 ...)\n\n Function that returns the greatest common divisor of the arguments."), // ------------------------------------------------------------------ lcm: doc('lcm', function lcm() { for (var _len36 = arguments.length, args = new Array(_len36), _key37 = 0; _key37 < _len36; _key37++) { @@ -16963,24 +17758,24 @@ } return LNumber(a); - }, "(lcm n1 n2 ...)\n\n Function return the least common multiple of their arguments."), + }, "(lcm n1 n2 ...)\n\n Function that returns the least common multiple of the arguments."), // ------------------------------------------------------------------ 'odd?': doc('odd?', single_math_op(function (num) { return LNumber(num).isOdd(); - }), "(odd? number)\n\n Function check if number os odd."), + }), "(odd? number)\n\n Checks if number is odd."), // ------------------------------------------------------------------ 'even?': doc('even?', single_math_op(function (num) { return LNumber(num).isEven(); - }), "(even? number)\n\n Function check if number is even."), + }), "(even? number)\n\n Checks if number is even."), // ------------------------------------------------------------------ // math functions '*': doc('*', reduce_math_op(function (a, b) { return LNumber(a).mul(b); - }, LNumber(1)), "(* . numbers)\n\n Multiplicate all numbers passed as arguments. If single value is passed\n it will return that value."), + }, LNumber(1)), "(* . numbers)\n\n Multiplies all numbers passed as arguments. If single value is passed\n it will return that value."), // ------------------------------------------------------------------ '+': doc('+', reduce_math_op(function (a, b) { return LNumber(a).add(b); - }, LNumber(0)), "(+ . numbers)\n\n Sum all numbers passed as arguments. If single value is passed it will\n return that value."), + }, LNumber(0)), "(+ . numbers)\n\n Sums all numbers passed as arguments. If single value is passed it will\n return that value."), // ------------------------------------------------------------------ '-': doc('-', function () { for (var _len37 = arguments.length, args = new Array(_len37), _key38 = 0; _key38 < _len37; _key38++) { @@ -17002,7 +17797,7 @@ return LNumber(a).sub(b); })); } - }, "(- n1 n2 ...)\n (- n)\n\n Substract number passed as argument. If only one argument is passed\n it will negate the value."), + }, "(- n1 n2 ...)\n (- n)\n\n Subtracts n2 and subsequent numbers from n1. If only one argument is passed\n it will negate the value."), // ------------------------------------------------------------------ '/': doc('/', function () { for (var _len38 = arguments.length, args = new Array(_len38), _key39 = 0; _key39 < _len38; _key39++) { @@ -17022,11 +17817,11 @@ return args.reduce(binary_math_op(function (a, b) { return LNumber(a).div(b); })); - }, "(/ n1 n2 ...)\n (/ n)\n\n Divide number passed as arguments one by one. If single argument\n is passed it will calculate (/ 1 n1)."), + }, "(/ n1 n2 ...)\n (/ n)\n\n Divides n1 by n2 and subsequent arguments one by one. If single argument\n is passed it will calculate (/ 1 n)."), // ------------------------------------------------------------------ abs: doc('abs', single_math_op(function (n) { return LNumber(n).abs(); - }), "(abs number)\n\n Function create absolute value from number."), + }), "(abs number)\n\n Function that returns the absolute value (magnitude) of number."), // ------------------------------------------------------------------ truncate: doc('truncate', function (n) { typecheck('truncate', n, 'number'); @@ -17040,11 +17835,11 @@ } return n; - }, "(truncate n)\n\n Function return integer value from real number."), + }, "(truncate n)\n\n Function that returns the integer part (floor) of a real number."), // ------------------------------------------------------------------ sqrt: doc('sqrt', single_math_op(function (n) { return LNumber(n).sqrt(); - }), "(sqrt number)\n\n Function return square root of the number."), + }), "(sqrt number)\n\n Function that returns the square root of the number."), // ------------------------------------------------------------------ '**': doc('**', binary_math_op(function (a, b) { a = LNumber(a); @@ -17055,20 +17850,20 @@ } return a.pow(b); - }), "(** a b)\n\n Function calculate number a to to the power of b."), + }), "(** a b)\n\n Function that calculates number a to to the power of b."), // ------------------------------------------------------------------ '1+': doc('1+', single_math_op(function (number) { return LNumber(number).add(1); - }), "(1+ number)\n\n Function add 1 to the number and return result."), + }), "(1+ number)\n\n Function that adds 1 to the number and return result."), // ------------------------------------------------------------------ '1-': doc(single_math_op(function (number) { return LNumber(number).sub(1); - }), "(1- number)\n\n Function substract 1 from the number and return result."), + }), "(1- number)\n\n Function that subtracts 1 from the number and return result."), // ------------------------------------------------------------------ '%': doc('%', function (a, b) { typecheck_args('%', [a, b], 'number'); return LNumber(a).rem(b); - }, "(% n1 n2)\n\n Function get reminder of it's arguments."), + }, "(% n1 n2)\n\n Function returns the remainder of n1/n2 (modulo)."), // ------------------------------------------------------------------ // Booleans '==': doc('==', function () { @@ -17080,7 +17875,7 @@ return seq_compare(function (a, b) { return LNumber(a).cmp(b) === 0; }, args); - }, "(== x1 x2 ...)\n\n Function compare its numerical arguments and check if they are equal"), + }, "(== x1 x2 ...)\n\n Function that compares its numerical arguments and checks if they are all equal."), // ------------------------------------------------------------------ '>': doc('>', function () { for (var _len40 = arguments.length, args = new Array(_len40), _key41 = 0; _key41 < _len40; _key41++) { @@ -17091,7 +17886,7 @@ return seq_compare(function (a, b) { return LNumber(a).cmp(b) === 1; }, args); - }, "(> x1 x2 ...)\n\n Function compare its numerical arguments and check if they are\n monotonically increasing"), + }, "(> x1 x2 x3 ...)\n\n Function that compares its numerical arguments and checks if they are\n monotonically decreasing, i.e. x1 > x2 and x2 > x3 and so on."), // ------------------------------------------------------------------ '<': doc('<', function () { for (var _len41 = arguments.length, args = new Array(_len41), _key42 = 0; _key42 < _len41; _key42++) { @@ -17102,7 +17897,7 @@ return seq_compare(function (a, b) { return LNumber(a).cmp(b) === -1; }, args); - }, "(< x1 x2 ...)\n\n Function compare its numerical arguments and check if they are\n monotonically decreasing"), + }, "(< x1 x2 ...)\n\n Function that compares its numerical arguments and checks if they are\n monotonically increasing, i.e. x1 < x2 and x2 < x3 and so on."), // ------------------------------------------------------------------ '<=': doc('<=', function () { for (var _len42 = arguments.length, args = new Array(_len42), _key43 = 0; _key43 < _len42; _key43++) { @@ -17113,7 +17908,7 @@ return seq_compare(function (a, b) { return [0, -1].includes(LNumber(a).cmp(b)); }, args); - }, "(<= x1 x2 ...)\n\n Function compare its numerical arguments and check if they are\n monotonically nonincreasing"), + }, "(<= x1 x2 ...)\n\n Function that compares its numerical arguments and checks if they are\n monotonically nondecreasing, i.e. x1 <= x2 and x2 <= x3 and so on."), // ------------------------------------------------------------------ '>=': doc('>=', function () { for (var _len43 = arguments.length, args = new Array(_len43), _key44 = 0; _key44 < _len43; _key44++) { @@ -17124,9 +17919,9 @@ return seq_compare(function (a, b) { return [0, 1].includes(LNumber(a).cmp(b)); }, args); - }, "(>= x1 x2 ...)\n\n Function compare its numerical arguments and check if they are\n monotonically nondecreasing"), + }, "(>= x1 x2 ...)\n\n Function that compares its numerical arguments and checks if they are\n monotonically nonincreasing, i.e. x1 >= x2 and x2 >= x3 and so on."), // ------------------------------------------------------------------ - 'eq?': doc('eq?', equal, "(eq? a b)\n\n Function compare two values if they are identical."), + 'eq?': doc('eq?', equal, "(eq? a b)\n\n Function that compares two values if they are identical."), // ------------------------------------------------------------------ or: doc(new Macro('or', function (code, _ref40) { var dynamic_scope = _ref40.dynamic_scope, @@ -17172,7 +17967,7 @@ return unpromise(value, next); } }(); - }), "(or . expressions)\n\n Macro execute the values one by one and return the one that is truthy value.\n If there are no expression that evaluate to true it return false."), + }), "(or . expressions)\n\n Macro that executes the values one by one and returns the first that is\n a truthy value. If there are no expressions that evaluate to true it\n returns false."), // ------------------------------------------------------------------ and: doc(new Macro('and', function (code) { var _ref41 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, @@ -17220,42 +18015,42 @@ return unpromise(value, next); } }(); - }), "(and . expressions)\n\n Macro evalute each expression in sequence if any value return false it will\n return false. If each value return true it will return the last value.\n If it's called without arguments it will return true."), + }), "(and . expressions)\n\n Macro that evalutes each expression in sequence and if any value returns false\n it will stop and return false. If each value returns true it will return the\n last value. If it's called without arguments it will return true."), // bit operations '|': doc('|', function (a, b) { return LNumber(a).or(b); - }, "(| a b)\n\n Function calculate or bit operation."), + }, "(| a b)\n\n Function that calculates the bitwise or operation."), '&': doc('&', function (a, b) { return LNumber(a).and(b); - }, "(& a b)\n\n Function calculate and bit operation."), + }, "(& a b)\n\n Function that calculates the bitwise and operation."), '~': doc('~', function (a) { return LNumber(a).neg(); - }, "(~ number)\n\n Function negate the value."), + }, "(~ number)\n\n Function that calculates the bitwise inverse (flip all the bits)."), '>>': doc('>>', function (a, b) { return LNumber(a).shr(b); - }, "(>> a b)\n\n Function right shit the value a by value b."), + }, "(>> a b)\n\n Function that right shifts the value a by value b bits."), '<<': doc('<<', function (a, b) { return LNumber(a).shl(b); - }, "(<< a b)\n\n Function left shit the value a by value b."), + }, "(<< a b)\n\n Function that left shifts the value a by value b bits."), not: doc('not', function not(value) { if (is_null(value)) { return true; } return !value; - }, "(not object)\n\n Function return negation of the argument.") + }, "(not object)\n\n Function that returns the Boolean negation of its argument.") }, undefined, 'global'); var user_env = global_env.inherit('user-env'); // ------------------------------------------------------------------------- function set_interaction_env(interaction, internal) { interaction.constant('**internal-env**', internal); - interaction.doc('**internal-env**', "**internal-env**\n\n Constant used to hide stdin, stdout and stderr so they don't interfere\n with variables with the same name. Constants are internal type\n of variables that can't be redefined, defining variable with same name\n will throw an error."); + interaction.doc('**internal-env**', "**internal-env**\n\n Constant used to hide stdin, stdout and stderr so they don't interfere\n with variables with the same name. Constants are an internal type\n of variable that can't be redefined, defining a variable with the same name\n will throw an error."); global_env.set('**interaction-environment**', interaction); } // ------------------------------------------------------------------------- set_interaction_env(user_env, internal_env); - global_env.doc('**interaction-environment**', "**interaction-environment**\n\n Internal dynamic, global variable used to find interpreter environment.\n It's used so the read and write functions can locate **internal-env**\n that contain references to stdin, stdout and stderr."); // ------------------------------------------------------------------------- + global_env.doc('**interaction-environment**', "**interaction-environment**\n\n Internal dynamic, global variable used to find interpreter environment.\n It's used so the read and write functions can locate **internal-env**\n that contains the references to stdin, stdout and stderr."); // ------------------------------------------------------------------------- (function () { var map = { @@ -17269,7 +18064,7 @@ if (value instanceof LNumber) { return value[fn](); } - }, "(".concat(name, " number)\n\n Function calculate ").concat(name, " of a number."))); + }, "(".concat(name, " number)\n\n Function that calculates the ").concat(name, " of a number."))); }); })(); // ------------------------------------------------------------------------- // ref: https://stackoverflow.com/a/4331218/387194 @@ -17329,7 +18124,7 @@ return list.cdr; } }, arg); - }, "(".concat(name, " arg)\n\n Function calculate ").concat(code))); + }, "(".concat(name, " arg)\n\n Function that calculates ").concat(code))); }); // ----------------------------------------------------------------------------- function reversseFind(dir, fn) { @@ -17402,7 +18197,7 @@ typecheck('require.resolve', path, 'string'); var name = path.valueOf(); return nodeRequire.resolve(name); - }, "(require.resolve path)\n\n Return path relative the current module.")); // --------------------------------------------------------------------- + }, "(require.resolve path)\n\n Returns the path relative to the current module.\n\n Only available when LIPS is running under Node.js.")); // --------------------------------------------------------------------- global_env.set('require', doc('require', function (module) { typecheck('require', module, 'string'); @@ -17427,7 +18222,7 @@ } return patch_value(value, global); - }, "(require module)\n\n Function to be used inside Node.js to import the module.")); + }, "(require module)\n\n Function used inside Node.js to import a module.")); case 21: case "end": @@ -17461,12 +18256,12 @@ } if (is_function(expected)) { - return "Invalid type got ".concat(got).concat(postfix); + return "Invalid type: got ".concat(got).concat(postfix); } if (expected instanceof Array) { if (expected.length === 1) { - expected = expected[0]; + expected = "a" + ("aeiou".includes(expected[0].toLowerCase()) ? "n " : " ") + expected[0]; } else { var last = expected[expected.length - 1]; expected = expected.slice(0, -1).join(', ') + ' or ' + last; @@ -18786,10 +19581,10 @@ var banner = function () { // Rollup tree-shaking is removing the variable if it's normal string because - // obviously 'Wed, 06 Sep 2023 20:32:14 +0000' == '{{' + 'DATE}}'; can be removed + // obviously 'Fri, 10 Nov 2023 16:25:41 +0000' == '{{' + 'DATE}}'; can be removed // but disabling Tree-shaking is adding lot of not used code so we use this // hack instead - var date = LString('Wed, 06 Sep 2023 20:32:14 +0000').valueOf(); + var date = LString('Fri, 10 Nov 2023 16:25:41 +0000').valueOf(); var _date = date === '{{' + 'DATE}}' ? new Date() : new Date(date); @@ -18835,7 +19630,7 @@ var lips = { version: 'DEV', banner: banner, - date: 'Wed, 06 Sep 2023 20:32:14 +0000', + date: 'Fri, 10 Nov 2023 16:25:41 +0000', exec: exec, // unwrap async generator into Promise parse: compose(uniterate_async, parse), diff --git a/dist/lips.min.js b/dist/lips.min.js index cac42566c..b14491673 100644 --- a/dist/lips.min.js +++ b/dist/lips.min.js @@ -31,15 +31,15 @@ * Copyright (c) 2014-present, Facebook, Inc. * released under MIT license * - * build: Wed, 06 Sep 2023 20:32:14 +0000 + * build: Fri, 10 Nov 2023 16:25:41 +0000 */ -(function(e,t){typeof exports==="object"&&typeof module!=="undefined"?module.exports=t():typeof define==="function"&&define.amd?define(t):(e=typeof globalThis!=="undefined"?globalThis:e||self,e.lips=t())})(this,function(){"use strict";function i(e){if(e===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return e}function o(e,t){o=Object.setPrototypeOf||function e(t,r){t.__proto__=r;return t};return o(e,t)}function n(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));return true}catch(e){return false}}function p(e,t,r){if(n()){p=Reflect.construct}else{p=function e(t,r,n){var i=[null];i.push.apply(i,r);var u=Function.bind.apply(t,i);var a=new u;if(n)o(a,n.prototype);return a}}return p.apply(null,arguments)}function u(e,t){if(typeof t!=="function"&&t!==null){throw new TypeError("Super expression must either be null or a function")}e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:true,configurable:true}});Object.defineProperty(e,"prototype",{writable:false});if(t)o(e,t)}function _(e){"@babel/helpers - typeof";return _="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_(e)}function a(e,t){if(t&&(_(t)==="object"||typeof t==="function")){return t}else if(t!==void 0){throw new TypeError("Derived constructors may only return object or undefined")}return i(e)}function f(e){f=Object.setPrototypeOf?Object.getPrototypeOf:function e(t){return t.__proto__||Object.getPrototypeOf(t)};return f(e)}function r(e){if(Array.isArray(e))return e}function t(e){if(typeof Symbol!=="undefined"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function l(e,t){if(t==null||t>e.length)t=e.length;for(var r=0,n=new Array(t);r=0)continue;r[i]=e[i]}return r}function S(e,t){if(e==null)return{};var r=C(e,t);var n,i;if(Object.getOwnPropertySymbols){var u=Object.getOwnPropertySymbols(e);for(i=0;i=0)continue;if(!Object.prototype.propertyIsEnumerable.call(e,n))continue;r[n]=e[n]}}return r}function B(e,t){var r=e==null?null:typeof Symbol!=="undefined"&&e[Symbol.iterator]||e["@@iterator"];if(r==null)return;var n=[];var i=true;var u=false;var a,o;try{for(r=r.call(e);!(i=(a=r.next()).done);i=true){n.push(a.value);if(t&&n.length===t)break}}catch(e){u=true;o=e}finally{try{if(!i&&r["return"]!=null)r["return"]()}finally{if(u)throw o}}return n}function j(e,t){return r(e)||B(e,t)||h(e,t)||d()}function I(e){this.wrapped=e}function P(e){return new I(e)}function N(u){var a,o;function e(n,i){return new Promise(function(e,t){var r={key:n,arg:i,resolve:e,reject:t,next:null};if(o){o=o.next=r}else{a=o=r;s(n,i)}})}function s(t,e){try{var r=u[t](e);var n=r.value;var i=n instanceof I;Promise.resolve(i?n.wrapped:n).then(function(e){if(i){s(t==="return"?"return":"next",e);return}c(r.done?"return":"normal",e)},function(e){s("throw",e)})}catch(e){c("throw",e)}}function c(e,t){switch(e){case"return":a.resolve({value:t,done:true});break;case"throw":a.reject(t);break;default:a.resolve({value:t,done:false});break}a=a.next;if(a){s(a.key,a.arg)}else{o=null}}this._invoke=e;if(typeof u["return"]!=="function"){this["return"]=undefined}}N.prototype[typeof Symbol==="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this};N.prototype.next=function(e){return this._invoke("next",e)};N.prototype["throw"]=function(e){return this._invoke("throw",e)};N.prototype["return"]=function(e){return this._invoke("return",e)};function e(e){return function(){return new N(e.apply(this,arguments))}}function R(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e["default"]:e}var T={exports:{}};var $={exports:{}};(function(e){var t=function(a){var e=Object.prototype;var f=e.hasOwnProperty;var s;var o=typeof Symbol==="function"?Symbol:{};var i=o.iterator||"@@iterator";var c=o.asyncIterator||"@@asyncIterator";var p=o.toStringTag||"@@toStringTag";function r(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:true,configurable:true,writable:true});return e[t]}try{r({},"")}catch(e){r=function(e,t,r){return e[t]=r}}function _(e,t,r,n){var i=t&&t.prototype instanceof g?t:g;var u=Object.create(i.prototype);var a=new O(n||[]);u._invoke=F(e,r,a);return u}a.wrap=_;function d(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}var v="suspendedStart";var m="suspendedYield";var y="executing";var l="completed";var h={};function g(){}function n(){}function t(){}var b={};r(b,i,function(){return this});var w=Object.getPrototypeOf;var D=w&&w(w(S([])));if(D&&D!==e&&f.call(D,i)){b=D}var u=t.prototype=g.prototype=Object.create(b);n.prototype=t;r(u,"constructor",t);r(t,"constructor",n);n.displayName=r(t,p,"GeneratorFunction");function E(e){["next","throw","return"].forEach(function(t){r(e,t,function(e){return this._invoke(t,e)})})}a.isGeneratorFunction=function(e){var t=typeof e==="function"&&e.constructor;return t?t===n||(t.displayName||t.name)==="GeneratorFunction":false};a.mark=function(e){if(Object.setPrototypeOf){Object.setPrototypeOf(e,t)}else{e.__proto__=t;r(e,p,"GeneratorFunction")}e.prototype=Object.create(u);return e};a.awrap=function(e){return{__await:e}};function A(o,s){function c(e,t,r,n){var i=d(o[e],o,t);if(i.type==="throw"){n(i.arg)}else{var u=i.arg;var a=u.value;if(a&&typeof a==="object"&&f.call(a,"__await")){return s.resolve(a.__await).then(function(e){c("next",e,r,n)},function(e){c("throw",e,r,n)})}return s.resolve(a).then(function(e){u.value=e;r(u)},function(e){return c("throw",e,r,n)})}}var t;function e(r,n){function e(){return new s(function(e,t){c(r,n,e,t)})}return t=t?t.then(e,e):e()}this._invoke=e}E(A.prototype);r(A.prototype,c,function(){return this});a.AsyncIterator=A;a.async=function(e,t,r,n,i){if(i===void 0)i=Promise;var u=new A(_(e,t,r,n),i);return a.isGeneratorFunction(t)?u:u.next().then(function(e){return e.done?e.value:u.next()})};function F(a,o,s){var c=v;return function e(t,r){if(c===y){throw new Error("Generator is already running")}if(c===l){if(t==="throw"){throw r}return B()}s.method=t;s.arg=r;while(true){var n=s.delegate;if(n){var i=x(n,s);if(i){if(i===h)continue;return i}}if(s.method==="next"){s.sent=s._sent=s.arg}else if(s.method==="throw"){if(c===v){c=l;throw s.arg}s.dispatchException(s.arg)}else if(s.method==="return"){s.abrupt("return",s.arg)}c=y;var u=d(a,o,s);if(u.type==="normal"){c=s.done?l:m;if(u.arg===h){continue}return{value:u.arg,done:s.done}}else if(u.type==="throw"){c=l;s.method="throw";s.arg=u.arg}}}}function x(e,t){var r=e.iterator[t.method];if(r===s){t.delegate=null;if(t.method==="throw"){if(e.iterator["return"]){t.method="return";t.arg=s;x(e,t);if(t.method==="throw"){return h}}t.method="throw";t.arg=new TypeError("The iterator does not provide a 'throw' method")}return h}var n=d(r,e.iterator,t.arg);if(n.type==="throw"){t.method="throw";t.arg=n.arg;t.delegate=null;return h}var i=n.arg;if(!i){t.method="throw";t.arg=new TypeError("iterator result is not an object");t.delegate=null;return h}if(i.done){t[e.resultName]=i.value;t.next=e.nextLoc;if(t.method!=="return"){t.method="next";t.arg=s}}else{return i}t.delegate=null;return h}E(u);r(u,p,"Generator");r(u,i,function(){return this});r(u,"toString",function(){return"[object Generator]"});function C(e){var t={tryLoc:e[0]};if(1 in e){t.catchLoc=e[1]}if(2 in e){t.finallyLoc=e[2];t.afterLoc=e[3]}this.tryEntries.push(t)}function k(e){var t=e.completion||{};t.type="normal";delete t.arg;e.completion=t}function O(e){this.tryEntries=[{tryLoc:"root"}];e.forEach(C,this);this.reset(true)}a.keys=function(r){var n=[];for(var e in r){n.push(e)}n.reverse();return function e(){while(n.length){var t=n.pop();if(t in r){e.value=t;e.done=false;return e}}e.done=true;return e}};function S(t){if(t){var e=t[i];if(e){return e.call(t)}if(typeof t.next==="function"){return t}if(!isNaN(t.length)){var r=-1,n=function e(){while(++r=0;--t){var i=this.tryEntries[t];var u=i.completion;if(i.tryLoc==="root"){return e("end")}if(i.tryLoc<=this.prev){var a=f.call(i,"catchLoc");var o=f.call(i,"finallyLoc");if(a&&o){if(this.prev=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&f.call(n,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e){this.complete(r.completion,r.afterLoc);k(r);return h}}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if(n.type==="throw"){var i=n.arg;k(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){this.delegate={iterator:S(e),resultName:t,nextLoc:r};if(this.method==="next"){this.arg=s}return h}};return a}(e.exports);try{regeneratorRuntime=t}catch(e){if(typeof globalThis==="object"){globalThis.regeneratorRuntime=t}else{Function("r","regeneratorRuntime = r")(t)}}})($);(function(e){e.exports=$.exports})(T);var z=R(T.exports);var V=typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{};var J=[];var G=[];var W=typeof Uint8Array!=="undefined"?Uint8Array:Array;var H=false;function Q(){H=true;var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var t=0,r=e.length;t0){throw new Error("Invalid string. Length must be a multiple of 4")}u=e[o-2]==="="?2:e[o-1]==="="?1:0;a=new W(o*3/4-u);n=u>0?o-4:o;var s=0;for(t=0,r=0;t>16&255;a[s++]=i>>8&255;a[s++]=i&255}if(u===2){i=G[e.charCodeAt(t)]<<2|G[e.charCodeAt(t+1)]>>4;a[s++]=i&255}else if(u===1){i=G[e.charCodeAt(t)]<<10|G[e.charCodeAt(t+1)]<<4|G[e.charCodeAt(t+2)]>>2;a[s++]=i>>8&255;a[s++]=i&255}return a}function K(e){return J[e>>18&63]+J[e>>12&63]+J[e>>6&63]+J[e&63]}function X(e,t,r){var n;var i=[];for(var u=t;us?s:o+a))}if(n===1){t=e[r-1];i+=J[t>>2];i+=J[t<<4&63];i+="=="}else if(n===2){t=(e[r-2]<<8)+e[r-1];i+=J[t>>10];i+=J[t>>4&63];i+=J[t<<2&63];i+="="}u.push(i);return u.join("")}function te(e,t,r,n,f){var i,u;var l=f*8-n-1;var h=(1<>1;var a=-7;var o=r?f-1:0;var s=r?-1:1;var c=e[t+o];o+=s;i=c&(1<<-a)-1;c>>=-a;a+=l;for(;a>0;i=i*256+e[t+o],o+=s,a-=8){}u=i&(1<<-a)-1;i>>=-a;a+=n;for(;a>0;u=u*256+e[t+o],o+=s,a-=8){}if(i===0){i=1-p}else if(i===h){return u?NaN:(c?-1:1)*Infinity}else{u=u+Math.pow(2,n);i=i-p}return(c?-1:1)*u*Math.pow(2,i-n)}function re(e,t,f,l,r,h){var n,i,u;var a=h*8-r-1;var o=(1<>1;var p=r===23?Math.pow(2,-24)-Math.pow(2,-77):0;var c=l?0:h-1;var _=l?1:-1;var d=t<0||t===0&&1/t<0?1:0;t=Math.abs(t);if(isNaN(t)||t===Infinity){i=isNaN(t)?1:0;n=o}else{n=Math.floor(Math.log(t)/Math.LN2);if(t*(u=Math.pow(2,-n))<1){n--;u*=2}if(n+s>=1){t+=p/u}else{t+=p*Math.pow(2,1-s)}if(t*u>=2){n++;u/=2}if(n+s>=o){i=0;n=o}else if(n+s>=1){i=(t*u-1)*Math.pow(2,r);n=n+s}else{i=t*Math.pow(2,s-1)*Math.pow(2,r);n=0}}for(;r>=8;e[f+c]=i&255,c+=_,i/=256,r-=8){}n=n<0;e[f+c]=n&255,c+=_,n/=256,a-=8){}e[f+c-_]|=d*128}var ne={}.toString;var ie=Array.isArray||function(e){return ne.call(e)=="[object Array]"}; +(function(e,t){typeof exports==="object"&&typeof module!=="undefined"?module.exports=t():typeof define==="function"&&define.amd?define(t):(e=typeof globalThis!=="undefined"?globalThis:e||self,e.lips=t())})(this,function(){"use strict";function i(e){if(e===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return e}function o(e,t){o=Object.setPrototypeOf||function e(t,r){t.__proto__=r;return t};return o(e,t)}function n(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));return true}catch(e){return false}}function p(e,t,r){if(n()){p=Reflect.construct}else{p=function e(t,r,n){var i=[null];i.push.apply(i,r);var u=Function.bind.apply(t,i);var a=new u;if(n)o(a,n.prototype);return a}}return p.apply(null,arguments)}function u(e,t){if(typeof t!=="function"&&t!==null){throw new TypeError("Super expression must either be null or a function")}e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:true,configurable:true}});Object.defineProperty(e,"prototype",{writable:false});if(t)o(e,t)}function _(e){"@babel/helpers - typeof";return _="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_(e)}function a(e,t){if(t&&(_(t)==="object"||typeof t==="function")){return t}else if(t!==void 0){throw new TypeError("Derived constructors may only return object or undefined")}return i(e)}function c(e){c=Object.setPrototypeOf?Object.getPrototypeOf:function e(t){return t.__proto__||Object.getPrototypeOf(t)};return c(e)}function r(e){if(Array.isArray(e))return e}function t(e){if(typeof Symbol!=="undefined"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function f(e,t){if(t==null||t>e.length)t=e.length;for(var r=0,n=new Array(t);r=0)continue;r[i]=e[i]}return r}function F(e,t){if(e==null)return{};var r=x(e,t);var n,i;if(Object.getOwnPropertySymbols){var u=Object.getOwnPropertySymbols(e);for(i=0;i=0)continue;if(!Object.prototype.propertyIsEnumerable.call(e,n))continue;r[n]=e[n]}}return r}function k(e,t){var r=e==null?null:typeof Symbol!=="undefined"&&e[Symbol.iterator]||e["@@iterator"];if(r==null)return;var n=[];var i=true;var u=false;var a,o;try{for(r=r.call(e);!(i=(a=r.next()).done);i=true){n.push(a.value);if(t&&n.length===t)break}}catch(e){u=true;o=e}finally{try{if(!i&&r["return"]!=null)r["return"]()}finally{if(u)throw o}}return n}function j(e,t){return r(e)||k(e,t)||l(e,t)||d()}function I(e){this.wrapped=e}function P(e){return new I(e)}function N(u){var a,o;function e(n,i){return new Promise(function(e,t){var r={key:n,arg:i,resolve:e,reject:t,next:null};if(o){o=o.next=r}else{a=o=r;s(n,i)}})}function s(t,e){try{var r=u[t](e);var n=r.value;var i=n instanceof I;Promise.resolve(i?n.wrapped:n).then(function(e){if(i){s(t==="return"?"return":"next",e);return}c(r.done?"return":"normal",e)},function(e){s("throw",e)})}catch(e){c("throw",e)}}function c(e,t){switch(e){case"return":a.resolve({value:t,done:true});break;case"throw":a.reject(t);break;default:a.resolve({value:t,done:false});break}a=a.next;if(a){s(a.key,a.arg)}else{o=null}}this._invoke=e;if(typeof u["return"]!=="function"){this["return"]=undefined}}N.prototype[typeof Symbol==="function"&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this};N.prototype.next=function(e){return this._invoke("next",e)};N.prototype["throw"]=function(e){return this._invoke("throw",e)};N.prototype["return"]=function(e){return this._invoke("return",e)};function e(e){return function(){return new N(e.apply(this,arguments))}}function R(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e["default"]:e}var T={exports:{}};var V={exports:{}};(function(e){var t=function(a){var e=Object.prototype;var f=e.hasOwnProperty;var s;var o=typeof Symbol==="function"?Symbol:{};var i=o.iterator||"@@iterator";var c=o.asyncIterator||"@@asyncIterator";var p=o.toStringTag||"@@toStringTag";function r(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:true,configurable:true,writable:true});return e[t]}try{r({},"")}catch(e){r=function(e,t,r){return e[t]=r}}function _(e,t,r,n){var i=t&&t.prototype instanceof g?t:g;var u=Object.create(i.prototype);var a=new O(n||[]);u._invoke=x(e,r,a);return u}a.wrap=_;function d(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}var v="suspendedStart";var y="suspendedYield";var m="executing";var l="completed";var h={};function g(){}function n(){}function t(){}var b={};r(b,i,function(){return this});var w=Object.getPrototypeOf;var D=w&&w(w(S([])));if(D&&D!==e&&f.call(D,i)){b=D}var u=t.prototype=g.prototype=Object.create(b);n.prototype=t;r(u,"constructor",t);r(t,"constructor",n);n.displayName=r(t,p,"GeneratorFunction");function E(e){["next","throw","return"].forEach(function(t){r(e,t,function(e){return this._invoke(t,e)})})}a.isGeneratorFunction=function(e){var t=typeof e==="function"&&e.constructor;return t?t===n||(t.displayName||t.name)==="GeneratorFunction":false};a.mark=function(e){if(Object.setPrototypeOf){Object.setPrototypeOf(e,t)}else{e.__proto__=t;r(e,p,"GeneratorFunction")}e.prototype=Object.create(u);return e};a.awrap=function(e){return{__await:e}};function A(o,s){function c(e,t,r,n){var i=d(o[e],o,t);if(i.type==="throw"){n(i.arg)}else{var u=i.arg;var a=u.value;if(a&&typeof a==="object"&&f.call(a,"__await")){return s.resolve(a.__await).then(function(e){c("next",e,r,n)},function(e){c("throw",e,r,n)})}return s.resolve(a).then(function(e){u.value=e;r(u)},function(e){return c("throw",e,r,n)})}}var t;function e(r,n){function e(){return new s(function(e,t){c(r,n,e,t)})}return t=t?t.then(e,e):e()}this._invoke=e}E(A.prototype);r(A.prototype,c,function(){return this});a.AsyncIterator=A;a.async=function(e,t,r,n,i){if(i===void 0)i=Promise;var u=new A(_(e,t,r,n),i);return a.isGeneratorFunction(t)?u:u.next().then(function(e){return e.done?e.value:u.next()})};function x(a,o,s){var c=v;return function e(t,r){if(c===m){throw new Error("Generator is already running")}if(c===l){if(t==="throw"){throw r}return B()}s.method=t;s.arg=r;while(true){var n=s.delegate;if(n){var i=F(n,s);if(i){if(i===h)continue;return i}}if(s.method==="next"){s.sent=s._sent=s.arg}else if(s.method==="throw"){if(c===v){c=l;throw s.arg}s.dispatchException(s.arg)}else if(s.method==="return"){s.abrupt("return",s.arg)}c=m;var u=d(a,o,s);if(u.type==="normal"){c=s.done?l:y;if(u.arg===h){continue}return{value:u.arg,done:s.done}}else if(u.type==="throw"){c=l;s.method="throw";s.arg=u.arg}}}}function F(e,t){var r=e.iterator[t.method];if(r===s){t.delegate=null;if(t.method==="throw"){if(e.iterator["return"]){t.method="return";t.arg=s;F(e,t);if(t.method==="throw"){return h}}t.method="throw";t.arg=new TypeError("The iterator does not provide a 'throw' method")}return h}var n=d(r,e.iterator,t.arg);if(n.type==="throw"){t.method="throw";t.arg=n.arg;t.delegate=null;return h}var i=n.arg;if(!i){t.method="throw";t.arg=new TypeError("iterator result is not an object");t.delegate=null;return h}if(i.done){t[e.resultName]=i.value;t.next=e.nextLoc;if(t.method!=="return"){t.method="next";t.arg=s}}else{return i}t.delegate=null;return h}E(u);r(u,p,"Generator");r(u,i,function(){return this});r(u,"toString",function(){return"[object Generator]"});function k(e){var t={tryLoc:e[0]};if(1 in e){t.catchLoc=e[1]}if(2 in e){t.finallyLoc=e[2];t.afterLoc=e[3]}this.tryEntries.push(t)}function C(e){var t=e.completion||{};t.type="normal";delete t.arg;e.completion=t}function O(e){this.tryEntries=[{tryLoc:"root"}];e.forEach(k,this);this.reset(true)}a.keys=function(r){var n=[];for(var e in r){n.push(e)}n.reverse();return function e(){while(n.length){var t=n.pop();if(t in r){e.value=t;e.done=false;return e}}e.done=true;return e}};function S(t){if(t){var e=t[i];if(e){return e.call(t)}if(typeof t.next==="function"){return t}if(!isNaN(t.length)){var r=-1,n=function e(){while(++r=0;--t){var i=this.tryEntries[t];var u=i.completion;if(i.tryLoc==="root"){return e("end")}if(i.tryLoc<=this.prev){var a=f.call(i,"catchLoc");var o=f.call(i,"finallyLoc");if(a&&o){if(this.prev=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&f.call(n,"finallyLoc")&&this.prev=0;--t){var r=this.tryEntries[t];if(r.finallyLoc===e){this.complete(r.completion,r.afterLoc);C(r);return h}}},catch:function(e){for(var t=this.tryEntries.length-1;t>=0;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n=r.completion;if(n.type==="throw"){var i=n.arg;C(r)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){this.delegate={iterator:S(e),resultName:t,nextLoc:r};if(this.method==="next"){this.arg=s}return h}};return a}(e.exports);try{regeneratorRuntime=t}catch(e){if(typeof globalThis==="object"){globalThis.regeneratorRuntime=t}else{Function("r","regeneratorRuntime = r")(t)}}})(V);(function(e){e.exports=V.exports})(T);var z=R(T.exports);var $=typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{};var J=[];var K=[];var G=typeof Uint8Array!=="undefined"?Uint8Array:Array;var H=false;function W(){H=true;var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var t=0,r=e.length;t0){throw new Error("Invalid string. Length must be a multiple of 4")}u=e[o-2]==="="?2:e[o-1]==="="?1:0;a=new G(o*3/4-u);n=u>0?o-4:o;var s=0;for(t=0,r=0;t>16&255;a[s++]=i>>8&255;a[s++]=i&255}if(u===2){i=K[e.charCodeAt(t)]<<2|K[e.charCodeAt(t+1)]>>4;a[s++]=i&255}else if(u===1){i=K[e.charCodeAt(t)]<<10|K[e.charCodeAt(t+1)]<<4|K[e.charCodeAt(t+2)]>>2;a[s++]=i>>8&255;a[s++]=i&255}return a}function Z(e){return J[e>>18&63]+J[e>>12&63]+J[e>>6&63]+J[e&63]}function X(e,t,r){var n;var i=[];for(var u=t;us?s:o+a))}if(n===1){t=e[r-1];i+=J[t>>2];i+=J[t<<4&63];i+="=="}else if(n===2){t=(e[r-2]<<8)+e[r-1];i+=J[t>>10];i+=J[t>>4&63];i+=J[t<<2&63];i+="="}u.push(i);return u.join("")}function te(e,t,r,n,f){var i,u;var l=f*8-n-1;var h=(1<>1;var a=-7;var o=r?f-1:0;var s=r?-1:1;var c=e[t+o];o+=s;i=c&(1<<-a)-1;c>>=-a;a+=l;for(;a>0;i=i*256+e[t+o],o+=s,a-=8){}u=i&(1<<-a)-1;i>>=-a;a+=n;for(;a>0;u=u*256+e[t+o],o+=s,a-=8){}if(i===0){i=1-p}else if(i===h){return u?NaN:(c?-1:1)*Infinity}else{u=u+Math.pow(2,n);i=i-p}return(c?-1:1)*u*Math.pow(2,i-n)}function re(e,t,f,l,r,h){var n,i,u;var a=h*8-r-1;var o=(1<>1;var p=r===23?Math.pow(2,-24)-Math.pow(2,-77):0;var c=l?0:h-1;var _=l?1:-1;var d=t<0||t===0&&1/t<0?1:0;t=Math.abs(t);if(isNaN(t)||t===Infinity){i=isNaN(t)?1:0;n=o}else{n=Math.floor(Math.log(t)/Math.LN2);if(t*(u=Math.pow(2,-n))<1){n--;u*=2}if(n+s>=1){t+=p/u}else{t+=p*Math.pow(2,1-s)}if(t*u>=2){n++;u/=2}if(n+s>=o){i=0;n=o}else if(n+s>=1){i=(t*u-1)*Math.pow(2,r);n=n+s}else{i=t*Math.pow(2,s-1)*Math.pow(2,r);n=0}}for(;r>=8;e[f+c]=i&255,c+=_,i/=256,r-=8){}n=n<0;e[f+c]=n&255,c+=_,n/=256,a-=8){}e[f+c-_]|=d*128}var ne={}.toString;var ie=Array.isArray||function(e){return ne.call(e)=="[object Array]"}; /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT - */var ue=50;c.TYPED_ARRAY_SUPPORT=V.TYPED_ARRAY_SUPPORT!==undefined?V.TYPED_ARRAY_SUPPORT:true;ae();function ae(){return c.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function oe(e,t){if(ae()=ae()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+ae().toString(16)+" bytes")}return e|0}c.isBuffer=et;function me(e){return!!(e!=null&&e._isBuffer)}c.compare=function e(t,r){if(!me(t)||!me(r)){throw new TypeError("Arguments must be Buffers")}if(t===r)return 0;var n=t.length;var i=r.length;for(var u=0,a=Math.min(n,i);u>>1;case"base64":return Ze(e).length;default:if(n)return We(e).length;t=(""+t).toLowerCase();n=true}}}c.byteLength=ye;function ge(e,t,r){var n=false;if(t===undefined||t<0){t=0}if(t>this.length){return""}if(r===undefined||r>this.length){r=this.length}if(r<=0){return""}r>>>=0;t>>>=0;if(r<=t){return""}if(!e)e="utf8";while(true){switch(e){case"hex":return Ne(this,t,r);case"utf8":case"utf-8":return Se(this,t,r);case"ascii":return Ie(this,t,r);case"latin1":case"binary":return Pe(this,t,r);case"base64":return Oe(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Re(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase();n=true}}}c.prototype._isBuffer=true;function be(e,t,r){var n=e[t];e[t]=e[r];e[r]=n}c.prototype.swap16=function e(){var t=this.length;if(t%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var r=0;r0){t=this.toString("hex",0,r).match(/.{2}/g).join(" ");if(this.length>r)t+=" ... "}return""};c.prototype.compare=function f(e,t,r,n,i){if(!me(e)){throw new TypeError("Argument must be a Buffer")}if(t===undefined){t=0}if(r===undefined){r=e?e.length:0}if(n===undefined){n=0}if(i===undefined){i=this.length}if(t<0||r>e.length||n<0||i>this.length){throw new RangeError("out of range index")}if(n>=i&&t>=r){return 0}if(n>=i){return-1}if(t>=r){return 1}t>>>=0;r>>>=0;n>>>=0;i>>>=0;if(this===e)return 0;var u=i-n;var a=r-t;var l=Math.min(u,a);var o=this.slice(n,i);var s=e.slice(t,r);for(var c=0;c2147483647){r=2147483647}else if(r<-2147483648){r=-2147483648}r=+r;if(isNaN(r)){r=i?0:e.length-1}if(r<0)r=e.length+r;if(r>=e.length){if(i)return-1;else r=e.length-1}else if(r<0){if(i)r=0;else return-1}if(typeof t==="string"){t=c.from(t,n)}if(me(t)){if(t.length===0){return-1}return De(e,t,r,n,i)}else if(typeof t==="number"){t=t&255;if(c.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf==="function"){if(i){return Uint8Array.prototype.indexOf.call(e,t,r)}else{return Uint8Array.prototype.lastIndexOf.call(e,t,r)}}return De(e,[t],r,n,i)}throw new TypeError("val must be string, number or Buffer")}function De(e,t,r,n,f){var i=1;var u=e.length;var a=t.length;if(n!==undefined){n=String(n).toLowerCase();if(n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le"){if(e.length<2||t.length<2){return-1}i=2;u/=2;a/=2;r/=2}}function o(e,t){if(i===1){return e[t]}else{return e.readUInt16BE(t*i)}}var s;if(f){var c=-1;for(s=r;su)r=u-a;for(s=r;s>=0;s--){var l=true;for(var h=0;hi){n=i}}var u=t.length;if(u%2!==0)throw new TypeError("Invalid hex string");if(n>u/2){n=u/2}for(var a=0;au)n=u;if(t.length>0&&(n<0||r<0)||r>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!i)i="utf8";var a=false;for(;;){switch(i){case"hex":return Ee(this,t,r,n);case"utf8":case"utf-8":return Ae(this,t,r,n);case"ascii":return Fe(this,t,r,n);case"latin1":case"binary":return xe(this,t,r,n);case"base64":return Ce(this,t,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ke(this,t,r,n);default:if(a)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase();a=true}}};c.prototype.toJSON=function e(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Oe(e,t,r){if(t===0&&r===e.length){return ee(e)}else{return ee(e.slice(t,r))}}function Se(e,f,t){t=Math.min(e.length,t);var r=[];var n=f;while(n239?4:i>223?3:i>191?2:1;if(n+a<=t){var o,s,l,c;switch(a){case 1:if(i<128){u=i}break;case 2:o=e[n+1];if((o&192)===128){c=(i&31)<<6|o&63;if(c>127){u=c}}break;case 3:o=e[n+1];s=e[n+2];if((o&192)===128&&(s&192)===128){c=(i&15)<<12|(o&63)<<6|s&63;if(c>2047&&(c<55296||c>57343)){u=c}}break;case 4:o=e[n+1];s=e[n+2];l=e[n+3];if((o&192)===128&&(s&192)===128&&(l&192)===128){c=(i&15)<<18|(o&63)<<12|(s&63)<<6|l&63;if(c>65535&&c<1114112){u=c}}}}if(u===null){u=65533;a=1}else if(u>65535){u-=65536;r.push(u>>>10&1023|55296);u=56320|u&1023}r.push(u);n+=a}return je(r)}var Be=4096;function je(e){var t=e.length;if(t<=Be){return String.fromCharCode.apply(String,e)}var r="";var n=0;while(nn)r=n;var i="";for(var u=t;un){t=n}if(r<0){r+=n;if(r<0)r=0}else if(r>n){r=n}if(rr)throw new RangeError("Trying to access beyond buffer length")}c.prototype.readUIntLE=function e(t,r,n){t=t|0;r=r|0;if(!n)Te(t,r,this.length);var i=this[t];var u=1;var a=0;while(++a0&&(u*=256)){i+=this[t+--r]*u}return i};c.prototype.readUInt8=function e(t,r){if(!r)Te(t,1,this.length);return this[t]};c.prototype.readUInt16LE=function e(t,r){if(!r)Te(t,2,this.length);return this[t]|this[t+1]<<8};c.prototype.readUInt16BE=function e(t,r){if(!r)Te(t,2,this.length);return this[t]<<8|this[t+1]};c.prototype.readUInt32LE=function e(t,r){if(!r)Te(t,4,this.length);return(this[t]|this[t+1]<<8|this[t+2]<<16)+this[t+3]*16777216};c.prototype.readUInt32BE=function e(t,r){if(!r)Te(t,4,this.length);return this[t]*16777216+(this[t+1]<<16|this[t+2]<<8|this[t+3])};c.prototype.readIntLE=function e(t,r,n){t=t|0;r=r|0;if(!n)Te(t,r,this.length);var i=this[t];var u=1;var a=0;while(++a=u)i-=Math.pow(2,8*r);return i};c.prototype.readIntBE=function e(t,r,n){t=t|0;r=r|0;if(!n)Te(t,r,this.length);var i=r;var u=1;var a=this[t+--i];while(i>0&&(u*=256)){a+=this[t+--i]*u}u*=128;if(a>=u)a-=Math.pow(2,8*r);return a};c.prototype.readInt8=function e(t,r){if(!r)Te(t,1,this.length);if(!(this[t]&128))return this[t];return(255-this[t]+1)*-1};c.prototype.readInt16LE=function e(t,r){if(!r)Te(t,2,this.length);var n=this[t]|this[t+1]<<8;return n&32768?n|4294901760:n};c.prototype.readInt16BE=function e(t,r){if(!r)Te(t,2,this.length);var n=this[t+1]|this[t]<<8;return n&32768?n|4294901760:n};c.prototype.readInt32LE=function e(t,r){if(!r)Te(t,4,this.length);return this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24};c.prototype.readInt32BE=function e(t,r){if(!r)Te(t,4,this.length);return this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]};c.prototype.readFloatLE=function e(t,r){if(!r)Te(t,4,this.length);return te(this,t,true,23,4)};c.prototype.readFloatBE=function e(t,r){if(!r)Te(t,4,this.length);return te(this,t,false,23,4)};c.prototype.readDoubleLE=function e(t,r){if(!r)Te(t,8,this.length);return te(this,t,true,52,8)};c.prototype.readDoubleBE=function e(t,r){if(!r)Te(t,8,this.length);return te(this,t,false,52,8)};function Le(e,t,r,n,i,u){if(!me(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}c.prototype.writeUIntLE=function e(t,r,n,i){t=+t;r=r|0;n=n|0;if(!i){var u=Math.pow(2,8*n)-1;Le(this,t,r,n,u,0)}var a=1;var o=0;this[r]=t&255;while(++o=0&&(o*=256)){this[r+a]=t/o&255}return r+n};c.prototype.writeUInt8=function e(t,r,n){t=+t;r=r|0;if(!n)Le(this,t,r,1,255,0);if(!c.TYPED_ARRAY_SUPPORT)t=Math.floor(t);this[r]=t&255;return r+1};function Ue(e,t,r,n){if(t<0)t=65535+t+1;for(var i=0,u=Math.min(e.length-r,2);i>>(n?i:1-i)*8}}c.prototype.writeUInt16LE=function e(t,r,n){t=+t;r=r|0;if(!n)Le(this,t,r,2,65535,0);if(c.TYPED_ARRAY_SUPPORT){this[r]=t&255;this[r+1]=t>>>8}else{Ue(this,t,r,true)}return r+2};c.prototype.writeUInt16BE=function e(t,r,n){t=+t;r=r|0;if(!n)Le(this,t,r,2,65535,0);if(c.TYPED_ARRAY_SUPPORT){this[r]=t>>>8;this[r+1]=t&255}else{Ue(this,t,r,false)}return r+2};function qe(e,t,r,n){if(t<0)t=4294967295+t+1;for(var i=0,u=Math.min(e.length-r,4);i>>(n?i:3-i)*8&255}}c.prototype.writeUInt32LE=function e(t,r,n){t=+t;r=r|0;if(!n)Le(this,t,r,4,4294967295,0);if(c.TYPED_ARRAY_SUPPORT){this[r+3]=t>>>24;this[r+2]=t>>>16;this[r+1]=t>>>8;this[r]=t&255}else{qe(this,t,r,true)}return r+4};c.prototype.writeUInt32BE=function e(t,r,n){t=+t;r=r|0;if(!n)Le(this,t,r,4,4294967295,0);if(c.TYPED_ARRAY_SUPPORT){this[r]=t>>>24;this[r+1]=t>>>16;this[r+2]=t>>>8;this[r+3]=t&255}else{qe(this,t,r,false)}return r+4};c.prototype.writeIntLE=function e(t,r,n,i){t=+t;r=r|0;if(!i){var u=Math.pow(2,8*n-1);Le(this,t,r,n,u-1,-u)}var a=0;var o=1;var s=0;this[r]=t&255;while(++a>0)-s&255}return r+n};c.prototype.writeIntBE=function e(t,r,n,i){t=+t;r=r|0;if(!i){var u=Math.pow(2,8*n-1);Le(this,t,r,n,u-1,-u)}var a=n-1;var o=1;var s=0;this[r+a]=t&255;while(--a>=0&&(o*=256)){if(t<0&&s===0&&this[r+a+1]!==0){s=1}this[r+a]=(t/o>>0)-s&255}return r+n};c.prototype.writeInt8=function e(t,r,n){t=+t;r=r|0;if(!n)Le(this,t,r,1,127,-128);if(!c.TYPED_ARRAY_SUPPORT)t=Math.floor(t);if(t<0)t=255+t+1;this[r]=t&255;return r+1};c.prototype.writeInt16LE=function e(t,r,n){t=+t;r=r|0;if(!n)Le(this,t,r,2,32767,-32768);if(c.TYPED_ARRAY_SUPPORT){this[r]=t&255;this[r+1]=t>>>8}else{Ue(this,t,r,true)}return r+2};c.prototype.writeInt16BE=function e(t,r,n){t=+t;r=r|0;if(!n)Le(this,t,r,2,32767,-32768);if(c.TYPED_ARRAY_SUPPORT){this[r]=t>>>8;this[r+1]=t&255}else{Ue(this,t,r,false)}return r+2};c.prototype.writeInt32LE=function e(t,r,n){t=+t;r=r|0;if(!n)Le(this,t,r,4,2147483647,-2147483648);if(c.TYPED_ARRAY_SUPPORT){this[r]=t&255;this[r+1]=t>>>8;this[r+2]=t>>>16;this[r+3]=t>>>24}else{qe(this,t,r,true)}return r+4};c.prototype.writeInt32BE=function e(t,r,n){t=+t;r=r|0;if(!n)Le(this,t,r,4,2147483647,-2147483648);if(t<0)t=4294967295+t+1;if(c.TYPED_ARRAY_SUPPORT){this[r]=t>>>24;this[r+1]=t>>>16;this[r+2]=t>>>8;this[r+3]=t&255}else{qe(this,t,r,false)}return r+4};function Me(e,t,r,n,i,u){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Ye(e,t,r,n,i){if(!i){Me(e,t,r,4)}re(e,t,r,n,23,4);return r+4}c.prototype.writeFloatLE=function e(t,r,n){return Ye(this,t,r,true,n)};c.prototype.writeFloatBE=function e(t,r,n){return Ye(this,t,r,false,n)};function $e(e,t,r,n,i){if(!i){Me(e,t,r,8)}re(e,t,r,n,52,8);return r+8}c.prototype.writeDoubleLE=function e(t,r,n){return $e(this,t,r,true,n)};c.prototype.writeDoubleBE=function e(t,r,n){return $e(this,t,r,false,n)};c.prototype.copy=function e(t,r,n,i){if(!n)n=0;if(!i&&i!==0)i=this.length;if(r>=t.length)r=t.length;if(!r)r=0;if(i>0&&i=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");if(i>this.length)i=this.length;if(t.length-r=0;--a){t[a+r]=this[a+n]}}else if(u<1e3||!c.TYPED_ARRAY_SUPPORT){for(a=0;a>>0;n=n===undefined?this.length:n>>>0;if(!t)t=0;var a;if(typeof t==="number"){for(a=r;a55295&&r<57344){if(!i){if(r>56319){if((t-=3)>-1)u.push(239,191,189);continue}else if(a+1===n){if((t-=3)>-1)u.push(239,191,189);continue}i=r;continue}if(r<56320){if((t-=3)>-1)u.push(239,191,189);i=r;continue}r=(i-55296<<10|r-56320)+65536}else if(i){if((t-=3)>-1)u.push(239,191,189)}i=null;if(r<128){if((t-=1)<0)break;u.push(r)}else if(r<2048){if((t-=2)<0)break;u.push(r>>6|192,r&63|128)}else if(r<65536){if((t-=3)<0)break;u.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((t-=4)<0)break;u.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else{throw new Error("Invalid code point")}}return u}function He(e){var t=[];for(var r=0;r>8;i=r%256;u.push(i);u.push(n)}return u}function Ze(e){return Z(Ve(e))}function Ke(e,t,r,n){for(var i=0;i=t.length||i>=e.length)break;t[i+r]=e[i]}return i}function Xe(e){return e!==e}function et(e){return e!=null&&(!!e._isBuffer||tt(e)||rt(e))}function tt(e){return!!e.constructor&&typeof e.constructor.isBuffer==="function"&&e.constructor.isBuffer(e)}function rt(e){return typeof e.readFloatLE==="function"&&typeof e.slice==="function"&&tt(e.slice(0,0))}let nt;try{nt=new TextDecoder}catch(e){}let it;let ut;let v=0;const at=105;const ot={};let st={};let ct;let ft;let lt=0;let ht=0;let pt;let _t=[];let dt;let vt;let mt={useRecords:false,mapsAsObjects:true};let yt=false;class gt{constructor(e){if(e){if(e.useRecords===false&&e.mapsAsObjects===undefined)e.mapsAsObjects=true;if(e.getStructures&&!e.structures)(e.structures=[]).uninitialized=true}Object.assign(this,e)}decode(e,t){if(it){return qt(()=>{Mt();return this?this.decode(e,t):gt.prototype.decode.call(mt,e,t)})}ut=t>-1?t:e.length;v=0;ht=0;ft=null;it=e;dt=e.dataView||(e.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength));if(this){st=this;if(this.structures){ct=this.structures;return bt()}else if(!ct||ct.length>0){ct=[]}}else{st=mt;if(!ct||ct.length>0)ct=[]}return bt()}decodeMultiple(r,n){let i,u=0;try{let e=r.length;yt=true;let t=this?this.decode(r,e):zt.decode(r,e);if(n){n(t);while(vut){let e=new Error("Unexpected end of CBOR data");e.incomplete=true;throw e}else if(!yt){throw new Error("Data read, but end of buffer not reached")}return e}catch(e){Mt();if(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")){e.incomplete=true}throw e}}function wt(){let r=it[v++];let i=r>>5;r=r&31;if(r>23){switch(r){case 24:r=it[v++];break;case 25:if(i==7){return Bt()}r=dt.getUint16(v);v+=2;break;case 26:if(i==7){let t=dt.getFloat32(v);if(st.useFloat32>2){let e=$t[(it[v]&127)<<1|it[v+1]>>7];v+=4;return(e*t+(t>0?.5:-.5)>>0)/e}v+=4;return t}r=dt.getUint32(v);v+=4;break;case 27:if(i==7){let e=dt.getFloat64(v);v+=8;return e}if(st.uint64AsNumber)return it[v++]*72057594037927940+it[v++]*281474976710656+it[v++]*1099511627776+it[v++]*4294967296+it[v++]*16777216+(it[v++]<<16)+(it[v++]<<8)+it[v++];r=dt.getBigUint64(v);v+=8;break;case 31:switch(i){case 2:case 3:case 4:let e=[];let t,r=0;while((t=wt())!=ot){e[r++]=t}return i==4?e:i==3?e.join(""):c.concat(e);case 5:let n;if(st.mapsAsObjects){let e={};while((n=It())!=ot)e[n]=wt();return e}else{if(vt){st.mapsAsObjects=true;vt=false}let e=new Map;while((n=wt())!=ot)e.set(n,wt());return e}case 7:return ot;default:throw new Error("Invalid major type for indefinite length "+i)}default:throw new Error("Unknown token "+r)}}switch(i){case 0:return r;case 1:return~r;case 2:return St(r);case 3:if(ht>=v){return ft.slice(v-lt,(v+=r)-lt)}if(ht==0&&ut<140&&r<32){let e=r<16?Ot(r):kt(r);if(e!=null)return e}return Ft(r);case 4:let t=new Array(r);for(let e=0;e>8==at){let t=ct[r&255];if(t){if(!t.read)t.read=Et(t);return t.read()}else if(st.getStructures){let e=qt(()=>{it=null;return st.getStructures()});if(ct===true)st.structures=ct=e;else ct.splice.apply(ct,[0,e.length].concat(e));t=ct[r&255];if(t){if(!t.read)t.read=Et(t);return t.read()}else return r}else return r}else{let e=_t[r];if(e){if(e.handlesRead)return e(wt);else return e(wt())}else return new Pt(wt())}case 7:switch(r){case 20:return false;case 21:return true;case 22:return null;case 23:return;case 31:default:throw new Error("Unknown token "+r)}default:if(isNaN(r)){let e=new Error("Unexpected end of CBOR data");e.incomplete=true;throw e}throw new Error("Unknown CBOR token "+r)}}const Dt=/^[a-zA-Z_$][a-zA-Z\d_$]*$/;function Et(n){let e=n.length;function t(){if(t.count++>2){this.read=new Function("a","r","return function(){a();return {"+n.map(e=>Dt.test(e)?e+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}}")(At,wt);return this.read()}At();let r={};for(let t=0;t23){switch(t){case 24:v++;break;case 25:v+=2;break;case 26:v+=4}}}let Ft=xt;function xt(e){let t;if(e<16){if(t=Ot(e))return t}if(e>64&&nt)return nt.decode(it.subarray(v,v+=e));const r=v+e;const n=[];t="";while(v65535){e-=65536;n.push(e>>>10&1023|55296);e=56320|e&1023}n.push(e)}else{n.push(i)}if(n.length>=4096){t+=Ct.apply(String,n);n.length=0}}if(n.length>0){t+=Ct.apply(String,n)}return t}let Ct=String.fromCharCode;function kt(t){let r=v;let n=new Array(t);for(let e=0;e0){v=r;return}n[e]=i}return Ct.apply(String,n)}function Ot(d){if(d<4){if(d<2){if(d===0)return"";else{let e=it[v++];if((e&128)>1){v-=1;return}return Ct(e)}}else{let e=it[v++];let t=it[v++];if((e&128)>0||(t&128)>0){v-=2;return}if(d<3)return Ct(e,t);let r=it[v++];if((r&128)>0){v-=3;return}return Ct(e,t,r)}}else{let l=it[v++];let h=it[v++];let p=it[v++];let _=it[v++];if((l&128)>0||(h&128)>0||(p&128)>0||(_&128)>0){v-=4;return}if(d<6){if(d===4)return Ct(l,h,p,_);else{let e=it[v++];if((e&128)>0){v-=5;return}return Ct(l,h,p,_,e)}}else if(d<8){let e=it[v++];let t=it[v++];if((e&128)>0||(t&128)>0){v-=6;return}if(d<7)return Ct(l,h,p,_,e,t);let r=it[v++];if((r&128)>0){v-=7;return}return Ct(l,h,p,_,e,t,r)}else{let o=it[v++];let s=it[v++];let c=it[v++];let f=it[v++];if((o&128)>0||(s&128)>0||(c&128)>0||(f&128)>0){v-=8;return}if(d<10){if(d===8)return Ct(l,h,p,_,o,s,c,f);else{let e=it[v++];if((e&128)>0){v-=9;return}return Ct(l,h,p,_,o,s,c,f,e)}}else if(d<12){let e=it[v++];let t=it[v++];if((e&128)>0||(t&128)>0){v-=10;return}if(d<11)return Ct(l,h,p,_,o,s,c,f,e,t);let r=it[v++];if((r&128)>0){v-=11;return}return Ct(l,h,p,_,o,s,c,f,e,t,r)}else{let n=it[v++];let i=it[v++];let u=it[v++];let a=it[v++];if((n&128)>0||(i&128)>0||(u&128)>0||(a&128)>0){v-=12;return}if(d<14){if(d===12)return Ct(l,h,p,_,o,s,c,f,n,i,u,a);else{let e=it[v++];if((e&128)>0){v-=13;return}return Ct(l,h,p,_,o,s,c,f,n,i,u,a,e)}}else{let e=it[v++];let t=it[v++];if((e&128)>0||(t&128)>0){v-=14;return}if(d<15)return Ct(l,h,p,_,o,s,c,f,n,i,u,a,e,t);let r=it[v++];if((r&128)>0){v-=15;return}return Ct(l,h,p,_,o,s,c,f,n,i,u,a,e,t,r)}}}}}function St(e){return st.copyBuffers?Uint8Array.prototype.slice.call(it,v,v+=e):it.subarray(v,v+=e)}function Bt(){let e=it[v++];let t=it[v++];let r=(e<<8)+t;let n=r>>10&31;let i=r&1023;let u;if(n==0)u=Math.exp(i,-24);else if(n!=31)u=Math.exp(i+1024,n-25);else u=i==0?Infinity:NaN;return r&32768?-u:u}let jt=new Array(4096);function It(){let e=it[v++];if(e>=96&&e<120){e=e-96;if(ht>=v)return ft.slice(v-lt,(v+=e)-lt);else if(!(ht==0&&ut<180))return Ft(e)}else{v--;return wt()}let t=(e<<5^(e>1?dt.getUint16(v):e>0?it[v]:0))&4095;let r=jt[t];let n=v;let i=v+e-3;let u;let a=0;if(r&&r.bytes==e){while(n{return new Date(e)};_t[1]=e=>{return new Date(e*1e3)};_t[2]=e=>{return new DataView(e.buffer,e.byteOffset,e.byteLength).getBigUint64(0)};_t[3]=e=>{return BigInt(-1)-new DataView(e.buffer,e.byteOffset,e.byteLength).getBigUint64(0)};const Rt=()=>{let r=wt();let n=r[0];let e=r[1];ct[e&255]=n;n.read=Et(n);let i={};for(let t=2,e=r.length;t{return(Nt[e[0]]||Error)(e[1],e[2])};_t[40009]=e=>{if(!pt)pt=new Map;let t=it[v];let r;if(t>>5==4)r=[];else r={};let n={target:r};pt.set(e,n);let i=wt();if(n.used)return Object.assign(r,i);n.target=i;return i};_t[40010]=e=>{let t=pt.get(e);t.used=true;return t.target};_t[258]=e=>new Set(e);(_t[259]=e=>{if(st.mapsAsObjects){st.mapsAsObjects=false;vt=true}return e()}).handlesRead=true;const Tt=["Uint8","Uint8Clamped","Uint16","Uint32","BigUint64","Int8","Int16","Int32","BigInt64","Float32","Float64"].map(e=>e+"Array");const Lt=[64,68,69,70,71,72,77,78,79,81,82];for(let e=0;e{if(!t)throw new Error("Could not find typed array for code "+typeCode);return new Nt[t](Uint8Array.prototype.slice.call(e,0).buffer)}}function qt(e){let t=ut;let r=v;let n=lt;let i=ht;let u=ft;let a=pt;let o=new Uint8Array(it.slice(0,ut));let s=ct;let c=st;let f=yt;let l=e();ut=t;v=r;lt=n;ht=i;ft=u;pt=a;it=o;yt=f;ct=s;st=c;dt=new DataView(it.buffer,it.byteOffset,it.byteLength);return l}function Mt(){it=null;pt=null;ct=null}function Yt(e){_t[e.tag]=e.decode}let $t=new Array(147);for(let e=0;e<256;e++){$t[e]=+("1e"+Math.floor(45.15-e*.30103))}let zt=new gt({useRecords:false});zt.decode;zt.decodeMultiple;let Vt;try{Vt=new TextEncoder}catch(e){}let Jt,Gt;const Wt=typeof c!=="undefined";const Ht=Wt?c.allocUnsafeSlow:Uint8Array;const Qt=Wt?c:Uint8Array;const Zt=105;const Kt=256;const Xt=Wt?4294967296:2144337920;let m;let er;let y=0;let tr;const rr=Symbol("record-id");class nr extends gt{constructor(e){super(e);this.offset=0;let i;let o;let s;let c;let r;let a=0;let t=Qt.prototype.utf8Write?function(e,t,r){return m.utf8Write(e,t,r)}:Vt&&Vt.encodeInto?function(e,t){return Vt.encodeInto(e,m.subarray(t)).written}:false;let n=this;let f=64;let u=e&&e.sequential;if(u){f=0;this.structures=[]}let l=[];let p=0;let _=0;if(this.structures&&this.structures.length>f){throw new Error("Too many shared structures")}this.encode=function(e){if(!m){m=new Ht(8192);er=new DataView(m.buffer,0,8192);y=0}tr=m.length-10;if(tr-y<2048){m=new Ht(m.length);er=new DataView(m.buffer,0,m.length);tr=m.length-10;y=0}i=y;r=n.structuredClone?new Map:null;o=n.structures;if(o){if(o.uninitialized)n.structures=o=n.getStructures();let t=o.length;if(t>f&&!u)t=f;if(!o.transitions){o.transitions=Object.create(null);for(let e=0;etr)v(y);n.offset=y;let e=or(m.subarray(i,y),r.idsToInsert);r=null;return e}return m.subarray(i,y)}finally{if(o){if(_<10)_++;if(p>1e4){o.transitions=null;_=0;p=0;if(l.length>0)l=[]}else if(l.length>0&&!u){for(let e=0,t=l.length;ef){n.structures=n.structures.slice(0,f)}if(n.saveStructures(n.structures,a)===false){n.structures=n.getStructures()||[];return n.encode(e)}a=n.structures.length}}}};const h=a=>{if(y>tr)m=v(y);var e=typeof a;var o;if(e==="string"){let i=a.length;let u;if(i<32){u=1}else if(i<256){u=2}else if(i<65536){u=3}else{u=5}let e=i*3;if(y+e>tr)m=v(y+e);if(i<64||!t){let e,t,r,n=y+u;for(e=0;e>6|192;m[n++]=t&63|128}else if((t&64512)===55296&&((r=a.charCodeAt(e+1))&64512)===56320){t=65536+((t&1023)<<10)+(r&1023);e++;m[n++]=t>>18|240;m[n++]=t>>12&63|128;m[n++]=t>>6&63|128;m[n++]=t&63|128}else{m[n++]=t>>12|224;m[n++]=t>>6&63|128;m[n++]=t&63|128}}o=n-y-u}else{o=t(a,y+u,e)}if(o<24){m[y++]=96|o}else if(o<256){if(u<2){m.copyWithin(y+2,y+1,y+1+o)}m[y++]=120;m[y++]=o}else if(o<65536){if(u<3){m.copyWithin(y+3,y+2,y+2+o)}m[y++]=121;m[y++]=o>>8;m[y++]=o&255}else{if(u<5){m.copyWithin(y+5,y+3,y+3+o)}m[y++]=122;er.setUint32(y,o);y+=4}y+=o}else if(e==="number"){if(a>>>0===a){if(a<24){m[y++]=a}else if(a<256){m[y++]=24;m[y++]=a}else if(a<65536){m[y++]=25;m[y++]=a>>8;m[y++]=a&255}else{m[y++]=26;er.setUint32(y,a);y+=4}}else if(a>>0===a){if(a>=-24){m[y++]=31-a}else if(a>=-256){m[y++]=56;m[y++]=~a}else if(a>=-65536){m[y++]=57;er.setUint16(y,~a);y+=2}else{m[y++]=58;er.setUint32(y,~a);y+=4}}else{let t;if((t=this.useFloat32)>0&&a<4294967296&&a>=-2147483648){m[y++]=250;er.setFloat32(y,a);let e;if(t<4||(e=a*$t[(m[y]&127)<<1|m[y+1]>>7])>>0===e){y+=4;return}else y--}m[y++]=251;er.setFloat64(y,a);y+=8}}else if(e==="object"){if(!a)m[y++]=246;else{if(r){let t=r.get(a);if(t){if(!t.id){let e=r.idsToInsert||(r.idsToInsert=[]);t.id=e.push(t)}m[y++]=217;m[y++]=40010>>8;m[y++]=40010&255;m[y++]=26;er.setUint32(y,t.id);y+=4;return}else r.set(a,{offset:y-i})}let e=a.constructor;if(e===Object){d(a,true)}else if(e===Array){o=a.length;if(o<24){m[y++]=128|o}else{ir(o)}for(let e=0;e>8;m[y++]=o&255}else{m[y++]=186;er.setUint32(y,o);y+=4}for(let[e,t]of a){h(e);h(t)}}else{for(let r=0,e=Jt.length;r>8;m[y++]=t&255}else if(t>-1){m[y++]=218;er.setUint32(y,t);y+=4}e.encode.call(this,a,h,v);return}}if(a[Symbol.iterator]){m[y++]=159;for(let e of a){h(e)}m[y++]=255;return}d(a,!a.hasOwnProperty)}}}else if(e==="boolean"){m[y++]=a?245:244}else if(e==="bigint"){if(a=0){m[y++]=27;er.setBigUint64(y,a)}else if(a>-(BigInt(1)<{let r=Object.keys(t);let n=r.length;if(n<24){m[y++]=160|n}else if(n<256){m[y++]=184;m[y++]=n}else if(n<65536){m[y++]=185;m[y++]=n>>8;m[y++]=n&255}else{m[y++]=186;er.setUint32(y,n);y+=4}let i;for(let e=0;e{m[y++]=185;let e=y-i;y+=2;let n=0;for(let e in t){if(r||t.hasOwnProperty(e)){h(e);h(t[e]);n++}}m[e+++i]=n>>8;m[e+i]=n&255}:t=>{let r=Object.keys(t);let n,i=c.transitions||(c.transitions=Object.create(null));let u=0;let a=r.length;for(let t=0;t=Kt){c.nextId=(e=f)+1}i[rr]=e;c[e]=r;if(o&&o.length<=f){m[y++]=217;m[y++]=Zt;m[y++]=e;s=true}else{m[y++]=216;m[y++]=Zt;if(u)p+=_*u;if(l.length>=Kt-f)l.shift()[rr]=undefined;l.push(i);if(a<22)m[y++]=130+a;else ir(a+2);h(r);m[y++]=25;m[y++]=Zt;m[y++]=e;for(let e=0;e{let t;if(e>16777216){if(e-i>Xt)throw new Error("Encoded buffer would be larger than maximum buffer size");t=Math.min(Xt,Math.round(Math.max((e-i)*(e>67108864?1.25:2),16777216)/4096)*4096)}else t=(Math.max(e-i<<2,m.length-1)>>12)+1<<12;let r=new Ht(t);er=new DataView(r.buffer,0,t);if(m.copy)m.copy(r,0,i,e);else r.set(m.slice(i,e));y-=i;i=0;tr=r.length-10;return m=r}}useBuffer(e){m=e;er=new DataView(m.buffer,m.byteOffset,m.byteLength);y=0}}function ir(e){if(e<256){m[y++]=152;m[y++]=e}else if(e<65536){m[y++]=153;m[y++]=e>>8;m[y++]=e&255}else{m[y++]=154;er.setUint32(y,e);y+=4}}Gt=[Date,Set,Error,RegExp,ArrayBuffer,Qt,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,BigUint64Array,Int8Array,Int16Array,Int32Array,BigInt64Array,Float32Array,Float64Array];Jt=[{tag:1,encode(e,t){let r=e.getTime()/1e3;if((this.useTimestamp32||e.getMilliseconds()===0)&&r>=0&&r<4294967296){m[y++]=26;er.setUint32(y,r);y+=4}else{m[y++]=251;er.setFloat64(y,r);y+=8}}},{tag:258,encode(e,t){let r=Array.from(e);t(r)}},{tag:27,encode(e,t){t([e.name,e.message])}},{tag:27,encode(e,t){t(["RegExp",e.source,e.flags])}},{encode(e,t,r){ar(e,r)}},{encode(e,t,r){ar(e,r)}},ur(64),ur(68),ur(69),ur(70),ur(71),ur(72),ur(77),ur(78),ur(79),ur(81),ur(82)];function ur(e){return{tag:e,encode:function e(t,r){let n=t.byteLength;let i=t.byteOffset||0;let u=t.buffer||t;r(Wt?c.from(u,i,n):new Uint8Array(u,i,n))}}}function ar(e,t){let r=e.byteLength;if(r<24){m[y++]=64+r}else if(r<256){m[y++]=88;m[y++]=r}else if(r<65536){m[y++]=89;m[y++]=r>>8;m[y++]=r&255}else{m[y++]=90;er.setUint32(y,r);y+=4}if(y+r>=m.length){t(y+r)}m.set(e,y);y+=r}function or(n,e){let i;let u=e.length*8;let a=n.length-u;e.sort((e,t)=>e.offset>t.offset?1:-1);while(i=e.pop()){let e=i.offset;let t=i.id;n.copyWithin(e+u,e,a);u-=8;let r=e+u;n[r++]=217;n[r++]=40009>>8;n[r++]=40009&255;n[r++]=26;n[r++]=t>>24;n[r++]=t>>16&255;n[r++]=t>>8&255;n[r++]=t&255;a=e}return n}function sr(e){if(e.Class){if(!e.encode)throw new Error("Extension has no encode function");Gt.unshift(e.Class);Jt.unshift(e)}Yt(e)}let cr=new nr({useRecords:false});cr.encode;var fr={}; + */var ue=50;se.TYPED_ARRAY_SUPPORT=$.TYPED_ARRAY_SUPPORT!==undefined?$.TYPED_ARRAY_SUPPORT:true;ae();function ae(){return se.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function oe(e,t){if(ae()=ae()){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+ae().toString(16)+" bytes")}return e|0}se.isBuffer=tt;function me(e){return!!(e!=null&&e._isBuffer)}se.compare=function e(t,r){if(!me(t)||!me(r)){throw new TypeError("Arguments must be Buffers")}if(t===r)return 0;var n=t.length;var i=r.length;for(var u=0,a=Math.min(n,i);u>>1;case"base64":return Ze(e).length;default:if(n)return He(e).length;t=(""+t).toLowerCase();n=true}}}se.byteLength=ge;function be(e,t,r){var n=false;if(t===undefined||t<0){t=0}if(t>this.length){return""}if(r===undefined||r>this.length){r=this.length}if(r<=0){return""}r>>>=0;t>>>=0;if(r<=t){return""}if(!e)e="utf8";while(true){switch(e){case"hex":return Re(this,t,r);case"utf8":case"utf-8":return Be(this,t,r);case"ascii":return Pe(this,t,r);case"latin1":case"binary":return Ne(this,t,r);case"base64":return Se(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Te(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase();n=true}}}se.prototype._isBuffer=true;function we(e,t,r){var n=e[t];e[t]=e[r];e[r]=n}se.prototype.swap16=function e(){var t=this.length;if(t%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var r=0;r0){t=this.toString("hex",0,r).match(/.{2}/g).join(" ");if(this.length>r)t+=" ... "}return""};se.prototype.compare=function f(e,t,r,n,i){if(!me(e)){throw new TypeError("Argument must be a Buffer")}if(t===undefined){t=0}if(r===undefined){r=e?e.length:0}if(n===undefined){n=0}if(i===undefined){i=this.length}if(t<0||r>e.length||n<0||i>this.length){throw new RangeError("out of range index")}if(n>=i&&t>=r){return 0}if(n>=i){return-1}if(t>=r){return 1}t>>>=0;r>>>=0;n>>>=0;i>>>=0;if(this===e)return 0;var u=i-n;var a=r-t;var l=Math.min(u,a);var o=this.slice(n,i);var s=e.slice(t,r);for(var c=0;c2147483647){r=2147483647}else if(r<-2147483648){r=-2147483648}r=+r;if(isNaN(r)){r=i?0:e.length-1}if(r<0)r=e.length+r;if(r>=e.length){if(i)return-1;else r=e.length-1}else if(r<0){if(i)r=0;else return-1}if(typeof t==="string"){t=se.from(t,n)}if(me(t)){if(t.length===0){return-1}return Ee(e,t,r,n,i)}else if(typeof t==="number"){t=t&255;if(se.TYPED_ARRAY_SUPPORT&&typeof Uint8Array.prototype.indexOf==="function"){if(i){return Uint8Array.prototype.indexOf.call(e,t,r)}else{return Uint8Array.prototype.lastIndexOf.call(e,t,r)}}return Ee(e,[t],r,n,i)}throw new TypeError("val must be string, number or Buffer")}function Ee(e,t,r,n,f){var i=1;var u=e.length;var a=t.length;if(n!==undefined){n=String(n).toLowerCase();if(n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le"){if(e.length<2||t.length<2){return-1}i=2;u/=2;a/=2;r/=2}}function o(e,t){if(i===1){return e[t]}else{return e.readUInt16BE(t*i)}}var s;if(f){var c=-1;for(s=r;su)r=u-a;for(s=r;s>=0;s--){var l=true;for(var h=0;hi){n=i}}var u=t.length;if(u%2!==0)throw new TypeError("Invalid hex string");if(n>u/2){n=u/2}for(var a=0;au)n=u;if(t.length>0&&(n<0||r<0)||r>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!i)i="utf8";var a=false;for(;;){switch(i){case"hex":return Ae(this,t,r,n);case"utf8":case"utf-8":return xe(this,t,r,n);case"ascii":return Fe(this,t,r,n);case"latin1":case"binary":return ke(this,t,r,n);case"base64":return Ce(this,t,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Oe(this,t,r,n);default:if(a)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase();a=true}}};se.prototype.toJSON=function e(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Se(e,t,r){if(t===0&&r===e.length){return ee(e)}else{return ee(e.slice(t,r))}}function Be(e,f,t){t=Math.min(e.length,t);var r=[];var n=f;while(n239?4:i>223?3:i>191?2:1;if(n+a<=t){var o,s,l,c;switch(a){case 1:if(i<128){u=i}break;case 2:o=e[n+1];if((o&192)===128){c=(i&31)<<6|o&63;if(c>127){u=c}}break;case 3:o=e[n+1];s=e[n+2];if((o&192)===128&&(s&192)===128){c=(i&15)<<12|(o&63)<<6|s&63;if(c>2047&&(c<55296||c>57343)){u=c}}break;case 4:o=e[n+1];s=e[n+2];l=e[n+3];if((o&192)===128&&(s&192)===128&&(l&192)===128){c=(i&15)<<18|(o&63)<<12|(s&63)<<6|l&63;if(c>65535&&c<1114112){u=c}}}}if(u===null){u=65533;a=1}else if(u>65535){u-=65536;r.push(u>>>10&1023|55296);u=56320|u&1023}r.push(u);n+=a}return Ie(r)}var je=4096;function Ie(e){var t=e.length;if(t<=je){return String.fromCharCode.apply(String,e)}var r="";var n=0;while(nn)r=n;var i="";for(var u=t;un){t=n}if(r<0){r+=n;if(r<0)r=0}else if(r>n){r=n}if(rr)throw new RangeError("Trying to access beyond buffer length")}se.prototype.readUIntLE=function e(t,r,n){t=t|0;r=r|0;if(!n)Le(t,r,this.length);var i=this[t];var u=1;var a=0;while(++a0&&(u*=256)){i+=this[t+--r]*u}return i};se.prototype.readUInt8=function e(t,r){if(!r)Le(t,1,this.length);return this[t]};se.prototype.readUInt16LE=function e(t,r){if(!r)Le(t,2,this.length);return this[t]|this[t+1]<<8};se.prototype.readUInt16BE=function e(t,r){if(!r)Le(t,2,this.length);return this[t]<<8|this[t+1]};se.prototype.readUInt32LE=function e(t,r){if(!r)Le(t,4,this.length);return(this[t]|this[t+1]<<8|this[t+2]<<16)+this[t+3]*16777216};se.prototype.readUInt32BE=function e(t,r){if(!r)Le(t,4,this.length);return this[t]*16777216+(this[t+1]<<16|this[t+2]<<8|this[t+3])};se.prototype.readIntLE=function e(t,r,n){t=t|0;r=r|0;if(!n)Le(t,r,this.length);var i=this[t];var u=1;var a=0;while(++a=u)i-=Math.pow(2,8*r);return i};se.prototype.readIntBE=function e(t,r,n){t=t|0;r=r|0;if(!n)Le(t,r,this.length);var i=r;var u=1;var a=this[t+--i];while(i>0&&(u*=256)){a+=this[t+--i]*u}u*=128;if(a>=u)a-=Math.pow(2,8*r);return a};se.prototype.readInt8=function e(t,r){if(!r)Le(t,1,this.length);if(!(this[t]&128))return this[t];return(255-this[t]+1)*-1};se.prototype.readInt16LE=function e(t,r){if(!r)Le(t,2,this.length);var n=this[t]|this[t+1]<<8;return n&32768?n|4294901760:n};se.prototype.readInt16BE=function e(t,r){if(!r)Le(t,2,this.length);var n=this[t+1]|this[t]<<8;return n&32768?n|4294901760:n};se.prototype.readInt32LE=function e(t,r){if(!r)Le(t,4,this.length);return this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24};se.prototype.readInt32BE=function e(t,r){if(!r)Le(t,4,this.length);return this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]};se.prototype.readFloatLE=function e(t,r){if(!r)Le(t,4,this.length);return te(this,t,true,23,4)};se.prototype.readFloatBE=function e(t,r){if(!r)Le(t,4,this.length);return te(this,t,false,23,4)};se.prototype.readDoubleLE=function e(t,r){if(!r)Le(t,8,this.length);return te(this,t,true,52,8)};se.prototype.readDoubleBE=function e(t,r){if(!r)Le(t,8,this.length);return te(this,t,false,52,8)};function Ue(e,t,r,n,i,u){if(!me(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}se.prototype.writeUIntLE=function e(t,r,n,i){t=+t;r=r|0;n=n|0;if(!i){var u=Math.pow(2,8*n)-1;Ue(this,t,r,n,u,0)}var a=1;var o=0;this[r]=t&255;while(++o=0&&(o*=256)){this[r+a]=t/o&255}return r+n};se.prototype.writeUInt8=function e(t,r,n){t=+t;r=r|0;if(!n)Ue(this,t,r,1,255,0);if(!se.TYPED_ARRAY_SUPPORT)t=Math.floor(t);this[r]=t&255;return r+1};function Me(e,t,r,n){if(t<0)t=65535+t+1;for(var i=0,u=Math.min(e.length-r,2);i>>(n?i:1-i)*8}}se.prototype.writeUInt16LE=function e(t,r,n){t=+t;r=r|0;if(!n)Ue(this,t,r,2,65535,0);if(se.TYPED_ARRAY_SUPPORT){this[r]=t&255;this[r+1]=t>>>8}else{Me(this,t,r,true)}return r+2};se.prototype.writeUInt16BE=function e(t,r,n){t=+t;r=r|0;if(!n)Ue(this,t,r,2,65535,0);if(se.TYPED_ARRAY_SUPPORT){this[r]=t>>>8;this[r+1]=t&255}else{Me(this,t,r,false)}return r+2};function qe(e,t,r,n){if(t<0)t=4294967295+t+1;for(var i=0,u=Math.min(e.length-r,4);i>>(n?i:3-i)*8&255}}se.prototype.writeUInt32LE=function e(t,r,n){t=+t;r=r|0;if(!n)Ue(this,t,r,4,4294967295,0);if(se.TYPED_ARRAY_SUPPORT){this[r+3]=t>>>24;this[r+2]=t>>>16;this[r+1]=t>>>8;this[r]=t&255}else{qe(this,t,r,true)}return r+4};se.prototype.writeUInt32BE=function e(t,r,n){t=+t;r=r|0;if(!n)Ue(this,t,r,4,4294967295,0);if(se.TYPED_ARRAY_SUPPORT){this[r]=t>>>24;this[r+1]=t>>>16;this[r+2]=t>>>8;this[r+3]=t&255}else{qe(this,t,r,false)}return r+4};se.prototype.writeIntLE=function e(t,r,n,i){t=+t;r=r|0;if(!i){var u=Math.pow(2,8*n-1);Ue(this,t,r,n,u-1,-u)}var a=0;var o=1;var s=0;this[r]=t&255;while(++a>0)-s&255}return r+n};se.prototype.writeIntBE=function e(t,r,n,i){t=+t;r=r|0;if(!i){var u=Math.pow(2,8*n-1);Ue(this,t,r,n,u-1,-u)}var a=n-1;var o=1;var s=0;this[r+a]=t&255;while(--a>=0&&(o*=256)){if(t<0&&s===0&&this[r+a+1]!==0){s=1}this[r+a]=(t/o>>0)-s&255}return r+n};se.prototype.writeInt8=function e(t,r,n){t=+t;r=r|0;if(!n)Ue(this,t,r,1,127,-128);if(!se.TYPED_ARRAY_SUPPORT)t=Math.floor(t);if(t<0)t=255+t+1;this[r]=t&255;return r+1};se.prototype.writeInt16LE=function e(t,r,n){t=+t;r=r|0;if(!n)Ue(this,t,r,2,32767,-32768);if(se.TYPED_ARRAY_SUPPORT){this[r]=t&255;this[r+1]=t>>>8}else{Me(this,t,r,true)}return r+2};se.prototype.writeInt16BE=function e(t,r,n){t=+t;r=r|0;if(!n)Ue(this,t,r,2,32767,-32768);if(se.TYPED_ARRAY_SUPPORT){this[r]=t>>>8;this[r+1]=t&255}else{Me(this,t,r,false)}return r+2};se.prototype.writeInt32LE=function e(t,r,n){t=+t;r=r|0;if(!n)Ue(this,t,r,4,2147483647,-2147483648);if(se.TYPED_ARRAY_SUPPORT){this[r]=t&255;this[r+1]=t>>>8;this[r+2]=t>>>16;this[r+3]=t>>>24}else{qe(this,t,r,true)}return r+4};se.prototype.writeInt32BE=function e(t,r,n){t=+t;r=r|0;if(!n)Ue(this,t,r,4,2147483647,-2147483648);if(t<0)t=4294967295+t+1;if(se.TYPED_ARRAY_SUPPORT){this[r]=t>>>24;this[r+1]=t>>>16;this[r+2]=t>>>8;this[r+3]=t&255}else{qe(this,t,r,false)}return r+4};function Ye(e,t,r,n,i,u){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Ve(e,t,r,n,i){if(!i){Ye(e,t,r,4)}re(e,t,r,n,23,4);return r+4}se.prototype.writeFloatLE=function e(t,r,n){return Ve(this,t,r,true,n)};se.prototype.writeFloatBE=function e(t,r,n){return Ve(this,t,r,false,n)};function ze(e,t,r,n,i){if(!i){Ye(e,t,r,8)}re(e,t,r,n,52,8);return r+8}se.prototype.writeDoubleLE=function e(t,r,n){return ze(this,t,r,true,n)};se.prototype.writeDoubleBE=function e(t,r,n){return ze(this,t,r,false,n)};se.prototype.copy=function e(t,r,n,i){if(!n)n=0;if(!i&&i!==0)i=this.length;if(r>=t.length)r=t.length;if(!r)r=0;if(i>0&&i=this.length)throw new RangeError("sourceStart out of bounds");if(i<0)throw new RangeError("sourceEnd out of bounds");if(i>this.length)i=this.length;if(t.length-r=0;--a){t[a+r]=this[a+n]}}else if(u<1e3||!se.TYPED_ARRAY_SUPPORT){for(a=0;a>>0;n=n===undefined?this.length:n>>>0;if(!t)t=0;var a;if(typeof t==="number"){for(a=r;a55295&&r<57344){if(!i){if(r>56319){if((t-=3)>-1)u.push(239,191,189);continue}else if(a+1===n){if((t-=3)>-1)u.push(239,191,189);continue}i=r;continue}if(r<56320){if((t-=3)>-1)u.push(239,191,189);i=r;continue}r=(i-55296<<10|r-56320)+65536}else if(i){if((t-=3)>-1)u.push(239,191,189)}i=null;if(r<128){if((t-=1)<0)break;u.push(r)}else if(r<2048){if((t-=2)<0)break;u.push(r>>6|192,r&63|128)}else if(r<65536){if((t-=3)<0)break;u.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((t-=4)<0)break;u.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else{throw new Error("Invalid code point")}}return u}function We(e){var t=[];for(var r=0;r>8;i=r%256;u.push(i);u.push(n)}return u}function Ze(e){return Q(Je(e))}function Xe(e,t,r,n){for(var i=0;i=t.length||i>=e.length)break;t[i+r]=e[i]}return i}function et(e){return e!==e}function tt(e){return e!=null&&(!!e._isBuffer||rt(e)||nt(e))}function rt(e){return!!e.constructor&&typeof e.constructor.isBuffer==="function"&&e.constructor.isBuffer(e)}function nt(e){return typeof e.readFloatLE==="function"&&typeof e.slice==="function"&&rt(e.slice(0,0))}let it;try{it=new TextDecoder}catch(e){}let ut;let at;let v=0;const ot=105;const st=57342;const ct=57343;const ft=57337;const lt=6;const ht={};let pt={};let _t;let dt;let vt=0;let yt=0;let mt;let gt;let bt=[];let wt=[];let Dt;let Et;let At;let xt={useRecords:false,mapsAsObjects:true};let Ft=false;let kt=2;try{new Function("")}catch(e){kt=Infinity}class Ct{constructor(r){if(r){if((r.keyMap||r._keyMap)&&!r.useRecords){r.useRecords=false;r.mapsAsObjects=true}if(r.useRecords===false&&r.mapsAsObjects===undefined)r.mapsAsObjects=true;if(r.getStructures)r.getShared=r.getStructures;if(r.getShared&&!r.structures)(r.structures=[]).uninitialized=true;if(r.keyMap){this.mapKey=new Map;for(let[e,t]of Object.entries(r.keyMap))this.mapKey.set(t,e)}}Object.assign(this,r)}decodeKey(e){return this.keyMap?this.mapKey.get(e)||e:e}encodeKey(e){return this.keyMap&&this.keyMap.hasOwnProperty(e)?this.keyMap[e]:e}encodeKeys(r){if(!this._keyMap)return r;let n=new Map;for(let[e,t]of Object.entries(r))n.set(this._keyMap.hasOwnProperty(e)?this._keyMap[e]:e,t);return n}decodeKeys(e){if(!this._keyMap||e.constructor.name!="Map")return e;if(!this._mapKey){this._mapKey=new Map;for(let[e,t]of Object.entries(this._keyMap))this._mapKey.set(t,e)}let r={};e.forEach((e,t)=>r[It(this._mapKey.has(t)?this._mapKey.get(t):t)]=e);return r}mapDecode(e,t){let r=this.decode(e);if(this._keyMap){switch(r.constructor.name){case"Array":return r.map(e=>this.decodeKeys(e))}}return r}decode(t,e){if(ut){return nr(()=>{ir();return this?this.decode(t,e):Ct.prototype.decode.call(xt,t,e)})}at=e>-1?e:t.length;v=0;yt=0;dt=null;mt=null;ut=t;try{Et=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))}catch(e){ut=null;if(t instanceof Uint8Array)throw e;throw new Error("Source must be a Uint8Array or Buffer but was a "+(t&&typeof t=="object"?t.constructor.name:typeof t))}if(this instanceof Ct){pt=this;Dt=this.sharedValues&&(this.pack?new Array(this.maxPrivatePackedValues||16).concat(this.sharedValues):this.sharedValues);if(this.structures){_t=this.structures;return Ot()}else if(!_t||_t.length>0){_t=[]}}else{pt=xt;if(!_t||_t.length>0)_t=[];Dt=null}return Ot()}decodeMultiple(r,n){let i,u=0;try{let e=r.length;Ft=true;let t=this?this.decode(r,e):or.decode(r,e);if(n){if(n(t)===false){return}while(v=mt.postBundlePosition){let e=new Error("Unexpected bundle position");e.incomplete=true;throw e}v=mt.postBundlePosition;mt=null}if(v==at){_t=null;ut=null;if(gt)gt=null}else if(v>at){let e=new Error("Unexpected end of CBOR data");e.incomplete=true;throw e}else if(!Ft){throw new Error("Data read, but end of buffer not reached")}return e}catch(e){ir();if(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")){e.incomplete=true}throw e}}function St(){let n=ut[v++];let i=n>>5;n=n&31;if(n>23){switch(n){case 24:n=ut[v++];break;case 25:if(i==7){return Yt()}n=Et.getUint16(v);v+=2;break;case 26:if(i==7){let t=Et.getFloat32(v);if(pt.useFloat32>2){let e=ar[(ut[v]&127)<<1|ut[v+1]>>7];v+=4;return(e*t+(t>0?.5:-.5)>>0)/e}v+=4;return t}n=Et.getUint32(v);v+=4;break;case 27:if(i==7){let e=Et.getFloat64(v);v+=8;return e}if(i>1){if(Et.getUint32(v)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");n=Et.getUint32(v+4)}else if(pt.int64AsNumber){n=Et.getUint32(v)*4294967296;n+=Et.getUint32(v+4)}else n=Et.getBigUint64(v);v+=8;break;case 31:switch(i){case 2:case 3:throw new Error("Indefinite length not supported for byte or text strings");case 4:let e=[];let t,r=0;while((t=St())!=ht){e[r++]=t}return i==4?e:i==3?e.join(""):se.concat(e);case 5:let n;if(pt.mapsAsObjects){let e={};if(pt.keyMap)while((n=St())!=ht)e[It(pt.decodeKey(n))]=St();else while((n=St())!=ht)e[It(n)]=St();return e}else{if(At){pt.mapsAsObjects=true;At=false}let e=new Map;if(pt.keyMap)while((n=St())!=ht)e.set(pt.decodeKey(n),St());else while((n=St())!=ht)e.set(n,St());return e}case 7:return ht;default:throw new Error("Invalid major type for indefinite length "+i)}default:throw new Error("Unknown token "+n)}}switch(i){case 0:return n;case 1:return~n;case 2:return Ut(n);case 3:if(yt>=v){return dt.slice(v-vt,(v+=n)-vt)}if(yt==0&&at<140&&n<32){let e=n<16?Lt(n):Tt(n);if(e!=null)return e}return Pt(n);case 4:let t=new Array(n);for(let e=0;e=ft){let e=_t[n&8191];if(e){if(!e.read)e.read=jt(e);return e.read()}if(n<65536){if(n==ct){let e=tr();let t=St();let r=St();zt(t,r);let n={};if(pt.keyMap)for(let t=2;t23){switch(t){case 24:t=ut[v++];break;case 25:t=Et.getUint16(v);v+=2;break;case 26:t=Et.getUint32(v);v+=4;break;default:throw new Error("Expected array header, but got "+ut[v-1])}}let r=this.compiledReader;while(r){if(r.propertyCount===t)return r(St);r=r.next}if(this.slowReads++>=kt){let e=this.length==t?this:this.slice(0,t);r=pt.keyMap?new Function("r","return {"+e.map(e=>pt.decodeKey(e)).map(e=>Bt.test(e)?It(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}"):new Function("r","return {"+e.map(e=>Bt.test(e)?It(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}");if(this.compiledReader)r.next=this.compiledReader;r.propertyCount=t;this.compiledReader=r;return r(St)}let n={};if(pt.keyMap)for(let e=0;e64&&it)return it.decode(ut.subarray(v,v+=e));const r=v+e;const n=[];t="";while(v65535){e-=65536;n.push(e>>>10&1023|55296);e=56320|e&1023}n.push(e)}else{n.push(i)}if(n.length>=4096){t+=Rt.apply(String,n);n.length=0}}if(n.length>0){t+=Rt.apply(String,n)}return t}let Rt=String.fromCharCode;function Tt(t){let r=v;let n=new Array(t);for(let e=0;e0){v=r;return}n[e]=i}return Rt.apply(String,n)}function Lt(d){if(d<4){if(d<2){if(d===0)return"";else{let e=ut[v++];if((e&128)>1){v-=1;return}return Rt(e)}}else{let e=ut[v++];let t=ut[v++];if((e&128)>0||(t&128)>0){v-=2;return}if(d<3)return Rt(e,t);let r=ut[v++];if((r&128)>0){v-=3;return}return Rt(e,t,r)}}else{let l=ut[v++];let h=ut[v++];let p=ut[v++];let _=ut[v++];if((l&128)>0||(h&128)>0||(p&128)>0||(_&128)>0){v-=4;return}if(d<6){if(d===4)return Rt(l,h,p,_);else{let e=ut[v++];if((e&128)>0){v-=5;return}return Rt(l,h,p,_,e)}}else if(d<8){let e=ut[v++];let t=ut[v++];if((e&128)>0||(t&128)>0){v-=6;return}if(d<7)return Rt(l,h,p,_,e,t);let r=ut[v++];if((r&128)>0){v-=7;return}return Rt(l,h,p,_,e,t,r)}else{let o=ut[v++];let s=ut[v++];let c=ut[v++];let f=ut[v++];if((o&128)>0||(s&128)>0||(c&128)>0||(f&128)>0){v-=8;return}if(d<10){if(d===8)return Rt(l,h,p,_,o,s,c,f);else{let e=ut[v++];if((e&128)>0){v-=9;return}return Rt(l,h,p,_,o,s,c,f,e)}}else if(d<12){let e=ut[v++];let t=ut[v++];if((e&128)>0||(t&128)>0){v-=10;return}if(d<11)return Rt(l,h,p,_,o,s,c,f,e,t);let r=ut[v++];if((r&128)>0){v-=11;return}return Rt(l,h,p,_,o,s,c,f,e,t,r)}else{let n=ut[v++];let i=ut[v++];let u=ut[v++];let a=ut[v++];if((n&128)>0||(i&128)>0||(u&128)>0||(a&128)>0){v-=12;return}if(d<14){if(d===12)return Rt(l,h,p,_,o,s,c,f,n,i,u,a);else{let e=ut[v++];if((e&128)>0){v-=13;return}return Rt(l,h,p,_,o,s,c,f,n,i,u,a,e)}}else{let e=ut[v++];let t=ut[v++];if((e&128)>0||(t&128)>0){v-=14;return}if(d<15)return Rt(l,h,p,_,o,s,c,f,n,i,u,a,e,t);let r=ut[v++];if((r&128)>0){v-=15;return}return Rt(l,h,p,_,o,s,c,f,n,i,u,a,e,t,r)}}}}}function Ut(e){return pt.copyBuffers?Uint8Array.prototype.slice.call(ut,v,v+=e):ut.subarray(v,v+=e)}let Mt=new Float32Array(1);let qt=new Uint8Array(Mt.buffer,0,4);function Yt(){let t=ut[v++];let r=ut[v++];let e=(t&127)>>2;if(e===31){if(r||t&3)return NaN;return t&128?-Infinity:Infinity}if(e===0){let e=((t&3)<<8|r)/(1<<24);return t&128?-e:e}qt[3]=t&128|(e>>1)+56;qt[2]=(t&7)<<5|r>>3;qt[1]=r<<5;qt[0]=0;return Mt[0]}new Array(4096);class Vt{constructor(e,t){this.value=e;this.tag=t}}bt[0]=e=>{return new Date(e)};bt[1]=e=>{return new Date(Math.round(e*1e3))};bt[2]=r=>{let n=BigInt(0);for(let e=0,t=r.byteLength;e{return BigInt(-1)-bt[2](e)};bt[4]=e=>{return+(e[1]+"e"+e[0])};bt[5]=e=>{return e[1]*Math.exp(e[0]*Math.log(2))};const zt=(e,t)=>{e=e-57344;let r=_t[e];if(r&&r.isShared){(_t.restoreStructures||(_t.restoreStructures=[]))[e]=r}_t[e]=t;t.read=jt(t)};bt[ot]=r=>{let e=r.length;let n=r[1];zt(r[0],n);let i={};for(let t=2;t{if(mt)return mt[0].slice(mt.position0,mt.position0+=e);return new Vt(e,14)};bt[15]=e=>{if(mt)return mt[1].slice(mt.position1,mt.position1+=e);return new Vt(e,15)};let $t={Error:Error,RegExp:RegExp};bt[27]=e=>{return($t[e[0]]||Error)(e[1],e[2])};const Jt=e=>{if(ut[v++]!=132)throw new Error("Packed values structure must be followed by a 4 element array");let t=e();Dt=Dt?t.concat(Dt.slice(t.length)):t;Dt.prefixes=e();Dt.suffixes=e();return e()};Jt.handlesRead=true;bt[51]=Jt;bt[lt]=e=>{if(!Dt){if(pt.getShared)rr();else return new Vt(e,lt)}if(typeof e=="number")return Dt[16+(e>=0?2*e:-2*e-1)];throw new Error("No support for non-integer packed references yet")};bt[28]=e=>{if(!gt){gt=new Map;gt.id=0}let t=gt.id++;let r=ut[v];let n;if(r>>5==4)n=[];else n={};let i={target:n};gt.set(t,i);let u=e();if(i.used)return Object.assign(n,u);i.target=u;return u};bt[28].handlesRead=true;bt[29]=e=>{let t=gt.get(e);t.used=true;return t.target};bt[258]=e=>new Set(e);(bt[259]=e=>{if(pt.mapsAsObjects){pt.mapsAsObjects=false;At=true}return e()}).handlesRead=true;function Kt(e,t){if(typeof e==="string")return e+t;if(e instanceof Array)return e.concat(t);return Object.assign({},e,t)}function Gt(){if(!Dt){if(pt.getShared)rr();else throw new Error("No packed values available")}return Dt}const Ht=1399353956;wt.push((e,t)=>{if(e>=225&&e<=255)return Kt(Gt().prefixes[e-224],t);if(e>=28704&&e<=32767)return Kt(Gt().prefixes[e-28672],t);if(e>=1879052288&&e<=2147483647)return Kt(Gt().prefixes[e-1879048192],t);if(e>=216&&e<=223)return Kt(t,Gt().suffixes[e-216]);if(e>=27647&&e<=28671)return Kt(t,Gt().suffixes[e-27639]);if(e>=1811940352&&e<=1879048191)return Kt(t,Gt().suffixes[e-1811939328]);if(e==Ht){return{packedValues:Dt,structures:_t.slice(0),version:t}}if(e==55799)return t});const Wt=new Uint8Array(new Uint16Array([1]).buffer)[0]==1;const Qt=[Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,typeof BigUint64Array=="undefined"?{name:"BigUint64Array"}:BigUint64Array,Int8Array,Int16Array,Int32Array,typeof BigInt64Array=="undefined"?{name:"BigInt64Array"}:BigInt64Array,Float32Array,Float64Array];const Zt=[64,68,69,70,71,72,77,78,79,85,86];for(let e=0;e{if(!o)throw new Error("Could not find typed array for code "+s);return new o(Uint8Array.prototype.slice.call(e,0).buffer)}:e=>{if(!o)throw new Error("Could not find typed array for code "+s);let t=new DataView(e.buffer,e.byteOffset,e.byteLength);let r=e.length>>u;let n=new o(r);let i=t[c];for(let e=0;e23){switch(e){case 24:e=ut[v++];break;case 25:e=Et.getUint16(v);v+=2;break;case 26:e=Et.getUint32(v);v+=4;break}}return e}function rr(){if(pt.getShared){let e=nr(()=>{ut=null;return pt.getShared()})||{};let t=e.structures||[];pt.sharedVersion=e.version;Dt=pt.sharedValues=e.packedValues;if(_t===true)pt.structures=_t=t;else _t.splice.apply(_t,[0,t.length].concat(t))}}function nr(e){let t=at;let r=v;let n=vt;let i=yt;let u=dt;let a=gt;let o=mt;let s=new Uint8Array(ut.slice(0,at));let c=_t;let f=pt;let l=Ft;let h=e();at=t;v=r;vt=n;yt=i;dt=u;gt=a;mt=o;ut=s;Ft=l;_t=c;pt=f;Et=new DataView(ut.buffer,ut.byteOffset,ut.byteLength);return h}function ir(){ut=null;gt=null;_t=null}function ur(e){bt[e.tag]=e.decode}const ar=new Array(147);for(let e=0;e<256;e++){ar[e]=+("1e"+Math.floor(45.15-e*.30103))}let or=new Ct({useRecords:false});or.decode;or.decodeMultiple;let sr;try{sr=new TextEncoder}catch(e){}let cr,fr;const lr=typeof globalThis==="object"&&globalThis.Buffer;const hr=typeof lr!=="undefined";const pr=hr?lr.allocUnsafeSlow:Uint8Array;const _r=hr?lr:Uint8Array;const dr=256;const vr=hr?4294967296:2144337920;let yr;let O;let mr;let S=0;let gr;let br=null;const wr=61440;const Dr=/[\u0080-\uFFFF]/;const Er=Symbol("record-id");class Ar extends Ct{constructor(r){super(r);this.offset=0;let s;let a;let _;let f;let n;r=r||{};let c=_r.prototype.utf8Write?function(e,t,r){return O.utf8Write(e,t,r)}:sr&&sr.encodeInto?function(e,t){return sr.encodeInto(e,O.subarray(t)).written}:false;let u=this;let e=r.structures||r.saveStructures;let l=r.maxSharedStructures;if(l==null)l=e?128:0;if(l>8190)throw new Error("Maximum maxSharedStructure is 8190");let o=r.sequential;if(o){l=0}if(!this.structures)this.structures=[];if(this.saveStructures)this.saveShared=this.saveStructures;let d,v,y=r.sharedValues;let i;if(y){i=Object.create(null);for(let e=0,t=y.length;ethis.encodeKeys(e));break}}return this.encode(e,t)};this.encode=function(t,e){if(!O){O=new pr(8192);mr=new DataView(O.buffer,0,8192);S=0}gr=O.length-10;if(gr-S<2048){O=new pr(O.length);mr=new DataView(O.buffer,0,O.length);gr=O.length-10;S=0}else if(e===Lr)S=S+7&2147483640;s=S;if(u.useSelfDescribedHeader){mr.setUint32(S,3654940416);S+=3}n=u.structuredClone?new Map:null;if(u.bundleStrings&&typeof t!=="string"){br=[];br.size=Infinity}else br=null;a=u.structures;if(a){if(a.uninitialized){let e=u.getShared()||{};u.structures=a=e.structures||[];u.sharedVersion=e.version;let r=u.sharedValues=e.packedValues;if(r){i={};for(let e=0,t=r.length;el&&!o)e=l;if(!a.transitions){a.transitions=Object.create(null);for(let u=0;u0){O[S++]=216;O[S++]=51;kr(4);let r=e.values;p(r);kr(0);kr(0);v=Object.create(i||null);for(let e=0,t=r.length;egr)w(S);u.offset=S;let e=Pr(O.subarray(s,S),n.idsToInsert);n=null;return e}if(e&Lr){O.start=s;O.end=S;return O}return O.subarray(s,S)}finally{if(a){if(g<10)g++;if(a.length>l)a.length=l;if(m>1e4){a.transitions=null;g=0;m=0;if(h.length>0)h=[]}else if(h.length>0&&!o){for(let e=0,t=h.length;el){u.structures=u.structures.slice(0,l)}let e=O.subarray(s,S);if(u.updateSharedData()===false)return u.encode(t);return e}if(e&Ur)S=s}};this.findCommonStringsToPack=()=>{d=new Map;if(!i)i=Object.create(null);return e=>{let r=e&&e.threshold||4;let n=this.pack?e.maxPrivatePackedValues||16:0;if(!y)y=this.sharedValues=[];for(let[e,t]of d){if(t.count>r){i[e]=n++;y.push(e);_=true}}while(this.saveShared&&this.updateSharedData()===false){}d=null}};const p=a=>{if(S>gr)O=w(S);var e=typeof a;var o;if(e==="string"){if(v){let e=v[a];if(e>=0){if(e<16)O[S++]=e+224;else{O[S++]=198;if(e&1)p(15-e>>1);else p(e-16>>1)}return}else if(d&&!r.pack){let e=d.get(a);if(e)e.count++;else d.set(a,{count:1})}}let i=a.length;if(br&&i>=4&&i<1024){if((br.size+=i)>wr){let e;let t=(br[0]?br[0].length*3+br[1].length:0)+10;if(S+t>gr)O=w(S+t);O[S++]=217;O[S++]=223;O[S++]=249;O[S++]=br.position?132:130;O[S++]=26;e=S-s;S+=4;if(br.position){Nr(s,p)}br=["",""];br.size=0;br.position=e}let e=Dr.test(a);br[e?0:1]+=a;O[S++]=e?206:207;p(i);return}let u;if(i<32){u=1}else if(i<256){u=2}else if(i<65536){u=3}else{u=5}let e=i*3;if(S+e>gr)O=w(S+e);if(i<64||!c){let e,t,r,n=S+u;for(e=0;e>6|192;O[n++]=t&63|128}else if((t&64512)===55296&&((r=a.charCodeAt(e+1))&64512)===56320){t=65536+((t&1023)<<10)+(r&1023);e++;O[n++]=t>>18|240;O[n++]=t>>12&63|128;O[n++]=t>>6&63|128;O[n++]=t&63|128}else{O[n++]=t>>12|224;O[n++]=t>>6&63|128;O[n++]=t&63|128}}o=n-S-u}else{o=c(a,S+u,e)}if(o<24){O[S++]=96|o}else if(o<256){if(u<2){O.copyWithin(S+2,S+1,S+1+o)}O[S++]=120;O[S++]=o}else if(o<65536){if(u<3){O.copyWithin(S+3,S+2,S+2+o)}O[S++]=121;O[S++]=o>>8;O[S++]=o&255}else{if(u<5){O.copyWithin(S+5,S+3,S+3+o)}O[S++]=122;mr.setUint32(S,o);S+=4}S+=o}else if(e==="number"){if(!this.alwaysUseFloat&&a>>>0===a){if(a<24){O[S++]=a}else if(a<256){O[S++]=24;O[S++]=a}else if(a<65536){O[S++]=25;O[S++]=a>>8;O[S++]=a&255}else{O[S++]=26;mr.setUint32(S,a);S+=4}}else if(!this.alwaysUseFloat&&a>>0===a){if(a>=-24){O[S++]=31-a}else if(a>=-256){O[S++]=56;O[S++]=~a}else if(a>=-65536){O[S++]=57;mr.setUint16(S,~a);S+=2}else{O[S++]=58;mr.setUint32(S,~a);S+=4}}else{let t;if((t=this.useFloat32)>0&&a<4294967296&&a>=-2147483648){O[S++]=250;mr.setFloat32(S,a);let e;if(t<4||(e=a*ar[(O[S]&127)<<1|O[S+1]>>7])>>0===e){S+=4;return}else S--}O[S++]=251;mr.setFloat64(S,a);S+=8}}else if(e==="object"){if(!a)O[S++]=246;else{if(n){let t=n.get(a);if(t){O[S++]=216;O[S++]=29;O[S++]=25;if(!t.references){let e=n.idsToInsert||(n.idsToInsert=[]);t.references=[];e.push(t)}t.references.push(S-s);S+=2;return}else n.set(a,{offset:S-s})}let e=a.constructor;if(e===Object){b(a,true)}else if(e===Array){o=a.length;if(o<24){O[S++]=128|o}else{kr(o)}for(let e=0;e>8;O[S++]=o&255}else{O[S++]=186;mr.setUint32(S,o);S+=4}if(u.keyMap){for(let[e,t]of a){p(u.encodeKey(e));p(t)}}else{for(let[e,t]of a){p(e);p(t)}}}else{for(let r=0,e=cr.length;r>8;O[S++]=t&255}else if(t>-1){O[S++]=218;mr.setUint32(S,t);S+=4}e.encode.call(this,a,p,w);return}}if(a[Symbol.iterator]){if(yr){let e=new Error("Iterable should be serialized as iterator");e.iteratorNotHandled=true;throw e}O[S++]=159;for(let e of a){p(e)}O[S++]=255;return}if(a[Symbol.asyncIterator]||Or(a)){let e=new Error("Iterable/blob should be serialized as iterator");e.iteratorNotHandled=true;throw e}if(this.useToJSON&&a.toJSON){const t=a.toJSON();if(t!==a)return p(t)}b(a,!a.hasOwnProperty)}}}else if(e==="boolean"){O[S++]=a?245:244}else if(e==="bigint"){if(a=0){O[S++]=27;mr.setBigUint64(S,a)}else if(a>-(BigInt(1)<{let t=Object.keys(e);let r=Object.values(e);let n=t.length;if(n<24){O[S++]=160|n}else if(n<256){O[S++]=184;O[S++]=n}else if(n<65536){O[S++]=185;O[S++]=n>>8;O[S++]=n&255}else{O[S++]=186;mr.setUint32(S,n);S+=4}if(u.keyMap){for(let e=0;e{O[S++]=185;let e=S-s;S+=2;let n=0;if(u.keyMap){for(let e in t)if(r||t.hasOwnProperty(e)){p(u.encodeKey(e));p(t[e]);n++}}else{for(let e in t)if(r||t.hasOwnProperty(e)){p(e);p(t[e]);n++}}O[e+++s]=n>>8;O[e+s]=n&255}:(t,r)=>{let n,i=f.transitions||(f.transitions=Object.create(null));let u=0;let a=0;let o;let s;if(this.keyMap){s=Object.keys(t).map(e=>this.encodeKey(e));a=s.length;for(let t=0;t>8|224;O[S++]=c&255}else{if(!s)s=i.__keys__||(i.__keys__=Object.keys(t));if(o===undefined){c=f.nextId++;if(!c){c=0;f.nextId=1}if(c>=dr){f.nextId=(c=l)+1}}else{c=o}f[c]=s;if(c>8|224;O[S++]=c&255;i=f.transitions;for(let e=0;e=dr-l)h.shift()[Er]=undefined;h.push(i);kr(a+2);p(57344+c);p(s);if(r===null)return;for(let e in t)if(r||t.hasOwnProperty(e))p(t[e]);return}}if(a<24){O[S++]=128|a}else{kr(a)}if(r===null)return;for(let e in t)if(r||t.hasOwnProperty(e))p(t[e])};const w=e=>{let t;if(e>16777216){if(e-s>vr)throw new Error("Encoded buffer would be larger than maximum buffer size");t=Math.min(vr,Math.round(Math.max((e-s)*(e>67108864?1.25:2),4194304)/4096)*4096)}else t=(Math.max(e-s<<2,O.length-1)>>12)+1<<12;let r=new pr(t);mr=new DataView(r.buffer,0,t);if(O.copy)O.copy(r,0,s,e);else r.set(O.slice(s,e));S-=s;s=0;gr=r.length-10;return O=r};let D=100;let E=1e3;this.encodeAsIterable=function(e,t){return k(e,t,A)};this.encodeAsAsyncIterable=function(e,t){return k(e,t,C)};function*A(n,i,e){let t=n.constructor;if(t===Object){let r=u.useRecords!==false;if(r)b(n,null);else xr(Object.keys(n).length,160);for(let t in n){let e=n[t];if(!r)p(t);if(e&&typeof e==="object"){if(i[t])yield*A(e,i[t]);else yield*x(e,i,t)}else p(e)}}else if(t===Array){let e=n.length;kr(e);for(let t=0;tD)){if(i.element)yield*A(e,i.element);else yield*x(e,i,"element")}else p(e)}}else if(n[Symbol.iterator]){O[S++]=159;for(let e of n){if(e&&(typeof e==="object"||S-s>D)){if(i.element)yield*A(e,i.element);else yield*x(e,i,"element")}else p(e)}O[S++]=255}else if(Or(n)){xr(n.size,64);yield O.subarray(s,S);yield n;F()}else if(n[Symbol.asyncIterator]){O[S++]=159;yield O.subarray(s,S);yield n;F();O[S++]=255}else{p(n)}if(e&&S>s)yield O.subarray(s,S);else if(S-s>D){yield O.subarray(s,S);F()}}function*x(t,r,n){let i=S-s;try{p(t);if(S-s>D){yield O.subarray(s,S);F()}}catch(e){if(e.iteratorNotHandled){r[n]={};S=s+i;yield*A.call(this,t,r[n])}else throw e}}function F(){D=E;u.encode(null,Mr)}function k(e,t,r){if(t&&t.chunkThreshold)D=E=t.chunkThreshold;else D=100;if(e&&typeof e==="object"){u.encode(null,Mr);return r(e,u.iterateProperties||(u.iterateProperties={}),true)}return[u.encode(e)]}async function*C(e,t){for(let r of A(e,t,true)){let e=r.constructor;if(e===_r||e===Uint8Array)yield r;else if(Or(r)){let e=r.stream().getReader();let t;while(!(t=await e.read()).done){yield t.value}}else if(r[Symbol.asyncIterator]){for await(let e of r){F();if(e)yield*C(e,t.async||(t.async={}));else yield u.encode(e)}}else{yield r}}}}useBuffer(e){O=e;mr=new DataView(O.buffer,O.byteOffset,O.byteLength);S=0}clearSharedData(){if(this.structures)this.structures=[];if(this.sharedValues)this.sharedValues=undefined}updateSharedData(){let t=this.sharedVersion||0;this.sharedVersion=t+1;let e=this.structures.slice(0);let r=new Fr(e,this.sharedValues,this.sharedVersion);let n=this.saveShared(r,e=>(e&&e.version||0)==t);if(n===false){r=this.getShared()||{};this.structures=r.structures||[];this.sharedValues=r.packedValues;this.sharedVersion=r.version;this.structures.nextId=this.structures.length}else{e.forEach((e,t)=>this.structures[t]=e)}return n}}function xr(e,t){if(e<24)O[S++]=t|e;else if(e<256){O[S++]=t|24;O[S++]=e}else if(e<65536){O[S++]=t|25;O[S++]=e>>8;O[S++]=e&255}else{O[S++]=t|26;mr.setUint32(S,e);S+=4}}class Fr{constructor(e,t,r){this.structures=e;this.packedValues=t;this.version=r}}function kr(e){if(e<24)O[S++]=128|e;else if(e<256){O[S++]=152;O[S++]=e}else if(e<65536){O[S++]=153;O[S++]=e>>8;O[S++]=e&255}else{O[S++]=154;mr.setUint32(S,e);S+=4}}const Cr=typeof Blob==="undefined"?function(){}:Blob;function Or(e){if(e instanceof Cr)return true;let t=e[Symbol.toStringTag];return t==="Blob"||t==="File"}function Sr(r,n){switch(typeof r){case"string":if(r.length>3){if(n.objectMap[r]>-1||n.values.length>=n.maxValues)return;let e=n.get(r);if(e){if(++e.count==2){n.values.push(r)}}else{n.set(r,{count:1});if(n.samplingPackedValues){let e=n.samplingPackedValues.get(r);if(e)e.count++;else n.samplingPackedValues.set(r,{count:1})}}}break;case"object":if(r){if(r instanceof Array){for(let e=0,t=r.length;e=0&&r<4294967296){O[S++]=26;mr.setUint32(S,r);S+=4}else{O[S++]=251;mr.setFloat64(S,r);S+=8}}},{tag:258,encode(e,t){let r=Array.from(e);t(r)}},{tag:27,encode(e,t){t([e.name,e.message])}},{tag:27,encode(e,t){t(["RegExp",e.source,e.flags])}},{getTag(e){return e.tag},encode(e,t){t(e.value)}},{encode(e,t,r){Ir(e,r)}},{getTag(e){if(e.constructor===Uint8Array){if(this.tagUint8Array||hr&&this.tagUint8Array!==false)return 64}},encode(e,t,r){Ir(e,r)}},jr(68,1),jr(69,2),jr(70,4),jr(71,8),jr(72,1),jr(77,2),jr(78,4),jr(79,8),jr(85,4),jr(86,8),{encode(t,n){let e=t.packedValues||[];let r=t.structures||[];if(e.values.length>0){O[S++]=216;O[S++]=51;kr(4);let r=e.values;n(r);kr(0);kr(0);packedObjectMap=Object.create(sharedPackedObjectMap||null);for(let e=0,t=r.length;e1)e-=4;return{tag:e,encode:function e(t,r){let n=t.byteLength;let i=t.byteOffset||0;let u=t.buffer||t;r(hr?lr.from(u,i,n):new Uint8Array(u,i,n))}}}function Ir(e,t){let r=e.byteLength;if(r<24){O[S++]=64+r}else if(r<256){O[S++]=88;O[S++]=r}else if(r<65536){O[S++]=89;O[S++]=r>>8;O[S++]=r&255}else{O[S++]=90;mr.setUint32(S,r);S+=4}if(S+r>=O.length){t(S+r)}O.set(e.buffer?e:new Uint8Array(e),S);S+=r}function Pr(n,e){let r;let i=e.length*2;let u=n.length-i;e.sort((e,t)=>e.offset>t.offset?1:-1);for(let r=0;r>8;n[e]=r&255}}while(r=e.pop()){let e=r.offset;n.copyWithin(e+i,e,u);i-=2;let t=e+i;n[t++]=216;n[t++]=28;u=e}return n}function Nr(e,t){mr.setUint32(br.position+e,S-br.position-e+1);let r=br;br=null;t(r[0]);t(r[1])}function Rr(e){if(e.Class){if(!e.encode)throw new Error("Extension has no encode function");fr.unshift(e.Class);cr.unshift(e)}ur(e)}let Tr=new Ar({useRecords:false});Tr.encode;Tr.encodeAsIterable;Tr.encodeAsAsyncIterable;const Lr=512;const Ur=1024;const Mr=2048;var qr={}; /**@license * * No Dependency fast and small LZJB Compression for Browser and Node @@ -48,7 +48,7 @@ * Released under BSD-3-Clause License * * build: Wed, 27 Oct 2021 10:43:10 GMT - */Object.defineProperty(fr,"__esModule",{value:true});const lr=8,hr=6,pr=3,_r=(1<r-_r){t[i++]=e[n++];continue}l=(e[n]+13^e[n+1]-13^e[n+2])&vr-1;s=n-h[l]&dr;h[l]=n;u=n-s;if(u>=0&&u!=n&&e[n]==e[u]&&e[n+1]==e[u+1]&&e[n+2]==e[u+2]){t[f]|=a;for(o=pr;o<_r;o++)if(e[n+o]!=e[u+o])break;t[i++]=o-pr<>lr;t[i++]=s;n+=o}else{t[i++]=e[n++]}}console.assert(e.length>=n);return i}function yr(e,t,r){t=t|0;var n=0,i=0,u=0,a=0,o=1<<(lr-1|0),s=0,c=0;while(n>(lr-hr|0))+pr|0;c=(e[n]<4){r[i]=r[u];i=i+1|0;u=u+1|0;r[i]=r[u];i=i+1|0;u=u+1|0;r[i]=r[u];i=i+1|0;u=u+1|0;r[i]=r[u];i=i+1|0;u=u+1|0;s=s-4|0}while(s>0){r[i]=r[u];i=i+1|0;u=u+1|0;s=s-1|0}}}else{r[i]=e[n];i=i+1|0;n=n+1|0}}return i}function gr(){const e=new TextEncoder("utf-8");return e.encode(br)}const br="@lzjb";const wr=gr();function Dr(...e){if(e.length>1){const r=e.reduce((e,t)=>e+t.length,0);const n=new Uint8Array(r);let t=0;e.forEach(e=>{n.set(e,t);t+=e.length});return n}else if(e.length){return e[0]}}function Er(t){const e=Math.ceil(Math.log2(t)/8);const r=new Uint8Array(e);for(let e=0;e=0;e--){r=r*256+t[e]}return r}function Fr(e,{magic:t=true}={}){const r=new Uint8Array(Math.max(e.length*1.5|0,16*1024));const n=mr(e,r);const i=Er(e.length);const u=[Uint8Array.of(i.length),i,r.slice(0,n)];if(t){u.unshift(wr)}return Dr(...u)}function xr(t,{magic:e=true}={}){if(e){const e=new TextDecoder("utf-8");const s=e.decode(t.slice(0,wr.length));if(s!==br){throw new Error("Invalid magic value")}}const r=e?wr.length:0;const n=t[r];const i=r+1;const u=r+n+1;const a=Ar(t.slice(i,u));t=t.slice(u);const o=new Uint8Array(a);yr(t,t.length,o);return o}var Cr=fr.pack=Fr;var kr=fr.unpack=xr;function Or(s,c){return c=c||{},new Promise(function(e,t){var r=new XMLHttpRequest,n=[],i=[],u={},a=function(){return{ok:2==(r.status/100|0),statusText:r.statusText,status:r.status,url:r.responseURL,text:function(){return Promise.resolve(r.responseText)},json:function(){return Promise.resolve(r.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([r.response]))},clone:a,headers:{keys:function(){return n},entries:function(){return i},get:function(e){return u[e.toLowerCase()]},has:function(e){return e.toLowerCase()in u}}}};for(var o in r.open(c.method||"get",s,!0),r.onload=function(){r.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(e,t,r){n.push(t=t.toLowerCase()),i.push([t,r]),u[t]=u[t]?u[t]+","+r:r}),e(a())},r.onerror=t,r.withCredentials="include"==c.credentials,c.headers)r.setRequestHeader(o,c.headers[o]);r.send(c.body||null)})} + */Object.defineProperty(qr,"__esModule",{value:true});const Yr=8,Vr=6,zr=3,$r=(1<r-$r){t[i++]=e[n++];continue}l=(e[n]+13^e[n+1]-13^e[n+2])&Kr-1;s=n-h[l]&Jr;h[l]=n;u=n-s;if(u>=0&&u!=n&&e[n]==e[u]&&e[n+1]==e[u+1]&&e[n+2]==e[u+2]){t[f]|=a;for(o=zr;o<$r;o++)if(e[n+o]!=e[u+o])break;t[i++]=o-zr<>Yr;t[i++]=s;n+=o}else{t[i++]=e[n++]}}console.assert(e.length>=n);return i}function Hr(e,t,r){t=t|0;var n=0,i=0,u=0,a=0,o=1<<(Yr-1|0),s=0,c=0;while(n>(Yr-Vr|0))+zr|0;c=(e[n]<4){r[i]=r[u];i=i+1|0;u=u+1|0;r[i]=r[u];i=i+1|0;u=u+1|0;r[i]=r[u];i=i+1|0;u=u+1|0;r[i]=r[u];i=i+1|0;u=u+1|0;s=s-4|0}while(s>0){r[i]=r[u];i=i+1|0;u=u+1|0;s=s-1|0}}}else{r[i]=e[n];i=i+1|0;n=n+1|0}}return i}function Wr(){const e=new TextEncoder("utf-8");return e.encode(Qr)}const Qr="@lzjb";const Zr=Wr();function Xr(...e){if(e.length>1){const r=e.reduce((e,t)=>e+t.length,0);const n=new Uint8Array(r);let t=0;e.forEach(e=>{n.set(e,t);t+=e.length});return n}else if(e.length){return e[0]}}function en(t){const e=Math.ceil(Math.log2(t)/8);const r=new Uint8Array(e);for(let e=0;e=0;e--){r=r*256+t[e]}return r}function rn(e,{magic:t=true}={}){const r=new Uint8Array(Math.max(e.length*1.5|0,16*1024));const n=Gr(e,r);const i=en(e.length);const u=[Uint8Array.of(i.length),i,r.slice(0,n)];if(t){u.unshift(Zr)}return Xr(...u)}function nn(t,{magic:e=true}={}){if(e){const e=new TextDecoder("utf-8");const s=e.decode(t.slice(0,Zr.length));if(s!==Qr){throw new Error("Invalid magic value")}}const r=e?Zr.length:0;const n=t[r];const i=r+1;const u=r+n+1;const a=tn(t.slice(i,u));t=t.slice(u);const o=new Uint8Array(a);Hr(t,t.length,o);return o}var un=qr.pack=rn;var an=qr.unpack=nn;function on(s,c){return c=c||{},new Promise(function(e,t){var r=new XMLHttpRequest,n=[],i=[],u={},a=function(){return{ok:2==(r.status/100|0),statusText:r.statusText,status:r.status,url:r.responseURL,text:function(){return Promise.resolve(r.responseText)},json:function(){return Promise.resolve(r.responseText).then(JSON.parse)},blob:function(){return Promise.resolve(new Blob([r.response]))},clone:a,headers:{keys:function(){return n},entries:function(){return i},get:function(e){return u[e.toLowerCase()]},has:function(e){return e.toLowerCase()in u}}}};for(var o in r.open(c.method||"get",s,!0),r.onload=function(){r.getAllResponseHeaders().replace(/^(.*?):[^\S\n]*([\s\S]*?)$/gm,function(e,t,r){n.push(t=t.toLowerCase()),i.push([t,r]),u[t]=u[t]?u[t]+","+r:r}),e(a())},r.onerror=t,r.withCredentials="include"==c.credentials,c.headers)r.setRequestHeader(o,c.headers[o]);r.send(c.body||null)})} /**@license * __ __ __ * / / \ \ _ _ ___ ___ \ \ @@ -83,5 +83,5 @@ * The rationalize algorithm is by Per M.A. Bothner, Alan Bawden and Marc Feeley. * source: Kawa, C-Gambit * - * Build time: Wed, 06 Sep 2023 20:32:14 +0000 - */var Sr=["token"],Br=["stderr","stdin","stdout","command_line"];function jr(i){var u=Ir();return function e(){var t=f(i),r;if(u){var n=f(this).constructor;r=Reflect.construct(t,arguments,n)}else{r=t.apply(this,arguments)}return a(this,r)}}function Ir(){if(typeof Reflect==="undefined"||!Reflect.construct)return false;if(Reflect.construct.sham)return false;if(typeof Proxy==="function")return true;try{Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}));return true}catch(e){return false}}function Pr(t,e){var r=typeof Symbol!=="undefined"&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=Nr(t))||e&&t&&typeof t.length==="number"){if(r)t=r;var n=0;var i=function e(){};return{s:i,n:function e(){if(n>=t.length)return{done:true};return{done:false,value:t[n++]}},e:function e(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var u=true,a=false,o;return{s:function e(){r=r.call(t)},n:function e(){var t=r.next();u=t.done;return t},e:function e(t){a=true;o=t},f:function e(){try{if(!u&&r["return"]!=null)r["return"]()}finally{if(a)throw o}}}}function Nr(e,t){if(!e)return;if(typeof e==="string")return Rr(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor)r=e.constructor.name;if(r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Rr(e,t)}function Rr(e,t){if(t==null||t>e.length)t=e.length;for(var r=0,n=new Array(t);r1&&arguments[1]!==undefined?arguments[1]:null;var n=arguments[1]===true;function t(e){if(!Qr()){return}var t=co.get("repr")(e);if(r===null||r instanceof RegExp&&r.test(t)){console.log(co.get("type")(e)+": "+t)}if(n){console.log(e)}}if(Fu(e)){e.then(t)}else{t(e)}return e}function Qr(){return fo&&fo.get("DEBUG",{throwError:false})}function Zr(e){return e?"(?:#".concat(e,"(?:#[ie])?|#[ie]#").concat(e,")"):"(?:#[ie])?"}function Kr(e,t){return"".concat(Zr(e),"[+-]?").concat(t,"+/").concat(t,"+")}function Xr(e,t){return"".concat(Zr(e),"(?:[+-]?(?:").concat(t,"+/").concat(t,"+|nan.0|inf.0|").concat(t,"+))?(?:[+-]i|[+-]?(?:").concat(t,"+/").concat(t,"+|").concat(t,"+|nan.0|inf.0)i)(?=[()[\\]\\s]|$)")}function en(e,t){return"".concat(Zr(e),"[+-]?").concat(t,"+")}var tn=/^#\/((?:\\\/|[^/]|\[[^\]]*\/[^\]]*\])+)\/([gimyus]*)$/;var rn="(?:[-+]?(?:[0-9]+(?:[eE][-+]?[0-9]+)|(?:\\.[0-9]+|[0-9]+\\.[0-9]+)(?:[eE][-+]?[0-9]+)?)|[0-9]+\\.)";var nn="(?:#[ie])?(?:[+-]?(?:[0-9]+/[0-9]+|nan.0|inf.0|".concat(rn,"|[+-]?[0-9]+))?(?:").concat(rn,"|[+-](?:[0-9]+/[0-9]+|[0-9]+|nan.0|inf.0))i");var un=new RegExp("^(#[ie])?".concat(rn,"$"),"i");function an(e,t){var r=e==="x"?"(?!\\+|".concat(t,")"):"(?!\\.|".concat(t,")");var n="";if(e===""){n="(?:[-+]?(?:[0-9]+(?:[eE][-+]?[0-9]+)|(?:\\.[0-9]+|[0-9]+\\.[0-9]+(?![0-9]))(?:[eE][-+]?[0-9]+)?))"}return new RegExp("^((?:(?:".concat(n,"|[-+]?inf.0|[-+]?nan.0|[+-]?").concat(t,"+/").concat(t,"+(?!").concat(t,")|[+-]?").concat(t,"+)").concat(r,")?)(").concat(n,"|[-+]?inf.0|[-+]?nan.0|[+-]?").concat(t,"+/").concat(t,"+|[+-]?").concat(t,"+|[+-])i$"),"i")}var on=function(){var u={};[[10,"","[0-9]"],[16,"x","[0-9a-fA-F]"],[8,"o","[0-7]"],[2,"b","[01]"]].forEach(function(e){var t=j(e,3),r=t[0],n=t[1],i=t[2];u[r]=an(n,i)});return u}();var sn={alarm:"",backspace:"\b",delete:"",escape:"",newline:"\n",null:"\0",return:"\r",space:" ",tab:"\t",dle:"",soh:"",dc1:"",stx:"",dc2:"",etx:"",dc3:"",eot:"",dc4:"",enq:"",nak:"",ack:"",syn:"",bel:"",etb:"",bs:"\b",can:"",ht:"\t",em:"",lf:"\n",sub:"",vt:"\v",esc:"",ff:"\f",fs:"",cr:"\r",gs:"",so:"",rs:"",si:"",us:"",del:""};function cn(e){var t=[];var r=0;var n=e.length;while(r=55296&&i<=56319&&r1&&arguments[1]!==undefined?arguments[1]:10;var r=En(e);var n=r.number.split("/");var i=Ia({num:k([n[0],r.radix||t]),denom:k([n[1],r.radix||t])});if(r.inexact){return i.valueOf()}else{return i}}function Fn(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;var r=En(e);if(r.inexact){return ka(parseInt(r.number,r.radix||t))}return k([r.number,r.radix||t])}function xn(e){var t=e.match(/#\\x([0-9a-f]+)$/i);var r;if(t){var n=parseInt(t[1],16);r=String.fromCodePoint(n)}else{t=e.match(/#\\(.+)$/);if(t){r=t[1]}}if(r){return pa(r)}throw new Error("Parse: invalid character")}function Cn(e){var i=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;function t(e){var t;if(e==="+"){t=k(1)}else if(e==="-"){t=k(-1)}else if(e.match(yn)){t=k([e,i])}else if(e.match(gn)){var r=e.split("/");t=Ia({num:k([r[0],i]),denom:k([r[1],i])})}else if(e.match(un)){var n=Sn(e);if(u.exact){return n.toRational()}return n}else if(e.match(/nan.0$/)){return k(NaN)}else if(e.match(/inf.0$/)){if(e[0]==="-"){return k(Number.NEGATIVE_INFINITY)}return k(Number.POSITIVE_INFINITY)}else{throw new Error("Internal Parser Error")}if(u.inexact){return ka(t.valueOf())}return t}var u=En(e);i=u.radix||i;var r;var n=u.number.match(wn);if(i!==10&&n){r=n}else{r=u.number.match(on[i])}var a,o;o=t(r[2]);if(r[1]){a=t(r[1])}else{a=k(0)}if(o.cmp(0)===0&&o.__type__==="bigint"){return a}return Ca({im:o,re:a})}function kn(e){return parseInt(e.toString(),10)===e}function On(e){var t=e.match(/^(([-+]?[0-9]*)(?:\.([0-9]+))?)e([-+]?[0-9]+)/i);if(t){var r=parseInt(t[4],10);var n;var i=t[1].replace(/[-+]?([0-9]*)\..+$/,"$1").length;var u=t[3]&&t[3].length;if(i0){return k(u).mul(o)}}}r=ka(r);if(t.exact){return r.toRational()}return r}function Bn(e){e=e.replace(/\\x([0-9a-f]+);/gi,function(e,t){return"\\u"+t.padStart(4,"0")}).replace(/\n/g,"\\n");var t=e.match(/(\\*)(\\x[0-9A-F])/i);if(t&&t[1].length%2===0){throw new Error("Invalid string literal, unclosed ".concat(t[2]))}try{return _a(JSON.parse(e))}catch(e){var r=e.message.replace(/in JSON /,"").replace(/.*Error: /,"");throw new Error("Invalid string literal: ".concat(r))}}function jn(e){if(e.match(/^\|.*\|$/)){e=e.replace(/(^\|)|(\|$)/g,"");var r={t:"\t",r:"\r",n:"\n"};e=e.replace(/\\(x[^;]+);/g,function(e,t){return String.fromCharCode(parseInt("0"+t,16))}).replace(/\\(.)/g,function(e,t){return r[t]||t})}return new L(e)}function In(e){if(so.hasOwnProperty(e)){return so[e]}if(e.match(/^"[\s\S]*"$/)){return Bn(e)}else if(e[0]==="#"){var t=e.match(tn);if(t){return new RegExp(t[1],t[2])}else if(e.match(hn)){return xn(e)}var r=e.match(/#\\(.+)/);if(r&&cn(r[1]).length===1){return xn(e)}}if(e.match(/[0-9a-f]|[+-]i/i)){if(e.match(mn)){return Fn(e)}else if(e.match(un)){return Sn(e)}else if(e.match(vn)){return An(e)}else if(e.match(dn)){return Cn(e)}}if(e.match(/^#[iexobd]/)){throw new Error("Invalid numeric constant: "+e)}return jn(e)}function Pn(e){return!(["(",")","[","]"].includes(e)||ei.names().includes(e))}function Nn(e){return Pn(e)&&!(e.match(tn)||e.match(/^"[\s\S]*"$/)||e.match(mn)||e.match(un)||e.match(dn)||e.match(vn)||e.match(hn)||["#t","#f","nil","true","false"].includes(e))}var Rn=/"(?:\\[\S\s]|[^"])*"?/g;function Tn(e){if(typeof e==="string"){var t=/([-\\^$[\]()+{}?*.|])/g;return e.replace(t,"\\$1")}return e}function Ln(){this.data=[]}Ln.prototype.push=function(e){this.data.push(e)};Ln.prototype.top=function(){return this.data[this.data.length-1]};Ln.prototype.pop=function(){return this.data.pop()};Ln.prototype.is_empty=function(){return!this.data.length};function Un(e){if(e instanceof _a){e=e.valueOf()}var t=new s(e,{whitespace:true});var r=[];while(true){var n=t.peek(true);if(n===Wa){break}r.push(n);t.skip()}return r}function qn(e){var t=e.token,r=S(e,Sr);if(t.match(/^"[\s\S]*"$/)&&t.match(/\n/)){var n=new RegExp("^ {1,"+(e.col+1)+"}","mg");t=t.replace(n,"")}return Lr({token:t},r)}function Mn(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(){};this.fn=e;this.cont=t}Mn.prototype.toString=function(){return"#"};function Yn(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r1&&arguments[1]!==undefined?arguments[1]:false;if(e instanceof _a){e=e.toString()}if(t){return Un(e)}else{var r=Un(e).map(function(e){if(e.token==="#\\ "){return e.token}return e.token.trim()}).filter(function(e){return e&&!e.match(/^;/)&&!e.match(/^#\|[\s\S]*\|#$/)});return Vn(r)}}function Vn(e){var t=0;var r=null;var n=[];for(var i=0;i0&&arguments[0]!==undefined?arguments[0]:null;if(e instanceof L){if(e.is_gensym()){return e}e=e.valueOf()}if(Wn(e)){return L(e)}if(e!==null){return r(e,Symbol("#:".concat(e)))}t++;return r(t,Symbol("#:g".concat(t)))}}();function Qn(e){var r=this;var n={pending:true,rejected:false,fulfilled:false,reason:undefined,type:undefined};e=e.then(function(e){n.type=Oo(e);n.fulfilled=true;n.pending=false;return e});_i(this,"_promise",e,{hidden:true});if(Du(e["catch"])){e=e["catch"](function(e){n.rejected=true;n.pending=false;n.reason=e})}Object.keys(n).forEach(function(t){Object.defineProperty(r,"__".concat(t,"__"),{enumerable:true,get:function e(){return n[t]}})});_i(this,"__promise__",e);this.then=false}Qn.prototype.then=function(e){return new Qn(this.valueOf().then(e))};Qn.prototype["catch"]=function(e){return new Qn(this.valueOf()["catch"](e))};Qn.prototype.valueOf=function(){if(!this._promise){throw new Error("QuotedPromise: invalid promise created")}return this._promise};Qn.prototype.toString=function(){if(this.__pending__){return Qn.pending_str}if(this.__rejected__){return Qn.rejected_str}return"#")};Qn.pending_str="#";Qn.rejected_str="#";function Zn(e){if(Array.isArray(e)){return Promise.all(Kn(e)).then(Xn)}return e}function Kn(e){var t=new Array(e.length),r=e.length;while(r--){var n=e[r];if(n instanceof Qn){t[r]=new Xa(n)}else{t[r]=n}}return t}function Xn(e){var t=new Array(e.length),r=e.length;while(r--){var n=e[r];if(n instanceof Xa){t[r]=n.valueOf()}else{t[r]=n}}return t}var ei={LITERAL:Symbol["for"]("literal"),SPLICE:Symbol["for"]("splice"),SYMBOL:Symbol["for"]("symbol"),names:function e(){return Object.keys(this.__list__)},type:function e(t){return this.get(t).type},get:function e(t){return this.__list__[t]},off:function e(t){var r=this;var n=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(Array.isArray(t)){t.forEach(function(e){return r.off(e,n)})}else if(n===null){delete this.__events__[t]}else{this.__events__=this.__events__.filter(function(e){return e!==n})}},on:function e(t,r){var n=this;if(Array.isArray(t)){t.forEach(function(e){return n.on(e,r)})}else if(!this.__events__[t]){this.__events__[t]=[r]}else{this.__events__[t].push(r)}},trigger:function e(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i",new L("quote-promise"),ei.LITERAL]];var ui=ii.map(function(e){return e[0]});Object.freeze(ui);Object.defineProperty(ei,"__builtins__",{writable:false,value:ui});ii.forEach(function(e){var t=j(e,3),r=t[0],n=t[1],i=t[2];ei.append(r,n,i)});var s=function(){function p(e){var t=this;var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},n=r.whitespace,i=n===void 0?false:n;A(this,p);_i(this,"__input__",e.replace(/\r/g,""));var u={};["_i","_whitespace","_col","_newline","_line","_state","_next","_token","_prev_char"].forEach(function(r){Object.defineProperty(t,r,{configurable:false,enumerable:false,get:function e(){return u[r]},set:function e(t){u[r]=t}})});this._whitespace=i;this._i=this._line=this._col=this._newline=0;this._state=this._next=this._token=null;this._prev_char=""}x(p,[{key:"get",value:function e(t){return this.__internal[t]}},{key:"set",value:function e(t,r){this.__internal[t]=r}},{key:"token",value:function e(){var t=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(t){var r=this._line;if(this._whitespace&&this._token==="\n"){--r}return{token:this._token,col:this._col,offset:this._i,line:r}}return this._token}},{key:"peek",value:function e(){var t=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(this._i>=this.__input__.length){return Wa}if(this._token){return this.token(t)}var r=this.next_token();if(r){this._token=this.__input__.substring(this._i,this._next);return this.token(t)}return Wa}},{key:"skip",value:function e(){if(this._next!==null){this._token=null;this._i=this._next}}},{key:"read_line",value:function e(){var t=this.__input__.length;if(this._i>=t){return Wa}for(var r=this._i;r=r){return Wa}if(t+this._i>=r){return this.read_rest()}var n=this._i+t;var i=this.__input__.substring(this._i,n);var u=i.match(/\n/g);if(u){this._line+=u.length}this._i=n;return i}},{key:"peek_char",value:function e(){if(this._i>=this.__input__.length){return Wa}return pa(this.__input__[this._i])}},{key:"read_char",value:function e(){var t=this.peek_char();this.skip_char();return t}},{key:"skip_char",value:function e(){if(this._i1&&arguments[1]!==undefined?arguments[1]:{},r=t.prev_char,n=t["char"],i=t.next_char;var u=j(e,4),a=u[0],o=u[1],s=u[2],f=u[3];if(e.length!==5){throw new Error("Lexer: Invald rule of length ".concat(e.length))}if(!n.match(a)){return false}if(!ai(o,r)){return false}if(!ai(s,i)){return false}if(f!==this._state){return false}return true}},{key:"next_token",value:function f(){if(this._i>=this.__input__.length){return false}var e=true;e:for(var t=this._i,r=this.__input__.length;t2&&arguments[2]!==undefined?arguments[2]:null;var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;if(t.length===0){throw new Error("Lexer: invalid literal rule")}if(t.length===1){return[[t,n,i,null,null]]}var u=[];for(var a=0,o=t.length;a1&&arguments[1]!==undefined?arguments[1]:{},r=t.env,n=t.meta,i=n===void 0?false:n,u=t.formatter,a=u===void 0?qn:u;A(this,o);if(e instanceof _a){e=e.toString()}_i(this,"_formatter",a,{hidden:true});_i(this,"__lexer__",new s(e));_i(this,"__env__",r);_i(this,"_meta",i,{hidden:true});_i(this,"_refs",[],{hidden:true});_i(this,"_state",{parentheses:0},{hidden:true})}x(o,[{key:"resolve",value:function e(t){return this.__env__&&this.__env__.get(t,{throwError:false})}},{key:"peek",value:function(){var e=O(z.mark(function e(){var r;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:r=this.__lexer__.peek(true);if(!(r===Wa)){t.next=4;break}return t.abrupt("return",Wa);case 4:if(!this.is_comment(r.token)){t.next=7;break}this.skip();return t.abrupt("continue",0);case 7:if(!(r.token==="#;")){t.next=14;break}this.skip();if(!(this.__lexer__.peek()===Wa)){t.next=11;break}throw new Error("Lexer: syntax error eof found after comment");case 11:t.next=13;return this._read_object();case 13:return t.abrupt("continue",0);case 14:return t.abrupt("break",17);case 17:r=this._formatter(r);if(!this._meta){t.next=20;break}return t.abrupt("return",r);case 20:return t.abrupt("return",r.token);case 21:case"end":return t.stop()}}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"reset",value:function e(){this._refs.length=0}},{key:"skip",value:function e(){this.__lexer__.skip()}},{key:"read",value:function(){var e=O(z.mark(function e(){var r;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:t.next=2;return this.peek();case 2:r=t.sent;this.skip();return t.abrupt("return",r);case 5:case"end":return t.stop()}}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"match_datum_label",value:function e(t){var r=t.match(/^#([0-9]+)=$/);return r&&r[1]}},{key:"match_datum_ref",value:function e(t){var r=t.match(/^#([0-9]+)#$/);return r&&r[1]}},{key:"is_open",value:function e(t){var r=["(","["].includes(t);if(r){this._state.parentheses++}return r}},{key:"is_close",value:function e(t){var r=[")","]"].includes(t);if(r){this._state.parentheses--}return r}},{key:"read_list",value:function(){var e=O(z.mark(function e(){var r,n,i,u;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:r=U,n=r;case 1:t.next=4;return this.peek();case 4:i=t.sent;if(!(i===Wa)){t.next=7;break}return t.abrupt("break",27);case 7:if(!this.is_close(i)){t.next=10;break}this.skip();return t.abrupt("break",27);case 10:if(!(i==="."&&r!==U)){t.next=17;break}this.skip();t.next=14;return this._read_object();case 14:n.cdr=t.sent;t.next=25;break;case 17:t.t0=q;t.next=20;return this._read_object();case 20:t.t1=t.sent;t.t2=U;u=new t.t0(t.t1,t.t2);if(r===U){r=u}else{n.cdr=u}n=u;case 25:t.next=1;break;case 27:return t.abrupt("return",r);case 28:case"end":return t.stop()}}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"read_value",value:function(){var e=O(z.mark(function e(){var r;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:t.next=2;return this.read();case 2:r=t.sent;if(!(r===Wa)){t.next=5;break}throw new Error("Parser: Expected token eof found");case 5:return t.abrupt("return",In(r));case 6:case"end":return t.stop()}}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"is_comment",value:function e(t){return t.match(/^;/)||t.match(/^#\|/)&&t.match(/\|#$/)}},{key:"evaluate",value:function e(t){return Lo(t,{env:this.__env__,error:function e(t){throw t}})}},{key:"read_object",value:function(){var e=O(z.mark(function e(){var r;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:this.reset();t.next=3;return this._read_object();case 3:r=t.sent;if(r instanceof si){r=r.valueOf()}if(!this._refs.length){t.next=7;break}return t.abrupt("return",this._resolve_object(r));case 7:return t.abrupt("return",r);case 8:case"end":return t.stop()}}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"ballanced",value:function e(){return this._state.parentheses===0}},{key:"ballancing_error",value:function e(t){var r=this._state.parentheses;var n=new Error("Parser: expected parenthesis but eof found");var i=new RegExp("\\){".concat(r,"}$"));n.__code__=[t.toString().replace(i,"")];throw n}},{key:"_resolve_object",value:function(){var t=O(z.mark(function e(r){var n=this;var i;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:if(!Array.isArray(r)){t.next=2;break}return t.abrupt("return",r.map(function(e){return n._resolve_object(e)}));case 2:if(!zi(r)){t.next=6;break}i={};Object.keys(r).forEach(function(e){i[e]=n._resolve_object(r[e])});return t.abrupt("return",i);case 6:if(!(r instanceof q)){t.next=8;break}return t.abrupt("return",this._resolve_pair(r));case 8:return t.abrupt("return",r);case 9:case"end":return t.stop()}}},e,this)}));function e(e){return t.apply(this,arguments)}return e}()},{key:"_resolve_pair",value:function(){var t=O(z.mark(function e(r){return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:if(!(r instanceof q)){t.next=15;break}if(!(r.car instanceof si)){t.next=7;break}t.next=4;return r.car.valueOf();case 4:r.car=t.sent;t.next=8;break;case 7:this._resolve_pair(r.car);case 8:if(!(r.cdr instanceof si)){t.next=14;break}t.next=11;return r.cdr.valueOf();case 11:r.cdr=t.sent;t.next=15;break;case 14:this._resolve_pair(r.cdr);case 15:return t.abrupt("return",r);case 16:case"end":return t.stop()}}},e,this)}));function e(e){return t.apply(this,arguments)}return e}()},{key:"_read_object",value:function(){var e=O(z.mark(function e(){var r,n,i,u,a,o,s,c,f;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:t.next=2;return this.peek();case 2:r=t.sent;if(!(r===Wa)){t.next=5;break}return t.abrupt("return",r);case 5:if(!ti(r)){t.next=39;break}n=ei.get(r);i=ri(r);this.skip();t.next=11;return this._read_object();case 11:a=t.sent;if(i){t.next=26;break}o=this.__env__.get(n.symbol);if(!(typeof o==="function")){t.next=26;break}if(!ni(r)){t.next=19;break}return t.abrupt("return",o.call(this.__env__,a));case 19:if(!(a===U)){t.next=23;break}return t.abrupt("return",o.apply(this.__env__));case 23:if(!(a instanceof q)){t.next=25;break}return t.abrupt("return",o.apply(this.__env__,a.to_array(false)));case 25:throw new Error("Parse Error: Invalid parser extension "+"invocation ".concat(n.symbol));case 26:if(ni(r)){u=new q(n.symbol,new q(a,U))}else{u=new q(n.symbol,a)}if(!i){t.next=29;break}return t.abrupt("return",u);case 29:if(!(o instanceof hu)){t.next=38;break}t.next=32;return this.evaluate(u);case 32:s=t.sent;if(!(s instanceof q||s instanceof L)){t.next=35;break}return t.abrupt("return",q.fromArray([L("quote"),s]));case 35:return t.abrupt("return",s);case 38:throw new Error("Parse Error: invlid parser extension: "+n.symbol);case 39:c=this.match_datum_ref(r);if(!(c!==null)){t.next=45;break}this.skip();if(!this._refs[c]){t.next=44;break}return t.abrupt("return",new si(c,this._refs[c]));case 44:throw new Error("Parse Error: invalid datum label #".concat(c,"#"));case 45:f=this.match_datum_label(r);if(!(f!==null)){t.next=52;break}this.skip();this._refs[f]=this._read_object();return t.abrupt("return",this._refs[f]);case 52:if(!this.is_open(r)){t.next=57;break}this.skip();return t.abrupt("return",this.read_list());case 57:return t.abrupt("return",this.read_value());case 58:case"end":return t.stop()}}},e,this)}));function t(){return e.apply(this,arguments)}return t}()}]);return o}();var si=function(){function r(e,t){A(this,r);this.name=e;this.data=t}x(r,[{key:"valueOf",value:function e(){return this.data}}]);return r}();function ci(e,t){return fi.apply(this,arguments)}function fi(){fi=e(z.mark(function e(r,n){var i,u;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:if(!n){if(co){n=co.get("**interaction-environment**",{throwError:false})}else{n=fo}}i=new oi(r,{env:n});case 2:t.next=5;return P(i.read_object());case 5:u=t.sent;if(!i.ballanced()){i.ballancing_error(u)}if(!(u===Wa)){t.next=9;break}return t.abrupt("break",13);case 9:t.next=11;return u;case 11:t.next=2;break;case 13:case"end":return t.stop()}}},e)}));return fi.apply(this,arguments)}function li(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(e){return e};var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;if(Fu(e)){var n=e.then(t);if(r===null){return n}else{return n["catch"](r)}}if(e instanceof Array){return hi(e,t,r)}if(zi(e)){return pi(e,t,r)}return t(e)}function hi(t,r,e){if(t.find(Fu)){return li(Zn(t),function(e){if(Object.isFrozen(t)){Object.freeze(e)}return r(e)},e)}return r(t)}function pi(t,e,r){var i=Object.keys(t);var n=[],u=[];var a=i.length;while(a--){var o=i[a];var s=t[o];n[a]=s;if(Fu(s)){u.push(s)}}if(u.length){return li(Zn(n),function(e){var n={};e.forEach(function(e,t){var r=i[t];n[r]=e});if(Object.isFrozen(t)){Object.freeze(n)}return n},r)}return e(t)}function _i(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{},i=n.hidden,u=i===void 0?false:i;Object.defineProperty(e,t,{value:r,configurable:true,enumerable:!u})}function di(e){return vi.apply(this,arguments)}function vi(){vi=O(z.mark(function e(r){var n,i,u,a,o,s,c;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:n=[];i=false;u=false;t.prev=3;o=Ur(r);case 5:t.next=7;return o.next();case 7:if(!(i=!(s=t.sent).done)){t.next=13;break}c=s.value;n.push(c);case 10:i=false;t.next=5;break;case 13:t.next=19;break;case 15:t.prev=15;t.t0=t["catch"](3);u=true;a=t.t0;case 19:t.prev=19;t.prev=20;if(!(i&&o["return"]!=null)){t.next=24;break}t.next=24;return o["return"]();case 24:t.prev=24;if(!u){t.next=27;break}throw a;case 27:return t.finish(24);case 28:return t.finish(19);case 29:return t.abrupt("return",n);case 30:case"end":return t.stop()}}},e,null,[[3,15,19,29],[20,,24,28]])}));return vi.apply(this,arguments)}function mi(e,t){if(t instanceof RegExp){return function(e){return String(e).match(t)}}else if(Du(t)){return t}throw new Error("Invalid matcher")}function g(e,t,r,n){if(typeof e!=="string"){t=arguments[0];r=arguments[1];n=arguments[2];e=null}if(r){if(n){t.__doc__=r}else{t.__doc__=yi(r)}}if(e){t.__name__=e}else if(t.name&&!Zu(t)){t.__name__=t.name}return t}function yi(e){return e.split("\n").map(function(e){return e.trim()}).join("\n")}function gi(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var r=e.length;if(t<=0){throw Error("previousSexp: Invalid argument sexp = ".concat(t))}e:while(t--&&r>=0){var n=1;while(n>0){var i=e[--r];if(!i){break e}if(i==="("||i.token==="("){n--}else if(i===")"||i.token===")"){n++}}r--}return e.slice(r+1)}function bi(e){if(!e||!e.length){return 0}var t=e.length;if(e[t-1].token==="\n"){return 0}while(--t){if(e[t].token==="\n"){var r=(e[t+1]||{}).token;if(r){return r.length}}}return 0}function wi(e,t){return f(e,t)===t.length;function f(r,n){function e(e,t){var r=Pr(e),n;try{for(r.s();!(n=r.n()).done;){var i=n.value;var u=f(i,t);if(u!==-1){return u}}}catch(e){r.e(e)}finally{r.f()}return-1}function t(){return r[u]===Symbol["for"]("symbol")&&!Nn(n[o])}function i(){var e=r[u+1];var t=n[o+1];if(e!==undefined&&t!==undefined){return f([e],[t])}}var u=0;var a={};for(var o=0;o0){continue}}else if(t()){return-1}}else if(r[u]instanceof Array){var c=f(r[u],n.slice(o));if(c===-1||c+o>n.length){return-1}o+=c-1;u++;continue}else{return-1}u++}if(r.length!==u){return-1}return n.length}}function Di(e){this.__code__=e.replace(/\r/g,"")}Di.defaults={offset:0,indent:2,exceptions:{specials:[/^(?:#:)?(?:define(?:-values|-syntax|-macro|-class|-record-type)?|(?:call-with-(?:input-file|output-file|port))|lambda|let-env|try|catch|when|unless|while|syntax-rules|(let|letrec)(-syntax|\*)?)$/],shift:{1:["&","#"]}}};Di.match=wi;Di.prototype._options=function e(t){var r=Di.defaults;if(typeof t==="undefined"){return Object.assign({},r)}var n=t&&t.exceptions||{};var i=n.specials||[];var u=n.shift||{1:[]};return Lr(Lr(Lr({},r),t),{},{exceptions:{specials:[].concat(M(r.exceptions.specials),M(i)),shift:Lr(Lr({},u),{},{1:[].concat(M(r.exceptions.shift[1]),M(u[1]))})}})};Di.prototype.indent=function e(t){var r=zn(this.__code__,true);return this._indent(r,t)};Di.exception_shift=function(u,e){function t(e){if(!e.length){return false}if(e.indexOf(u)!==-1){return true}else{var t=e.filter(function(e){return e instanceof RegExp});if(!t.length){return false}var r=Pr(t),n;try{for(r.s();!(n=r.n()).done;){var i=n.value;if(u.match(i)){return true}}}catch(e){r.e(e)}finally{r.f()}}return false}if(t(e.exceptions.specials)){return e.indent}var r=e.exceptions.shift;for(var n=0,i=Object.entries(r);n0){t.offset=0}if(n.toString()===e.toString()&&Yo(n)){return t.offset+n[0].col}else if(n.length===1){return t.offset+n[0].col+1}else{var u=-1;if(i){var a=Di.exception_shift(i.token,t);if(a!==-1){u=a}}if(u===-1){u=Di.exception_shift(n[1].token,t)}if(u!==-1){return t.offset+n[0].col+u}else if(n[0].line3&&n[1].line===n[3].line){if(n[1].token==="("||n[1].token==="["){return t.offset+n[1].col}return t.offset+n[3].col}else if(n[0].line===n[1].line){return t.offset+t.indent+n[0].col}else{var o=n.slice(2);for(var s=0;s")};Ei.prototype.match=function(e){return e.match(this.pattern)};function Ai(){for(var e=arguments.length,t=new Array(e),r=0;r")};Di.Pattern=Ai;Di.Ahead=Ei;var Fi=/^[[(]$/;var xi=/^[\])]$/;var Ci=/[^()[\]]/;var ki=new Ei(/[^)\]]/);var Oi=Symbol["for"]("*");var Si=new Ai([Fi,Oi,xi],[Ci],"+");var Bi=new Ai([Fi,Oi,xi],"+");var ji=new Ai([Symbol["for"]("symbol")],"?");var Ii=new Ai([Symbol["for"]("symbol")],"*");var Pi=[Fi,Ii,xi];var Ni=new Ai([Fi,Symbol["for"]("symbol"),Oi,xi],"+");var Ri=Ui("define","lambda","define-macro","syntax-rules");var Ti=/^(?!.*\b(?:[()[\]]|define(?:-macro)?|let(?:\*|rec|-env|-syntax|)?|lambda|syntax-rules)\b).*$/;var Li=/^(?:#:)?(let(?:\*|rec|-env|-syntax)?)$/;function Ui(){for(var e=arguments.length,t=new Array(e),r=0;r0&&!i[e]){i[e]=gi(n,e)}});var u=Pr(t),p;try{for(u.s();!(p=u.n()).done;){var a=j(p.value,3),_=a[0],o=a[1],s=a[2];o=o.valueOf();var d=o>0?i[o]:n;var v=d.filter(function(e){return e.trim()&&!ti(e)});var m=h(d);var y=wi(_,v);var g=e.slice(r).find(function(e){return e.trim()&&!ti(e)});if(y&&(s instanceof Ei&&s.match(g)||!s)){var c=r-m;if(e[c]!=="\n"){if(!e[c].trim()){e[c]="\n"}else{e.splice(c,0,"\n");r++}}r+=m;continue e}}}catch(e){u.e(e)}finally{u.f()}}this.__code__=e.join("");return this};Di.prototype._spaces=function(e){return new Array(e+1).join(" ")};Di.prototype.format=function c(e){var t=this.__code__.replace(/[ \t]*\n[ \t]*/g,"\n ");var r=zn(t,true);var n=this._options(e);var i=0;var u=0;for(var a=0;a0&&arguments[0]!==undefined?arguments[0]:true;var n=new Map;function i(e){if(e instanceof q){if(n.has(e)){return n.get(e)}var t=new q;n.set(e,t);if(r){t.car=i(e.car)}else{t.car=e.car}t.cdr=i(e.cdr);t[Yu]=e[Yu];return t}return e}return i(this)};q.prototype.last_pair=function(){var e=this;while(true){if(e.cdr===U){return e}e=e.cdr}};q.prototype.to_array=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var t=[];if(this.car instanceof q){if(e){t.push(this.car.to_array())}else{t.push(this.car)}}else{t.push(this.car.valueOf())}if(this.cdr instanceof q){t=t.concat(this.cdr.to_array())}return t};q.fromArray=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;if(e instanceof q||r&&e instanceof Array&&e[qu]){return e}if(t===false){var n=U;for(var i=e.length;i--;){n=new q(e[i],n)}return n}if(e.length&&!(e instanceof Array)){e=M(e)}var u=U;var a=e.length;while(a--){var o=e[a];if(o instanceof Array){o=q.fromArray(o,t,r)}else if(typeof o==="string"){o=_a(o)}else if(typeof o==="number"&&!Number.isNaN(o)){o=k(o)}u=new q(o,u)}return u};q.prototype.to_object=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var t=this;var r={};while(true){if(t instanceof q&&t.car instanceof q){var n=t.car;var i=n.car;if(i instanceof L){i=i.__name__}if(i instanceof _a){i=i.valueOf()}var u=n.cdr;if(u instanceof q){u=u.to_object(e)}if(Fo(u)){if(!e){u=u.valueOf()}}r[i]=u;t=t.cdr}else{break}}return r};q.fromPairs=function(e){return e.reduce(function(e,t){return new q(new q(new L(t[0]),t[1]),e)},U)};q.fromObject=function(t){var e=Object.keys(t).map(function(e){return[e,t[e]]});return q.fromPairs(e)};q.prototype.reduce=function(e){var t=this;var r=U;while(true){if(t!==U){r=e(r,t.car);t=t.cdr}else{break}}return r};q.prototype.reverse=function(){if(this.haveCycles()){throw new Error("You can't reverse list that have cycles")}var e=this;var t=U;while(e!==U){var r=e.cdr;e.cdr=t;t=e;e=r}return t};q.prototype.transform=function(n){function i(e){if(e instanceof q){if(e.replace){delete e.replace;return e}var t=n(e.car);if(t instanceof q){t=i(t)}var r=n(e.cdr);if(r instanceof q){r=i(r)}return new q(t,r)}return e}return i(this)};q.prototype.map=function(e){if(typeof this.car!=="undefined"){return new q(e(this.car),this.cdr===U?U:this.cdr.map(e))}else{return U}};var $i=new Map;function zi(e){return e&&_(e)==="object"&&e.constructor===Object}var Vi=Object.getOwnPropertyNames(Array.prototype);var Ji=[];Vi.forEach(function(e){Ji.push(Array[e],Array.prototype[e])});function Gi(e){e=Bu(e);return Ji.includes(e)}function Wi(e){return Du(e)&&(Zu(e)||e.__doc__)}function Hi(r){var e=r.constructor||Object;var n=zi(r);var i=Du(r[Symbol.asyncIterator])||Du(r[Symbol.iterator]);var u;if($i.has(e)){u=$i.get(e)}else{$i.forEach(function(e,t){t=Bu(t);if(r.constructor===t&&(t===Object&&n&&!i||t!==Object)){u=e}})}return u}var Qi=new Map;[[true,"#t"],[false,"#f"],[null,"null"],[undefined,"#"]].forEach(function(e){var t=j(e,2),r=t[0],n=t[1];Qi.set(r,n)});function Zi(r){if(r&&_(r)==="object"){var n={};var e=Object.getOwnPropertySymbols(r);e.forEach(function(e){var t=e.toString().replace(/Symbol\(([^)]+)\)/,"$1");n[t]=nu(r[e])});var t=Object.getOwnPropertyNames(r);t.forEach(function(e){var t=r[e];if(t&&_(t)==="object"&&t.constructor===Object){n[e]=Zi(t)}else{n[e]=nu(t)}});return n}return r}function Ki(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function Xi(e,t){return e.hasOwnProperty(t)&&Du(e.toString)}function eu(e){if(ea(e)){return"#"}var t=e.prototype&&e.prototype.constructor;if(Du(t)&&Zu(t)){if(e[$u]&&t.hasOwnProperty("__name__")){var r=t.__name__;if(_a.isString(r)){r=r.toString();return"#")}return"#"}}if(e.hasOwnProperty("__name__")){var n=e.__name__;if(_(n)==="symbol"){n=Gn(n)}if(typeof n==="string"){return"#")}}if(Xi(e,"toString")){return e.toString()}else if(e.name&&!Zu(e)){return"#")}else{return"#"}}var tu=new Map;[[Error,function(e){return e.message}],[q,function(e,t){var r=t.quote,n=t.skip_cycles,i=t.pair_args;if(!n){e.markCycles()}return e.toString.apply(e,[r].concat(M(i)))}],[pa,function(e,t){var r=t.quote;if(r){return e.toString()}return e.valueOf()}],[_a,function(e,t){var r=t.quote;e=e.toString();if(r){return JSON.stringify(e).replace(/\\n/g,"\n")}return e}],[RegExp,function(e){return"#"+e.toString()}]].forEach(function(e){var t=j(e,2),r=t[0],n=t[1];tu.set(r,n)});var ru=[L,k,hu,eo,Na,Ra,Ka,Qn];function nu(e,t,c){if(typeof jQuery!=="undefined"&&e instanceof jQuery.fn.init){return"#"}if(Qi.has(e)){return Qi.get(e)}if(iu(e)){return"#"}if(e){var r=e.constructor;if(tu.has(r)){for(var n=arguments.length,f=new Array(n>3?n-3:0),i=3;i"}if(e===null){return"null"}if(_(e)==="object"){var a=e.constructor;if(!a){a=Object}var o;if(typeof a.__class__==="string"){o=a.__class__}else{var s=Hi(e);if(s){if(Du(s)){return s(e,t)}else{throw new Error("toString: Invalid repr value")}}o=a.name}if(Du(e.toString)&&Zu(e.toString)){return e.toString().valueOf()}if(Oo(e)==="instance"){if(Zu(a)&&a.__name__){o=a.__name__.valueOf()}else if(!ea(a)){o="instance"}}if(Co(e,Symbol.iterator)){if(o){return"#")}return"#"}if(Co(e,Symbol.asyncIterator)){if(o){return"#")}return"#"}if(o!==""){return"#<"+o+">"}return"#"}if(typeof e!=="string"){return e.toString()}return e}function iu(e){return e&&_(e)==="object"&&e.hasOwnProperty&&e.hasOwnProperty("constructor")&&typeof e.constructor==="function"&&e.constructor.prototype===e}q.prototype.markCycles=function(){uu(this);return this};q.prototype.haveCycles=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(!e){return this.haveCycles("car")||this.haveCycles("cdr")}return!!(this[Yu]&&this[Yu][e])};function uu(e){var t=[];var i=[];var u=[];function a(e){if(!t.includes(e)){t.push(e)}}function o(e,t,r,n){if(r instanceof q){if(n.includes(r)){if(!u.includes(r)){u.push(r)}if(!e[Yu]){e[Yu]={}}e[Yu][t]=r;if(!i.includes(e)){i.push(e)}return true}}}var s=Yn(function e(t,r){if(t instanceof q){delete t.ref;delete t[Yu];a(t);r.push(t);var n=o(t,"car",t.car,r);var i=o(t,"cdr",t.cdr,r);if(!n){s(t.car,r.slice())}if(!i){return new Mn(function(){return e(t.cdr,r.slice())})}}});function r(e,t){if(e[Yu][t]instanceof q){var r=n.indexOf(e[Yu][t]);e[Yu][t]="#".concat(r,"#")}}s(e,[]);var n=t.filter(function(e){return u.includes(e)});n.forEach(function(e,t){e[Mu]="#".concat(t,"=")});i.forEach(function(e){r(e,"car");r(e,"cdr")})}q.prototype.toString=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=t.nested,n=r===void 0?false:r;var i=[];if(this[Mu]){i.push(this[Mu]+"(")}else if(!n){i.push("(")}var u;if(this[Yu]&&this[Yu].car){u=this[Yu].car}else{u=nu(this.car,e,true)}if(u!==undefined){i.push(u)}if(this.cdr instanceof q){if(this[Yu]&&this[Yu].cdr){i.push(" . ");i.push(this[Yu].cdr)}else{if(this.cdr[Mu]){i.push(" . ")}else{i.push(" ")}var a=this.cdr.toString(e,{nested:true});i.push(a)}}else if(this.cdr!==U){i=i.concat([" . ",nu(this.cdr,e,true)])}if(!n||this[Mu]){i.push(")")}return i.join("")};q.prototype.set=function(e,t){this[e]=t;if(t instanceof q){this.markCycles()}};q.prototype.append=function(e){if(e instanceof Array){return this.append(q.fromArray(e))}var t=this;if(t.car===undefined){if(e instanceof q){this.car=e.car;this.cdr=e.cdr}else{this.car=e}}else if(e!==U){while(true){if(t instanceof q&&t.cdr!==U){t=t.cdr}else{break}}t.cdr=e}return this};q.prototype.serialize=function(){return[this.car,this.cdr]};q.prototype[Symbol.iterator]=function(){var r=this;return{next:function e(){var t=r;r=t.cdr;if(t===U){return{value:undefined,done:true}}else{return{value:t.car,done:false}}}}};function au(e){return e<0?-e:e}function ou(e,t){var r=b(t),n=r[0],i=r.slice(1);while(i.length>0){var u=i,a=j(u,1),o=a[0];if(!e(n,o)){return false}var s=i;var c=b(s);n=c[0];i=c.slice(1)}return true}function su(e,t){if(Du(e)){return Du(t)&&Bu(e)===Bu(t)}else if(e instanceof k){if(!(t instanceof k)){return false}var r;if(e.__type__===t.__type__){if(e.__type__==="complex"){r=e.__im__.__type__===t.__im__.__type__&&e.__re__.__type__===t.__re__.__type__}else{r=true}if(r&&e.cmp(t)===0){if(e.valueOf()===0){return Object.is(e.valueOf(),t.valueOf())}return true}}return false}else if(typeof e==="number"){if(typeof t!=="number"){return false}if(Number.isNaN(e)){return Number.isNaN(t)}if(e===Number.NEGATIVE_INFINITY){return t===Number.NEGATIVE_INFINITY}if(e===Number.POSITIVE_INFINITY){return t===Number.POSITIVE_INFINITY}return su(k(e),k(t))}else if(e instanceof pa){if(!(t instanceof pa)){return false}return e.__char__===t.__char__}else{return e===t}}function cu(e,t){if(Oo(e)!==Oo(t)){return false}if(!fu(e)){return false}if(e instanceof RegExp){return e.source===t.source}if(e instanceof _a){return e.valueOf()===t.valueOf()}return su(e,t)}function fu(e){return e instanceof L||_a.isString(e)||e===U||e===null||e instanceof pa||e instanceof k||e===true||e===false}var lu=function(){if(Math.trunc){return Math.trunc}else{return function(e){if(e===0){return 0}else if(e<0){return Math.ceil(e)}else{return Math.floor(e)}}}}();function hu(e,t,r,n){if(typeof this!=="undefined"&&this.constructor!==hu||typeof this==="undefined"){return new hu(e,t)}Eo("Macro",e,"string",1);Eo("Macro",t,"function",2);if(r){if(n){this.__doc__=r}else{this.__doc__=yi(r)}}this.__name__=e;this.__fn__=t}hu.defmacro=function(e,t,r,n){var i=new hu(e,t,r,n);i.__defmacro__=true;return i};hu.prototype.invoke=function(e,t,r){var n=t.env,i=t.dynamic_scope,u=t.error;var a={dynamic_scope:i,error:u,macro_expand:r};var o=this.__fn__.call(n,e,a,this.__name__);return o};hu.prototype.toString=function(){return"#")};var pu="define-macro";var _u=-1e4;function du(c){return function(){var r=O(z.mark(function e(r,y){var u,g,n,i,s,D,E,A,F,x,C,b,a,w,o;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:o=function e(){o=O(z.mark(function e(r,n,i){var h,u,a,p,o,_,s,d,c,v,f,l,m;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:if(!(r instanceof q&&r.car instanceof L)){t.next=50;break}if(!r[qu]){t.next=3;break}return t.abrupt("return",r);case 3:h=r.car.valueOf();u=i.get(r.car,{throwError:false});a=D(r.car);p=a||E(u,r)||A(u);if(!(p&&r.cdr.car instanceof q)){t.next=28;break}if(!a){t.next=15;break}g=x(r.cdr.car);t.next=12;return b(r.cdr.car,n);case 12:o=t.sent;t.next=17;break;case 15:g=F(r.cdr.car);o=r.cdr.car;case 17:t.t0=q;t.t1=r.car;t.t2=q;t.t3=o;t.next=23;return w(r.cdr.cdr,n,i);case 23:t.t4=t.sent;t.t5=new t.t2(t.t3,t.t4);return t.abrupt("return",new t.t0(t.t1,t.t5));case 28:if(!C(h,u)){t.next=50;break}_=u instanceof vu?r:r.cdr;t.next=32;return u.invoke(_,Lr(Lr({},y),{},{env:i}),true);case 32:s=t.sent;if(!(u instanceof vu)){t.next=41;break}d=s,c=d.expr,v=d.scope;if(!(c instanceof q)){t.next=40;break}if(!(n!==-1&&n<=1||n<_u)){t.next=38;break}return t.abrupt("return",c);case 38:if(n!==-1){n=n-1}return t.abrupt("return",w(c,n,v));case 40:s=c;case 41:if(!(s instanceof L)){t.next=43;break}return t.abrupt("return",to(s));case 43:if(!(s instanceof q)){t.next=48;break}if(!(n!==-1&&n<=1||n<_u)){t.next=46;break}return t.abrupt("return",s);case 46:if(n!==-1){n=n-1}return t.abrupt("return",w(s,n,i));case 48:if(!fu(s)){t.next=50;break}return t.abrupt("return",s);case 50:f=r.car;if(!(f instanceof q)){t.next=55;break}t.next=54;return w(f,n,i);case 54:f=t.sent;case 55:l=r.cdr;if(!(l instanceof q)){t.next=60;break}t.next=59;return w(l,n,i);case 59:l=t.sent;case 60:m=new q(f,l);return t.abrupt("return",m);case 62:case"end":return t.stop()}}},e)}));return o.apply(this,arguments)};w=function e(t,r,n){return o.apply(this,arguments)};a=function e(){a=O(z.mark(function e(r,n){var i;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:if(!(r===U)){t.next=2;break}return t.abrupt("return",U);case 2:i=r.car;t.t0=q;t.t1=q;t.t2=i.car;t.next=8;return w(i.cdr,n,u);case 8:t.t3=t.sent;t.t4=new t.t1(t.t2,t.t3);t.next=12;return b(r.cdr);case 12:t.t5=t.sent;return t.abrupt("return",new t.t0(t.t4,t.t5));case 14:case"end":return t.stop()}}},e)}));return a.apply(this,arguments)};b=function e(t,r){return a.apply(this,arguments)};C=function e(t,r){return r instanceof hu&&r.__defmacro__&&!g.includes(t)};x=function e(t){return[].concat(M(g),M(t.to_array(false).map(function(e){if(e instanceof q){return e.car.valueOf()}throw new Error("macroexpand: Invalid let binding")})))};F=function e(t){var r=[];while(true){if(t!==U){if(t instanceof L){r.push(t.valueOf());break}r.push(t.car.valueOf());t=t.cdr}else{break}}return[].concat(M(g),r)};A=function e(t){return t===i};E=function e(t,r){return t===s&&r.cdr.car instanceof q};D=function e(t){var r=t.valueOf();return n.includes(r)};u=y["env"]=this;g=[];n=["let","let*","letrec"];i=co.get("lambda");s=co.get("define");if(!(r.cdr instanceof q&&k.isNumber(r.cdr.car))){t.next=21;break}t.t0=to;t.next=19;return w(r,r.cdr.car.valueOf(),u);case 19:t.t1=t.sent.car;return t.abrupt("return",(0,t.t0)(t.t1));case 21:if(!c){t.next=27;break}t.t2=to;t.next=25;return w(r,1,u);case 25:t.t3=t.sent.car;return t.abrupt("return",(0,t.t2)(t.t3));case 27:t.t4=to;t.next=30;return w(r,-1,u);case 30:t.t5=t.sent.car;return t.abrupt("return",(0,t.t4)(t.t5));case 32:case"end":return t.stop()}}},e,this)}));return function(e,t){return r.apply(this,arguments)}}()}function vu(e,t){this.__env__=t;this.__fn__=e;this.__defmacro__=true}vu.__merge_env__=Symbol["for"]("merge");vu.prototype=Object.create(hu.prototype);vu.prototype.invoke=function(e,t,r){var n=t.error,i=t.env;var u={error:n,env:i,dynamic_scope:this.__env__,macro_expand:r};return this.__fn__.call(i,e,u,this.__name__||"syntax")};vu.prototype.constructor=vu;vu.prototype.toString=function(){if(this.__name__){return"#")}return"#"};vu.className="syntax";var mu=function(e){u(r,e);var t=jr(r);function r(){A(this,r);return t.apply(this,arguments)}return x(r)}(vu);vu.Parameter=mu;function yu(e,t,w,D){var r=arguments.length>4&&arguments[4]!==undefined?arguments[4]:{};var E={"...":{symbols:{},lists:[]},symbols:{}};var A=r.expansion,C=r.define;function F(e){if(Qr()){console.log(e)}}F(w);function x(e,t){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:[];var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;F({code:t&&nu(t,true),pattern:e&&nu(e,true)});if(fu(e)&&!(e instanceof L)){return cu(e,t)}if(e instanceof L&&w.includes(e.literal())){var c=A.ref(t);if(L.is(t,e)){if(typeof c==="undefined"){return true}return c===C||c===co}return false}if(e instanceof q&&e.car instanceof q&&e.car.cdr instanceof q&&L.is(e.car.cdr.car,D)){F(">> 0");if(t===U){F({pattern:e.toString()});if(e.car.car instanceof L){if(e.car.cdr instanceof q&&L.is(e.car.cdr.car,D)){var f=e.car.car.valueOf();var l=e.last_pair();if(L.is(l.car,D)){E["..."].symbols[f]=null;return true}else{return false}}var h=e.car.car.valueOf();if(E["..."].symbols[h]){throw new Error("syntax: named ellipsis can only "+"appear onces")}E["..."].symbols[h]=t}}}if(e instanceof q&&e.cdr instanceof q&&L.is(e.cdr.car,D)){if(e.cdr.cdr!==U){if(e.cdr.cdr instanceof q){var p=e.cdr.cdr.length();var _=t.length();var i=t;while(_-1>p){i=i.cdr;_--}var d=i.cdr;i.cdr=U;if(!x(e.cdr.cdr,d,r,n)){return false}}}if(e.car instanceof L){var u=e.car.__name__;if(E["..."].symbols[u]&&!r.includes(u)&&!n){throw new Error("syntax: named ellipsis can only appear onces")}F(">> 1");if(t===U){F(">> 2");if(n){F("NIL");E["..."].symbols[u]=U}else{F("NULL");E["..."].symbols[u]=null}}else if(t instanceof q&&(t.car instanceof q||t.car===U)){F(">> 3 "+n);if(n){if(E["..."].symbols[u]){var a=E["..."].symbols[u];if(a===U){a=new q(U,new q(t,U))}else{a=a.append(new q(t,U))}E["..."].symbols[u]=a}else{E["..."].symbols[u]=new q(t,U)}}else{F(">> 4");E["..."].symbols[u]=new q(t,U)}}else{F(">> 6");if(t instanceof q){F(">> 7 "+n);r.push(u);if(!E["..."].symbols[u]){E["..."].symbols[u]=new q(t,U)}else{var v=E["..."].symbols[u];E["..."].symbols[u]=v.append(new q(t,U))}F({IIIIII:E["..."].symbols[u].toString()})}else{F(">> 8");return false}}return true}else if(e.car instanceof q){var m=M(r);if(t===U){F(">> 9");E["..."].lists.push(U);return true}F(">> 10");var y=t;while(y instanceof q){if(!x(e.car,y.car,m,true)){return false}y=y.cdr}return true}return false}if(e instanceof L){if(L.is(e,D)){throw new Error("syntax: invalid usage of ellipsis")}F(">> 11");var o=e.__name__;if(w.includes(o)){return true}F({name:o,ellipsis:n});if(n){E["..."].symbols[o]=E["..."].symbols[o]||[];E["..."].symbols[o].push(t)}E.symbols[o]=t;if(!E.symbols[o]);return true}if(e instanceof q&&t instanceof q){F(">> 12");F({a:12,code:t&&t.toString(),pattern:e.toString()});if(t.cdr===U){var g=e.car instanceof L&&e.cdr instanceof L;if(g){if(!x(e.car,t.car,r,n)){return false}F(">> 12 | 1");var s=e.cdr.valueOf();if(!(s in E.symbols)){E.symbols[s]=U}s=e.car.valueOf();if(!(s in E.symbols)){E.symbols[s]=t.car}return true}}F({pattern:e.toString(),code:t.toString()});if(e.cdr instanceof q&&e.car instanceof L&&e.cdr.cdr instanceof q&&e.cdr.car instanceof L&&L.is(e.cdr.cdr.car,D)&&e.cdr.cdr.cdr instanceof q&&!L.is(e.cdr.cdr.cdr.car,D)&&x(e.car,t.car,r,n)&&x(e.cdr.cdr.cdr,t.cdr,r,n)){var b=e.cdr.car.__name__;F({pattern:e.car.toString(),code:t.car.toString(),name:b});if(w.includes(b)){return true}E["..."].symbols[b]=null;return true}F("recur");if(x(e.car,t.car,r,n)&&x(e.cdr,t.cdr,r,n)){return true}}else if(e===U&&(t===U||t===undefined)){return true}else if(e.car instanceof q&&L.is(e.car.car,D)){throw new Error("syntax: invalid usage of ellipsis")}else{return false}}if(x(e,t)){return E}}function gu(e,i){function u(t){if(t instanceof q){if(!i.length){return t}var e=u(t.car);var r=u(t.cdr);return new q(e,r)}else if(t instanceof L){var n=i.find(function(e){return e.gensym===t});if(n){return L(n.name)}return t}else{return t}}return u(e)}function bu(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var O=e.bindings,t=e.expr,S=e.scope,a=e.symbols,f=e.names,B=e.ellipsis;var c={};function o(e){if(e instanceof L){return true}return["string","symbol"].includes(_(e))}function j(e){if(!o(e)){var t=Oo(e);throw new Error("syntax: internal error, need symbol got ".concat(t))}var r=e.valueOf();if(r===B){throw new Error("syntax: internal error, ellipis not transformed")}var n=_(r);if(["string","symbol"].includes(n)){if(r in O.symbols){return O.symbols[r]}else if(n==="string"&&r.match(/\./)){var i=r.split(".");var u=i[0];if(u in O.symbols){return q.fromArray([L("."),O.symbols[u]].concat(i.slice(1).map(function(e){return _a(e)})))}}}if(a.includes(r)){return L(r)}return s(r)}function I(e){if(Qr()){console.log(e)}}function s(e){if(!c[e]){var t=S.ref(e);var r=Hn(e);if(t){var n=S.get(e);S.set(r,n)}else{var i=S.get(e,{throwError:false});if(typeof i!=="undefined"){S.set(r,i)}}f.push({name:e,gensym:r});c[e]=r;if(typeof e==="string"&&e.match(/\./)){var u=e.split(".").filter(Boolean),a=b(u),o=a[0],s=a.slice(1);if(c[o]){Hu(r,"__object__",[c[o]].concat(M(s)))}}}return c[e]}function P(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:function(){};var i=r.nested;I(" ==> "+e.toString(true));I(t);if(e instanceof L){var u=e.valueOf();I("[t 1");if(t[u]){if(t[u]instanceof q){var c=t[u],f=c.car,l=c.cdr;if(i){var h=f.car,p=f.cdr;if(p!==U){n(u,new q(p,U))}return h}if(l!==U){n(u,l)}return f}else if(t[u]instanceof Array){n(u,t[u].slice(1));return t[u][0]}}return j(u)}if(e instanceof q){if(e.car instanceof L&&e.cdr instanceof q&&L.is(e.cdr.car,B)){I("[t 2");var a=e.car.valueOf();var o=t[a];I({expr:e.toString(true),name:a,bindings:t,item:o});if(o===null){return}else if(o){I({b:t[a].toString()});if(o instanceof q){I("[t 2 Pair "+i);I({______:o.toString()});var s=o.car,_=o.cdr;if(i){if(_!==U){I("|| next 1");n(a,_)}I({car:s.toString()});return s}else{if(s.cdr!==U){I("|| next 2");n(a,new q(s.cdr,_))}I({car:s.car.toString()});return s.car}}else if(o instanceof Array){I("[t 2 Array "+i);if(i){n(a,o.slice(1));return q.fromArray(o)}else{var d=o.slice(1);if(d.length){n(a,d)}return o[0]}}else{return o}}}I("[t 3 recur "+e.toString());var v=P(e.car,t,r,n);var m=P(e.cdr,t,r,n);return new q(v,m)}return e}function R(t,r){var e=Object.values(t);var n=Object.getOwnPropertySymbols(t);if(n.length){e.push.apply(e,M(n.map(function(e){return t[e]})))}return e.length&&e.every(function(e){if(e===null){return!r}return e instanceof q||e===U||e instanceof Array&&e.length})}function T(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function N(i){var n=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},e=n.disabled;I("traverse>> "+nu(i));if(i instanceof q){if(!e&&i.car instanceof q&&L.is(i.car.car,B)){return N(i.car.cdr,{disabled:true})}if(i.cdr instanceof q&&L.is(i.cdr.car,B)&&!e){I(">> 1");var t=O["..."].symbols;var f=Object.values(t);if(f.length&&f.every(function(e){return e===null})){return N(i.cdr.cdr,{disabled:e})}var l=T(t);var u=i.car instanceof L&&L.is(i.cdr.cdr.car,B);if(i.car instanceof q||u){if(O["..."].lists[0]===U){return U}var h=i.car;if(u){h=new q(i.car,new q(i.cdr.car,U))}I(">> 2");var a;if(l.length){I(">> 2 (a)");var o=Lr({},t);a=U;var p=function e(){if(!R(o)){return"break"}var n={};var t=function e(t,r){n[t]=r};var r=P(h,o,{nested:true},t);if(r!==undefined){if(u){if(a===U){a=r}else{a=a.append(r)}}else{a=new q(r,a)}}o=n};while(true){var _=p();if(_==="break")break}if(a!==U&&!u){a=a.reverse()}if(i.cdr.cdr!==U&&!L.is(i.cdr.cdr.car,B)){var d=N(i.cdr.cdr,{disabled:e});return a.append(d)}return a}else{I(">> 3");var v=P(i.car,t,{nested:true});if(v){return new q(v,U)}return U}}else if(i.car instanceof L){I(">> 4");if(L.is(i.cdr.cdr.car,B)){I(">> 4 (a)")}else{I(">> 4 (b)")}var m=i.car.__name__;var s=Y({},m,t[m]);var y=t[m]===null;var c=U;var g=function e(){if(!R(s,true)){I({bind:s});return"break"}var n={};var t=function e(t,r){n[t]=r};var r=P(i,s,{nested:false},t);I({value:r.toString()});if(typeof r!=="undefined"){c=new q(r,c)}s=n};while(true){var b=g();if(b==="break")break}if(c!==U){c=c.reverse()}if(i.cdr instanceof q){if(i.cdr.cdr instanceof q||i.cdr.cdr instanceof L){var w=N(i.cdr.cdr,{disabled:e});if(y){return w}I("<<<< 1");c.append(w)}}I("<<<< 2");return c}}var D=N(i.car,{disabled:e});var r;var E;if(i.car instanceof L){var A=S.get(i.car,{throwError:false});E=A instanceof hu&&A.__name__==="syntax-rules"}if(E){if(i.cdr.car instanceof L){r=new q(N(i.cdr.car,{disabled:e}),new q(i.cdr.cdr.car,N(i.cdr.cdr.cdr,{disabled:e})))}else{r=new q(i.cdr.car,N(i.cdr.cdr,{disabled:e}))}I("REST >>>> "+r.toString())}else{r=N(i.cdr,{disabled:e})}I({a:true,car:nu(i.car),cdr:nu(i.cdr),head:nu(D),rest:nu(r)});return new q(D,r)}if(i instanceof L){if(e&&L.is(i,B)){return i}var F=Object.keys(O["..."].symbols);var x=i.literal();if(F.includes(x)){var C="missing ellipsis symbol next to name `".concat(x,"'");throw new Error("syntax-rules: ".concat(C))}var k=j(i);if(typeof k!=="undefined"){return k}}return i}return N(t,{})}function wu(e){return xu(e)||e===U||e===null}function Du(e){return typeof e==="function"&&typeof e.bind==="function"}function Eu(e){return e instanceof Ro}function Au(e){return Du(e)||Eu(e)}function Fu(e){if(e instanceof Qn){return false}if(e instanceof Promise){return true}return e&&Du(e.then)}function xu(e){return typeof e==="undefined"}function Cu(e){switch(_(e)){case"string":return _a(e);case"bigint":return k(e);case"number":if(Number.isNaN(e)){return oo}else{return k(e)}}return e}function ku(n,i){var e=Object.getOwnPropertyNames(n);var t=Object.getOwnPropertySymbols(n);e.concat(t).forEach(function(e){var t=i(n[e]);var r=Object.getOwnPropertyDescriptor(n,e);if(!r||r.writable&&n[e]!==t){n[e]=t}});return n}function Ou(t){var e=[_a,k].some(function(e){return t instanceof e});if(e){return t.valueOf()}if(t instanceof Array){return t.map(Ou)}if(t instanceof Qn){delete t.then}if(zi(t)){return ku(t,Ou)}return t}function Su(e,t){if(e instanceof q){e.markCycles();return to(e)}if(Du(e)){if(t){return ju(e,t)}}return Cu(e)}function Bu(e){if(Pu(e)){return e[Uu]}return e}function ju(e,t){if(e[Symbol["for"]("__bound__")]){return e}var r=e.bind(t);var n=Object.getOwnPropertyNames(e);var i=Pr(n),u;try{for(i.s();!(u=i.n()).done;){var a=u.value;if(Wu(a)){try{r[a]=e[a]}catch(e){}}}}catch(e){i.e(e)}finally{i.f()}Hu(r,"__fn__",e);Hu(r,"__context__",t);Hu(r,"__bound__",true);if(ea(e)){Hu(r,"__native__",true)}if(zi(t)&&Zu(e)){Hu(r,"__method__",true)}r.valueOf=function(){return e};return r}function Iu(e){return Pu(e)&&e[Symbol["for"]("__context__")]===Object}function Pu(e){return!!(Du(e)&&e[Uu])}function Nu(e){if(Du(e)){var t=e[Lu];if(t&&(t===ys||t.constructor&&t.constructor.__class__)){return true}}return false}function Ru(e){return e instanceof Na||e instanceof Ra}function Tu(e){if(Du(e)){if(Ru(e[Lu])){return true}}return false}var Lu=Symbol["for"]("__context__");var Uu=Symbol["for"]("__fn__");var qu=Symbol["for"]("__data__");var Mu=Symbol["for"]("__ref__");var Yu=Symbol["for"]("__cycles__");var $u=Symbol["for"]("__class__");var zu=Symbol["for"]("__method__");var Vu=Symbol["for"]("__prototype__");var Ju=Symbol["for"]("__lambda__");var Gu=["name","length","caller","callee","arguments","prototype"];function Wu(e){return!Gu.includes(e)}function Hu(e,t,r){Object.defineProperty(e,Symbol["for"](t),{get:function e(){return r},set:function e(){},configurable:false,enumerable:false})}function Qu(t,r){try{Object.defineProperty(t,"length",{get:function e(){return r}});return t}catch(e){var n=new Array(r).fill(0).map(function(e,t){return"a"+t}).join(",");var i=new Function("f","return function(".concat(n,") {\n return f.apply(this, arguments);\n };"));return i(t)}}function Zu(e){return e&&e[Ju]}function Ku(e){return e&&e[zu]}function Xu(e){return Zu(e)&&!e[Vu]&&!Ku(e)&&!Tu(e)}function ea(e){var t=Symbol["for"]("__native__");return Du(e)&&e.toString().match(/\{\s*\[native code\]\s*\}/)&&(e.name.match(/^bound /)&&e[t]===true||!e.name.match(/^bound /)&&!e[t])}function ta(e){var g;switch(e){case Symbol["for"]("letrec"):g="letrec";break;case Symbol["for"]("let"):g="let";break;case Symbol["for"]("let*"):g="let*";break;default:throw new Error("Invalid let_macro value")}return hu.defmacro(g,function(t,e){var f=e.dynamic_scope,l=e.error,n=e.macro_expand;var h;if(t.car instanceof L){if(!(t.cdr.car instanceof q||t.cdr.car===U)){throw new Error("let require list of pairs")}var r;if(t.cdr.car===U){h=U;r=U}else{r=t.cdr.car.map(function(e){return e.car});h=t.cdr.car.map(function(e){return e.cdr.car})}return q.fromArray([L("letrec"),[[t.car,q(L("lambda"),q(r,t.cdr.cdr))]],q(t.car,h)])}else if(n){return}var p=this;h=co.get("list->array")(t.car);var _=p.inherit(g);var d,v;if(g==="let*"){v=_}else if(g==="let"){d=[]}var m=0;function y(){var e=new q(new L("begin"),t.cdr);return Lo(e,{env:_,dynamic_scope:f,error:l})}return function t(){var r=h[m++];if(f){f=g==="let*"?_:p}if(!r){if(d&&d.length){var e=d.map(function(e){return e.value});var n=e.filter(Fu);if(n.length){return Zn(e).then(function(e){for(var t=0,r=e.length;t1&&arguments[1]!==undefined?arguments[1]:{},r=t.dynamic_scope,n=t.error;var i=this;if(r){r=this}var u=e;var a=[];while(u instanceof q){a.push(Lo(u.car,{env:i,dynamic_scope:r,error:n}));u=u.cdr}var o=a.filter(Fu).length;if(o){return Zn(a).then(s.bind(this))}else{return s.call(this,a)}})}function na(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n2?n-2:0),u=2;u1&&arguments[1]!==undefined?arguments[1]:null;return function(){for(var e=arguments.length,t=new Array(e),r=0;r1?e-1:0),r=1;r=a){return u.apply(this,n)}else{return i}}return i.apply(this,arguments)}}function ha(n,i){Eo("limit",i,"function",2);return function(){for(var e=arguments.length,t=new Array(e),r=0;r1){e=e.toLowerCase();if(pa.__names__[e]){t=e;e=pa.__names__[e]}else{throw new Error("Internal: Unknown named character")}}else{t=pa.__rev_names__[e]}Object.defineProperty(this,"__char__",{value:e,enumerable:true});if(t){Object.defineProperty(this,"__name__",{value:t,enumerable:true})}}pa.__names__=sn;pa.__rev_names__={};Object.keys(pa.__names__).forEach(function(e){var t=pa.__names__[e];pa.__rev_names__[t]=e});pa.prototype.toUpperCase=function(){return pa(this.__char__.toUpperCase())};pa.prototype.toLowerCase=function(){return pa(this.__char__.toLowerCase())};pa.prototype.toString=function(){return"#\\"+(this.__name__||this.__char__)};pa.prototype.valueOf=pa.prototype.serialize=function(){return this.__char__};function _a(e){if(typeof this!=="undefined"&&!(this instanceof _a)||typeof this==="undefined"){return new _a(e)}if(e instanceof Array){this.__string__=e.map(function(e,t){Eo("LString",e,"character",t+1);return e.toString()}).join("")}else{this.__string__=e.valueOf()}}{var da=["length","constructor"];var va=Object.getOwnPropertyNames(String.prototype).filter(function(e){return!da.includes(e)});var ma=function e(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r0){r.push(this.__string__.substring(0,e))}r.push(t);if(e1&&arguments[1]!==undefined?arguments[1]:false;if(e instanceof k){return e}if(typeof this!=="undefined"&&!(this instanceof k)||typeof this==="undefined"){return new k(e,t)}if(typeof e==="undefined"){throw new Error("Invalid LNumber constructor call")}var r=k.getType(e);if(k.types[r]){return k.types[r](e,t)}var n=e instanceof Array&&_a.isString(e[0])&&k.isNumber(e[1]);if(e instanceof k){return k(e.value)}if(!k.isNumber(e)&&!n){throw new Error("You can't create LNumber from ".concat(Oo(e)))}if(e===null){e=0}var i;if(n){var c=e,u=j(c,2),a=u[0],o=u[1];if(a instanceof _a){a=a.valueOf()}if(o instanceof k){o=o.valueOf()}var f=a.match(/^([+-])/);var l=false;if(f){a=a.replace(/^[+-]/,"");if(f[1]==="-"){l=true}}}if(Number.isNaN(e)){return ka(e)}else if(typeof BigInt!=="undefined"){if(typeof e!=="bigint"){if(n){var s;switch(o){case 8:s="0o";break;case 16:s="0x";break;case 2:s="0b";break;case 10:s="";break}if(typeof s==="undefined"){var h=BigInt(o);i=M(a).map(function(e,t){return BigInt(parseInt(e,o))*Fa(h,BigInt(t))}).reduce(function(e,t){return e+t})}else{i=BigInt(s+a)}}else{i=BigInt(e)}if(l){i*=BigInt(-1)}}else{i=e}return Pa(i,true)}else if(typeof Gr!=="undefined"&&!(e instanceof Gr)){if(e instanceof Array){return Pa(p(Gr,M(e)))}return Pa(new Gr(e))}else if(n){this.constant(parseInt(a,o),"integer")}else{this.constant(e,"integer")}}k.prototype.constant=function(e,t){Object.defineProperty(this,"__value__",{value:e,enumerable:true});Object.defineProperty(this,"__type__",{value:t,enumerable:true})};k.types={float:function e(t){return new ka(t)},complex:function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!k.isComplex(t)){t={im:0,re:t}}return new Ca(t,r)},rational:function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!k.isRational(t)){t={num:t,denom:1}}return new Ia(t,r)}};k.prototype.serialize=function(){return this.__value__};k.prototype.isNaN=function(){return Number.isNaN(this.__value__)};k.prototype.gcd=function(e){var t=this.abs();e=e.abs();if(e.cmp(t)===1){var r=t;t=e;e=r}while(true){t=t.rem(e);if(t.cmp(0)===0){return e}e=e.rem(t);if(e.cmp(0)===0){return t}}};k.isFloat=function e(t){return t instanceof ka||Number(t)===t&&t%1!==0};k.isNumber=function(e){return e instanceof k||k.isNative(e)||k.isBN(e)};k.isComplex=function(e){if(!e){return false}var t=e instanceof Ca||(k.isNumber(e.im)||Number.isNaN(e.im))&&(k.isNumber(e.re)||Number.isNaN(e.re));return t};k.isRational=function(e){if(!e){return false}return e instanceof Ia||k.isNumber(e.num)&&k.isNumber(e.denom)};k.isInteger=function(e){if(!(k.isNative(e)||e instanceof k)){return false}if(k.isFloat(e)){return false}if(k.isRational(e)){return false}if(k.isComplex(e)){return false}return true};k.isNative=function(e){return typeof e==="bigint"||typeof e==="number"};k.isBigInteger=function(e){return e instanceof Pa||typeof e==="bigint"||k.isBN(e)};k.isBN=function(e){return typeof Gr!=="undefined"&&e instanceof Gr};k.getArgsType=function(e,t){if(e instanceof ka||t instanceof ka){return ka}if(e instanceof Pa||t instanceof Pa){return Pa}return k};k.prototype.toString=function(e){if(Number.isNaN(this.__value__)){return"+nan.0"}if(e>2&&e<36){return this.__value__.toString(e)}return this.__value__.toString()};k.prototype.asType=function(e){var t=k.getType(this);return k.types[t]?k.types[t](e):k(e)};k.prototype.isBigNumber=function(){return typeof this.__value__==="bigint"||typeof Gr!=="undefined"&&!(this.value instanceof Gr)};["floor","ceil","round"].forEach(function(e){k.prototype[e]=function(){if(this["float"]||k.isFloat(this.__value__)){return k(Math[e](this.__value__))}else{return k(Math[e](this.valueOf()))}}});k.prototype.valueOf=function(){if(k.isNative(this.__value__)){return Number(this.__value__)}else if(k.isBN(this.__value__)){return this.__value__.toNumber()}};var wa=function(){var e=function e(t,r){return[t,r]};return{bigint:{bigint:e,float:function e(t,r){return[ka(t.valueOf()),r]},rational:function e(t,r){return[{num:t,denom:1},r]},complex:function e(t,r){return[{im:0,re:t},r]}},integer:{integer:e,float:function e(t,r){return[ka(t.valueOf()),r]},rational:function e(t,r){return[{num:t,denom:1},r]},complex:function e(t,r){return[{im:0,re:t},r]}},float:{bigint:function e(t,r){return[t,r&&ka(r.valueOf())]},integer:function e(t,r){return[t,r&&ka(r.valueOf())]},float:e,rational:function e(t,r){return[t,r&&ka(r.valueOf())]},complex:function e(t,r){return[{re:t,im:ka(0)},r]}},complex:{bigint:t("bigint"),integer:t("integer"),float:t("float"),rational:t("rational"),complex:function f(e,t){var r=k.coerce(e.__re__,t.__re__),n=j(r,2),i=n[0],u=n[1];var a=k.coerce(e.__im__,t.__im__),o=j(a,2),s=o[0],c=o[1];return[{im:s,re:i},{im:c,re:u}]}},rational:{bigint:function e(t,r){return[t,r&&{num:r,denom:1}]},integer:function e(t,r){return[t,r&&{num:r,denom:1}]},float:function e(t,r){return[ka(t.valueOf()),r]},rational:e,complex:function e(t,r){return[{im:Da(t.__type__,r.__im__.__type__,0)[0],re:Da(t.__type__,r.__re__.__type__,t)[0]},{im:Da(t.__type__,r.__im__.__type__,r.__im__)[0],re:Da(t.__type__,r.__re__.__type__,r.__re__)[0]}]}}};function t(r){return function(e,t){return[{im:Da(r,e.__im__.__type__,0,e.__im__)[1],re:Da(r,e.__re__.__type__,0,e.__re__)[1]},{im:Da(r,e.__im__.__type__,0,0)[1],re:Da(r,t.__type__,0,t)[1]}]}}}();function Da(e,t,r,n){return wa[e][t](r,n)}k.coerce=function(e,t){var r=k.getType(e);var n=k.getType(t);if(!wa[r]){throw new Error("LNumber::coerce unknown lhs type ".concat(r))}else if(!wa[r][n]){throw new Error("LNumber::coerce unknown rhs type ".concat(n))}var i=wa[r][n](e,t);return i.map(function(e){return k(e,true)})};k.prototype.coerce=function(e){if(!(typeof e==="number"||e instanceof k)){throw new Error("LNumber: you can't coerce ".concat(Oo(e)))}if(typeof e==="number"){e=k(e)}return k.coerce(this,e)};k.getType=function(e){if(e instanceof k){return e.__type__}if(k.isFloat(e)){return"float"}if(k.isComplex(e)){return"complex"}if(k.isRational(e)){return"rational"}if(typeof e==="number"){return"integer"}if(typeof BigInt!=="undefined"&&typeof e!=="bigint"||typeof Gr!=="undefined"&&!(e instanceof Gr)){return"bigint"}};k.prototype.isFloat=function(){return!!(k.isFloat(this.__value__)||this["float"])};var Ea={add:"+",sub:"-",mul:"*",div:"/",rem:"%",or:"|",and:"&",neg:"~",shl:">>",shr:"<<"};var Aa={};Object.keys(Ea).forEach(function(t){Aa[Ea[t]]=t;k.prototype[t]=function(e){return this.op(Ea[t],e)}});k._ops={"*":function e(t,r){return t*r},"+":function e(t,r){return t+r},"-":function e(t,r){if(typeof r==="undefined"){return-t}return t-r},"/":function e(t,r){return t/r},"%":function e(t,r){return t%r},"|":function e(t,r){return t|r},"&":function e(t,r){return t&r},"~":function e(t){return~t},">>":function e(t,r){return t>>r},"<<":function e(t,r){return t<1&&arguments[1]!==undefined?arguments[1]:false;if(typeof this!=="undefined"&&!(this instanceof Ca)||typeof this==="undefined"){return new Ca(e,t)}if(e instanceof Ca){return Ca({im:e.__im__,re:e.__re__})}if(k.isNumber(e)&&t){if(!t){return Number(e)}}else if(!k.isComplex(e)){var r="Invalid constructor call for LComplex expect &(:im :re ) object but got ".concat(nu(e));throw new Error(r)}var n=e.im instanceof k?e.im:k(e.im);var i=e.re instanceof k?e.re:k(e.re);this.constant(n,i)}Ca.prototype=Object.create(k.prototype);Ca.prototype.constructor=Ca;Ca.prototype.constant=function(e,t){Object.defineProperty(this,"__im__",{value:e,enumerable:true});Object.defineProperty(this,"__re__",{value:t,enumerable:true});Object.defineProperty(this,"__type__",{value:"complex",enumerable:true})};Ca.prototype.serialize=function(){return{re:this.__re__,im:this.__im__}};Ca.prototype.toRational=function(e){if(k.isFloat(this.__im__)&&k.isFloat(this.__re__)){var t=ka(this.__im__).toRational(e);var r=ka(this.__re__).toRational(e);return Ca({im:t,re:r})}return this};Ca.prototype.pow=function(e){throw new Error("Not yet implemented")};Ca.prototype.add=function(e){return this.complex_op("add",e,function(e,t,r,n){return{re:e.add(t),im:r.add(n)}})};Ca.prototype.factor=function(){if(this.__im__ instanceof ka||this.__im__ instanceof ka){var e=this.__re__,t=this.__im__;var r,n;if(e instanceof ka){r=e.toRational().mul(e.toRational())}else{r=e.mul(e)}if(t instanceof ka){n=t.toRational().mul(t.toRational())}else{n=t.mul(t)}return r.add(n)}else{return this.__re__.mul(this.__re__).add(this.__im__.mul(this.__im__))}};Ca.prototype.modulus=function(){return this.factor().sqrt()};Ca.prototype.conjugate=function(){return Ca({re:this.__re__,im:this.__im__.sub()})};Ca.prototype.sqrt=function(){var e=this.modulus();var t,r;if(e.cmp(0)===0){t=r=e}else if(this.__re__.cmp(0)===1){t=ka(.5).mul(e.add(this.__re__)).sqrt();r=this.__im__.div(t).div(2)}else{r=ka(.5).mul(e.sub(this.__re__)).sqrt();if(this.__im__.cmp(0)===-1){r=r.sub()}t=this.__im__.div(r).div(2)}return Ca({im:r,re:t})};Ca.prototype.div=function(e){if(k.isNumber(e)&&!k.isComplex(e)){if(!(e instanceof k)){e=k(e)}var t=this.__re__.div(e);var r=this.__im__.div(e);return Ca({re:t,im:r})}else if(!k.isComplex(e)){throw new Error("[LComplex::div] Invalid value")}if(this.cmp(e)===0){var n=this.coerce(e),i=j(n,2),f=i[0],u=i[1];var l=f.__im__.div(u.__im__);return l.coerce(u.__re__)[0]}var h=this.coerce(e),a=j(h,2),p=a[0],o=a[1];var s=o.factor();var _=o.conjugate();var c=p.mul(_);if(!k.isComplex(c)){return c.div(s)}var d=c.__re__.op("/",s);var v=c.__im__.op("/",s);return Ca({re:d,im:v})};Ca.prototype.sub=function(e){return this.complex_op("sub",e,function(e,t,r,n){return{re:e.sub(t),im:r.sub(n)}})};Ca.prototype.mul=function(e){return this.complex_op("mul",e,function(e,t,r,n){var i={re:e.mul(t).sub(r.mul(n)),im:e.mul(n).add(t.mul(r))};return i})};Ca.prototype.complex_op=function(e,t,i){var u=this;var r=function e(t,r){var n=i(u.__re__,t,u.__im__,r);if("im"in n&&"re"in n){if(n.im.cmp(0)===0){return n.re}return Ca(n,true)}return n};if(typeof t==="undefined"){return r()}if(k.isNumber(t)&&!k.isComplex(t)){if(!(t instanceof k)){t=k(t)}var n=t.asType(0);t={__im__:n,__re__:t}}else if(!k.isComplex(t)){throw new Error("[LComplex::".concat(e,"] Invalid value"))}var a=t.__re__ instanceof k?t.__re__:this.__re__.asType(t.__re__);var o=t.__im__ instanceof k?t.__im__:this.__im__.asType(t.__im__);return r(a,o)};Ca._op={"+":"add","-":"sub","*":"mul","/":"div"};Ca.prototype._op=function(e,t){var r=Ca._op[e];return this[r](t)};Ca.prototype.cmp=function(e){var t=this.coerce(e),r=j(t,2),n=r[0],i=r[1];var u=n.__re__.coerce(i.__re__),a=j(u,2),o=a[0],f=a[1];var s=o.cmp(f);if(s!==0){return s}else{var l=n.__im__.coerce(i.__im__),c=j(l,2),h=c[0],p=c[1];return h.cmp(p)}};Ca.prototype.valueOf=function(){return[this.__re__,this.__im__].map(function(e){return e.valueOf()})};Ca.prototype.toString=function(){var e;if(this.__re__.cmp(0)!==0){e=[nu(this.__re__)]}else{e=[]}var t=this.__im__.valueOf();var r=[Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY].includes(t);var n=nu(this.__im__);if(!r&&!Number.isNaN(t)){var i=this.__im__.cmp(0);if(i<0||i===0&&this.__im__._minus){e.push("-")}else{e.push("+")}n=n.replace(/^-/,"")}e.push(n);e.push("i");return e.join("")};function ka(e){if(typeof this!=="undefined"&&!(this instanceof ka)||typeof this==="undefined"){return new ka(e)}if(!k.isNumber(e)){throw new Error("Invalid constructor call for LFloat")}if(e instanceof k){return ka(e.valueOf())}if(typeof e==="number"){if(Object.is(e,-0)){Object.defineProperty(this,"_minus",{value:true})}this.constant(e,"float")}}ka.prototype=Object.create(k.prototype);ka.prototype.constructor=ka;ka.prototype.toString=function(){if(this.__value__===Number.NEGATIVE_INFINITY){return"-inf.0"}if(this.__value__===Number.POSITIVE_INFINITY){return"+inf.0"}if(Number.isNaN(this.__value__)){return"+nan.0"}var e=this.__value__.toString();if(!k.isFloat(this.__value__)&&!e.match(/e/i)){var t=e+".0";return this._minus?"-"+t:t}return e.replace(/^([0-9]+)e/,"$1.0e")};ka.prototype._op=function(e,t){if(t instanceof k){t=t.__value__}var r=k._ops[e];if(e==="/"&&this.__value__===0&&t===0){return NaN}return ka(r(this.__value__,t))};ka.prototype.toRational=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){return Oa(this.__value__.valueOf())}return Sa(e.valueOf())(this.__value__.valueOf())};ka.prototype.sqrt=function(){var e=this.valueOf();if(this.cmp(0)<0){var t=ka(Math.sqrt(-e));return Ca({re:0,im:t})}return ka(Math.sqrt(e))};ka.prototype.abs=function(){var e=this.valueOf();if(e<0){e=-e}return ka(e)};var Oa=Sa(1e-10);function Sa(n){return function(e){var t=function e(n,t,r){var i=function e(t,r){return r0){i=ja(n,r)}else if(n.cmp(r)<=0){i=r}else if(r.cmp(0)>0){i=ja(r,n)}else if(t.cmp(0)<0){i=k(ja(n.sub(),r.sub())).sub()}else{i=k(0)}if(k.isFloat(t)||k.isFloat(e)){return ka(i)}return i}function ja(e,t){var r=k(e).floor();var n=k(t).floor();if(e.cmp(r)<1){return r}else if(r.cmp(n)===0){var i=k(1).div(t.sub(n));var u=k(1).div(e.sub(r));return r.add(k(1).div(ja(i,u)))}else{return r.add(k(1))}}function Ia(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(typeof this!=="undefined"&&!(this instanceof Ia)||typeof this==="undefined"){return new Ia(e,t)}if(!k.isRational(e)){throw new Error("Invalid constructor call for LRational")}var r,n;if(e instanceof Ia){r=k(e.__num__);n=k(e.__denom__)}else{r=k(e.num);n=k(e.denom)}if(!t&&n.cmp(0)!==0){var i=r.op("%",n).cmp(0)===0;if(i){return k(r.div(n))}}this.constant(r,n)}Ia.prototype=Object.create(k.prototype);Ia.prototype.constructor=Ia;Ia.prototype.constant=function(e,t){Object.defineProperty(this,"__num__",{value:e,enumerable:true});Object.defineProperty(this,"__denom__",{value:t,enumerable:true});Object.defineProperty(this,"__type__",{value:"rational",enumerable:true})};Ia.prototype.serialize=function(){return{num:this.__num__,denom:this.__denom__}};Ia.prototype.pow=function(e){var t=e.cmp(0);if(t===0){return k(1)}if(t===-1){e=e.sub();var r=this.__denom__.pow(e);var n=this.__num__.pow(e);return Ia({num:r,denom:n})}var i=this;e=e.valueOf();while(e>1){i=i.mul(this);e--}return i};Ia.prototype.sqrt=function(){var e=this.__num__.sqrt();var t=this.__denom__.sqrt();if(e instanceof ka||t instanceof ka){return e.div(t)}return Ia({num:e,denom:t})};Ia.prototype.abs=function(){var e=this.__num__;var t=this.__denom__;if(e.cmp(0)===-1){e=e.sub()}if(t.cmp(0)!==1){t=t.sub()}return Ia({num:e,denom:t})};Ia.prototype.cmp=function(e){return k(this.valueOf(),true).cmp(e)};Ia.prototype.toString=function(){var e=this.__num__.gcd(this.__denom__);var t,r;if(e.cmp(1)!==0){t=this.__num__.div(e);if(t instanceof Ia){t=k(t.valueOf(true))}r=this.__denom__.div(e);if(r instanceof Ia){r=k(r.valueOf(true))}}else{t=this.__num__;r=this.__denom__}var n=this.cmp(0)<0;if(n){if(t.abs().cmp(r.abs())===0){return t.toString()}}else if(t.cmp(r)===0){return t.toString()}return t.toString()+"/"+r.toString()};Ia.prototype.valueOf=function(e){if(this.__denom__.cmp(0)===0){if(this.__num__.cmp(0)<0){return Number.NEGATIVE_INFINITY}return Number.POSITIVE_INFINITY}if(e){return k._ops["/"](this.__num__.value,this.__denom__.value)}return ka(this.__num__.valueOf()).div(this.__denom__.valueOf())};Ia.prototype.mul=function(e){if(!(e instanceof k)){e=k(e)}if(k.isRational(e)){var t=this.__num__.mul(e.__num__);var r=this.__denom__.mul(e.__denom__);return Ia({num:t,denom:r})}var n=k.coerce(this,e),i=j(n,2),u=i[0],a=i[1];return u.mul(a)};Ia.prototype.div=function(e){if(!(e instanceof k)){e=k(e)}if(k.isRational(e)){var t=this.__num__.mul(e.__denom__);var r=this.__denom__.mul(e.__num__);return Ia({num:t,denom:r})}var n=k.coerce(this,e),i=j(n,2),u=i[0],a=i[1];var o=u.div(a);return o};Ia.prototype._op=function(e,t){return this[Aa[e]](t)};Ia.prototype.sub=function(e){if(typeof e==="undefined"){return this.mul(-1)}if(!(e instanceof k)){e=k(e)}if(k.isRational(e)){var t=e.__num__.sub();var r=e.__denom__;return this.add(Ia({num:t,denom:r}))}if(!(e instanceof k)){e=k(e).sub()}else{e=e.sub()}var n=k.coerce(this,e),i=j(n,2),u=i[0],a=i[1];return u.add(a)};Ia.prototype.add=function(e){if(!(e instanceof k)){e=k(e)}if(k.isRational(e)){var t=this.__denom__;var r=e.__denom__;var n=this.__num__;var i=e.__num__;var u,a;if(t!==r){a=r.mul(n).add(i.mul(t));u=t.mul(r)}else{a=n.add(i);u=t}return Ia({num:a,denom:u})}if(k.isFloat(e)){return ka(this.valueOf()).add(e)}var o=k.coerce(this,e),s=j(o,2),c=s[0],f=s[1];return c.add(f)};function Pa(e,t){if(typeof this!=="undefined"&&!(this instanceof Pa)||typeof this==="undefined"){return new Pa(e,t)}if(e instanceof Pa){return Pa(e.__value__,e._native)}if(!k.isBigInteger(e)){throw new Error("Invalid constructor call for LBigInteger")}this.constant(e,"bigint");Object.defineProperty(this,"_native",{value:t})}Pa.prototype=Object.create(k.prototype);Pa.prototype.constructor=Pa;Pa.bn_op={"+":"iadd","-":"isub","*":"imul","/":"idiv","%":"imod","|":"ior","&":"iand","~":"inot","<<":"ishrn",">>":"ishln"};Pa.prototype.serialize=function(){return this.__value__.toString()};Pa.prototype._op=function(e,t){if(typeof t==="undefined"){if(k.isBN(this.__value__)){e=Pa.bn_op[e];return Pa(this.__value__.clone()[e](),false)}return Pa(k._ops[e](this.__value__),true)}if(k.isBN(this.__value__)&&k.isBN(t.__value__)){e=Pa.bn_op[e];return Pa(this.__value__.clone()[e](t),false)}var r=k._ops[e](this.__value__,t.__value__);if(e==="/"){var n=this.op("%",t).cmp(0)===0;if(n){return k(r)}return Ia({num:this,denom:t})}return Pa(r,true)};Pa.prototype.sqrt=function(){var e;var t=this.cmp(0)<0;if(k.isNative(this.__value__)){e=k(Math.sqrt(t?-this.valueOf():this.valueOf()))}else if(k.isBN(this.__value__)){e=t?this.__value__.neg().sqrt():this.__value__.sqrt()}if(t){return Ca({re:0,im:e})}return e};k.NaN=k(NaN);function Na(e){var n=this;if(typeof this!=="undefined"&&!(this instanceof Na)||typeof this==="undefined"){return new Na(e)}Eo("InputPort",e,"function");_i(this,"__type__",Ga);var i;Object.defineProperty(this,"__parser__",{enumerable:true,get:function e(){return i},set:function e(t){Eo("InputPort::__parser__",t,"parser");i=t}});this._read=e;this._with_parser=this._with_init_parser.bind(this,O(z.mark(function e(){var r;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:if(n.char_ready()){t.next=5;break}t.next=3;return n._read();case 3:r=t.sent;i=new oi(r,{env:n});case 5:return t.abrupt("return",n.__parser__);case 6:case"end":return t.stop()}}},e)})));this.char_ready=function(){return!!this.__parser__&&this.__parser__.__lexer__.peek()!==Wa};this._make_defaults()}Na.prototype._make_defaults=function(){this.read=this._with_parser(function(e){return e.read_object()});this.read_line=this._with_parser(function(e){return e.__lexer__.read_line()});this.read_char=this._with_parser(function(e){return e.__lexer__.read_char()});this.read_string=this._with_parser(function(e,t){if(!k.isInteger(t)){var r=k.getType(t);bo("read-string",r,"integer")}return e.__lexer__.read_string(t.valueOf())});this.peek_char=this._with_parser(function(e){return e.__lexer__.peek_char()})};Na.prototype._with_init_parser=function(o,s){var c=this;return O(z.mark(function e(){var r,n,i,u,a=arguments;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:t.next=2;return o.call(c);case 2:r=t.sent;for(n=a.length,i=new Array(n),u=0;u"};function Ra(e){if(typeof this!=="undefined"&&!(this instanceof Ra)||typeof this==="undefined"){return new Ra(e)}Eo("OutputPort",e,"function");_i(this,"__type__",Ga);this.write=e}Ra.prototype.is_open=function(){return this._closed!==true};Ra.prototype.close=function(){Object.defineProperty(this,"_closed",{get:function e(){return true},set:function e(){},configurable:false,enumerable:false});this.write=function(){throw new Error("output-port: port is closed")}};Ra.prototype.flush=function(){};Ra.prototype.toString=function(){return"#"};var Ta=function(e){u(n,e);var r=jr(n);function n(e){var t;A(this,n);t=r.call(this,function(){var e;return(e=t)._write.apply(e,arguments)});Eo("BufferedOutputPort",e,"function");_i(i(t),"_fn",e,{hidden:true});_i(i(t),"_buffer",[],{hidden:true});return t}x(n,[{key:"flush",value:function e(){if(this._buffer.length){this._fn(this._buffer.join(""));this._buffer.length=0}}},{key:"_write",value:function e(){var t=this;for(var r=arguments.length,n=new Array(r),i=0;i"};La.prototype.valueOf=function(){return this.__buffer__.map(function(e){return e.valueOf()}).join("")};function Ua(e,t){var r=this;if(typeof this!=="undefined"&&!(this instanceof Ua)||typeof this==="undefined"){return new Ua(e,t)}Eo("OutputFilePort",e,"string");_i(this,"__filename__",e);_i(this,"_fd",t.valueOf(),{hidden:true});_i(this,"__type__",Ga);this.write=function(e){if(!_a.isString(e)){e=nu(e)}else{e=e.valueOf()}r.fs().write(r._fd,e,function(e){if(e){throw e}})}}Ua.prototype=Object.create(Ra.prototype);Ua.prototype.constructor=Ua;Ua.prototype.fs=function(){if(!this._fs){this._fs=this.internal("fs")}return this._fs};Ua.prototype.internal=function(e){return fo.get("**internal-env**").get(e)};Ua.prototype.close=function(){var n=this;return new Promise(function(t,r){n.fs().close(n._fd,function(e){if(e){r(e)}else{_i(n,"_fd",null,{hidden:true});Ra.prototype.close.call(n);t()}})})};Ua.prototype.toString=function(){return"#")};function qa(e,t){var r=this;if(typeof this!=="undefined"&&!(this instanceof qa)||typeof this==="undefined"){return new qa(e)}Eo("InputStringPort",e,"string");t=t||co;e=e.valueOf();this._with_parser=this._with_init_parser.bind(this,function(){if(!r.__parser__){r.__parser__=new oi(e,{env:t})}return r.__parser__});_i(this,"__type__",Ga);this._make_defaults()}qa.prototype.char_ready=function(){return true};qa.prototype=Object.create(Na.prototype);qa.prototype.constructor=qa;qa.prototype.toString=function(){return"#"};function Ma(e){if(typeof this!=="undefined"&&!(this instanceof Ma)||typeof this==="undefined"){return new Ma(e)}Eo("InputByteVectorPort",e,"uint8array");_i(this,"__vector__",e);_i(this,"__type__",Ja);var r=0;Object.defineProperty(this,"__index__",{enumerable:true,get:function e(){return r},set:function e(t){Eo("InputByteVectorPort::__index__",t,"number");if(t instanceof k){t=t.valueOf()}if(typeof t==="bigint"){t=Number(t)}if(Math.floor(t)!==t){throw new Error("InputByteVectorPort::__index__ value is "+"not integer")}r=t}})}Ma.prototype=Object.create(Na.prototype);Ma.prototype.constructor=Ma;Ma.prototype.toString=function(){return"#"};Ma.prototype.close=function(){var t=this;_i(this,"__vector__",U);["read_u8","close","peek_u8","read_u8_vector"].forEach(function(e){t[e]=function(){throw new Error("Input-binary-port: port is closed")}});this.char_ready=function(){return false}};Ma.prototype.u8_ready=function(){return true};Ma.prototype.peek_u8=function(){if(this.__index__>=this.__vector__.length){return Wa}return this.__vector__[this.__index__]};Ma.prototype.skip=function(){if(this.__index__<=this.__vector__.length){++this.__index__}};Ma.prototype.read_u8=function(){var e=this.peek_u8();this.skip();return e};Ma.prototype.read_u8_vector=function(e){if(typeof e==="undefined"){e=this.__vector__.length}else if(e>this.__index__+this.__vector__.length){e=this.__index__+this.__vector__.length}if(this.peek_u8()===Wa){return Wa}return this.__vector__.slice(this.__index__,e)};function Ya(){if(typeof this!=="undefined"&&!(this instanceof Ya)||typeof this==="undefined"){return new Ya}_i(this,"__type__",Ja);_i(this,"_buffer",[],{hidden:true});this.write=function(e){Eo("write",e,["number","uint8array"]);if(k.isNumber(e)){this._buffer.push(e.valueOf())}else{var t;(t=this._buffer).push.apply(t,M(Array.from(e)))}};Object.defineProperty(this,"__buffer__",{enumerable:true,get:function e(){return Uint8Array.from(this._buffer)}})}Ya.prototype=Object.create(Ra.prototype);Ya.prototype.constructor=Ya;Ya.prototype.close=function(){Ra.prototype.close.call(this);_i(this,"_buffer",null,{hidden:true})};Ya.prototype._close_guard=function(){if(this._closed){throw new Error("output-port: binary port is closed")}};Ya.prototype.write_u8=function(e){Eo("OutputByteVectorPort::write_u8",e,"number");this.write(e)};Ya.prototype.write_u8_vector=function(e){Eo("OutputByteVectorPort::write_u8_vector",e,"uint8array");this.write(e)};Ya.prototype.toString=function(){return"#"};Ya.prototype.valueOf=function(){return this.__buffer__};function $a(e,t){if(typeof this!=="undefined"&&!(this instanceof $a)||typeof this==="undefined"){return new $a(e,t)}qa.call(this,e);Eo("InputFilePort",t,"string");_i(this,"__filename__",t)}$a.prototype=Object.create(qa.prototype);$a.prototype.constructor=$a;$a.prototype.toString=function(){return"#")};function za(e,t){if(typeof this!=="undefined"&&!(this instanceof za)||typeof this==="undefined"){return new za(e,t)}Ma.call(this,e);Eo("InputBinaryFilePort",t,"string");_i(this,"__filename__",t)}za.prototype=Object.create(Ma.prototype);za.prototype.constructor=za;za.prototype.toString=function(){return"#")};function Va(e,t){if(typeof this!=="undefined"&&!(this instanceof Va)||typeof this==="undefined"){return new Va(e,t)}Eo("OutputBinaryFilePort",e,"string");_i(this,"__filename__",e);_i(this,"_fd",t.valueOf(),{hidden:true});_i(this,"__type__",Ja);var u,r;this.write=function(e){var n=this;Eo("write",e,["number","uint8array"]);var i;if(!u){u=this.internal("fs")}if(!r){r=this.internal("Buffer")}if(k.isNumber(e)){i=r.from([e.valueOf()])}else{i=r.from(Array.from(e))}return new Promise(function(t,r){u.write(n._fd,i,function(e){if(e){r(e)}else{t()}})})}}Va.prototype=Object.create(Ua.prototype);Va.prototype.constructor=Va;Va.prototype.write_u8=function(e){Eo("OutputByteVectorPort::write_u8",e,"number");this.write(e)};Va.prototype.write_u8_vector=function(e){Eo("OutputByteVectorPort::write_u8_vector",e,"uint8array");this.write(e)};var Ja=Symbol["for"]("binary");var Ga=Symbol["for"]("text");var Wa=new Ha;function Ha(){}Ha.prototype.toString=function(){return"#"};function Qa(e){var c=this;var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=t.stderr,n=t.stdin,i=t.stdout,u=t.command_line,a=u===void 0?null:u,o=S(t,Br);if(typeof this!=="undefined"&&!(this instanceof Qa)||typeof this==="undefined"){return new Qa(e,Lr({stdin:n,stdout:i,stderr:r,command_line:a},o))}if(typeof e==="undefined"){e="anonymous"}this.__env__=fo.inherit(e,o);this.__env__.set("parent.frame",g("parent.frame",function(){return c.__env__},co.__env__["parent.frame"].__doc__));var f="**interaction-environment-defaults**";this.set(f,Ki(o).concat(f));var s=ao.inherit("internal-".concat(e));if(Ru(n)){s.set("stdin",n)}if(Ru(r)){s.set("stderr",r)}if(Ru(i)){s.set("stdout",i)}s.set("command-line",a);lo(this.__env__,s)}Qa.prototype.exec=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;Eo("Interpreter::exec",e,["string","array"],1);Eo("Interpreter::exec",t,"boolean",2);co.set("**interaction-environment**",this.__env__);if(r===null){r=this.__env__}return qo(e,r,t?r:false)};Qa.prototype.get=function(e){var t=this.__env__.get(e);if(Du(t)){return t.bind(this.__env__)}return t};Qa.prototype.set=function(e,t){return this.__env__.set(e,t)};Qa.prototype.constant=function(e,t){return this.__env__.constant(e,t)};function Za(e,t){this.name="LipsError";this.message=e;this.args=t;this.stack=(new Error).stack}Za.prototype=new Error;Za.prototype.constructor=Za;function Ka(e,t,r){if(arguments.length===1){if(_(arguments[0])==="object"){e=arguments[0];t=null}else if(typeof arguments[0]==="string"){e={};t=null;r=arguments[0]}}this.__docs__=new Map;this.__env__=e;this.__parent__=t;this.__name__=r||"anonymous"}Ka.prototype.list=function(){return Ki(this.__env__)};Ka.prototype.fs=function(){return this.get("**fs**")};Ka.prototype.unset=function(e){if(e instanceof L){e=e.valueOf()}if(e instanceof _a){e=e.valueOf()}delete this.__env__[e]};Ka.prototype.inherit=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(_(e)==="object"){t=e}if(!e||_(e)==="object"){e="child of "+(this.__name__||"unknown")}return new Ka(t||{},this,e)};Ka.prototype.doc=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;if(e instanceof L){e=e.__name__}if(e instanceof _a){e=e.valueOf()}if(t){if(!r){t=yi(t)}this.__docs__.set(e,t);return this}if(this.__docs__.has(e)){return this.__docs__.get(e)}if(this.__parent__){return this.__parent__.doc(e)}};Ka.prototype.newFrame=function(e,t){var n=this.inherit("__frame__");n.set("parent.frame",g("parent.frame",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;e=e.valueOf();var t=n.__parent__;if(!(t instanceof Ka)){return U}if(e<=0){return t}var r=t.get("parent.frame");return r(e-1)},co.__env__["parent.frame"].__doc__));t.callee=e;n.set("arguments",t);return n};Ka.prototype._lookup=function(e){if(e instanceof L){e=e.__name__}if(e instanceof _a){e=e.valueOf()}if(this.__env__.hasOwnProperty(e)){return Xa(this.__env__[e])}if(this.__parent__){return this.__parent__._lookup(e)}};Ka.prototype.toString=function(){return"#"};Ka.prototype.clone=function(){var t=this;var r={};Object.keys(this.__env__).forEach(function(e){r[e]=t.__env__[e]});return new Ka(r,this.__parent__,this.__name__)};Ka.prototype.merge=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"merge";Eo("Environment::merge",e,"environment");return this.inherit(t,e.__env__)};function Xa(e){if(typeof this!=="undefined"&&!(this instanceof Xa)||typeof this==="undefined"){return new Xa(e)}this.value=e}Xa.isUndefined=function(e){return e instanceof Xa&&typeof e.value==="undefined"};Xa.prototype.valueOf=function(){return this.value};function eo(e){if(e.length){if(e.length===1){return e[0]}}if(typeof this!=="undefined"&&!(this instanceof eo)||typeof this==="undefined"){return new eo(e)}this.__values__=e}eo.prototype.toString=function(){return this.__values__.map(function(e){return nu(e)}).join("\n")};eo.prototype.valueOf=function(){return this.__values__};Ka.prototype.get=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};Eo("Environment::get",e,["symbol","string"]);var r=t.throwError,c=r===void 0?true:r;var n=e;if(n instanceof L||n instanceof _a){n=n.valueOf()}var i=this._lookup(n);if(i instanceof Xa){if(Xa.isUndefined(i)){return undefined}return Su(i.valueOf())}var u;if(e instanceof L&&e[L.object]){u=e[L.object]}else if(typeof n==="string"){u=n.split(".").filter(Boolean)}if(u&&u.length>0){var f=u,a=b(f),o=a[0],s=a.slice(1);i=this._lookup(o);if(s.length){try{if(i instanceof Xa){i=i.valueOf()}else{i=no(Mr,o);if(Du(i)){i=Bu(i)}}if(typeof i!=="undefined"){return no.apply(void 0,[i].concat(M(s)))}}catch(e){throw e}}else if(i instanceof Xa){return Su(i.valueOf())}i=no(Mr,n)}if(typeof i!=="undefined"){return i}if(c){throw new Error("Unbound variable `"+n.toString()+"'")}};Ka.prototype.set=function(e,t){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;Eo("Environment::set",e,["string","symbol"]);if(k.isNumber(t)){t=k(t)}if(e instanceof L){e=e.__name__}if(e instanceof _a){e=e.valueOf()}this.__env__[e]=t;if(r){this.doc(e,r,true)}return this};Ka.prototype.constant=function(t,e){var r=this;if(this.__env__.hasOwnProperty(t)){throw new Error("Environment::constant: ".concat(t," already exists"))}if(arguments.length===1&&zi(arguments[0])){var n=arguments[0];Object.keys(n).forEach(function(e){r.constant(t,n[e])})}else{Object.defineProperty(this.__env__,t,{value:e,enumerable:true})}return this};Ka.prototype.has=function(e){return this.__env__.hasOwnProperty(e)};Ka.prototype.ref=function(e){var t=this;while(true){if(!t){break}if(t.has(e)){return t}t=t.__parent__}};Ka.prototype.parents=function(){var e=this;var t=[];while(e){t.unshift(e);e=e.__parent__}return t};function to(e){if(Fu(e)){return e.then(to)}if(e instanceof q||e instanceof L){e[qu]=true}return e}var ro=ci(zn('(lambda ()\n "[native code]"\n (throw "Invalid Invocation"))'))[0];var no=g("get",function c(e){var t;for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=io(this,"stdin")}Do("peek-char",e,"input-port");return e.peek_char()},"(peek-char port)\n\n This function reads and returns a character from the string\n port, or, if there is no more data in the string port, it\n returns an EOF."),"read-line":g("read-line",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=io(this,"stdin")}Do("read-line",e,"input-port");return e.read_line()},"(read-char port)\n\n This function reads and returns the next line from the input\n port."),"read-char":g("read-char",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=io(this,"stdin")}Do("read-char",e,"input-port");return e.read_char()},"(read-char port)\n\n This function reads and returns the next character from the\n input port."),read:g("read",function(){var e=O(z.mark(function e(){var r,n,i,u,a,o,s,c,f=arguments;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:r=f.length>0&&f[0]!==undefined?f[0]:null;if(!_a.isString(r)){t.next=30;break}n=false;i=false;t.prev=4;a=Ur(ci(r,this));case 6:t.next=8;return a.next();case 8:if(!(n=!(o=t.sent).done)){t.next=14;break}s=o.value;return t.abrupt("return",s);case 11:n=false;t.next=6;break;case 14:t.next=20;break;case 16:t.prev=16;t.t0=t["catch"](4);i=true;u=t.t0;case 20:t.prev=20;t.prev=21;if(!(n&&a["return"]!=null)){t.next=25;break}t.next=25;return a["return"]();case 25:t.prev=25;if(!i){t.next=28;break}throw u;case 28:return t.finish(25);case 29:return t.finish(20);case 30:if(r===null){c=io(this,"stdin")}else{c=r}Do("read",c,"input-port");return t.abrupt("return",c.read.call(this));case 33:case"end":return t.stop()}}},e,this,[[4,16,20,30],[21,,25,29]])}));function t(){return e.apply(this,arguments)}return t}(),"(read [string])\n\n This function, if used with a string, will parse it and\n return the LIPS code, if there is any. If called without an\n input, it will read a string from standard input (using\n the browser's prompt or a user defined input method) and\n calls itself with that string. This function can be used\n together with `eval` to evaluate code from a string."),pprint:g("pprint",function e(t){if(t instanceof q){t=new ys.Formatter(t.toString(true))["break"]().format();co.get("display").call(co,t)}else{co.get("write").call(co,t)}co.get("newline").call(co)},"(pprint expression)\n\n This function will pretty print its input. If it is called\n with a non-list, it will just call the print function on its\n input."),print:g("print",function e(){var t=co.get("display");var r=co.get("newline");for(var n=arguments.length,i=new Array(n),u=0;u1?r-1:0),i=1;in.length){throw new Error("Not enough arguments")}var o=0;var s=co.get("repr");t=t.replace(u,function(e){var t=e[1];if(t==="~"){return"~"}else if(t==="%"){return"\n"}else{var r=n[o++];if(t==="a"){return s(r)}else{return s(r,true)}}});a=t.match(/~([\S])/);if(a){throw new Error("format: Unrecognized escape seqence ".concat(a[1]))}return t},"(format string n1 n2 ...)\n\n This function accepts a string template and replaces any\n escape sequences in its inputs:\n\n * ~a value as if printed with `display`\n * ~s value as if printed with `write`\n * ~% newline character\n * ~~ literal tilde '~'\n\n If there are missing inputs or other escape characters it\n will error."),display:g("display",function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(r===null){r=io(this,"stdout")}else{Eo("display",r,"output-port")}var n=co.get("repr")(t);r.write.call(co,n)},"(display string [port])\n\n This function outputs the string to the standard output or\n the port if given."),"display-error":g("display-error",function e(){var t=io(this,"stderr");var r=co.get("repr");for(var n=arguments.length,i=new Array(n),u=0;u1&&arguments[1]!==undefined?arguments[1]:{},r=t.dynamic_scope,n=t.error;if(r){r=this}var i=this;var u;var a=Lo(e.cdr.car,{env:this,dynamic_scope:r,error:n});a=So(a);function o(t,r,n){if(Fu(t)){return t.then(function(e){return o(t,e,n)})}if(Fu(r)){return r.then(function(e){return o(t,e,n)})}if(Fu(n)){return n.then(function(e){return o(t,r,e)})}i.get("set-obj!").call(i,t,r,n);return n}if(e.car instanceof q&&L.is(e.car.car,".")){var f=e.car.cdr.car;var l=e.car.cdr.cdr.car;var h=Lo(f,{env:this,dynamic_scope:r,error:n});var p=Lo(l,{env:this,dynamic_scope:r,error:n});return o(h,p,a)}if(!(e.car instanceof L)){throw new Error("set! first argument need to be a symbol or "+"dot accessor that evaluate to object.")}var s=e.car.valueOf();u=this.ref(e.car.__name__);return li(a,function(e){if(!u){var t=s.split(".");if(t.length>1){var r=t.pop();var n=t.join(".");var i=c.get(n,{throwError:false});if(i){o(i,r,e);return}}throw new Error("Unbound variable `"+s+"'")}u.set(s,e)})}),"(set! name value)\n\n Macro that can be used to set the value of the variable (mutate)\n it search the scope chain until it finds first non emtpy slot and set it."),"unset!":g(new hu("set!",function(e){if(!(e.car instanceof L)){throw new Error("unset! first argument need to be a symbol or "+"dot accessor that evaluate to object.")}var t=e.car;var r=this.ref(t);if(r){delete r.__env__[t.__name__]}}),"(unset! name)\n\n Function delete specified name from environment."),"set-car!":g("set-car!",function(e,t){Eo("set-car!",e,"pair");e.car=t},"(set-car! obj value)\n\n Function that set car (head) of the list/pair to specified value.\n It can destroy the list. Old value is lost."),"set-cdr!":g("set-cdr!",function(e,t){Eo("set-cdr!",e,"pair");e.cdr=t},"(set-cdr! obj value)\n\n Function that set cdr (tail) of the list/pair to specified value.\n It can destroy the list. Old value is lost."),"empty?":g("empty?",function(e){return typeof e==="undefined"||e===U},"(empty? object)\n\n Function return true if value is undfined empty list."),gensym:g("gensym",Hn,"(gensym)\n\n Function generate unique symbol, to use with macros as meta name."),load:g("load",function e(o,t){Eo("load",o,"string");var s=this;if(s.__name__==="__frame__"){s=s.__parent__}if(!(t instanceof Ka)){if(s===co){t=s}else{t=this.get("**interaction-environment**")}}var c="**module-path**";var f=co.get(c,{throwError:false});o=o.valueOf();if(!o.match(/.[^.]+$/)){o+=".scm"}var r=o.match(/\.xcb$/);function l(e){if(r){e=ps(e)}else{if(Oo(e)==="buffer"){e=e.toString()}e=e.replace(/^#!.*/,"");if(e.match(/^\{/)){e=as(e)}}return qo(e,t)}function n(e){return Mr.fetch(e).then(function(e){return r?e.arrayBuffer():e.text()}).then(function(e){if(r){e=new Uint8Array(e)}return e})}if(mo()){return new Promise(function(){var r=O(z.mark(function e(r,n){var i,u,a;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:i=Jr("path");if(!f){t.next=6;break}f=f.valueOf();o=i.join(f,o);t.next=12;break;case 6:u=s.get("command-line",{throwError:false});if(!u){t.next=11;break}t.next=10;return u();case 10:a=t.sent;case 11:if(a&&a!==U){process.cwd();o=i.join(i.dirname(a.car.valueOf()),o)}case 12:co.set(c,i.dirname(o));Jr("fs").readFile(o,function(e,t){if(e){n(e);co.set(c,f)}else{try{l(t).then(function(){r();co.set(c,f)})["catch"](n)}catch(e){n(e)}}});case 14:case"end":return t.stop()}}},e)}));return function(e,t){return r.apply(this,arguments)}}())}if(f){f=f.valueOf();o=f+"/"+o.replace(/^\.?\/?/,"")}return n(o).then(function(e){co.set(c,o.replace(/\/[^/]*$/,""));return l(e)}).then(function(){})["finally"](function(){co.set(c,f)})},"(load filename)\n (load filename environment)\n\n Function fetch the file and evaluate its content as LIPS code,\n If second argument is provided and it's environment the evaluation\n will happen in that environment."),do:g(new hu("do",function(){var r=O(z.mark(function e(r,h){var n,i,u,o,s,a,c,f,l,p,_;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:n=h.dynamic_scope,i=h.error;u=this;if(n){n=u}o=u.inherit("do");s=r.car;a=r.cdr.car;c=r.cdr.cdr;if(c!==U){c=new q(L("begin"),c)}f={env:u,dynamic_scope:n,error:i};l=s;case 10:if(!(l!==U)){t.next=21;break}p=l.car;t.t0=o;t.t1=p.car;t.next=16;return Lo(p.cdr.car,f);case 16:t.t2=t.sent;t.t0.set.call(t.t0,t.t1,t.t2);l=l.cdr;t.next=10;break;case 21:f={env:o,dynamic_scope:n,error:i};_=z.mark(function e(){var r,n,i,u,a;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:if(!(c!==U)){t.next=3;break}t.next=3;return ys.evaluate(c,f);case 3:r=s;n={};case 5:if(!(r!==U)){t.next=15;break}i=r.car;if(!(i.cdr.cdr!==U)){t.next=12;break}t.next=10;return Lo(i.cdr.cdr.car,f);case 10:u=t.sent;n[i.car.valueOf()]=u;case 12:r=r.cdr;t.next=5;break;case 15:a=Object.getOwnPropertySymbols(n);Object.keys(n).concat(a).forEach(function(e){o.set(e,n[e])});case 17:case"end":return t.stop()}}},e)});case 23:t.next=25;return Lo(a.car,f);case 25:t.t3=t.sent;if(!(t.t3===false)){t.next=30;break}return t.delegateYield(_(),"t4",28);case 28:t.next=23;break;case 30:if(!(a.cdr!==U)){t.next=34;break}t.next=33;return Lo(a.cdr.car,f);case 33:return t.abrupt("return",t.sent);case 34:case"end":return t.stop()}}},e,this)}));return function(e,t){return r.apply(this,arguments)}}()),"(do (( )) (test expression) . body)\n\n Iteration macro that evaluate the expression body in scope of the variables.\n On each loop it increase the variables according to next expression and runs\n test to check if the loop should continue. If test is single called, the macro\n will not return anything. If the test is pair of expression and value the\n macro will return that value after finish."),if:g(new hu("if",function(r,e){var n=e.dynamic_scope,i=e.error;if(n){n=this}var u=this;var t=function e(t){if(t===false){return Lo(r.cdr.cdr.car,{env:u,dynamic_scope:n,error:i})}else{return Lo(r.cdr.car,{env:u,dynamic_scope:n,error:i})}};if(r===U){throw new Error("too few expressions for `if`")}var a=Lo(r.car,{env:u,dynamic_scope:n,error:i});return li(a,t)}),"(if cond true-expr false-expr)\n\n Macro evaluate condition expression and if the value is true, it\n evaluate and return true expression if not it evaluate and return\n false expression"),"let-env":new hu("let-env",function(t){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var r=e.dynamic_scope,n=e.error;Eo("let-env",t,"pair");var i=Lo(t.car,{env:this,dynamic_scope:r,error:n});return li(i,function(e){Eo("let-env",e,"environment");return Lo(q(L("begin"),t.cdr),{env:e,dynamic_scope:r,error:n})})},"(let-env env . body)\n\n Special macro that evaluate body in context of given environment\n object."),letrec:g(ta(Symbol["for"]("letrec")),"(letrec ((a value-a) (b value-b)) body)\n\n Macro that creates new environment, then evaluate and assign values to\n names and then evaluate the body in context of that environment.\n Values are evaluated sequentialy and next value can access to\n previous values/names."),"letrec*":g(ta(Symbol["for"]("letrec")),"(letrec* ((a value-a) (b value-b)) body)\n\n Same as letrec but the order of execution of the binding is guaranteed,\n so use can use recursive code as well as reference previous binding.\n In LIPS both letrec and letrec* behave the same."),"let*":g(ta(Symbol["for"]("let*")),"(let* ((a value-a) (b value-b)) body)\n\n Macro similar to `let` but next argument get environment\n from previous let variable, so they you can define one variable,\n and use in next argument."),let:g(ta(Symbol["for"]("let")),"(let ((a value-a) (b value-b)) body)\n\n Macro that creates new environment, then evaluate and assign values to\n names and then evaluate the body in context of that environment.\n Values are evaluated sequentialy but you can't access\n previous values/names when next are evaluated. You can only get them\n from body of let expression."),"begin*":g(ra("begin*",function(e){return e.pop()}),"(begin* . expr)\n\n This macro is parallel version of begin. It evaluate each expression and\n if it's a promise it will evaluate it in parallel and return value\n of last expression."),begin:g(new hu("begin",function(e,t){var n=Object.assign({},t);var i=co.get("list->array")(e);if(n.dynamic_scope){n.dynamic_scope=this}n.env=this;var u;return function t(){if(i.length){var e=i.shift();var r=Lo(e,n);return li(r,function(e){u=e;return t()})}else{return u}}()}),"(begin . args)\n\n Macro runs list of expression and return valuate of the list one.\n It can be used in place where you can only have single exression,\n like if expression."),ignore:new hu("ignore",function(e,t){var r=t.dynamic_scope,n=t.error;var i={env:this,error:n};if(r){i.dynamic_scope=this}Lo(new q(new L("begin"),e),i)},"(ignore expression)\n\n Macro that will evaluate expression and swallow any promises that may\n be created. It wil run and ignore any value that may be returned by\n expression. The code should have side effects and/or when it's promise\n it should resolve to undefined."),"call/cc":g(hu.defmacro("call/cc",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var r=Lr({env:this},t);return li(Lo(e.car,r),function(e){if(Du(e)){return e(new Ro(null))}})}),"(call/cc proc)\n\n TODO"),define:g(hu.defmacro("define",function(r,e){var n=this;if(r.car instanceof q&&r.car.car instanceof L){var t=new q(new L("define"),new q(r.car.car,new q(new q(new L("lambda"),new q(r.car.cdr,r.cdr)))));return t}else if(e.macro_expand){return}if(e.dynamic_scope){e.dynamic_scope=this}e.env=n;var i=r.cdr.car;var u;if(i instanceof q){i=Lo(i,e);u=true}else if(i instanceof L){i=n.get(i)}Eo("define",r.car,"symbol");return li(i,function(e){if(n.__name__===vu.__merge_env__){n=n.__parent__}if(u&&(Du(e)&&Zu(e)||e instanceof vu)){e.__name__=r.car.valueOf();if(e.__name__ instanceof _a){e.__name__=e.__name__.valueOf()}}var t;if(r.cdr.cdr instanceof q&&_a.isString(r.cdr.cdr.car)){t=r.cdr.cdr.car.valueOf()}n.set(r.car,e,t,true)})}),'(define name expression)\n (define name expression "doc string")\n (define (function-name . args) body)\n\n Macro for defining values. It can be used to define variables,\n or function. If first argument is list it will create function\n with name beeing first element of the list. The macro evalute\n code `(define function (lambda args body))`'),"set-obj!":g("set-obj!",function(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;var i=_(e);if(wu(e)||i!=="object"&&i!=="function"){var u=bo("set-obj!",Oo(e),["object","function"]);throw new Error(u)}Eo("set-obj!",t,["string","symbol","number"]);e=Bu(e);t=t.valueOf();if(arguments.length===2){delete e[t]}else if(iu(e)&&Du(r)){e[t]=Bu(r);e[t][Vu]=true}else if(Du(r)||Fo(r)||r===U){e[t]=r}else{e[t]=r&&!iu(r)?r.valueOf():r}if(Vi){var a=e[t];Object.defineProperty(e,t,Lr(Lr({},n),{},{value:a}))}},"(set-obj! obj key value)\n (set-obj! obj key value props)\n\n Function set property of JavaScript object. Props should be vector of pairs,\n passed to Object.defineProperty."),"null-environment":g("null-environment",function(){return co.inherit("null")},"(null-environment)\n\n Function return new base environment with std lib."),values:g("values",function e(){for(var t=arguments.length,r=new Array(t),n=0;n1&&arguments[1]!==undefined?arguments[1]:{},h=e.dynamic_scope,p=e.error;var _=this;var d;if(l.cdr instanceof q&&_a.isString(l.cdr.car)&&l.cdr.cdr!==U){d=l.cdr.car.valueOf()}function v(){var e;if(h){if(!(this instanceof Ka)){e=_}else{e=this}}else{e=_}e=e.inherit("lambda");var t=l.car;var r=0;var n;if(typeof this!=="undefined"&&!(this instanceof Ka)){if(this&&!this.__instance__){Object.defineProperty(this,"__instance__",{enumerable:false,get:function e(){return true},set:function e(){},configurable:false})}e.set("this",this)}for(var i=arguments.length,u=new Array(i),a=0;a>> "+c.toString());if(c){o=c}var d=r.merge(t,vu.__merge_env__);if(l){return{expr:o,scope:d}}var v=Lo(o,Lr(Lr({},p),{},{env:d}));return gu(v,_)}i=i.cdr}}catch(e){e.message+=" in macro: ".concat(m.toString(true));throw e}throw new Error("Invalid Syntax ".concat(e.toString(true)))},b);r.__code__=m;return r},"(syntax-rules () (pattern expression) ...)\n\n Base of Hygienic macro, it will return new syntax expander\n that works like lisp macros."),quote:g(new hu("quote",function(e){return to(e.car)}),"(quote expression)\n\n Macro that return single lips expression as data (it don't evaluate its\n argument). It will return list of pairs if put in front of lips code.\n And if put in fron of symbol it will return that symbol not value\n associated with that name."),"unquote-splicing":g("unquote-splicing",function(){throw new Error("You can't call `unquote-splicing` outside of quasiquote")},"(unquote-splicing code)\n\n Special form to be used in quasiquote macro, parser is processing special\n characters ,@ and create call to this pseudo function. It can be used\n to evalute expression inside and return the value without parenthesis.\n the value will be joined to the output list structure."),unquote:g("unquote",function(){throw new Error("You can't call `unquote` outside of quasiquote")},"(unquote code)\n\n Special form to be used in quasiquote macro, parser is processing special\n characters , and create call to this pseudo function. It can be used\n to evalute expression inside and return the value, the output is inserted\n into list structure created by queasiquote."),quasiquote:hu.defmacro("quasiquote",function(e,t){var o=t.dynamic_scope,s=t.error;var c=this;if(o){o=c}function a(e){return e instanceof q||zi(e)||Array.isArray(e)}function h(e,t){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:a;if(e instanceof q){var n=e.car;var i=e.cdr;if(r(n)){n=t(n)}if(r(i)){i=t(i)}if(Fu(n)||Fu(i)){return Zn([n,i]).then(function(e){var t=j(e,2),r=t[0],n=t[1];return new q(r,n)})}else{return new q(n,i)}}return e}function u(e,t){if(e instanceof q){if(t!==U){e.append(t)}}else{e=new q(e,t)}return e}function r(e){return!!e.filter(function(e){return e instanceof q&&L.is(e.car,/^(unquote|unquote-splicing)$/)}).length}function p(e,n,i){return e.reduce(function(e,t){if(!(t instanceof q)){e.push(t);return e}if(L.is(t.car,"unquote-splicing")){var r;if(n+11){var t="You can't splice multiple atoms inside list";throw new Error(t)}if(!(i.cdr instanceof q&&r[0]===U)){return r[0]}}r=r.map(function(e){if(d.has(e)){return e.clone()}else{d.add(e);return e}});var n=l(i.cdr,0,1);if(n===U&&r[0]===U){return undefined}return li(n,function(e){if(r[0]===U){return e}if(r.length===1){return u(r[0],e)}var t=r.reduce(function(e,t){return u(e,t)});return u(t,e)})})}(i.car.cdr)}var d=new Set;function l(e,t,r){if(e instanceof q){if(e.car instanceof q){if(L.is(e.car.car,"unquote-splicing")){return f(e,t+1,r)}if(L.is(e.car.car,"unquote")){if(t+2===r&&e.car.cdr instanceof q&&e.car.cdr.car instanceof q&&L.is(e.car.cdr.car.car,"unquote-splicing")){var n=e.car.cdr;return new q(new q(new L("unquote"),f(n,t+2,r)),U)}else if(e.car.cdr instanceof q&&e.car.cdr.cdr!==U){if(e.car.cdr.car instanceof q){var i=[];return function t(r){if(r===U){return q.fromArray(i)}return li(Lo(r.car,{env:c,dynamic_scope:o,error:s}),function(e){i.push(e);return t(r.cdr)})}(e.car.cdr)}else{return e.car.cdr}}}}if(L.is(e.car,"quasiquote")){var u=l(e.cdr,t,r+1);return new q(e.car,u)}if(L.is(e.car,"quote")){return new q(e.car,l(e.cdr,t,r))}if(L.is(e.car,"unquote")){t++;if(tr){throw new Error("You can't call `unquote` outside "+"of quasiquote")}if(e.cdr instanceof q){if(e.cdr.cdr!==U){if(e.cdr.car instanceof q){var a=[];return function t(r){if(r===U){return q.fromArray(a)}return li(Lo(r.car,{env:c,dynamic_scope:o,error:s}),function(e){a.push(e);return t(r.cdr)})}(e.cdr)}else{return e.cdr}}else{return Lo(e.cdr.car,{env:c,dynamic_scope:o,error:s})}}else{return e.cdr}}return h(e,function(e){return l(e,t,r)})}else if(zi(e)){return _(e,t,r)}else if(e instanceof Array){return p(e,t,r)}return e}function n(e){if(e instanceof q){delete e[qu];if(!e.haveCycles("car")){n(e.car)}if(!e.haveCycles("cdr")){n(e.cdr)}}}if(zi(e.car)&&!r(Object.values(e.car))){return to(e.car)}if(Array.isArray(e.car)&&!r(e.car)){return to(e.car)}if(e.car instanceof q&&!e.car.find("unquote")&&!e.car.find("unquote-splicing")&&!e.car.find("quasiquote")){return to(e.car)}var i=l(e.car,0,1);return li(i,function(e){n(e);return to(e)})},"(quasiquote list ,value ,@value)\n\n Similar macro to `quote` but inside it you can use special\n expressions unquote abbreviated to , that will evaluate expresion inside\n and return its value or unquote-splicing abbreviated to ,@ that will\n evaluate expression but return value without parenthesis (it will join)\n the list with its value. Best used with macros but it can be used outside"),clone:g("clone",function e(t){Eo("clone",t,"pair");return t.clone()},"(clone list)\n\n Function return clone of the list."),append:g("append",function e(){var t;for(var r=arguments.length,n=new Array(r),i=0;iarray")(t).reverse();return co.get("array->list")(r)}else if(!(t instanceof Array)){throw new Error(bo("reverse",Oo(t),"array or pair"))}else{return t.reverse()}},"(reverse list)\n\n Function will reverse the list or array. If value is not a list\n or array it will throw exception."),nth:g("nth",function e(t,r){Eo("nth",t,"number");Eo("nth",r,["array","pair"]);if(r instanceof q){var n=r;var i=0;while(iarray")(r).join(t)},"(join separator list)\n\n Function return string by joining elements of the list"),split:g("split",function e(t,r){Eo("split",t,["regex","string"]);Eo("split",r,"string");return co.get("array->list")(r.split(t))},"(split separator string)\n\n Function create list by splitting string by separatar that can\n be a string or regular expression."),replace:g("replace",function e(t,r,n){Eo("replace",t,["regex","string"]);Eo("replace",r,["string","function"]);Eo("replace",n,"string");return n.replace(t,r)},"(replace pattern replacement string)\n\n Function change pattern to replacement inside string. Pattern can be string\n or regex and replacement can be function or string."),match:g("match",function e(t,r){Eo("match",t,["regex","string"]);Eo("match",r,"string");var n=r.match(t);return n?co.get("array->list")(n):false},"(match pattern string)\n\n function return match object from JavaScript as list or #f if not match."),search:g("search",function e(t,r){Eo("search",t,["regex","string"]);Eo("search",r,"string");return r.search(t)},"(search pattern string)\n\n Function return first found index of the pattern inside a string"),repr:g("repr",function e(t,r){return nu(t,r)},"(repr obj)\n\n Function return string LIPS representation of an object as string."),"escape-regex":g("escape-regex",function(e){Eo("escape-regex",e,"string");return Tn(e.valueOf())},"(escape-regex string)\n\n Function return new string where all special operators used in regex,\n are escaped with slash so they can be used in RegExp constructor\n to match literal string"),env:g("env",function e(e){e=e||this;var t=Object.keys(e.__env__).map(L);var r;if(t.length){r=q.fromArray(t)}else{r=U}if(e.__parent__ instanceof Ka){return co.get("env")(e.__parent__).append(r)}return r},"(env)\n (env obj)\n\n Function return list of values (functions, macros and variables)\n inside environment and it's parents."),new:g("new",function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n2&&arguments[2]!==undefined?arguments[2]:ei.LITERAL;Eo("set-special!",e,"string",1);Eo("set-special!",t,"symbol",2);ei.append(e.valueOf(),t,r)},'(set-special! symbol name [type])\n\n Add special symbol to the list of transforming operators by the parser.\n e.g.: `(add-special! "#" \'x)` will allow to use `#(1 2 3)` and it will be\n transformed into (x (1 2 3)) so you can write x macro that will process\n the list. 3rd argument is optional and it can be constant value\n lips.specials.SPLICE if this constant is used it will transform\n `#(1 2 3)` into (x 1 2 3) that is required by # that define vectors.'),get:no,".":no,unbind:g(Bu,"(unbind fn)\n\n Function remove bidning from function so you can get props from it."),type:g(Oo,"(type object)\n\n Function return type of an object as string."),debugger:g("debugger",function(){debugger},"(debugger)\n\n Function stop JavaScript code in debugger."),in:g("in",function(e,t){if(e instanceof L||e instanceof _a||e instanceof k){e=e.valueOf()}return e in Ou(t)},"(in key value)\n\n Function use is in operator to check if value is in object."),instanceof:g("instanceof",function(e,t){return t instanceof Bu(e)},"(instanceof type obj)\n\n Function check of object is instance of object."),"prototype?":g("prototype?",iu,"(prototype? obj)\n\n Function check if value is JavaScript Object prototype."),"macro?":g("macro?",function(e){return e instanceof hu},"(macro? expression)\n\n Function check if value is a macro."),"function?":g("function?",Du,"(function? expression)\n\n Function check if value is a function."),"real?":g("real?",function(e){if(Oo(e)!=="number"){return false}if(e instanceof k){return e.isFloat()}return k.isFloat(e)},"(real? number)\n\n Function check if value is real number."),"number?":g("number?",function(e){return Number.isNaN(e)||k.isNumber(e)},"(number? expression)\n\n Function check if value is a number or NaN value."),"string?":g("string?",function(e){return _a.isString(e)},"(string? expression)\n\n Function check if value is a string."),"pair?":g("pair?",function(e){return e instanceof q},"(pair? expression)\n\n Function check if value is a pair or list structure."),"regex?":g("regex?",function(e){return e instanceof RegExp},"(regex? expression)\n\n Function check if value is regular expression."),"null?":g("null?",function(e){return wu(e)},"(null? expression)\n\n Function check if value is nulish."),"boolean?":g("boolean?",function(e){return typeof e==="boolean"},"(boolean? expression)\n\n Function check if value is boolean."),"symbol?":g("symbol?",function(e){return e instanceof L},"(symbol? expression)\n\n Function check if value is LIPS symbol"),"array?":g("array?",function(e){return e instanceof Array},"(array? expression)\n\n Function check if value is an arrray."),"object?":g("object?",function(e){return e!==U&&e!==null&&!(e instanceof pa)&&!(e instanceof RegExp)&&!(e instanceof _a)&&!(e instanceof q)&&!(e instanceof k)&&_(e)==="object"&&!(e instanceof Array)},"(object? expression)\n\n Function check if value is an plain object."),flatten:g("flatten",function e(t){Eo("flatten",t,"pair");return t.flatten()},"(flatten list)\n\n Return shallow list from tree structure (pairs)."),"array->list":g("array->list",function(e){Eo("array->list",e,"array");return q.fromArray(e)},"(array->list array)\n\n Function convert JavaScript array to LIPS list."),"tree->array":g("tree->array",Yi("tree->array",true),"(tree->array list)\n\n Function convert LIPS list structure into JavaScript array."),"list->array":g("list->array",Yi("list->array"),"(list->array list)\n\n Function convert LIPS list into JavaScript array."),apply:g("apply",function e(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;iarray").call(this,u));return t.apply(this,Po(t,n))},"(apply fn list)\n\n Function that call function with list of arguments."),length:g("length",function e(t){if(!t||t===U){return 0}if(t instanceof q){return t.length()}if("length"in t){return t.length}},"(length expression)\n\n Function return length of the object, the object can be list\n or any object that have length property."),"string->number":g("string->number",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;Eo("string->number",e,"string",1);Eo("string->number",t,"number",2);e=e.valueOf();t=t.valueOf();if(e.match(gn)||e.match(vn)){return An(e,t)}else if(e.match(bn)||e.match(dn)){return Cn(e,t)}else{var r=t===10&&!e.match(/e/i)||t===16;if(e.match(yn)&&r||e.match(mn)){return Fn(e,t)}if(e.match(un)){return Sn(e)}}return false},"(string->number number [radix])\n\n Function convert string to number."),try:g(new hu("try",function(t,e){var c=this;var f=e.dynamic_scope,l=e.error;return new Promise(function(i,n){var u,a;if(L.is(t.cdr.car.car,"catch")){u=t.cdr.car;if(t.cdr.cdr instanceof q&&L.is(t.cdr.cdr.car.car,"finally")){a=t.cdr.cdr.car}}else if(L.is(t.cdr.car.car,"finally")){a=t.cdr.car}if(!(a||u)){throw new Error("try: invalid syntax")}var o=i;if(a){o=function e(t,r){o=n;li(Lo(new q(new L("begin"),a.cdr),s),function(){r(t)})}}var s={env:c,error:function e(t){var r=c.inherit("try");if(u){r.set(u.cdr.car.car,t);var n={env:r,error:l};if(f){n.dynamic_scope=c}li(Lo(new q(new L("begin"),u.cdr.cdr),n),function(e){o(e,i)})}else{o(t,l)}}};if(f){s.dynamic_scope=c}var e=Lo(t.car,s);if(Fu(e)){e.then(function(e){o(e,i)})["catch"](s.error)}else{o(e,i)}})}),"(try expr (catch (e) code))\n (try expr (catch (e) code) (finally code))\n (try expr (finally code))\n\n Macro execute user code and catch exception. If catch is provided\n it's executed when expression expr throw error. If finally is provide\n it's always executed at the end."),raise:g("raise",function(e){throw e},"(raise obj)\n\n Throws new exception with given object."),throw:g("throw",function(e){throw new Error(e)},"(throw string)\n\n Throws new expection."),find:g("find",function t(r,n){Eo("find",r,["regex","function"]);Eo("find",n,["pair","nil"]);if(wu(n)){return U}var e=mi("find",r);return li(e(n.car),function(e){if(e&&e!==U){return n.car}return t(r,n.cdr)})},"(find fn list)\n (find regex list)\n\n Higher order Function find first value for which function return true.\n If called with regex it will create matcher function."),"for-each":g("for-each",function(e){var t;Eo("for-each",e,"function");for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i1?t-1:0),u=1;u3?n-3:0),u=3;u3?i-3:0),a=3;aarray")(r);var u=[];var a=mi("filter",t);return function t(r){function e(e){if(e&&e!==U){u.push(n)}return t(++r)}if(r===i.length){return q.fromArray(u)}var n=i[r];return li(a(n),e)}(0)},"(filter fn list)\n (filter regex list)\n\n Higher order function that call `fn` for each element of the list\n and return list for only those elements for which funtion return\n true value. If called with regex it will create matcher function."),compose:g(ua,"(compose . fns)\n\n Higher order function and create new function that apply all functions\n From right to left and return it's value. Reverse of compose.\n e.g.:\n ((compose (curry + 2) (curry * 3)) 3)\n 11"),pipe:g(ia,"(pipe . fns)\n\n Higher order function and create new function that apply all functions\n From left to right and return it's value. Reverse of compose.\n e.g.:\n ((pipe (curry + 2) (curry * 3)) 3)\n 15"),curry:g(la,"(curry fn . args)\n\n Higher order function that create curried version of the function.\n The result function will have parially applied arguments and it\n will keep returning functions until all arguments are added\n\n e.g.:\n (define (add a b c d) (+ a b c d))\n (define add1 (curry add 1))\n (define add12 (add 2))\n (display (add12 3 4))"),gcd:g("gcd",function e(){for(var t=arguments.length,r=new Array(t),n=0;no?u%=o:o%=u}u=au(s*r[a])/(u+o)}return k(u)},"(lcm n1 n2 ...)\n\n Function return the least common multiple of their arguments."),"odd?":g("odd?",sa(function(e){return k(e).isOdd()}),"(odd? number)\n\n Function check if number os odd."),"even?":g("even?",sa(function(e){return k(e).isEven()}),"(even? number)\n\n Function check if number is even."),"*":g("*",fa(function(e,t){return k(e).mul(t)},k(1)),"(* . numbers)\n\n Multiplicate all numbers passed as arguments. If single value is passed\n it will return that value."),"+":g("+",fa(function(e,t){return k(e).add(t)},k(0)),"(+ . numbers)\n\n Sum all numbers passed as arguments. If single value is passed it will\n return that value."),"-":g("-",function(){for(var e=arguments.length,t=new Array(e),r=0;r":g(">",function(){for(var e=arguments.length,t=new Array(e),r=0;r",t,"number");return ou(function(e,t){return k(e).cmp(t)===1},t)},"(> x1 x2 ...)\n\n Function compare its numerical arguments and check if they are\n monotonically increasing"),"<":g("<",function(){for(var e=arguments.length,t=new Array(e),r=0;r=":g(">=",function(){for(var e=arguments.length,t=new Array(e),r=0;r=",t,"number");return ou(function(e,t){return[0,1].includes(k(e).cmp(t))},t)},"(>= x1 x2 ...)\n\n Function compare its numerical arguments and check if they are\n monotonically nondecreasing"),"eq?":g("eq?",su,"(eq? a b)\n\n Function compare two values if they are identical."),or:g(new hu("or",function(e,t){var i=t.dynamic_scope,u=t.error;var a=co.get("list->array")(e);var o=this;if(i){i=o}if(!a.length){return false}var s;return function t(){function e(e){s=e;if(s!==false){return s}else{return t()}}if(!a.length){if(s!==false){return s}else{return false}}else{var r=a.shift();var n=Lo(r,{env:o,dynamic_scope:i,error:u});return li(n,e)}}()}),"(or . expressions)\n\n Macro execute the values one by one and return the one that is truthy value.\n If there are no expression that evaluate to true it return false."),and:g(new hu("and",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},i=t.dynamic_scope,u=t.error;var a=co.get("list->array")(e);var o=this;if(i){i=o}if(!a.length){return true}var s;return function t(){function e(e){s=e;if(s===false){return false}else{return t()}}if(!a.length){if(s!==false){return s}else{return false}}else{var r=a.shift();var n=Lo(r,{env:o,dynamic_scope:i,error:u});return li(n,e)}}()}),"(and . expressions)\n\n Macro evalute each expression in sequence if any value return false it will\n return false. If each value return true it will return the last value.\n If it's called without arguments it will return true."),"|":g("|",function(e,t){return k(e).or(t)},"(| a b)\n\n Function calculate or bit operation."),"&":g("&",function(e,t){return k(e).and(t)},"(& a b)\n\n Function calculate and bit operation."),"~":g("~",function(e){return k(e).neg()},"(~ number)\n\n Function negate the value."),">>":g(">>",function(e,t){return k(e).shr(t)},"(>> a b)\n\n Function right shit the value a by value b."),"<<":g("<<",function(e,t){return k(e).shl(t)},"(<< a b)\n\n Function left shit the value a by value b."),not:g("not",function e(t){if(wu(t)){return true}return!t},"(not object)\n\n Function return negation of the argument.")},undefined,"global");var fo=co.inherit("user-env");function lo(e,t){e.constant("**internal-env**",t);e.doc("**internal-env**","**internal-env**\n\n Constant used to hide stdin, stdout and stderr so they don't interfere\n with variables with the same name. Constants are internal type\n of variables that can't be redefined, defining variable with same name\n will throw an error.");co.set("**interaction-environment**",e)}lo(fo,ao);co.doc("**interaction-environment**","**interaction-environment**\n\n Internal dynamic, global variable used to find interpreter environment.\n It's used so the read and write functions can locate **internal-env**\n that contain references to stdin, stdout and stderr.");(function(){var e={ceil:"ceiling"};["floor","round","ceil"].forEach(function(t){var r=e[t]?e[t]:t;co.set(r,g(r,function(e){Eo(r,e,"number");if(e instanceof k){return e[t]()}},"(".concat(r," number)\n\n Function calculate ").concat(r," of a number.")))})})();function ho(e){if(e.length===1){return e[0]}else{var t=[];var r=ho(e.slice(1));for(var n=0;n3&&arguments[3]!==undefined?arguments[3]:null;var i=e?" in expression `".concat(e,"`"):"";if(n!==null){i+=" (argument ".concat(n,")")}if(Du(r)){return"Invalid type got ".concat(t).concat(i)}if(r instanceof Array){if(r.length===1){r=r[0]}else{var u=r[r.length-1];r=r.slice(0,-1).join(", ")+" or "+u}}return"Expecting ".concat(r,", got ").concat(t).concat(i)}function wo(r,e,n){e.forEach(function(e,t){Eo(r,e,n,t+1)})}function Do(e,t,r){Eo(e,t,r);if(t.__type__===Ja){throw new Error(bo(e,"binary-port","textual-port"))}}function Eo(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;e=e.valueOf();var i=Oo(t).toLowerCase();if(Du(r)){if(!r(t)){throw new Error(bo(e,i,r,n))}return}var u=false;if(r instanceof q){r=r.to_array()}if(r instanceof Array){r=r.map(function(e){return e.valueOf()})}if(r instanceof Array){r=r.map(function(e){return e.valueOf().toLowerCase()});if(r.includes(i)){u=true}}else{r=r.valueOf().toLowerCase()}if(!u&&i!==r){throw new Error(bo(e,i,r,n))}}function Ao(e){var t=_(e);return["string","function"].includes(t)||_(e)==="symbol"||e instanceof Qn||e instanceof L||e instanceof k||e instanceof _a||e instanceof RegExp}function Fo(e){return e instanceof k||e instanceof _a||e instanceof pa}function xo(e,t){if(e===null){return false}return _(e)==="object"&&t in Object.getOwnPropertySymbols(e)}function Co(e,t){if(xo(e,t)||xo(e.__proto__,t)){return Du(e[t])}}function ko(r){var n=new WeakMap;return function(e){var t=n.get(e);if(!t){t=r(e)}return t}}Oo=ko(Oo);function Oo(e){var t=$r.get(e);if(t){return t}if(_(e)==="object"){for(var r=0,n=Object.entries(Yr);r2&&arguments[2]!==undefined?arguments[2]:{},u=t.env,a=t.dynamic_scope,r=t.error,o=r===void 0?function(){}:r;e=Bo(e,{env:u,dynamic_scope:a,error:o});return li(e,function(e){if(Xu(i)){i=Bu(i)}e=Po(i,e);var t=e.slice();var r=(a||u).newFrame(i,t);var n=So(i.apply(r,e));return li(n,function(e){if(e instanceof q){e.markCycles();return to(e)}return Cu(e)},o)})}var Ro=function(){function t(e){A(this,t);this.__value__=e}x(t,[{key:"invoke",value:function e(){if(this.__value__===null){throw new Error("Continuations are not implemented yet")}}},{key:"toString",value:function e(){return"#"}}]);return t}();var To=function e(){};function Lo(t){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=e.env,n=e.dynamic_scope,c=e.error,i=c===void 0?To:c;try{if(n===true){r=n=r||co}else if(r===true){r=n=co}else{r=r||co}var u={env:r,dynamic_scope:n,error:i};var a;if(wu(t)){return t}if(t instanceof L){return r.get(t)}if(!(t instanceof q)){return t}var o=t.car;var f=t.cdr;if(o instanceof q){a=So(Lo(o,u));if(Fu(a)){return a.then(function(e){return Lo(new q(e,t.cdr),u)})}else if(!Au(a)){throw new Error(Oo(a)+" "+r.get("repr")(a)+" is not callable while evaluating "+t.toString())}}if(o instanceof L){a=r.get(o)}else if(Du(o)){a=o}var s;if(a instanceof vu){s=jo(a,t,u)}else if(a instanceof hu){s=Io(a,f,u)}else if(Du(a)){s=No(a,f,u)}else if(Eu(a)){s=a.invoke()}else if(t instanceof q){a=o&&o.toString();throw new Error("".concat(Oo(o)," ").concat(a," is not a function"))}else{return t}var l=r.get(Symbol["for"]("__promise__"),{throwError:false});if(l===true&&Fu(s)){s=s.then(function(e){if(e instanceof q&&!a[qu]){return Lo(e,u)}return e});return new Qn(s)}return s}catch(e){i&&i.call(r,e,t)}}var Uo=Mo(function(e){return e});var qo=Mo(function(e,t){return t});function Mo(_){return function(){var n=O(z.mark(function e(r,n,i){var u,a,o,s,h,c,p,f,l;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:if(i===true){n=i=n||fo}else if(n===true){n=i=fo}else{n=n||fo}u=[];a=Array.isArray(r)?r:ci(r);o=false;s=false;t.prev=5;c=Ur(a);case 7:t.next=9;return c.next();case 9:if(!(o=!(p=t.sent).done)){t.next=27;break}f=p.value;l=Lo(f,{env:n,dynamic_scope:i,error:function e(t,r){if(t&&t.message){if(t.message.match(/^Error:/)){var n=/^(Error:)\s*([^:]+:\s*)/;t.message=t.message.replace(n,"$1 $2")}if(r){if(!(t.__code__ instanceof Array)){t.__code__=[]}t.__code__.push(r.toString(true))}}throw t}});if(Fu(l)){t.next=16;break}u.push(_(f,l));t.next=24;break;case 16:t.t0=u;t.t1=_;t.t2=f;t.next=21;return l;case 21:t.t3=t.sent;t.t4=(0,t.t1)(t.t2,t.t3);t.t0.push.call(t.t0,t.t4);case 24:o=false;t.next=7;break;case 27:t.next=33;break;case 29:t.prev=29;t.t5=t["catch"](5);s=true;h=t.t5;case 33:t.prev=33;t.prev=34;if(!(o&&c["return"]!=null)){t.next=38;break}t.next=38;return c["return"]();case 38:t.prev=38;if(!s){t.next=41;break}throw h;case 41:return t.finish(38);case 42:return t.finish(33);case 43:return t.abrupt("return",u);case 44:case"end":return t.stop()}}},e,null,[[5,29,33,43],[34,,38,42]])}));function e(e,t,r){return n.apply(this,arguments)}return e}()}function Yo(e){var t={"[":"]","(":")"};var r;if(typeof e==="string"){r=zn(e)}else{r=e.map(function(e){return e&&e.token?e.token:e})}var n=Object.keys(t);var i=Object.values(t).concat(n);r=r.filter(function(e){return i.includes(e)});var u=new Ln;var a=Pr(r),o;try{for(a.s();!(o=a.n()).done;){var s=o.value;if(n.includes(s)){u.push(s)}else if(!u.is_empty()){var f=u.top();var c=t[f];if(s===c){u.pop()}else{throw new Error("Syntax error: missing closing ".concat(c))}}else{throw new Error("Syntax error: not matched closing ".concat(s))}}}catch(e){a.e(e)}finally{a.f()}return u.is_empty()}function $o(e){var t="("+e.toString()+")()";var r=window.URL||window.webkitURL;var n;try{n=new Blob([t],{type:"application/javascript"})}catch(e){var i=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder;n=new i;n.append(t);n=n.getBlob()}return new Mr.Worker(r.createObjectURL(n))}function zo(){return ys.version.match(/^(\{\{VER\}\}|DEV)$/)}function Vo(){if(mo()){return}var e;if(document.currentScript){e=document.currentScript}else{var t=document.querySelectorAll("script");if(!t.length){return}e=t[t.length-1]}var r=e.getAttribute("src");return r}var Jo=Vo();function Go(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"";var t="dist/std.xcb";if(e===""){if(Jo){e=Jo.replace(/[^/]*$/,"std.xcb")}else if(zo()){e="https://cdn.jsdelivr.net/gh/jcubic/lips@devel/".concat(t)}else{e="https://cdn.jsdelivr.net/npm/@jcubic/lips@".concat(ys.version,"/").concat(t)}}var r=co.get("load");return r.call(fo,e,co)}function Wo(e){this.url=e;var a=this.worker=$o(function(){var a;var o;self.addEventListener("message",function(e){var r=e.data;var t=r.id;if(r.type!=="RPC"||t===null){return}function n(e){self.postMessage({id:t,type:"RPC",result:e})}function i(e){self.postMessage({id:t,type:"RPC",error:e})}if(r.method==="eval"){if(!o){i("Worker RPC: LIPS not initilized, call init first");return}o.then(function(){var e=r.params[0];var t=r.params[1];a.exec(e,t).then(function(e){e=e.map(function(e){return e&&e.valueOf()});n(e)})["catch"](function(e){i(e)})})}else if(r.method==="init"){var u=r.params[0];if(typeof u!=="string"){i("Worker RPC: url is not a string")}else{importScripts("".concat(u,"/dist/lips.min.js"));a=new ys.Interpreter("worker");o=Go(u);o.then(function(){n(true)})}}})});this.rpc=function(){var n=0;return function e(t,r){var u=++n;return new Promise(function(n,i){a.addEventListener("message",function e(t){var r=t.data;if(r&&r.type==="RPC"&&r.id===u){if(r.error){i(r.error)}else{n(r.result)}a.removeEventListener("message",e)}});a.postMessage({type:"RPC",method:t,id:u,params:r})})}}();this.rpc("init",[e])["catch"](function(e){console.error(e)});this.exec=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;return this.rpc("eval",[e,t])}}var Ho={pair:function e(t){var r=j(t,2),n=r[0],i=r[1];return q(n,i)},number:function e(t){if(_a.isString(t)){return k([t,10])}return k(t)},regex:function e(t){var r=j(t,2),n=r[0],i=r[1];return new RegExp(n,i)},nil:function e(){return U},symbol:function e(t){if(_a.isString(t)){return L(t)}else if(Array.isArray(t)){return L(Symbol["for"](t[0]))}},string:_a,character:pa};var Qo=Object.keys(Ho);var Zo={};for(var Ko=0,Xo=Object.entries(Qo);Ko1){var n=t.reduce(function(e,t){return e+t.length},0);var i=new Uint8Array(n);var u=0;t.forEach(function(e){i.set(e,u);u+=e.length});return i}else if(t.length){return t[0]}}function cs(){var e=1;var t=new TextEncoder("utf-8");return t.encode("LIPS".concat(e.toString().padStart(3," ")))}var fs=7;function ls(e){var t=new TextDecoder("utf-8");var r=t.decode(e.slice(0,fs));var n=r.substring(0,4);if(n==="LIPS"){var i=r.match(/^(....).*([0-9]+)$/);if(i){return{type:i[1],version:Number(i[2])}}}return{type:"unknown"}}function hs(e){var t=cs();var r=os.encode(e);return ss(t,Cr(r,{magic:false}))}function ps(e){var t=ls(e),r=t.type,n=t.version;if(r==="LIPS"&&n===1){var i=kr(e.slice(fs),{magic:false});return os.decode(i)}else{throw new Error("Invalid file format ".concat(r))}}function _s(e){console.error(e.message||e);if(e.code){console.error(e.code.map(function(e,t){return"[".concat(t+1,"]: ").concat(e)}))}}function ds(){var a=["text/x-lips","text/x-scheme"];var o;function s(r){return new Promise(function(t){var e=r.getAttribute("src");if(e){return fetch(e).then(function(e){return e.text()}).then(qo).then(t)["catch"](function(e){_s(e);t()})}else{return qo(r.innerHTML).then(t)["catch"](function(e){_s(e);t()})}})}function e(){return new Promise(function(i){var u=Array.from(document.querySelectorAll("script"));return function e(){var t=u.shift();if(!t){i()}else{var r=t.getAttribute("type");if(a.includes(r)){var n=t.getAttribute("bootstrap");if(!o&&typeof n==="string"){return Go(n).then(function(){return s(t)}).then(e)}else{return s(t).then(e)}}else if(r&&r.match(/lips|lisp/)){console.warn("Expecting "+a.join(" or ")+" found "+r)}return e()}}()})}if(!window.document){return Promise.resolve()}else if(vs){var t=vs;var r=t.getAttribute("bootstrap");if(typeof r==="string"){return Go(r).then(function(){o=true;return e()})}}return e()}var vs=typeof window!=="undefined"&&window.document&&document.currentScript;if(typeof window!=="undefined"){Wr(window,ds)}var ms=function(){var e=_a("Wed, 06 Sep 2023 20:32:14 +0000").valueOf();var t=e==="{{"+"DATE}}"?new Date:new Date(e);var r=function e(t){return t.toString().padStart(2,"0")};var n=t.getFullYear();var i=[n,r(t.getMonth()+1),r(t.getDate())].join("-");var u="\n __ __ __\n / / \\ \\ _ _ ___ ___ \\ \\\n| | \\ \\ | | | || . \\/ __> | |\n| | > \\ | |_ | || _/\\__ \\ | |\n| | / ^ \\ |___||_||_| <___/ | |\n \\_\\ /_/ \\_\\ /_/\n\nLIPS Interpreter DEV (".concat(i,") \nCopyright (c) 2018-").concat(n," Jakub T. Jankiewicz\n\nType (env) to see environment with functions macros and variables. You can also\nuse (help name) to display help for specic function or macro, (apropos name)\nto display list of matched names in environment and (dir object) to list\nproperties of an object.\n").replace(/^.*\n/,"");return u}();_i(Ei,"__class__","ahead");_i(q,"__class__","pair");_i(Mi,"__class__","nil");_i(Ai,"__class__","pattern");_i(Di,"__class__","formatter");_i(hu,"__class__","macro");_i(vu,"__class__","syntax");_i(Ka,"__class__","environment");_i(Na,"__class__","input-port");_i(Ra,"__class__","output-port");_i(Ta,"__class__","output-port");_i(La,"__class__","output-string-port");_i(qa,"__class__","input-string-port");_i($a,"__class__","input-file-port");_i(Ua,"__class__","output-file-port");_i(Za,"__class__","lips-error");[k,Ca,Ia,ka,Pa].forEach(function(e){_i(e,"__class__","number")});_i(pa,"__class__","character");_i(L,"__class__","symbol");_i(_a,"__class__","string");_i(Qn,"__class__","promise");var ys={version:"DEV",banner:ms,date:"Wed, 06 Sep 2023 20:32:14 +0000",exec:qo,parse:ua(di,ci),tokenize:zn,evaluate:Lo,compile:Uo,serialize:us,unserialize:as,serialize_bin:hs,unserialize_bin:ps,bootstrap:Go,Environment:Ka,env:fo,Worker:Wo,Interpreter:Qa,balanced_parenthesis:Yo,balancedParenthesis:Yo,balanced:Yo,Macro:hu,Syntax:vu,Pair:q,Values:eo,QuotedPromise:Qn,Error:Za,quote:to,InputPort:Na,OutputPort:Ra,BufferedOutputPort:Ta,InputFilePort:$a,OutputFilePort:Ua,InputStringPort:qa,OutputStringPort:La,InputByteVectorPort:Ma,OutputByteVectorPort:Ya,InputBinaryFilePort:za,OutputBinaryFilePort:Va,Formatter:Di,Parser:oi,Lexer:s,specials:ei,repr:$i,nil:U,eof:Wa,LSymbol:L,LNumber:k,LFloat:ka,LComplex:Ca,LRational:Ia,LBigInteger:Pa,LCharacter:pa,LString:_a,rationalize:Ba};co.set("lips",ys);var gs={};var bs=Object.freeze({__proto__:null,default:gs});function ws(e,t){var r=0;for(var n=e.length-1;n>=0;n--){var i=e[n];if(i==="."){e.splice(n,1)}else if(i===".."){e.splice(n,1);r++}else if(r){e.splice(n,1);r--}}if(t){for(;r--;r){e.unshift("..")}}return e}var Ds=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var Es=function(e){return Ds.exec(e).slice(1)};function As(){var e="",t=false;for(var r=arguments.length-1;r>=-1&&!t;r--){var n=r>=0?arguments[r]:"/";if(typeof n!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!n){continue}e=n+"/"+e;t=n.charAt(0)==="/"}e=ws(Ns(e.split("/"),function(e){return!!e}),!t).join("/");return(t?"/":"")+e||"."}function Fs(e){var t=xs(e),r=Rs(e,-1)==="/";e=ws(Ns(e.split("/"),function(e){return!!e}),!t).join("/");if(!e&&!t){e="."}if(e&&r){e+="/"}return(t?"/":"")+e}function xs(e){return e.charAt(0)==="/"}function Cs(){var e=Array.prototype.slice.call(arguments,0);return Fs(Ns(e,function(e,t){if(typeof e!=="string"){throw new TypeError("Arguments to path.join must be strings")}return e}).join("/"))}function ks(e,t){e=As(e).substr(1);t=As(t).substr(1);function r(e){var t=0;for(;t=0;r--){if(e[r]!=="")break}if(t>r)return[];return e.slice(t,r-t+1)}var n=r(e.split("/"));var i=r(t.split("/"));var u=Math.min(n.length,i.length);var a=u;for(var o=0;o=t.length)return{done:true};return{done:false,value:t[n++]}},e:function e(t){throw t},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var u=true,a=false,o;return{s:function e(){r=r.call(t)},n:function e(){var t=r.next();u=t.done;return t},e:function e(t){a=true;o=t},f:function e(){try{if(!u&&r["return"]!=null)r["return"]()}finally{if(a)throw o}}}}function pn(e,t){if(!e)return;if(typeof e==="string")return _n(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor)r=e.constructor.name;if(r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return _n(e,t)}function _n(e,t){if(t==null||t>e.length)t=e.length;for(var r=0,n=new Array(t);r1&&arguments[1]!==undefined?arguments[1]:null;var n=arguments[1]===true;function t(e){if(!Cn()){return}var t=qo.get("repr")(e);if(r===null||r instanceof RegExp&&r.test(t)){console.log(qo.get("type")(e)+": "+t)}if(n){console.log(e)}}if(ra(e)){e.then(t)}else{t(e)}return e}function Cn(){return Yo&&Yo.get("DEBUG",{throwError:false})}function On(e){return e?"(?:#".concat(e,"(?:#[ie])?|#[ie]#").concat(e,")"):"(?:#[ie])?"}function Sn(e,t){return"".concat(On(e),"[+-]?").concat(t,"+/").concat(t,"+")}function Bn(e,t){return"".concat(On(e),"(?:[+-]?(?:").concat(t,"+/").concat(t,"+|nan.0|inf.0|").concat(t,"+))?(?:[+-]i|[+-]?(?:").concat(t,"+/").concat(t,"+|").concat(t,"+|nan.0|inf.0)i)(?=[()[\\]\\s]|$)")}function jn(e,t){return"".concat(On(e),"[+-]?").concat(t,"+")}var In=/^#\/((?:\\\/|[^/]|\[[^\]]*\/[^\]]*\])+)\/([gimyus]*)$/;var Pn="(?:[-+]?(?:[0-9]+(?:[eE][-+]?[0-9]+)|(?:\\.[0-9]+|[0-9]+\\.[0-9]+)(?:[eE][-+]?[0-9]+)?)|[0-9]+\\.)";var Nn="(?:#[ie])?(?:[+-]?(?:[0-9]+/[0-9]+|nan.0|inf.0|".concat(Pn,"|[+-]?[0-9]+))?(?:").concat(Pn,"|[+-](?:[0-9]+/[0-9]+|[0-9]+|nan.0|inf.0))i");var Rn=new RegExp("^(#[ie])?".concat(Pn,"$"),"i");function Tn(e,t){var r=e==="x"?"(?!\\+|".concat(t,")"):"(?!\\.|".concat(t,")");var n="";if(e===""){n="(?:[-+]?(?:[0-9]+(?:[eE][-+]?[0-9]+)|(?:\\.[0-9]+|[0-9]+\\.[0-9]+(?![0-9]))(?:[eE][-+]?[0-9]+)?))"}return new RegExp("^((?:(?:".concat(n,"|[-+]?inf.0|[-+]?nan.0|[+-]?").concat(t,"+/").concat(t,"+(?!").concat(t,")|[+-]?").concat(t,"+)").concat(r,")?)(").concat(n,"|[-+]?inf.0|[-+]?nan.0|[+-]?").concat(t,"+/").concat(t,"+|[+-]?").concat(t,"+|[+-])i$"),"i")}var Ln=function(){var u={};[[10,"","[0-9]"],[16,"x","[0-9a-fA-F]"],[8,"o","[0-7]"],[2,"b","[01]"]].forEach(function(e){var t=j(e,3),r=t[0],n=t[1],i=t[2];u[r]=Tn(n,i)});return u}();var Un={alarm:"",backspace:"\b",delete:"",escape:"",newline:"\n",null:"\0",return:"\r",space:" ",tab:"\t",dle:"",soh:"",dc1:"",stx:"",dc2:"",etx:"",dc3:"",eot:"",dc4:"",enq:"",nak:"",ack:"",syn:"",bel:"",etb:"",bs:"\b",can:"",ht:"\t",em:"",lf:"\n",sub:"",vt:"\v",esc:"",ff:"\f",fs:"",cr:"\r",gs:"",so:"",rs:"",si:"",us:"",del:""};function Mn(e){var t=[];var r=0;var n=e.length;while(r=55296&&i<=56319&&r1&&arguments[1]!==undefined?arguments[1]:10;var r=ei(e);var n=r.number.split("/");var i=fo({num:C([n[0],r.radix||t]),denom:C([n[1],r.radix||t])});if(r.inexact){return i.valueOf()}else{return i}}function ri(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;var r=ei(e);if(r.inexact){return uo(parseInt(r.number,r.radix||t))}return C([r.number,r.radix||t])}function ni(e){var t=e.match(/#\\x([0-9a-f]+)$/i);var r;if(t){var n=parseInt(t[1],16);r=String.fromCodePoint(n)}else{t=e.match(/#\\(.+)$/);if(t){r=t[1]}}if(r){return za(r)}throw new Error("Parse: invalid character")}function ii(e){var i=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;function t(e){var t;if(e==="+"){t=C(1)}else if(e==="-"){t=C(-1)}else if(e.match(Hn)){t=C([e,i])}else if(e.match(Wn)){var r=e.split("/");t=fo({num:C([r[0],i]),denom:C([r[1],i])})}else if(e.match(Rn)){var n=oi(e);if(u.exact){return n.toRational()}return n}else if(e.match(/nan.0$/)){return C(NaN)}else if(e.match(/inf.0$/)){if(e[0]==="-"){return C(Number.NEGATIVE_INFINITY)}return C(Number.POSITIVE_INFINITY)}else{throw new Error("Internal Parser Error")}if(u.inexact){return uo(t.valueOf())}return t}var u=ei(e);i=u.radix||i;var r;var n=u.number.match(Zn);if(i!==10&&n){r=n}else{r=u.number.match(Ln[i])}var a,o;o=t(r[2]);if(r[1]){a=t(r[1])}else{a=C(0)}if(o.cmp(0)===0&&o.__type__==="bigint"){return a}return io({im:o,re:a})}function ui(e){return parseInt(e.toString(),10)===e}function ai(e){var t=e.match(/^(([-+]?[0-9]*)(?:\.([0-9]+))?)e([-+]?[0-9]+)/i);if(t){var r=parseInt(t[4],10);var n;var i=t[1].replace(/[-+]?([0-9]*)\..+$/,"$1").length;var u=t[3]&&t[3].length;if(i0){return C(u).mul(o)}}}r=uo(r);if(t.exact){return r.toRational()}return r}function si(e){e=e.replace(/\\x([0-9a-f]+);/gi,function(e,t){return"\\u"+t.padStart(4,"0")}).replace(/\n/g,"\\n");var t=e.match(/(\\*)(\\x[0-9A-F])/i);if(t&&t[1].length%2===0){throw new Error("Invalid string literal, unclosed ".concat(t[2]))}try{return $a(JSON.parse(e))}catch(e){var r=e.message.replace(/in JSON /,"").replace(/.*Error: /,"");throw new Error("Invalid string literal: ".concat(r))}}function ci(e){if(e.match(/^\|.*\|$/)){e=e.replace(/(^\|)|(\|$)/g,"");var r={t:"\t",r:"\r",n:"\n"};e=e.replace(/\\(x[^;]+);/g,function(e,t){return String.fromCharCode(parseInt("0"+t,16))}).replace(/\\(.)/g,function(e,t){return r[t]||t})}return new L(e)}function fi(e){if(Mo.hasOwnProperty(e)){return Mo[e]}if(e.match(/^"[\s\S]*"$/)){return si(e)}else if(e[0]==="#"){var t=e.match(In);if(t){return new RegExp(t[1],t[2])}else if(e.match(Vn)){return ni(e)}var r=e.match(/#\\(.+)/);if(r&&Mn(r[1]).length===1){return ni(e)}}if(e.match(/[0-9a-f]|[+-]i/i)){if(e.match(Gn)){return ri(e)}else if(e.match(Rn)){return oi(e)}else if(e.match(Kn)){return ti(e)}else if(e.match(Jn)){return ii(e)}}if(e.match(/^#[iexobd]/)){throw new Error("Invalid numeric constant: "+e)}return ci(e)}function li(e){return!(["(",")","[","]"].includes(e)||Bi.names().includes(e))}function hi(e){return li(e)&&!(e.match(In)||e.match(/^"[\s\S]*"$/)||e.match(Gn)||e.match(Rn)||e.match(Jn)||e.match(Kn)||e.match(Vn)||["#t","#f","nil","true","false"].includes(e))}var pi=/"(?:\\[\S\s]|[^"])*"?/g;function _i(e){if(typeof e==="string"){var t=/([-\\^$[\]()+{}?*.|])/g;return e.replace(t,"\\$1")}return e}function di(){this.data=[]}di.prototype.push=function(e){this.data.push(e)};di.prototype.top=function(){return this.data[this.data.length-1]};di.prototype.pop=function(){return this.data.pop()};di.prototype.is_empty=function(){return!this.data.length};function vi(e){if(e instanceof $a){e=e.valueOf()}var t=new s(e,{whitespace:true});var r=[];while(true){var n=t.peek(true);if(n===Fo){break}r.push(n);t.skip()}return r}function yi(e){var t=e.token,r=F(e,sn);if(t.match(/^"[\s\S]*"$/)&&t.match(/\n/)){var n=new RegExp("^ {1,"+(e.col+1)+"}","mg");t=t.replace(n,"")}return vn({token:t},r)}function mi(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(){};this.fn=e;this.cont=t}mi.prototype.toString=function(){return"#"};function gi(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r1&&arguments[1]!==undefined?arguments[1]:false;if(e instanceof $a){e=e.toString()}if(t){return vi(e)}else{var r=vi(e).map(function(e){if(e.token==="#\\ "){return e.token}return e.token.trim()}).filter(function(e){return e&&!e.match(/^;/)&&!e.match(/^#\|[\s\S]*\|#$/)});return Di(r)}}function Di(e){var t=0;var r=null;var n=[];for(var i=0;i0&&arguments[0]!==undefined?arguments[0]:null;if(e instanceof L){if(e.is_gensym()){return e}e=e.valueOf()}if(xi(e)){return L(e)}if(e!==null){return r(e,Symbol("#:".concat(e)))}t++;return r(t,Symbol("#:g".concat(t)))}}();function ki(e){var r=this;var n={pending:true,rejected:false,fulfilled:false,reason:undefined,type:undefined};e=e.then(function(e){n.type=us(e);n.fulfilled=true;n.pending=false;return e});$i(this,"_promise",e,{hidden:true});if(Xu(e["catch"])){e=e["catch"](function(e){n.rejected=true;n.pending=false;n.reason=e})}Object.keys(n).forEach(function(t){Object.defineProperty(r,"__".concat(t,"__"),{enumerable:true,get:function e(){return n[t]}})});$i(this,"__promise__",e);this.then=false}ki.prototype.then=function(e){return new ki(this.valueOf().then(e))};ki.prototype["catch"]=function(e){return new ki(this.valueOf()["catch"](e))};ki.prototype.valueOf=function(){if(!this._promise){throw new Error("QuotedPromise: invalid promise created")}return this._promise};ki.prototype.toString=function(){if(this.__pending__){return ki.pending_str}if(this.__rejected__){return ki.rejected_str}return"#")};ki.pending_str="#";ki.rejected_str="#";function Ci(e){if(Array.isArray(e)){return Promise.all(Oi(e)).then(Si)}return e}function Oi(e){var t=new Array(e.length),r=e.length;while(r--){var n=e[r];if(n instanceof ki){t[r]=new Bo(n)}else{t[r]=n}}return t}function Si(e){var t=new Array(e.length),r=e.length;while(r--){var n=e[r];if(n instanceof Bo){t[r]=n.valueOf()}else{t[r]=n}}return t}var Bi={LITERAL:Symbol["for"]("literal"),SPLICE:Symbol["for"]("splice"),SYMBOL:Symbol["for"]("symbol"),names:function e(){return Object.keys(this.__list__)},type:function e(t){return this.get(t).type},get:function e(t){return this.__list__[t]},off:function e(t){var r=this;var n=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(Array.isArray(t)){t.forEach(function(e){return r.off(e,n)})}else if(n===null){delete this.__events__[t]}else{this.__events__=this.__events__.filter(function(e){return e!==n})}},on:function e(t,r){var n=this;if(Array.isArray(t)){t.forEach(function(e){return n.on(e,r)})}else if(!this.__events__[t]){this.__events__[t]=[r]}else{this.__events__[t].push(r)}},trigger:function e(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i",new L("quote-promise"),Bi.LITERAL]];var Ri=Ni.map(function(e){return e[0]});Object.freeze(Ri);Object.defineProperty(Bi,"__builtins__",{writable:false,value:Ri});Ni.forEach(function(e){var t=j(e,3),r=t[0],n=t[1],i=t[2];Bi.append(r,n,i)});var s=function(){function p(e){var t=this;var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},n=r.whitespace,i=n===void 0?false:n;D(this,p);$i(this,"__input__",e.replace(/\r/g,""));var u={};["_i","_whitespace","_col","_newline","_line","_state","_next","_token","_prev_char"].forEach(function(r){Object.defineProperty(t,r,{configurable:false,enumerable:false,get:function e(){return u[r]},set:function e(t){u[r]=t}})});this._whitespace=i;this._i=this._line=this._col=this._newline=0;this._state=this._next=this._token=null;this._prev_char=""}A(p,[{key:"get",value:function e(t){return this.__internal[t]}},{key:"set",value:function e(t,r){this.__internal[t]=r}},{key:"token",value:function e(){var t=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(t){var r=this._line;if(this._whitespace&&this._token==="\n"){--r}return{token:this._token,col:this._col,offset:this._i,line:r}}return this._token}},{key:"peek",value:function e(){var t=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;if(this._i>=this.__input__.length){return Fo}if(this._token){return this.token(t)}var r=this.next_token();if(r){this._token=this.__input__.substring(this._i,this._next);return this.token(t)}return Fo}},{key:"skip",value:function e(){if(this._next!==null){this._token=null;this._i=this._next}}},{key:"read_line",value:function e(){var t=this.__input__.length;if(this._i>=t){return Fo}for(var r=this._i;r=r){return Fo}if(t+this._i>=r){return this.read_rest()}var n=this._i+t;var i=this.__input__.substring(this._i,n);var u=i.match(/\n/g);if(u){this._line+=u.length}this._i=n;return i}},{key:"peek_char",value:function e(){if(this._i>=this.__input__.length){return Fo}return za(this.__input__[this._i])}},{key:"read_char",value:function e(){var t=this.peek_char();this.skip_char();return t}},{key:"skip_char",value:function e(){if(this._i1&&arguments[1]!==undefined?arguments[1]:{},r=t.prev_char,n=t["char"],i=t.next_char;var u=j(e,4),a=u[0],o=u[1],s=u[2],f=u[3];if(e.length!==5){throw new Error("Lexer: Invald rule of length ".concat(e.length))}if(!n.match(a)){return false}if(!Ti(o,r)){return false}if(!Ti(s,i)){return false}if(f!==this._state){return false}return true}},{key:"next_token",value:function f(){if(this._i>=this.__input__.length){return false}var e=true;e:for(var t=this._i,r=this.__input__.length;t2&&arguments[2]!==undefined?arguments[2]:null;var i=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;if(t.length===0){throw new Error("Lexer: invalid literal rule")}if(t.length===1){return[[t,n,i,null,null]]}var u=[];for(var a=0,o=t.length;a1&&arguments[1]!==undefined?arguments[1]:{},r=t.env,n=t.meta,i=n===void 0?false:n,u=t.formatter,a=u===void 0?yi:u;D(this,o);if(e instanceof $a){e=e.toString()}$i(this,"_formatter",a,{hidden:true});$i(this,"__lexer__",new s(e));$i(this,"__env__",r);$i(this,"_meta",i,{hidden:true});$i(this,"_refs",[],{hidden:true});$i(this,"_state",{parentheses:0},{hidden:true})}A(o,[{key:"resolve",value:function e(t){return this.__env__&&this.__env__.get(t,{throwError:false})}},{key:"peek",value:function(){var e=B(z.mark(function e(){var r;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:r=this.__lexer__.peek(true);if(!(r===Fo)){t.next=4;break}return t.abrupt("return",Fo);case 4:if(!this.is_comment(r.token)){t.next=7;break}this.skip();return t.abrupt("continue",0);case 7:if(!(r.token==="#;")){t.next=14;break}this.skip();if(!(this.__lexer__.peek()===Fo)){t.next=11;break}throw new Error("Lexer: syntax error eof found after comment");case 11:t.next=13;return this._read_object();case 13:return t.abrupt("continue",0);case 14:return t.abrupt("break",17);case 17:r=this._formatter(r);if(!this._meta){t.next=20;break}return t.abrupt("return",r);case 20:return t.abrupt("return",r.token);case 21:case"end":return t.stop()}}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"reset",value:function e(){this._refs.length=0}},{key:"skip",value:function e(){this.__lexer__.skip()}},{key:"read",value:function(){var e=B(z.mark(function e(){var r;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:t.next=2;return this.peek();case 2:r=t.sent;this.skip();return t.abrupt("return",r);case 5:case"end":return t.stop()}}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"match_datum_label",value:function e(t){var r=t.match(/^#([0-9]+)=$/);return r&&r[1]}},{key:"match_datum_ref",value:function e(t){var r=t.match(/^#([0-9]+)#$/);return r&&r[1]}},{key:"is_open",value:function e(t){var r=["(","["].includes(t);if(r){this._state.parentheses++}return r}},{key:"is_close",value:function e(t){var r=[")","]"].includes(t);if(r){this._state.parentheses--}return r}},{key:"read_list",value:function(){var e=B(z.mark(function e(){var r,n,i,u;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:r=U,n=r;case 1:t.next=4;return this.peek();case 4:i=t.sent;if(!(i===Fo)){t.next=7;break}return t.abrupt("break",27);case 7:if(!this.is_close(i)){t.next=10;break}this.skip();return t.abrupt("break",27);case 10:if(!(i==="."&&r!==U)){t.next=17;break}this.skip();t.next=14;return this._read_object();case 14:n.cdr=t.sent;t.next=25;break;case 17:t.t0=M;t.next=20;return this._read_object();case 20:t.t1=t.sent;t.t2=U;u=new t.t0(t.t1,t.t2);if(r===U){r=u}else{n.cdr=u}n=u;case 25:t.next=1;break;case 27:return t.abrupt("return",r);case 28:case"end":return t.stop()}}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"read_value",value:function(){var e=B(z.mark(function e(){var r;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:t.next=2;return this.read();case 2:r=t.sent;if(!(r===Fo)){t.next=5;break}throw new Error("Parser: Expected token eof found");case 5:return t.abrupt("return",fi(r));case 6:case"end":return t.stop()}}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"is_comment",value:function e(t){return t.match(/^;/)||t.match(/^#\|/)&&t.match(/\|#$/)}},{key:"evaluate",value:function e(t){return _s(t,{env:this.__env__,error:function e(t){throw t}})}},{key:"read_object",value:function(){var e=B(z.mark(function e(){var r;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:this.reset();t.next=3;return this._read_object();case 3:r=t.sent;if(r instanceof Ui){r=r.valueOf()}if(!this._refs.length){t.next=7;break}return t.abrupt("return",this._resolve_object(r));case 7:return t.abrupt("return",r);case 8:case"end":return t.stop()}}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"ballanced",value:function e(){return this._state.parentheses===0}},{key:"ballancing_error",value:function e(t){var r=this._state.parentheses;var n=new Error("Parser: expected parenthesis but eof found");var i=new RegExp("\\){".concat(r,"}$"));n.__code__=[t.toString().replace(i,"")];throw n}},{key:"_resolve_object",value:function(){var t=B(z.mark(function e(r){var n=this;var i;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:if(!Array.isArray(r)){t.next=2;break}return t.abrupt("return",r.map(function(e){return n._resolve_object(e)}));case 2:if(!wu(r)){t.next=6;break}i={};Object.keys(r).forEach(function(e){i[e]=n._resolve_object(r[e])});return t.abrupt("return",i);case 6:if(!(r instanceof M)){t.next=8;break}return t.abrupt("return",this._resolve_pair(r));case 8:return t.abrupt("return",r);case 9:case"end":return t.stop()}}},e,this)}));function e(e){return t.apply(this,arguments)}return e}()},{key:"_resolve_pair",value:function(){var t=B(z.mark(function e(r){return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:if(!(r instanceof M)){t.next=15;break}if(!(r.car instanceof Ui)){t.next=7;break}t.next=4;return r.car.valueOf();case 4:r.car=t.sent;t.next=8;break;case 7:this._resolve_pair(r.car);case 8:if(!(r.cdr instanceof Ui)){t.next=14;break}t.next=11;return r.cdr.valueOf();case 11:r.cdr=t.sent;t.next=15;break;case 14:this._resolve_pair(r.cdr);case 15:return t.abrupt("return",r);case 16:case"end":return t.stop()}}},e,this)}));function e(e){return t.apply(this,arguments)}return e}()},{key:"_read_object",value:function(){var e=B(z.mark(function e(){var r,n,i,u,a,o,s,c,f;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:t.next=2;return this.peek();case 2:r=t.sent;if(!(r===Fo)){t.next=5;break}return t.abrupt("return",r);case 5:if(!ji(r)){t.next=39;break}n=Bi.get(r);i=Ii(r);this.skip();t.next=11;return this._read_object();case 11:a=t.sent;if(i){t.next=26;break}o=this.__env__.get(n.symbol);if(!(typeof o==="function")){t.next=26;break}if(!Pi(r)){t.next=19;break}return t.abrupt("return",o.call(this.__env__,a));case 19:if(!(a===U)){t.next=23;break}return t.abrupt("return",o.apply(this.__env__));case 23:if(!(a instanceof M)){t.next=25;break}return t.abrupt("return",o.apply(this.__env__,a.to_array(false)));case 25:throw new Error("Parse Error: Invalid parser extension "+"invocation ".concat(n.symbol));case 26:if(Pi(r)){u=new M(n.symbol,new M(a,U))}else{u=new M(n.symbol,a)}if(!i){t.next=29;break}return t.abrupt("return",u);case 29:if(!(o instanceof Vu)){t.next=38;break}t.next=32;return this.evaluate(u);case 32:s=t.sent;if(!(s instanceof M||s instanceof L)){t.next=35;break}return t.abrupt("return",M.fromArray([L("quote"),s]));case 35:return t.abrupt("return",s);case 38:throw new Error("Parse Error: invlid parser extension: "+n.symbol);case 39:c=this.match_datum_ref(r);if(!(c!==null)){t.next=45;break}this.skip();if(!this._refs[c]){t.next=44;break}return t.abrupt("return",new Ui(c,this._refs[c]));case 44:throw new Error("Parse Error: invalid datum label #".concat(c,"#"));case 45:f=this.match_datum_label(r);if(!(f!==null)){t.next=52;break}this.skip();this._refs[f]=this._read_object();return t.abrupt("return",this._refs[f]);case 52:if(!this.is_open(r)){t.next=57;break}this.skip();return t.abrupt("return",this.read_list());case 57:return t.abrupt("return",this.read_value());case 58:case"end":return t.stop()}}},e,this)}));function t(){return e.apply(this,arguments)}return t}()}]);return o}();var Ui=function(){function r(e,t){D(this,r);this.name=e;this.data=t}A(r,[{key:"valueOf",value:function e(){return this.data}}]);return r}();function Mi(e,t){return qi.apply(this,arguments)}function qi(){qi=e(z.mark(function e(r,n){var i,u;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:if(!n){if(qo){n=qo.get("**interaction-environment**",{throwError:false})}else{n=Yo}}i=new Li(r,{env:n});case 2:t.next=5;return P(i.read_object());case 5:u=t.sent;if(!i.ballanced()){i.ballancing_error(u)}if(!(u===Fo)){t.next=9;break}return t.abrupt("break",13);case 9:t.next=11;return u;case 11:t.next=2;break;case 13:case"end":return t.stop()}}},e)}));return qi.apply(this,arguments)}function Yi(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(e){return e};var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;if(ra(e)){var n=e.then(t);if(r===null){return n}else{return n["catch"](r)}}if(e instanceof Array){return Vi(e,t,r)}if(wu(e)){return zi(e,t,r)}return t(e)}function Vi(t,r,e){if(t.find(ra)){return Yi(Ci(t),function(e){if(Object.isFrozen(t)){Object.freeze(e)}return r(e)},e)}return r(t)}function zi(t,e,r){var i=Object.keys(t);var n=[],u=[];var a=i.length;while(a--){var o=i[a];var s=t[o];n[a]=s;if(ra(s)){u.push(s)}}if(u.length){return Yi(Ci(n),function(e){var n={};e.forEach(function(e,t){var r=i[t];n[r]=e});if(Object.isFrozen(t)){Object.freeze(n)}return n},r)}return e(t)}function $i(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{},i=n.hidden,u=i===void 0?false:i;Object.defineProperty(e,t,{value:r,configurable:true,enumerable:!u})}function Ji(e){return Ki.apply(this,arguments)}function Ki(){Ki=B(z.mark(function e(r){var n,i,u,a,o,s,c;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:n=[];i=false;u=false;t.prev=3;o=yn(r);case 5:t.next=7;return o.next();case 7:if(!(i=!(s=t.sent).done)){t.next=13;break}c=s.value;n.push(c);case 10:i=false;t.next=5;break;case 13:t.next=19;break;case 15:t.prev=15;t.t0=t["catch"](3);u=true;a=t.t0;case 19:t.prev=19;t.prev=20;if(!(i&&o["return"]!=null)){t.next=24;break}t.next=24;return o["return"]();case 24:t.prev=24;if(!u){t.next=27;break}throw a;case 27:return t.finish(24);case 28:return t.finish(19);case 29:return t.abrupt("return",n);case 30:case"end":return t.stop()}}},e,null,[[3,15,19,29],[20,,24,28]])}));return Ki.apply(this,arguments)}function Gi(e,t){if(t instanceof RegExp){return function(e){return String(e).match(t)}}else if(Xu(t)){return t}throw new Error("Invalid matcher")}function y(e,t,r,n){if(typeof e!=="string"){t=arguments[0];r=arguments[1];n=arguments[2];e=null}if(r){if(n){t.__doc__=r}else{t.__doc__=Hi(r)}}if(e){t.__name__=e}else if(t.name&&!Ca(t)){t.__name__=t.name}return t}function Hi(e){return e.split("\n").map(function(e){return e.trim()}).join("\n")}function Wi(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:1;var r=e.length;if(t<=0){throw Error("previousSexp: Invalid argument sexp = ".concat(t))}e:while(t--&&r>=0){var n=1;while(n>0){var i=e[--r];if(!i){break e}if(i==="("||i.token==="("){n--}else if(i===")"||i.token===")"){n++}}r--}return e.slice(r+1)}function Qi(e){if(!e||!e.length){return 0}var t=e.length;if(e[t-1].token==="\n"){return 0}while(--t){if(e[t].token==="\n"){var r=(e[t+1]||{}).token;if(r){return r.length}}}return 0}function Zi(e,t){return f(e,t)===t.length;function f(r,n){function e(e,t){var r=hn(e),n;try{for(r.s();!(n=r.n()).done;){var i=n.value;var u=f(i,t);if(u!==-1){return u}}}catch(e){r.e(e)}finally{r.f()}return-1}function t(){return r[u]===Symbol["for"]("symbol")&&!hi(n[o])}function i(){var e=r[u+1];var t=n[o+1];if(e!==undefined&&t!==undefined){return f([e],[t])}}var u=0;var a={};for(var o=0;o0){continue}}else if(t()){return-1}}else if(r[u]instanceof Array){var c=f(r[u],n.slice(o));if(c===-1||c+o>n.length){return-1}o+=c-1;u++;continue}else{return-1}u++}if(r.length!==u){return-1}return n.length}}function Xi(e){this.__code__=e.replace(/\r/g,"")}Xi.defaults={offset:0,indent:2,exceptions:{specials:[/^(?:#:)?(?:define(?:-values|-syntax|-macro|-class|-record-type)?|(?:call-with-(?:input-file|output-file|port))|lambda|let-env|try|catch|when|unless|while|syntax-rules|(let|letrec)(-syntax|\*)?)$/],shift:{1:["&","#"]}}};Xi.match=Zi;Xi.prototype._options=function e(t){var r=Xi.defaults;if(typeof t==="undefined"){return Object.assign({},r)}var n=t&&t.exceptions||{};var i=n.specials||[];var u=n.shift||{1:[]};return vn(vn(vn({},r),t),{},{exceptions:{specials:[].concat(q(r.exceptions.specials),q(i)),shift:vn(vn({},u),{},{1:[].concat(q(r.exceptions.shift[1]),q(u[1]))})}})};Xi.prototype.indent=function e(t){var r=wi(this.__code__,true);return this._indent(r,t)};Xi.exception_shift=function(u,e){function t(e){if(!e.length){return false}if(e.indexOf(u)!==-1){return true}else{var t=e.filter(function(e){return e instanceof RegExp});if(!t.length){return false}var r=hn(t),n;try{for(r.s();!(n=r.n()).done;){var i=n.value;if(u.match(i)){return true}}}catch(e){r.e(e)}finally{r.f()}}return false}if(t(e.exceptions.specials)){return e.indent}var r=e.exceptions.shift;for(var n=0,i=Object.entries(r);n0){t.offset=0}if(n.toString()===e.toString()&&ms(n)){return t.offset+n[0].col}else if(n.length===1){return t.offset+n[0].col+1}else{var u=-1;if(i){var a=Xi.exception_shift(i.token,t);if(a!==-1){u=a}}if(u===-1){u=Xi.exception_shift(n[1].token,t)}if(u!==-1){return t.offset+n[0].col+u}else if(n[0].line3&&n[1].line===n[3].line){if(n[1].token==="("||n[1].token==="["){return t.offset+n[1].col}return t.offset+n[3].col}else if(n[0].line===n[1].line){return t.offset+t.indent+n[0].col}else{var o=n.slice(2);for(var s=0;s")};eu.prototype.match=function(e){return e.match(this.pattern)};function tu(){for(var e=arguments.length,t=new Array(e),r=0;r")};Xi.Pattern=tu;Xi.Ahead=eu;var ru=/^[[(]$/;var nu=/^[\])]$/;var iu=/[^()[\]]/;var uu=new eu(/[^)\]]/);var au=Symbol["for"]("*");var ou=new tu([ru,au,nu],[iu],"+");var su=new tu([ru,au,nu],"+");var cu=new tu([Symbol["for"]("symbol")],"?");var fu=new tu([Symbol["for"]("symbol")],"*");var lu=[ru,fu,nu];var hu=new tu([ru,Symbol["for"]("symbol"),au,nu],"+");var pu=vu("define","lambda","define-macro","syntax-rules");var _u=/^(?!.*\b(?:[()[\]]|define(?:-macro)?|let(?:\*|rec|-env|-syntax|)?|lambda|syntax-rules)\b).*$/;var du=/^(?:#:)?(let(?:\*|rec|-env|-syntax)?)$/;function vu(){for(var e=arguments.length,t=new Array(e),r=0;r0&&!i[e]){i[e]=Wi(n,e)}});var u=hn(t),p;try{for(u.s();!(p=u.n()).done;){var a=j(p.value,3),_=a[0],o=a[1],s=a[2];o=o.valueOf();var d=o>0?i[o]:n;var v=d.filter(function(e){return e.trim()&&!ji(e)});var y=h(d);var m=Zi(_,v);var g=e.slice(r).find(function(e){return e.trim()&&!ji(e)});if(m&&(s instanceof eu&&s.match(g)||!s)){var c=r-y;if(e[c]!=="\n"){if(!e[c].trim()){e[c]="\n"}else{e.splice(c,0,"\n");r++}}r+=y;continue e}}}catch(e){u.e(e)}finally{u.f()}}this.__code__=e.join("");return this};Xi.prototype._spaces=function(e){return new Array(e+1).join(" ")};Xi.prototype.format=function c(e){var t=this.__code__.replace(/[ \t]*\n[ \t]*/g,"\n ");var r=wi(t,true);var n=this._options(e);var i=0;var u=0;for(var a=0;a0&&arguments[0]!==undefined?arguments[0]:true;var n=new Map;function i(e){if(e instanceof M){if(n.has(e)){return n.get(e)}var t=new M;n.set(e,t);if(r){t.car=i(e.car)}else{t.car=e.car}t.cdr=i(e.cdr);t[ga]=e[ga];return t}return e}return i(this)};M.prototype.last_pair=function(){var e=this;while(true){if(e.cdr===U){return e}e=e.cdr}};M.prototype.to_array=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var t=[];if(this.car instanceof M){if(e){t.push(this.car.to_array())}else{t.push(this.car)}}else{t.push(this.car.valueOf())}if(this.cdr instanceof M){t=t.concat(this.cdr.to_array())}return t};M.fromArray=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;if(e instanceof M||r&&e instanceof Array&&e[ya]){return e}if(t===false){var n=U;for(var i=e.length;i--;){n=new M(e[i],n)}return n}if(e.length&&!(e instanceof Array)){e=q(e)}var u=U;var a=e.length;while(a--){var o=e[a];if(o instanceof Array){o=M.fromArray(o,t,r)}else if(typeof o==="string"){o=$a(o)}else if(typeof o==="number"&&!Number.isNaN(o)){o=C(o)}u=new M(o,u)}return u};M.prototype.to_object=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var t=this;var r={};while(true){if(t instanceof M&&t.car instanceof M){var n=t.car;var i=n.car;if(i instanceof L){i=i.__name__}if(i instanceof $a){i=i.valueOf()}var u=n.cdr;if(u instanceof M){u=u.to_object(e)}if(ts(u)){if(!e){u=u.valueOf()}}r[i]=u;t=t.cdr}else{break}}return r};M.fromPairs=function(e){return e.reduce(function(e,t){return new M(new M(new L(t[0]),t[1]),e)},U)};M.fromObject=function(t){var e=Object.keys(t).map(function(e){return[e,t[e]]});return M.fromPairs(e)};M.prototype.reduce=function(e){var t=this;var r=U;while(true){if(t!==U){r=e(r,t.car);t=t.cdr}else{break}}return r};M.prototype.reverse=function(){if(this.haveCycles()){throw new Error("You can't reverse list that have cycles")}var e=this;var t=U;while(e!==U){var r=e.cdr;e.cdr=t;t=e;e=r}return t};M.prototype.transform=function(n){function i(e){if(e instanceof M){if(e.replace){delete e.replace;return e}var t=n(e.car);if(t instanceof M){t=i(t)}var r=n(e.cdr);if(r instanceof M){r=i(r)}return new M(t,r)}return e}return i(this)};M.prototype.map=function(e){if(typeof this.car!=="undefined"){return new M(e(this.car),this.cdr===U?U:this.cdr.map(e))}else{return U}};var bu=new Map;function wu(e){return e&&_(e)==="object"&&e.constructor===Object}var Du=Object.getOwnPropertyNames(Array.prototype);var Eu=[];Du.forEach(function(e){Eu.push(Array[e],Array.prototype[e])});function Au(e){e=sa(e);return Eu.includes(e)}function xu(e){return Xu(e)&&(Ca(e)||e.__doc__)}function Fu(r){var e=r.constructor||Object;var n=wu(r);var i=Xu(r[Symbol.asyncIterator])||Xu(r[Symbol.iterator]);var u;if(bu.has(e)){u=bu.get(e)}else{bu.forEach(function(e,t){t=sa(t);if(r.constructor===t&&(t===Object&&n&&!i||t!==Object)){u=e}})}return u}var ku=new Map;[[true,"#t"],[false,"#f"],[null,"null"],[undefined,"#"]].forEach(function(e){var t=j(e,2),r=t[0],n=t[1];ku.set(r,n)});function Cu(r){if(r&&_(r)==="object"){var n={};var e=Object.getOwnPropertySymbols(r);e.forEach(function(e){var t=e.toString().replace(/Symbol\(([^)]+)\)/,"$1");n[t]=Pu(r[e])});var t=Object.getOwnPropertyNames(r);t.forEach(function(e){var t=r[e];if(t&&_(t)==="object"&&t.constructor===Object){n[e]=Cu(t)}else{n[e]=Pu(t)}});return n}return r}function Ou(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function Su(e,t){return e.hasOwnProperty(t)&&Xu(e.toString)}function Bu(e){if(Ba(e)){return"#"}var t=e.prototype&&e.prototype.constructor;if(Xu(t)&&Ca(t)){if(e[ba]&&t.hasOwnProperty("__name__")){var r=t.__name__;if($a.isString(r)){r=r.toString();return"#")}return"#"}}if(e.hasOwnProperty("__name__")){var n=e.__name__;if(_(n)==="symbol"){n=Ai(n)}if(typeof n==="string"){return"#")}}if(Su(e,"toString")){return e.toString()}else if(e.name&&!Ca(e)){return"#")}else{return"#"}}var ju=new Map;[[Error,function(e){return e.message}],[M,function(e,t){var r=t.quote,n=t.skip_cycles,i=t.pair_args;if(!n){e.markCycles()}return e.toString.apply(e,[r].concat(q(i)))}],[za,function(e,t){var r=t.quote;if(r){return e.toString()}return e.valueOf()}],[$a,function(e,t){var r=t.quote;e=e.toString();if(r){return JSON.stringify(e).replace(/\\n/g,"\n")}return e}],[RegExp,function(e){return"#"+e.toString()}]].forEach(function(e){var t=j(e,2),r=t[0],n=t[1];ju.set(r,n)});var Iu=[L,C,Vu,jo,ho,po,So,ki];function Pu(e,t,c){if(typeof jQuery!=="undefined"&&e instanceof jQuery.fn.init){return"#"}if(ku.has(e)){return ku.get(e)}if(Nu(e)){return"#"}if(e){var r=e.constructor;if(ju.has(r)){for(var n=arguments.length,f=new Array(n>3?n-3:0),i=3;i"}if(e===null){return"null"}if(_(e)==="object"){var a=e.constructor;if(!a){a=Object}var o;if(typeof a.__class__==="string"){o=a.__class__}else{var s=Fu(e);if(s){if(Xu(s)){return s(e,t)}else{throw new Error("toString: Invalid repr value")}}o=a.name}if(Xu(e.toString)&&Ca(e.toString)){return e.toString().valueOf()}if(us(e)==="instance"){if(Ca(a)&&a.__name__){o=a.__name__.valueOf()}else if(!Ba(a)){o="instance"}}if(ns(e,Symbol.iterator)){if(o){return"#")}return"#"}if(ns(e,Symbol.asyncIterator)){if(o){return"#")}return"#"}if(o!==""){return"#<"+o+">"}return"#"}if(typeof e!=="string"){return e.toString()}return e}function Nu(e){return e&&_(e)==="object"&&e.hasOwnProperty&&e.hasOwnProperty("constructor")&&typeof e.constructor==="function"&&e.constructor.prototype===e}M.prototype.markCycles=function(){Ru(this);return this};M.prototype.haveCycles=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(!e){return this.haveCycles("car")||this.haveCycles("cdr")}return!!(this[ga]&&this[ga][e])};function Ru(e){var t=[];var i=[];var u=[];function a(e){if(!t.includes(e)){t.push(e)}}function o(e,t,r,n){if(r instanceof M){if(n.includes(r)){if(!u.includes(r)){u.push(r)}if(!e[ga]){e[ga]={}}e[ga][t]=r;if(!i.includes(e)){i.push(e)}return true}}}var s=gi(function e(t,r){if(t instanceof M){delete t.ref;delete t[ga];a(t);r.push(t);var n=o(t,"car",t.car,r);var i=o(t,"cdr",t.cdr,r);if(!n){s(t.car,r.slice())}if(!i){return new mi(function(){return e(t.cdr,r.slice())})}}});function r(e,t){if(e[ga][t]instanceof M){var r=n.indexOf(e[ga][t]);e[ga][t]="#".concat(r,"#")}}s(e,[]);var n=t.filter(function(e){return u.includes(e)});n.forEach(function(e,t){e[ma]="#".concat(t,"=")});i.forEach(function(e){r(e,"car");r(e,"cdr")})}M.prototype.toString=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=t.nested,n=r===void 0?false:r;var i=[];if(this[ma]){i.push(this[ma]+"(")}else if(!n){i.push("(")}var u;if(this[ga]&&this[ga].car){u=this[ga].car}else{u=Pu(this.car,e,true)}if(u!==undefined){i.push(u)}if(this.cdr instanceof M){if(this[ga]&&this[ga].cdr){i.push(" . ");i.push(this[ga].cdr)}else{if(this.cdr[ma]){i.push(" . ")}else{i.push(" ")}var a=this.cdr.toString(e,{nested:true});i.push(a)}}else if(this.cdr!==U){i=i.concat([" . ",Pu(this.cdr,e,true)])}if(!n||this[ma]){i.push(")")}return i.join("")};M.prototype.set=function(e,t){this[e]=t;if(t instanceof M){this.markCycles()}};M.prototype.append=function(e){if(e instanceof Array){return this.append(M.fromArray(e))}var t=this;if(t.car===undefined){if(e instanceof M){this.car=e.car;this.cdr=e.cdr}else{this.car=e}}else if(e!==U){while(true){if(t instanceof M&&t.cdr!==U){t=t.cdr}else{break}}t.cdr=e}return this};M.prototype.serialize=function(){return[this.car,this.cdr]};M.prototype[Symbol.iterator]=function(){var r=this;return{next:function e(){var t=r;r=t.cdr;if(t===U){return{value:undefined,done:true}}else{return{value:t.car,done:false}}}}};function Tu(e){return e<0?-e:e}function Lu(e,t){var r=m(t),n=r[0],i=r.slice(1);while(i.length>0){var u=i,a=j(u,1),o=a[0];if(!e(n,o)){return false}var s=i;var c=m(s);n=c[0];i=c.slice(1)}return true}function Uu(e,t){if(Xu(e)){return Xu(t)&&sa(e)===sa(t)}else if(e instanceof C){if(!(t instanceof C)){return false}var r;if(e.__type__===t.__type__){if(e.__type__==="complex"){r=e.__im__.__type__===t.__im__.__type__&&e.__re__.__type__===t.__re__.__type__}else{r=true}if(r&&e.cmp(t)===0){if(e.valueOf()===0){return Object.is(e.valueOf(),t.valueOf())}return true}}return false}else if(typeof e==="number"){if(typeof t!=="number"){return false}if(Number.isNaN(e)){return Number.isNaN(t)}if(e===Number.NEGATIVE_INFINITY){return t===Number.NEGATIVE_INFINITY}if(e===Number.POSITIVE_INFINITY){return t===Number.POSITIVE_INFINITY}return Uu(C(e),C(t))}else if(e instanceof za){if(!(t instanceof za)){return false}return e.__char__===t.__char__}else{return e===t}}function Mu(e,t){if(us(e)!==us(t)){return false}if(!qu(e)){return false}if(e instanceof RegExp){return e.source===t.source}if(e instanceof $a){return e.valueOf()===t.valueOf()}return Uu(e,t)}function qu(e){return e instanceof L||$a.isString(e)||e===U||e===null||e instanceof za||e instanceof C||e===true||e===false}var Yu=function(){if(Math.trunc){return Math.trunc}else{return function(e){if(e===0){return 0}else if(e<0){return Math.ceil(e)}else{return Math.floor(e)}}}}();function Vu(e,t,r,n){if(typeof this!=="undefined"&&this.constructor!==Vu||typeof this==="undefined"){return new Vu(e,t)}h("Macro",e,"string",1);h("Macro",t,"function",2);if(r){if(n){this.__doc__=r}else{this.__doc__=Hi(r)}}this.__name__=e;this.__fn__=t}Vu.defmacro=function(e,t,r,n){var i=new Vu(e,t,r,n);i.__defmacro__=true;return i};Vu.prototype.invoke=function(e,t,r){var n=t.env,i=t.dynamic_scope,u=t.error;var a={dynamic_scope:i,error:u,macro_expand:r};var o=this.__fn__.call(n,e,a,this.__name__);return o};Vu.prototype.toString=function(){return"#")};var zu="define-macro";var $u=-1e4;function Ju(c){return function(){var r=B(z.mark(function e(r,m){var u,g,n,i,s,D,E,A,x,F,k,b,a,w,o;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:o=function e(){o=B(z.mark(function e(r,n,i){var h,u,a,p,o,_,s,d,c,v,f,l,y;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:if(!(r instanceof M&&r.car instanceof L)){t.next=50;break}if(!r[ya]){t.next=3;break}return t.abrupt("return",r);case 3:h=r.car.valueOf();u=i.get(r.car,{throwError:false});a=D(r.car);p=a||E(u,r)||A(u);if(!(p&&r.cdr.car instanceof M)){t.next=28;break}if(!a){t.next=15;break}g=F(r.cdr.car);t.next=12;return b(r.cdr.car,n);case 12:o=t.sent;t.next=17;break;case 15:g=x(r.cdr.car);o=r.cdr.car;case 17:t.t0=M;t.t1=r.car;t.t2=M;t.t3=o;t.next=23;return w(r.cdr.cdr,n,i);case 23:t.t4=t.sent;t.t5=new t.t2(t.t3,t.t4);return t.abrupt("return",new t.t0(t.t1,t.t5));case 28:if(!k(h,u)){t.next=50;break}_=u instanceof Ku?r:r.cdr;t.next=32;return u.invoke(_,vn(vn({},m),{},{env:i}),true);case 32:s=t.sent;if(!(u instanceof Ku)){t.next=41;break}d=s,c=d.expr,v=d.scope;if(!(c instanceof M)){t.next=40;break}if(!(n!==-1&&n<=1||n<$u)){t.next=38;break}return t.abrupt("return",c);case 38:if(n!==-1){n=n-1}return t.abrupt("return",w(c,n,v));case 40:s=c;case 41:if(!(s instanceof L)){t.next=43;break}return t.abrupt("return",Io(s));case 43:if(!(s instanceof M)){t.next=48;break}if(!(n!==-1&&n<=1||n<$u)){t.next=46;break}return t.abrupt("return",s);case 46:if(n!==-1){n=n-1}return t.abrupt("return",w(s,n,i));case 48:if(!qu(s)){t.next=50;break}return t.abrupt("return",s);case 50:f=r.car;if(!(f instanceof M)){t.next=55;break}t.next=54;return w(f,n,i);case 54:f=t.sent;case 55:l=r.cdr;if(!(l instanceof M)){t.next=60;break}t.next=59;return w(l,n,i);case 59:l=t.sent;case 60:y=new M(f,l);return t.abrupt("return",y);case 62:case"end":return t.stop()}}},e)}));return o.apply(this,arguments)};w=function e(t,r,n){return o.apply(this,arguments)};a=function e(){a=B(z.mark(function e(r,n){var i;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:if(!(r===U)){t.next=2;break}return t.abrupt("return",U);case 2:i=r.car;t.t0=M;t.t1=M;t.t2=i.car;t.next=8;return w(i.cdr,n,u);case 8:t.t3=t.sent;t.t4=new t.t1(t.t2,t.t3);t.next=12;return b(r.cdr);case 12:t.t5=t.sent;return t.abrupt("return",new t.t0(t.t4,t.t5));case 14:case"end":return t.stop()}}},e)}));return a.apply(this,arguments)};b=function e(t,r){return a.apply(this,arguments)};k=function e(t,r){return r instanceof Vu&&r.__defmacro__&&!g.includes(t)};F=function e(t){return[].concat(q(g),q(t.to_array(false).map(function(e){if(e instanceof M){return e.car.valueOf()}throw new Error("macroexpand: Invalid let binding")})))};x=function e(t){var r=[];while(true){if(t!==U){if(t instanceof L){r.push(t.valueOf());break}r.push(t.car.valueOf());t=t.cdr}else{break}}return[].concat(q(g),r)};A=function e(t){return t===i};E=function e(t,r){return t===s&&r.cdr.car instanceof M};D=function e(t){var r=t.valueOf();return n.includes(r)};u=m["env"]=this;g=[];n=["let","let*","letrec"];i=qo.get("lambda");s=qo.get("define");if(!(r.cdr instanceof M&&C.isNumber(r.cdr.car))){t.next=21;break}t.t0=Io;t.next=19;return w(r,r.cdr.car.valueOf(),u);case 19:t.t1=t.sent.car;return t.abrupt("return",(0,t.t0)(t.t1));case 21:if(!c){t.next=27;break}t.t2=Io;t.next=25;return w(r,1,u);case 25:t.t3=t.sent.car;return t.abrupt("return",(0,t.t2)(t.t3));case 27:t.t4=Io;t.next=30;return w(r,-1,u);case 30:t.t5=t.sent.car;return t.abrupt("return",(0,t.t4)(t.t5));case 32:case"end":return t.stop()}}},e,this)}));return function(e,t){return r.apply(this,arguments)}}()}function Ku(e,t){this.__env__=t;this.__fn__=e;this.__defmacro__=true}Ku.__merge_env__=Symbol["for"]("merge");Ku.prototype=Object.create(Vu.prototype);Ku.prototype.invoke=function(e,t,r){var n=t.error,i=t.env;var u={error:n,env:i,dynamic_scope:this.__env__,macro_expand:r};return this.__fn__.call(i,e,u,this.__name__||"syntax")};Ku.prototype.constructor=Ku;Ku.prototype.toString=function(){if(this.__name__){return"#")}return"#"};Ku.className="syntax";var Gu=function(e){u(r,e);var t=fn(r);function r(){D(this,r);return t.apply(this,arguments)}return A(r)}(Ku);Ku.Parameter=Gu;function Hu(e,t,w,D){var r=arguments.length>4&&arguments[4]!==undefined?arguments[4]:{};var E={"...":{symbols:{},lists:[]},symbols:{}};var A=r.expansion,k=r.define;function x(e){if(Cn()){console.log(e)}}x(w);function F(e,t){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:[];var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;x({code:t&&Pu(t,true),pattern:e&&Pu(e,true)});if(qu(e)&&!(e instanceof L)){return Mu(e,t)}if(e instanceof L&&w.includes(e.literal())){var c=A.ref(t);if(L.is(t,e)){if(typeof c==="undefined"){return true}return c===k||c===qo}return false}if(e instanceof M&&e.car instanceof M&&e.car.cdr instanceof M&&L.is(e.car.cdr.car,D)){x(">> 0");if(t===U){x({pattern:e.toString()});if(e.car.car instanceof L){if(e.car.cdr instanceof M&&L.is(e.car.cdr.car,D)){var f=e.car.car.valueOf();var l=e.last_pair();if(L.is(l.car,D)){E["..."].symbols[f]=null;return true}else{return false}}var h=e.car.car.valueOf();if(E["..."].symbols[h]){throw new Error("syntax: named ellipsis can only "+"appear onces")}E["..."].symbols[h]=t}}}if(e instanceof M&&e.cdr instanceof M&&L.is(e.cdr.car,D)){if(e.cdr.cdr!==U){if(e.cdr.cdr instanceof M){var p=e.cdr.cdr.length();var _=t.length();var i=t;while(_-1>p){i=i.cdr;_--}var d=i.cdr;i.cdr=U;if(!F(e.cdr.cdr,d,r,n)){return false}}}if(e.car instanceof L){var u=e.car.__name__;if(E["..."].symbols[u]&&!r.includes(u)&&!n){throw new Error("syntax: named ellipsis can only appear onces")}x(">> 1");if(t===U){x(">> 2");if(n){x("NIL");E["..."].symbols[u]=U}else{x("NULL");E["..."].symbols[u]=null}}else if(t instanceof M&&(t.car instanceof M||t.car===U)){x(">> 3 "+n);if(n){if(E["..."].symbols[u]){var a=E["..."].symbols[u];if(a===U){a=new M(U,new M(t,U))}else{a=a.append(new M(t,U))}E["..."].symbols[u]=a}else{E["..."].symbols[u]=new M(t,U)}}else{x(">> 4");E["..."].symbols[u]=new M(t,U)}}else{x(">> 6");if(t instanceof M){x(">> 7 "+n);r.push(u);if(!E["..."].symbols[u]){E["..."].symbols[u]=new M(t,U)}else{var v=E["..."].symbols[u];E["..."].symbols[u]=v.append(new M(t,U))}x({IIIIII:E["..."].symbols[u].toString()})}else{x(">> 8");return false}}return true}else if(e.car instanceof M){var y=q(r);if(t===U){x(">> 9");E["..."].lists.push(U);return true}x(">> 10");var m=t;while(m instanceof M){if(!F(e.car,m.car,y,true)){return false}m=m.cdr}return true}return false}if(e instanceof L){if(L.is(e,D)){throw new Error("syntax: invalid usage of ellipsis")}x(">> 11");var o=e.__name__;if(w.includes(o)){return true}x({name:o,ellipsis:n});if(n){E["..."].symbols[o]=E["..."].symbols[o]||[];E["..."].symbols[o].push(t)}E.symbols[o]=t;if(!E.symbols[o]);return true}if(e instanceof M&&t instanceof M){x(">> 12");x({a:12,code:t&&t.toString(),pattern:e.toString()});if(t.cdr===U){var g=e.car instanceof L&&e.cdr instanceof L;if(g){if(!F(e.car,t.car,r,n)){return false}x(">> 12 | 1");var s=e.cdr.valueOf();if(!(s in E.symbols)){E.symbols[s]=U}s=e.car.valueOf();if(!(s in E.symbols)){E.symbols[s]=t.car}return true}}x({pattern:e.toString(),code:t.toString()});if(e.cdr instanceof M&&e.car instanceof L&&e.cdr.cdr instanceof M&&e.cdr.car instanceof L&&L.is(e.cdr.cdr.car,D)&&e.cdr.cdr.cdr instanceof M&&!L.is(e.cdr.cdr.cdr.car,D)&&F(e.car,t.car,r,n)&&F(e.cdr.cdr.cdr,t.cdr,r,n)){var b=e.cdr.car.__name__;x({pattern:e.car.toString(),code:t.car.toString(),name:b});if(w.includes(b)){return true}E["..."].symbols[b]=null;return true}x("recur");if(F(e.car,t.car,r,n)&&F(e.cdr,t.cdr,r,n)){return true}}else if(e===U&&(t===U||t===undefined)){return true}else if(e.car instanceof M&&L.is(e.car.car,D)){throw new Error("syntax: invalid usage of ellipsis")}else{return false}}if(F(e,t)){return E}}function Wu(e,i){function u(t){if(t instanceof M){if(!i.length){return t}var e=u(t.car);var r=u(t.cdr);return new M(e,r)}else if(t instanceof L){var n=i.find(function(e){return e.gensym===t});if(n){return L(n.name)}return t}else{return t}}return u(e)}function Qu(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var O=e.bindings,t=e.expr,S=e.scope,a=e.symbols,f=e.names,B=e.ellipsis;var c={};function o(e){if(e instanceof L){return true}return["string","symbol"].includes(_(e))}function j(e){if(!o(e)){var t=us(e);throw new Error("syntax: internal error, need symbol got ".concat(t))}var r=e.valueOf();if(r===B){throw new Error("syntax: internal error, ellipis not transformed")}var n=_(r);if(["string","symbol"].includes(n)){if(r in O.symbols){return O.symbols[r]}else if(n==="string"&&r.match(/\./)){var i=r.split(".");var u=i[0];if(u in O.symbols){return M.fromArray([L("."),O.symbols[u]].concat(i.slice(1).map(function(e){return $a(e)})))}}}if(a.includes(r)){return L(r)}return s(r)}function I(e){if(Cn()){console.log(e)}}function s(e){if(!c[e]){var t=S.ref(e);var r=Fi(e);if(t){var n=S.get(e);S.set(r,n)}else{var i=S.get(e,{throwError:false});if(typeof i!=="undefined"){S.set(r,i)}}f.push({name:e,gensym:r});c[e]=r;if(typeof e==="string"&&e.match(/\./)){var u=e.split(".").filter(Boolean),a=m(u),o=a[0],s=a.slice(1);if(c[o]){Fa(r,"__object__",[c[o]].concat(q(s)))}}}return c[e]}function P(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:function(){};var i=r.nested;I(" ==> "+e.toString(true));I(t);if(e instanceof L){var u=e.valueOf();I("[t 1");if(t[u]){if(t[u]instanceof M){var c=t[u],f=c.car,l=c.cdr;if(i){var h=f.car,p=f.cdr;if(p!==U){n(u,new M(p,U))}return h}if(l!==U){n(u,l)}return f}else if(t[u]instanceof Array){n(u,t[u].slice(1));return t[u][0]}}return j(u)}if(e instanceof M){if(e.car instanceof L&&e.cdr instanceof M&&L.is(e.cdr.car,B)){I("[t 2");var a=e.car.valueOf();var o=t[a];I({expr:e.toString(true),name:a,bindings:t,item:o});if(o===null){return}else if(o){I({b:t[a].toString()});if(o instanceof M){I("[t 2 Pair "+i);I({______:o.toString()});var s=o.car,_=o.cdr;if(i){if(_!==U){I("|| next 1");n(a,_)}I({car:s.toString()});return s}else{if(s.cdr!==U){I("|| next 2");n(a,new M(s.cdr,_))}I({car:s.car.toString()});return s.car}}else if(o instanceof Array){I("[t 2 Array "+i);if(i){n(a,o.slice(1));return M.fromArray(o)}else{var d=o.slice(1);if(d.length){n(a,d)}return o[0]}}else{return o}}}I("[t 3 recur "+e.toString());var v=P(e.car,t,r,n);var y=P(e.cdr,t,r,n);return new M(v,y)}return e}function R(t,r){var e=Object.values(t);var n=Object.getOwnPropertySymbols(t);if(n.length){e.push.apply(e,q(n.map(function(e){return t[e]})))}return e.length&&e.every(function(e){if(e===null){return!r}return e instanceof M||e===U||e instanceof Array&&e.length})}function T(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function N(i){var n=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},e=n.disabled;I("traverse>> "+Pu(i));if(i instanceof M){if(!e&&i.car instanceof M&&L.is(i.car.car,B)){return N(i.car.cdr,{disabled:true})}if(i.cdr instanceof M&&L.is(i.cdr.car,B)&&!e){I(">> 1");var t=O["..."].symbols;var f=Object.values(t);if(f.length&&f.every(function(e){return e===null})){return N(i.cdr.cdr,{disabled:e})}var l=T(t);var u=i.car instanceof L&&L.is(i.cdr.cdr.car,B);if(i.car instanceof M||u){if(O["..."].lists[0]===U){return U}var h=i.car;if(u){h=new M(i.car,new M(i.cdr.car,U))}I(">> 2");var a;if(l.length){I(">> 2 (a)");var o=vn({},t);a=U;var p=function e(){if(!R(o)){return"break"}var n={};var t=function e(t,r){n[t]=r};var r=P(h,o,{nested:true},t);if(r!==undefined){if(u){if(a===U){a=r}else{a=a.append(r)}}else{a=new M(r,a)}}o=n};while(true){var _=p();if(_==="break")break}if(a!==U&&!u){a=a.reverse()}if(i.cdr.cdr!==U&&!L.is(i.cdr.cdr.car,B)){var d=N(i.cdr.cdr,{disabled:e});return a.append(d)}return a}else{I(">> 3");var v=P(i.car,t,{nested:true});if(v){return new M(v,U)}return U}}else if(i.car instanceof L){I(">> 4");if(L.is(i.cdr.cdr.car,B)){I(">> 4 (a)")}else{I(">> 4 (b)")}var y=i.car.__name__;var s=Y({},y,t[y]);var m=t[y]===null;var c=U;var g=function e(){if(!R(s,true)){I({bind:s});return"break"}var n={};var t=function e(t,r){n[t]=r};var r=P(i,s,{nested:false},t);I({value:r.toString()});if(typeof r!=="undefined"){c=new M(r,c)}s=n};while(true){var b=g();if(b==="break")break}if(c!==U){c=c.reverse()}if(i.cdr instanceof M){if(i.cdr.cdr instanceof M||i.cdr.cdr instanceof L){var w=N(i.cdr.cdr,{disabled:e});if(m){return w}I("<<<< 1");c.append(w)}}I("<<<< 2");return c}}var D=N(i.car,{disabled:e});var r;var E;if(i.car instanceof L){var A=S.get(i.car,{throwError:false});E=A instanceof Vu&&A.__name__==="syntax-rules"}if(E){if(i.cdr.car instanceof L){r=new M(N(i.cdr.car,{disabled:e}),new M(i.cdr.cdr.car,N(i.cdr.cdr.cdr,{disabled:e})))}else{r=new M(i.cdr.car,N(i.cdr.cdr,{disabled:e}))}I("REST >>>> "+r.toString())}else{r=N(i.cdr,{disabled:e})}I({a:true,car:Pu(i.car),cdr:Pu(i.cdr),head:Pu(D),rest:Pu(r)});return new M(D,r)}if(i instanceof L){if(e&&L.is(i,B)){return i}var x=Object.keys(O["..."].symbols);var F=i.literal();if(x.includes(F)){var k="missing ellipsis symbol next to name `".concat(F,"'");throw new Error("syntax-rules: ".concat(k))}var C=j(i);if(typeof C!=="undefined"){return C}}return i}return N(t,{})}function Zu(e){return na(e)||e===U||e===null}function Xu(e){return typeof e==="function"&&typeof e.bind==="function"}function ea(e){return e instanceof hs}function ta(e){return Xu(e)||ea(e)}function ra(e){if(e instanceof ki){return false}if(e instanceof Promise){return true}return e&&Xu(e.then)}function na(e){return typeof e==="undefined"}function ia(e){switch(_(e)){case"string":return $a(e);case"bigint":return C(e);case"number":if(Number.isNaN(e)){return Uo}else{return C(e)}}return e}function ua(n,i){var e=Object.getOwnPropertyNames(n);var t=Object.getOwnPropertySymbols(n);e.concat(t).forEach(function(e){var t=i(n[e]);var r=Object.getOwnPropertyDescriptor(n,e);if(!r||r.writable&&n[e]!==t){n[e]=t}});return n}function aa(t){var e=[$a,C].some(function(e){return t instanceof e});if(e){return t.valueOf()}if(t instanceof Array){return t.map(aa)}if(t instanceof ki){delete t.then}if(wu(t)){return ua(t,aa)}return t}function oa(e,t){if(e instanceof M){e.markCycles();return Io(e)}if(Xu(e)){if(t){return ca(e,t)}}return ia(e)}function sa(e){if(la(e)){return e[va]}return e}function ca(e,t){if(e[Symbol["for"]("__bound__")]){return e}var r=e.bind(t);var n=Object.getOwnPropertyNames(e);var i=hn(n),u;try{for(i.s();!(u=i.n()).done;){var a=u.value;if(xa(a)){try{r[a]=e[a]}catch(e){}}}}catch(e){i.e(e)}finally{i.f()}Fa(r,"__fn__",e);Fa(r,"__context__",t);Fa(r,"__bound__",true);if(Ba(e)){Fa(r,"__native__",true)}if(wu(t)&&Ca(e)){Fa(r,"__method__",true)}r.valueOf=function(){return e};return r}function fa(e){return la(e)&&e[Symbol["for"]("__context__")]===Object}function la(e){return!!(Xu(e)&&e[va])}function ha(e){if(Xu(e)){var t=e[da];if(t&&(t===Gs||t.constructor&&t.constructor.__class__)){return true}}return false}function pa(e){return e instanceof ho||e instanceof po}function _a(e){if(Xu(e)){if(pa(e[da])){return true}}return false}var da=Symbol["for"]("__context__");var va=Symbol["for"]("__fn__");var ya=Symbol["for"]("__data__");var ma=Symbol["for"]("__ref__");var ga=Symbol["for"]("__cycles__");var ba=Symbol["for"]("__class__");var wa=Symbol["for"]("__method__");var Da=Symbol["for"]("__prototype__");var Ea=Symbol["for"]("__lambda__");var Aa=["name","length","caller","callee","arguments","prototype"];function xa(e){return!Aa.includes(e)}function Fa(e,t,r){Object.defineProperty(e,Symbol["for"](t),{get:function e(){return r},set:function e(){},configurable:false,enumerable:false})}function ka(t,r){try{Object.defineProperty(t,"length",{get:function e(){return r}});return t}catch(e){var n=new Array(r).fill(0).map(function(e,t){return"a"+t}).join(",");var i=new Function("f","return function(".concat(n,") {\n return f.apply(this, arguments);\n };"));return i(t)}}function Ca(e){return e&&e[Ea]}function Oa(e){return e&&e[wa]}function Sa(e){return Ca(e)&&!e[Da]&&!Oa(e)&&!_a(e)}function Ba(e){var t=Symbol["for"]("__native__");return Xu(e)&&e.toString().match(/\{\s*\[native code\]\s*\}/)&&(e.name.match(/^bound /)&&e[t]===true||!e.name.match(/^bound /)&&!e[t])}function ja(e){var g;switch(e){case Symbol["for"]("letrec"):g="letrec";break;case Symbol["for"]("let"):g="let";break;case Symbol["for"]("let*"):g="let*";break;default:throw new Error("Invalid let_macro value")}return Vu.defmacro(g,function(t,e){var f=e.dynamic_scope,l=e.error,n=e.macro_expand;var h;if(t.car instanceof L){if(!(t.cdr.car instanceof M||t.cdr.car===U)){throw new Error("let require list of pairs")}var r;if(t.cdr.car===U){h=U;r=U}else{r=t.cdr.car.map(function(e){return e.car});h=t.cdr.car.map(function(e){return e.cdr.car})}return M.fromArray([L("letrec"),[[t.car,M(L("lambda"),M(r,t.cdr.cdr))]],M(t.car,h)])}else if(n){return}var p=this;h=qo.get("list->array")(t.car);var _=p.inherit(g);var d,v;if(g==="let*"){v=_}else if(g==="let"){d=[]}var y=0;function m(){var e=new M(new L("begin"),t.cdr);return _s(e,{env:_,dynamic_scope:f,error:l})}return function t(){var r=h[y++];if(f){f=g==="let*"?_:p}if(!r){if(d&&d.length){var e=d.map(function(e){return e.value});var n=e.filter(ra);if(n.length){return Ci(e).then(function(e){for(var t=0,r=e.length;t1&&arguments[1]!==undefined?arguments[1]:{},r=t.dynamic_scope,n=t.error;var i=this;if(r){r=this}var u=e;var a=[];while(u instanceof M){a.push(_s(u.car,{env:i,dynamic_scope:r,error:n}));u=u.cdr}var o=a.filter(ra).length;if(o){return Ci(a).then(s.bind(this))}else{return s.call(this,a)}})}function Pa(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n2?n-2:0),u=2;u1&&arguments[1]!==undefined?arguments[1]:null;return function(){for(var e=arguments.length,t=new Array(e),r=0;r1?e-1:0),r=1;r=a){return u.apply(this,n)}else{return i}}return i.apply(this,arguments)}}function Va(n,i){h("limit",i,"function",2);return function(){for(var e=arguments.length,t=new Array(e),r=0;r1){e=e.toLowerCase();if(za.__names__[e]){t=e;e=za.__names__[e]}else{throw new Error("Internal: Unknown named character")}}else{t=za.__rev_names__[e]}Object.defineProperty(this,"__char__",{value:e,enumerable:true});if(t){Object.defineProperty(this,"__name__",{value:t,enumerable:true})}}za.__names__=Un;za.__rev_names__={};Object.keys(za.__names__).forEach(function(e){var t=za.__names__[e];za.__rev_names__[t]=e});za.prototype.toUpperCase=function(){return za(this.__char__.toUpperCase())};za.prototype.toLowerCase=function(){return za(this.__char__.toLowerCase())};za.prototype.toString=function(){return"#\\"+(this.__name__||this.__char__)};za.prototype.valueOf=za.prototype.serialize=function(){return this.__char__};function $a(e){if(typeof this!=="undefined"&&!(this instanceof $a)||typeof this==="undefined"){return new $a(e)}if(e instanceof Array){this.__string__=e.map(function(e,t){h("LString",e,"character",t+1);return e.toString()}).join("")}else{this.__string__=e.valueOf()}}{var Ja=["length","constructor"];var Ka=Object.getOwnPropertyNames(String.prototype).filter(function(e){return!Ja.includes(e)});var Ga=function e(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r0){r.push(this.__string__.substring(0,e))}r.push(t);if(e1&&arguments[1]!==undefined?arguments[1]:false;if(e instanceof C){return e}if(typeof this!=="undefined"&&!(this instanceof C)||typeof this==="undefined"){return new C(e,t)}if(typeof e==="undefined"){throw new Error("Invalid LNumber constructor call")}var r=C.getType(e);if(C.types[r]){return C.types[r](e,t)}var n=e instanceof Array&&$a.isString(e[0])&&C.isNumber(e[1]);if(e instanceof C){return C(e.value)}if(!C.isNumber(e)&&!n){throw new Error("You can't create LNumber from ".concat(us(e)))}if(e===null){e=0}var i;if(n){var c=e,u=j(c,2),a=u[0],o=u[1];if(a instanceof $a){a=a.valueOf()}if(o instanceof C){o=o.valueOf()}var f=a.match(/^([+-])/);var l=false;if(f){a=a.replace(/^[+-]/,"");if(f[1]==="-"){l=true}}}if(Number.isNaN(e)){return uo(e)}else if(typeof BigInt!=="undefined"){if(typeof e!=="bigint"){if(n){var s;switch(o){case 8:s="0o";break;case 16:s="0x";break;case 2:s="0b";break;case 10:s="";break}if(typeof s==="undefined"){var h=BigInt(o);i=q(a).map(function(e,t){return BigInt(parseInt(e,o))*ro(h,BigInt(t))}).reduce(function(e,t){return e+t})}else{i=BigInt(s+a)}}else{i=BigInt(e)}if(l){i*=BigInt(-1)}}else{i=e}return lo(i,true)}else if(typeof xn!=="undefined"&&!(e instanceof xn)){if(e instanceof Array){return lo(p(xn,q(e)))}return lo(new xn(e))}else if(n){this.constant(parseInt(a,o),"integer")}else{this.constant(e,"integer")}}C.prototype.constant=function(e,t){Object.defineProperty(this,"__value__",{value:e,enumerable:true});Object.defineProperty(this,"__type__",{value:t,enumerable:true})};C.types={float:function e(t){return new uo(t)},complex:function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!C.isComplex(t)){t={im:0,re:t}}return new io(t,r)},rational:function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(!C.isRational(t)){t={num:t,denom:1}}return new fo(t,r)}};C.prototype.serialize=function(){return this.__value__};C.prototype.isNaN=function(){return Number.isNaN(this.__value__)};C.prototype.gcd=function(e){var t=this.abs();e=e.abs();if(e.cmp(t)===1){var r=t;t=e;e=r}while(true){t=t.rem(e);if(t.cmp(0)===0){return e}e=e.rem(t);if(e.cmp(0)===0){return t}}};C.isFloat=function e(t){return t instanceof uo||Number(t)===t&&t%1!==0};C.isNumber=function(e){return e instanceof C||C.isNative(e)||C.isBN(e)};C.isComplex=function(e){if(!e){return false}var t=e instanceof io||(C.isNumber(e.im)||Number.isNaN(e.im))&&(C.isNumber(e.re)||Number.isNaN(e.re));return t};C.isRational=function(e){if(!e){return false}return e instanceof fo||C.isNumber(e.num)&&C.isNumber(e.denom)};C.isInteger=function(e){if(!(C.isNative(e)||e instanceof C)){return false}if(C.isFloat(e)){return false}if(C.isRational(e)){return false}if(C.isComplex(e)){return false}return true};C.isNative=function(e){return typeof e==="bigint"||typeof e==="number"};C.isBigInteger=function(e){return e instanceof lo||typeof e==="bigint"||C.isBN(e)};C.isBN=function(e){return typeof xn!=="undefined"&&e instanceof xn};C.getArgsType=function(e,t){if(e instanceof uo||t instanceof uo){return uo}if(e instanceof lo||t instanceof lo){return lo}return C};C.prototype.toString=function(e){if(Number.isNaN(this.__value__)){return"+nan.0"}if(e>2&&e<36){return this.__value__.toString(e)}return this.__value__.toString()};C.prototype.asType=function(e){var t=C.getType(this);return C.types[t]?C.types[t](e):C(e)};C.prototype.isBigNumber=function(){return typeof this.__value__==="bigint"||typeof xn!=="undefined"&&!(this.value instanceof xn)};["floor","ceil","round"].forEach(function(e){C.prototype[e]=function(){if(this["float"]||C.isFloat(this.__value__)){return C(Math[e](this.__value__))}else{return C(Math[e](this.valueOf()))}}});C.prototype.valueOf=function(){if(C.isNative(this.__value__)){return Number(this.__value__)}else if(C.isBN(this.__value__)){return this.__value__.toNumber()}};var Za=function(){var e=function e(t,r){return[t,r]};return{bigint:{bigint:e,float:function e(t,r){return[uo(t.valueOf()),r]},rational:function e(t,r){return[{num:t,denom:1},r]},complex:function e(t,r){return[{im:0,re:t},r]}},integer:{integer:e,float:function e(t,r){return[uo(t.valueOf()),r]},rational:function e(t,r){return[{num:t,denom:1},r]},complex:function e(t,r){return[{im:0,re:t},r]}},float:{bigint:function e(t,r){return[t,r&&uo(r.valueOf())]},integer:function e(t,r){return[t,r&&uo(r.valueOf())]},float:e,rational:function e(t,r){return[t,r&&uo(r.valueOf())]},complex:function e(t,r){return[{re:t,im:uo(0)},r]}},complex:{bigint:t("bigint"),integer:t("integer"),float:t("float"),rational:t("rational"),complex:function f(e,t){var r=C.coerce(e.__re__,t.__re__),n=j(r,2),i=n[0],u=n[1];var a=C.coerce(e.__im__,t.__im__),o=j(a,2),s=o[0],c=o[1];return[{im:s,re:i},{im:c,re:u}]}},rational:{bigint:function e(t,r){return[t,r&&{num:r,denom:1}]},integer:function e(t,r){return[t,r&&{num:r,denom:1}]},float:function e(t,r){return[uo(t.valueOf()),r]},rational:e,complex:function e(t,r){return[{im:Xa(t.__type__,r.__im__.__type__,0)[0],re:Xa(t.__type__,r.__re__.__type__,t)[0]},{im:Xa(t.__type__,r.__im__.__type__,r.__im__)[0],re:Xa(t.__type__,r.__re__.__type__,r.__re__)[0]}]}}};function t(r){return function(e,t){return[{im:Xa(r,e.__im__.__type__,0,e.__im__)[1],re:Xa(r,e.__re__.__type__,0,e.__re__)[1]},{im:Xa(r,e.__im__.__type__,0,0)[1],re:Xa(r,t.__type__,0,t)[1]}]}}}();function Xa(e,t,r,n){return Za[e][t](r,n)}C.coerce=function(e,t){var r=C.getType(e);var n=C.getType(t);if(!Za[r]){throw new Error("LNumber::coerce unknown lhs type ".concat(r))}else if(!Za[r][n]){throw new Error("LNumber::coerce unknown rhs type ".concat(n))}var i=Za[r][n](e,t);return i.map(function(e){return C(e,true)})};C.prototype.coerce=function(e){if(!(typeof e==="number"||e instanceof C)){throw new Error("LNumber: you can't coerce ".concat(us(e)))}if(typeof e==="number"){e=C(e)}return C.coerce(this,e)};C.getType=function(e){if(e instanceof C){return e.__type__}if(C.isFloat(e)){return"float"}if(C.isComplex(e)){return"complex"}if(C.isRational(e)){return"rational"}if(typeof e==="number"){return"integer"}if(typeof BigInt!=="undefined"&&typeof e!=="bigint"||typeof xn!=="undefined"&&!(e instanceof xn)){return"bigint"}};C.prototype.isFloat=function(){return!!(C.isFloat(this.__value__)||this["float"])};var eo={add:"+",sub:"-",mul:"*",div:"/",rem:"%",or:"|",and:"&",neg:"~",shl:">>",shr:"<<"};var to={};Object.keys(eo).forEach(function(t){to[eo[t]]=t;C.prototype[t]=function(e){return this.op(eo[t],e)}});C._ops={"*":function e(t,r){return t*r},"+":function e(t,r){return t+r},"-":function e(t,r){if(typeof r==="undefined"){return-t}return t-r},"/":function e(t,r){return t/r},"%":function e(t,r){return t%r},"|":function e(t,r){return t|r},"&":function e(t,r){return t&r},"~":function e(t){return~t},">>":function e(t,r){return t>>r},"<<":function e(t,r){return t<1&&arguments[1]!==undefined?arguments[1]:false;if(typeof this!=="undefined"&&!(this instanceof io)||typeof this==="undefined"){return new io(e,t)}if(e instanceof io){return io({im:e.__im__,re:e.__re__})}if(C.isNumber(e)&&t){if(!t){return Number(e)}}else if(!C.isComplex(e)){var r="Invalid constructor call for LComplex expect &(:im :re ) object but got ".concat(Pu(e));throw new Error(r)}var n=e.im instanceof C?e.im:C(e.im);var i=e.re instanceof C?e.re:C(e.re);this.constant(n,i)}io.prototype=Object.create(C.prototype);io.prototype.constructor=io;io.prototype.constant=function(e,t){Object.defineProperty(this,"__im__",{value:e,enumerable:true});Object.defineProperty(this,"__re__",{value:t,enumerable:true});Object.defineProperty(this,"__type__",{value:"complex",enumerable:true})};io.prototype.serialize=function(){return{re:this.__re__,im:this.__im__}};io.prototype.toRational=function(e){if(C.isFloat(this.__im__)&&C.isFloat(this.__re__)){var t=uo(this.__im__).toRational(e);var r=uo(this.__re__).toRational(e);return io({im:t,re:r})}return this};io.prototype.pow=function(e){throw new Error("Not yet implemented")};io.prototype.add=function(e){return this.complex_op("add",e,function(e,t,r,n){return{re:e.add(t),im:r.add(n)}})};io.prototype.factor=function(){if(this.__im__ instanceof uo||this.__im__ instanceof uo){var e=this.__re__,t=this.__im__;var r,n;if(e instanceof uo){r=e.toRational().mul(e.toRational())}else{r=e.mul(e)}if(t instanceof uo){n=t.toRational().mul(t.toRational())}else{n=t.mul(t)}return r.add(n)}else{return this.__re__.mul(this.__re__).add(this.__im__.mul(this.__im__))}};io.prototype.modulus=function(){return this.factor().sqrt()};io.prototype.conjugate=function(){return io({re:this.__re__,im:this.__im__.sub()})};io.prototype.sqrt=function(){var e=this.modulus();var t,r;if(e.cmp(0)===0){t=r=e}else if(this.__re__.cmp(0)===1){t=uo(.5).mul(e.add(this.__re__)).sqrt();r=this.__im__.div(t).div(2)}else{r=uo(.5).mul(e.sub(this.__re__)).sqrt();if(this.__im__.cmp(0)===-1){r=r.sub()}t=this.__im__.div(r).div(2)}return io({im:r,re:t})};io.prototype.div=function(e){if(C.isNumber(e)&&!C.isComplex(e)){if(!(e instanceof C)){e=C(e)}var t=this.__re__.div(e);var r=this.__im__.div(e);return io({re:t,im:r})}else if(!C.isComplex(e)){throw new Error("[LComplex::div] Invalid value")}if(this.cmp(e)===0){var n=this.coerce(e),i=j(n,2),f=i[0],u=i[1];var l=f.__im__.div(u.__im__);return l.coerce(u.__re__)[0]}var h=this.coerce(e),a=j(h,2),p=a[0],o=a[1];var s=o.factor();var _=o.conjugate();var c=p.mul(_);if(!C.isComplex(c)){return c.div(s)}var d=c.__re__.op("/",s);var v=c.__im__.op("/",s);return io({re:d,im:v})};io.prototype.sub=function(e){return this.complex_op("sub",e,function(e,t,r,n){return{re:e.sub(t),im:r.sub(n)}})};io.prototype.mul=function(e){return this.complex_op("mul",e,function(e,t,r,n){var i={re:e.mul(t).sub(r.mul(n)),im:e.mul(n).add(t.mul(r))};return i})};io.prototype.complex_op=function(e,t,i){var u=this;var r=function e(t,r){var n=i(u.__re__,t,u.__im__,r);if("im"in n&&"re"in n){if(n.im.cmp(0)===0){return n.re}return io(n,true)}return n};if(typeof t==="undefined"){return r()}if(C.isNumber(t)&&!C.isComplex(t)){if(!(t instanceof C)){t=C(t)}var n=t.asType(0);t={__im__:n,__re__:t}}else if(!C.isComplex(t)){throw new Error("[LComplex::".concat(e,"] Invalid value"))}var a=t.__re__ instanceof C?t.__re__:this.__re__.asType(t.__re__);var o=t.__im__ instanceof C?t.__im__:this.__im__.asType(t.__im__);return r(a,o)};io._op={"+":"add","-":"sub","*":"mul","/":"div"};io.prototype._op=function(e,t){var r=io._op[e];return this[r](t)};io.prototype.cmp=function(e){var t=this.coerce(e),r=j(t,2),n=r[0],i=r[1];var u=n.__re__.coerce(i.__re__),a=j(u,2),o=a[0],f=a[1];var s=o.cmp(f);if(s!==0){return s}else{var l=n.__im__.coerce(i.__im__),c=j(l,2),h=c[0],p=c[1];return h.cmp(p)}};io.prototype.valueOf=function(){return[this.__re__,this.__im__].map(function(e){return e.valueOf()})};io.prototype.toString=function(){var e;if(this.__re__.cmp(0)!==0){e=[Pu(this.__re__)]}else{e=[]}var t=this.__im__.valueOf();var r=[Number.NEGATIVE_INFINITY,Number.POSITIVE_INFINITY].includes(t);var n=Pu(this.__im__);if(!r&&!Number.isNaN(t)){var i=this.__im__.cmp(0);if(i<0||i===0&&this.__im__._minus){e.push("-")}else{e.push("+")}n=n.replace(/^-/,"")}e.push(n);e.push("i");return e.join("")};function uo(e){if(typeof this!=="undefined"&&!(this instanceof uo)||typeof this==="undefined"){return new uo(e)}if(!C.isNumber(e)){throw new Error("Invalid constructor call for LFloat")}if(e instanceof C){return uo(e.valueOf())}if(typeof e==="number"){if(Object.is(e,-0)){Object.defineProperty(this,"_minus",{value:true})}this.constant(e,"float")}}uo.prototype=Object.create(C.prototype);uo.prototype.constructor=uo;uo.prototype.toString=function(){if(this.__value__===Number.NEGATIVE_INFINITY){return"-inf.0"}if(this.__value__===Number.POSITIVE_INFINITY){return"+inf.0"}if(Number.isNaN(this.__value__)){return"+nan.0"}var e=this.__value__.toString();if(!C.isFloat(this.__value__)&&!e.match(/e/i)){var t=e+".0";return this._minus?"-"+t:t}return e.replace(/^([0-9]+)e/,"$1.0e")};uo.prototype._op=function(e,t){if(t instanceof C){t=t.__value__}var r=C._ops[e];if(e==="/"&&this.__value__===0&&t===0){return NaN}return uo(r(this.__value__,t))};uo.prototype.toRational=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){return ao(this.__value__.valueOf())}return oo(e.valueOf())(this.__value__.valueOf())};uo.prototype.sqrt=function(){var e=this.valueOf();if(this.cmp(0)<0){var t=uo(Math.sqrt(-e));return io({re:0,im:t})}return uo(Math.sqrt(e))};uo.prototype.abs=function(){var e=this.valueOf();if(e<0){e=-e}return uo(e)};var ao=oo(1e-10);function oo(n){return function(e){var t=function e(n,t,r){var i=function e(t,r){return r0){i=co(n,r)}else if(n.cmp(r)<=0){i=r}else if(r.cmp(0)>0){i=co(r,n)}else if(t.cmp(0)<0){i=C(co(n.sub(),r.sub())).sub()}else{i=C(0)}if(C.isFloat(t)||C.isFloat(e)){return uo(i)}return i}function co(e,t){var r=C(e).floor();var n=C(t).floor();if(e.cmp(r)<1){return r}else if(r.cmp(n)===0){var i=C(1).div(t.sub(n));var u=C(1).div(e.sub(r));return r.add(C(1).div(co(i,u)))}else{return r.add(C(1))}}function fo(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;if(typeof this!=="undefined"&&!(this instanceof fo)||typeof this==="undefined"){return new fo(e,t)}if(!C.isRational(e)){throw new Error("Invalid constructor call for LRational")}var r,n;if(e instanceof fo){r=C(e.__num__);n=C(e.__denom__)}else{r=C(e.num);n=C(e.denom)}if(!t&&n.cmp(0)!==0){var i=r.op("%",n).cmp(0)===0;if(i){return C(r.div(n))}}this.constant(r,n)}fo.prototype=Object.create(C.prototype);fo.prototype.constructor=fo;fo.prototype.constant=function(e,t){Object.defineProperty(this,"__num__",{value:e,enumerable:true});Object.defineProperty(this,"__denom__",{value:t,enumerable:true});Object.defineProperty(this,"__type__",{value:"rational",enumerable:true})};fo.prototype.serialize=function(){return{num:this.__num__,denom:this.__denom__}};fo.prototype.pow=function(e){var t=e.cmp(0);if(t===0){return C(1)}if(t===-1){e=e.sub();var r=this.__denom__.pow(e);var n=this.__num__.pow(e);return fo({num:r,denom:n})}var i=this;e=e.valueOf();while(e>1){i=i.mul(this);e--}return i};fo.prototype.sqrt=function(){var e=this.__num__.sqrt();var t=this.__denom__.sqrt();if(e instanceof uo||t instanceof uo){return e.div(t)}return fo({num:e,denom:t})};fo.prototype.abs=function(){var e=this.__num__;var t=this.__denom__;if(e.cmp(0)===-1){e=e.sub()}if(t.cmp(0)!==1){t=t.sub()}return fo({num:e,denom:t})};fo.prototype.cmp=function(e){return C(this.valueOf(),true).cmp(e)};fo.prototype.toString=function(){var e=this.__num__.gcd(this.__denom__);var t,r;if(e.cmp(1)!==0){t=this.__num__.div(e);if(t instanceof fo){t=C(t.valueOf(true))}r=this.__denom__.div(e);if(r instanceof fo){r=C(r.valueOf(true))}}else{t=this.__num__;r=this.__denom__}var n=this.cmp(0)<0;if(n){if(t.abs().cmp(r.abs())===0){return t.toString()}}else if(t.cmp(r)===0){return t.toString()}return t.toString()+"/"+r.toString()};fo.prototype.valueOf=function(e){if(this.__denom__.cmp(0)===0){if(this.__num__.cmp(0)<0){return Number.NEGATIVE_INFINITY}return Number.POSITIVE_INFINITY}if(e){return C._ops["/"](this.__num__.value,this.__denom__.value)}return uo(this.__num__.valueOf()).div(this.__denom__.valueOf())};fo.prototype.mul=function(e){if(!(e instanceof C)){e=C(e)}if(C.isRational(e)){var t=this.__num__.mul(e.__num__);var r=this.__denom__.mul(e.__denom__);return fo({num:t,denom:r})}var n=C.coerce(this,e),i=j(n,2),u=i[0],a=i[1];return u.mul(a)};fo.prototype.div=function(e){if(!(e instanceof C)){e=C(e)}if(C.isRational(e)){var t=this.__num__.mul(e.__denom__);var r=this.__denom__.mul(e.__num__);return fo({num:t,denom:r})}var n=C.coerce(this,e),i=j(n,2),u=i[0],a=i[1];var o=u.div(a);return o};fo.prototype._op=function(e,t){return this[to[e]](t)};fo.prototype.sub=function(e){if(typeof e==="undefined"){return this.mul(-1)}if(!(e instanceof C)){e=C(e)}if(C.isRational(e)){var t=e.__num__.sub();var r=e.__denom__;return this.add(fo({num:t,denom:r}))}if(!(e instanceof C)){e=C(e).sub()}else{e=e.sub()}var n=C.coerce(this,e),i=j(n,2),u=i[0],a=i[1];return u.add(a)};fo.prototype.add=function(e){if(!(e instanceof C)){e=C(e)}if(C.isRational(e)){var t=this.__denom__;var r=e.__denom__;var n=this.__num__;var i=e.__num__;var u,a;if(t!==r){a=r.mul(n).add(i.mul(t));u=t.mul(r)}else{a=n.add(i);u=t}return fo({num:a,denom:u})}if(C.isFloat(e)){return uo(this.valueOf()).add(e)}var o=C.coerce(this,e),s=j(o,2),c=s[0],f=s[1];return c.add(f)};function lo(e,t){if(typeof this!=="undefined"&&!(this instanceof lo)||typeof this==="undefined"){return new lo(e,t)}if(e instanceof lo){return lo(e.__value__,e._native)}if(!C.isBigInteger(e)){throw new Error("Invalid constructor call for LBigInteger")}this.constant(e,"bigint");Object.defineProperty(this,"_native",{value:t})}lo.prototype=Object.create(C.prototype);lo.prototype.constructor=lo;lo.bn_op={"+":"iadd","-":"isub","*":"imul","/":"idiv","%":"imod","|":"ior","&":"iand","~":"inot","<<":"ishrn",">>":"ishln"};lo.prototype.serialize=function(){return this.__value__.toString()};lo.prototype._op=function(e,t){if(typeof t==="undefined"){if(C.isBN(this.__value__)){e=lo.bn_op[e];return lo(this.__value__.clone()[e](),false)}return lo(C._ops[e](this.__value__),true)}if(C.isBN(this.__value__)&&C.isBN(t.__value__)){e=lo.bn_op[e];return lo(this.__value__.clone()[e](t),false)}var r=C._ops[e](this.__value__,t.__value__);if(e==="/"){var n=this.op("%",t).cmp(0)===0;if(n){return C(r)}return fo({num:this,denom:t})}return lo(r,true)};lo.prototype.sqrt=function(){var e;var t=this.cmp(0)<0;if(C.isNative(this.__value__)){e=C(Math.sqrt(t?-this.valueOf():this.valueOf()))}else if(C.isBN(this.__value__)){e=t?this.__value__.neg().sqrt():this.__value__.sqrt()}if(t){return io({re:0,im:e})}return e};C.NaN=C(NaN);function ho(e){var n=this;if(typeof this!=="undefined"&&!(this instanceof ho)||typeof this==="undefined"){return new ho(e)}h("InputPort",e,"function");$i(this,"__type__",xo);var i;Object.defineProperty(this,"__parser__",{enumerable:true,get:function e(){return i},set:function e(t){h("InputPort::__parser__",t,"parser");i=t}});this._read=e;this._with_parser=this._with_init_parser.bind(this,B(z.mark(function e(){var r;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:if(n.char_ready()){t.next=5;break}t.next=3;return n._read();case 3:r=t.sent;i=new Li(r,{env:n});case 5:return t.abrupt("return",n.__parser__);case 6:case"end":return t.stop()}}},e)})));this.char_ready=function(){return!!this.__parser__&&this.__parser__.__lexer__.peek()!==Fo};this._make_defaults()}ho.prototype._make_defaults=function(){this.read=this._with_parser(function(e){return e.read_object()});this.read_line=this._with_parser(function(e){return e.__lexer__.read_line()});this.read_char=this._with_parser(function(e){return e.__lexer__.read_char()});this.read_string=this._with_parser(function(e,t){if(!C.isInteger(t)){var r=C.getType(t);Qo("read-string",r,"integer")}return e.__lexer__.read_string(t.valueOf())});this.peek_char=this._with_parser(function(e){return e.__lexer__.peek_char()})};ho.prototype._with_init_parser=function(o,s){var c=this;return B(z.mark(function e(){var r,n,i,u,a=arguments;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:t.next=2;return o.call(c);case 2:r=t.sent;for(n=a.length,i=new Array(n),u=0;u"};function po(e){if(typeof this!=="undefined"&&!(this instanceof po)||typeof this==="undefined"){return new po(e)}h("OutputPort",e,"function");$i(this,"__type__",xo);this.write=e}po.prototype.is_open=function(){return this._closed!==true};po.prototype.close=function(){Object.defineProperty(this,"_closed",{get:function e(){return true},set:function e(){},configurable:false,enumerable:false});this.write=function(){throw new Error("output-port: port is closed")}};po.prototype.flush=function(){};po.prototype.toString=function(){return"#"};var _o=function(e){u(n,e);var r=fn(n);function n(e){var t;D(this,n);t=r.call(this,function(){var e;return(e=t)._write.apply(e,arguments)});h("BufferedOutputPort",e,"function");$i(i(t),"_fn",e,{hidden:true});$i(i(t),"_buffer",[],{hidden:true});return t}A(n,[{key:"flush",value:function e(){if(this._buffer.length){this._fn(this._buffer.join(""));this._buffer.length=0}}},{key:"_write",value:function e(){var t=this;for(var r=arguments.length,n=new Array(r),i=0;i"};vo.prototype.valueOf=function(){return this.__buffer__.map(function(e){return e.valueOf()}).join("")};function yo(e,t){var r=this;if(typeof this!=="undefined"&&!(this instanceof yo)||typeof this==="undefined"){return new yo(e,t)}h("OutputFilePort",e,"string");$i(this,"__filename__",e);$i(this,"_fd",t.valueOf(),{hidden:true});$i(this,"__type__",xo);this.write=function(e){if(!$a.isString(e)){e=Pu(e)}else{e=e.valueOf()}r.fs().write(r._fd,e,function(e){if(e){throw e}})}}yo.prototype=Object.create(po.prototype);yo.prototype.constructor=yo;yo.prototype.fs=function(){if(!this._fs){this._fs=this.internal("fs")}return this._fs};yo.prototype.internal=function(e){return Yo.get("**internal-env**").get(e)};yo.prototype.close=function(){var n=this;return new Promise(function(t,r){n.fs().close(n._fd,function(e){if(e){r(e)}else{$i(n,"_fd",null,{hidden:true});po.prototype.close.call(n);t()}})})};yo.prototype.toString=function(){return"#")};function mo(e,t){var r=this;if(typeof this!=="undefined"&&!(this instanceof mo)||typeof this==="undefined"){return new mo(e)}h("InputStringPort",e,"string");t=t||qo;e=e.valueOf();this._with_parser=this._with_init_parser.bind(this,function(){if(!r.__parser__){r.__parser__=new Li(e,{env:t})}return r.__parser__});$i(this,"__type__",xo);this._make_defaults()}mo.prototype.char_ready=function(){return true};mo.prototype=Object.create(ho.prototype);mo.prototype.constructor=mo;mo.prototype.toString=function(){return"#"};function go(e){if(typeof this!=="undefined"&&!(this instanceof go)||typeof this==="undefined"){return new go(e)}h("InputByteVectorPort",e,"uint8array");$i(this,"__vector__",e);$i(this,"__type__",Ao);var r=0;Object.defineProperty(this,"__index__",{enumerable:true,get:function e(){return r},set:function e(t){h("InputByteVectorPort::__index__",t,"number");if(t instanceof C){t=t.valueOf()}if(typeof t==="bigint"){t=Number(t)}if(Math.floor(t)!==t){throw new Error("InputByteVectorPort::__index__ value is "+"not integer")}r=t}})}go.prototype=Object.create(ho.prototype);go.prototype.constructor=go;go.prototype.toString=function(){return"#"};go.prototype.close=function(){var t=this;$i(this,"__vector__",U);["read_u8","close","peek_u8","read_u8_vector"].forEach(function(e){t[e]=function(){throw new Error("Input-binary-port: port is closed")}});this.char_ready=function(){return false}};go.prototype.u8_ready=function(){return true};go.prototype.peek_u8=function(){if(this.__index__>=this.__vector__.length){return Fo}return this.__vector__[this.__index__]};go.prototype.skip=function(){if(this.__index__<=this.__vector__.length){++this.__index__}};go.prototype.read_u8=function(){var e=this.peek_u8();this.skip();return e};go.prototype.read_u8_vector=function(e){if(typeof e==="undefined"){e=this.__vector__.length}else if(e>this.__index__+this.__vector__.length){e=this.__index__+this.__vector__.length}if(this.peek_u8()===Fo){return Fo}return this.__vector__.slice(this.__index__,e)};function bo(){if(typeof this!=="undefined"&&!(this instanceof bo)||typeof this==="undefined"){return new bo}$i(this,"__type__",Ao);$i(this,"_buffer",[],{hidden:true});this.write=function(e){h("write",e,["number","uint8array"]);if(C.isNumber(e)){this._buffer.push(e.valueOf())}else{var t;(t=this._buffer).push.apply(t,q(Array.from(e)))}};Object.defineProperty(this,"__buffer__",{enumerable:true,get:function e(){return Uint8Array.from(this._buffer)}})}bo.prototype=Object.create(po.prototype);bo.prototype.constructor=bo;bo.prototype.close=function(){po.prototype.close.call(this);$i(this,"_buffer",null,{hidden:true})};bo.prototype._close_guard=function(){if(this._closed){throw new Error("output-port: binary port is closed")}};bo.prototype.write_u8=function(e){h("OutputByteVectorPort::write_u8",e,"number");this.write(e)};bo.prototype.write_u8_vector=function(e){h("OutputByteVectorPort::write_u8_vector",e,"uint8array");this.write(e)};bo.prototype.toString=function(){return"#"};bo.prototype.valueOf=function(){return this.__buffer__};function wo(e,t){if(typeof this!=="undefined"&&!(this instanceof wo)||typeof this==="undefined"){return new wo(e,t)}mo.call(this,e);h("InputFilePort",t,"string");$i(this,"__filename__",t)}wo.prototype=Object.create(mo.prototype);wo.prototype.constructor=wo;wo.prototype.toString=function(){return"#")};function Do(e,t){if(typeof this!=="undefined"&&!(this instanceof Do)||typeof this==="undefined"){return new Do(e,t)}go.call(this,e);h("InputBinaryFilePort",t,"string");$i(this,"__filename__",t)}Do.prototype=Object.create(go.prototype);Do.prototype.constructor=Do;Do.prototype.toString=function(){return"#")};function Eo(e,t){if(typeof this!=="undefined"&&!(this instanceof Eo)||typeof this==="undefined"){return new Eo(e,t)}h("OutputBinaryFilePort",e,"string");$i(this,"__filename__",e);$i(this,"_fd",t.valueOf(),{hidden:true});$i(this,"__type__",Ao);var u,r;this.write=function(e){var n=this;h("write",e,["number","uint8array"]);var i;if(!u){u=this.internal("fs")}if(!r){r=this.internal("Buffer")}if(C.isNumber(e)){i=r.from([e.valueOf()])}else{i=r.from(Array.from(e))}return new Promise(function(t,r){u.write(n._fd,i,function(e){if(e){r(e)}else{t()}})})}}Eo.prototype=Object.create(yo.prototype);Eo.prototype.constructor=Eo;Eo.prototype.write_u8=function(e){h("OutputByteVectorPort::write_u8",e,"number");this.write(e)};Eo.prototype.write_u8_vector=function(e){h("OutputByteVectorPort::write_u8_vector",e,"uint8array");this.write(e)};var Ao=Symbol["for"]("binary");var xo=Symbol["for"]("text");var Fo=new ko;function ko(){}ko.prototype.toString=function(){return"#"};function Co(e){var c=this;var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=t.stderr,n=t.stdin,i=t.stdout,u=t.command_line,a=u===void 0?null:u,o=F(t,cn);if(typeof this!=="undefined"&&!(this instanceof Co)||typeof this==="undefined"){return new Co(e,vn({stdin:n,stdout:i,stderr:r,command_line:a},o))}if(typeof e==="undefined"){e="anonymous"}this.__env__=Yo.inherit(e,o);this.__env__.set("parent.frame",y("parent.frame",function(){return c.__env__},qo.__env__["parent.frame"].__doc__));var f="**interaction-environment-defaults**";this.set(f,Ou(o).concat(f));var s=Lo.inherit("internal-".concat(e));if(pa(n)){s.set("stdin",n)}if(pa(r)){s.set("stderr",r)}if(pa(i)){s.set("stdout",i)}s.set("command-line",a);Vo(this.__env__,s)}Co.prototype.exec=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;h("Interpreter::exec",e,["string","array"],1);h("Interpreter::exec",t,"boolean",2);qo.set("**interaction-environment**",this.__env__);if(r===null){r=this.__env__}return vs(e,r,t?r:false)};Co.prototype.get=function(e){var t=this.__env__.get(e);if(Xu(t)){return t.bind(this.__env__)}return t};Co.prototype.set=function(e,t){return this.__env__.set(e,t)};Co.prototype.constant=function(e,t){return this.__env__.constant(e,t)};function Oo(e,t){this.name="LipsError";this.message=e;this.args=t;this.stack=(new Error).stack}Oo.prototype=new Error;Oo.prototype.constructor=Oo;function So(e,t,r){if(arguments.length===1){if(_(arguments[0])==="object"){e=arguments[0];t=null}else if(typeof arguments[0]==="string"){e={};t=null;r=arguments[0]}}this.__docs__=new Map;this.__env__=e;this.__parent__=t;this.__name__=r||"anonymous"}So.prototype.list=function(){return Ou(this.__env__)};So.prototype.fs=function(){return this.get("**fs**")};So.prototype.unset=function(e){if(e instanceof L){e=e.valueOf()}if(e instanceof $a){e=e.valueOf()}delete this.__env__[e]};So.prototype.inherit=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(_(e)==="object"){t=e}if(!e||_(e)==="object"){e="child of "+(this.__name__||"unknown")}return new So(t||{},this,e)};So.prototype.doc=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:false;if(e instanceof L){e=e.__name__}if(e instanceof $a){e=e.valueOf()}if(t){if(!r){t=Hi(t)}this.__docs__.set(e,t);return this}if(this.__docs__.has(e)){return this.__docs__.get(e)}if(this.__parent__){return this.__parent__.doc(e)}};So.prototype.newFrame=function(e,t){var n=this.inherit("__frame__");n.set("parent.frame",y("parent.frame",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:1;e=e.valueOf();var t=n.__parent__;if(!(t instanceof So)){return U}if(e<=0){return t}var r=t.get("parent.frame");return r(e-1)},qo.__env__["parent.frame"].__doc__));t.callee=e;n.set("arguments",t);return n};So.prototype._lookup=function(e){if(e instanceof L){e=e.__name__}if(e instanceof $a){e=e.valueOf()}if(this.__env__.hasOwnProperty(e)){return Bo(this.__env__[e])}if(this.__parent__){return this.__parent__._lookup(e)}};So.prototype.toString=function(){return"#"};So.prototype.clone=function(){var t=this;var r={};Object.keys(this.__env__).forEach(function(e){r[e]=t.__env__[e]});return new So(r,this.__parent__,this.__name__)};So.prototype.merge=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"merge";h("Environment::merge",e,"environment");return this.inherit(t,e.__env__)};function Bo(e){if(typeof this!=="undefined"&&!(this instanceof Bo)||typeof this==="undefined"){return new Bo(e)}this.value=e}Bo.isUndefined=function(e){return e instanceof Bo&&typeof e.value==="undefined"};Bo.prototype.valueOf=function(){return this.value};function jo(e){if(e.length){if(e.length===1){return e[0]}}if(typeof this!=="undefined"&&!(this instanceof jo)||typeof this==="undefined"){return new jo(e)}this.__values__=e}jo.prototype.toString=function(){return this.__values__.map(function(e){return Pu(e)}).join("\n")};jo.prototype.valueOf=function(){return this.__values__};So.prototype.get=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};h("Environment::get",e,["symbol","string"]);var r=t.throwError,c=r===void 0?true:r;var n=e;if(n instanceof L||n instanceof $a){n=n.valueOf()}var i=this._lookup(n);if(i instanceof Bo){if(Bo.isUndefined(i)){return undefined}return oa(i.valueOf())}var u;if(e instanceof L&&e[L.object]){u=e[L.object]}else if(typeof n==="string"){u=n.split(".").filter(Boolean)}if(u&&u.length>0){var f=u,a=m(f),o=a[0],s=a.slice(1);i=this._lookup(o);if(s.length){try{if(i instanceof Bo){i=i.valueOf()}else{i=No(gn,o);if(Xu(i)){i=sa(i)}}if(typeof i!=="undefined"){return No.apply(void 0,[i].concat(q(s)))}}catch(e){throw e}}else if(i instanceof Bo){return oa(i.valueOf())}i=No(gn,n)}if(typeof i!=="undefined"){return i}if(c){throw new Error("Unbound variable `"+n.toString()+"'")}};So.prototype.set=function(e,t){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:null;h("Environment::set",e,["string","symbol"]);if(C.isNumber(t)){t=C(t)}if(e instanceof L){e=e.__name__}if(e instanceof $a){e=e.valueOf()}this.__env__[e]=t;if(r){this.doc(e,r,true)}return this};So.prototype.constant=function(t,e){var r=this;if(this.__env__.hasOwnProperty(t)){throw new Error("Environment::constant: ".concat(t," already exists"))}if(arguments.length===1&&wu(arguments[0])){var n=arguments[0];Object.keys(n).forEach(function(e){r.constant(t,n[e])})}else{Object.defineProperty(this.__env__,t,{value:e,enumerable:true})}return this};So.prototype.has=function(e){return this.__env__.hasOwnProperty(e)};So.prototype.ref=function(e){var t=this;while(true){if(!t){break}if(t.has(e)){return t}t=t.__parent__}};So.prototype.parents=function(){var e=this;var t=[];while(e){t.unshift(e);e=e.__parent__}return t};function Io(e){if(ra(e)){return e.then(Io)}if(e instanceof M||e instanceof L){e[ya]=true}return e}var Po=Mi(wi('(lambda ()\n "[native code]"\n (throw "Invalid Invocation"))'))[0];var No=y("get",function c(e){var t;for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=Ro(this,"stdin")}Xo("peek-char",e,"input-port");return e.peek_char()},"(peek-char port)\n\n This function reads and returns a character from the string\n port, or, if there is no more data in the string port, it\n returns an EOF."),"read-line":y("read-line",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=Ro(this,"stdin")}Xo("read-line",e,"input-port");return e.read_line()},"(read-char port)\n\n This function reads and returns the next line from the input\n port."),"read-char":y("read-char",function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:null;if(e===null){e=Ro(this,"stdin")}Xo("read-char",e,"input-port");return e.read_char()},"(read-char port)\n\n This function reads and returns the next character from the\n input port."),read:y("read",function(){var e=B(z.mark(function e(){var r,n,i,u,a,o,s,c,f=arguments;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:r=f.length>0&&f[0]!==undefined?f[0]:null;if(!$a.isString(r)){t.next=30;break}n=false;i=false;t.prev=4;a=yn(Mi(r,this));case 6:t.next=8;return a.next();case 8:if(!(n=!(o=t.sent).done)){t.next=14;break}s=o.value;return t.abrupt("return",s);case 11:n=false;t.next=6;break;case 14:t.next=20;break;case 16:t.prev=16;t.t0=t["catch"](4);i=true;u=t.t0;case 20:t.prev=20;t.prev=21;if(!(n&&a["return"]!=null)){t.next=25;break}t.next=25;return a["return"]();case 25:t.prev=25;if(!i){t.next=28;break}throw u;case 28:return t.finish(25);case 29:return t.finish(20);case 30:if(r===null){c=Ro(this,"stdin")}else{c=r}Xo("read",c,"input-port");return t.abrupt("return",c.read.call(this));case 33:case"end":return t.stop()}}},e,this,[[4,16,20,30],[21,,25,29]])}));function t(){return e.apply(this,arguments)}return t}(),"(read [string])\n\n This function, if used with a string, will parse it and\n return the LIPS code, if there is any. If called with a\n port, it will parse the next item from the port. If called\n without an input, it will read a string from standard input\n (using the browser's prompt or a user defined input method)\n and calls itself with that string. This function can be used\n together with `eval` to evaluate code from a string."),pprint:y("pprint",function e(t){if(t instanceof M){t=new Gs.Formatter(t.toString(true))["break"]().format();qo.get("display").call(qo,t)}else{qo.get("write").call(qo,t)}qo.get("newline").call(qo)},"(pprint expression)\n\n This function will pretty print its input to stdout. If it is called\n with a non-list, it will just call the print function on its\n input."),print:y("print",function e(){var t=qo.get("display");var r=qo.get("newline");for(var n=arguments.length,i=new Array(n),u=0;u1?r-1:0),i=1;in.length){throw new Error("Not enough arguments")}var o=0;var s=qo.get("repr");t=t.replace(u,function(e){var t=e[1];if(t==="~"){return"~"}else if(t==="%"){return"\n"}else{var r=n[o++];if(t==="a"){return s(r)}else{return s(r,true)}}});a=t.match(/~([\S])/);if(a){throw new Error("format: Unrecognized escape seqence ".concat(a[1]))}return t},"(format string n1 n2 ...)\n\n This function accepts a string template and replaces any\n escape sequences in its inputs:\n\n * ~a value as if printed with `display`\n * ~s value as if printed with `write`\n * ~% newline character\n * ~~ literal tilde '~'\n\n If there are missing inputs or other escape characters it\n will error."),display:y("display",function e(t){var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:null;if(r===null){r=Ro(this,"stdout")}else{h("display",r,"output-port")}var n=qo.get("repr")(t);r.write.call(qo,n)},"(display string [port])\n\n This function outputs the string to the standard output or\n the port if given. No newline."),"display-error":y("display-error",function e(){var t=Ro(this,"stderr");var r=qo.get("repr");for(var n=arguments.length,i=new Array(n),u=0;u1&&arguments[1]!==undefined?arguments[1]:{},r=t.dynamic_scope,n=t.error;if(r){r=this}var i=this;var u;var a=_s(e.cdr.car,{env:this,dynamic_scope:r,error:n});a=as(a);function o(t,r,n){if(ra(t)){return t.then(function(e){return o(t,e,n)})}if(ra(r)){return r.then(function(e){return o(t,e,n)})}if(ra(n)){return n.then(function(e){return o(t,r,e)})}i.get("set-obj!").call(i,t,r,n);return n}if(e.car instanceof M&&L.is(e.car.car,".")){var f=e.car.cdr.car;var l=e.car.cdr.cdr.car;var h=_s(f,{env:this,dynamic_scope:r,error:n});var p=_s(l,{env:this,dynamic_scope:r,error:n});return o(h,p,a)}if(!(e.car instanceof L)){throw new Error("set! first argument need to be a symbol or "+"dot accessor that evaluate to object.")}var s=e.car.valueOf();u=this.ref(e.car.__name__);return Yi(a,function(e){if(!u){var t=s.split(".");if(t.length>1){var r=t.pop();var n=t.join(".");var i=c.get(n,{throwError:false});if(i){o(i,r,e);return}}throw new Error("Unbound variable `"+s+"'")}u.set(s,e)})}),"(set! name value)\n\n Macro that can be used to set the value of the variable or slot (mutate it).\n set! searches the scope chain until it finds first non emtpy slot and sets it."),"unset!":y(new Vu("set!",function(e){if(!(e.car instanceof L)){throw new Error("unset! first argument need to be a symbol or "+"dot accessor that evaluate to object.")}var t=e.car;var r=this.ref(t);if(r){delete r.__env__[t.__name__]}}),"(unset! name)\n\n Function to delete the specified name from environment.\n Trying to access the name afterwards will error."),"set-car!":y("set-car!",function(e,t){h("set-car!",e,"pair");e.car=t},"(set-car! obj value)\n\n Function that sets the car (first item) of the list/pair to specified value.\n The old value is lost."),"set-cdr!":y("set-cdr!",function(e,t){h("set-cdr!",e,"pair");e.cdr=t},"(set-cdr! obj value)\n\n Function that sets the cdr (tail) of the list/pair to specified value.\n It will destroy the list. The old tail is lost."),"empty?":y("empty?",function(e){return typeof e==="undefined"||e===U},"(empty? object)\n\n Function that returns #t if value is nil (an empty list) or undefined."),gensym:y("gensym",Fi,"(gensym)\n\n Generates a unique symbol that is not bound anywhere,\n to use with macros as meta name."),load:y("load",function e(o,t){h("load",o,"string");var s=this;if(s.__name__==="__frame__"){s=s.__parent__}if(!(t instanceof So)){if(s===qo){t=s}else{t=this.get("**interaction-environment**")}}var c="**module-path**";var f=qo.get(c,{throwError:false});o=o.valueOf();if(!o.match(/.[^.]+$/)){o+=".scm"}var r=o.match(/\.xcb$/);function l(e){if(r){e=Vs(e)}else{if(us(e)==="buffer"){e=e.toString()}e=e.replace(/^#!.*/,"");if(e.match(/^\{/)){e=Rs(e)}}return vs(e,t)}function n(e){return gn.fetch(e).then(function(e){return r?e.arrayBuffer():e.text()}).then(function(e){if(r){e=new Uint8Array(e)}return e})}if(Go()){return new Promise(function(){var r=B(z.mark(function e(r,n){var i,u,a;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:i=An("path");if(!f){t.next=6;break}f=f.valueOf();o=i.join(f,o);t.next=12;break;case 6:u=s.get("command-line",{throwError:false});if(!u){t.next=11;break}t.next=10;return u();case 10:a=t.sent;case 11:if(a&&a!==U){process.cwd();o=i.join(i.dirname(a.car.valueOf()),o)}case 12:qo.set(c,i.dirname(o));An("fs").readFile(o,function(e,t){if(e){n(e);qo.set(c,f)}else{try{l(t).then(function(){r();qo.set(c,f)})["catch"](n)}catch(e){n(e)}}});case 14:case"end":return t.stop()}}},e)}));return function(e,t){return r.apply(this,arguments)}}())}if(f){f=f.valueOf();o=f+"/"+o.replace(/^\.?\/?/,"")}return n(o).then(function(e){qo.set(c,o.replace(/\/[^/]*$/,""));return l(e)}).then(function(){})["finally"](function(){qo.set(c,f)})},"(load filename)\n (load filename environment)\n\n Fetches the file (from disk or network) and evaluates its content as LIPS code.\n If the second argument is provided and it's an environment the evaluation\n will happen in that environment."),do:y(new Vu("do",function(){var r=B(z.mark(function e(r,h){var n,i,u,o,s,a,c,f,l,p,_;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:n=h.dynamic_scope,i=h.error;u=this;if(n){n=u}o=u.inherit("do");s=r.car;a=r.cdr.car;c=r.cdr.cdr;if(c!==U){c=new M(L("begin"),c)}f={env:u,dynamic_scope:n,error:i};l=s;case 10:if(!(l!==U)){t.next=21;break}p=l.car;t.t0=o;t.t1=p.car;t.next=16;return _s(p.cdr.car,f);case 16:t.t2=t.sent;t.t0.set.call(t.t0,t.t1,t.t2);l=l.cdr;t.next=10;break;case 21:f={env:o,dynamic_scope:n,error:i};_=z.mark(function e(){var r,n,i,u,a;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:if(!(c!==U)){t.next=3;break}t.next=3;return Gs.evaluate(c,f);case 3:r=s;n={};case 5:if(!(r!==U)){t.next=15;break}i=r.car;if(!(i.cdr.cdr!==U)){t.next=12;break}t.next=10;return _s(i.cdr.cdr.car,f);case 10:u=t.sent;n[i.car.valueOf()]=u;case 12:r=r.cdr;t.next=5;break;case 15:a=Object.getOwnPropertySymbols(n);Object.keys(n).concat(a).forEach(function(e){o.set(e,n[e])});case 17:case"end":return t.stop()}}},e)});case 23:t.next=25;return _s(a.car,f);case 25:t.t3=t.sent;if(!(t.t3===false)){t.next=30;break}return t.delegateYield(_(),"t4",28);case 28:t.next=23;break;case 30:if(!(a.cdr!==U)){t.next=34;break}t.next=33;return _s(a.cdr.car,f);case 33:return t.abrupt("return",t.sent);case 34:case"end":return t.stop()}}},e,this)}));return function(e,t){return r.apply(this,arguments)}}()),"(do (( )) (test return) . body)\n\n Iteration macro that evaluates the expression body in scope of the variables.\n On each loop it changes the variables according to the expression and runs\n test to check if the loop should continue. If test is a single value, the macro\n will return undefined. If the test is a pair of expressions the macro will evaluate\n and return the second expression after the loop exits."),if:y(new Vu("if",function(r,e){var n=e.dynamic_scope,i=e.error;if(n){n=this}var u=this;var t=function e(t){if(t===false){return _s(r.cdr.cdr.car,{env:u,dynamic_scope:n,error:i})}else{return _s(r.cdr.car,{env:u,dynamic_scope:n,error:i})}};if(r===U){throw new Error("too few expressions for `if`")}var a=_s(r.car,{env:u,dynamic_scope:n,error:i});return Yi(a,t)}),"(if cond true-expr false-expr)\n\n Macro that evaluates cond expression and if the value is true, it\n evaluates and returns true-expression, if not it evaluates and returns\n false-expression."),"let-env":new Vu("let-env",function(t){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var r=e.dynamic_scope,n=e.error;h("let-env",t,"pair");var i=_s(t.car,{env:this,dynamic_scope:r,error:n});return Yi(i,function(e){h("let-env",e,"environment");return _s(M(L("begin"),t.cdr),{env:e,dynamic_scope:r,error:n})})},"(let-env env . body)\n\n Special macro that evaluates body in context of given environment\n object."),letrec:y(ja(Symbol["for"]("letrec")),"(letrec ((a value-a) (b value-b) ...) . body)\n\n Macro that creates a new environment, then evaluates and assigns values to\n names and then evaluates the body in context of that environment.\n Values are evaluated sequentialy and the next value can access the\n previous values/names."),"letrec*":y(ja(Symbol["for"]("letrec")),"(letrec* ((a value-a) (b value-b) ...) . body)\n\n Same as letrec but the order of execution of the binding is guaranteed,\n so you can use recursive code as well as referencing the previous binding.\n\n In LIPS both letrec and letrec* behave the same."),"let*":y(ja(Symbol["for"]("let*")),"(let* ((a value-a) (b value-b) ...) . body)\n\n Macro similar to `let`, but the subsequent bindings after the first\n are evaluated in the environment including the previous let variables,\n so you can define one variable, and use it in the next's definition."),let:y(ja(Symbol["for"]("let")),"(let ((a value-a) (b value-b) ...) . body)\n\n Macro that creates a new environment, then evaluates and assigns values to\n names, and then evaluates the body in context of that environment.\n Values are evaluated sequentialy but you can't access previous values/names\n when the next are evaluated. You can only get them in the body of the let expression.\n (If you want to define multiple variables and use them in each other's definitions,\n use `let*`.)"),"begin*":y(Ia("begin*",function(e){return e.pop()}),"(begin* . body)\n\n This macro is a parallel version of begin. It evaluates each expression\n in the body and if it's a promise it will await it in parallel and return \n the value of the last expression (i.e. it uses Promise.all())."),begin:y(new Vu("begin",function(e,t){var n=Object.assign({},t);var i=qo.get("list->array")(e);if(n.dynamic_scope){n.dynamic_scope=this}n.env=this;var u;return function t(){if(i.length){var e=i.shift();var r=_s(e,n);return Yi(r,function(e){u=e;return t()})}else{return u}}()}),"(begin . args)\n\n Macro that runs a list of expressions in order and returns the value\n of the last one. It can be used in places where you can only have a\n single expression, like (if)."),ignore:new Vu("ignore",function(e,t){var r=t.dynamic_scope,n=t.error;var i={env:this,error:n};if(r){i.dynamic_scope=this}_s(new M(new L("begin"),e),i)},"(ignore . body)\n\n Macro that will evaluate the expression and swallow any promises that may\n be created. It wil discard any value that may be returned by the last body\n expression. The code should have side effects and/or when it's promise\n it should resolve to undefined."),"call/cc":y(Vu.defmacro("call/cc",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var r=vn({env:this},t);return Yi(_s(e.car,r),function(e){if(Xu(e)){return e(new hs(null))}})}),"(call/cc proc)\n\n Call-with-current-continuation.\n\n NOT SUPPORED BY LIPS RIGHT NOW"),define:y(Vu.defmacro("define",function(r,e){var n=this;if(r.car instanceof M&&r.car.car instanceof L){var t=new M(new L("define"),new M(r.car.car,new M(new M(new L("lambda"),new M(r.car.cdr,r.cdr)))));return t}else if(e.macro_expand){return}if(e.dynamic_scope){e.dynamic_scope=this}e.env=n;var i=r.cdr.car;var u;if(i instanceof M){i=_s(i,e);u=true}else if(i instanceof L){i=n.get(i)}h("define",r.car,"symbol");return Yi(i,function(e){if(n.__name__===Ku.__merge_env__){n=n.__parent__}if(u&&(Xu(e)&&Ca(e)||e instanceof Ku)){e.__name__=r.car.valueOf();if(e.__name__ instanceof $a){e.__name__=e.__name__.valueOf()}}var t;if(r.cdr.cdr instanceof M&&$a.isString(r.cdr.cdr.car)){t=r.cdr.cdr.car.valueOf()}n.set(r.car,e,t,true)})}),'(define name expression)\n (define name expression "doc string")\n (define (function-name . args) . body)\n\n Macro for defining values. It can be used to define variables,\n or functions. If the first argument is list it will create a function\n with name being first element of the list. This form expands to\n `(define function-name (lambda args body))`'),"set-obj!":y("set-obj!",function(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;var i=_(e);if(Zu(e)||i!=="object"&&i!=="function"){var u=Qo("set-obj!",us(e),["object","function"]);throw new Error(u)}h("set-obj!",t,["string","symbol","number"]);e=sa(e);t=t.valueOf();if(arguments.length===2){delete e[t]}else if(Nu(e)&&Xu(r)){e[t]=sa(r);e[t][Da]=true}else if(Xu(r)||ts(r)||r===U){e[t]=r}else{e[t]=r&&!Nu(r)?r.valueOf():r}if(Du){var a=e[t];Object.defineProperty(e,t,vn(vn({},n),{},{value:a}))}},"(set-obj! obj key value)\n (set-obj! obj key value props)\n\n Function set a property of a JavaScript object. props should be a vector of pairs,\n passed to Object.defineProperty."),"null-environment":y("null-environment",function(){return qo.inherit("null")},"(null-environment)\n\n Returns a clean environment with only the standard library."),values:y("values",function e(){for(var t=arguments.length,r=new Array(t),n=0;n1&&arguments[1]!==undefined?arguments[1]:{},h=e.dynamic_scope,p=e.error;var _=this;var d;if(l.cdr instanceof M&&$a.isString(l.cdr.car)&&l.cdr.cdr!==U){d=l.cdr.car.valueOf()}function v(){var e;if(h){if(!(this instanceof So)){e=_}else{e=this}}else{e=_}e=e.inherit("lambda");var t=l.car;var r=0;var n;if(typeof this!=="undefined"&&!(this instanceof So)){if(this&&!this.__instance__){Object.defineProperty(this,"__instance__",{enumerable:false,get:function e(){return true},set:function e(){},configurable:false})}e.set("this",this)}for(var i=arguments.length,u=new Array(i),a=0;a>> "+c.toString());if(c){o=c}var d=r.merge(t,Ku.__merge_env__);if(l){return{expr:o,scope:d}}var v=_s(o,vn(vn({},p),{},{env:d}));return Wu(v,_)}i=i.cdr}}catch(e){e.message+=" in macro: ".concat(y.toString(true));throw e}throw new Error("Invalid Syntax ".concat(e.toString(true)))},b);r.__code__=y;return r},"(syntax-rules () (pattern expression) ...)\n\n Base of hygienic macros, it will return a new syntax expander\n that works like Lisp macros."),quote:y(new Vu("quote",function(e){return Io(e.car)}),"(quote expression) or 'expression\n\n Macro that returns a single LIPS expression as data (it won't evaluate the\n argument). It will return a list if put in front of LIPS code.\n And if put in front of a symbol it will return the symbol itself, not the value\n bound to that name."),"unquote-splicing":y("unquote-splicing",function(){throw new Error("You can't call `unquote-splicing` outside of quasiquote")},"(unquote-splicing code) or ,@code\n\n Special form used in the quasiquote macro. It evaluates the expression inside and\n splices the list into quasiquote's result. If it is not the last element of the expression,\n the computed value must be a pair."),unquote:y("unquote",function(){throw new Error("You can't call `unquote` outside of quasiquote")},"(unquote code) or ,code\n\n Special form used in the quasiquote macro. It evaluates the expression inside and\n substitutes the value into quasiquote's result."),quasiquote:Vu.defmacro("quasiquote",function(e,t){var o=t.dynamic_scope,s=t.error;var c=this;if(o){o=c}function a(e){return e instanceof M||wu(e)||Array.isArray(e)}function h(e,t){var r=arguments.length>2&&arguments[2]!==undefined?arguments[2]:a;if(e instanceof M){var n=e.car;var i=e.cdr;if(r(n)){n=t(n)}if(r(i)){i=t(i)}if(ra(n)||ra(i)){return Ci([n,i]).then(function(e){var t=j(e,2),r=t[0],n=t[1];return new M(r,n)})}else{return new M(n,i)}}return e}function u(e,t){if(e instanceof M){if(t!==U){e.append(t)}}else{e=new M(e,t)}return e}function r(e){return!!e.filter(function(e){return e instanceof M&&L.is(e.car,/^(unquote|unquote-splicing)$/)}).length}function p(e,n,i){return e.reduce(function(e,t){if(!(t instanceof M)){e.push(t);return e}if(L.is(t.car,"unquote-splicing")){var r;if(n+11){var t="You can't splice multiple atoms inside list";throw new Error(t)}if(!(i.cdr instanceof M&&r[0]===U)){return r[0]}}r=r.map(function(e){if(d.has(e)){return e.clone()}else{d.add(e);return e}});var n=l(i.cdr,0,1);if(n===U&&r[0]===U){return undefined}return Yi(n,function(e){if(r[0]===U){return e}if(r.length===1){return u(r[0],e)}var t=r.reduce(function(e,t){return u(e,t)});return u(t,e)})})}(i.car.cdr)}var d=new Set;function l(e,t,r){if(e instanceof M){if(e.car instanceof M){if(L.is(e.car.car,"unquote-splicing")){return f(e,t+1,r)}if(L.is(e.car.car,"unquote")){if(t+2===r&&e.car.cdr instanceof M&&e.car.cdr.car instanceof M&&L.is(e.car.cdr.car.car,"unquote-splicing")){var n=e.car.cdr;return new M(new M(new L("unquote"),f(n,t+2,r)),U)}else if(e.car.cdr instanceof M&&e.car.cdr.cdr!==U){if(e.car.cdr.car instanceof M){var i=[];return function t(r){if(r===U){return M.fromArray(i)}return Yi(_s(r.car,{env:c,dynamic_scope:o,error:s}),function(e){i.push(e);return t(r.cdr)})}(e.car.cdr)}else{return e.car.cdr}}}}if(L.is(e.car,"quasiquote")){var u=l(e.cdr,t,r+1);return new M(e.car,u)}if(L.is(e.car,"quote")){return new M(e.car,l(e.cdr,t,r))}if(L.is(e.car,"unquote")){t++;if(tr){throw new Error("You can't call `unquote` outside "+"of quasiquote")}if(e.cdr instanceof M){if(e.cdr.cdr!==U){if(e.cdr.car instanceof M){var a=[];return function t(r){if(r===U){return M.fromArray(a)}return Yi(_s(r.car,{env:c,dynamic_scope:o,error:s}),function(e){a.push(e);return t(r.cdr)})}(e.cdr)}else{return e.cdr}}else{return _s(e.cdr.car,{env:c,dynamic_scope:o,error:s})}}else{return e.cdr}}return h(e,function(e){return l(e,t,r)})}else if(wu(e)){return _(e,t,r)}else if(e instanceof Array){return p(e,t,r)}return e}function n(e){if(e instanceof M){delete e[ya];if(!e.haveCycles("car")){n(e.car)}if(!e.haveCycles("cdr")){n(e.cdr)}}}if(wu(e.car)&&!r(Object.values(e.car))){return Io(e.car)}if(Array.isArray(e.car)&&!r(e.car)){return Io(e.car)}if(e.car instanceof M&&!e.car.find("unquote")&&!e.car.find("unquote-splicing")&&!e.car.find("quasiquote")){return Io(e.car)}var i=l(e.car,0,1);return Yi(i,function(e){n(e);return Io(e)})},"(quasiquote list)\n\n Similar macro to `quote` but inside it you can use special\n expressions (unquote x) abbreviated to ,x that will evaluate x\n and insert its value verbatim or (unquote-splicing x) abbreviated to ,@x that will\n evaluate x and splice the value into the result. Best used with macros but it can be used outside."),clone:y("clone",function e(t){h("clone",t,"pair");return t.clone()},"(clone list)\n\n Function that returns a clone of the list, that does not share any pairs\n with the original, so the clone can be safely mutated without affecting the original."),append:y("append",function e(){var t;for(var r=arguments.length,n=new Array(r),i=0;iarray")(t).reverse();return qo.get("array->list")(r)}else if(!(t instanceof Array)){throw new Error(Qo("reverse",us(t),"array or pair"))}else{return t.reverse()}},"(reverse list)\n\n Function that reverses the list or array. If value is not a list\n or array it will error."),nth:y("nth",function e(t,r){h("nth",t,"number");h("nth",r,["array","pair"]);if(r instanceof M){var n=r;var i=0;while(iarray")(r).join(t)},"(join separator list)\n\n Function that returns a string by joining elements of the list using separator."),split:y("split",function e(t,r){h("split",t,["regex","string"]);h("split",r,"string");return qo.get("array->list")(r.split(t))},"(split separator string)\n\n Function that creates a list by splitting string by separator which can\n be a string or regular expression."),replace:y("replace",function e(t,r,n){h("replace",t,["regex","string"]);h("replace",r,["string","function"]);h("replace",n,"string");return n.replace(t,r)},"(replace pattern replacement string)\n\n Function that changes pattern to replacement inside string. Pattern can be a string\n or regex and replacement can be function or string. See Javascript String.replace()."),match:y("match",function e(t,r){h("match",t,["regex","string"]);h("match",r,"string");var n=r.match(t);return n?qo.get("array->list")(n):false},"(match pattern string)\n\n Function that returns a match object from JavaScript as a list or #f if no match."),search:y("search",function e(t,r){h("search",t,["regex","string"]);h("search",r,"string");return r.search(t)},"(search pattern string)\n\n Function that returns the first found index of the pattern inside a string."),repr:y("repr",function e(t,r){return Pu(t,r)},"(repr obj)\n\n Function that returns a LIPS code representation of the object as a string."),"escape-regex":y("escape-regex",function(e){h("escape-regex",e,"string");return _i(e.valueOf())},"(escape-regex string)\n\n Function that returns a new string where all special operators used in regex,\n are escaped with backslashes so they can be used in the RegExp constructor\n to match a literal string."),env:y("env",function e(e){e=e||this;var t=Object.keys(e.__env__).map(L);var r;if(t.length){r=M.fromArray(t)}else{r=U}if(e.__parent__ instanceof So){return qo.get("env")(e.__parent__).append(r)}return r},"(env)\n (env obj)\n\n Function that returns a list of names (functions, macros and variables)\n that are bound in the current environment or one of its parents."),new:y("new",function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n2&&arguments[2]!==undefined?arguments[2]:Bi.LITERAL;h("set-special!",e,"string",1);h("set-special!",t,"symbol",2);Bi.append(e.valueOf(),t,r)},'(set-special! symbol name [type])\n\n Add a special symbol to the list of transforming operators by the parser.\n e.g.: `(add-special! "#" \'x)` will allow to use `#(1 2 3)` and it will be\n transformed into (x (1 2 3)) so you can write x macro that will process\n the list. 3rd argument is optional, and it can be one of two values:\n lips.specials.LITERAL, which is the default behavior, or\n lips.specials.SPLICE which causes the value to be unpacked into the expression.\n This can be used for e.g. to make `#(1 2 3)` into (x 1 2 3) that is needed\n by # that defines vectors.'),get:No,".":No,unbind:y(sa,"(unbind fn)\n\n Function that removes the weak 'this' binding from a function so you\n can get properties from the actual function object."),type:y(us,"(type object)\n\n Function that returns the type of an object as string."),debugger:y("debugger",function(){debugger},'(debugger)\n\n Function that triggers the JavaScript debugger (e.g. the browser devtools)\n using the "debugger;" statement. If a debugger is not running this\n function does nothing.'),in:y("in",function(e,t){if(e instanceof L||e instanceof $a||e instanceof C){e=e.valueOf()}return e in aa(t)},'(in key value)\n\n Function that uses the Javascript "in" operator to check if key is\n a valid property in the value.'),instanceof:y("instanceof",function(e,t){return t instanceof sa(e)},"(instanceof type obj)\n\n Predicate that tests if the obj is an instance of type."),"prototype?":y("prototype?",Nu,"(prototype? obj)\n\n Predicate that tests if value is a valid JavaScript prototype,\n i.e. calling (new) with it will not throw ' is not a constructor'."),"macro?":y("macro?",function(e){return e instanceof Vu},"(macro? expression)\n\n Predicate that tests if value is a macro."),"function?":y("function?",Xu,"(function? expression)\n\n Predicate that tests if value is a callable function."),"real?":y("real?",function(e){if(us(e)!=="number"){return false}if(e instanceof C){return e.isFloat()}return C.isFloat(e)},"(real? number)\n\n Predicate that tests if value is a real number (not complex)."),"number?":y("number?",function(e){return Number.isNaN(e)||C.isNumber(e)},"(number? expression)\n\n Predicate that tests if value is a number or NaN value."),"string?":y("string?",function(e){return $a.isString(e)},"(string? expression)\n\n Predicate that tests if value is a string."),"pair?":y("pair?",function(e){return e instanceof M},"(pair? expression)\n\n Predicate that tests if value is a pair or list structure."),"regex?":y("regex?",function(e){return e instanceof RegExp},"(regex? expression)\n\n Predicate that tests if value is a regular expression."),"null?":y("null?",function(e){return Zu(e)},"(null? expression)\n\n Predicate that tests if value is null-ish (i.e. undefined, nil, or Javascript null)."),"boolean?":y("boolean?",function(e){return typeof e==="boolean"},"(boolean? expression)\n\n Predicate that tests if value is a boolean (#t or #f)."),"symbol?":y("symbol?",function(e){return e instanceof L},"(symbol? expression)\n\n Predicate that tests if value is a LIPS symbol."),"array?":y("array?",function(e){return e instanceof Array},"(array? expression)\n\n Predicate that tests if value is an arrray."),"object?":y("object?",function(e){return e!==U&&e!==null&&!(e instanceof za)&&!(e instanceof RegExp)&&!(e instanceof $a)&&!(e instanceof M)&&!(e instanceof C)&&_(e)==="object"&&!(e instanceof Array)},"(object? expression)\n\n Predicate that tests if value is an plain object (not another LIPS type)."),flatten:y("flatten",function e(t){h("flatten",t,"pair");return t.flatten()},"(flatten list)\n\n Returns a shallow list from tree structure (pairs)."),"array->list":y("array->list",function(e){h("array->list",e,"array");return M.fromArray(e)},"(array->list array)\n\n Function that converts a JavaScript array to a LIPS cons list."),"tree->array":y("tree->array",gu("tree->array",true),"(tree->array list)\n\n Function that converts a LIPS cons tree structure into a JavaScript array."),"list->array":y("list->array",gu("list->array"),"(list->array list)\n\n Function that converts a LIPS list into a JavaScript array."),apply:y("apply",function e(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;iarray").call(this,u));return t.apply(this,fs(t,n))},"(apply fn list)\n\n Function that calls fn with the list of arguments."),length:y("length",function e(t){if(!t||t===U){return 0}if(t instanceof M){return t.length()}if("length"in t){return t.length}},'(length expression)\n\n Function that returns the length of the object. The object can be a LIPS\n list or any object that has a "length" property. Returns undefined if the\n length could not be found.'),"string->number":y("string->number",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;h("string->number",e,"string",1);h("string->number",t,"number",2);e=e.valueOf();t=t.valueOf();if(e.match(Wn)||e.match(Kn)){return ti(e,t)}else if(e.match(Qn)||e.match(Jn)){return ii(e,t)}else{var r=t===10&&!e.match(/e/i)||t===16;if(e.match(Hn)&&r||e.match(Gn)){return ri(e,t)}if(e.match(Rn)){return oi(e)}}return false},"(string->number number [radix])\n\n Function that parses a string into a number."),try:y(new Vu("try",function(t,e){var c=this;var f=e.dynamic_scope,l=e.error;return new Promise(function(i,n){var u,a;if(L.is(t.cdr.car.car,"catch")){u=t.cdr.car;if(t.cdr.cdr instanceof M&&L.is(t.cdr.cdr.car.car,"finally")){a=t.cdr.cdr.car}}else if(L.is(t.cdr.car.car,"finally")){a=t.cdr.car}if(!(a||u)){throw new Error("try: invalid syntax")}var o=i;if(a){o=function e(t,r){o=n;Yi(_s(new M(new L("begin"),a.cdr),s),function(){r(t)})}}var s={env:c,error:function e(t){var r=c.inherit("try");if(u){r.set(u.cdr.car.car,t);var n={env:r,error:l};if(f){n.dynamic_scope=c}Yi(_s(new M(new L("begin"),u.cdr.cdr),n),function(e){o(e,i)})}else{o(t,l)}}};if(f){s.dynamic_scope=c}var e=_s(t.car,s);if(ra(e)){e.then(function(e){o(e,i)})["catch"](s.error)}else{o(e,i)}})}),"(try expr (catch (e) code))\n (try expr (catch (e) code) (finally code))\n (try expr (finally code))\n\n Macro that executes expr and catches any exceptions thrown. If catch is provided\n it's executed when an error is thown. If finally is provided it's always executed\n at the end."),raise:y("raise",function(e){throw e},"(raise obj)\n\n Throws the object verbatim (no wrapping an a new Error)."),throw:y("throw",function(e){throw new Error(e)},"(throw string)\n\n Throws a new exception."),find:y("find",function t(r,n){h("find",r,["regex","function"]);h("find",n,["pair","nil"]);if(Zu(n)){return U}var e=Gi("find",r);return Yi(e(n.car),function(e){if(e&&e!==U){return n.car}return t(r,n.cdr)})},"(find fn list)\n (find regex list)\n\n Higher-order function that finds the first value for which fn return true.\n If called with a regex it will create a matcher function."),"for-each":y("for-each",function(e){var t;h("for-each",e,"function");for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i1?t-1:0),u=1;u3?n-3:0),u=3;u3?i-3:0),a=3;aarray")(r);var u=[];var a=Gi("filter",t);return function t(r){function e(e){if(e&&e!==U){u.push(n)}return t(++r)}if(r===i.length){return M.fromArray(u)}var n=i[r];return Yi(a(n),e)}(0)},"(filter fn list)\n (filter regex list)\n\n Higher-order function that calls `fn` for each element of the list\n and return a new list for only those elements for which fn returns\n a truthy value. If called with a regex it will create a matcher function."),compose:y(Ra,"(compose . fns)\n\n Higher-order function that creates a new function that applies all functions\n from right to left and returns the last value. Reverse of pipe.\n e.g.:\n ((compose (curry + 2) (curry * 3)) 10) --\x3e (+ 2 (* 3 10)) --\x3e 32"),pipe:y(Na,"(pipe . fns)\n\n Higher-order function that creates a new function that applies all functions\n from left to right and returns the last value. Reverse of compose.\n e.g.:\n ((pipe (curry + 2) (curry * 3)) 10) --\x3e (* 3 (+ 2 10)) --\x3e 36"),curry:y(Ya,"(curry fn . args)\n\n Higher-order function that creates a curried version of the function.\n The result function will have parially applied arguments and it\n will keep returning one-argument functions until all arguments are provided,\n then it calls the original function with the accumulated arguments.\n\n e.g.:\n (define (add a b c d) (+ a b c d))\n (define add1 (curry add 1))\n (define add12 (add 2))\n (display (add12 3 4))"),gcd:y("gcd",function e(){for(var t=arguments.length,r=new Array(t),n=0;no?u%=o:o%=u}u=Tu(s*r[a])/(u+o)}return C(u)},"(lcm n1 n2 ...)\n\n Function that returns the least common multiple of the arguments."),"odd?":y("odd?",Ua(function(e){return C(e).isOdd()}),"(odd? number)\n\n Checks if number is odd."),"even?":y("even?",Ua(function(e){return C(e).isEven()}),"(even? number)\n\n Checks if number is even."),"*":y("*",qa(function(e,t){return C(e).mul(t)},C(1)),"(* . numbers)\n\n Multiplies all numbers passed as arguments. If single value is passed\n it will return that value."),"+":y("+",qa(function(e,t){return C(e).add(t)},C(0)),"(+ . numbers)\n\n Sums all numbers passed as arguments. If single value is passed it will\n return that value."),"-":y("-",function(){for(var e=arguments.length,t=new Array(e),r=0;r":y(">",function(){for(var e=arguments.length,t=new Array(e),r=0;r",t,"number");return Lu(function(e,t){return C(e).cmp(t)===1},t)},"(> x1 x2 x3 ...)\n\n Function that compares its numerical arguments and checks if they are\n monotonically decreasing, i.e. x1 > x2 and x2 > x3 and so on."),"<":y("<",function(){for(var e=arguments.length,t=new Array(e),r=0;r=":y(">=",function(){for(var e=arguments.length,t=new Array(e),r=0;r=",t,"number");return Lu(function(e,t){return[0,1].includes(C(e).cmp(t))},t)},"(>= x1 x2 ...)\n\n Function that compares its numerical arguments and checks if they are\n monotonically nonincreasing, i.e. x1 >= x2 and x2 >= x3 and so on."),"eq?":y("eq?",Uu,"(eq? a b)\n\n Function that compares two values if they are identical."),or:y(new Vu("or",function(e,t){var i=t.dynamic_scope,u=t.error;var a=qo.get("list->array")(e);var o=this;if(i){i=o}if(!a.length){return false}var s;return function t(){function e(e){s=e;if(s!==false){return s}else{return t()}}if(!a.length){if(s!==false){return s}else{return false}}else{var r=a.shift();var n=_s(r,{env:o,dynamic_scope:i,error:u});return Yi(n,e)}}()}),"(or . expressions)\n\n Macro that executes the values one by one and returns the first that is\n a truthy value. If there are no expressions that evaluate to true it\n returns false."),and:y(new Vu("and",function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},i=t.dynamic_scope,u=t.error;var a=qo.get("list->array")(e);var o=this;if(i){i=o}if(!a.length){return true}var s;return function t(){function e(e){s=e;if(s===false){return false}else{return t()}}if(!a.length){if(s!==false){return s}else{return false}}else{var r=a.shift();var n=_s(r,{env:o,dynamic_scope:i,error:u});return Yi(n,e)}}()}),"(and . expressions)\n\n Macro that evalutes each expression in sequence and if any value returns false\n it will stop and return false. If each value returns true it will return the\n last value. If it's called without arguments it will return true."),"|":y("|",function(e,t){return C(e).or(t)},"(| a b)\n\n Function that calculates the bitwise or operation."),"&":y("&",function(e,t){return C(e).and(t)},"(& a b)\n\n Function that calculates the bitwise and operation."),"~":y("~",function(e){return C(e).neg()},"(~ number)\n\n Function that calculates the bitwise inverse (flip all the bits)."),">>":y(">>",function(e,t){return C(e).shr(t)},"(>> a b)\n\n Function that right shifts the value a by value b bits."),"<<":y("<<",function(e,t){return C(e).shl(t)},"(<< a b)\n\n Function that left shifts the value a by value b bits."),not:y("not",function e(t){if(Zu(t)){return true}return!t},"(not object)\n\n Function that returns the Boolean negation of its argument.")},undefined,"global");var Yo=qo.inherit("user-env");function Vo(e,t){e.constant("**internal-env**",t);e.doc("**internal-env**","**internal-env**\n\n Constant used to hide stdin, stdout and stderr so they don't interfere\n with variables with the same name. Constants are an internal type\n of variable that can't be redefined, defining a variable with the same name\n will throw an error.");qo.set("**interaction-environment**",e)}Vo(Yo,Lo);qo.doc("**interaction-environment**","**interaction-environment**\n\n Internal dynamic, global variable used to find interpreter environment.\n It's used so the read and write functions can locate **internal-env**\n that contains the references to stdin, stdout and stderr.");(function(){var e={ceil:"ceiling"};["floor","round","ceil"].forEach(function(t){var r=e[t]?e[t]:t;qo.set(r,y(r,function(e){h(r,e,"number");if(e instanceof C){return e[t]()}},"(".concat(r," number)\n\n Function that calculates the ").concat(r," of a number.")))})})();function zo(e){if(e.length===1){return e[0]}else{var t=[];var r=zo(e.slice(1));for(var n=0;n3&&arguments[3]!==undefined?arguments[3]:null;var i=e?" in expression `".concat(e,"`"):"";if(n!==null){i+=" (argument ".concat(n,")")}if(Xu(r)){return"Invalid type: got ".concat(t).concat(i)}if(r instanceof Array){if(r.length===1){r="a"+("aeiou".includes(r[0].toLowerCase())?"n ":" ")+r[0]}else{var u=r[r.length-1];r=r.slice(0,-1).join(", ")+" or "+u}}return"Expecting ".concat(r,", got ").concat(t).concat(i)}function Zo(r,e,n){e.forEach(function(e,t){h(r,e,n,t+1)})}function Xo(e,t,r){h(e,t,r);if(t.__type__===Ao){throw new Error(Qo(e,"binary-port","textual-port"))}}function h(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;e=e.valueOf();var i=us(t).toLowerCase();if(Xu(r)){if(!r(t)){throw new Error(Qo(e,i,r,n))}return}var u=false;if(r instanceof M){r=r.to_array()}if(r instanceof Array){r=r.map(function(e){return e.valueOf()})}if(r instanceof Array){r=r.map(function(e){return e.valueOf().toLowerCase()});if(r.includes(i)){u=true}}else{r=r.valueOf().toLowerCase()}if(!u&&i!==r){throw new Error(Qo(e,i,r,n))}}function es(e){var t=_(e);return["string","function"].includes(t)||_(e)==="symbol"||e instanceof ki||e instanceof L||e instanceof C||e instanceof $a||e instanceof RegExp}function ts(e){return e instanceof C||e instanceof $a||e instanceof za}function rs(e,t){if(e===null){return false}return _(e)==="object"&&t in Object.getOwnPropertySymbols(e)}function ns(e,t){if(rs(e,t)||rs(e.__proto__,t)){return Xu(e[t])}}function is(r){var n=new WeakMap;return function(e){var t=n.get(e);if(!t){t=r(e)}return t}}us=is(us);function us(e){var t=wn.get(e);if(t){return t}if(_(e)==="object"){for(var r=0,n=Object.entries(bn);r2&&arguments[2]!==undefined?arguments[2]:{},u=t.env,a=t.dynamic_scope,r=t.error,o=r===void 0?function(){}:r;e=os(e,{env:u,dynamic_scope:a,error:o});return Yi(e,function(e){if(Sa(i)){i=sa(i)}e=fs(i,e);var t=e.slice();var r=(a||u).newFrame(i,t);var n=as(i.apply(r,e));return Yi(n,function(e){if(e instanceof M){e.markCycles();return Io(e)}return ia(e)},o)})}var hs=function(){function t(e){D(this,t);this.__value__=e}A(t,[{key:"invoke",value:function e(){if(this.__value__===null){throw new Error("Continuations are not implemented yet")}}},{key:"toString",value:function e(){return"#"}}]);return t}();var ps=function e(){};function _s(t){var e=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},r=e.env,n=e.dynamic_scope,c=e.error,i=c===void 0?ps:c;try{if(n===true){r=n=r||qo}else if(r===true){r=n=qo}else{r=r||qo}var u={env:r,dynamic_scope:n,error:i};var a;if(Zu(t)){return t}if(t instanceof L){return r.get(t)}if(!(t instanceof M)){return t}var o=t.car;var f=t.cdr;if(o instanceof M){a=as(_s(o,u));if(ra(a)){return a.then(function(e){return _s(new M(e,t.cdr),u)})}else if(!ta(a)){throw new Error(us(a)+" "+r.get("repr")(a)+" is not callable while evaluating "+t.toString())}}if(o instanceof L){a=r.get(o)}else if(Xu(o)){a=o}var s;if(a instanceof Ku){s=ss(a,t,u)}else if(a instanceof Vu){s=cs(a,f,u)}else if(Xu(a)){s=ls(a,f,u)}else if(ea(a)){s=a.invoke()}else if(t instanceof M){a=o&&o.toString();throw new Error("".concat(us(o)," ").concat(a," is not a function"))}else{return t}var l=r.get(Symbol["for"]("__promise__"),{throwError:false});if(l===true&&ra(s)){s=s.then(function(e){if(e instanceof M&&!a[ya]){return _s(e,u)}return e});return new ki(s)}return s}catch(e){i&&i.call(r,e,t)}}var ds=ys(function(e){return e});var vs=ys(function(e,t){return t});function ys(_){return function(){var n=B(z.mark(function e(r,n,i){var u,a,o,s,h,c,p,f,l;return z.wrap(function e(t){while(1){switch(t.prev=t.next){case 0:if(i===true){n=i=n||Yo}else if(n===true){n=i=Yo}else{n=n||Yo}u=[];a=Array.isArray(r)?r:Mi(r);o=false;s=false;t.prev=5;c=yn(a);case 7:t.next=9;return c.next();case 9:if(!(o=!(p=t.sent).done)){t.next=27;break}f=p.value;l=_s(f,{env:n,dynamic_scope:i,error:function e(t,r){if(t&&t.message){if(t.message.match(/^Error:/)){var n=/^(Error:)\s*([^:]+:\s*)/;t.message=t.message.replace(n,"$1 $2")}if(r){if(!(t.__code__ instanceof Array)){t.__code__=[]}t.__code__.push(r.toString(true))}}throw t}});if(ra(l)){t.next=16;break}u.push(_(f,l));t.next=24;break;case 16:t.t0=u;t.t1=_;t.t2=f;t.next=21;return l;case 21:t.t3=t.sent;t.t4=(0,t.t1)(t.t2,t.t3);t.t0.push.call(t.t0,t.t4);case 24:o=false;t.next=7;break;case 27:t.next=33;break;case 29:t.prev=29;t.t5=t["catch"](5);s=true;h=t.t5;case 33:t.prev=33;t.prev=34;if(!(o&&c["return"]!=null)){t.next=38;break}t.next=38;return c["return"]();case 38:t.prev=38;if(!s){t.next=41;break}throw h;case 41:return t.finish(38);case 42:return t.finish(33);case 43:return t.abrupt("return",u);case 44:case"end":return t.stop()}}},e,null,[[5,29,33,43],[34,,38,42]])}));function e(e,t,r){return n.apply(this,arguments)}return e}()}function ms(e){var t={"[":"]","(":")"};var r;if(typeof e==="string"){r=wi(e)}else{r=e.map(function(e){return e&&e.token?e.token:e})}var n=Object.keys(t);var i=Object.values(t).concat(n);r=r.filter(function(e){return i.includes(e)});var u=new di;var a=hn(r),o;try{for(a.s();!(o=a.n()).done;){var s=o.value;if(n.includes(s)){u.push(s)}else if(!u.is_empty()){var f=u.top();var c=t[f];if(s===c){u.pop()}else{throw new Error("Syntax error: missing closing ".concat(c))}}else{throw new Error("Syntax error: not matched closing ".concat(s))}}}catch(e){a.e(e)}finally{a.f()}return u.is_empty()}function gs(e){var t="("+e.toString()+")()";var r=window.URL||window.webkitURL;var n;try{n=new Blob([t],{type:"application/javascript"})}catch(e){var i=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder;n=new i;n.append(t);n=n.getBlob()}return new gn.Worker(r.createObjectURL(n))}function bs(){return Gs.version.match(/^(\{\{VER\}\}|DEV)$/)}function ws(){if(Go()){return}var e;if(document.currentScript){e=document.currentScript}else{var t=document.querySelectorAll("script");if(!t.length){return}e=t[t.length-1]}var r=e.getAttribute("src");return r}var Ds=ws();function Es(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:"";var t="dist/std.xcb";if(e===""){if(Ds){e=Ds.replace(/[^/]*$/,"std.xcb")}else if(bs()){e="https://cdn.jsdelivr.net/gh/jcubic/lips@devel/".concat(t)}else{e="https://cdn.jsdelivr.net/npm/@jcubic/lips@".concat(Gs.version,"/").concat(t)}}var r=qo.get("load");return r.call(Yo,e,qo)}function As(e){this.url=e;var a=this.worker=gs(function(){var a;var o;self.addEventListener("message",function(e){var r=e.data;var t=r.id;if(r.type!=="RPC"||t===null){return}function n(e){self.postMessage({id:t,type:"RPC",result:e})}function i(e){self.postMessage({id:t,type:"RPC",error:e})}if(r.method==="eval"){if(!o){i("Worker RPC: LIPS not initilized, call init first");return}o.then(function(){var e=r.params[0];var t=r.params[1];a.exec(e,t).then(function(e){e=e.map(function(e){return e&&e.valueOf()});n(e)})["catch"](function(e){i(e)})})}else if(r.method==="init"){var u=r.params[0];if(typeof u!=="string"){i("Worker RPC: url is not a string")}else{importScripts("".concat(u,"/dist/lips.min.js"));a=new Gs.Interpreter("worker");o=Es(u);o.then(function(){n(true)})}}})});this.rpc=function(){var n=0;return function e(t,r){var u=++n;return new Promise(function(n,i){a.addEventListener("message",function e(t){var r=t.data;if(r&&r.type==="RPC"&&r.id===u){if(r.error){i(r.error)}else{n(r.result)}a.removeEventListener("message",e)}});a.postMessage({type:"RPC",method:t,id:u,params:r})})}}();this.rpc("init",[e])["catch"](function(e){console.error(e)});this.exec=function(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;return this.rpc("eval",[e,t])}}var xs={pair:function e(t){var r=j(t,2),n=r[0],i=r[1];return M(n,i)},number:function e(t){if($a.isString(t)){return C([t,10])}return C(t)},regex:function e(t){var r=j(t,2),n=r[0],i=r[1];return new RegExp(n,i)},nil:function e(){return U},symbol:function e(t){if($a.isString(t)){return L(t)}else if(Array.isArray(t)){return L(Symbol["for"](t[0]))}},string:$a,character:za};var Fs=Object.keys(xs);var ks={};for(var Cs=0,Os=Object.entries(Fs);Cs1){var n=t.reduce(function(e,t){return e+t.length},0);var i=new Uint8Array(n);var u=0;t.forEach(function(e){i.set(e,u);u+=e.length});return i}else if(t.length){return t[0]}}function Us(){var e=1;var t=new TextEncoder("utf-8");return t.encode("LIPS".concat(e.toString().padStart(3," ")))}var Ms=7;function qs(e){var t=new TextDecoder("utf-8");var r=t.decode(e.slice(0,Ms));var n=r.substring(0,4);if(n==="LIPS"){var i=r.match(/^(....).*([0-9]+)$/);if(i){return{type:i[1],version:Number(i[2])}}}return{type:"unknown"}}function Ys(e){var t=Us();var r=Ts.encode(e);return Ls(t,un(r,{magic:false}))}function Vs(e){var t=qs(e),r=t.type,n=t.version;if(r==="LIPS"&&n===1){var i=an(e.slice(Ms),{magic:false});return Ts.decode(i)}else{throw new Error("Invalid file format ".concat(r))}}function zs(e){console.error(e.message||e);if(e.code){console.error(e.code.map(function(e,t){return"[".concat(t+1,"]: ").concat(e)}))}}function $s(){var a=["text/x-lips","text/x-scheme"];var o;function s(r){return new Promise(function(t){var e=r.getAttribute("src");if(e){return fetch(e).then(function(e){return e.text()}).then(vs).then(t)["catch"](function(e){zs(e);t()})}else{return vs(r.innerHTML).then(t)["catch"](function(e){zs(e);t()})}})}function e(){return new Promise(function(i){var u=Array.from(document.querySelectorAll("script"));return function e(){var t=u.shift();if(!t){i()}else{var r=t.getAttribute("type");if(a.includes(r)){var n=t.getAttribute("bootstrap");if(!o&&typeof n==="string"){return Es(n).then(function(){return s(t)}).then(e)}else{return s(t).then(e)}}else if(r&&r.match(/lips|lisp/)){console.warn("Expecting "+a.join(" or ")+" found "+r)}return e()}}()})}if(!window.document){return Promise.resolve()}else if(Js){var t=Js;var r=t.getAttribute("bootstrap");if(typeof r==="string"){return Es(r).then(function(){o=true;return e()})}}return e()}var Js=typeof window!=="undefined"&&window.document&&document.currentScript;if(typeof window!=="undefined"){Fn(window,$s)}var Ks=function(){var e=$a("Fri, 10 Nov 2023 16:25:41 +0000").valueOf();var t=e==="{{"+"DATE}}"?new Date:new Date(e);var r=function e(t){return t.toString().padStart(2,"0")};var n=t.getFullYear();var i=[n,r(t.getMonth()+1),r(t.getDate())].join("-");var u="\n __ __ __\n / / \\ \\ _ _ ___ ___ \\ \\\n| | \\ \\ | | | || . \\/ __> | |\n| | > \\ | |_ | || _/\\__ \\ | |\n| | / ^ \\ |___||_||_| <___/ | |\n \\_\\ /_/ \\_\\ /_/\n\nLIPS Interpreter DEV (".concat(i,") \nCopyright (c) 2018-").concat(n," Jakub T. Jankiewicz\n\nType (env) to see environment with functions macros and variables. You can also\nuse (help name) to display help for specic function or macro, (apropos name)\nto display list of matched names in environment and (dir object) to list\nproperties of an object.\n").replace(/^.*\n/,"");return u}();$i(eu,"__class__","ahead");$i(M,"__class__","pair");$i(mu,"__class__","nil");$i(tu,"__class__","pattern");$i(Xi,"__class__","formatter");$i(Vu,"__class__","macro");$i(Ku,"__class__","syntax");$i(So,"__class__","environment");$i(ho,"__class__","input-port");$i(po,"__class__","output-port");$i(_o,"__class__","output-port");$i(vo,"__class__","output-string-port");$i(mo,"__class__","input-string-port");$i(wo,"__class__","input-file-port");$i(yo,"__class__","output-file-port");$i(Oo,"__class__","lips-error");[C,io,fo,uo,lo].forEach(function(e){$i(e,"__class__","number")});$i(za,"__class__","character");$i(L,"__class__","symbol");$i($a,"__class__","string");$i(ki,"__class__","promise");var Gs={version:"DEV",banner:Ks,date:"Fri, 10 Nov 2023 16:25:41 +0000",exec:vs,parse:Ra(Ji,Mi),tokenize:wi,evaluate:_s,compile:ds,serialize:Ns,unserialize:Rs,serialize_bin:Ys,unserialize_bin:Vs,bootstrap:Es,Environment:So,env:Yo,Worker:As,Interpreter:Co,balanced_parenthesis:ms,balancedParenthesis:ms,balanced:ms,Macro:Vu,Syntax:Ku,Pair:M,Values:jo,QuotedPromise:ki,Error:Oo,quote:Io,InputPort:ho,OutputPort:po,BufferedOutputPort:_o,InputFilePort:wo,OutputFilePort:yo,InputStringPort:mo,OutputStringPort:vo,InputByteVectorPort:go,OutputByteVectorPort:bo,InputBinaryFilePort:Do,OutputBinaryFilePort:Eo,Formatter:Xi,Parser:Li,Lexer:s,specials:Bi,repr:bu,nil:U,eof:Fo,LSymbol:L,LNumber:C,LFloat:uo,LComplex:io,LRational:fo,LBigInteger:lo,LCharacter:za,LString:$a,rationalize:so};qo.set("lips",Gs);var Hs={};var Ws=Object.freeze({__proto__:null,default:Hs});function Qs(e,t){var r=0;for(var n=e.length-1;n>=0;n--){var i=e[n];if(i==="."){e.splice(n,1)}else if(i===".."){e.splice(n,1);r++}else if(r){e.splice(n,1);r--}}if(t){for(;r--;r){e.unshift("..")}}return e}var Zs=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var Xs=function(e){return Zs.exec(e).slice(1)};function ec(){var e="",t=false;for(var r=arguments.length-1;r>=-1&&!t;r--){var n=r>=0?arguments[r]:"/";if(typeof n!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!n){continue}e=n+"/"+e;t=n.charAt(0)==="/"}e=Qs(lc(e.split("/"),function(e){return!!e}),!t).join("/");return(t?"/":"")+e||"."}function tc(e){var t=rc(e),r=hc(e,-1)==="/";e=Qs(lc(e.split("/"),function(e){return!!e}),!t).join("/");if(!e&&!t){e="."}if(e&&r){e+="/"}return(t?"/":"")+e}function rc(e){return e.charAt(0)==="/"}function nc(){var e=Array.prototype.slice.call(arguments,0);return tc(lc(e,function(e,t){if(typeof e!=="string"){throw new TypeError("Arguments to path.join must be strings")}return e}).join("/"))}function ic(e,t){e=ec(e).substr(1);t=ec(t).substr(1);function r(e){var t=0;for(;t=0;r--){if(e[r]!=="")break}if(t>r)return[];return e.slice(t,r-t+1)}var n=r(e.split("/"));var i=r(t.split("/"));var u=Math.min(n.length,i.length);var a=u;for(var o=0;o string (replace #/^ +/gm ""))) fn) -(define-macro (let-syntax vars . body) "(let-syntax ((name fn)) body)\u000A\u000A Macro works like combination of let and define-syntax. It creaates\u000A local macros and evaluate body in context of those macros.\u000A The macro to letrec-syntax is like letrec is to let." (quasiquote (let (unquote vars) (unquote-splicing (map (lambda (rule) (quasiquote (typecheck "let-syntax" (unquote (car rule)) "syntax"))) vars)) (unquote-splicing body)))) -(define-macro (letrec-syntax vars . body) "(letrec-syntax ((name fn)) body)\u000A\u000A Macro works like combination of letrec and define-syntax. It creaates\u000A local macros and evaluate body in context of those macros." (quasiquote (letrec (unquote vars) (unquote-splicing (map (lambda (rule) (quasiquote (typecheck "letrec-syntax" (unquote (car rule)) "syntax"))) vars)) (unquote-splicing body)))) -(define-macro (define-syntax name expr . rest) "(define-syntax name expression [__doc__])\u000A\u000AMacro define new hygienic macro using syntax-rules with optional documentation" (let ((expr-name (gensym "expr-name"))) (quasiquote (define (unquote name) (let (((unquote expr-name) (unquote expr))) (typecheck "define-syntax" (unquote expr-name) "syntax") (unquote expr-name)) (unquote-splicing rest))))) -(define (quoted-symbol? x) "(quoted-symbol? code)\u000A\u000AHelper function that test if value is quoted symbol. To be used in macros\u000Athat pass literal code that is transformed by parser.\u000A\u000Ausage:\u000A\u000A (define-macro (test x)\u000A (if (quoted-symbol? x)\u000A `',(cadr x)))\u000A\u000A (list 'hello (test 'world))" (and (pair? x) (eq? (car x) (quote quote)) (symbol? (cadr x)) (null? (cddr x)))) -(define-macro (--> expr . body) "Helper macro that simplify calling methods on objects. It work with chaining\u000Ausage: (--> ($ \"body\")\u000A (css \"color\" \"red\")\u000A (on \"click\" (lambda () (display \"click\"))))\u000A\u000A (--> document (querySelectorAll \"div\"))\u000A\u000A (--> (fetch \"https://jcubic.pl\")\u000A (text)\u000A (match #/([^<]+)<\\/title>/)\u000A 1)\u000A\u000A (--> document\u000A (querySelectorAll \".cmd-prompt\")\u000A 0\u000A 'innerHTML\u000A (replace #/<(\"[^\"]+\"|[^>])+>/g \"\"))\u000A\u000A (--> document.body\u000A (style.setProperty \"--color\" \"red\"))" (let ((obj (gensym "obj"))) (quasiquote (let* (((unquote obj) (unquote expr))) (unquote-splicing (map (lambda (code) (let* ((value (gensym "value")) (name (cond ((quoted-symbol? code) (symbol->string (cadr code))) ((pair? code) (symbol->string (car code))) (#t code))) (accessor (if (string? name) (quasiquote (. (unquote obj) (unquote-splicing (split "." name)))) (quasiquote (. (unquote obj) (unquote name))))) (call (and (pair? code) (not (quoted-symbol? code))))) (quasiquote (let (((unquote value) (unquote accessor))) (unquote (if call (quasiquote (if (not (function? (unquote value))) (throw (new Error (string-append "--> " (unquote (repr name)) " is not a function" " in expression " (unquote (repr (quasiquote (--> (unquote expr) unquote body))))))) (set! (unquote obj) ((unquote value) (unquote-splicing (cdr code)))))) (quasiquote (set! (unquote obj) (unquote value))))))))) body)) (unquote obj))))) -(define-macro (define-global first . rest) "(define-global var value)\u000A(define-global (name . args) body)\u000A\u000AMacro that define functions or variables in global context, so they can be used\u000Ainside let and get let variables in closure, Useful for universal macros." (if (pair? first) (let ((name (car first))) (quasiquote (--> lips.env (set (unquote (symbol->string name)) (lambda (unquote (cdr first)) (unquote-splicing rest)))))) (quasiquote (--> lips.env (set (unquote (symbol->string first)) (unquote (car rest))))))) +(define-macro (let-syntax vars . body) "(let-syntax ((name fn) ...) . body)\u000A\u000A Works like a combination of let and define-syntax. It creates\u000A local macros and evaluates body in context of those macros.\u000A The macro to letrec-syntax is like letrec is to let." (quasiquote (let (unquote vars) (unquote-splicing (map (lambda (rule) (quasiquote (typecheck "let-syntax" (unquote (car rule)) "syntax"))) vars)) (unquote-splicing body)))) +(define-macro (letrec-syntax vars . body) "(letrec-syntax ((name fn) ...) . body)\u000A\u000A Works like a combination of letrec and define-syntax. It creates\u000A local macros and evaluates the body in context of those macros." (quasiquote (letrec (unquote vars) (unquote-splicing (map (lambda (rule) (quasiquote (typecheck "letrec-syntax" (unquote (car rule)) "syntax"))) vars)) (unquote-splicing body)))) +(define-macro (define-syntax name expr . rest) "(define-syntax name expression [__doc__])\u000A\u000ADefines a new hygienic macro using syntax-rules with optional documentation." (let ((expr-name (gensym "expr-name"))) (quasiquote (define (unquote name) (let (((unquote expr-name) (unquote expr))) (typecheck "define-syntax" (unquote expr-name) "syntax") (unquote expr-name)) (unquote-splicing rest))))) +(define (quoted-symbol? x) "(quoted-symbol? code)\u000A\u000AHelper function that tests if value is a quoted symbol. To be used in macros\u000Athat pass literal code that is transformed by parser.\u000A\u000Ausage:\u000A\u000A (define-macro (test x)\u000A (if (quoted-symbol? x)\u000A `',(cadr x)))\u000A\u000A (list 'hello (test 'world))" (and (pair? x) (eq? (car x) (quote quote)) (symbol? (cadr x)) (null? (cddr x)))) +(define-macro (--> expr . body) "Helper macro that simplifies calling methods on objects. It works with chaining\u000Ausage: (--> ($ \"body\")\u000A (css \"color\" \"red\")\u000A (on \"click\" (lambda () (display \"click\"))))\u000A\u000A (--> document (querySelectorAll \"div\"))\u000A\u000A (--> (fetch \"https://jcubic.pl\")\u000A (text)\u000A (match #/<title>([^<]+)<\\/title>/)\u000A 1)\u000A\u000A (--> document\u000A (querySelectorAll \".cmd-prompt\")\u000A 0\u000A 'innerHTML\u000A (replace #/<(\"[^\"]+\"|[^>])+>/g \"\"))\u000A\u000A (--> document.body\u000A (style.setProperty \"--color\" \"red\"))" (let ((obj (gensym "obj"))) (quasiquote (let* (((unquote obj) (unquote expr))) (unquote-splicing (map (lambda (code) (let* ((value (gensym "value")) (name (cond ((quoted-symbol? code) (symbol->string (cadr code))) ((pair? code) (symbol->string (car code))) (#t code))) (accessor (if (string? name) (quasiquote (. (unquote obj) (unquote-splicing (split "." name)))) (quasiquote (. (unquote obj) (unquote name))))) (call (and (pair? code) (not (quoted-symbol? code))))) (quasiquote (let (((unquote value) (unquote accessor))) (unquote (if call (quasiquote (if (not (function? (unquote value))) (throw (new Error (string-append "--> " (unquote (repr name)) " is not a function" " in expression " (unquote (repr (quasiquote (--> (unquote expr) unquote body))))))) (set! (unquote obj) ((unquote value) (unquote-splicing (cdr code)))))) (quasiquote (set! (unquote obj) (unquote value))))))))) body)) (unquote obj))))) +(define-macro (define-global first . rest) "(define-global var value)\u000A(define-global (name . args) body)\u000A\u000ADefines functions or variables in the global context, so they can be used\u000Ainside let and get let variables in a closure. Useful for universal macros." (if (pair? first) (let ((name (car first))) (quasiquote (--> lips.env (set (unquote (symbol->string name)) (lambda (unquote (cdr first)) (unquote-splicing rest)))))) (quasiquote (--> lips.env (set (unquote (symbol->string first)) (unquote (car rest))))))) (define-macro (globalize expr . rest) "(globalize expr)\u000A\u000A Macro will get the value of the expression and add each method as function to global\u000A scope." (let* ((env (current-environment)) (obj (eval expr env)) (name (gensym "name")) (env-name (gensym "env-name")) (make-name (if (pair? rest) (let ((pre (symbol->string (car rest)))) (lambda (name) (string->symbol (concat pre name)))) string->symbol))) (quasiquote (let (((unquote name) (unquote expr))) (unquote-splicing (filter pair? (map (lambda (key) (if (and (not (match #/^_/ key)) (function? (. obj key))) (let* ((args (gensym "args"))) (quasiquote (define-global ((unquote (make-name key)) unquote args) (apply (. (unquote name) (unquote key)) (unquote args))))))) (array->list (--> Object (keys obj)))))))))) -(define (single list) "(single list)\u000A\u000AFunction check if argument is list with single element" (and (pair? list) (not (cdr list)))) -(define (iterator? x) "(iterator? x)\u000A\u000A Function check if value is JavaScript iterator object" (and (object? x) (procedure? (. x Symbol.iterator)))) -(define-macro (.. expr) "(.. foo.bar.baz)\u000A\u000AMacro that gets value from nested object where argument is comma separated symbol" (if (not (symbol? expr)) expr (let ((parts (split "." (symbol->string expr)))) (if (single parts) expr (quasiquote (. (unquote (string->symbol (car parts))) (unquote-splicing (cdr parts)))))))) +(define (single list) "(single list)\u000A\u000AChecks if argument is list with one element." (and (pair? list) (not (cdr list)))) +(define (iterator? x) "(iterator? x)\u000A\u000A Checks if value is JavaScript iterator object." (and (object? x) (procedure? (. x Symbol.iterator)))) +(define-macro (.. expr) "(.. foo.bar.baz)\u000A\u000AGets the value from a nested object where the argument is a period separated symbol." (if (not (symbol? expr)) expr (let ((parts (split "." (symbol->string expr)))) (if (single parts) expr (quasiquote (. (unquote (string->symbol (car parts))) (unquote-splicing (cdr parts)))))))) (set-special! "#:" (quote gensym-interal)) -(define (gensym-interal symbol) "(gensym-interal symbol)\u000A\u000AParser extension that create new quoted named gensym." (quasiquote (quote (unquote (gensym symbol))))) -(define (plain-object? x) "(plain-object? x)\u000A\u000AFunction check if value is plain JavaScript object. Created using object macro." (and (== (--> (type x) (cmp "object")) 0) (eq? (. x (quote constructor)) Object))) -(define typed-array? (let ((TypedArray (Object.getPrototypeOf Uint8Array))) (lambda (o) "(typed-array? o)\u000A\u000AFunction test if argumnet is JavaScript typed array (Scheme byte vector)." (instanceof TypedArray o)))) -(define (symbol->string s) "(symbol->string symbol)\u000A\u000AFunction convert LIPS symbol to string." (typecheck "symbol->string" s "symbol") (let ((name s.__name__)) (if (string? name) name (name.toString)))) -(define (string->symbol string) "(string->symbol string)\u000A\u000AFunction convert string to LIPS symbol." (typecheck "string->symbol" string "string") (%as.data (new lips.LSymbol string))) -(define (alist->object alist) "(alist->object alist)\u000A\u000AFunction convert alist pairs to JavaScript object." (if (pair? alist) (alist.to_object) (alist->object (new lips.Pair undefined ())))) -(define (object->alist object) "(object->alist object)\u000A\u000AFunction convert JavaScript object to Alist" (typecheck "object->alist" object "object") (vector->list (--> (Object.entries object) (map (lambda (arr) (apply cons (vector->list arr))))))) -(define (parent.frames) "(parent.frames)\u000A\u000AFuncion return list of environments from parent frames (lambda function calls)" (let iter ((result (quote ())) (frame (parent.frame 1))) (if (eq? frame (interaction-environment)) (cons frame result) (if (null? frame) result (let ((parent.frame (--> frame (get (quote parent.frame) (object :throwError #f))))) (if (function? parent.frame) (iter (cons frame result) (parent.frame 0)) result)))))) -(define (pair-map fn seq-list) "(pair-map fn list)\u000A\u000AFunction call fn argument for pairs in a list and return combined list with\u000Avalues returned from function fn. It work like the map but take two items from list" (let iter ((seq-list seq-list) (result (quote ()))) (if (null? seq-list) result (if (and (pair? seq-list) (pair? (cdr seq-list))) (let* ((first (car seq-list)) (second (cadr seq-list)) (value (fn first second))) (if (null? value) (iter (cddr seq-list) result) (iter (cddr seq-list) (cons value result)))))))) -(define (object-expander readonly expr . rest) "(object-expander reaonly '(:foo (:bar 10) (:baz (1 2 3))))\u000A(object-expander reaonly '(:foo :bar))\u000A\u000ARecursive function helper for defining LIPS code for create objects\u000Ausing key like syntax. if no values are used it will create JavaScript\u000Ashorthand objects where keys are used for keys and values" (let ((name (gensym "name")) (r-only (gensym "r-only")) (quot (if (null? rest) #f (car rest)))) (if (null? expr) (quasiquote (alist->object ())) (quasiquote (let (((unquote name) (unquote (Object.fromEntries (new Array)))) ((unquote r-only) (unquote (Object.fromEntries (new Array (new Array "writable" #f)))))) (unquote-splicing (let loop ((lst expr) (result ())) (if (null? lst) (reverse result) (let ((first (car lst)) (second (if (null? (cdr lst)) () (cadr lst)))) (if (not (key? first)) (let ((msg (string-append (type first) " " (repr first) " is not a symbol!"))) (throw msg)) (let ((prop (key->string first))) (if (or (key? second) (null? second)) (let ((code (quasiquote (set-obj! (unquote name) (unquote prop) undefined)))) (loop (cdr lst) (cons code result))) (let ((code (if readonly (if (and (pair? second) (key? (car second))) (quasiquote (set-obj! (unquote name) (unquote prop) (unquote (object-expander readonly second quot)) (unquote r-only))) (if quot (quasiquote (set-obj! (unquote name) (unquote prop) (quote (unquote second)) (unquote r-only))) (quasiquote (set-obj! (unquote name) (unquote prop) (unquote second) (unquote r-only))))) (if (and (pair? second) (key? (car second))) (quasiquote (set-obj! (unquote name) (unquote prop) (unquote (object-expander readonly second)))) (if quot (quasiquote (set-obj! (unquote name) (unquote prop) (quote (unquote second)))) (quasiquote (set-obj! (unquote name) (unquote prop) (unquote second)))))))) (loop (cddr lst) (cons code result)))))))))) (unquote (if readonly (quasiquote (Object.preventExtensions (unquote name))))) (unquote name)))))) -(define-macro (object . expr) "(object :name value)\u000A\u000AMacro that create JavaScript object using key like syntax." (try (object-expander #f expr) (catch (e) (try (error e.message) (catch (e) (console.error e.message)))))) -(define-macro (object-literal . expr) "(object-literal :name value)\u000A\u000AMacro that create JavaScript object using key like syntax. This is similar,\u000Ato object but all values are quoted. This macro is used with & object literal." (try (object-expander #t expr #t) (catch (e) (try (error e.message) (catch (e) (console.error e.message)))))) -(define (alist->assign desc . sources) "(alist->assign alist . list-of-alists)\u000A\u000AFunction that work like Object.assign but for LIPS alist." (for-each (lambda (source) (for-each (lambda (pair) (let* ((key (car pair)) (value (cdr pair)) (d-pair (assoc key desc))) (if (pair? d-pair) (set-cdr! d-pair value) (append! desc (list pair))))) source)) sources) desc) -(define (key? symbol) "(key? symbol)\u000A\u000AFunction check if symbol is key symbol, have colon as first character." (and (symbol? symbol) (== (--> (substring (symbol->string symbol) 0 1) (cmp ":")) 0))) -(define (key->string symbol) "(key->string symbol)\u000A\u000AIf symbol is key it convert that to string - remove colon." (if (key? symbol) (substring (symbol->string symbol) 1))) -(define (%as.data obj) "(%as.data obj)\u000A\u000AMark object as data to stop evaluation." (if (object? obj) (begin (set-obj! obj (quote data) #t) obj))) -(define (%hidden-props obj) "(%hidden-props obj)\u000A\u000AFunction return hidden names of an object, for ES6 class prototype\u000Ait return all methods since they are indistinguishable from hidden property\u000Acreated using defineProperty." (let* ((descriptors (Object.getOwnPropertyDescriptors obj)) (names (Object.keys descriptors))) (--> names (filter (lambda (name) (let ((descriptor (. descriptors name))) (eq? descriptor.enumerable #f))))))) -(define (dir obj . rest) "(dir obj)\u000A\u000AFunction return all props on the object including those in prototype chain." (if (or (null? obj) (eq? obj Object.prototype)) () (let ((proto (if (null? rest) #f (car rest))) (names (Object.getOwnPropertyNames obj))) (if (not proto) (let ((hidden (%hidden-props obj))) (set! names (--> names (filter (lambda (name) (not (hidden.includes name)))))))) (append (array->list (--> names (map (unary string->symbol)))) (dir (Object.getPrototypeOf obj) #t))))) -(define (tree-map f tree) "(tree-map fn tree)\u000A\u000ATree version of map. Function is invoked on every leaf." (if (pair? tree) (cons (tree-map f (car tree)) (tree-map f (cdr tree))) (f tree))) -(define (native.number x) "(native.number obj)\u000A\u000AIf argument is number it will convert to native number." (if (number? x) (value x) x)) -(define (value obj) "(value obj)\u000A\u000AFunction unwrap LNumbers and convert nil value to undefined." (if (eq? obj ()) undefined (if (number? obj) ((. obj "valueOf")) obj))) -(define-macro (define-formatter-rule . patterns) "(rule-pattern pattern)\u000A\u000AAnaphoric Macro for defining patterns for formatter. With Ahead, Pattern and * defined values." (let ((rules (gensym "rules"))) (quasiquote (let (((unquote rules) lips.Formatter.rules) (Ahead (lambda (pattern) (let ((Ahead (.. lips.Formatter.Ahead))) (new Ahead (if (string? pattern) (new RegExp pattern) pattern))))) (* (Symbol.for "*")) (Pattern (lambda (pattern flag) (new lips.Formatter.Pattern (list->array pattern) (if (null? flag) undefined flag))))) (unquote-splicing (map (lambda (pattern) (quasiquote (--> (unquote rules) (push (tree->array (tree-map native.number (unquote-splicing pattern))))))) patterns)))))) +(define (gensym-interal symbol) "(gensym-interal symbol)\u000A\u000AParser extension that creates a new quoted named gensym." (quasiquote (quote (unquote (gensym symbol))))) +(define (plain-object? x) "(plain-object? x)\u000A\u000AChecks if value is a plain JavaScript object created using the object macro." (and (== (--> (type x) (cmp "object")) 0) (eq? (. x (quote constructor)) Object))) +(define typed-array? (let ((TypedArray (Object.getPrototypeOf Uint8Array))) (lambda (o) "(typed-array? o)\u000A\u000AFunction that tests if the arguments is a JavaScript typed array (Scheme byte vector)." (instanceof TypedArray o)))) +(define (symbol->string s) "(symbol->string symbol)\u000A\u000AFunction that converts a LIPS symbol to a string." (typecheck "symbol->string" s "symbol") (let ((name s.__name__)) (if (string? name) name (name.toString)))) +(define (string->symbol string) "(string->symbol string)\u000A\u000AFunction that converts a string to a LIPS symbol." (typecheck "string->symbol" string "string") (%as.data (new lips.LSymbol string))) +(define (alist->object alist) "(alist->object alist)\u000A\u000AFunction that converts alist pairs to a JavaScript object." (if (pair? alist) (alist.to_object) (alist->object (new lips.Pair undefined ())))) +(define (object->alist object) "(object->alist object)\u000A\u000AFunction that converts a JavaScript object to Alist" (typecheck "object->alist" object "object") (vector->list (--> (Object.entries object) (map (lambda (arr) (apply cons (vector->list arr))))))) +(define (parent.frames) "(parent.frames)\u000A\u000AReturns the list of environments from parent frames (lambda function calls)" (let iter ((result (quote ())) (frame (parent.frame 1))) (if (eq? frame (interaction-environment)) (cons frame result) (if (null? frame) result (let ((parent.frame (--> frame (get (quote parent.frame) (object :throwError #f))))) (if (function? parent.frame) (iter (cons frame result) (parent.frame 0)) result)))))) +(define (pair-map fn seq-list) "(pair-map fn list)\u000A\u000AFunction that calls fn argument for pairs in a list and returns a combined list with\u000Avalues returned from function fn. It works likes map but take two items from the list each time." (let iter ((seq-list seq-list) (result (quote ()))) (if (null? seq-list) result (if (and (pair? seq-list) (pair? (cdr seq-list))) (let* ((first (car seq-list)) (second (cadr seq-list)) (value (fn first second))) (if (null? value) (iter (cddr seq-list) result) (iter (cddr seq-list) (cons value result)))))))) +(define (object-expander readonly expr . rest) "(object-expander readonly '(:foo (:bar 10) (:baz (1 2 3))))\u000A(object-expander readonly '(:foo :bar))\u000A\u000ARecursive function helper for defining LIPS code to create objects\u000Ausing key like syntax. If no values are used it will create a JavaScript\u000Ashorthand objects where keys are used for keys and the values." (let ((name (gensym "name")) (r-only (gensym "r-only")) (quot (if (null? rest) #f (car rest)))) (if (null? expr) (quasiquote (alist->object ())) (quasiquote (let (((unquote name) (unquote (Object.fromEntries (new Array)))) ((unquote r-only) (unquote (Object.fromEntries (new Array (new Array "writable" #f)))))) (unquote-splicing (let loop ((lst expr) (result ())) (if (null? lst) (reverse result) (let ((first (car lst)) (second (if (null? (cdr lst)) () (cadr lst)))) (if (not (key? first)) (let ((msg (string-append (type first) " " (repr first) " is not a symbol!"))) (throw msg)) (let ((prop (key->string first))) (if (or (key? second) (null? second)) (let ((code (quasiquote (set-obj! (unquote name) (unquote prop) undefined)))) (loop (cdr lst) (cons code result))) (let ((code (if readonly (if (and (pair? second) (key? (car second))) (quasiquote (set-obj! (unquote name) (unquote prop) (unquote (object-expander readonly second quot)) (unquote r-only))) (if quot (quasiquote (set-obj! (unquote name) (unquote prop) (quote (unquote second)) (unquote r-only))) (quasiquote (set-obj! (unquote name) (unquote prop) (unquote second) (unquote r-only))))) (if (and (pair? second) (key? (car second))) (quasiquote (set-obj! (unquote name) (unquote prop) (unquote (object-expander readonly second)))) (if quot (quasiquote (set-obj! (unquote name) (unquote prop) (quote (unquote second)))) (quasiquote (set-obj! (unquote name) (unquote prop) (unquote second)))))))) (loop (cddr lst) (cons code result)))))))))) (unquote (if readonly (quasiquote (Object.preventExtensions (unquote name))))) (unquote name)))))) +(define-macro (object . expr) "(object :name value)\u000A\u000ACreates a JavaScript object using key like syntax." (try (object-expander #f expr) (catch (e) (try (error e.message) (catch (e) (console.error e.message)))))) +(define-macro (object-literal . expr) "(object-literal :name value)\u000A\u000ACreates a JavaScript object using key like syntax. This is similar,\u000Ato object but all values are quoted. This macro is used by the & object literal." (try (object-expander #t expr #t) (catch (e) (try (error e.message) (catch (e) (console.error e.message)))))) +(define (alist->assign desc . sources) "(alist->assign alist . list-of-alists)\u000A\u000AFunction that works like Object.assign but for LIPS alists." (for-each (lambda (source) (for-each (lambda (pair) (let* ((key (car pair)) (value (cdr pair)) (d-pair (assoc key desc))) (if (pair? d-pair) (set-cdr! d-pair value) (append! desc (list pair))))) source)) sources) desc) +(define (key? symbol) "(key? symbol)\u000A\u000AChecks if symbol is a keyword (has a colon as first character)." (and (symbol? symbol) (== (--> (substring (symbol->string symbol) 0 1) (cmp ":")) 0))) +(define (key->string symbol) "(key->string symbol)\u000A\u000AIf symbol is a keyword it converts that to string and removes the colon." (if (key? symbol) (substring (symbol->string symbol) 1))) +(define (%as.data obj) "(%as.data obj)\u000A\u000AMarks the object as data to stop evaluation." (if (object? obj) (begin (set-obj! obj (quote data) #t) obj))) +(define (%hidden-props obj) "(%hidden-props obj)\u000A\u000AReturns the hidden names of an object, for ES6 class prototypes\u000Ait returns all methods since they are indistinguishable from hidden properties\u000Acreated using defineProperty." (let* ((descriptors (Object.getOwnPropertyDescriptors obj)) (names (Object.keys descriptors))) (--> names (filter (lambda (name) (let ((descriptor (. descriptors name))) (eq? descriptor.enumerable #f))))))) +(define (dir obj . rest) "(dir obj)\u000A\u000AReturns all props on the object including those in prototype chain." (if (or (null? obj) (eq? obj Object.prototype)) () (let ((proto (if (null? rest) #f (car rest))) (names (Object.getOwnPropertyNames obj))) (if (not proto) (let ((hidden (%hidden-props obj))) (set! names (--> names (filter (lambda (name) (not (hidden.includes name)))))))) (append (array->list (--> names (map (unary string->symbol)))) (dir (Object.getPrototypeOf obj) #t))))) +(define (tree-map f tree) "(tree-map fn tree)\u000A\u000ATree version of map. fn is invoked on every leaf." (if (pair? tree) (cons (tree-map f (car tree)) (tree-map f (cdr tree))) (f tree))) +(define (native.number x) "(native.number obj)\u000A\u000AIf argument is a number it will convert it to a native number." (if (number? x) (value x) x)) +(define (value obj) "(value obj)\u000A\u000AFunction that unwraps LNumbers and converts nil to undefined." (if (eq? obj ()) undefined (if (number? obj) ((. obj "valueOf")) obj))) +(define-macro (define-formatter-rule . patterns) "(rule-pattern pattern)\u000A\u000AAnaphoric macro for defining patterns for the formatter. With Ahead, Pattern and * defined values." (let ((rules (gensym "rules"))) (quasiquote (let (((unquote rules) lips.Formatter.rules) (Ahead (lambda (pattern) (let ((Ahead (.. lips.Formatter.Ahead))) (new Ahead (if (string? pattern) (new RegExp pattern) pattern))))) (* (Symbol.for "*")) (Pattern (lambda (pattern flag) (new lips.Formatter.Pattern (list->array pattern) (if (null? flag) undefined flag))))) (unquote-splicing (map (lambda (pattern) (quasiquote (--> (unquote rules) (push (tree->array (tree-map native.number (unquote-splicing pattern))))))) patterns)))))) (define-syntax cond (syntax-rules (=> else) ((cond (else else1 else2 ...)) (if #t (begin else1 else2 ...))) ((cond (test => receiver) more-clause ...) (let ((t test)) (cond/maybe-more t (receiver t) more-clause ...))) ((cond (generator guard => receiver) more-clause ...) (call-with-values (lambda () generator) (lambda t (cond/maybe-more (apply guard t) (apply receiver t) more-clause ...)))) ((cond (test) more-clause ...) (let ((t test)) (cond/maybe-more t t more-clause ...))) ((cond (test body1 body2 ...) more-clause ...) (cond/maybe-more test (begin body1 body2 ...) more-clause ...))) "(cond (predicate? . body)\u000A (predicate? . body)\u000A (else . body))\u000A\u000AMacro for condition checks. For usage instead of nested ifs.") (define-syntax cond/maybe-more (syntax-rules () ((cond/maybe-more test consequent) (if test consequent)) ((cond/maybe-more test consequent clause ...) (if test consequent (cond clause ...)))) "(cond/maybe-more test consequent ...)\u000A\u000AHelper macro used by cond.") (define-macro (cond . list) "(cond (predicate? . body)\u000A (predicate? . body))\u000A\u000A(cond (predicate? => procedure)\u000A (predicate? => procedure))\u000A\u000AMacro for condition checks. For usage instead of nested ifs.\u000AYou can use predicate and any number of expressions. Or symbol =>\u000AFollowed by procedure that will be invoked with result\u000Aof the predicate." (if (pair? list) (let* ((item (car list)) (value (gensym)) (first (car item)) (fn (and (not (null? (cdr item))) (eq? (cadr item) (quote =>)))) (expression (if fn (caddr item) (cdr item))) (rest (cdr list))) (quasiquote (let (((unquote value) (unquote first))) (if (unquote value) (unquote (if fn (quasiquote ((unquote expression) (unquote value))) (quasiquote (begin (unquote-splicing expression))))) (unquote (if (and (pair? rest) (or (eq? (caar rest) #t) (eq? (caar rest) (quote else)))) (quasiquote (begin (unquote-splicing (cdar rest)))) (if (not (null? rest)) (quasiquote (cond (unquote-splicing rest)))))))))) ())) -(define (%r re . rest) "(%r re)\u000A\u000ACreate new regular expression from string, to not break Emacs formatting" (if (null? rest) (new RegExp re) (new RegExp re (car rest)))) -(define (interaction-environment) "(interaction-environment)\u000A\u000AFunction return interaction environement equal to lips.env can be overwritten,\u000Awhen creating new interpreter with lips.Interpreter." **interaction-environment**) -(define (current-output-port) "(current-output-port)\u000A\u000AFunction return default stdout port." (let-env (interaction-environment) (--> **internal-env** (get (quote stdout))))) -(define (current-error-port) "(current-output-port)\u000A\u000AFunction return default stdout port." (let-env (interaction-environment) (--> **internal-env** (get (quote stderr))))) -(define (current-input-port) "(current-input-port)\u000A\u000AFunction return default stdin port." (let-env (interaction-environment) (--> **internal-env** (get (quote stdin))))) -(define (command-line) "(command-line)\u000A\u000AFunction return command line arguments or empty list" (let ((args (let-env (interaction-environment) (--> **internal-env** (get (quote command-line)))))) (if (or (null? args) (zero? (length args))) (quote ("")) (vector->list args)))) -(define (flush-output . rest) "(flush-output)\u000A\u000AIf output-port is buffered, this causes the contents of its buffer to be written to\u000Athe output device. Otherwise it has no effect. Returns an unspecified value." (let ((port (if (null? rest) (current-output-port) (car rest)))) (typecheck "flush-output" port "output-port") (--> port (flush)))) -(define (regex? x) "(regex? x)\u000A\u000AFunction return true of value is regular expression, it return false otherwise." (== (--> (type x) (cmp "regex")) 0)) -(define (set-repr! type fn) "(add-repr! type fn)\u000A\u000AFunction add string represention to the type, which should be constructor function.\u000A\u000AFunction fn should have args (obj q) and it should return string, obj is vlaue that\u000Aneed to be converted to string, if the object is nested and you need to use `repr`,\u000Ait should pass second parameter q to repr, so string will be quoted when it's true.\u000A\u000Ae.g.: (lambda (obj q) (string-append \"<\" (repr obj q) \">\"))" (typecheck "add-repr!" type "function") (typecheck "add-repr!" fn "function") (ignore (--> lips.repr (set type fn)))) -(define (unset-repr! type) "(unset-repr! type)\u000A\u000AFunction remove string represention to the type, which should be constructor function,\u000Aadded by add-repr! function." (typecheck "unset-repr!" type "function") (ignore (--> lips.repr (delete type)))) +(define (%r re . rest) "(%r re)\u000A\u000ACreates a new regular expression from string, to not break Emacs formatting." (if (null? rest) (new RegExp re) (new RegExp re (car rest)))) +(define (interaction-environment) "(interaction-environment)\u000A\u000AReturns the interaction environement equal to lips.env. This can be overwritten\u000Awhen creating new interpreter with lips.Interpreter." **interaction-environment**) +(define (current-output-port) "(current-output-port)\u000A\u000AReturns the default stdout port." (let-env (interaction-environment) (--> **internal-env** (get (quote stdout))))) +(define (current-error-port) "(current-output-port)\u000A\u000AReturns the default stderr port." (let-env (interaction-environment) (--> **internal-env** (get (quote stderr))))) +(define (current-input-port) "(current-input-port)\u000A\u000AReturns the default stdin port." (let-env (interaction-environment) (--> **internal-env** (get (quote stdin))))) +(define (command-line) "(command-line)\u000A\u000AReturns the command line arguments, or an empty list if not running under Node.js." (let ((args (let-env (interaction-environment) (--> **internal-env** (get (quote command-line)))))) (if (or (null? args) (zero? (length args))) (quote ("")) (vector->list args)))) +(define (flush-output . rest) "(flush-output [port])\u000A\u000AIf output-port is buffered, this causes the contents of its buffer to be written to\u000Athe output device. Otherwise it has no effect. Returns an unspecified value." (let ((port (if (null? rest) (current-output-port) (car rest)))) (typecheck "flush-output" port "output-port") (--> port (flush)))) +(define (regex? x) "(regex? x)\u000A\u000AReturns true if value is a regular expression, or false otherwise." (== (--> (type x) (cmp "regex")) 0)) +(define (set-repr! type fn) "(add-repr! type fn)\u000A\u000AFunction that adds the string represention to the type, which should be a constructor function.\u000A\u000AFunction fn should have args (obj q) and it should return a string. obj is the value that\u000Aneed to be converted to a string. If the object is nested and you need to use `repr` recursively,\u000Ait should pass the second parameter q to repr, so string will be quoted when it's true.\u000A\u000Ae.g.: (lambda (obj q) (string-append \"<\" (repr obj q) \">\"))" (typecheck "add-repr!" type "function") (typecheck "add-repr!" fn "function") (ignore (--> lips.repr (set type fn)))) +(define (unset-repr! type) "(unset-repr! type)\u000A\u000ARemoves the string represention of the type, which should be constructor function,\u000Aadded by add-repr! function." (typecheck "unset-repr!" type "function") (ignore (--> lips.repr (delete type)))) (set-special! "&" (quote object-literal) lips.specials.SPLICE) (set-repr! Object (lambda (x q) (concat "&(" (--> (Object.getOwnPropertyNames x) (map (lambda (key) (let ((value (repr (. x key) q)) (key (repr (string->symbol key)))) (concat ":" key " " value)))) (join " ")) ")"))) -(define (bound? x . rest) "(bound? x [env])\u000A\u000AFunction check if variable is defined in given environement or interaction environment\u000Aif not specified." (let ((env (if (null? rest) (interaction-environment) (car rest)))) (try (begin (--> env (get x)) #t) (catch (e) #f)))) -(define (environment-bound? env x) "(environment-bound? env symbol)\u000A\u000AFunction check if symbol is bound variable similar to bound?." (typecheck "environment-bound?" env "environment" 1) (typecheck "environment-bound?" x "symbol" 2) (bound? x env)) -(define (qsort e predicate) "(qsort list predicate)\u000A\u000ASort the list using quick sort alorithm according to predicate." (if (or (null? e) (<= (length e) 1)) e (let loop ((left ()) (right ()) (pivot (car e)) (rest (cdr e))) (if (null? rest) (append (append (qsort left predicate) (list pivot)) (qsort right predicate)) (if (predicate (car rest) pivot) (loop (append left (list (car rest))) right pivot (cdr rest)) (loop left (append right (list (car rest))) pivot (cdr rest))))))) -(define (sort list . rest) "(sort list [predicate])\u000A\u000ASort the list using optional predicate function. if not function is specified\u000Ait will use <= and sort in increasing order." (let ((predicate (if (null? rest) <= (car rest)))) (typecheck "sort" list "pair") (typecheck "sort" predicate "function") (qsort list predicate))) -(define (every fn list) "(every fn list)\u000A\u000AFunction call function fn on each item of the list, if every value is true\u000Ait will return true otherwise it return false." (if (null? list) #t (and (fn (car list)) (every fn (cdr list))))) -(define-macro (promise . body) "(promise . body)\u000A\u000AAnaphoric macro that expose resolve and reject functions from JS promise" (quasiquote (new Promise (lambda (resolve reject) (try (begin (unquote-splicing body)) (catch (e) (error e.message))))))) -(define-macro (timer time . body) "(timer time . body)\u000A\u000AMacro evaluate expression after delay, it return timer. To clear the timer you can use\u000Anative JS clearTimeout function." (quasiquote (setTimeout (lambda () (try (begin (unquote-splicing body)) (catch (e) (error (.. e.message))))) (unquote time)))) -(define-macro (wait time . expr) "(wait time . expr)\u000A\u000AFunction return promise that will resolve with evaluating the expression after delay." (quasiquote (promise (timer (unquote time) (resolve (begin (unquote-splicing expr))))))) -(define (await value) "(await value)\u000A\u000AFunction unquote quoted promise so it can be automagicaly evaluated (resolved\u000Ato its value)." (if (instanceof lips.QuotedPromise value) (value.valueOf) value)) -(define-macro (quote-promise expr) "(quote-promise expr)\u000A'>expr\u000A\u000AMacro used to escape promise the whole expression, will be wrapped\u000Awith JavaScript class that behave like Promise but will not\u000Aauto resolve like normal promise." (quasiquote (let ((env)) (set! env (current-environment)) (env.set (Symbol.for "__promise__") #t) (unquote expr)))) -(define (defmacro? obj) "(defmacro? expression)\u000A\u000AFunction check if object is macro and it's expandable." (and (macro? obj) (. obj (quote defmacro)))) -(define (n-ary n fn) "(n-ary n fn)\u000A\u000AReturn new function that limit number of arguments to n." (lambda args (apply fn (take n args)))) -(define (take n lst) "(take n list)\u000A\u000AReturn n first values of the list." (let iter ((result (quote ())) (i n) (lst lst)) (if (or (null? lst) (<= i 0)) (reverse result) (iter (cons (car lst) result) (- i 1) (cdr lst))))) -(define unary (%doc "(unary fn)\u000A\u000AFunction return new function with arguments limited to one." (curry n-ary 1))) -(define binary (%doc "(binary fn)\u000A\u000AFunction return new function with arguments limited to two." (curry n-ary 2))) -(define (%class-lambda expr) "(class-lambda expr)\u000A\u000AReturn lambda expression where input expression lambda have `this` as first argument." (let ((args (gensym (quote args)))) (quasiquote (lambda (unquote args) (apply (unquote (cadr expr)) this (unquote args)))))) -(define (%class-method-name expr) "(%class-method-name expr)\u000A\u000AHelper function that allow to use [Symbol.asyncIterator] inside method name." (if (pair? expr) (car expr) (list (quote quote) expr))) -(define-macro (define-class name parent . body) "(define-class name parent . body)\u000A\u000ADefine class - JavaScript function constructor with prototype.\u000A\u000Ausage:\u000A\u000A (define-class Person Object\u000A (constructor (lambda (self name)\u000A (set-obj! self '_name name)))\u000A (hi (lambda (self)\u000A (display (string-append self._name \" say hi\"))\u000A (newline))))\u000A (define jack (new Person \"Jack\"))\u000A (jack.hi)" (let iter ((functions (quote ())) (constructor (quote ())) (lst body)) (if (null? lst) (quasiquote (begin (define (unquote name) (unquote (if (null? constructor) (quasiquote (lambda ())) (append (%class-lambda constructor) (list (quote this)))))) (set-obj! (unquote name) (Symbol.for "__class__") #t) (unquote (if (not (null? parent)) (quasiquote (begin (set-obj! (unquote name) (quote prototype) (Object.create (. (unquote parent) (quote prototype)))) (set-obj! (. (unquote name) (quote prototype)) (quote constructor) (unquote name)))))) (set-obj! (unquote name) (quote __name__) (quote (unquote name))) (unquote-splicing (map (lambda (fn) (quasiquote (set-obj! (. (unquote name) (quote prototype)) (unquote (%class-method-name (car fn))) (unquote (%class-lambda fn))))) functions)))) (let ((item (car lst))) (if (eq? (car item) (quote constructor)) (iter functions item (cdr lst)) (iter (cons item functions) constructor (cdr lst))))))) -(define-syntax class (syntax-rules () ((_) (error "class: parent required")) ((_ parent body ...) (let () (define-class temp parent body ...) temp))) "(class <parent> body ...)\u000A\u000AMacro allow to create anonymous classes. See define-class for details.") -(define (make-tags expr) "(make-tags expression)\u000A\u000AFunction that return list structure of code with better syntax then raw LIPS" (quasiquote (h (unquote (let ((val (car expr))) (if (key? val) (key->string val) val))) (alist->object ((unquote (quote quasiquote)) (unquote (pair-map (lambda (car cdr) (quasiquote ((unquote (key->string car)) (unquote (quote unquote)) (unquote cdr)))) (cadr expr))))) (unquote (if (not (null? (cddr expr))) (if (and (pair? (caddr expr)) (let ((s (caaddr expr))) (and (symbol? s) (eq? s (quote list))))) (quasiquote (list->array (list (unquote-splicing (map make-tags (cdaddr expr)))))) (caddr expr))))))) -(define (%sxml h expr) "(%sxml h expr)\u000A\u000AHelper function that render expression using create element function." (let* ((have-attrs (and (not (null? (cdr expr))) (pair? (cadr expr)) (eq? (caadr expr) (quote @)))) (attrs (if have-attrs (cdadr expr) ())) (rest (if have-attrs (cddr expr) (cdr expr)))) (quasiquote ((unquote h) (unquote (let* ((symbol (car expr)) (name (symbol->string symbol))) (if (char-lower-case? (car (string->list name))) name symbol))) (alist->object ((unquote (quote quasiquote)) (unquote (map (lambda (pair) (cons (symbol->string (car pair)) (list (quote unquote) (cadr pair)))) attrs)))) (unquote-splicing (if (null? rest) () (let ((first (car rest))) (if (pair? first) (cond ((symbol=? (quote sxml-unquote) (car first)) (cdr first)) (else (map (lambda (expr) (%sxml h expr)) rest))) (list first))))))))) +(define (bound? x . rest) "(bound? x [env])\u000A\u000AFunction that check if the variable is defined in the given environement, or interaction-environment\u000Aif not specified." (let ((env (if (null? rest) (interaction-environment) (car rest)))) (try (begin (--> env (get x)) #t) (catch (e) #f)))) +(define (environment-bound? env x) "(environment-bound? env symbol)\u000A\u000AChecks if symbol is a bound variable similar to bound?." (typecheck "environment-bound?" env "environment" 1) (typecheck "environment-bound?" x "symbol" 2) (bound? x env)) +(define (qsort e predicate) "(qsort list predicate)\u000A\u000ASorts the list using the quick sort alorithm according to predicate." (if (or (null? e) (<= (length e) 1)) e (let loop ((left ()) (right ()) (pivot (car e)) (rest (cdr e))) (if (null? rest) (append (append (qsort left predicate) (list pivot)) (qsort right predicate)) (if (predicate (car rest) pivot) (loop (append left (list (car rest))) right pivot (cdr rest)) (loop left (append right (list (car rest))) pivot (cdr rest))))))) +(define (sort list . rest) "(sort list [predicate])\u000A\u000ASorts the list using optional predicate function. If no comparison function is given\u000Ait will use <= and sort in increasing order." (let ((predicate (if (null? rest) <= (car rest)))) (typecheck "sort" list "pair") (typecheck "sort" predicate "function") (qsort list predicate))) +(define (every fn list) "(every fn list)\u000A\u000AFunction that calls fn on each item of the list, if every value returns true\u000Ait will return true otherwise it return false.\u000AAnalagous to Python all(map(fn, list))." (if (null? list) #t (and (fn (car list)) (every fn (cdr list))))) +(define-macro (promise . body) "(promise . body)\u000A\u000AAnaphoric macro that exposes resolve and reject functions from JS promise." (quasiquote (new Promise (lambda (resolve reject) (try (begin (unquote-splicing body)) (catch (e) (error e.message))))))) +(define-macro (timer time . body) "(timer time . body)\u000A\u000AEvaluates body after delay, it returns the timer ID from setTimeout.\u000ATo clear the timer you can use native JS clearTimeout function." (quasiquote (setTimeout (lambda () (try (begin (unquote-splicing body)) (catch (e) (error (.. e.message))))) (unquote time)))) +(define-macro (wait time . expr) "(wait time . expr)\u000A\u000AReturns a promise that will resolve with the expression after delay." (quasiquote (promise (timer (unquote time) (resolve (begin (unquote-splicing expr))))))) +(define (await value) "(await value)\u000A\u000AUnquotes a quoted promise so it can be automagicaly evaluated (resolved\u000Ato its value)." (if (instanceof lips.QuotedPromise value) (value.valueOf) value)) +(define-macro (quote-promise expr) "(quote-promise expr) or '>expr\u000A\u000AMacro used to escape automati awaiting of the expression. It will be wrapped\u000Awith a JavaScript class that behaves like Promise but will not be automatically\u000Aresolved by LIPS like normal promises are." (quasiquote (let ((env)) (set! env (current-environment)) (env.set (Symbol.for "__promise__") #t) (unquote expr)))) +(define (defmacro? obj) "(defmacro? expression)\u000A\u000AChecks if object is a macro and it's expandable." (and (macro? obj) (. obj (quote defmacro)))) +(define (n-ary n fn) "(n-ary n fn)\u000A\u000AReturns a new function that limits the number of arguments to n." (lambda args (apply fn (take n args)))) +(define (take n lst) "(take n list)\u000A\u000AReturns n first values of the list." (let iter ((result (quote ())) (i n) (lst lst)) (if (or (null? lst) (<= i 0)) (reverse result) (iter (cons (car lst) result) (- i 1) (cdr lst))))) +(define unary (%doc "(unary fn)\u000A\u000AReturns a new function with arguments limited to one." (curry n-ary 1))) +(define binary (%doc "(binary fn)\u000A\u000AReturns a new function with arguments limited to two." (curry n-ary 2))) +(define (%class-lambda expr) "(class-lambda expr)\u000A\u000AReturns a lambda expression where input expression lambda have `this` as first argument." (let ((args (gensym (quote args)))) (quasiquote (lambda (unquote args) (apply (unquote (cadr expr)) this (unquote args)))))) +(define (%class-method-name expr) "(%class-method-name expr)\u000A\u000AHelper function that allows to use [Symbol.asyncIterator] inside method name." (if (pair? expr) (car expr) (list (quote quote) expr))) +(define-macro (define-class name parent . body) "(define-class name parent . body)\u000A\u000ADefines a class - JavaScript function constructor with prototype.\u000A\u000Ausage:\u000A\u000A (define-class Person Object\u000A (constructor (lambda (self name)\u000A (set-obj! self '_name name)))\u000A (hi (lambda (self)\u000A (display (string-append self._name \" says hi\"))\u000A (newline))))\u000A (define jack (new Person \"Jack\"))\u000A (jack.hi) ; prints \"Jack says hi\"" (let iter ((functions (quote ())) (constructor (quote ())) (lst body)) (if (null? lst) (quasiquote (begin (define (unquote name) (unquote (if (null? constructor) (quasiquote (lambda ())) (append (%class-lambda constructor) (list (quote this)))))) (set-obj! (unquote name) (Symbol.for "__class__") #t) (unquote (if (not (null? parent)) (quasiquote (begin (set-obj! (unquote name) (quote prototype) (Object.create (. (unquote parent) (quote prototype)))) (set-obj! (. (unquote name) (quote prototype)) (quote constructor) (unquote name)))))) (set-obj! (unquote name) (quote __name__) (quote (unquote name))) (unquote-splicing (map (lambda (fn) (quasiquote (set-obj! (. (unquote name) (quote prototype)) (unquote (%class-method-name (car fn))) (unquote (%class-lambda fn))))) functions)))) (let ((item (car lst))) (if (eq? (car item) (quote constructor)) (iter functions item (cdr lst)) (iter (cons item functions) constructor (cdr lst))))))) +(define-syntax class (syntax-rules () ((_) (error "class: parent required")) ((_ parent body ...) (let () (define-class temp parent body ...) temp))) "(class <parent> body ...)\u000A\u000AAllows to create anonymous classes. See define-class for details.") +(define (make-tags expr) "(make-tags expression)\u000A\u000AReturns a list structure of code with better syntax then raw LIPS" (quasiquote (h (unquote (let ((val (car expr))) (if (key? val) (key->string val) val))) (alist->object ((unquote (quote quasiquote)) (unquote (pair-map (lambda (car cdr) (quasiquote ((unquote (key->string car)) (unquote (quote unquote)) (unquote cdr)))) (cadr expr))))) (unquote (if (not (null? (cddr expr))) (if (and (pair? (caddr expr)) (let ((s (caaddr expr))) (and (symbol? s) (eq? s (quote list))))) (quasiquote (list->array (list (unquote-splicing (map make-tags (cdaddr expr)))))) (caddr expr))))))) +(define (%sxml h expr) "(%sxml h expr)\u000A\u000AHelper function that renders the expression using create element function." (let* ((have-attrs (and (not (null? (cdr expr))) (pair? (cadr expr)) (eq? (caadr expr) (quote @)))) (attrs (if have-attrs (cdadr expr) ())) (rest (if have-attrs (cddr expr) (cdr expr)))) (quasiquote ((unquote h) (unquote (let* ((symbol (car expr)) (name (symbol->string symbol))) (if (char-lower-case? (car (string->list name))) name symbol))) (alist->object ((unquote (quote quasiquote)) (unquote (map (lambda (pair) (cons (symbol->string (car pair)) (list (quote unquote) (cadr pair)))) attrs)))) (unquote-splicing (if (null? rest) () (let ((first (car rest))) (if (pair? first) (cond ((symbol=? (quote sxml-unquote) (car first)) (cdr first)) (else (map (lambda (expr) (%sxml h expr)) rest))) (list first))))))))) (set-special! "~" (quote sxml-unquote-mapper)) (define (sxml-unquote-mapper expression) (quasiquote (sxml-unquote (unquote expression)))) -(define (sxml-unquote) "(sxml-unquote expression)\u000A~expression\u000A\u000AThread expression as code and evaluate it inside sxml, similar to unquote\u000Awith quasiquote." (throw "sxml-unquote: Can't use outside of sxml")) -(define-macro (pragma->sxml pragma) (quasiquote (define-macro (sxml expr) "(sxml expr)\u000A\u000AMacro for JSX like syntax but with SXML.\u000Ae.g. usage:\u000A\u000A(sxml (div (@ (data-foo \"hello\")\u000A (id \"foo\"))\u000A (span \"hello\")\u000A (span \"world\")))" (%sxml (quote (unquote pragma)) expr)))) +(define (sxml-unquote) "(sxml-unquote expression) or ~expression\u000A\u000ATreat expression as code and evaluate it inside sxml, similar to unquote\u000Awith quasiquote." (throw "sxml-unquote: Can't use outside of sxml")) +(define-macro (pragma->sxml pragma) (quasiquote (define-macro (sxml expr) "(sxml expr)\u000A\u000AMacro for JSX like syntax but with SXML.\u000Ae.g. usage:\u000A\u000A(sxml (div (@ (data-foo \"hello\")\u000A (id \"foo\"))\u000A (span \"hello\")\u000A (span \"world\")))\u000A;; ==> <div data-foo=\"hello\" id=\"foo\"><span>hello</span><span>world</span></div>" (%sxml (quote (unquote pragma)) expr)))) (pragma->sxml h) -(define-macro (with-tags expr) "(with-tags expression)\u000A\u000AMacro that evalute LIPS shorter code for S-Expression equivalent of JSX.\u000Ae.g.:\u000A\u000A(with-tags (:div (:class \"item\" :id \"item-1\")\u000A (list (:span () \"Random Item\")\u000A (:a (:onclick (lambda (e) (alert \"close\")))\u000A \"close\"))))\u000A\u000AAbove expression can be passed to function that renders JSX (like render in React, Preact)\u000ATo get the string from the macro you can use vhtml library from npm." (make-tags expr)) -(define (get-resource url) "(get-resource url)\u000A\u000ALoad JavaScript or CSS file in browser by adding script tag to head of the current document.\u000AWhen called from Node it allow it allow to load JavaScript files only." (typecheck "get-resource" url "string") (if (not (bound? (quote document))) (if (eq? self global) (let ((code (%read-file #f url))) (self.eval code)) (throw (new Error "get-script: document not defined"))) (let ((load (lambda (node) (new Promise (lambda (resolve reject) (set! node.onload (lambda () (resolve))) (set! node.onerror (lambda () (reject (string-append "get-resource: Failed to load " url)))) (if document.head (document.head.appendChild node))))))) (cond ((url.match #/.js$/) (let ((script (document.createElement "script"))) (set! script.src url) (load script))) ((url.match #/.css$/) (let ((link (document.createElement "link"))) (set! link.href url) (set! link.rel "stylesheet") (load link))))))) -(define (gensym? value) "(gensym? value)\u000A\u000AFunction return #t if value is symbol and it's gensym. It returns #f otherwise." (and (symbol? value) (--> value (is_gensym)))) -(define (degree->radians x) "(degree->radians x)\u000A\u000AConvert degree to radians." (* x (/ Math.PI 180))) -(define (radians->degree x) "(radians->degree x)\u000A\u000AConvert radians to degree." (* x (/ 180 Math.PI))) -(define-syntax while (syntax-rules () ((_ predicate body ...) (do () ((not predicate)) body ...))) "(while cond . body)\u000A\u000AMacro that create a loop, it exectue body until cond expression is false.") -(define-syntax ++ (syntax-rules () ((++ x) (let ((tmp (+ x 1))) (set! x tmp) tmp))) "(++ variable)\u000A\u000AMacro that work only on variables and increment the value by one.") -(define-syntax -- (syntax-rules () ((-- x) (let ((tmp (- x 1))) (set! x tmp) tmp))) "(-- variable)\u000A\u000AMacro that decrement the value it work only on symbols") -(define (pretty-format . lists) "(pretty-format pair)\u000A\u000AFunction return pretty printed string from pair expression." (let ((code (--> (list->vector lists) (map (lambda (pair i) (typecheck "pretty-pair" pair "pair" i) (repr pair #t))) (join "")))) (--> (new lips.Formatter code) (break) (format)))) -(define (reset) "(reset)\u000A\u000AFunction reset environment and remove all user defined variables." (let-env **interaction-environment** (let ((defaults **interaction-environment-defaults**) (env **interaction-environment**)) (--> env (list) (forEach (lambda (name) (if (not (--> defaults (includes name))) (--> env (unset name))))))))) +(define-macro (with-tags expr) "(with-tags expression)\u000A\u000Avalutes LIPS shorter code for S-Expression equivalent of JSX.\u000Ae.g.:\u000A\u000A(with-tags (:div (:class \"item\" :id \"item-1\")\u000A (list (:span () \"Random Item\")\u000A (:a (:onclick (lambda (e) (alert \"close\")))\u000A \"close\"))))\u000A\u000AAbove expression can be passed to function that renders JSX (like render in React, Preact)\u000ATo get the string from the macro you can use vhtml library from npm." (make-tags expr)) +(define (get-resource url) "(get-resource url)\u000A\u000ALoad JavaScript or CSS file in browser by adding script/link tag to head of the current document.\u000AWhen called from Node it allow it allows to load JavaScript files only." (typecheck "get-resource" url "string") (if (not (bound? (quote document))) (if (eq? self global) (let ((code (%read-file #f url))) (self.eval code)) (throw (new Error "get-script: document not defined"))) (let ((load (lambda (node) (new Promise (lambda (resolve reject) (set! node.onload (lambda () (resolve))) (set! node.onerror (lambda () (reject (string-append "get-resource: Failed to load " url)))) (if document.head (document.head.appendChild node))))))) (cond ((url.match #/.js$/) (let ((script (document.createElement "script"))) (set! script.src url) (load script))) ((url.match #/.css$/) (let ((link (document.createElement "link"))) (set! link.href url) (set! link.rel "stylesheet") (load link))))))) +(define (gensym? value) "(gensym? value)\u000A\u000AReturns #t if value is a symbol created by gensym. It returns #f otherwise." (and (symbol? value) (--> value (is_gensym)))) +(define (degree->radians x) "(degree->radians x)\u000A\u000AConvert degrees to radians." (* x (/ Math.PI 180))) +(define (radians->degree x) "(radians->degree x)\u000A\u000AConvert radians to degrees." (* x (/ 180 Math.PI))) +(define-syntax while (syntax-rules () ((_ predicate body ...) (do () ((not predicate)) body ...))) "(while cond . body)\u000A\u000ACreates a loop, it executes cond and body until cond expression is false.") +(define-syntax ++ (syntax-rules () ((++ x) (let ((tmp (+ x 1))) (set! x tmp) tmp))) "(++ variable)\u000A\u000AWorks only on variables and increment the value by one.") +(define-syntax -- (syntax-rules () ((-- x) (let ((tmp (- x 1))) (set! x tmp) tmp))) "(-- variable)\u000A\u000AWorks only on variables and decrements the value by one.") +(define (pretty-format . lists) "(pretty-format pair)\u000A\u000AReturns a pretty printed string from pair expression." (let ((code (--> (list->vector lists) (map (lambda (pair i) (typecheck "pretty-pair" pair "pair" i) (repr pair #t))) (join "")))) (--> (new lips.Formatter code) (break) (format)))) +(define (reset) "(reset)\u000A\u000AFunction resets the environment and removes all user defined variables." (let-env **interaction-environment** (let ((defaults **interaction-environment-defaults**) (env **interaction-environment**)) (--> env (list) (forEach (lambda (name) (if (not (--> defaults (includes name))) (--> env (unset name))))))))) (define (make-list n . rest) (if (or (not (integer? n)) (<= n 0)) (throw (new Error "make-list: first argument need to be integer larger then 0")) (let ((fill (if (null? rest) undefined (car rest)))) (array->list (--> (new Array n) (fill fill)))))) -(define (range stop . rest) "(range stop)\u000A(range start stop)\u000A(range start stop step)\u000A\u000AFunction returns list of numbers from start to stop with optonal step.\u000AIf start is not defined it starts from 0. If start is larger than stop\u000Athe step need to be negative." (let* ((i (if (null? rest) 0 stop)) (stop (if (null? rest) stop (car rest))) (step (if (or (null? rest) (null? (cdr rest))) 1 (cadr rest))) (test (cond ((> i stop) (lambda (i) (and (< step 0) (>= i stop)))) ((< i stop) (lambda (i) (and (> step 0) (< i stop)))) (else (lambda () #f)))) (result (vector))) (typecheck "range" i "number" 1) (typecheck "range" step "number" 2) (typecheck "range" stop "number" 3) (while (test i) (result.push i) (set! i (+ i step))) (array->list result))) -(define-macro (do-iterator spec cond . body) "(do-iterator (var expr) (test) body ...)\u000A\u000AMacro iterate over iterators (e.g. create with JavaScript generator function)\u000Ait works with normal and async iterators. You can loop over infinite iterators\u000Aand break the loop if you want, using expression like in do macro, long sync iterators\u000Awill block main thread (you can't print 1000 numbers from inf iterators,\u000Abecause it will freeze the browser), but if you use async iterators you can process\u000Athe values as they are generated." (let ((gen (gensym "name")) (name (car spec)) (async (gensym "async")) (sync (gensym "sync")) (iterator (gensym "iterator")) (test (if (null? cond) #f (car cond))) (next (gensym "next")) (stop (gensym "stop")) (item (gensym "item"))) (quasiquote (let* (((unquote gen) (unquote (cadr spec))) ((unquote sync) (. (unquote gen) Symbol.iterator)) ((unquote async) (. (unquote gen) Symbol.asyncIterator)) ((unquote iterator)) ((unquote next) (lambda () ((. (unquote iterator) "next"))))) (if (or (procedure? (unquote sync)) (procedure? (unquote async))) (begin (set! (unquote iterator) (if (procedure? (unquote sync)) ((unquote sync)) ((unquote async)))) (let* (((unquote item) ((unquote next))) ((unquote stop) #f) ((unquote name) (. (unquote item) "value"))) (while (not (or (eq? (. (unquote item) "done") #t) (unquote stop))) (if (unquote test) (set! (unquote stop) #t) (begin (unquote-splicing body))) (set! (unquote item) ((unquote next))) (set! (unquote name) (. (unquote item) "value")))))))))) +(define (range stop . rest) "(range stop)\u000A(range start stop)\u000A(range start stop step)\u000A\u000AReturns a list of numbers from start to stop with optional step.\u000AIf start is not defined it starts from 0. If start is larger than stop\u000Athe step needs to be negative otherwise it will hang in an infinite loop." (let* ((i (if (null? rest) 0 stop)) (stop (if (null? rest) stop (car rest))) (step (if (or (null? rest) (null? (cdr rest))) 1 (cadr rest))) (test (cond ((> i stop) (lambda (i) (and (< step 0) (>= i stop)))) ((< i stop) (lambda (i) (and (> step 0) (< i stop)))) (else (lambda () #f)))) (result (vector))) (typecheck "range" i "number" 1) (typecheck "range" step "number" 2) (typecheck "range" stop "number" 3) (while (test i) (result.push i) (set! i (+ i step))) (array->list result))) +(define-macro (do-iterator spec cond . body) "(do-iterator (var expr) (test) body ...)\u000A\u000AIterates over iterators (e.g. creates with JavaScript generator function)\u000Athat works with normal and async iterators. You can loop over infinite iterators\u000Aand break the loop if you want, using expression like in do macro. Long synchronous iterators\u000Awill block the main thread (you can't print 1000 numbers from infinite iterators,\u000Abecause it will freeze the browser), but if you use async iterators you can process\u000Athe values as they are generated." (let ((gen (gensym "name")) (name (car spec)) (async (gensym "async")) (sync (gensym "sync")) (iterator (gensym "iterator")) (test (if (null? cond) #f (car cond))) (next (gensym "next")) (stop (gensym "stop")) (item (gensym "item"))) (quasiquote (let* (((unquote gen) (unquote (cadr spec))) ((unquote sync) (. (unquote gen) Symbol.iterator)) ((unquote async) (. (unquote gen) Symbol.asyncIterator)) ((unquote iterator)) ((unquote next) (lambda () ((. (unquote iterator) "next"))))) (if (or (procedure? (unquote sync)) (procedure? (unquote async))) (begin (set! (unquote iterator) (if (procedure? (unquote sync)) ((unquote sync)) ((unquote async)))) (let* (((unquote item) ((unquote next))) ((unquote stop) #f) ((unquote name) (. (unquote item) "value"))) (while (not (or (eq? (. (unquote item) "done") #t) (unquote stop))) (if (unquote test) (set! (unquote stop) #t) (begin (unquote-splicing body))) (set! (unquote item) ((unquote next))) (set! (unquote name) (. (unquote item) "value")))))))))) (set-repr! Set (lambda () "#<Set>")) (set-repr! Map (lambda () "#<Map>")) -(define (native-symbol? x) "(native-symbol? object)\u000A\u000AFunction check if value is JavaScript symbol." (and (string=? (type x) "symbol") (not (symbol? x)))) +(define (native-symbol? x) "(native-symbol? object)\u000A\u000AChecks if value is JavaScript Symbol." (and (string=? (type x) "symbol") (not (symbol? x)))) (set-special! "’" (quote warn-quote)) -(define-macro (warn-quote) "(warn-quote)\u000A\u000ASimple macro that throw error, when you try to use ’ symbol as quote in code" (throw (new Error (string-append "You're using invalid quote character run: " "(set-special! \"’\" 'quote)" " to allow running this type of quote")))) -(define-macro (let-env-values env spec . body) "(let-env-values env ((name var)) . body)\u000A\u000AMacro add mapping for variables var from specified env,\u000AMacro work similar to let-env but lexical scope is working with it." (let ((env-name (gensym (quote env)))) (quasiquote (let (((unquote env-name) (unquote env))) (let (unquote (map (lambda (pair) (quasiquote ((unquote (car pair)) (--> (unquote env-name) (get (quote (unquote (cadr pair)))))))) spec)) (unquote-splicing body)))))) -(define (apropos name) "(apropos name)\u000A\u000ASearch environment and display names that match the given name.\u000Aname can be regex, string or symbol." (typecheck "apropos" name (quote ("string" "regex" "symbol"))) (let ((regex (lambda (string) (new RegExp (escape-regex string))))) (filter (cond ((string? name) (regex name)) ((symbol? name) (regex (symbol->string name))) (else name)) (env (interaction-environment))))) -(define (promisify fn) "(promisify fn)\u000A\u000ASimple function for adding promises to NodeJS callback based function.\u000AFunction tested only with fs module." (lambda args (new Promise (lambda (resolve reject) (apply fn (append args (list (lambda (err data) (if (null? err) (resolve data) (reject err)))))))))) -(define-macro (list* . args) "(list* arg1 ...)\u000A\u000AParallel version of list." (let ((result (gensym "result"))) (quasiquote (let (((unquote result) (vector))) (unquote-splicing (map (lambda (arg) (quasiquote (--> (unquote result) (push (quote-promise (unquote arg)))))) args)) (map await (vector->list (unquote result))))))) -(define-macro (%not-implemented name) "(not-implemented name)\u000A\u000AReturns new function taht throw exception that function is not implmeneted" (let ((str-name (symbol->string name))) (quasiquote (lambda () (unquote (string-append "(" str-name ")\u000A\u000AThis function is not yet implemented.")) (throw (new Error (unquote (string-append str-name " has not beed implemented")))))))) -(define-macro (%make-env name . names) "(%make-env name f1 f2 ...)\u000A\u000ACreate new Environment with given name and defined symbols in it from global env.\u000AIf given function name f1 f2 ... don't exists, it will define function that\u000Athrow exception that function is not yet implemented." (quasiquote (new lips.Environment (alist->object (list (unquote-splicing (map (lambda (name) (quasiquote (cons (quote (unquote name)) (unquote (let ((ref (lips.env.ref name))) (if (null? ref) (quasiquote (%not-implemented (unquote name))) (quasiquote (lips.env.get (quote (unquote name)))))))))) names)))) null (unquote name)))) +(define-macro (warn-quote) "(warn-quote)\u000A\u000ASimple macro that throws an error, when you try to use ’ symbol as quote in code." (throw (new Error (string-append "You're using an invalid Unicode quote character. Run: " "(set-special! \"’\" 'quote)" " to allow the use of this type of quote")))) +(define-macro (let-env-values env spec . body) "(let-env-values env ((name var)) . body)\u000A\u000AAdds mappings for variables var from specified env.\u000Ait is similar to let-env but lexical scope is working with it." (let ((env-name (gensym (quote env)))) (quasiquote (let (((unquote env-name) (unquote env))) (let (unquote (map (lambda (pair) (quasiquote ((unquote (car pair)) (--> (unquote env-name) (get (quote (unquote (cadr pair)))))))) spec)) (unquote-splicing body)))))) +(define (apropos name) "(apropos name)\u000A\u000ASearch the current environment and display names that match the given name.\u000Aname can be regex, string or symbol." (typecheck "apropos" name (quote ("string" "regex" "symbol"))) (let ((regex (lambda (string) (new RegExp (escape-regex string))))) (filter (cond ((string? name) (regex name)) ((symbol? name) (regex (symbol->string name))) (else name)) (env (interaction-environment))))) +(define (promisify fn) "(promisify fn)\u000A\u000ASimple function for adding promises to NodeJS two-callback based functions.\u000AFunction tested only with fs module." (lambda args (new Promise (lambda (resolve reject) (apply fn (append args (list (lambda (err data) (if (null? err) (resolve data) (reject err)))))))))) +(define-macro (list* . args) "(list* arg1 ...)\u000A\u000AParallel asynchronous version of list. Like begin* except all values are returned in a list." (let ((result (gensym "result"))) (quasiquote (let (((unquote result) (vector))) (unquote-splicing (map (lambda (arg) (quasiquote (--> (unquote result) (push (quote-promise (unquote arg)))))) args)) (map await (vector->list (unquote result))))))) +(define-macro (%not-implemented name) "(%not-implemented name)\u000A\u000AReturns new function that throws an exception with a message that this function is not implmeneted." (let ((str-name (symbol->string name))) (quasiquote (lambda () (unquote (string-append "(" str-name ")\u000A\u000AThis function is not yet implemented.")) (throw (new Error (unquote (string-append str-name " has not beed implemented")))))))) +(define-macro (%make-env name . names) "(%make-env name f1 f2 ...)\u000A\u000ACreates a new Environment with given name and defined symbols in it from the global env.\u000AIf given function name f1 f2 ... don't exist, it will define them as functions that\u000Athrow exception that function is not yet implemented." (quasiquote (new lips.Environment (alist->object (list (unquote-splicing (map (lambda (name) (quasiquote (cons (quote (unquote name)) (unquote (let ((ref (lips.env.ref name))) (if (null? ref) (quasiquote (%not-implemented (unquote name))) (quasiquote (lips.env.get (quote (unquote name)))))))))) names)))) null (unquote name)))) (define Y (lambda (h) "(Y f)\u000A\u000A _ __ __ _ _ _ _ __ __ _ _ _\u000A / \\ \\ / / / __ / ____ \\ / \\ \\ / / ____ \\ \\ \\\u000A+ \\ v / + \\ \\ + / ___| + + \\ v / / ___| + + +\u000A| \\ / | \\ \\ | | |__ | | \\ / | |__ | | |\u000A| | | | / \\ | | __| | | | | | __| | | |\u000A| | | | / /\\ \\ | | | | | | | | | | | |\u000A+ |_| + /_/ \\_\\ + |_| + + |_| |_| + + +\u000A \\_ \\_ \\_ _/ \\_ _/ _/ _/" ((lambda (x) (x x)) (lambda (g) (h (lambda args (apply (g g) args))))))) -(define (indexed-db?) "(indexed-db?)\u000A\u000AFunction test if indexedDB is available." (let* ((any (lambda args (let iter ((args args)) (if (null? args) #f (if (not (null? (car args))) (car args) (iter (cdr args))))))) (indexedDB (any window.indexedDB window.indexedDB window.mozIndexedDB window.webkitIndexedDB))) (if (not (null? indexedDB)) (try (begin (window.indexedDB.open "MyTestDatabase" 3) #t) (catch (e) #f)) #f))) -(define (environment? obj) "(environment? obj)\u000A\u000AFunction check if object is LIPS environment." (instanceof lips.Environment obj)) -(define %read-file (let ((read-file #f) (fetch-url #f)) (lambda (binary path) "(%read-file binary path)\u000A\u000ARead file from url or file system. If binary is false it will return\u000Astring that contain all the content. For HTTP requests, If binary\u000Ais false it will: when in browser return ArrayBuffer and in Node\u000Ait will return Buffer object. When reading from file system\u000Ain both cases it will return Buffer objects.\u000A\u000AThe code that use those function, in binary mode, need to check\u000Aif the result is ArrayBuffer or Node.js/BrowserFS Buffer object." (if (not read-file) (let ((fs (--> (interaction-environment) (get (quote **internal-env**)) (get (quote fs) &(:throwError #f))))) (if (null? fs) (throw (new Error "open-input-file: fs not defined")) (let ((*read-file* (promisify fs.readFile))) (set! read-file (lambda (path binary) (let ((buff (*read-file* path))) (if binary (if (eq? self window) (new Blob (vector buff)) buff) (--> buff (toString)))))))))) (if (not fetch-url) (set! fetch-url (lambda (url binary) (if (eq? self window) (let ((res (fetch url))) (if binary (res.arrayBuffer) (res.text))) (http-get url binary))))) (cond ((char=? (string-ref path 0) #\/) (if (not (file-exists? path)) (throw (new Error (string-append "file " path " don't exists"))) (read-file path binary))) ((--> #/^https?:\/\// (test path)) (fetch-url path binary)) (else (%read-file binary (string-append (current-directory) path))))))) +(define (indexed-db?) "(indexed-db?)\u000A\u000AFunction that tests if IndexedDB is available." (let* ((any (lambda args (let iter ((args args)) (if (null? args) #f (if (not (null? (car args))) (car args) (iter (cdr args))))))) (indexedDB (any window.indexedDB window.indexedDB window.mozIndexedDB window.webkitIndexedDB))) (if (not (null? indexedDB)) (try (begin (window.indexedDB.open "IndexedDBExistenceCheck" 3) #t) (catch (e) #f)) #f))) +(define (environment? obj) "(environment? obj)\u000A\u000AChecks if object is a LIPS environment." (instanceof lips.Environment obj)) +(define %read-file (let ((read-file #f) (fetch-url #f)) (lambda (binary path) "(%read-file binary path)\u000A\u000ARead file from url or file system. If binary is false it will return a\u000Astring that contain all the content. For HTTP requests, if binary\u000Ais false it will return an ArrayBuffer (when in a browser) or a Buffer\u000A(when in NodeJS). When reading from the file system in both cases it will\u000Areturn Buffer objects.\u000A\u000ACode that uses this function in binary mode needs to check\u000Aif the result is ArrayBuffer or Node.js/BrowserFS Buffer object." (if (not read-file) (let ((fs (--> (interaction-environment) (get (quote **internal-env**)) (get (quote fs) &(:throwError #f))))) (if (null? fs) (throw (new Error "open-input-file: fs not defined")) (let ((*read-file* (promisify fs.readFile))) (set! read-file (lambda (path binary) (let ((buff (*read-file* path))) (if binary (if (eq? self window) (new Blob (vector buff)) buff) (--> buff (toString)))))))))) (if (not fetch-url) (set! fetch-url (lambda (url binary) (if (eq? self window) (let ((res (fetch url))) (if binary (res.arrayBuffer) (res.text))) (http-get url binary))))) (cond ((char=? (string-ref path 0) #\/) (if (not (file-exists? path)) (throw (new Error (string-append "file " path " don't exists"))) (read-file path binary))) ((--> #/^https?:\/\// (test path)) (fetch-url path binary)) (else (%read-file binary (string-append (current-directory) path))))))) (define %read-binary-file (curry %read-file #t)) (define %read-text-file (curry %read-file #f)) -(define (%fs-promisify-proc fn message) "(%fs-promisify-proc fn string)\u000A\u000AFunction return promisified version of fs function or throw exception\u000Aif fs is not available." (let ((fs (--> lips.env (get (quote **internal-env**)) (get (quote fs))))) (if (null? fs) (throw (new Error (string-append message ": fs not defined"))) (promisify (. fs fn))))) -(define (response->content binary res) "(response->text binary res)\u000A\u000AFunction read all text from Node.js HTTP response object. If binary argument\u000Ais true it will return Buffer object that can be converted to u8vector.\u000A\u000A***Warrning:*** it may overflow the stack (part of Node) when converting\u000Awhole buffer to u8vector." (let ((result (vector)) (append (if binary (lambda (chunk) (result.push (Buffer.from chunk "binary"))) (lambda (chunk) (result.push chunk))))) (res.setEncoding (if binary "binary" "utf8")) (new Promise (lambda (resolve) (res.on "data" append) (res.on "end" (lambda () (if binary (resolve (Buffer.concat result)) (resolve (result.join ""))))))))) +(define (%fs-promisify-proc fn message) "(%fs-promisify-proc fn string)\u000A\u000AReturns a promisified version of a fs function or throws an exception\u000Aif fs is not available." (let ((fs (--> lips.env (get (quote **internal-env**)) (get (quote fs))))) (if (null? fs) (throw (new Error (string-append message ": fs not defined"))) (promisify (. fs fn))))) +(define (response->content binary res) "(response->text binary res)\u000A\u000AReads all text from a Node.js HTTP response object. If binary argument\u000Ais true it will return Buffer object that can be converted to u8vector.\u000A\u000A***Warrning:*** it may overflow the Javascript call stack when converting the\u000Awhole buffer to u8vector, because LIPS doesn't have TCO." (let ((result (vector)) (append (if binary (lambda (chunk) (result.push (Buffer.from chunk "binary"))) (lambda (chunk) (result.push chunk))))) (res.setEncoding (if binary "binary" "utf8")) (new Promise (lambda (resolve) (res.on "data" append) (res.on "end" (lambda () (if binary (resolve (Buffer.concat result)) (resolve (result.join ""))))))))) (define response->buffer (curry response->content #t)) (define response->text (curry response->content #f)) -(define http-get (if (eq? self window) (lambda (url binary) "(http-get url)\u000A\u000ANode.js Function that send HTTP Request and return string or\u000Abinary Buffer object." (throw (new Error "http-get: function is Node.js only."))) (let* ((http (. (require "http") (quote get))) (https (. (require "https") (quote get)))) (lambda (url binary) "(http-get url)\u000A\u000ANode.js Function that send HTTP Request and return string or\u000Abinary Buffer object." (let ((request (if (null? (url.match #/^https/)) http https))) (new Promise (lambda (resolve reject) (--> (request url (lambda (res) (if (= res.statusCode 200) (resolve (response->content binary res)) (let ((code res.statusCode)) (res.resume) (reject (string-append "Request return " (number->string code))))))) (on "error" reject))))))))) -(define (buffer->u8vector bin) "(buffer->u8vector bin)\u000A\u000ACross platform function that can be used in both Node and Browser.\u000AIt can be used together with %read-file or %read-binary-file and convert\u000Athe result ArrayBuffer or Buffer to u8vector." (if (instanceof ArrayBuffer bin) (new Uint8Array bin) (Uint8Array.from bin))) -(define (complement fn) "(complement fn)\u000A\u000AHiger order function that returns complement of the given function. If the function fn\u000Afor a given arguments return true the result function will return false, if it would\u000Areturn false, the result function will return true." (typecheck "complement" fn "function") (lambda args (not (apply fn args)))) -(define (always constant) "(always constant)\u000A\u000AHigher order function returns new function that always return given constant." (lambda () constant)) -(define (once fn) "(once fn)\u000A\u000AHigher order function that return new function, that is guarantee\u000Ato be called only once." (typecheck "once" fn "function") (let ((result)) (lambda args (if (string=? (type result) "undefined") (set! result (apply fn args))) result))) -(define (flip fn) "(flip fn)\u000A\u000AHigher order function that return new function where first two arguments are swapped.\u000A\u000AExample:\u000A\u000A (define first (curry (flip vector-ref) 0))\u000A (first #(1 2 3))\u000A ;; ==> 1" (typecheck "flip" fn "function") (lambda (a b . rest) (apply fn b a rest))) -(define (unfold fn init) "(unfold fn init)\u000A\u000AFunction returns list from given function and init value. The function should\u000Areturn cons where first is the item added to the list and second is next value\u000Apassed to the funtion. If function return false it end the loop." (typecheck "unfold" fn "function") (let iter ((pair (fn init)) (result (quote ()))) (if (not pair) (reverse result) (iter (fn (cdr pair)) (cons (car pair) result))))) +(define http-get (if (eq? self window) (lambda (url binary) "(http-get url)\u000A\u000AThis function is only available when running LIPS in NodeJS." (throw (new Error "http-get: function is Node.js only."))) (let* ((http (. (require "http") (quote get))) (https (. (require "https") (quote get)))) (lambda (url binary) "(http-get url)\u000A\u000ANode.js function that sends a HTTP Request and returns a string or\u000Abinary Buffer object." (let ((request (if (null? (url.match #/^https/)) http https))) (new Promise (lambda (resolve reject) (--> (request url (lambda (res) (if (= res.statusCode 200) (resolve (response->content binary res)) (let ((code res.statusCode)) (res.resume) (reject (string-append "Request return " (number->string code))))))) (on "error" reject))))))))) +(define (buffer->u8vector bin) "(buffer->u8vector bin)\u000A\u000ACross platform function that can be used in both Node and browser.\u000AIt can be used together with %read-file or %read-binary-file to convert\u000Athe result ArrayBuffer or Buffer to u8vector." (if (instanceof ArrayBuffer bin) (new Uint8Array bin) (Uint8Array.from bin))) +(define (complement fn) "(complement fn)\u000A\u000AHiger order function that returns the Boolean complement of the given function. If the function fn\u000Afor a given arguments return true the result function will return false, if it would\u000Areturn false, the result function will return true." (typecheck "complement" fn "function") (lambda args (not (apply fn args)))) +(define (always constant) "(always constant)\u000A\u000AHigher-order function that returns a new thunk that always returns the given constant when called." (lambda () constant)) +(define (once fn) "(once fn)\u000A\u000AHigher-order function that returns a new function, that only calls the original\u000Aon the first invocation, and immediately returns the first call's result again\u000Aon subsequent invocations." (typecheck "once" fn "function") (let ((result)) (lambda args (if (string=? (type result) "undefined") (set! result (apply fn args))) result))) +(define (flip fn) "(flip fn)\u000A\u000AHigher-order function that returns a new function where the first two arguments are swapped.\u000A\u000AExample:\u000A\u000A (define first (curry (flip vector-ref) 0))\u000A (first #(1 2 3))\u000A ;; ==> 1" (typecheck "flip" fn "function") (lambda (a b . rest) (apply fn b a rest))) +(define (unfold fn init) "(unfold fn init)\u000A\u000AReturns a list from the given function and init value. The function should\u000Areturn a pair where first is the item added to the list and second is next value\u000Apassed to the funtion. If the function returns false it ends the loop." (typecheck "unfold" fn "function") (let iter ((pair (fn init)) (result (quote ()))) (if (not pair) (reverse result) (iter (fn (cdr pair)) (cons (car pair) result))))) (define string-join join) (define string-split split) -(define (symbol-append . rest) "(symbol-append s1 s2 ...)\u000A\u000AFunction create new symbol from symbols passed as arguments." (string->symbol (apply string-append (map symbol->string rest)))) -(define-macro (set-global! name) "(set-global! name)\u000A\u000AMacro make the name global variable." (let ((var (symbol-append (quote self.) name))) (quasiquote (set! (unquote var) (unquote name))))) +(define (symbol-append . rest) "(symbol-append s1 s2 ...)\u000A\u000AFunction that creates a new symbol from symbols passed as arguments." (string->symbol (apply string-append (map symbol->string rest)))) +(define-macro (set-global! name) "(set-global! name)\u000A\u000AMacro to make the name a Javascript global variable (i.e. accessible on globalThis)." (let ((var (symbol-append (quote self.) name))) (quasiquote (set! (unquote var) (unquote name))))) (define performance (if (and (eq? self global) (not (bound? (quote performance)))) (. (require "perf_hooks") (quote performance)) performance)) (define string-append concat) (define = ==) @@ -129,119 +129,119 @@ (define list->vector list->array) (define vector->list array->list) (define call-with-current-continuation call/cc) -(define-macro (define-symbol-macro type spec . rest) "(define-symbol-macro type (name . args) . body)\u000A\u000AMacro that creates special symbol macro for evaluator similar to build in , or `.\u000AIt's like alias for real macro. Similar to CL reader macros but it receives already\u000Aparsed code like normal macros. Type can be SPLICE or LITERAL symbols.\u000AALL default symbol macros are literal." (let* ((name (car spec)) (symbol (cadr spec)) (args (cddr spec))) (quasiquote (begin (set-special! (unquote symbol) (quote (unquote name)) (unquote (string->symbol (concat "lips.specials." (symbol->string type))))) (define-macro ((unquote name) (unquote-splicing args)) (unquote-splicing rest)))))) +(define-macro (define-symbol-macro type spec . rest) "(define-symbol-macro type (name . args) . body)\u000A\u000ACreates special symbol macros for evaluator similar to built-in , or `.\u000AIt's like an alias for a real macro. Similar to CL reader macros but it receives already\u000Aparsed code like normal macros. Type can be SPLICE or LITERAL symbols (see set-special!).\u000AALL default symbol macros are literal." (let* ((name (car spec)) (symbol (cadr spec)) (args (cddr spec))) (quasiquote (begin (set-special! (unquote symbol) (quote (unquote name)) (unquote (string->symbol (concat "lips.specials." (symbol->string type))))) (define-macro ((unquote name) (unquote-splicing args)) (unquote-splicing rest)))))) (set-special! "#" (quote vector-literal) lips.specials.SPLICE) (define-macro (vector-literal . args) (if (not (or (pair? args) (eq? args ()))) (throw (new Error (concat "Parse Error: vector require pair got " (type args) " in " (repr args)))) (let ((v (list->array args))) (Object.freeze v) v))) -(define-syntax vector (syntax-rules () ((_ arg ...) (list->array (list arg ...)))) "(vector 1 2 3 (+ 3 1))\u000A#(1 2 3 4)\u000A\u000AMacro for defining vectors (JavaScript arrays). Vector literals are\u000Aautomatically quoted. So you can use expressions inside them. Only other\u000Aliterals, like other vectors or object.") +(define-syntax vector (syntax-rules () ((_ arg ...) (list->array (list arg ...)))) "(vector 1 2 3 (+ 3 1)) or #(1 2 3 4)\u000A\u000AMacro for defining vectors (Javascript Arrays). Vector literals are\u000Aautomatically quoted, so you can't use expressions inside them, only other\u000Aliterals, like other vectors or objects.") (set-repr! Array (lambda (arr q) (let ((result (--> (Array.from arr) (map (lambda (x i) (if (not (in i arr)) "#<empty>" (repr (. arr i) q))))))) (concat "#(" (--> result (join " ")) ")")))) -(define (eqv? a b) "(eqv? a b)\u000A\u000AFunction compare the values. It return true if they are the same, they\u000Aneed to have same type" (if (string=? (type a) (type b)) (cond ((number? a) (or (and (exact? a) (exact? b) (= a b)) (and (inexact? a) (inexact? b) (cond ((a.isNaN) (b.isNaN)) ((and (zero? a) (zero? b)) (eq? a._minus b._minus)) ((and (complex? a) (complex? b)) (let ((re.a (real-part a)) (re.b (real-part b)) (im.a (imag-part a)) (im.b (imag-part b))) (and (if (and (zero? re.a) (zero? re.b)) (eq? (. re.a (quote _minus)) (. re.b (quote _minus))) #t) (if (and (zero? im.a) (zero? im.b)) (eq? (. im.a (quote _minus)) (. im.b (quote _minus))) #t) (or (= re.a re.b) (and (--> re.a (isNaN)) (--> re.b (isNaN)))) (or (= im.a im.b) (and (--> im.a (isNaN)) (--> im.b (isNaN))))))) (else (= a b)))))) ((and (pair? a) (null? a)) (null? b)) (else (eq? a b))) #f)) +(define (eqv? a b) "(eqv? a b)\u000A\u000AFunction that compares the values. It returns true if they are the same, they\u000Aneed to have the same type." (if (string=? (type a) (type b)) (cond ((number? a) (or (and (exact? a) (exact? b) (= a b)) (and (inexact? a) (inexact? b) (cond ((a.isNaN) (b.isNaN)) ((and (zero? a) (zero? b)) (eq? a._minus b._minus)) ((and (complex? a) (complex? b)) (let ((re.a (real-part a)) (re.b (real-part b)) (im.a (imag-part a)) (im.b (imag-part b))) (and (if (and (zero? re.a) (zero? re.b)) (eq? (. re.a (quote _minus)) (. re.b (quote _minus))) #t) (if (and (zero? im.a) (zero? im.b)) (eq? (. im.a (quote _minus)) (. im.b (quote _minus))) #t) (or (= re.a re.b) (and (--> re.a (isNaN)) (--> re.b (isNaN)))) (or (= im.a im.b) (and (--> im.a (isNaN)) (--> im.b (isNaN))))))) (else (= a b)))))) ((and (pair? a) (null? a)) (null? b)) (else (eq? a b))) #f)) (define (equal? a b) "(equal? a b)\u000A\u000AThe function checks if values are equal. If both are a pair or an array\u000Ait compares their elements recursively." (cond ((and (pair? a)) (and (pair? b) (equal? (car a) (car b)) (equal? (cdr a) (cdr b)))) ((symbol? a) (and (symbol? b) (equal? a.__name__ b.__name__))) ((regex? a) (and (regex? b) (equal? (. a (quote source)) (. b (quote source))))) ((typed-array? a) (and (typed-array? b) (equal? (Array.from a) (Array.from b)))) ((vector? a) (and (vector? b) (= (length a) (length b)) (--> a (every (lambda (item i) (equal? item (vector-ref b i))))))) ((string? a) (and (string? b) (string=? a b))) ((function? a) (and (function? b) (%same-functions a b))) ((array? a) (and (array? b) (eq? (length a) (length b)) (= (--> a (filter (lambda (item i) (equal? item (. b i)))) (quote length)) (length a)))) ((plain-object? a) (and (plain-object? b) (let ((keys_a (--> (Object.keys a) (sort))) (keys_b (--> (Object.keys b) (sort)))) (and (= (length keys_a) (length keys_b)) (equal? keys_a keys_b) (equal? (--> keys_a (map (lambda (key) (. a key)))) (--> keys_b (map (lambda (key) (. b key))))))))) (else (eqv? a b)))) -(define make-promise (lambda (proc) "(make-promise fn)\u000A\u000AFunction create promise from a function." (typecheck "make-promise" proc "function") (let ((result-ready? #f) (result #f)) (let ((promise (lambda () (if result-ready? result (let ((x (proc))) (if result-ready? result (begin (set! result-ready? #t) (set! result x) result))))))) (set-obj! promise (Symbol.for "promise") #t) (set! promise.toString (lambda () (string-append "#<promise - " (if result-ready? (string-append "forced with " (type result)) "not forced") ">"))) promise)))) -(define-macro (delay expression) "(delay expression)\u000A\u000AMacro will create a promise from expression that can be forced with (force)." (quasiquote (make-promise (lambda () (unquote expression))))) -(define (force promise) "(force promise)\u000A\u000AFunction forces the promise and evaluates the delayed expression." (promise)) -(define (promise? obj) "(promise? obj)\u000A\u000AFunction checks if value is a promise created with delay or make-promise." (string=? (type obj) "promise")) -(define (positive? x) "(positive? x)\u000A\u000AFunction checks if number is larger then 0" (typecheck "positive?" x "number") (> x 0)) -(define (negative? x) "(negative? x)\u000A\u000AFunction checks if number is smaller then 0" (typecheck "negative?" x "number") (< x 0)) -(define (zero? x) "(zero? x)\u000A\u000AFunction checks if number is equal to 0" (typecheck "zero?" x "number") (= x 0)) +(define make-promise (lambda (proc) "(make-promise fn)\u000A\u000AFunction that creates a promise from a function." (typecheck "make-promise" proc "function") (let ((result-ready? #f) (result #f)) (let ((promise (lambda () (if result-ready? result (let ((x (proc))) (if result-ready? result (begin (set! result-ready? #t) (set! result x) result))))))) (set-obj! promise (Symbol.for "promise") #t) (set! promise.toString (lambda () (string-append "#<promise - " (if result-ready? (string-append "forced with " (type result)) "not forced") ">"))) promise)))) +(define-macro (delay expression) "(delay expression)\u000A\u000AWill create a promise from expression that can be forced with (force)." (quasiquote (make-promise (lambda () (unquote expression))))) +(define (force promise) "(force promise)\u000A\u000AFunction that forces the promise and evaluates the delayed expression." (promise)) +(define (promise? obj) "(promise? obj)\u000A\u000AChecks if the value is a promise created with delay or make-promise." (string=? (type obj) "promise")) +(define (positive? x) "(positive? x)\u000A\u000AChecks if the number is larger then 0" (typecheck "positive?" x "number") (> x 0)) +(define (negative? x) "(negative? x)\u000A\u000AChecks if the number is smaller then 0" (typecheck "negative?" x "number") (< x 0)) +(define (zero? x) "(zero? x)\u000A\u000AChecks if the number is equal to 0" (typecheck "zero?" x "number") (= x 0)) (define (quotient a b) "(quotient a b)\u000A\u000AReturn quotient from division as integer." (typecheck "quotient" a "number") (typecheck "quotient" b "number") (if (zero? b 0) (throw (new Error "quotient: division by zero")) (let ((quotient (/ a b))) (if (integer? quotient) quotient (if (> quotient 0) (floor quotient) (ceiling quotient)))))) -(define (number->string x . rest) "(number->string x [radix])\u000A\u000AFunction converts number to string with optional radix (number base)." (typecheck "number->string" x "number" 1) (let ((radix (if (null? rest) 10 (car rest)))) (typecheck "number->string" radix "number" 2) (--> x (toString (--> radix (valueOf)))))) -(define (boolean? x) "(boolean? x)\u000A\u000AFunction return true if value is boolean." (string=? (type x) "boolean")) -(define (vector-ref vector i) "(vector-ref vector i)\u000A\u000AReturn i element from vector." (typecheck "number->string" vector "array" 1) (typecheck "number->string" i "number" 2) (. vector i)) -(define (vector-set! vector i obj) "(vector-set! vector i obj)\u000A\u000ASet obj as value in vector at position 1." (typecheck "vector-set!" vector "array" 1) (typecheck "vector-set!" i "number" 2) (set-obj! vector i obj)) +(define (number->string x . rest) "(number->string x [radix])\u000A\u000AFunction that converts number to string with optional radix (number base)." (typecheck "number->string" x "number" 1) (let ((radix (if (null? rest) 10 (car rest)))) (typecheck "number->string" radix "number" 2) (--> x (toString (--> radix (valueOf)))))) +(define (boolean? x) "(boolean? x)\u000A\u000AReturns true if value is boolean." (string=? (type x) "boolean")) +(define (vector-ref vector i) "(vector-ref vector i)\u000A\u000AReturn i-th element from vector." (typecheck "number->string" vector "array" 1) (typecheck "number->string" i "number" 2) (. vector i)) +(define (vector-set! vector i obj) "(vector-set! vector i obj)\u000A\u000ASet obj as value in vector at position i." (typecheck "vector-set!" vector "array" 1) (typecheck "vector-set!" i "number" 2) (set-obj! vector i obj)) (define (%number-type type x) (typecheck "%number-type" type (vector "string" "pair")) (typecheck "%number-type" x "number") (let* ((t x.__type__) (typeof (lambda (type) (string=? t type)))) (and (number? x) (if (pair? type) (some typeof type) (typeof type))))) -(define (real? x) "(real? x)\u000A\u000AFunction checks if argument x is real." (and (number? x) (or (eq? x +nan.0) (eq? x Number.NEGATIVE_INFINITY) (eq? x Number.POSITIVE_INFINITY) (and (%number-type "complex" x) (let ((i (imag-part x))) (and (zero? i) (exact? i)))) (%number-type (quote ("float" "bigint" "rational")) x)))) -(define (integer? x) "(integer? x)\u000A\u000AFunction checks if argument x is integer." (and (number? x) (not (eq? x +nan.0)) (not (eq? x Number.NEGATIVE_INFINITY)) (not (eq? x Number.POSITIVE_INFINITY)) (or (%number-type "bigint" x) (and (%number-type "float" x) (= (modulo x 2) 1))))) -(define (complex? x) "(complex? x)\u000A\u000AFunction check if argument x is complex." (and (number? x) (or (eq? x +nan.0) (eq? x Number.NEGATIVE_INFINITY) (eq? x Number.POSITIVE_INFINITY) (%number-type (quote ("complex" "float" "bigint" "rational")) x)))) -(define (rational? x) "(rational? x)\u000A\u000AFunction checks if value is rational." (and (number? x) (not (eq? x +nan.0)) (not (eq? x Number.NEGATIVE_INFINITY)) (not (eq? x Number.POSITIVE_INFINITY)) (or (%number-type "rational" x) (integer? x)))) -(define (typecheck-args _type name _list) "(typecheck-args args type)\u000A\u000AFunction checks if all items in the array are of same type." (let iter ((n 1) (_list _list)) (if (pair? _list) (begin (typecheck name (car _list) _type n) (iter (+ n 1) (cdr _list)))))) +(define (real? x) "(real? x)\u000A\u000AChecks if the argument x is real." (and (number? x) (or (eq? x +nan.0) (eq? x Number.NEGATIVE_INFINITY) (eq? x Number.POSITIVE_INFINITY) (and (%number-type "complex" x) (let ((i (imag-part x))) (and (zero? i) (exact? i)))) (%number-type (quote ("float" "bigint" "rational")) x)))) +(define (integer? x) "(integer? x)\u000A\u000AChecks if the argument x is integer." (and (number? x) (not (eq? x +nan.0)) (not (eq? x Number.NEGATIVE_INFINITY)) (not (eq? x Number.POSITIVE_INFINITY)) (or (%number-type "bigint" x) (and (%number-type "float" x) (= (modulo x 2) 1))))) +(define (complex? x) "(complex? x)\u000A\u000AChecks if argument x is complex." (and (number? x) (or (eq? x +nan.0) (eq? x Number.NEGATIVE_INFINITY) (eq? x Number.POSITIVE_INFINITY) (%number-type (quote ("complex" "float" "bigint" "rational")) x)))) +(define (rational? x) "(rational? x)\u000A\u000AChecks if the value is rational." (and (number? x) (not (eq? x +nan.0)) (not (eq? x Number.NEGATIVE_INFINITY)) (not (eq? x Number.POSITIVE_INFINITY)) (or (%number-type "rational" x) (integer? x)))) +(define (typecheck-args _type name _list) "(typecheck-args args type)\u000A\u000AFunction that makes sure that all items in the array are of same type." (let iter ((n 1) (_list _list)) (if (pair? _list) (begin (typecheck name (car _list) _type n) (iter (+ n 1) (cdr _list)))))) (define numbers? (curry typecheck-args "number")) -(define (max . args) "(max n1 n2 ...)\u000A\u000AReturn maximum of it's arguments." (numbers? "max" args) (apply Math.max args)) -(define (min . args) "(min n1 n2 ...)\u000A\u000AReturn minimum of it's arguments." (numbers? "min" args) (apply Math.min args)) -(define (make-rectangular re im) "(make-rectangular im re)\u000A\u000ACreate complex number from imaginary and real part." (let ((value (quasiquote ((re unquote re) (im unquote im))))) (lips.LComplex (--> value (to_object #t))))) +(define (max . args) "(max n1 n2 ...)\u000A\u000AReturns the maximum of its arguments." (numbers? "max" args) (apply Math.max args)) +(define (min . args) "(min n1 n2 ...)\u000A\u000AReturns the minimum of its arguments." (numbers? "min" args) (apply Math.min args)) +(define (make-rectangular re im) "(make-rectangular im re)\u000A\u000ACreates a complex number from imaginary and real part (a+bi form)." (let ((value (quasiquote ((re unquote re) (im unquote im))))) (lips.LComplex (--> value (to_object #t))))) (define (exact? n) "(exact? n)" (typecheck "exact?" n "number") (let ((type n.__type__)) (or (string=? type "bigint") (string=? type "rational") (and (string=? type "complex") (exact? n.__im__) (exact? n.__re__))))) (define (inexact? n) "(inexact? n)" (typecheck "inexact?" n "number") (not (exact? n))) (define (exact->inexact n) "(exact->inexact n)\u000A\u000AConvert exact number to inexact." (typecheck "exact->inexact" n "number") (if (%number-type "complex" n) (lips.LComplex (object :im (exact->inexact (. n (quote __im__))) :re (exact->inexact (. n (quote __re__))))) (if (or (rational? n) (integer? n)) (lips.LFloat (--> n (valueOf)) #t) n))) -(define (inexact->exact n) "(inexact->exact number)\u000A\u000AFunction converts real number to exact rational number." (typecheck "inexact->exact" n "number") (if (exact? n) n (--> n (toRational)))) -(define (log z) "(log z)\u000A\u000AFunction calculates natural logarithm of z where the argument can be\u000Aany number (including complex negative and rational).\u000AIf the value is 0 it return NaN." (cond ((real? z) (cond ((zero? z) +nan.0) ((> z 0) (Math.log z)) (else (+ (Math.log (abs z)) (* Math.PI +1i))))) ((complex? z) (let ((arg (Math.atan2 (imag-part z) (real-part z)))) (+ (Math.log (z.modulus)) (* +1i arg)))) ((rational? z) (log (exact->inexact z))))) +(define (inexact->exact n) "(inexact->exact number)\u000A\u000AFunction that converts real number to exact rational number." (typecheck "inexact->exact" n "number") (if (exact? n) n (--> n (toRational)))) +(define (log z) "(log z)\u000A\u000AFunction that calculates natural logarithm of z where the argument can be\u000Aany number (including complex negative and rational).\u000AIf the value is 0 it return NaN." (cond ((real? z) (cond ((zero? z) +nan.0) ((> z 0) (Math.log z)) (else (+ (Math.log (abs z)) (* Math.PI +1i))))) ((complex? z) (let ((arg (Math.atan2 (imag-part z) (real-part z)))) (+ (Math.log (z.modulus)) (* +1i arg)))) ((rational? z) (log (exact->inexact z))))) (define _maths (list "sin" "cos" "tan" "asin" "acos" "atan" "atan")) (define _this_env (current-environment)) -(let iter ((fns _maths)) (if (not (null? fns)) (let* ((name (car fns)) (op (. Math name)) (fn (lambda (n) (lips.LNumber (op n))))) (--> _this_env (set name fn)) (set-obj! fn (quote __doc__) (concat "(" name " n)\u000A\u000AFunction calculate " name " math operation (it call JavaScript Math." name " function)")) (iter (cdr fns))))) -(define (sin n) "(sin n)\u000A\u000AFunction calculate sine of a number." (typecheck "sin" n "number") (if (string=? n.__type__ "complex") (let ((re (real-part n)) (im (imag-part n))) (lips.LComplex (object :re (* (Math.sin re) (Math.cosh im)) :im (* (Math.cos re) (Math.sinh im))))) (Math.sin n))) -(define (cos n) "(cos n)\u000A\u000AFunction calculate cosine of a number." (typecheck "cos" n "number") (if (string=? n.__type__ "complex") (let ((re (real-part n)) (im (imag-part n))) (lips.LComplex (object :re (* (Math.cos re) (Math.cosh im)) :im (- (* (Math.sin re) (Math.sinh im)))))) (Math.cos n))) -(define (tan n) "(tan n)\u000A\u000AFunction calculate tanent of a number." (typecheck "tan" n "number") (if (string=? n.__type__ "complex") (let* ((re (real-part n)) (im (imag-part n)) (re2 (* 2 re)) (im2 (* 2 im))) (lips.LComplex (object :re (/ (Math.sin re2) (+ (Math.cos re2) (Math.cosh im2))) :im (/ (Math.sinh im2) (+ (Math.cos re2) (Math.cosh im2)))))) (Math.tan n))) -(define (exp n) "(exp n)\u000A\u000AFunction calculate e rised to the power of n." (typecheck "exp" n "number") (if (string=? n.__type__ "complex") (let* ((re (real-part n)) (im (imag-part n)) (factor (Math.exp re))) (make-rectangular (* factor (cos im)) (* factor (sin im)))) (Math.exp n))) -(define (modulo a b) "(modulo a b)\u000A\u000AFunction returns modulo operation on it's argumennts." (typecheck "modulo" a "number" 1) (typecheck "modulo" b "number" 2) (- a (* b (floor (/ a b))))) -(define (remainder__ a b) "(modulo a b)\u000A\u000AFunction returns reminder from division operation." (typecheck "remainder" a "number" 1) (typecheck "remainder" b "number" 2) (- a (* b (truncate (/ a b))))) +(let iter ((fns _maths)) (if (not (null? fns)) (let* ((name (car fns)) (op (. Math name)) (fn (lambda (n) (lips.LNumber (op n))))) (--> _this_env (set name fn)) (set-obj! fn (quote __doc__) (concat "(" name " n)\u000A\u000AFunction that calculates " name " math operation (it call JavaScript Math." name " function)")) (iter (cdr fns))))) +(define (sin n) "(sin n)\u000A\u000AFunction that calculates sine of a number." (typecheck "sin" n "number") (if (string=? n.__type__ "complex") (let ((re (real-part n)) (im (imag-part n))) (lips.LComplex (object :re (* (Math.sin re) (Math.cosh im)) :im (* (Math.cos re) (Math.sinh im))))) (Math.sin n))) +(define (cos n) "(cos n)\u000A\u000AFunction that calculates cosine of a number." (typecheck "cos" n "number") (if (string=? n.__type__ "complex") (let ((re (real-part n)) (im (imag-part n))) (lips.LComplex (object :re (* (Math.cos re) (Math.cosh im)) :im (- (* (Math.sin re) (Math.sinh im)))))) (Math.cos n))) +(define (tan n) "(tan n)\u000A\u000AFunction that calculates tangent of a number." (typecheck "tan" n "number") (if (string=? n.__type__ "complex") (let* ((re (real-part n)) (im (imag-part n)) (re2 (* 2 re)) (im2 (* 2 im))) (lips.LComplex (object :re (/ (Math.sin re2) (+ (Math.cos re2) (Math.cosh im2))) :im (/ (Math.sinh im2) (+ (Math.cos re2) (Math.cosh im2)))))) (Math.tan n))) +(define (exp n) "(exp n)\u000A\u000AFunction that calculates e raised to the power of n." (typecheck "exp" n "number") (if (string=? n.__type__ "complex") (let* ((re (real-part n)) (im (imag-part n)) (factor (Math.exp re))) (make-rectangular (* factor (cos im)) (* factor (sin im)))) (Math.exp n))) +(define (modulo a b) "(modulo a b)\u000A\u000AReturns modulo operation on its argumennts." (typecheck "modulo" a "number" 1) (typecheck "modulo" b "number" 2) (- a (* b (floor (/ a b))))) +(define (remainder__ a b) "(modulo a b)\u000A\u000AReturns remainder from division operation." (typecheck "remainder" a "number" 1) (typecheck "remainder" b "number" 2) (- a (* b (truncate (/ a b))))) (define (list-tail l k) "(list-tail list k)\u000A\u000AReturns the sublist of list obtained by omitting the first k elements." (typecheck "list-tail" l (quote ("pair" "nil"))) (if (< k 0) (throw (new Error "list-ref: index out of range")) (let ((l l) (k k)) (while (> k 0) (if (null? l) (throw (new Error "list-tail: not enough elements in the list"))) (set! l (cdr l)) (set! k (- k 1))) l))) -(define (list-ref l k) "(list-ref list n)\u000A\u000AReturns n element of a list." (typecheck "list-ref" l (quote ("pair" "nil"))) (if (< k 0) (throw (new Error "list-ref: index out of range")) (let ((l l) (k k)) (while (> k 0) (if (or (null? (cdr l)) (null? l)) (throw (new Error "list-ref: not enough elements in the list"))) (set! l (cdr l)) (set! k (- k 1))) (if (null? l) l (car l))))) -(define (not x) "(not x)\u000A\u000AFunction return true if value is false and false otherwise." (if x #f #t)) -(define (rationalize number tolerance) "(rationalize number tolerance)\u000A\u000AFunction returns simplest rational number differing from number by no more\u000Athan the tolerance." (typecheck "rationalize" number "number" 1) (typecheck "rationalize" tolerance "number" 2) (lips.rationalize number tolerance)) -(define (%mem/search access op obj list) "(%member obj list function)\u000A\u000AHelper method to get first list where car equal to obj\u000Ausing provied functions as comparator." (if (null? list) #f (if (op (access list) obj) list (%mem/search access op obj (cdr list))))) -(define (memq obj list) "(memq obj list)\u000A\u000AFunction return first object in the list that match using eq? function." (typecheck "memq" list (quote ("nil" "pair"))) (%mem/search car eq? obj list)) -(define (memv obj list) "(memv obj list)\u000A\u000AFunction return first object in the list that match using eqv? function." (typecheck "memv" list (quote ("nil" "pair"))) (%mem/search car eqv? obj list)) -(define (member obj list) "(member obj list)\u000A\u000AFunction returns first object in the list that match using equal? function." (typecheck "member" list (quote ("nil" "pair"))) (%mem/search car equal? obj list)) -(define (%assoc/acessor name) "(%assoc/acessor name)\u000A\u000AFunction return carr with typecheck using give name." (lambda (x) (typecheck name x "pair") (caar x))) +(define (list-ref l k) "(list-ref list n)\u000A\u000AReturns n-th element of a list." (typecheck "list-ref" l (quote ("pair" "nil"))) (if (< k 0) (throw (new Error "list-ref: index out of range")) (let ((l l) (k k)) (while (> k 0) (if (or (null? (cdr l)) (null? l)) (throw (new Error "list-ref: not enough elements in the list"))) (set! l (cdr l)) (set! k (- k 1))) (if (null? l) l (car l))))) +(define (not x) "(not x)\u000A\u000AReturns true if value is false and false otherwise." (if x #f #t)) +(define (rationalize number tolerance) "(rationalize number tolerance)\u000A\u000AReturns simplest rational number approximation differing from number by no more\u000Athan the tolerance." (typecheck "rationalize" number "number" 1) (typecheck "rationalize" tolerance "number" 2) (lips.rationalize number tolerance)) +(define (%mem/search acces op obj list) "(%member obj list function)\u000A\u000AHelper method to get first list where car equal to obj\u000Ausing provied functions as comparator." (if (null? list) #f (if (op (acces list) obj) list (%mem/search acces op obj (cdr list))))) +(define (memq obj list) "(memq obj list)\u000A\u000AReturns first object in the list that match using eq? function." (typecheck "memq" list (quote ("nil" "pair"))) (%mem/search car eq? obj list)) +(define (memv obj list) "(memv obj list)\u000A\u000AReturns first object in the list that match using eqv? function." (typecheck "memv" list (quote ("nil" "pair"))) (%mem/search car eqv? obj list)) +(define (member obj list) "(member obj list)\u000A\u000AReturns first object in the list that match using equal? function." (typecheck "member" list (quote ("nil" "pair"))) (%mem/search car equal? obj list)) +(define (%assoc/acessor name) "(%assoc/acessor name)\u000A\u000AReturns carr with typecheck using give name." (lambda (x) (typecheck name x "pair") (caar x))) (define (%assoc/search op obj alist) "(%assoc/search op obj alist)\u000A\u000AGeneric function that used in assoc functions with defined comparator\u000Afunction." (typecheck "assoc" alist (vector "nil" "pair")) (let ((ret (%mem/search (%assoc/acessor "assoc") op obj alist))) (if ret (car ret) ret))) -(define assoc (%doc "(assoc obj alist)\u000A\u000AFunction returns pair from alist that match given key using equal? check." (curry %assoc/search equal?))) -(define assq (%doc "(assq obj alist)\u000A\u000AFunction returns pair from a list that matches given key using eq? check." (curry %assoc/search eq?))) -(define assv (%doc "(assv obj alist)\u000A\u000AFunction returns pair from alist that match given key using eqv? check." (curry %assoc/search eqv?))) -(define (make-string k . rest) "(make-string k [char])\u000A\u000AFunction returns new string with k elements. If char is provided\u000Ait's filled with that character." (let ((char (if (null? rest) #\space (car rest)))) (typecheck "make-string" k "number" 1) (typecheck "make-string" char "character" 2) (let iter ((result (quote ())) (k k)) (if (<= k 0) (list->string result) (iter (cons char result) (- k 1)))))) -(define (string . args) "(string chr1 chr2 ...)\u000A\u000AFunction creates a new string from it's arguments. Each argument\u000ANeed to be a character object." (for-each (lambda (x) (typecheck "string" x "character")) args) (list->string args)) +(define assoc (%doc "(assoc obj alist)\u000A\u000AReturns pair from alist that match given key using equal? check." (curry %assoc/search equal?))) +(define assq (%doc "(assq obj alist)\u000A\u000AReturns pair from a list that matches given key using eq? check." (curry %assoc/search eq?))) +(define assv (%doc "(assv obj alist)\u000A\u000AReturns pair from alist that match given key using eqv? check." (curry %assoc/search eqv?))) +(define (make-string k . rest) "(make-string k [char])\u000A\u000AReturns new string with k elements. If char is provided\u000Ait's filled with that character." (let ((char (if (null? rest) #\space (car rest)))) (typecheck "make-string" k "number" 1) (typecheck "make-string" char "character" 2) (let iter ((result (quote ())) (k k)) (if (<= k 0) (list->string result) (iter (cons char result) (- k 1)))))) +(define (string . args) "(string chr1 chr2 ...)\u000A\u000AFunction that creates a new string from it's arguments. Each argument\u000Aneeds to be a character object." (for-each (lambda (x) (typecheck "string" x "character")) args) (list->string args)) (define (string-copy string) "(string-copy string)\u000A\u000AReturns a copy of the given string." (typecheck "string-copy" string "string") (--> string (clone))) -(define (string-fill! string char) "(string-fill! symbol char)\u000A\u000AFunction destructively fills the string with given character." (typecheck "string-fill!" string "string" 1) (typecheck "string-fill!" char "character" 2) (--> string (fill char))) -(define (identity n) "(identity n)\u000A\u000ANo op function. It just returns its argument." n) -(define (string-copy x) "(string-copy x)\u000A\u000ACreates a new string based of given argument." (typecheck "string-copy" x "string") (lips.LString x)) -(define (list->string _list) "(list->string _list)\u000A\u000AFunction returns a string from list of characters." (let ((array (list->array (map (lambda (x) (typecheck "list->string" x "character") (x.valueOf)) _list)))) (--> array (join "")))) -(define (string->list string) "(string->list string)\u000A\u000AFunction returns a list of characters created from string." (typecheck "string->list" string "string") (array->list (--> (Array.from string) (map (lambda (x) (lips.LCharacter x)))))) -(define-macro (string-set! object index char) "(string-set! object index char)\u000A\u000AMacro that replaces character in string in given index. It create new JavaScript\u000Astring and replaces the old value. Object needs to be symbol that points to the variable\u000Athat holds the string." (typecheck "string-set!" object "symbol") (let ((chars (gensym "chars"))) (quasiquote (begin (typecheck "string-set!" (unquote object) "string") (typecheck "string-set!" (unquote index) "number") (typecheck "string-set!" (unquote char) "character") (let (((unquote chars) (list->vector (string->list (unquote object))))) (set-obj! (unquote chars) (unquote index) (unquote char)) (set! (unquote object) (list->string (vector->list (unquote chars))))))))) -(define (string-length string) "(string-length string)\u000A\u000AFunction return length of the string." (typecheck "string-ref" string "string") (. string (quote length))) -(define (string-ref string k) "(string-ref string k)\u000A\u000AFunction return character inside string at given zero-based index." (typecheck "string-ref" string "string" 1) (typecheck "string-ref" k "number" 2) (lips.LCharacter (--> string (get k)))) -(define (%string-cmp name string1 string2) "(%string-cmp name a b)\u000A\u000AFunction compares two strings and returns 0 if they are equal,\u000A-1 if it is smaller and 1 if is larger. The function compares\u000Athe codepoints of the character." (typecheck name string1 "string" 1) (typecheck name string2 "string" 2) (--> string1 (cmp string2))) -(define (string=? string1 string2) "(string=? string1 string2)\u000A\u000AFunction checks if two strings are equal." (= (%string-cmp "string=?" string1 string2) 0)) -(define (string<? string1 string2) "(string<? string1 string2)\u000A\u000AFunction returns true if the second string is smaller than the first one." (= (%string-cmp "string<?" string1 string2) -1)) -(define (string>? string1 string2) "(string<? string1 string2)\u000A\u000AFunction returns true if the second string is larger than the first one." (= (%string-cmp "string>?" string1 string2) 1)) -(define (string<=? string1 string2) "(string<? string1 string2)\u000A\u000AFunction returns true if the second string is not larger than the first one." (< (%string-cmp "string<=?" string1 string2) 1)) -(define (string>=? string1 string2) "(string<? string1 string2)\u000A\u000AFunction returns true if second character is not smaller then the first one." (> (%string-cmp "string>=?" string1 string2) -1)) -(define (%string-ci-cmp name string1 string2) "(%string-ci-cmp name a b)\u000A\u000AFunction compares two strings ignoring case and returns 0 if they are equal,\u000A-1 if it is smaller and 1 if is larger. The function compares\u000Athe codepoints of the character." (typecheck name string1 "string" 1) (typecheck name string2 "string" 2) (--> string1 (lower) (cmp (--> string2 (lower))))) -(define (string-ci=? string1 string2) "(string-ci=? string1 string2)\u000A\u000AFunction checks if two strings are equal." (= (%string-ci-cmp "string-ci=?" string1 string2) 0)) -(define (string-ci<? string1 string2) "(string-ci<? string1 string2)\u000A\u000AFunction returns true if the second string is smaller than the first one." (= (%string-ci-cmp "string-ci<?" string1 string2) -1)) -(define (string-ci>? string1 string2) "(string-ci<? string1 string2)\u000A\u000AFunction returns true if the second string is larger than the first one." (= (%string-ci-cmp "string-ci>?" string1 string2) 1)) -(define (string-ci<=? string1 string2) "(string-ci<? string1 string2)\u000A\u000AFunction returns true if the second string is not larger than the first one." (< (%string-ci-cmp "string-ci<=?" string1 string2) 1)) -(define (string-ci>=? string1 string2) "(string-ci>=? string1 string2)\u000A\u000AFunction returns true if second character is not smaller than the first one." (> (%string-ci-cmp "string-ci>=?" string1 string2) -1)) -(define char? (%doc "(char? obj)\u000A\u000AFunction checks if the object is a character." (curry instanceof lips.LCharacter))) -(define (char->integer chr) "(char->integer chr)\u000A\u000AFunction returns the codepoint of Unicode character." (typecheck "char->integer" chr "character") (--> chr.__char__ (codePointAt 0))) -(define (integer->char n) "(integer->char chr)\u000A\u000AFunction converts number argument to chararacter." (typecheck "integer->char" n "number") (if (integer? n) (string-ref (String.fromCodePoint n) 0) (throw "argument to integer->char need to be integer."))) +(define (string-fill! string char) "(string-fill! symbol char)\u000A\u000AFunction that destructively fills the string with given character." (typecheck "string-fill!" string "string" 1) (typecheck "string-fill!" char "character" 2) (--> string (fill char))) +(define (identity n) "(identity n)\u000A\u000ANo-op function. It just returns its argument." n) +(define (string-copy x) "(string-copy x)\u000A\u000ACreates a new string based on given argument." (typecheck "string-copy" x "string") (lips.LString x)) +(define (list->string _list) "(list->string _list)\u000A\u000AReturns a string from a list of characters." (let ((array (list->array (map (lambda (x) (typecheck "list->string" x "character") (x.valueOf)) _list)))) (--> array (join "")))) +(define (string->list string) "(string->list string)\u000A\u000AReturns a list of characters created from string." (typecheck "string->list" string "string") (array->list (--> (Array.from string) (map (lambda (x) (lips.LCharacter x)))))) +(define-macro (string-set! object index char) "(string-set! object index char)\u000A\u000AReplaces character in string in given index. It create new JavaScript\u000Astring and replaces the old value. Object needs to be symbol that points to the variable\u000Athat holds the string." (typecheck "string-set!" object "symbol") (let ((chars (gensym "chars"))) (quasiquote (begin (typecheck "string-set!" (unquote object) "string") (typecheck "string-set!" (unquote index) "number") (typecheck "string-set!" (unquote char) "character") (let (((unquote chars) (list->vector (string->list (unquote object))))) (set-obj! (unquote chars) (unquote index) (unquote char)) (set! (unquote object) (list->string (vector->list (unquote chars))))))))) +(define (string-length string) "(string-length string)\u000A\u000AReturns the length of the string." (typecheck "string-ref" string "string") (. string (quote length))) +(define (string-ref string k) "(string-ref string k)\u000A\u000AReturns character inside string at given zero-based index." (typecheck "string-ref" string "string" 1) (typecheck "string-ref" k "number" 2) (lips.LCharacter (--> string (get k)))) +(define (%string-cmp name string1 string2) "(%string-cmp name a b)\u000A\u000AFunction that compares two strings and returns 0 if they are equal,\u000A-1 if it is smaller and 1 if is larger. The function compares\u000Athe codepoints of the character." (typecheck name string1 "string" 1) (typecheck name string2 "string" 2) (--> string1 (cmp string2))) +(define (string=? string1 string2) "(string=? string1 string2)\u000A\u000AChecks if two strings are equal." (= (%string-cmp "string=?" string1 string2) 0)) +(define (string<? string1 string2) "(string<? string1 string2)\u000A\u000AReturns true if the second string is smaller than the first one." (= (%string-cmp "string<?" string1 string2) -1)) +(define (string>? string1 string2) "(string<? string1 string2)\u000A\u000AReturns true if the second string is larger than the first one." (= (%string-cmp "string>?" string1 string2) 1)) +(define (string<=? string1 string2) "(string<? string1 string2)\u000A\u000AReturns true if the second string is not larger than the first one." (< (%string-cmp "string<=?" string1 string2) 1)) +(define (string>=? string1 string2) "(string<? string1 string2)\u000A\u000AReturns true if second character is not smaller then the first one." (> (%string-cmp "string>=?" string1 string2) -1)) +(define (%string-ci-cmp name string1 string2) "(%string-ci-cmp name a b)\u000A\u000AFunction that compares two strings ignoring case and returns 0 if they are equal,\u000A-1 if it is smaller and 1 if is larger. The function compares\u000Athe codepoints of the character." (typecheck name string1 "string" 1) (typecheck name string2 "string" 2) (--> string1 (lower) (cmp (--> string2 (lower))))) +(define (string-ci=? string1 string2) "(string-ci=? string1 string2)\u000A\u000AChecks if two strings are equal, ignoring case." (= (%string-ci-cmp "string-ci=?" string1 string2) 0)) +(define (string-ci<? string1 string2) "(string-ci<? string1 string2)\u000A\u000AReturns true if the second string is smaller than the first one, ignoring case." (= (%string-ci-cmp "string-ci<?" string1 string2) -1)) +(define (string-ci>? string1 string2) "(string-ci<? string1 string2)\u000A\u000AReturns true if the second string is larger than the first one, ignoring case." (= (%string-ci-cmp "string-ci>?" string1 string2) 1)) +(define (string-ci<=? string1 string2) "(string-ci<? string1 string2)\u000A\u000AReturns true if the second string is not larger than the first one, ignoring case." (< (%string-ci-cmp "string-ci<=?" string1 string2) 1)) +(define (string-ci>=? string1 string2) "(string-ci>=? string1 string2)\u000A\u000AReturns true if second character is not smaller than the first one, ignoring case." (> (%string-ci-cmp "string-ci>=?" string1 string2) -1)) +(define char? (%doc "(char? obj)\u000A\u000AChecks if the object is a character." (curry instanceof lips.LCharacter))) +(define (char->integer chr) "(char->integer chr)\u000A\u000AReturns the codepoint of Unicode character." (typecheck "char->integer" chr "character") (--> chr.__char__ (codePointAt 0))) +(define (integer->char n) "(integer->char chr)\u000A\u000AFunction that converts number argument to chararacter." (typecheck "integer->char" n "number") (if (integer? n) (string-ref (String.fromCodePoint n) 0) (throw "argument to integer->char need to be integer."))) (define-macro (%define-chr-re spec str re) "(%define-chr-re (name chr) sring re)\u000A\u000AMacro defines the procedure that tests character against regular expression." (quasiquote (define (unquote spec) (unquote str) (typecheck (unquote (symbol->string (car spec))) (unquote (cadr spec)) "character") (not (null? (--> chr (toString) (match (unquote re)))))))) -(%define-chr-re (char-whitespace? chr) "(char-whitespace? chr)\u000A\u000AFunction returns true if character is whitespace." (let-env (interaction-environment) (--> **internal-env** (get (quote space-unicode-regex))))) -(%define-chr-re (char-numeric? chr) "(char-numeric? chr)\u000A\u000AFunction return true if character is number." (let-env (interaction-environment) (--> **internal-env** (get (quote numeral-unicode-regex))))) -(%define-chr-re (char-alphabetic? chr) "(char-alphabetic? chr)\u000A\u000AFunction return true if character is leter of the ASCII alphabet." (let-env (interaction-environment) (--> **internal-env** (get (quote letter-unicode-regex))))) -(define (%char-cmp name chr1 chr2) "(%char-cmp name a b)\u000A\u000AFunction compare two characters and return 0 if they are equal,\u000A-1 second is smaller and 1 if is larget. The function compare\u000Athe codepoints of the character." (typecheck name chr1 "character" 1) (typecheck name chr2 "character" 2) (let ((a (char->integer chr1)) (b (char->integer chr2))) (cond ((= a b) 0) ((< a b) -1) (else 1)))) -(define (char=? chr1 chr2) "(char=? chr1 chr2)\u000A\u000AFunction check if two characters are equal." (= (%char-cmp "char=?" chr1 chr2) 0)) -(define (char<? chr1 chr2) "(char<? chr1 chr2)\u000A\u000AFunction return true if second character is smaller then the first one." (= (%char-cmp "char<?" chr1 chr2) -1)) -(define (char>? chr1 chr2) "(char<? chr1 chr2)\u000A\u000AFunction return true if second character is larger then the first one." (= (%char-cmp "char>?" chr1 chr2) 1)) -(define (char<=? chr1 chr2) "(char<? chr1 chr2)\u000A\u000AFunction return true if second character is not larger then the first one." (< (%char-cmp "char<=?" chr1 chr2) 1)) -(define (char>=? chr1 chr2) "(char<? chr1 chr2)\u000A\u000AFunction return true if second character is not smaller then the first one." (> (%char-cmp "char>=?" chr1 chr2) -1)) -(define (%char-ci-cmp name chr1 chr2) "(%char-cmp name a b)\u000A\u000AFunction compare two characters and return 0 if they are equal,\u000A-1 second is smaller and 1 if is larget. The function compare\u000Athe codepoints of the character." (typecheck name chr1 "character" 1) (typecheck name chr2 "character" 2) (%char-cmp name (char-downcase chr1) (char-downcase chr2))) -(define (char-ci=? chr1 chr2) "(char-ci=? chr1 chr2)\u000A\u000AFunction check if two characters are equal." (= (%char-ci-cmp "char-ci=?" chr1 chr2) 0)) -(define (char-ci<? chr1 chr2) "(char-ci<? chr1 chr2)\u000A\u000AFunction return true if second character is smaller then the first one." (= (%char-ci-cmp "char-ci<?" chr1 chr2) -1)) -(define (char-ci>? chr1 chr2) "(char-ci<? chr1 chr2)\u000A\u000AFunction return true if second character is larger then the first one." (= (%char-ci-cmp "char-ci>?" chr1 chr2) 1)) -(define (char-ci<=? chr1 chr2) "(char-ci<? chr1 chr2)\u000A\u000AFunction return true if second character is not larger then the first one." (< (%char-ci-cmp "char-ci<=?" chr1 chr2) 1)) -(define (char-ci>=? chr1 chr2) "(char-ci<? chr1 chr2)\u000A\u000AFunction return true if second character is not smaller then the first one." (> (%char-ci-cmp "char-ci>=?" chr1 chr2) -1)) +(%define-chr-re (char-whitespace? chr) "(char-whitespace? chr)\u000A\u000AReturns true if character is whitespace." (let-env (interaction-environment) (--> **internal-env** (get (quote space-unicode-regex))))) +(%define-chr-re (char-numeric? chr) "(char-numeric? chr)\u000A\u000AReturns true if character is number." (let-env (interaction-environment) (--> **internal-env** (get (quote numeral-unicode-regex))))) +(%define-chr-re (char-alphabetic? chr) "(char-alphabetic? chr)\u000A\u000AReturns true if character is leter of the ASCII alphabet." (let-env (interaction-environment) (--> **internal-env** (get (quote letter-unicode-regex))))) +(define (%char-cmp name chr1 chr2) "(%char-cmp name a b)\u000A\u000AFunction that compares two characters and return 0 if they are equal,\u000A-1 second is smaller and 1 if is larget. The function compare\u000Athe codepoints of the character." (typecheck name chr1 "character" 1) (typecheck name chr2 "character" 2) (let ((a (char->integer chr1)) (b (char->integer chr2))) (cond ((= a b) 0) ((< a b) -1) (else 1)))) +(define (char=? chr1 chr2) "(char=? chr1 chr2)\u000A\u000AChecks if two characters are equal." (= (%char-cmp "char=?" chr1 chr2) 0)) +(define (char<? chr1 chr2) "(char<? chr1 chr2)\u000A\u000AReturns true if second character is smaller then the first one." (= (%char-cmp "char<?" chr1 chr2) -1)) +(define (char>? chr1 chr2) "(char<? chr1 chr2)\u000A\u000AReturns true if second character is larger then the first one." (= (%char-cmp "char>?" chr1 chr2) 1)) +(define (char<=? chr1 chr2) "(char<? chr1 chr2)\u000A\u000AReturns true if second character is not larger then the first one." (< (%char-cmp "char<=?" chr1 chr2) 1)) +(define (char>=? chr1 chr2) "(char<? chr1 chr2)\u000A\u000AReturns true if second character is not smaller then the first one." (> (%char-cmp "char>=?" chr1 chr2) -1)) +(define (%char-ci-cmp name chr1 chr2) "(%char-cmp name a b)\u000A\u000AFunction that compares two characters and return 0 if they are equal,\u000A-1 second is smaller and 1 if is larget. The function compare\u000Athe codepoints of the character." (typecheck name chr1 "character" 1) (typecheck name chr2 "character" 2) (%char-cmp name (char-downcase chr1) (char-downcase chr2))) +(define (char-ci=? chr1 chr2) "(char-ci=? chr1 chr2)\u000A\u000AChecks if two characters are equal." (= (%char-ci-cmp "char-ci=?" chr1 chr2) 0)) +(define (char-ci<? chr1 chr2) "(char-ci<? chr1 chr2)\u000A\u000AReturns true if second character is smaller then the first one." (= (%char-ci-cmp "char-ci<?" chr1 chr2) -1)) +(define (char-ci>? chr1 chr2) "(char-ci<? chr1 chr2)\u000A\u000AReturns true if second character is larger then the first one." (= (%char-ci-cmp "char-ci>?" chr1 chr2) 1)) +(define (char-ci<=? chr1 chr2) "(char-ci<? chr1 chr2)\u000A\u000AReturns true if second character is not larger then the first one." (< (%char-ci-cmp "char-ci<=?" chr1 chr2) 1)) +(define (char-ci>=? chr1 chr2) "(char-ci<? chr1 chr2)\u000A\u000AReturns true if second character is not smaller then the first one." (> (%char-ci-cmp "char-ci>=?" chr1 chr2) -1)) (define (char-upcase char) "(char-upcase char)\u000A\u000ACreate uppercase version of the character." (typecheck "char-upcase" char "character") (char.toUpperCase)) (define (char-downcase char) "(char-downcase chr)\u000A\u000ACreate lowercase version of the character." (typecheck "char-upcase" char "character") (char.toLowerCase)) -(define (char-upper-case? char) "(char-upper-case? char)\u000A\u000AFunction check if character is upper case." (typecheck "char-upper-case?" char "character") (and (char-alphabetic? char) (char=? (char-upcase char) char))) -(define (char-lower-case? char) "(char-upper-case? char)\u000A\u000AFunction check if character is lower case." (typecheck "char-lower-case?" char "character") (and (char-alphabetic? char) (char=? (char-downcase char) char))) +(define (char-upper-case? char) "(char-upper-case? char)\u000A\u000AChecks if character is upper case." (typecheck "char-upper-case?" char "character") (and (char-alphabetic? char) (char=? (char-upcase char) char))) +(define (char-lower-case? char) "(char-upper-case? char)\u000A\u000AChecks if character is lower case." (typecheck "char-lower-case?" char "character") (and (char-alphabetic? char) (char=? (char-downcase char) char))) (define (newline . rest) "(newline [port])\u000A\u000AWrite newline character to standard output or given port" (let ((port (if (null? rest) (current-output-port) (car rest)))) (display "\u000A" port))) (define (write obj . rest) "(write obj [port])\u000A\u000AWrite object to standard output or give port. For strings it will include\u000Awrap in quotes." (let ((port (if (null? rest) (current-output-port) (car rest)))) (display (repr obj #t) port))) (define (write-char char . rest) "(write-char char [port])\u000A\u000AWrite single character to given port using write function." (typecheck "write-char" char "character") (if (not (null? rest)) (typecheck "write-char" (car rest) "output-port")) (apply display (cons (char.valueOf) rest))) (define fold-right reduce) (define fold-left fold) -(define (make-vector n . rest) "(make-vector n [fill])\u000A\u000ACreate new vector with n empty elements. If fill is specified it will set\u000Aall elements of the vector to that value." (let ((result (new Array n))) (if (not (null? rest)) (--> result (fill (car rest))) result))) -(define (vector? n) "(vector? n)\u000A\u000AFunction return true of value is vector and false if not." (string=? (type n) "array")) -(define (vector-ref vec n) "(vector-ref vec n)\u000A\u000AFunction return nth element of the vector vec." (typecheck "vector-ref" vec "array" 1) (typecheck "vector-ref" n "number" 2) (. vec n)) -(define (vector-set! vec n value) "(vector-set! vec n value)\u000A\u000AFunction set nth item of the vector to value." (typecheck "vector-ref" vec "array" 1) (typecheck "vector-ref" n "number" 2) (set-obj! vec n value)) +(define (make-vector n . rest) "(make-vector n [fill])\u000A\u000ACreates a new vector with n empty elements. If fill is specified it will set\u000Aall elements of the vector to that value." (let ((result (new Array n))) (if (not (null? rest)) (--> result (fill (car rest))) result))) +(define (vector? n) "(vector? n)\u000A\u000AReturns true if value is vector and false if not." (string=? (type n) "array")) +(define (vector-ref vec n) "(vector-ref vec n)\u000A\u000AReturns nth element of the vector vec." (typecheck "vector-ref" vec "array" 1) (typecheck "vector-ref" n "number" 2) (. vec n)) +(define (vector-set! vec n value) "(vector-set! vec n value)\u000A\u000AFunction that sets nth item of the vector to value." (typecheck "vector-ref" vec "array" 1) (typecheck "vector-ref" n "number" 2) (set-obj! vec n value)) (define (vector-fill! vec value) "(vector-fill! vec value)\u000A\u000ASet every element of the vector to given value." (typecheck "vector-ref" vec "array") (let recur ((n (- (length vec) 1))) (if (>= n 0) (begin (set-obj! vec n value) (recur (- n 1)))))) -(define (vector-length vec) "(vector-length vec)\u000A\u000AFunction return length of the vector. If argument is not vector it throw exception." (typecheck "vector-length" vec "array") (length vec)) +(define (vector-length vec) "(vector-length vec)\u000A\u000AReturns length of the vector. It errors if the argument is not a vector." (typecheck "vector-length" vec "array") (length vec)) (define-syntax case (syntax-rules (else =>) ((case (key ...) clauses ...) (let ((atom-key (key ...))) (case atom-key clauses ...))) ((case key (else => result)) (result key)) ((case key (else result1 result2 ...)) (begin result1 result2 ...)) ((case key ((atoms ...) => result)) (if (memv key (quote (atoms ...))) (result key))) ((case key ((atoms ...) => result) clause clauses ...) (if (memv key (quote (atoms ...))) (result key) (case key clause clauses ...))) ((case key ((atoms ...) result1 result2 ...)) (if (memv key (quote (atoms ...))) (begin result1 result2 ...))) ((case key ((atoms ...) result1 result2 ...) clause clauses ...) (if (memv key (quote (atoms ...))) (begin result1 result2 ...) (case key clause clauses ...)))) "(case value\u000A ((<items>) result1)\u000A ((<items>) result2)\u000A [else result3])\u000A\u000AMacro for switch case statement. It test if value is any of the item. If\u000Aitem match the value it will return coresponding result expression value.\u000AIf no value match and there is else it will return that result.") (--> lips.Formatter.defaults.exceptions.specials (push "case")) (define (numerator n) "(numerator n)\u000A\u000AReturn numberator of rational or same number if n is not rational." (typecheck "numerator" n "number") (cond ((integer? n) n) ((rational? n) n.__num__) (else (numerator (inexact->exact n))))) @@ -251,12 +251,12 @@ (define (make-polar r angle) "(make-polar magnitude angle)\u000A\u000ACreate new complex number from polar parameters." (typecheck "make-polar" r "number") (typecheck "make-polar" angle "number") (if (or (complex? r) (complex? angle)) (error "make-polar: argument can't be complex") (let ((re (* r (sin angle))) (im (* r (cos angle)))) (make-rectangular im re)))) (define (angle x) "(angle x)\u000A\u000AReturns angle of the complex number in polar coordinate system." (if (not (%number-type "complex" x)) (error "angle: number need to be complex") (Math.atan2 x.__im__ x.__re__))) (define (magnitude x) "(magnitude x)\u000A\u000AReturns magnitude of the complex number in polar coordinate system." (if (not (%number-type "complex" x)) (error "magnitude: number need to be complex") (sqrt (+ (* x.__im__ x.__im__) (* x.__re__ x.__re__))))) -(define random (let ((a 69069) (c 1) (m (expt 2 32)) (seed 19380110)) (lambda new-seed "(random)\u000A(random seed)\u000A\u000AFunction generate new random real number using Knuth algorithm." (if (pair? new-seed) (set! seed (car new-seed)) (set! seed (modulo (+ (* seed a) c) m))) (exact->inexact (/ seed m))))) -(define (eof-object? obj) "(eof-object? arg)\u000A\u000AFunction check if value is eof object, returned from input string\u000Aport when there are no more data to read." (eq? obj eof)) -(define (output-port? obj) "(output-port? arg)\u000A\u000AFunction return true if argument is output port." (instanceof lips.OutputPort obj)) -(define (input-port? obj) "(input-port? arg)\u000A\u000AFunction return true if argument is input port." (instanceof lips.InputPort obj)) -(define (char-ready? . rest) "(char-ready?)\u000A(char-ready? port)\u000A\u000AFunction checks if characters is ready in input port. This is useful mostly\u000Afor interactive ports that return false if it would wait for user input.\u000AIt return false if port is closed." (let ((port (if (null? rest) (current-input-port) (car rest)))) (typecheck "char-ready?" port "input-port") (port.char_ready))) -(define open-input-file (let ((readFile #f)) (lambda (filename) "(open-input-file filename)\u000A\u000AFunction return new Input Port with given filename. In Browser user need to\u000Aprovide global fs variable that is instance of FS interface." (new lips.InputFilePort (%read-file #f filename) filename)))) +(define random (let ((a 69069) (c 1) (m (expt 2 32)) (seed 19380110)) (lambda new-seed "(random)\u000A(random seed)\u000A\u000AFunction that generates new random real number using Knuth algorithm." (if (pair? new-seed) (set! seed (car new-seed)) (set! seed (modulo (+ (* seed a) c) m))) (exact->inexact (/ seed m))))) +(define (eof-object? obj) "(eof-object? arg)\u000A\u000AChecks if value is eof object, returned from input string\u000Aport when there are no more data to read." (eq? obj eof)) +(define (output-port? obj) "(output-port? arg)\u000A\u000AReturns true if argument is output port." (instanceof lips.OutputPort obj)) +(define (input-port? obj) "(input-port? arg)\u000A\u000AReturns true if argument is input port." (instanceof lips.InputPort obj)) +(define (char-ready? . rest) "(char-ready?)\u000A(char-ready? port)\u000A\u000AChecks if characters is ready in input port. This is useful mostly\u000Afor interactive ports that return false if it would wait for user input.\u000AIt return false if port is closed." (let ((port (if (null? rest) (current-input-port) (car rest)))) (typecheck "char-ready?" port "input-port") (port.char_ready))) +(define open-input-file (let ((readFile #f)) (lambda (filename) "(open-input-file filename)\u000A\u000AReturns new Input Port with given filename. In Browser user need to\u000Aprovide global fs variable that is instance of FS interface." (new lips.InputFilePort (%read-file #f filename) filename)))) (define (close-input-port port) "(close-input-port port)\u000A\u000AProcedure close port that was opened with open-input-file. After that\u000Ait no longer accept reading from that port." (typecheck "close-input-port" port "input-port") (port.close)) (define (close-output-port port) "(close-output-port port)\u000A\u000AProcedure close port that was opened with open-output-file. After that\u000Ait no longer accept write to that port." (typecheck "close-output-port" port "output-port") (port.close)) (define (call-with-input-file filename proc) "(call-with-input-file filename proc)\u000A\u000AProcedure open file for reading, call user defined procedure with given port\u000Aand then close the port. It return value that was returned by user proc\u000Aand it close the port even if user proc throw exception." (let ((p (open-input-file filename))) (try (proc p) (finally (close-input-port p))))) @@ -266,26 +266,26 @@ (define (with-input-from-string string thunk) "(with-input-from-string string thunk)\u000A\u000AProcedure open string and make it current-input-port then thunk is executed.\u000AAfter thunk is executed current-input-port is restored and string port\u000Ais closed." (with-input-from-port (open-input-string string) thunk)) (define (with-output-to-file string thunk) (let* ((port (open-output-file string)) (env **interaction-environment**) (internal-env (env.get (quote **internal-env**))) (old-stdout (internal-env.get "stdout"))) (internal-env.set "stdout" port) (try (thunk) (finally (internal-env.set "stdout" old-stdout) (close-output-port port))))) (define (file-exists? filename) (new Promise (lambda (resolve) (let ((fs (--> lips.env (get (quote **internal-env**)) (get (quote fs))))) (if (null? fs) (throw (new Error "file-exists?: fs not defined")) (fs.stat filename (lambda (err stat) (if (null? err) (resolve (stat.isFile)) (resolve #f))))))))) -(define open-output-file (let ((open)) (lambda (filename) "(open-output-file filename)\u000A\u000AFunction open file and return port that can be used for writing. If file\u000Aexists it will throw an Error." (typecheck "open-output-file" filename "string") (if (not (procedure? open)) (set! open (%fs-promisify-proc (quote open) "open-output-file"))) (if (file-exists? filename) (throw (new Error "open-output-file: file exists")) (lips.OutputFilePort filename (open filename "w")))))) -(define (scheme-report-environment version) "(scheme-report-environment version)\u000A\u000AFunction return new Environment object for given Scheme Spec version.\u000AOnly argument 5 is supported that create environemnt for R5RS." (typecheck "scheme-report-environment" version "number") (case version ((5) (%make-env "R5RS" * + - / < <= = > >= abs acos and angle append apply asin assoc assq assv atan begin boolean? caaaar caaadr caaar caadar caaddr caadr caar cadaar cadadr cadar caddar cadddr caddr cadr call-with-current-continuation call-with-input-file call-with-output-file call-with-values car case cdaaar cdaadr cdaar cdadar cdaddr cdadr cdar cddaar cddadr cddar cdddar cddddr cdddr cddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? char<=? char<? char=? char>=? char>? char? close-input-port close-output-port complex? cond cons cos current-input-port current-output-port define define-syntax delay denominator display do dynamic-wind eof-object? eq? equal? eqv? eval even? exact->inexact exact? exp expt floor for-each force gcd if imag-part inexact->exact inexact? input-port? integer->char integer? interaction-environment lambda lcm length let let* let-syntax letrec letrec-syntax list list->string list->vector list-ref list-tail list? load log magnitude make-polar make-rectangular make-string make-vector map max member memq memv min modulo negative? newline not null-environment null? number->string number? numerator odd? open-input-file open-output-file or output-port? pair? peek-char positive? procedure? quasiquote quote quotient rational? rationalize read read-char real-part real? remainder reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list string->number string->symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string<? string=? string>=? string>? string? substring symbol->string symbol? tan truncate values vector vector->list vector-fill! vector-length vector-ref vector-set! vector? with-input-from-file with-output-to-file write write-char zero?)) ((7) (throw (new Error "not yet implemented"))) (else (throw (new Error (string-append "scheme-report-environment: version " (number->string version) " not supported")))))) -(define-macro (%make-vector prefix type help) "(%make-vector prefix type help)\u000A\u000AMega helper macro that create list of functions for single byte vector\u000Abased on typed array from JavaScript" (letrec ((prefix-str (symbol->string prefix)) (type-str (symbol->string type)) (l-type (--> type-str (toLowerCase))) (static (lambda (name) (string->symbol (format "~a.~a" type-str name)))) (TypedArray.from (static "from")) (fn-name (lambda (str) (string->symbol (format str prefix-str)))) (type-vector (fn-name "~avector")) (make-vector (fn-name "make-~avector")) (vector? (fn-name "~avector?")) (vector-in-range? (fn-name "%~avector-in-range?")) (vector-ref (fn-name "~avector-ref")) (repr-str (format "#~a" prefix-str)) (vector-length (fn-name "~avector-length")) (vector->list (fn-name "~avector->list")) (vector-set! (fn-name "~avector-set!")) (list->tvector (fn-name "list->~avector")) (vector->tvector (fn-name "vector->~avector"))) (quasiquote (begin (define ((unquote type-vector) . args) (unquote (format "(~a v1 v2 ...)\u000A\u000ACreate ~a from give arguments." type-vector help)) ((unquote TypedArray.from) (list->vector args))) (define ((unquote vector-length) v) (unquote (format "(~a v)\u000A\u000Areturn length of ~a." vector-length help)) (typecheck (unquote (symbol->string vector-length)) v (unquote l-type)) v.length) (define ((unquote make-vector) k . fill) (unquote (format "(~a k fill)\u000A\u000AAllocate new ~a of length k, with optional initial values." make-vector help)) (let ((v (new (unquote type) k))) (if (not (null? fill)) (--> v (fill (car fill)))) v)) (define ((unquote vector?) x) (unquote (format "(~a x)\u000A\u000AFunction return #t of argument is ~a otherwise it return #f." vector? help)) (and (object? x) (equal? (. x (quote constructor)) (unquote type)))) (define ((unquote vector-in-range?) vector k) (unquote (format "(~a vector k)\u000A\u000AFunction test if index is range for ~a." vector-in-range? help)) (typecheck (unquote (symbol->string vector-in-range?)) vector (unquote l-type)) (typecheck (unquote (symbol->string vector-in-range?)) k "number") (let ((len (length vector))) (and (>= k 0) (< k len)))) (define ((unquote vector-ref) vector k) (unquote (format "(~a vector k)\u000A\u000AFunction return value frome vector at index k. If index is out of range it throw exception." vector-ref help)) (typecheck (unquote (symbol->string vector-ref)) vector (unquote l-type)) (typecheck (unquote (symbol->string vector-ref)) k "number") (if (not ((unquote vector-in-range?) vector k)) (throw (new Error (unquote (format "~a index out of range" vector-ref)))) (. vector k))) (define ((unquote vector->list) vector) (typecheck (unquote (symbol->string vector->list)) vector (unquote l-type)) (vector->list (Array.from vector))) (define ((unquote vector-set!) vector k v) (unquote (format "(~a vector k)\u000A\u000AFunction set value of ~a at index k. If index is out of range it throw exception." vector-set! help)) (typecheck (unquote (symbol->string vector-set!)) vector (unquote l-type)) (typecheck (unquote (symbol->string vector-set!)) k "number") (if (not ((unquote vector-in-range?) vector k)) (throw (new Error (unquote (format "~a index out of range" vector-set!)))) (set-obj! vector k v))) (define ((unquote list->tvector) lst) (typecheck (unquote (symbol->string list->tvector)) lst "pair") (apply (unquote vector) lst)) (define ((unquote vector->tvector) vector) (typecheck (unquote (symbol->string vector->tvector)) vector "array") ((unquote TypedArray.from) vector)) (set-special! (unquote repr-str) (quote (unquote type-vector)) lips.specials.SPLICE) (set-repr! (unquote type) (lambda (x _quote) (string-append (unquote repr-str) (repr ((unquote vector->list) x) _quote)))))))) -(%make-vector u8 Uint8Array "usigned 8-bit integer vector") -(%make-vector s8 Int8Array "signed 8-bit integer vector") -(%make-vector u16 Uint16Array "usigned 16-bit integer vector") -(%make-vector s16 Int16Array "signed 16-bit integer vector") -(%make-vector u32 Uint32Array "usigned 32-bit integer vector") -(%make-vector s32 Int32Array "signed 32-bit integer vector") -(%make-vector f32 Float32Array "32-bit IEEE floating point number vector") -(%make-vector f64 Float64Array "64-bit IEEE floating point number vector") -(define (list-match? predicate list) "(list-match? predicate list)\u000A\u000AFunction check if consecutive elements of the list match the predicate function." (typecheck "list-match?" predicate #("function" "macro")) (typecheck "list-match?" list "pair") (or (or (null? list) (null? (cdr list))) (and (predicate (car list) (cadr list)) (list-match? predicate (cdr list))))) -(define (symbol=? . args) "(symbol=? s1 s2 ...)\u000A\u000AFunction check if each value is symbol and it's the same acording to string=? predicate." (list-match? (lambda (a b) (and (symbol? a) (symbol? b) (equal? a b))) args)) -(define (values-ref values n) "(values-ref values n)\u000A\u000AFunction return n value of values object which is result of value function." (typecheck "values-ref" values "values" 1) (typecheck "values-ref" n "number" 1) (--> values (valueOf) n)) +(define open-output-file (let ((open)) (lambda (filename) "(open-output-file filename)\u000A\u000AFunction that opens file and return port that can be used for writing. If file\u000Aexists it will throw an Error." (typecheck "open-output-file" filename "string") (if (not (procedure? open)) (set! open (%fs-promisify-proc (quote open) "open-output-file"))) (if (file-exists? filename) (throw (new Error "open-output-file: file exists")) (lips.OutputFilePort filename (open filename "w")))))) +(define (scheme-report-environment version) "(scheme-report-environment version)\u000A\u000AReturns new Environment object for given Scheme Spec version.\u000AOnly argument 5 is supported that create environemnt for R5RS." (typecheck "scheme-report-environment" version "number") (case version ((5) (%make-env "R5RS" * + - / < <= = > >= abs acos and angle append apply asin assoc assq assv atan begin boolean? caaaar caaadr caaar caadar caaddr caadr caar cadaar cadadr cadar caddar cadddr caddr cadr call-with-current-continuation call-with-input-file call-with-output-file call-with-values car case cdaaar cdaadr cdaar cdadar cdaddr cdadr cdar cddaar cddadr cddar cdddar cddddr cdddr cddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? char<=? char<? char=? char>=? char>? char? close-input-port close-output-port complex? cond cons cos current-input-port current-output-port define define-syntax delay denominator display do dynamic-wind eof-object? eq? equal? eqv? eval even? exact->inexact exact? exp expt floor for-each force gcd if imag-part inexact->exact inexact? input-port? integer->char integer? interaction-environment lambda lcm length let let* let-syntax letrec letrec-syntax list list->string list->vector list-ref list-tail list? load log magnitude make-polar make-rectangular make-string make-vector map max member memq memv min modulo negative? newline not null-environment null? number->string number? numerator odd? open-input-file open-output-file or output-port? pair? peek-char positive? procedure? quasiquote quote quotient rational? rationalize read read-char real-part real? remainder reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list string->number string->symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string<? string=? string>=? string>? string? substring symbol->string symbol? tan truncate values vector vector->list vector-fill! vector-length vector-ref vector-set! vector? with-input-from-file with-output-to-file write write-char zero?)) ((7) (throw (new Error "not yet implemented"))) (else (throw (new Error (string-append "scheme-report-environment: version " (number->string version) " not supported")))))) +(define-macro (%make-vector prefix type help) "(%make-vector prefix type help)\u000A\u000AMega-helper macro that creates a list of functions for single byte vectors\u000Abased on typed arrays from JavaScript." (letrec ((prefix-str (symbol->string prefix)) (type-str (symbol->string type)) (l-type (--> type-str (toLowerCase))) (static (lambda (name) (string->symbol (format "~a.~a" type-str name)))) (TypedArray.from (static "from")) (fn-name (lambda (str) (string->symbol (format str prefix-str)))) (type-vector (fn-name "~avector")) (make-vector (fn-name "make-~avector")) (vector? (fn-name "~avector?")) (vector-in-range? (fn-name "%~avector-in-range?")) (vector-ref (fn-name "~avector-ref")) (repr-str (format "#~a" prefix-str)) (vector-length (fn-name "~avector-length")) (vector->list (fn-name "~avector->list")) (vector-set! (fn-name "~avector-set!")) (list->tvector (fn-name "list->~avector")) (vector->tvector (fn-name "vector->~avector"))) (quasiquote (begin (define ((unquote type-vector) . args) (unquote (format "(~a v1 v2 ...)\u000A\u000ACreate ~a from give arguments." type-vector help)) ((unquote TypedArray.from) (list->vector args))) (define ((unquote vector-length) v) (unquote (format "(~a v)\u000A\u000Areturn length of ~a." vector-length help)) (typecheck (unquote (symbol->string vector-length)) v (unquote l-type)) v.length) (define ((unquote make-vector) k . fill) (unquote (format "(~a k fill)\u000A\u000AAllocate new ~a of length k, with optional initial values." make-vector help)) (let ((v (new (unquote type) k))) (if (not (null? fill)) (--> v (fill (car fill)))) v)) (define ((unquote vector?) x) (unquote (format "(~a x)\u000A\u000AReturns #t of argument is ~a otherwise it return #f." vector? help)) (and (object? x) (equal? (. x (quote constructor)) (unquote type)))) (define ((unquote vector-in-range?) vector k) (unquote (format "(~a vector k)\u000A\u000AFunction that tests if index is range for ~a." vector-in-range? help)) (typecheck (unquote (symbol->string vector-in-range?)) vector (unquote l-type)) (typecheck (unquote (symbol->string vector-in-range?)) k "number") (let ((len (length vector))) (and (>= k 0) (< k len)))) (define ((unquote vector-ref) vector k) (unquote (format "(~a vector k)\u000A\u000AReturns value frome vector at index k. If index is out of range it throw exception." vector-ref help)) (typecheck (unquote (symbol->string vector-ref)) vector (unquote l-type)) (typecheck (unquote (symbol->string vector-ref)) k "number") (if (not ((unquote vector-in-range?) vector k)) (throw (new Error (unquote (format "~a index out of range" vector-ref)))) (. vector k))) (define ((unquote vector->list) vector) (typecheck (unquote (symbol->string vector->list)) vector (unquote l-type)) (vector->list (Array.from vector))) (define ((unquote vector-set!) vector k v) (unquote (format "(~a vector k)\u000A\u000AFunction set value of ~a at index k. If index is out of range it throw exception." vector-set! help)) (typecheck (unquote (symbol->string vector-set!)) vector (unquote l-type)) (typecheck (unquote (symbol->string vector-set!)) k "number") (if (not ((unquote vector-in-range?) vector k)) (throw (new Error (unquote (format "~a index out of range" vector-set!)))) (set-obj! vector k v))) (define ((unquote list->tvector) lst) (typecheck (unquote (symbol->string list->tvector)) lst "pair") (apply (unquote vector) lst)) (define ((unquote vector->tvector) vector) (typecheck (unquote (symbol->string vector->tvector)) vector "array") ((unquote TypedArray.from) vector)) (set-special! (unquote repr-str) (quote (unquote type-vector)) lips.specials.SPLICE) (set-repr! (unquote type) (lambda (x _quote) (string-append (unquote repr-str) (repr ((unquote vector->list) x) _quote)))))))) +(%make-vector u8 Uint8Array "unsigned 8-bit integer vector (C unsigned char)") +(%make-vector s8 Int8Array "signed 8-bit integer vector (C signed char)") +(%make-vector u16 Uint16Array "unsigned 16-bit integer vector (C unsigned short)") +(%make-vector s16 Int16Array "signed 16-bit integer vector (C short)") +(%make-vector u32 Uint32Array "unsigned 32-bit integer vector (C int)") +(%make-vector s32 Int32Array "signed 32-bit integer vector (C unsigned int)") +(%make-vector f32 Float32Array "32-bit IEEE-754 floating point number vector (C float)") +(%make-vector f64 Float64Array "64-bit IEEE-754 floating point number vector (C double)") +(define (list-match? predicate list) "(list-match? predicate list)\u000A\u000AChecks if consecutive elements of the list match the predicate function." (typecheck "list-match?" predicate #("function" "macro")) (typecheck "list-match?" list "pair") (or (or (null? list) (null? (cdr list))) (and (predicate (car list) (cadr list)) (list-match? predicate (cdr list))))) +(define (symbol=? . args) "(symbol=? s1 s2 ...)\u000A\u000AChecks if each value is symbol and it's the same acording to string=? predicate." (list-match? (lambda (a b) (and (symbol? a) (symbol? b) (equal? a b))) args)) +(define (values-ref values n) "(values-ref values n)\u000A\u000AReturns n value of values object which is result of value function." (typecheck "values-ref" values "values" 1) (typecheck "values-ref" n "number" 1) (--> values (valueOf) n)) (define-syntax let-values (syntax-rules () ((_ ()) ()) ((_ () body ...) (begin body ...)) ((_ (((x ...) values) ...) body ...) (apply (lambda (x ... ...) body ...) (vector->list (apply vector-append (map (lambda (arg) ((. arg "valueOf"))) (list values ...))))))) "(let-values binding body ...)\u000A\u000AThe macro work similar to let but variable is list of values and value\u000Aneed to evaluate to result of calling values.") -(define (vector-append . args) "(vector-append v1 v2 ...)\u000A\u000AFunction return new vector by combining it's arguments that should be vectors." (if (null? args) (vector) (begin (typecheck "vector-append" (car args) "array") (--> (car args) (concat (apply vector-append (cdr args))))))) -(define-macro (%range-function spec . body) "(%range-function spec . body)\u000A\u000AMacro that creates R7RS vector functions that have range start end." (let* ((name (car spec)) (name-str (symbol->string name)) (args (append (cdr spec) (quote rest)))) (quasiquote (define ((unquote name) (unquote-splicing args)) (unquote (if (string? (car body)) (car body))) (let ((start (if (null? rest) 0 (car rest))) (end (if (or (null? rest) (null? (cdr rest))) (. (unquote (car args)) (quote length)) (cadr rest)))) (typecheck (unquote name-str) start "number") (typecheck (unquote name-str) end "number") (unquote-splicing (if (string? (car body)) (cdr body) body))))))) -(%range-function (vector->list vector) "(vector->list vector)\u000A(vector->list vector start)\u000A(vector->list vector start end)\u000A\u000AFunction copy given range of vector to list. If no start is specified it use\u000Astart of the vector, if no end is specified it convert to the end of the vector." (typecheck "vector->list" vector "array") (array->list (vector.slice start end))) -(%range-function (string->vector string) "(string->list string)\u000A(string->list string start)\u000A(string->list string start end)\u000A\u000AFunction copy given range of string to list. If no start is specified it use\u000Astart of the string, if no end is specified it convert to the end of the string." (typecheck "string->vector" string "string") (--> (string.substring start end) (split "") (map (unary lips.LCharacter)))) -(%range-function (vector->string vector) "(vector->string vector)\u000A(vector->string vector start)\u000A(vector->string vector start end)\u000A\u000AFunction return new string created from vector of characters in given range.\u000AIf no start is given it create string from 0, if no end is given it return\u000Astring to the end." (typecheck "vector->string" vector "array") (--> vector (slice start end) (map (lambda (char) (char.valueOf))) (join ""))) +(define (vector-append . args) "(vector-append v1 v2 ...)\u000A\u000AReturns new vector by combining it's arguments that should be vectors." (if (null? args) (vector) (begin (typecheck "vector-append" (car args) "array") (--> (car args) (concat (apply vector-append (cdr args))))))) +(define-macro (%range-function spec . body) "(%range-function spec . body)\u000A\u000ACreates R7RS vector functions that have range start end." (let* ((name (car spec)) (name-str (symbol->string name)) (args (append (cdr spec) (quote rest)))) (quasiquote (define ((unquote name) (unquote-splicing args)) (unquote (if (string? (car body)) (car body))) (let ((start (if (null? rest) 0 (car rest))) (end (if (or (null? rest) (null? (cdr rest))) (. (unquote (car args)) (quote length)) (cadr rest)))) (typecheck (unquote name-str) start "number") (typecheck (unquote name-str) end "number") (unquote-splicing (if (string? (car body)) (cdr body) body))))))) +(%range-function (vector->list vector) "(vector->list vector)\u000A(vector->list vector start)\u000A(vector->list vector start end)\u000A\u000AFunction that copies given range of vector to list. If no start is specified it use\u000Astart of the vector, if no end is specified it convert to the end of the vector." (typecheck "vector->list" vector "array") (array->list (vector.slice start end))) +(%range-function (string->vector string) "(string->list string)\u000A(string->list string start)\u000A(string->list string start end)\u000A\u000AFunction that copies given range of string to list. If no start is specified it use\u000Astart of the string, if no end is specified it convert to the end of the string." (typecheck "string->vector" string "string") (--> (string.substring start end) (split "") (map (unary lips.LCharacter)))) +(%range-function (vector->string vector) "(vector->string vector)\u000A(vector->string vector start)\u000A(vector->string vector start end)\u000A\u000AReturns new string created from vector of characters in given range.\u000AIf no start is given it create string from 0, if no end is given it return\u000Astring to the end." (typecheck "vector->string" vector "array") (--> vector (slice start end) (map (lambda (char) (char.valueOf))) (join ""))) (%range-function (vector-fill! vector fill) "(vector-fill! vector fill)\u000A(vector-fill! vector fill start)\u000A(vector-fill! vector fill start end)\u000A\u000AFill vector with a given value in given range. If start is not given is start\u000Aat 0. If end is not given it fill till the end if the vector." (typecheck "vector->fill!" vector "array") (let recur ((n (- end start))) (if (>= n start) (begin (set-obj! vector n fill) (recur (- n 1)))))) (define-syntax let*-values (syntax-rules () ((_ ()) ()) ((_ () body ...) (begin body ...)) ((_ ((bind values) rest ...) . body) (apply (lambda bind (let*-values (rest ...) . body)) (vector->list ((. values "valueOf")))))) "(let*-values binding body ...)\u000A\u000AThe macro work similar to let* but variable is list of values and value\u000Aneed to evaluate to result of calling values.") (define (quotient&remainder x y) (values (quotient x y) (remainder x y))) @@ -296,20 +296,20 @@ (define (truncate-quotient x y) (quotient x y)) (define (truncate-remainder x y) (remainder x y)) (define-syntax case-lambda (syntax-rules () ((case-lambda (params body0 ...) ...) (lambda args (let ((len (length args))) (letrec-syntax ((cl (syntax-rules ::: () ((cl) (error "no matching clause")) ((cl ((p :::) . body) . rest) (if (= len (length (quote (p :::)))) (apply (lambda (p :::) . body) args) (cl . rest))) ((cl ((p ::: . tail) . body) . rest) (if (>= len (length (quote (p :::)))) (apply (lambda (p ::: . tail) . body) args) (cl . rest)))))) (cl (params body0 ...) ...)))))) "(case-lambda expr ...)\u000A\u000AMacro create new function with different version of the function depend on\u000Anumber of arguments. Each expression is similar to single lambda.\u000A\u000Ae.g.:\u000A\u000A (define sum\u000A (case-lambda\u000A ((x) x)\u000A ((x y) (+ x y))\u000A ((x y z) (+ x y z))))\u000A\u000A (sum 1)\u000A (sum 1 2)\u000A (sum 1 2 3)\u000A\u000AMore arguments will give error.") -(define (boolean=? . args) "(boolean=? b1 b2 ...)\u000A\u000AFunction check if all arguments are boolean and if they are the same." (if (< (length args) 2) (error "boolean=?: too few arguments") (reduce (lambda (acc item) (and (boolean? item) (eq? acc item))) (car args) (cdr args)))) -(define (port? x) "(port? x)\u000A\u000AFunction return true of argumet is nput or output port port object." (or (output-port? x) (input-port? x))) +(define (boolean=? . args) "(boolean=? b1 b2 ...)\u000A\u000AChecks if all arguments are boolean and if they are the same." (if (< (length args) 2) (error "boolean=?: too few arguments") (reduce (lambda (acc item) (and (boolean? item) (eq? acc item))) (car args) (cdr args)))) +(define (port? x) "(port? x)\u000A\u000AReturns true if the argument is an input or output port object." (or (output-port? x) (input-port? x))) (define (square x) "(square z)\u000A\u000AReturns the square of z. This is equivalent to (* z z)." (* x x)) -(define-syntax when (syntax-rules () ((when test result1 result2 ...) (if test (begin result1 result2 ...)))) "(when test body ...)\u000A\u000AMacro execute body when test expression is true.") -(define-syntax unless (syntax-rules () ((unless test result1 result2 ...) (if (not test) (begin result1 result2 ...)))) "(unless test body ...)\u000A\u000AMacro execute body when test expression is false.") +(define-syntax when (syntax-rules () ((when test result1 result2 ...) (if test (begin result1 result2 ...)))) "(when test body ...)\u000A\u000AExecutes body when test expression is true.") +(define-syntax unless (syntax-rules () ((unless test result1 result2 ...) (if (not test) (begin result1 result2 ...)))) "(unless test body ...)\u000A\u000AExecutes body when test expression is false.") (define inexact exact->inexact) (define exact inexact->exact) -(define (exact-integer? n) "(exact-integer? n)\u000A\u000AFunction returns #t if z is both exact and an integer; otherwise\u000Areturns #f." (and (integer? n) (exact? n))) -(define (vector-map fn . rest) "(vector-map fn vector1 vector2 ...)\u000A\u000AFunction return new vector from applying function fn to each element\u000Aof the vectors, similar to map for lists." (if (or (= (length rest) 0) (not (every vector? rest))) (error "vector-map: function require at least 1 vector") (let ((len (apply min (map vector-length rest))) (result (vector))) (do ((i 0 (+ i 1))) ((= i len) result) (let* ((args (map (lambda (v) (vector-ref v i)) rest)) (value (apply fn args))) (--> result (push value))))))) -(define (string-map fn . rest) "(string-map fn string1 stringr2 ...)\u000A\u000AFunction return new string from applying function fn to each element\u000Aof the strings, similar to map for lists." (if (or (= (length rest) 0) (not (every string? rest))) (error "string-map: function require at least 1 string") (vector->string (apply vector-map fn (map string->vector rest))))) -(define (dynamic-wind before thunk after) "(dynamic-wind before thunk after)\u000A\u000AFunction accept 3 procedures/lambdas and execute thunk with before and always\u000Aafter even if error accur" (before) (let ((result (try (thunk) (catch (e) (error e))))) (after) result)) +(define (exact-integer? n) "(exact-integer? n)\u000A\u000AReturns #t if z is both exact and an integer; otherwise\u000Areturns #f." (and (integer? n) (exact? n))) +(define (vector-map fn . rest) "(vector-map fn vector1 vector2 ...)\u000A\u000AReturns new vector from applying function fn to each element\u000Aof the vectors, similar to map for lists." (if (or (= (length rest) 0) (not (every vector? rest))) (error "vector-map: function require at least 1 vector") (let ((len (apply min (map vector-length rest))) (result (vector))) (do ((i 0 (+ i 1))) ((= i len) result) (let* ((args (map (lambda (v) (vector-ref v i)) rest)) (value (apply fn args))) (--> result (push value))))))) +(define (string-map fn . rest) "(string-map fn string1 stringr2 ...)\u000A\u000AReturns new string from applying function fn to each element\u000Aof the strings, similar to map for lists." (if (or (= (length rest) 0) (not (every string? rest))) (error "string-map: function require at least 1 string") (vector->string (apply vector-map fn (map string->vector rest))))) +(define (dynamic-wind before thunk after) "(dynamic-wind before thunk after)\u000A\u000AAccepts 3 procedures/lambdas and executes before, then thunk, and \u000Aalways after even if an error occurs in thunk." (before) (let ((result (try (thunk) (catch (e) (after) (error e))))) (after) result)) (define (with-exception-handler handler thunk) "(with-exception-handler handler thunk)\u000A\u000AProcedure call and return value of thunk function, if exception happen\u000Ait call handler procedure." (try (thunk) (catch (e) (handler e)))) -(define-syntax define-values (syntax-rules () ((define-values () expr) (define dummy (call-with-values (lambda () expr) (lambda args #f)))) ((define-values (var) expr) (define var expr)) ((define-values (var0 var1 ... varn) expr) (begin (define var0 (call-with-values (lambda () expr) list)) (define var1 (let ((v (cadr var0))) (set-cdr! var0 (cddr var0)) v)) ... (define varn (let ((v (cadr var0))) (set! var0 (car var0)) v)))) ((define-values (var0 var1 ... . varn) expr) (begin (define var0 (call-with-values (lambda () expr) list)) (define var1 (let ((v (cadr var0))) (set-cdr! var0 (cddr var0)) v)) ... (define varn (let ((v (cdr var0))) (set! var0 (car var0)) v)))) ((define-values var expr) (define var (call-with-values (lambda () expr) list)))) "(define-values (a b ...) expr)\u000A\u000AFunction evaluate expression expr and if it evaluates to result of values\u000Athen it will defined each value as variable like with define.") -(define-macro (include . files) "(include file ...)\u000A\u000AMacro that load at least one file content and insert them into one,\u000Abody expression." (if (null? files) (throw (new Error "include: at least one file path required")) (let ((result (vector)) (env (interaction-environment))) (if (eq? self global) (let* ((fs (require "fs")) (readFile (lambda (file) (new Promise (lambda (resolve reject) (fs.readFile file (lambda (err data) (if (null? err) (resolve (--> data (toString))) (reject err))))))))) (for-each (lambda (file) (let* ((expr (lips.parse (readFile file) env))) (set! result (--> result (concat expr))))) files)) (for-each (lambda (file) (let* ((text (--> (fetch file) (text))) (expr (lips.parse text env))) (set! result (--> result (concat expr))))) files)) (if (> result.length 0) (quasiquote (begin (unquote-splicing (vector->list result)))))))) +(define-syntax define-values (syntax-rules () ((define-values () expr) (define dummy (call-with-values (lambda () expr) (lambda args #f)))) ((define-values (var) expr) (define var expr)) ((define-values (var0 var1 ... varn) expr) (begin (define var0 (call-with-values (lambda () expr) list)) (define var1 (let ((v (cadr var0))) (set-cdr! var0 (cddr var0)) v)) ... (define varn (let ((v (cadr var0))) (set! var0 (car var0)) v)))) ((define-values (var0 var1 ... . varn) expr) (begin (define var0 (call-with-values (lambda () expr) list)) (define var1 (let ((v (cadr var0))) (set-cdr! var0 (cddr var0)) v)) ... (define varn (let ((v (cdr var0))) (set! var0 (car var0)) v)))) ((define-values var expr) (define var (call-with-values (lambda () expr) list)))) "(define-values (a b ...) expr)\u000A\u000AEvaluates expression expr and if it evaluates to result of values\u000Athen it will defined each value as variable like with define.") +(define-macro (include . files) "(include file ...)\u000A\u000ALoad at least one file content and insert them into one,\u000Abody expression." (if (null? files) (throw (new Error "include: at least one file path required")) (let ((result (vector)) (env (interaction-environment))) (if (eq? self global) (let* ((fs (require "fs")) (readFile (lambda (file) (new Promise (lambda (resolve reject) (fs.readFile file (lambda (err data) (if (null? err) (resolve (--> data (toString))) (reject err))))))))) (for-each (lambda (file) (let* ((expr (lips.parse (readFile file) env))) (set! result (--> result (concat expr))))) files)) (for-each (lambda (file) (let* ((text (--> (fetch file) (text))) (expr (lips.parse text env))) (set! result (--> result (concat expr))))) files)) (if (> result.length 0) (quasiquote (begin (unquote-splicing (vector->list result)))))))) (define-syntax syntax-error (syntax-rules () ((_ "step" arg ...) (join " " (vector->list (vector (repr arg) ...)))) ((_ message arg ...) (error (format "~a ~a" message (_ "step" arg ...)))))) (define-syntax cond-expand (syntax-rules (and or not else r7rs srfi-0 srfi-2 srfi-4 srfi-6 srfi-10 srfi-22 srfi-23 srfi-46 srfi-176 lips complex full-unicode ieee-float ratios exact-complex full-numeric-tower) ((cond-expand) (syntax-error "Unfulfilled cond-expand")) ((cond-expand (else body ...)) (begin body ...)) ((cond-expand ((and) body ...) more-clauses ...) (begin body ...)) ((cond-expand ((and req1 req2 ...) body ...) more-clauses ...) (cond-expand (req1 (cond-expand ((and req2 ...) body ...) more-clauses ...)) more-clauses ...)) ((cond-expand ((or) body ...) more-clauses ...) (cond-expand more-clauses ...)) ((cond-expand ((or req1 req2 ...) body ...) more-clauses ...) (cond-expand (req1 (begin body ...)) (else (cond-expand ((or req2 ...) body ...) more-clauses ...)))) ((cond-expand ((not req) body ...) more-clauses ...) (cond-expand (req (cond-expand more-clauses ...)) (else body ...))) ((cond-expand (r7rs body ...) more-clauses ...) (begin body ...)) ((cond-expand (srfi-0 body ...) more-clauses ...) (begin body ...)) ((cond-expand (srfi-2 body ...) more-clauses ...) (begin body ...)) ((cond-expand (srfi-4 body ...) more-clauses ...) (begin body ...)) ((cond-expand (srfi-6 body ...) more-clauses ...) (begin body ...)) ((cond-expand (srfi-10 body ...) more-clauses ...) (begin body ...)) ((cond-expand (srfi-22 body ...) more-clauses ...) (begin body ...)) ((cond-expand (srfi-23 body ...) more-clauses ...) (begin body ...)) ((cond-expand (srfi-46 body ...) more-clauses ...) (begin body ...)) ((cond-expand (srfi-176 body ...) more-clauses ...) (begin body ...)) ((cond-expand (lips body ...) more-clauses ...) (begin body ...)) ((cond-expand (complex body ...) more-clauses ...) (begin body ...)) ((cond-expand (full-unicode body ...) more-clauses ...) (begin body ...)) ((cond-expand (ieee-float body ...) more-clauses ...) (begin body ...)) ((cond-expand (ratios body ...) more-clauses ...) (begin body ...)) ((cond-expand (exact-complex body ...) more-clauses ...) (begin body ...)) ((cond-expand (full-numeric-tower body ...) more-clauses ...) (begin body ...)))) (define (features) (quote (r7rs srfi-0 srfi-2 srfi-4 srfi-6 srfi-10 srfi-22 srfi-23 srfi-46 srfi-176 lips complex full-unicode ieee-float ratios exact-complex full-numeric-tower))) @@ -322,19 +322,19 @@ (define bytevector-u8-ref u8vector-ref) (define bytevector-u8-set! u8vector-set!) (define (bytevector-append v1 . rest) "(bytevector-append v1 ...)\u000A\u000ACreate new bytevector u8vector that is created from joining each argument." (typecheck "bytevector-append" v1 "uint8array" 1) (map (lambda (arg) (typecheck "bytevector-append" arg "uint8array")) rest) (if (null? rest) v1 (new Uint8Array (apply vector-append (Array.from v1) (map Array.from rest))))) -(define (bytevector-copy v . rest) "(bytevector-copy v)\u000A(bytevector-copy v start)\u000A(bytevector-copy v start end)\u000A\u000AFunction and return new vector from start to end. If no start and end is provided\u000Awhole vector is copied and returned." (if (null? rest) (new Uint8Array v) (let ((start (car rest))) (if (null? (cdr rest)) (v.slice start) (v.slice start (cadr rest)))))) +(define (bytevector-copy v . rest) "(bytevector-copy v)\u000A(bytevector-copy v start)\u000A(bytevector-copy v start end)\u000A\u000AReturns a new vector from start to end. If no start and end is provided\u000Awhole vector is copied and returned." (if (null? rest) (new Uint8Array v) (let ((start (car rest))) (if (null? (cdr rest)) (v.slice start) (v.slice start (cadr rest)))))) (define (bytevector-copy! to at from . rest) "(bytevector-copy! to at from)\u000A(bytevector-copy! to at from start)\u000A(bytevector-copy! to at from start end)\u000A\u000ACopies the bytes of bytevector from between start and end to bytevector to,\u000Astarting at at." (typecheck "bytevector-copy!" to "uint8array") (typecheck "bytevector-copy!" from "uint8array") (cond ((< at 0) (throw (new Error "bytevector-copy! `at` need to be positive"))) ((> at (bytevector-length to)) (throw (new Error "bytevector-copy! `at` need to be less then byte vector length")))) (let* ((start (if (null? rest) 0 (car rest))) (end (if (or (null? rest) (null? (cdr rest))) (- (bytevector-length from) start) (cadr rest)))) (let ((i at) (j start)) (while (and (< i (bytevector-length to)) (< i (bytevector-length from)) (< j (+ start end))) (bytevector-u8-set! to i (bytevector-u8-ref from j)) (set! i (+ i 1)) (set! j (+ j 1)))))) -(define string->utf8 (let ((encoder (new TextEncoder "utf-8"))) (lambda (string . rest) "(string->utf8 string)\u000A(string->utf8 string start)\u000A(string->utf8 string start end)\u000A\u000AFunction converts string into u8 bytevector using utf8 encoding.\u000AThe start and end is the range of the input string for the conversion." (typecheck "string->utf8" string "string") (if (null? rest) (encoder.encode string) (let* ((start (car rest)) (len (--> (Array.from string) (quote length))) (end (if (null? (cdr rest)) len (cadr rest)))) (encoder.encode (substring string start end))))))) -(define utf8->string (let ((decoder (new TextDecoder "utf-8"))) (lambda (v . rest) "(utf8->string u8vector)\u000A(utf8->string u8vector start)\u000A(utf8->string u8vector start end)\u000A\u000AFunction converts u8 bytevector into string using utf8 encoding.\u000AThe start and end is the range of the input byte vector for the conversion." (typecheck "utf8->string" v "uint8array") (if (null? rest) (decoder.decode v) (let* ((start (car rest)) (len (--> (Array.from string) (quote length))) (end (if (null? (cdr rest)) len (cadr rest)))) (decoder.decode (v.slice start end))))))) -(define (open-input-string string) "(open-input-string string)\u000A\u000AFunction create new string port as input that can be used to\u000Aread S-exressions from this port using `read` function." (typecheck "open-input-string" string "string") (new lips.InputStringPort string (interaction-environment))) -(define (open-output-string) "(open-output-string)\u000A\u000AFunction create new output port that can used to write string into\u000Aand after finish get the whole string using `get-output-string`." (new lips.OutputStringPort repr)) +(define string->utf8 (let ((encoder (new TextEncoder "utf-8"))) (lambda (string . rest) "(string->utf8 string)\u000A(string->utf8 string start)\u000A(string->utf8 string start end)\u000A\u000AConverts string into u8 bytevector using utf8 encoding.\u000AThe start and end is the range of the input string for the conversion." (typecheck "string->utf8" string "string") (if (null? rest) (encoder.encode string) (let* ((start (car rest)) (len (--> (Array.from string) (quote length))) (end (if (null? (cdr rest)) len (cadr rest)))) (encoder.encode (substring string start end))))))) +(define utf8->string (let ((decoder (new TextDecoder "utf-8"))) (lambda (v . rest) "(utf8->string u8vector)\u000A(utf8->string u8vector start)\u000A(utf8->string u8vector start end)\u000A\u000AConverts u8 bytevector into string using utf8 encoding.\u000AThe start and end is the range of the input byte vector for the conversion." (typecheck "utf8->string" v "uint8array") (if (null? rest) (decoder.decode v) (let* ((start (car rest)) (len (--> (Array.from string) (quote length))) (end (if (null? (cdr rest)) len (cadr rest)))) (decoder.decode (v.slice start end))))))) +(define (open-input-string string) "(open-input-string string)\u000A\u000ACreates new string port as input that can be used to\u000Aread S-exressions from this port using `read` function." (typecheck "open-input-string" string "string") (new lips.InputStringPort string (interaction-environment))) +(define (open-output-string) "(open-output-string)\u000A\u000ACreates new output port that can used to write string into\u000Aand after finish get the whole string using `get-output-string`." (new lips.OutputStringPort repr)) (define (open-output-bytevector) "(open-output-bytevector)\u000A\u000ACreate new output port that can be used to write binary data.\u000AAfter done with the data the output buffer can be obtained by calling\u000A`get-output-bytevector` function." (new lips.OutputByteVectorPort)) -(define (get-output-bytevector port) "(get-output-string port)\u000A\u000AFunction get full string from string port. If nothing was wrote\u000Ato given port it will return empty string." (if (not (instanceof lips.OutputByteVectorPort port)) (throw (new Error (string-append "get-output-bytevector: expecting output-bytevector-port get " (type port)))) (port.valueOf))) -(define (get-output-string port) "(get-output-string port)\u000A\u000AFunction get full string from string port. If nothing was wrote\u000Ato given port it will return empty string." (if (not (instanceof lips.OutputStringPort port)) (throw (new Error (string-append "get-output-string: expecting output-string-port get " (type port)))) (port.valueOf))) +(define (get-output-bytevector port) "(get-output-string port)\u000A\u000AGets full string from string port. If nothing was wrote\u000Ato given port it will return empty string." (if (not (instanceof lips.OutputByteVectorPort port)) (throw (new Error (string-append "get-output-bytevector: expecting output-bytevector-port get " (type port)))) (port.valueOf))) +(define (get-output-string port) "(get-output-string port)\u000A\u000AGets full string from string port. If nothing was wrote\u000Ato given port it will return empty string." (if (not (instanceof lips.OutputStringPort port)) (throw (new Error (string-append "get-output-string: expecting output-string-port get " (type port)))) (port.valueOf))) (define (open-input-bytevector bytevector) "(open-input-bytevector bytevector)\u000A\u000ACreate new input binary port with given bytevector" (typecheck "open-input-bytevector" bytevector "uint8array") (new lips.InputByteVectorPort bytevector)) -(define (open-binary-input-file filename) "(open-binary-input-file filename)\u000A\u000AFunction return new Input Binary Port with given filename. In Browser\u000Auser need to provide global fs variable that is instance of FS interface." (let ((u8vector (buffer->u8vector (%read-binary-file filename)))) (new lips.InputBinaryFilePort u8vector filename))) -(define (binary-port? port) "(binary-port? port)\u000A\u000AFunction test if argument is binary port." (and (port? port) (eq? port.__type__ (Symbol.for "binary")))) -(define (textual-port? port) "(textual-port? port)\u000A\u000AFunction test if argument is string port." (and (port? port) (eq? port.__type__ (Symbol.for "text")))) +(define (open-binary-input-file filename) "(open-binary-input-file filename)\u000A\u000AReturns new Input Binary Port with given filename. In Browser\u000Auser need to provide global fs variable that is instance of FS interface." (let ((u8vector (buffer->u8vector (%read-binary-file filename)))) (new lips.InputBinaryFilePort u8vector filename))) +(define (binary-port? port) "(binary-port? port)\u000A\u000AFunction that tests if argument is binary port." (and (port? port) (eq? port.__type__ (Symbol.for "binary")))) +(define (textual-port? port) "(textual-port? port)\u000A\u000AFunction that tests if argument is string port." (and (port? port) (eq? port.__type__ (Symbol.for "text")))) (define-macro (%define-binary-input-lambda name docstring fn) (let ((port (gensym)) (name-str (symbol->string name))) (quasiquote (define ((unquote name) . rest) (unquote docstring) (let (((unquote port) (if (null? rest) (current-input-port) (car rest)))) (typecheck (unquote name-str) (unquote port) "input-port") (if (not (binary-port? (unquote port))) (throw (new Error (string-append (unquote name-str) " invalid port. Binary port required."))) ((unquote fn) (unquote port)))))))) (%define-binary-input-lambda peek-u8 "(peek-u8)\u000A(peek-u8 port)\u000A\u000AReturn next byte from input-binary port. If there are no more bytes\u000Ait return eof object." (lambda (port) (port.peek_u8))) (%define-binary-input-lambda read-u8 "(read-u8)\u000A(read-u8 port)\u000A\u000ARead next byte from input-binary port. If there are no more bytes\u000Ait return eof object." (lambda (port) (port.read_u8))) @@ -343,23 +343,23 @@ (define-macro (%define-binary-output-lambda name type docstring fn) (let ((port (gensym (quote port))) (data (gensym (quote data))) (name-str (symbol->string name))) (quasiquote (define ((unquote name) (unquote data) . rest) (unquote docstring) (let (((unquote port) (if (null? rest) (current-output-port) (car rest)))) (typecheck (unquote name-str) (unquote port) "output-port") (typecheck (unquote name-str) (unquote data) (unquote type)) (if (not (binary-port? (unquote port))) (throw (new Error (string-append (unquote name-str) " invalid port. Binary port required."))) ((unquote fn) (unquote data) (unquote port)))))))) (%define-binary-output-lambda write-u8 "number" "(write-u8 byte)\u000A(write-u8 byte port)\u000A\u000AWrite byte into binary output port." (lambda (data port) (port.write_u8 data))) (%define-binary-output-lambda write-bytevector "uint8array" "(write-bytevector bytevector)\u000A(write-bytevector bytevector port)\u000A\u000AWrite byte vector into binary output port." (lambda (data port) (port.write_u8_vector data))) -(define open-binary-output-file (let ((open)) (lambda (filename) "(open-binary-output-file filename)\u000A\u000AFunction open file and return port that can be used for writing. If file\u000Aexists it will throw an Error." (typecheck "open-output-file" filename "string") (if (not (procedure? open)) (set! open (%fs-promisify-proc (quote open) "open-binary-output-file"))) (if (file-exists? filename) (throw (new Error "open-binary-output-file: file exists")) (lips.OutputBinaryFilePort filename (open filename "w")))))) -(define (read-bytevector! vector . rest) "(read-bytevector! bytevector)\u000A(read-bytevector! bytevector port)\u000A(read-bytevector! bytevector port start)\u000A(read-bytevector! bytevector port start end)\u000A\u000AFunction read next bytes from binary input port and write them into byte vector.\u000Aif not start is specified it start to write into 0 position of the vector until\u000Athe end or end the vector if no end is specified." (typecheck "read-bytevector!" vector "uint8array") (let ((port (if (null? rest) (current-input-port) (car rest))) (start (if (or (null? rest) (null? (cdr rest))) 0 (cadr rest))) (end (if (or (null? rest) (null? (cdr rest)) (null? (cddr rest))) (bytevector-length vector) (caddr rest)))) (typecheck "read-bytevector!" port "input-port") (if (not (binary-port? port)) (throw (new Error "read-bytevector!: invalid port. Binary port required.")) (begin (typecheck "read-bytevector!" start "number") (typecheck "read-bytevector!" end "number") (let ((out (read-bytevector (- end start) port))) (vector.set out start end)))))) -(define delete-file (let ((unlink #f)) (lambda (filename) "(delete-file filename)\u000A\u000AFunction delete the file of given name." (typecheck "delete-file" filename "string") (if (not (procedure? unlink)) (set! unlink (%fs-promisify-proc (quote unlink) "delete-file"))) (unlink filename)))) +(define open-binary-output-file (let ((open)) (lambda (filename) "(open-binary-output-file filename)\u000A\u000AOpens file and return port that can be used for writing. If file\u000Aexists it will throw an Error." (typecheck "open-output-file" filename "string") (if (not (procedure? open)) (set! open (%fs-promisify-proc (quote open) "open-binary-output-file"))) (if (file-exists? filename) (throw (new Error "open-binary-output-file: file exists")) (lips.OutputBinaryFilePort filename (open filename "w")))))) +(define (read-bytevector! vector . rest) "(read-bytevector! bytevector)\u000A(read-bytevector! bytevector port)\u000A(read-bytevector! bytevector port start)\u000A(read-bytevector! bytevector port start end)\u000A\u000AReads next bytes from binary input port and write them into byte vector.\u000Aif not start is specified it start to write into 0 position of the vector until\u000Athe end or end the vector if no end is specified." (typecheck "read-bytevector!" vector "uint8array") (let ((port (if (null? rest) (current-input-port) (car rest))) (start (if (or (null? rest) (null? (cdr rest))) 0 (cadr rest))) (end (if (or (null? rest) (null? (cdr rest)) (null? (cddr rest))) (bytevector-length vector) (caddr rest)))) (typecheck "read-bytevector!" port "input-port") (if (not (binary-port? port)) (throw (new Error "read-bytevector!: invalid port. Binary port required.")) (begin (typecheck "read-bytevector!" start "number") (typecheck "read-bytevector!" end "number") (let ((out (read-bytevector (- end start) port))) (vector.set out start end)))))) +(define delete-file (let ((unlink #f)) (lambda (filename) "(delete-file filename)\u000A\u000ADeletes the file of given name." (typecheck "delete-file" filename "string") (if (not (procedure? unlink)) (set! unlink (%fs-promisify-proc (quote unlink) "delete-file"))) (unlink filename)))) (define (call-with-port port proc) "(call-with-port port proc)\u000A\u000AProc is executed with given port and after it returns, the port is closed." (try (proc port) (finally (if (procedure? port.close) (port.close))))) (define (close-port port) "(close-port port)\u000A\u000AClose input or output port." (typecheck "close-port" port #("input-port" "output-port")) (port.close)) (define (eof-object) "(eof-object)\u000A\u000AProcedure returns eof object that indicate end of the port" lips.eof) -(define (output-port-open? port) "(output-port-open? port)\u000A\u000AFunction check if argument is output-port and if you can write to it." (and (output-port? port) (port.is_open))) -(define (input-port-open? port) "(input-port-open? port)\u000A\u000AFunction check if argument is input-port and if you can read from it." (and (input-port? port) (port.is_open))) +(define (output-port-open? port) "(output-port-open? port)\u000A\u000AChecks if argument is output-port and if you can write to it." (and (output-port? port) (port.is_open))) +(define (input-port-open? port) "(input-port-open? port)\u000A\u000AChecks if argument is input-port and if you can read from it." (and (input-port? port) (port.is_open))) (define (flush-output-port port) "(flush-output-port port)\u000A\u000AFunctio do nothing, flush is not needed in LIPS in both NodeJS and Browser.\u000AThe function is added, so it don't throw exception when using R7RS code." (if #f #f)) (define (write-string string . rest) "(write-string string)\u000A(write-string string port)\u000A(write-string string port start)\u000A(write-string string port start end)\u000A\u000AWrites the characters of string from start to end in left-toright order\u000Ato the textual output port." (typecheck "write-string" string "string") (let ((port (if (null? rest) (current-output-port) (car rest))) (start (if (or (null? rest) (null? (cdr rest))) 0 (cadr rest))) (end (if (or (null? rest) (null? (cdr rest)) (null? (cddr rest))) (string-length string) (caddr rest)))) (typecheck "write-string" port "output-port") (typecheck "write-string" start "number") (typecheck "write-string" end "number") (display (substring string start end) port))) (define (write-char char . rest) "(write-char string)\u000A(write-char string port)\u000A\u000AWrites the character char (not an external representation of the character)\u000Ato the given textual output port and returns an unspecified value." (typecheck "write-char" char "character") (let ((port (if (null? rest) (current-output-port) (car rest)))) (typecheck "write-char" port "output-port") (display (string char) port))) (define (read-string k . rest) "(read-string k)\u000A(read-string k port)\u000A\u000AReads the next k characters, or as many as are available\u000Abefore the end of file, from the textual input port into a\u000Anewly allocated string in left-to-right order and returns the\u000Astring. If no characters are available before the end of file,\u000Aan end-of-file object is returned." (typecheck "read-string" k "number") (let ((port (if (null? rest) (current-input-port) (car rest)))) (typecheck "read-string" port "input-port") (port.read_string k))) (define (list-copy obj) "(list-copy obj)\u000A\u000ACopy the object passed as argument but only if it's list. The car elements\u000Aof the list are not copied, they are passed as is." (typecheck "list-copy" obj #("pair" "nil")) (if (null? obj) obj (obj.clone #f))) (define-macro (define-record-type name constructor pred . fields) "(define-record-type name constructor pred . fields)\u000A\u000AMacro for defining records. Example of usage:\u000A\u000A(define-record-type <pare>\u000A (kons x y)\u000A pare?\u000A (x kar set-kar!)\u000A (y kdr set-kdr!))\u000A\u000A(define p (kons 1 2))\u000A(print (kar p))\u000A;; 1\u000A(set-kdr! p 3)\u000A(print (kdr p))\u000A;; 3" (let ((obj-name (gensym (quote obj-name))) (value-name (gensym (quote value-name)))) (quasiquote (begin (define (unquote name) (class Object (constructor (lambda (self (unquote-splicing (cdr constructor))) (unquote-splicing (map (lambda (field) (let* ((name (symbol->string field)) (prop (string-append "self." name))) (quasiquote (set! (unquote (string->symbol prop)) (unquote field))))) (cdr constructor))))) (toType (lambda (self) "record")) (toString (lambda (self) (string-append "#<" (unquote (symbol->string name)) ">"))))) (define (unquote constructor) (new (unquote name) (unquote-splicing (cdr constructor)))) (define ((unquote pred) obj) (instanceof (unquote name) obj)) (unquote-splicing (map (lambda (field) (let ((prop-name (car field)) (get (cadr field)) (set (if (null? (cddr field)) () (caddr field)))) (quasiquote (begin (define ((unquote get) (unquote obj-name)) (typecheck (unquote (symbol->string get)) (unquote obj-name) "record") (if (not ((unquote pred) (unquote obj-name))) (throw (new Error (unquote (string-append "object is not record of type " (symbol->string name))))) (. (unquote obj-name) (quote (unquote prop-name))))) (unquote (if (not (null? set)) (quasiquote (define ((unquote set) (unquote obj-name) (unquote value-name)) (typecheck (unquote (symbol->string get)) (unquote obj-name) "record") (if (not ((unquote pred) (unquote obj-name))) (throw (new Error (unquote (string-append "object is not record of type " (symbol->string name))))) (set-obj! (unquote obj-name) (quote (unquote prop-name)) (unquote value-name))))))))))) fields)))))) -(define (nan? x) "(nan? x)\u000A\u000AFunction check if argument x is Not a Number (NaN) value." (and (number? x) (or (x.isNaN) (and (%number-type "complex" x) (or (nan? (real-part x)) (nan? (imag-part x))))))) -(define (infinite? x) "(infinite? x)\u000A\u000AFunction check if value is infinite." (or (eq? x Number.NEGATIVE_INFINITY) (eq? x Number.POSITIVE_INFINITY) (and (number? x) (not (eq? x +nan.0)) (%number-type "complex" x) (or (infinite? (real-part x)) (infinite? (imag-part x)))))) -(define (finite? x) "(finite? x)\u000A\u000AFunction check if value is finite." (not (infinite? x))) +(define (nan? x) "(nan? x)\u000A\u000AChecks if argument x is Not a Number (NaN) value." (and (number? x) (or (x.isNaN) (and (%number-type "complex" x) (or (nan? (real-part x)) (nan? (imag-part x))))))) +(define (infinite? x) "(infinite? x)\u000A\u000AChecks if value is infinite." (or (eq? x Number.NEGATIVE_INFINITY) (eq? x Number.POSITIVE_INFINITY) (and (number? x) (not (eq? x +nan.0)) (%number-type "complex" x) (or (infinite? (real-part x)) (infinite? (imag-part x)))))) +(define (finite? x) "(finite? x)\u000A\u000AChecks if value is finite." (not (infinite? x))) (define-class %Library Object (constructor (lambda (self name) (set! self.__namespace__ &()) (set! self.__name__ name))) (append (lambda (self namespace env) (if (environment? (. self.__namespace__ namespace)) (throw (new Error (string-append "namespace " namespace " already exists in library " self.__name__))) (set-obj! self.__namespace__ namespace env)))) (env (lambda (self namespace) (let ((env (. self.__namespace__ namespace))) (if (not (environment? env)) (throw (new Error (string-append "namespace " namespace " sdon't exists"))) env)))) (get (lambda (self namespace name) (--> (self.env namespace) (get name)))) (set (lambda (self namespace name value) (--> (self.env namespace) (set name value)))) (toString (lambda (self) (string-append "#<Library(" self.__name__ ")>")))) (define (%import-name library namespace names) (quasiquote (begin (unquote-splicing (map (lambda (name) (quasiquote (define (unquote name) (--> (unquote library) (get (quote (unquote namespace)) (quote (unquote name))))))) names))))) (define-macro (import . specs) "(import (library namespace))\u000A(import (only (library namespace) name1 name2))\u000A\u000AMacro for importing names from library." (let ((parent (current-environment))) (quasiquote (begin (unquote-splicing (map (lambda (spec) (if (not (pair? spec)) (throw (new Error "import: invalid syntax")) (cond ((symbol=? (car spec) (quote only)) (let ((lib (caadr spec)) (namespace (caaddr spec))) (if (pair? (cadr spec)) (%import-name (unquote lib) (quote (unquote namespace)) (quote (unquote (caddr spec)))) (throw (new Error "import: invalid syntax"))))) (else (let* ((lib-name (car spec)) (lib (parent.get lib-name)) (namespace (cadr spec))) (%import-name lib-name namespace (env (lib.env namespace)))))))) specs)))))) @@ -367,15 +367,15 @@ (define (%export module namespace specs) (quasiquote (begin (unquote-splicing (map (lambda (expr) (cond ((symbol? expr) (quasiquote (--> (unquote module) (set (quote (unquote namespace)) (quote (unquote expr)) (unquote expr))))) ((and (pair? expr) (symbol=? (car expr) (quote rename))) (quasiquote (--> (unquote module) (set (quote (unquote namespace)) (quote (unquote (cadr expr))) (unquote (caddr expr)))))))) specs))))) (define-macro (define-library spec . body) "(define-library (library (name namespace) . body)\u000A\u000AMacro for defining modules inside you can use define to create functions.\u000AAnd use export name to add that name to defined environment." (let ((parent (. (current-environment) (quote __parent__))) (module-var (gensym)) (namespace-var (gensym)) (name (car spec)) (namespace (cadr spec))) (quasiquote (let (((unquote module-var) (new-library (unquote (repr name)) (unquote (repr namespace)))) ((unquote namespace-var) (quote (unquote namespace)))) (define-macro (export . body) (%export (unquote module-var) (unquote namespace-var) body)) (unquote-splicing body) (--> (unquote parent) (set (quote (unquote name)) (unquote module-var))))))) (define-syntax define-library/export (syntax-rules (rename :c) ((_ :c (rename to from)) (print (string-append "export " (symbol->string (quote from)) " ==> " (symbol->string (quote to))))) ((_ :c name) (print (string-append "export " (symbol->string (quote name))))) ((_ x ...) (begin (define-library/export :c x) ...)))) -(define-values (current-directory set-current-directory!) (if (eq? self window) (let ((cwd (string-append location.origin (--> location.pathname (replace #/\/[^/]+$/ "/"))))) (values (lambda () "(current-directory)\u000A\u000AReturn corrent working directory, default it's corrent URL." cwd) (lambda (value) "(set-current-directory! string)\u000A\u000AFunction change current working directory to provided string." (typecheck "set-current-directory!" value "string") (set! cwd value)))) (let ((process (require "process"))) (values (lambda () "(current-directory)\u000A\u000AReturn corrent working directory, default it's path from where\u000Athe script was executed." (string-append (process.cwd) "/")) (lambda (value) "(set-current-directory! string)\u000A\u000AFunction change current working directory to provided string." (typecheck "set-current-directory!" value "string") (process.chdir value)))))) +(define-values (current-directory set-current-directory!) (if (eq? self window) (let ((cwd (string-append location.origin (--> location.pathname (replace #/\/[^/]+$/ "/"))))) (values (lambda () "(current-directory)\u000A\u000AReturn current working directory, default is the current URL." cwd) (lambda (value) "(set-current-directory! string)\u000A\u000AChanges the current working directory to provided string." (typecheck "set-current-directory!" value "string") (set! cwd value)))) (let ((process (require "process"))) (values (lambda () "(current-directory)\u000A\u000AReturns the current working directory, default is the path from where\u000Athe script was executed." (string-append (process.cwd) "/")) (lambda (value) "(set-current-directory! string)\u000A\u000AChanges the current working directory to provided string." (typecheck "set-current-directory!" value "string") (process.chdir value)))))) (define (error message . args) "(error message ...)\u000A\u000AFunction raises error with given message and arguments,\u000Awhich are called invariants." (raise (new lips.Error message (args.to_array)))) -(define (error-object? obj) "(error-object? obj)\u000A\u000AFunction check if object is of Error object throwed by error function." (instanceof lips.Error obj)) +(define (error-object? obj) "(error-object? obj)\u000A\u000AChecks if object is of Error object throwed by error function." (instanceof lips.Error obj)) (define (error-object-message obj) "(error-object-message error-object)\u000A\u000AReturns the message encapsulated by error-object." (if (error-object? obj) obj.message)) (define (error-object-irritants obj) "(error-object-irritants error-object)\u000A\u000AReturns a list of the irritants encapsulated by error-object." (if (error-object? obj) obj.args)) -(define (get-environment-variables) "(get-environment-variables)\u000A\u000AFunction returns all variables as alist. This funtion throws exception\u000Awhen called in browser." (if (eq? self window) (throw "get-environment-variables: Node.js only funtion") (object->alist process.env))) -(define (get-environment-variable name) "(get-environment-variable name)\u000A\u000AFunction return given environment variable. This funtion throws exception\u000Awhen called in browser." (. process.env name)) +(define (get-environment-variables) "(get-environment-variables)\u000A\u000AReturns all process environment variables as an alist. This funtion throws exception\u000Awhen called in browser." (if (eq? self window) (throw "get-environment-variables: Node.js only funtion") (object->alist process.env))) +(define (get-environment-variable name) "(get-environment-variable name)\u000A\u000AReturns given environment variable. This funtion throws exception\u000Awhen called in browser." (. process.env name)) (define (current-second) "(current-second)\u000A\u000AFunctionn return exact integer of the seconds since January 1, 1970" (inexact->exact (truncate (/ (+ %%start-jiffy (current-jiffy)) (jiffies-per-second))))) (define %%start-jiffy (truncate (* 1000 (if (eq? self window) performance.timing.navigationStart performance.timeOrigin))) "Constant value that indicates start jiffy of the scheme process.") (define (current-jiffy) "(current-jiffy)\u000A\u000ARetturn corrent jiffy. In LIPS is jiffy since start of the process.\u000AYou can divide this value by (jiffies-per-second) to get seconds since\u000Astart of the process. And you can add %%start-jiffy to get jiffy since\u000AJanuary 1, 1970." (inexact->exact (truncate (* (performance.now) 1000)))) (define (jiffies-per-second) 1000000) -(let* ((fs (cond ((eq? self global) (require "fs")) ((and (not (null? self.BrowserFS)) (indexed-db?)) (new Promise (lambda (resolve reject) (BrowserFS.configure &(:fs "IndexedDB" :options &()) (lambda (e) (if (null? e) (resolve (BrowserFS.BFSRequire "fs")) (reject e))))))) ((not (null? self.BrowserFS)) (console.warn (string-append "BrowserFS not initilalized " "IndexedDB is not available")) ()))) (Buffer (cond ((eq? self global) self.Buffer) ((not (null? self.BrowserFS)) (. (BrowserFS.BFSRequire "buffer") (quote Buffer)))))) (let ((internal (lips.env.get (quote **internal-env**)))) (if (not (null? Buffer)) (internal.set "Buffer" Buffer)) (if (not (null? fs)) (internal.set "fs" fs)))) +(let* ((fs (cond ((eq? self global) (require "fs")) ((and (not (null? self.BrowserFS)) (indexed-db?)) (new Promise (lambda (resolve reject) (BrowserFS.configure &(:fs "IndexedDB" :options &()) (lambda (e) (if (null? e) (resolve (BrowserFS.BFSRequire "fs")) (reject e))))))) ((not (null? self.BrowserFS)) (console.warn (string-append "BrowserFS is not initilalized and " "IndexedDB is not available")) ()))) (Buffer (cond ((eq? self global) self.Buffer) ((not (null? self.BrowserFS)) (. (BrowserFS.BFSRequire "buffer") (quote Buffer)))))) (let ((internal (lips.env.get (quote **internal-env**)))) (if (not (null? Buffer)) (internal.set "Buffer" Buffer)) (if (not (null? fs)) (internal.set "fs" fs)))) diff --git a/dist/std.scm b/dist/std.scm index fa4c270f7..d72a91a82 100644 --- a/dist/std.scm +++ b/dist/std.scm @@ -22,10 +22,10 @@ ;; ----------------------------------------------------------------------------- (define-macro (let-syntax vars . body) - "(let-syntax ((name fn)) body) + "(let-syntax ((name fn) ...) . body) - Macro works like combination of let and define-syntax. It creaates - local macros and evaluate body in context of those macros. + Works like a combination of let and define-syntax. It creates + local macros and evaluates body in context of those macros. The macro to letrec-syntax is like letrec is to let." `(let ,vars ,@(map (lambda (rule) @@ -35,10 +35,10 @@ ;; ----------------------------------------------------------------------------- (define-macro (letrec-syntax vars . body) - "(letrec-syntax ((name fn)) body) + "(letrec-syntax ((name fn) ...) . body) - Macro works like combination of letrec and define-syntax. It creaates - local macros and evaluate body in context of those macros." + Works like a combination of letrec and define-syntax. It creates + local macros and evaluates the body in context of those macros." `(letrec ,vars ,@(map (lambda (rule) `(typecheck "letrec-syntax" ,(car rule) "syntax")) @@ -49,7 +49,7 @@ (define-macro (define-syntax name expr . rest) "(define-syntax name expression [__doc__]) - Macro define new hygienic macro using syntax-rules with optional documentation" + Defines a new hygienic macro using syntax-rules with optional documentation." (let ((expr-name (gensym "expr-name"))) `(define ,name (let ((,expr-name ,expr)) @@ -61,7 +61,7 @@ (define (quoted-symbol? x) "(quoted-symbol? code) - Helper function that test if value is quoted symbol. To be used in macros + Helper function that tests if value is a quoted symbol. To be used in macros that pass literal code that is transformed by parser. usage: @@ -75,7 +75,7 @@ ;; ----------------------------------------------------------------------------- (define-macro (--> expr . body) - "Helper macro that simplify calling methods on objects. It work with chaining + "Helper macro that simplifies calling methods on objects. It works with chaining usage: (--> ($ \"body\") (css \"color\" \"red\") (on \"click\" (lambda () (display \"click\")))) @@ -124,8 +124,8 @@ "(define-global var value) (define-global (name . args) body) - Macro that define functions or variables in global context, so they can be used - inside let and get let variables in closure, Useful for universal macros." + Defines functions or variables in the global context, so they can be used + inside let and get let variables in a closure. Useful for universal macros." (if (pair? first) (let ((name (car first))) `(--> lips.env @@ -159,21 +159,21 @@ (define (single list) "(single list) - Function check if argument is list with single element" + Checks if argument is list with one element." (and (pair? list) (not (cdr list)))) ;; ----------------------------------------------------------------------------- (define (iterator? x) "(iterator? x) - Function check if value is JavaScript iterator object" + Checks if value is JavaScript iterator object." (and (object? x) (procedure? (. x Symbol.iterator)))) ;; ----------------------------------------------------------------------------- (define-macro (.. expr) "(.. foo.bar.baz) - Macro that gets value from nested object where argument is comma separated symbol" + Gets the value from a nested object where the argument is a period separated symbol." (if (not (symbol? expr)) expr (let ((parts (split "." (symbol->string expr)))) @@ -188,14 +188,14 @@ (define (gensym-interal symbol) "(gensym-interal symbol) - Parser extension that create new quoted named gensym." + Parser extension that creates a new quoted named gensym." `(quote ,(gensym symbol))) ;; ----------------------------------------------------------------------------- (define (plain-object? x) "(plain-object? x) - Function check if value is plain JavaScript object. Created using object macro." + Checks if value is a plain JavaScript object created using the object macro." ;; here we don't use string=? or equal? because it may not be defined (and (== (--> (type x) (cmp "object")) 0) (eq? (. x 'constructor) Object))) @@ -205,14 +205,14 @@ (lambda (o) "(typed-array? o) - Function test if argumnet is JavaScript typed array (Scheme byte vector)." + Function that tests if the arguments is a JavaScript typed array (Scheme byte vector)." (instanceof TypedArray o)))) ;; ----------------------------------------------------------------------------- (define (symbol->string s) "(symbol->string symbol) - Function convert LIPS symbol to string." + Function that converts a LIPS symbol to a string." (typecheck "symbol->string" s "symbol") (let ((name s.__name__)) (if (string? name) @@ -223,7 +223,7 @@ (define (string->symbol string) "(string->symbol string) - Function convert string to LIPS symbol." + Function that converts a string to a LIPS symbol." (typecheck "string->symbol" string "string") (%as.data (new lips.LSymbol string))) @@ -231,7 +231,7 @@ (define (alist->object alist) "(alist->object alist) - Function convert alist pairs to JavaScript object." + Function that converts alist pairs to a JavaScript object." (if (pair? alist) (alist.to_object) (alist->object (new lips.Pair undefined nil)))) @@ -240,7 +240,7 @@ (define (object->alist object) "(object->alist object) - Function convert JavaScript object to Alist" + Function that converts a JavaScript object to Alist" (typecheck "object->alist" object "object") (vector->list (--> (Object.entries object) (map (lambda (arr) @@ -250,7 +250,7 @@ (define (parent.frames) "(parent.frames) - Funcion return list of environments from parent frames (lambda function calls)" + Returns the list of environments from parent frames (lambda function calls)" (let iter ((result '()) (frame (parent.frame 1))) (if (eq? frame (interaction-environment)) (cons frame result) @@ -265,8 +265,8 @@ (define (pair-map fn seq-list) "(pair-map fn list) - Function call fn argument for pairs in a list and return combined list with - values returned from function fn. It work like the map but take two items from list" + Function that calls fn argument for pairs in a list and returns a combined list with + values returned from function fn. It works likes map but take two items from the list each time." (let iter ((seq-list seq-list) (result '())) (if (null? seq-list) result @@ -281,12 +281,12 @@ ;; ----------------------------------------------------------------------------- (define (object-expander readonly expr . rest) - "(object-expander reaonly '(:foo (:bar 10) (:baz (1 2 3)))) - (object-expander reaonly '(:foo :bar)) + "(object-expander readonly '(:foo (:bar 10) (:baz (1 2 3)))) + (object-expander readonly '(:foo :bar)) - Recursive function helper for defining LIPS code for create objects - using key like syntax. if no values are used it will create JavaScript - shorthand objects where keys are used for keys and values" + Recursive function helper for defining LIPS code to create objects + using key like syntax. If no values are used it will create a JavaScript + shorthand objects where keys are used for keys and the values." (let ((name (gensym "name")) (r-only (gensym "r-only")) (quot (if (null? rest) false (car rest)))) @@ -334,7 +334,7 @@ (define-macro (object . expr) "(object :name value) - Macro that create JavaScript object using key like syntax." + Creates a JavaScript object using key like syntax." (try (object-expander false expr) (catch (e) @@ -347,8 +347,8 @@ (define-macro (object-literal . expr) "(object-literal :name value) - Macro that create JavaScript object using key like syntax. This is similar, - to object but all values are quoted. This macro is used with & object literal." + Creates a JavaScript object using key like syntax. This is similar, + to object but all values are quoted. This macro is used by the & object literal." (try (object-expander true expr true) (catch (e) @@ -361,7 +361,7 @@ (define (alist->assign desc . sources) "(alist->assign alist . list-of-alists) - Function that work like Object.assign but for LIPS alist." + Function that works like Object.assign but for LIPS alists." (for-each (lambda (source) (for-each (lambda (pair) (let* ((key (car pair)) @@ -378,7 +378,7 @@ (define (key? symbol) "(key? symbol) - Function check if symbol is key symbol, have colon as first character." + Checks if symbol is a keyword (has a colon as first character)." ;; we can't use string=? because it's in R5RS.scm we use same code that use cmp (and (symbol? symbol) (== (--> (substring (symbol->string symbol) 0 1) (cmp ":")) 0))) @@ -386,7 +386,7 @@ (define (key->string symbol) "(key->string symbol) - If symbol is key it convert that to string - remove colon." + If symbol is a keyword it converts that to string and removes the colon." (if (key? symbol) (substring (symbol->string symbol) 1))) @@ -394,7 +394,7 @@ (define (%as.data obj) "(%as.data obj) - Mark object as data to stop evaluation." + Marks the object as data to stop evaluation." (if (object? obj) (begin (set-obj! obj 'data true) @@ -404,8 +404,8 @@ (define (%hidden-props obj) "(%hidden-props obj) - Function return hidden names of an object, for ES6 class prototype - it return all methods since they are indistinguishable from hidden property + Returns the hidden names of an object, for ES6 class prototypes + it returns all methods since they are indistinguishable from hidden properties created using defineProperty." (let* ((descriptors (Object.getOwnPropertyDescriptors obj)) (names (Object.keys descriptors))) @@ -417,7 +417,7 @@ (define (dir obj . rest) "(dir obj) - Function return all props on the object including those in prototype chain." + Returns all props on the object including those in prototype chain." (if (or (null? obj) (eq? obj Object.prototype)) nil (let ((proto (if (null? rest) false (car rest))) @@ -434,7 +434,7 @@ (define (tree-map f tree) "(tree-map fn tree) - Tree version of map. Function is invoked on every leaf." + Tree version of map. fn is invoked on every leaf." (if (pair? tree) (cons (tree-map f (car tree)) (tree-map f (cdr tree))) (f tree))) @@ -443,7 +443,7 @@ (define (native.number x) "(native.number obj) - If argument is number it will convert to native number." + If argument is a number it will convert it to a native number." (if (number? x) (value x) x)) @@ -452,7 +452,7 @@ (define (value obj) "(value obj) - Function unwrap LNumbers and convert nil value to undefined." + Function that unwraps LNumbers and converts nil to undefined." (if (eq? obj nil) undefined (if (number? obj) @@ -463,7 +463,7 @@ (define-macro (define-formatter-rule . patterns) "(rule-pattern pattern) - Anaphoric Macro for defining patterns for formatter. With Ahead, Pattern and * defined values." + Anaphoric macro for defining patterns for the formatter. With Ahead, Pattern and * defined values." (let ((rules (gensym "rules"))) `(let ((,rules lips.Formatter.rules) (Ahead (lambda (pattern) @@ -578,7 +578,7 @@ (define (%r re . rest) "(%r re) - Create new regular expression from string, to not break Emacs formatting" + Creates a new regular expression from string, to not break Emacs formatting." (if (null? rest) (new RegExp re) (new RegExp re (car rest)))) @@ -596,7 +596,7 @@ (define (interaction-environment) "(interaction-environment) - Function return interaction environement equal to lips.env can be overwritten, + Returns the interaction environement equal to lips.env. This can be overwritten when creating new interpreter with lips.Interpreter." **interaction-environment**) @@ -604,7 +604,7 @@ (define (current-output-port) "(current-output-port) - Function return default stdout port." + Returns the default stdout port." (let-env (interaction-environment) (--> **internal-env** (get 'stdout)))) @@ -612,7 +612,7 @@ (define (current-error-port) "(current-output-port) - Function return default stdout port." + Returns the default stderr port." (let-env (interaction-environment) (--> **internal-env** (get 'stderr)))) @@ -620,7 +620,7 @@ (define (current-input-port) "(current-input-port) - Function return default stdin port." + Returns the default stdin port." (let-env (interaction-environment) (--> **internal-env** (get 'stdin)))) @@ -628,7 +628,7 @@ (define (command-line) "(command-line) - Function return command line arguments or empty list" + Returns the command line arguments, or an empty list if not running under Node.js." (let ((args (let-env (interaction-environment) (--> **internal-env** (get 'command-line))))) (if (or (null? args) (zero? (length args))) @@ -637,7 +637,7 @@ ;; ----------------------------------------------------------------------------- (define (flush-output . rest) - "(flush-output) + "(flush-output [port]) If output-port is buffered, this causes the contents of its buffer to be written to the output device. Otherwise it has no effect. Returns an unspecified value." @@ -649,18 +649,18 @@ (define (regex? x) "(regex? x) - Function return true of value is regular expression, it return false otherwise." + Returns true if value is a regular expression, or false otherwise." (== (--> (type x) (cmp "regex")) 0)) ;; ----------------------------------------------------------------------------- (define (set-repr! type fn) "(add-repr! type fn) - Function add string represention to the type, which should be constructor function. + Function that adds the string represention to the type, which should be a constructor function. - Function fn should have args (obj q) and it should return string, obj is vlaue that - need to be converted to string, if the object is nested and you need to use `repr`, - it should pass second parameter q to repr, so string will be quoted when it's true. + Function fn should have args (obj q) and it should return a string. obj is the value that + need to be converted to a string. If the object is nested and you need to use `repr` recursively, + it should pass the second parameter q to repr, so string will be quoted when it's true. e.g.: (lambda (obj q) (string-append \"<\" (repr obj q) \">\"))" (typecheck "add-repr!" type "function") @@ -671,7 +671,7 @@ (define (unset-repr! type) "(unset-repr! type) - Function remove string represention to the type, which should be constructor function, + Removes the string represention of the type, which should be constructor function, added by add-repr! function." (typecheck "unset-repr!" type "function") (ignore (--> lips.repr (delete type)))) @@ -696,7 +696,7 @@ (define (bound? x . rest) "(bound? x [env]) - Function check if variable is defined in given environement or interaction environment + Function that check if the variable is defined in the given environement, or interaction-environment if not specified." (let ((env (if (null? rest) (interaction-environment) (car rest)))) (try (begin @@ -709,7 +709,7 @@ (define (environment-bound? env x) "(environment-bound? env symbol) - Function check if symbol is bound variable similar to bound?." + Checks if symbol is a bound variable similar to bound?." (typecheck "environment-bound?" env "environment" 1) (typecheck "environment-bound?" x "symbol" 2) (bound? x env)) @@ -720,7 +720,7 @@ (define (qsort e predicate) "(qsort list predicate) - Sort the list using quick sort alorithm according to predicate." + Sorts the list using the quick sort alorithm according to predicate." (if (or (null? e) (<= (length e) 1)) e (let loop ((left nil) (right nil) @@ -735,7 +735,7 @@ (define (sort list . rest) "(sort list [predicate]) - Sort the list using optional predicate function. if not function is specified + Sorts the list using optional predicate function. If no comparison function is given it will use <= and sort in increasing order." (let ((predicate (if (null? rest) <= (car rest)))) (typecheck "sort" list "pair") @@ -746,8 +746,9 @@ (define (every fn list) "(every fn list) - Function call function fn on each item of the list, if every value is true - it will return true otherwise it return false." + Function that calls fn on each item of the list, if every value returns true + it will return true otherwise it return false. + Analagous to Python all(map(fn, list))." (if (null? list) true (and (fn (car list)) (every fn (cdr list))))) @@ -756,7 +757,7 @@ (define-macro (promise . body) "(promise . body) - Anaphoric macro that expose resolve and reject functions from JS promise" + Anaphoric macro that exposes resolve and reject functions from JS promise." `(new Promise (lambda (resolve reject) (try (begin ,@body) (catch (e) @@ -766,22 +767,22 @@ (define-macro (timer time . body) "(timer time . body) - Macro evaluate expression after delay, it return timer. To clear the timer you can use - native JS clearTimeout function." + Evaluates body after delay, it returns the timer ID from setTimeout. + To clear the timer you can use native JS clearTimeout function." `(setTimeout (lambda () (try (begin ,@body) (catch (e) (error (.. e.message))))) ,time)) ;; ----------------------------------------------------------------------------- (define-macro (wait time . expr) "(wait time . expr) - Function return promise that will resolve with evaluating the expression after delay." + Returns a promise that will resolve with the expression after delay." `(promise (timer ,time (resolve (begin ,@expr))))) ;; ----------------------------------------------------------------------------- (define (await value) "(await value) - Function unquote quoted promise so it can be automagicaly evaluated (resolved + Unquotes a quoted promise so it can be automagicaly evaluated (resolved to its value)." (if (instanceof lips.QuotedPromise value) (value.valueOf) @@ -789,12 +790,11 @@ ;; ----------------------------------------------------------------------------- (define-macro (quote-promise expr) - "(quote-promise expr) - '>expr + "(quote-promise expr) or '>expr - Macro used to escape promise the whole expression, will be wrapped - with JavaScript class that behave like Promise but will not - auto resolve like normal promise." + Macro used to escape automati awaiting of the expression. It will be wrapped + with a JavaScript class that behaves like Promise but will not be automatically + resolved by LIPS like normal promises are." `(let ((env)) (set! env (current-environment)) (env.set (Symbol.for "__promise__") true) @@ -804,14 +804,14 @@ (define (defmacro? obj) "(defmacro? expression) - Function check if object is macro and it's expandable." + Checks if object is a macro and it's expandable." (and (macro? obj) (. obj 'defmacro))) ;; ----------------------------------------------------------------------------- (define (n-ary n fn) "(n-ary n fn) - Return new function that limit number of arguments to n." + Returns a new function that limits the number of arguments to n." (lambda args (apply fn (take n args)))) @@ -819,7 +819,7 @@ (define (take n lst) "(take n list) - Return n first values of the list." + Returns n first values of the list." (let iter ((result '()) (i n) (lst lst)) (if (or (null? lst) (<= i 0)) (reverse result) @@ -828,13 +828,13 @@ ;; ----------------------------------------------------------------------------- (define unary (%doc "(unary fn) - Function return new function with arguments limited to one." + Returns a new function with arguments limited to one." (curry n-ary 1))) ;; ----------------------------------------------------------------------------- (define binary (%doc "(binary fn) - Function return new function with arguments limited to two." + Returns a new function with arguments limited to two." (curry n-ary 2))) ;; ----------------------------------------------------------------------------- @@ -844,7 +844,7 @@ (define (%class-lambda expr) "(class-lambda expr) - Return lambda expression where input expression lambda have `this` as first argument." + Returns a lambda expression where input expression lambda have `this` as first argument." (let ((args (gensym 'args))) `(lambda ,args (apply ,(cadr expr) this ,args)))) @@ -853,7 +853,7 @@ (define (%class-method-name expr) "(%class-method-name expr) - Helper function that allow to use [Symbol.asyncIterator] inside method name." + Helper function that allows to use [Symbol.asyncIterator] inside method name." (if (pair? expr) (car expr) (list 'quote expr))) @@ -862,7 +862,7 @@ (define-macro (define-class name parent . body) "(define-class name parent . body) - Define class - JavaScript function constructor with prototype. + Defines a class - JavaScript function constructor with prototype. usage: @@ -870,10 +870,10 @@ (constructor (lambda (self name) (set-obj! self '_name name))) (hi (lambda (self) - (display (string-append self._name \" say hi\")) + (display (string-append self._name \" says hi\")) (newline)))) (define jack (new Person \"Jack\")) - (jack.hi)" + (jack.hi) ; prints \"Jack says hi\"" (let iter ((functions '()) (constructor '()) (lst body)) (if (null? lst) `(begin @@ -911,13 +911,13 @@ temp))) "(class <parent> body ...) - Macro allow to create anonymous classes. See define-class for details.") + Allows to create anonymous classes. See define-class for details.") ;; ----------------------------------------------------------------------------- (define (make-tags expr) "(make-tags expression) - Function that return list structure of code with better syntax then raw LIPS" + Returns a list structure of code with better syntax then raw LIPS" `(h ,(let ((val (car expr))) (if (key? val) (key->string val) val)) (alist->object (,'quasiquote ,(pair-map (lambda (car cdr) `(,(key->string car) . (,'unquote ,cdr))) @@ -932,7 +932,7 @@ (define (%sxml h expr) "(%sxml h expr) - Helper function that render expression using create element function." + Helper function that renders the expression using create element function." (let* ((have-attrs (and (not (null? (cdr expr))) (pair? (cadr expr)) (eq? (caadr expr) '@))) @@ -974,10 +974,9 @@ ;; ----------------------------------------------------------------------------- (define (sxml-unquote) - "(sxml-unquote expression) - ~expression + "(sxml-unquote expression) or ~expression - Thread expression as code and evaluate it inside sxml, similar to unquote + Treat expression as code and evaluate it inside sxml, similar to unquote with quasiquote." (throw "sxml-unquote: Can't use outside of sxml")) @@ -992,7 +991,8 @@ (sxml (div (@ (data-foo \"hello\") (id \"foo\")) (span \"hello\") - (span \"world\")))" + (span \"world\"))) + ;; ==> <div data-foo=\"hello\" id=\"foo\"><span>hello</span><span>world</span></div>" (%sxml ',pragma expr))) ;; ----------------------------------------------------------------------------- @@ -1002,7 +1002,7 @@ (define-macro (with-tags expr) "(with-tags expression) - Macro that evalute LIPS shorter code for S-Expression equivalent of JSX. + valutes LIPS shorter code for S-Expression equivalent of JSX. e.g.: (with-tags (:div (:class \"item\" :id \"item-1\") @@ -1018,8 +1018,8 @@ (define (get-resource url) "(get-resource url) - Load JavaScript or CSS file in browser by adding script tag to head of the current document. - When called from Node it allow it allow to load JavaScript files only." + Load JavaScript or CSS file in browser by adding script/link tag to head of the current document. + When called from Node it allow it allows to load JavaScript files only." (typecheck "get-resource" url "string") (if (not (bound? 'document)) (if (eq? self global) @@ -1050,21 +1050,21 @@ (define (gensym? value) "(gensym? value) - Function return #t if value is symbol and it's gensym. It returns #f otherwise." + Returns #t if value is a symbol created by gensym. It returns #f otherwise." (and (symbol? value) (--> value (is_gensym)))) ;; ----------------------------------------------------------------------------- (define (degree->radians x) "(degree->radians x) - Convert degree to radians." + Convert degrees to radians." (* x (/ Math.PI 180))) ;; ----------------------------------------------------------------------------- (define (radians->degree x) "(radians->degree x) - Convert radians to degree." + Convert radians to degrees." (* x (/ 180 Math.PI))) ;; ----------------------------------------------------------------------------- @@ -1076,7 +1076,7 @@ body ...))) "(while cond . body) - Macro that create a loop, it exectue body until cond expression is false.") + Creates a loop, it executes cond and body until cond expression is false.") ;; ----------------------------------------------------------------------------- (define-syntax ++ @@ -1087,7 +1087,7 @@ tmp))) "(++ variable) - Macro that work only on variables and increment the value by one.") + Works only on variables and increment the value by one.") ;; ----------------------------------------------------------------------------- (define-syntax -- @@ -1098,13 +1098,13 @@ tmp))) "(-- variable) - Macro that decrement the value it work only on symbols") + Works only on variables and decrements the value by one.") ;; ----------------------------------------------------------------------------- (define (pretty-format . lists) "(pretty-format pair) - Function return pretty printed string from pair expression." + Returns a pretty printed string from pair expression." (let ((code (--> (list->vector lists) (map (lambda (pair i) (typecheck "pretty-pair" pair "pair" i) @@ -1116,7 +1116,7 @@ (define (reset) "(reset) - Function reset environment and remove all user defined variables." + Function resets the environment and removes all user defined variables." (let-env **interaction-environment** (let ((defaults **interaction-environment-defaults**) (env **interaction-environment**)) @@ -1137,9 +1137,9 @@ (range start stop) (range start stop step) - Function returns list of numbers from start to stop with optonal step. + Returns a list of numbers from start to stop with optional step. If start is not defined it starts from 0. If start is larger than stop - the step need to be negative." + the step needs to be negative otherwise it will hang in an infinite loop." (let* ((i (if (null? rest) 0 stop)) (stop (if (null? rest) stop (car rest))) (step (if (or (null? rest) (null? (cdr rest))) @@ -1164,10 +1164,10 @@ (define-macro (do-iterator spec cond . body) "(do-iterator (var expr) (test) body ...) - Macro iterate over iterators (e.g. create with JavaScript generator function) - it works with normal and async iterators. You can loop over infinite iterators - and break the loop if you want, using expression like in do macro, long sync iterators - will block main thread (you can't print 1000 numbers from inf iterators, + Iterates over iterators (e.g. creates with JavaScript generator function) + that works with normal and async iterators. You can loop over infinite iterators + and break the loop if you want, using expression like in do macro. Long synchronous iterators + will block the main thread (you can't print 1000 numbers from infinite iterators, because it will freeze the browser), but if you use async iterators you can process the values as they are generated." (let ((gen (gensym "name")) @@ -1207,7 +1207,7 @@ (define (native-symbol? x) "(native-symbol? object) - Function check if value is JavaScript symbol." + Checks if value is JavaScript Symbol." (and (string=? (type x) "symbol") (not (symbol? x)))) ;; ----------------------------------------------------------------------------- @@ -1217,17 +1217,17 @@ (define-macro (warn-quote) "(warn-quote) - Simple macro that throw error, when you try to use ’ symbol as quote in code" - (throw (new Error (string-append "You're using invalid quote character run: " + Simple macro that throws an error, when you try to use ’ symbol as quote in code." + (throw (new Error (string-append "You're using an invalid Unicode quote character. Run: " "(set-special! \"’\" 'quote)" - " to allow running this type of quote")))) + " to allow the use of this type of quote")))) ;; ----------------------------------------------------------------------------- (define-macro (let-env-values env spec . body) "(let-env-values env ((name var)) . body) - Macro add mapping for variables var from specified env, - Macro work similar to let-env but lexical scope is working with it." + Adds mappings for variables var from specified env. + it is similar to let-env but lexical scope is working with it." (let ((env-name (gensym 'env))) `(let ((,env-name ,env)) (let ,(map (lambda (pair) @@ -1239,7 +1239,7 @@ (define (apropos name) "(apropos name) - Search environment and display names that match the given name. + Search the current environment and display names that match the given name. name can be regex, string or symbol." (typecheck "apropos" name '("string" "regex" "symbol")) (let ((regex (lambda (string) @@ -1253,7 +1253,7 @@ (define (promisify fn) "(promisify fn) - Simple function for adding promises to NodeJS callback based function. + Simple function for adding promises to NodeJS two-callback based functions. Function tested only with fs module." (lambda args (new Promise (lambda (resolve reject) @@ -1266,7 +1266,7 @@ (define-macro (list* . args) "(list* arg1 ...) - Parallel version of list." + Parallel asynchronous version of list. Like begin* except all values are returned in a list." (let ((result (gensym "result"))) `(let ((,result (vector))) ,@(map (lambda (arg) @@ -1276,9 +1276,9 @@ ;; ----------------------------------------------------------------------------- (define-macro (%not-implemented name) - "(not-implemented name) + "(%not-implemented name) - Returns new function taht throw exception that function is not implmeneted" + Returns new function that throws an exception with a message that this function is not implmeneted." (let ((str-name (symbol->string name))) `(lambda () ,(string-append "(" str-name ")\n\nThis function is not yet implemented.") @@ -1288,8 +1288,8 @@ (define-macro (%make-env name . names) "(%make-env name f1 f2 ...) - Create new Environment with given name and defined symbols in it from global env. - If given function name f1 f2 ... don't exists, it will define function that + Creates a new Environment with given name and defined symbols in it from the global env. + If given function name f1 f2 ... don't exist, it will define them as functions that throw exception that function is not yet implemented." `(new lips.Environment (alist->object (list ,@(map (lambda (name) `(cons ',name ,(let ((ref (lips.env.ref name))) @@ -1321,7 +1321,7 @@ (define (indexed-db?) "(indexed-db?) - Function test if indexedDB is available." + Function that tests if IndexedDB is available." (let* ((any (lambda args (let iter ((args args)) (if (null? args) @@ -1337,7 +1337,7 @@ (try (begin ;; open will fail in about:blank - (window.indexedDB.open "MyTestDatabase" 3) + (window.indexedDB.open "IndexedDBExistenceCheck" 3) true) (catch (e) false)) @@ -1347,7 +1347,7 @@ (define (environment? obj) "(environment? obj) - Function check if object is LIPS environment." + Checks if object is a LIPS environment." (instanceof lips.Environment obj)) ;; ----------------------------------------------------------------------------- @@ -1356,13 +1356,13 @@ (lambda (binary path) "(%read-file binary path) - Read file from url or file system. If binary is false it will return - string that contain all the content. For HTTP requests, If binary - is false it will: when in browser return ArrayBuffer and in Node - it will return Buffer object. When reading from file system - in both cases it will return Buffer objects. + Read file from url or file system. If binary is false it will return a + string that contain all the content. For HTTP requests, if binary + is false it will return an ArrayBuffer (when in a browser) or a Buffer + (when in NodeJS). When reading from the file system in both cases it will + return Buffer objects. - The code that use those function, in binary mode, need to check + Code that uses this function in binary mode needs to check if the result is ArrayBuffer or Node.js/BrowserFS Buffer object." (if (not read-file) (let ((fs (--> (interaction-environment) @@ -1404,7 +1404,7 @@ (define (%fs-promisify-proc fn message) "(%fs-promisify-proc fn string) - Function return promisified version of fs function or throw exception + Returns a promisified version of a fs function or throws an exception if fs is not available." (let ((fs (--> lips.env (get '**internal-env**) (get 'fs)))) (if (null? fs) @@ -1415,11 +1415,11 @@ (define (response->content binary res) "(response->text binary res) - Function read all text from Node.js HTTP response object. If binary argument + Reads all text from a Node.js HTTP response object. If binary argument is true it will return Buffer object that can be converted to u8vector. - ***Warrning:*** it may overflow the stack (part of Node) when converting - whole buffer to u8vector." + ***Warrning:*** it may overflow the Javascript call stack when converting the + whole buffer to u8vector, because LIPS doesn't have TCO." (let ((result (vector)) (append (if binary (lambda (chunk) @@ -1444,15 +1444,14 @@ (lambda (url binary) "(http-get url) - Node.js Function that send HTTP Request and return string or - binary Buffer object." + This function is only available when running LIPS in NodeJS." (throw (new Error "http-get: function is Node.js only."))) (let* ((http (. (require "http") 'get)) (https (. (require "https") 'get))) (lambda (url binary) "(http-get url) - Node.js Function that send HTTP Request and return string or + Node.js function that sends a HTTP Request and returns a string or binary Buffer object." (let ((request (if (null? (url.match #/^https/)) http https))) (new Promise @@ -1472,8 +1471,8 @@ (define (buffer->u8vector bin) "(buffer->u8vector bin) - Cross platform function that can be used in both Node and Browser. - It can be used together with %read-file or %read-binary-file and convert + Cross platform function that can be used in both Node and browser. + It can be used together with %read-file or %read-binary-file to convert the result ArrayBuffer or Buffer to u8vector." (if (instanceof ArrayBuffer bin) (new Uint8Array bin) @@ -1483,7 +1482,7 @@ (define (complement fn) "(complement fn) - Higer order function that returns complement of the given function. If the function fn + Higer order function that returns the Boolean complement of the given function. If the function fn for a given arguments return true the result function will return false, if it would return false, the result function will return true." (typecheck "complement" fn "function") @@ -1494,7 +1493,7 @@ (define (always constant) "(always constant) - Higher order function returns new function that always return given constant." + Higher-order function that returns a new thunk that always returns the given constant when called." (lambda () constant)) @@ -1502,8 +1501,9 @@ (define (once fn) "(once fn) - Higher order function that return new function, that is guarantee - to be called only once." + Higher-order function that returns a new function, that only calls the original + on the first invocation, and immediately returns the first call's result again + on subsequent invocations." (typecheck "once" fn "function") (let ((result)) (lambda args @@ -1515,7 +1515,7 @@ (define (flip fn) "(flip fn) - Higher order function that return new function where first two arguments are swapped. + Higher-order function that returns a new function where the first two arguments are swapped. Example: @@ -1530,9 +1530,9 @@ (define (unfold fn init) "(unfold fn init) - Function returns list from given function and init value. The function should - return cons where first is the item added to the list and second is next value - passed to the funtion. If function return false it end the loop." + Returns a list from the given function and init value. The function should + return a pair where first is the item added to the list and second is next value + passed to the funtion. If the function returns false it ends the loop." (typecheck "unfold" fn "function") (let iter ((pair (fn init)) (result '())) (if (not pair) @@ -1547,14 +1547,14 @@ (define (symbol-append . rest) "(symbol-append s1 s2 ...) - Function create new symbol from symbols passed as arguments." + Function that creates a new symbol from symbols passed as arguments." (string->symbol (apply string-append (map symbol->string rest)))) ;; ----------------------------------------------------------------------------- (define-macro (set-global! name) "(set-global! name) - Macro make the name global variable." + Macro to make the name a Javascript global variable (i.e. accessible on globalThis)." (let ((var (symbol-append 'self. name))) `(set! ,var ,name))) @@ -1599,9 +1599,9 @@ (define-macro (define-symbol-macro type spec . rest) "(define-symbol-macro type (name . args) . body) - Macro that creates special symbol macro for evaluator similar to build in , or `. - It's like alias for real macro. Similar to CL reader macros but it receives already - parsed code like normal macros. Type can be SPLICE or LITERAL symbols. + Creates special symbol macros for evaluator similar to built-in , or `. + It's like an alias for a real macro. Similar to CL reader macros but it receives already + parsed code like normal macros. Type can be SPLICE or LITERAL symbols (see set-special!). ALL default symbol macros are literal." (let* ((name (car spec)) (symbol (cadr spec)) @@ -1630,12 +1630,11 @@ (define-syntax vector (syntax-rules () ((_ arg ...) (list->array (list arg ...)))) - "(vector 1 2 3 (+ 3 1)) - #(1 2 3 4) + "(vector 1 2 3 (+ 3 1)) or #(1 2 3 4) - Macro for defining vectors (JavaScript arrays). Vector literals are - automatically quoted. So you can use expressions inside them. Only other - literals, like other vectors or object.") + Macro for defining vectors (Javascript Arrays). Vector literals are + automatically quoted, so you can't use expressions inside them, only other + literals, like other vectors or objects.") ;; ----------------------------------------------------------------------------- (set-repr! Array @@ -1654,8 +1653,8 @@ (define (eqv? a b) "(eqv? a b) - Function compare the values. It return true if they are the same, they - need to have same type" + Function that compares the values. It returns true if they are the same, they + need to have the same type." (if (string=? (type a) (type b)) (cond ((number? a) (or (and (exact? a) (exact? b) (= a b)) @@ -1740,7 +1739,7 @@ (lambda (proc) "(make-promise fn) - Function create promise from a function." + Function that creates a promise from a function." (typecheck "make-promise" proc "function") (let ((result-ready? #f) (result #f)) @@ -1767,28 +1766,28 @@ (define-macro (delay expression) "(delay expression) - Macro will create a promise from expression that can be forced with (force)." + Will create a promise from expression that can be forced with (force)." `(make-promise (lambda () ,expression))) ;; ----------------------------------------------------------------------------- (define (force promise) "(force promise) - Function forces the promise and evaluates the delayed expression." + Function that forces the promise and evaluates the delayed expression." (promise)) ;; ----------------------------------------------------------------------------- (define (promise? obj) "(promise? obj) - Function checks if value is a promise created with delay or make-promise." + Checks if the value is a promise created with delay or make-promise." (string=? (type obj) "promise")) ;; ----------------------------------------------------------------------------- (define (positive? x) "(positive? x) - Function checks if number is larger then 0" + Checks if the number is larger then 0" (typecheck "positive?" x "number") (> x 0)) @@ -1796,7 +1795,7 @@ (define (negative? x) "(negative? x) - Function checks if number is smaller then 0" + Checks if the number is smaller then 0" (typecheck "negative?" x "number") (< x 0)) @@ -1804,7 +1803,7 @@ (define (zero? x) "(zero? x) - Function checks if number is equal to 0" + Checks if the number is equal to 0" (typecheck "zero?" x "number") (= x 0)) @@ -1828,7 +1827,7 @@ (define (number->string x . rest) "(number->string x [radix]) - Function converts number to string with optional radix (number base)." + Function that converts number to string with optional radix (number base)." (typecheck "number->string" x "number" 1) (let ((radix (if (null? rest) 10 (car rest)))) (typecheck "number->string" radix "number" 2) @@ -1838,14 +1837,14 @@ (define (boolean? x) "(boolean? x) - Function return true if value is boolean." + Returns true if value is boolean." (string=? (type x) "boolean")) ;; ----------------------------------------------------------------------------- (define (vector-ref vector i) "(vector-ref vector i) - Return i element from vector." + Return i-th element from vector." (typecheck "number->string" vector "array" 1) (typecheck "number->string" i "number" 2) (. vector i)) @@ -1854,7 +1853,7 @@ (define (vector-set! vector i obj) "(vector-set! vector i obj) - Set obj as value in vector at position 1." + Set obj as value in vector at position i." (typecheck "vector-set!" vector "array" 1) (typecheck "vector-set!" i "number" 2) (set-obj! vector i obj)) @@ -1875,7 +1874,7 @@ (define (real? x) "(real? x) - Function checks if argument x is real." + Checks if the argument x is real." (and (number? x) (or (eq? x NaN) (eq? x Number.NEGATIVE_INFINITY) (eq? x Number.POSITIVE_INFINITY) @@ -1888,7 +1887,7 @@ (define (integer? x) "(integer? x) - Function checks if argument x is integer." + Checks if the argument x is integer." (and (number? x) (not (eq? x NaN)) (not (eq? x Number.NEGATIVE_INFINITY)) @@ -1901,7 +1900,7 @@ (define (complex? x) "(complex? x) - Function check if argument x is complex." + Checks if argument x is complex." (and (number? x) (or (eq? x NaN) (eq? x Number.NEGATIVE_INFINITY) (eq? x Number.POSITIVE_INFINITY) @@ -1911,7 +1910,7 @@ (define (rational? x) "(rational? x) - Function checks if value is rational." + Checks if the value is rational." (and (number? x) (not (eq? x NaN)) (not (eq? x Number.NEGATIVE_INFINITY)) @@ -1922,7 +1921,7 @@ (define (typecheck-args _type name _list) "(typecheck-args args type) - Function checks if all items in the array are of same type." + Function that makes sure that all items in the array are of same type." (let iter ((n 1) (_list _list)) (if (pair? _list) (begin @@ -1936,7 +1935,7 @@ (define (max . args) "(max n1 n2 ...) - Return maximum of it's arguments." + Returns the maximum of its arguments." (numbers? "max" args) (apply Math.max args)) @@ -1944,7 +1943,7 @@ (define (min . args) "(min n1 n2 ...) - Return minimum of it's arguments." + Returns the minimum of its arguments." (numbers? "min" args) (apply Math.min args)) @@ -1952,7 +1951,7 @@ (define (make-rectangular re im) "(make-rectangular im re) - Create complex number from imaginary and real part." + Creates a complex number from imaginary and real part (a+bi form)." (let ((value `((re . ,re) (im . ,im)))) (lips.LComplex (--> value (to_object true))))) @@ -1990,7 +1989,7 @@ (define (inexact->exact n) "(inexact->exact number) - Function converts real number to exact rational number." + Function that converts real number to exact rational number." (typecheck "inexact->exact" n "number") (if (exact? n) n @@ -2000,7 +1999,7 @@ (define (log z) "(log z) - Function calculates natural logarithm of z where the argument can be + Function that calculates natural logarithm of z where the argument can be any number (including complex negative and rational). If the value is 0 it return NaN." (cond ((real? z) @@ -2031,7 +2030,7 @@ (op (. Math name)) (fn (lambda (n) (lips.LNumber (op n))))) (--> _this_env (set name fn)) - (set-obj! fn '__doc__ (concat "(" name " n)\n\nFunction calculate " name + (set-obj! fn '__doc__ (concat "(" name " n)\n\nFunction that calculates " name " math operation (it call JavaScript Math." name " function)")) (iter (cdr fns))))) @@ -2040,7 +2039,7 @@ (define (sin n) "(sin n) - Function calculate sine of a number." + Function that calculates sine of a number." (typecheck "sin" n "number") (if (string=? n.__type__ "complex") (let ((re (real-part n)) @@ -2055,7 +2054,7 @@ (define (cos n) "(cos n) - Function calculate cosine of a number." + Function that calculates cosine of a number." (typecheck "cos" n "number") (if (string=? n.__type__ "complex") (let ((re (real-part n)) @@ -2070,7 +2069,7 @@ (define (tan n) "(tan n) - Function calculate tanent of a number." + Function that calculates tangent of a number." (typecheck "tan" n "number") (if (string=? n.__type__ "complex") (let* ((re (real-part n)) @@ -2089,7 +2088,7 @@ (define (exp n) "(exp n) - Function calculate e rised to the power of n." + Function that calculates e raised to the power of n." (typecheck "exp" n "number") (if (string=? n.__type__ "complex") (let* ((re (real-part n)) @@ -2103,7 +2102,7 @@ (define (modulo a b) "(modulo a b) - Function returns modulo operation on it's argumennts." + Returns modulo operation on its argumennts." (typecheck "modulo" a "number" 1) (typecheck "modulo" b "number" 2) (- a (* b (floor (/ a b))))) @@ -2111,7 +2110,7 @@ (define (remainder__ a b) "(modulo a b) - Function returns reminder from division operation." + Returns remainder from division operation." (typecheck "remainder" a "number" 1) (typecheck "remainder" b "number" 2) (- a (* b (truncate (/ a b))))) @@ -2136,7 +2135,7 @@ (define (list-ref l k) "(list-ref list n) - Returns n element of a list." + Returns n-th element of a list." (typecheck "list-ref" l '("pair" "nil")) (if (< k 0) (throw (new Error "list-ref: index out of range")) @@ -2154,36 +2153,36 @@ (define (not x) "(not x) - Function return true if value is false and false otherwise." + Returns true if value is false and false otherwise." (if x false true)) ;; ----------------------------------------------------------------------------- (define (rationalize number tolerance) "(rationalize number tolerance) - Function returns simplest rational number differing from number by no more + Returns simplest rational number approximation differing from number by no more than the tolerance." (typecheck "rationalize" number "number" 1) (typecheck "rationalize" tolerance "number" 2) (lips.rationalize number tolerance)) ;; ----------------------------------------------------------------------------- -(define (%mem/search access op obj list) +(define (%mem/search acces op obj list) "(%member obj list function) Helper method to get first list where car equal to obj using provied functions as comparator." (if (null? list) false - (if (op (access list) obj) + (if (op (acces list) obj) list - (%mem/search access op obj (cdr list))))) + (%mem/search acces op obj (cdr list))))) ;; ----------------------------------------------------------------------------- (define (memq obj list) "(memq obj list) - Function return first object in the list that match using eq? function." + Returns first object in the list that match using eq? function." (typecheck "memq" list '("nil" "pair")) (%mem/search car eq? obj list )) @@ -2191,7 +2190,7 @@ (define (memv obj list) "(memv obj list) - Function return first object in the list that match using eqv? function." + Returns first object in the list that match using eqv? function." (typecheck "memv" list '("nil" "pair")) (%mem/search car eqv? obj list)) @@ -2199,7 +2198,7 @@ (define (member obj list) "(member obj list) - Function returns first object in the list that match using equal? function." + Returns first object in the list that match using equal? function." (typecheck "member" list '("nil" "pair")) (%mem/search car equal? obj list)) @@ -2207,7 +2206,7 @@ (define (%assoc/acessor name) "(%assoc/acessor name) - Function return carr with typecheck using give name." + Returns carr with typecheck using give name." (lambda (x) (typecheck name x "pair") (caar x))) @@ -2228,21 +2227,21 @@ (define assoc (%doc "(assoc obj alist) - Function returns pair from alist that match given key using equal? check." + Returns pair from alist that match given key using equal? check." (curry %assoc/search equal?))) ;; ----------------------------------------------------------------------------- (define assq (%doc "(assq obj alist) - Function returns pair from a list that matches given key using eq? check." + Returns pair from a list that matches given key using eq? check." (curry %assoc/search eq?))) ;; ----------------------------------------------------------------------------- (define assv (%doc "(assv obj alist) - Function returns pair from alist that match given key using eqv? check." + Returns pair from alist that match given key using eqv? check." (curry %assoc/search eqv?))) ;; ----------------------------------------------------------------------------- @@ -2255,7 +2254,7 @@ (define (make-string k . rest) "(make-string k [char]) - Function returns new string with k elements. If char is provided + Returns new string with k elements. If char is provided it's filled with that character." (let ((char (if (null? rest) #\space (car rest)))) (typecheck "make-string" k "number" 1) @@ -2269,8 +2268,8 @@ (define (string . args) "(string chr1 chr2 ...) - Function creates a new string from it's arguments. Each argument - Need to be a character object." + Function that creates a new string from it's arguments. Each argument + needs to be a character object." (for-each (lambda (x) (typecheck "string" x "character")) args) @@ -2292,7 +2291,7 @@ (define (string-fill! string char) "(string-fill! symbol char) - Function destructively fills the string with given character." + Function that destructively fills the string with given character." (typecheck "string-fill!" string "string" 1) (typecheck "string-fill!" char "character" 2) (--> string (fill char))) @@ -2301,14 +2300,14 @@ (define (identity n) "(identity n) - No op function. It just returns its argument." + No-op function. It just returns its argument." n) ;; ----------------------------------------------------------------------------- (define (string-copy x) "(string-copy x) - Creates a new string based of given argument." + Creates a new string based on given argument." (typecheck "string-copy" x "string") (lips.LString x)) @@ -2316,7 +2315,7 @@ (define (list->string _list) "(list->string _list) - Function returns a string from list of characters." + Returns a string from a list of characters." (let ((array (list->array (map (lambda (x) (typecheck "list->string" x "character") @@ -2328,7 +2327,7 @@ (define (string->list string) "(string->list string) - Function returns a list of characters created from string." + Returns a list of characters created from string." (typecheck "string->list" string "string") (array->list (--> (Array.from string) (map (lambda (x) @@ -2339,7 +2338,7 @@ (define-macro (string-set! object index char) "(string-set! object index char) - Macro that replaces character in string in given index. It create new JavaScript + Replaces character in string in given index. It create new JavaScript string and replaces the old value. Object needs to be symbol that points to the variable that holds the string." (typecheck "string-set!" object "symbol") @@ -2356,7 +2355,7 @@ (define (string-length string) "(string-length string) - Function return length of the string." + Returns the length of the string." (typecheck "string-ref" string "string") (. string 'length)) @@ -2364,7 +2363,7 @@ (define (string-ref string k) "(string-ref string k) - Function return character inside string at given zero-based index." + Returns character inside string at given zero-based index." (typecheck "string-ref" string "string" 1) (typecheck "string-ref" k "number" 2) (lips.LCharacter (--> string (get k)))) @@ -2372,7 +2371,7 @@ (define (%string-cmp name string1 string2) "(%string-cmp name a b) - Function compares two strings and returns 0 if they are equal, + Function that compares two strings and returns 0 if they are equal, -1 if it is smaller and 1 if is larger. The function compares the codepoints of the character." (typecheck name string1 "string" 1) @@ -2383,42 +2382,42 @@ (define (string=? string1 string2) "(string=? string1 string2) - Function checks if two strings are equal." + Checks if two strings are equal." (= (%string-cmp "string=?" string1 string2) 0)) ;; ----------------------------------------------------------------------------- (define (string<? string1 string2) "(string<? string1 string2) - Function returns true if the second string is smaller than the first one." + Returns true if the second string is smaller than the first one." (= (%string-cmp "string<?" string1 string2) -1)) ;; ----------------------------------------------------------------------------- (define (string>? string1 string2) "(string<? string1 string2) - Function returns true if the second string is larger than the first one." + Returns true if the second string is larger than the first one." (= (%string-cmp "string>?" string1 string2) 1)) ;; ----------------------------------------------------------------------------- (define (string<=? string1 string2) "(string<? string1 string2) - Function returns true if the second string is not larger than the first one." + Returns true if the second string is not larger than the first one." (< (%string-cmp "string<=?" string1 string2) 1)) ;; ----------------------------------------------------------------------------- (define (string>=? string1 string2) "(string<? string1 string2) - Function returns true if second character is not smaller then the first one." + Returns true if second character is not smaller then the first one." (> (%string-cmp "string>=?" string1 string2) -1)) ;; ----------------------------------------------------------------------------- (define (%string-ci-cmp name string1 string2) "(%string-ci-cmp name a b) - Function compares two strings ignoring case and returns 0 if they are equal, + Function that compares two strings ignoring case and returns 0 if they are equal, -1 if it is smaller and 1 if is larger. The function compares the codepoints of the character." (typecheck name string1 "string" 1) @@ -2429,35 +2428,35 @@ (define (string-ci=? string1 string2) "(string-ci=? string1 string2) - Function checks if two strings are equal." + Checks if two strings are equal, ignoring case." (= (%string-ci-cmp "string-ci=?" string1 string2) 0)) ;; ----------------------------------------------------------------------------- (define (string-ci<? string1 string2) "(string-ci<? string1 string2) - Function returns true if the second string is smaller than the first one." + Returns true if the second string is smaller than the first one, ignoring case." (= (%string-ci-cmp "string-ci<?" string1 string2) -1)) ;; ----------------------------------------------------------------------------- (define (string-ci>? string1 string2) "(string-ci<? string1 string2) - Function returns true if the second string is larger than the first one." + Returns true if the second string is larger than the first one, ignoring case." (= (%string-ci-cmp "string-ci>?" string1 string2) 1)) ;; ----------------------------------------------------------------------------- (define (string-ci<=? string1 string2) "(string-ci<? string1 string2) - Function returns true if the second string is not larger than the first one." + Returns true if the second string is not larger than the first one, ignoring case." (< (%string-ci-cmp "string-ci<=?" string1 string2) 1)) ;; ----------------------------------------------------------------------------- (define (string-ci>=? string1 string2) "(string-ci>=? string1 string2) - Function returns true if second character is not smaller than the first one." + Returns true if second character is not smaller than the first one, ignoring case." (> (%string-ci-cmp "string-ci>=?" string1 string2) -1)) ;; ----------------------------------------------------------------------------- @@ -2469,14 +2468,14 @@ (define char? (%doc "(char? obj) - Function checks if the object is a character." + Checks if the object is a character." (curry instanceof lips.LCharacter))) ;; ----------------------------------------------------------------------------- (define (char->integer chr) "(char->integer chr) - Function returns the codepoint of Unicode character." + Returns the codepoint of Unicode character." (typecheck "char->integer" chr "character") (--> chr.__char__ (codePointAt 0))) @@ -2484,7 +2483,7 @@ (define (integer->char n) "(integer->char chr) - Function converts number argument to chararacter." + Function that converts number argument to chararacter." (typecheck "integer->char" n "number") (if (integer? n) (string-ref (String.fromCodePoint n) 0) @@ -2504,7 +2503,7 @@ (%define-chr-re (char-whitespace? chr) "(char-whitespace? chr) - Function returns true if character is whitespace." + Returns true if character is whitespace." (let-env (interaction-environment) (--> **internal-env** (get 'space-unicode-regex)))) @@ -2512,7 +2511,7 @@ (%define-chr-re (char-numeric? chr) "(char-numeric? chr) - Function return true if character is number." + Returns true if character is number." (let-env (interaction-environment) (--> **internal-env** (get 'numeral-unicode-regex)))) @@ -2520,7 +2519,7 @@ (%define-chr-re (char-alphabetic? chr) "(char-alphabetic? chr) - Function return true if character is leter of the ASCII alphabet." + Returns true if character is leter of the ASCII alphabet." (let-env (interaction-environment) (--> **internal-env** (get 'letter-unicode-regex)))) @@ -2528,7 +2527,7 @@ (define (%char-cmp name chr1 chr2) "(%char-cmp name a b) - Function compare two characters and return 0 if they are equal, + Function that compares two characters and return 0 if they are equal, -1 second is smaller and 1 if is larget. The function compare the codepoints of the character." (typecheck name chr1 "character" 1) @@ -2543,42 +2542,42 @@ (define (char=? chr1 chr2) "(char=? chr1 chr2) - Function check if two characters are equal." + Checks if two characters are equal." (= (%char-cmp "char=?" chr1 chr2) 0)) ;; ----------------------------------------------------------------------------- (define (char<? chr1 chr2) "(char<? chr1 chr2) - Function return true if second character is smaller then the first one." + Returns true if second character is smaller then the first one." (= (%char-cmp "char<?" chr1 chr2) -1)) ;; ----------------------------------------------------------------------------- (define (char>? chr1 chr2) "(char<? chr1 chr2) - Function return true if second character is larger then the first one." + Returns true if second character is larger then the first one." (= (%char-cmp "char>?" chr1 chr2) 1)) ;; ----------------------------------------------------------------------------- (define (char<=? chr1 chr2) "(char<? chr1 chr2) - Function return true if second character is not larger then the first one." + Returns true if second character is not larger then the first one." (< (%char-cmp "char<=?" chr1 chr2) 1)) ;; ----------------------------------------------------------------------------- (define (char>=? chr1 chr2) "(char<? chr1 chr2) - Function return true if second character is not smaller then the first one." + Returns true if second character is not smaller then the first one." (> (%char-cmp "char>=?" chr1 chr2) -1)) ;; ----------------------------------------------------------------------------- (define (%char-ci-cmp name chr1 chr2) "(%char-cmp name a b) - Function compare two characters and return 0 if they are equal, + Function that compares two characters and return 0 if they are equal, -1 second is smaller and 1 if is larget. The function compare the codepoints of the character." (typecheck name chr1 "character" 1) @@ -2589,35 +2588,35 @@ (define (char-ci=? chr1 chr2) "(char-ci=? chr1 chr2) - Function check if two characters are equal." + Checks if two characters are equal." (= (%char-ci-cmp "char-ci=?" chr1 chr2) 0)) ;; ----------------------------------------------------------------------------- (define (char-ci<? chr1 chr2) "(char-ci<? chr1 chr2) - Function return true if second character is smaller then the first one." + Returns true if second character is smaller then the first one." (= (%char-ci-cmp "char-ci<?" chr1 chr2) -1)) ;; ----------------------------------------------------------------------------- (define (char-ci>? chr1 chr2) "(char-ci<? chr1 chr2) - Function return true if second character is larger then the first one." + Returns true if second character is larger then the first one." (= (%char-ci-cmp "char-ci>?" chr1 chr2) 1)) ;; ----------------------------------------------------------------------------- (define (char-ci<=? chr1 chr2) "(char-ci<? chr1 chr2) - Function return true if second character is not larger then the first one." + Returns true if second character is not larger then the first one." (< (%char-ci-cmp "char-ci<=?" chr1 chr2) 1)) ;; ----------------------------------------------------------------------------- (define (char-ci>=? chr1 chr2) "(char-ci<? chr1 chr2) - Function return true if second character is not smaller then the first one." + Returns true if second character is not smaller then the first one." (> (%char-ci-cmp "char-ci>=?" chr1 chr2) -1)) ;; ----------------------------------------------------------------------------- @@ -2640,7 +2639,7 @@ (define (char-upper-case? char) "(char-upper-case? char) - Function check if character is upper case." + Checks if character is upper case." (typecheck "char-upper-case?" char "character") (and (char-alphabetic? char) (char=? (char-upcase char) char))) @@ -2649,7 +2648,7 @@ (define (char-lower-case? char) "(char-upper-case? char) - Function check if character is lower case." + Checks if character is lower case." (typecheck "char-lower-case?" char "character") (and (char-alphabetic? char) (char=? (char-downcase char) char))) @@ -2689,7 +2688,7 @@ (define (make-vector n . rest) "(make-vector n [fill]) - Create new vector with n empty elements. If fill is specified it will set + Creates a new vector with n empty elements. If fill is specified it will set all elements of the vector to that value." (let ((result (new Array n))) (if (not (null? rest)) @@ -2700,14 +2699,14 @@ (define (vector? n) "(vector? n) - Function return true of value is vector and false if not." + Returns true if value is vector and false if not." (string=? (type n) "array")) ;; ----------------------------------------------------------------------------- (define (vector-ref vec n) "(vector-ref vec n) - Function return nth element of the vector vec." + Returns nth element of the vector vec." (typecheck "vector-ref" vec "array" 1) (typecheck "vector-ref" n "number" 2) (. vec n)) @@ -2716,7 +2715,7 @@ (define (vector-set! vec n value) "(vector-set! vec n value) - Function set nth item of the vector to value." + Function that sets nth item of the vector to value." (typecheck "vector-ref" vec "array" 1) (typecheck "vector-ref" n "number" 2) (set-obj! vec n value)) @@ -2737,7 +2736,7 @@ (define (vector-length vec) "(vector-length vec) - Function return length of the vector. If argument is not vector it throw exception." + Returns length of the vector. It errors if the argument is not a vector." (typecheck "vector-length" vec "array") (length vec)) @@ -2871,7 +2870,7 @@ "(random) (random seed) - Function generate new random real number using Knuth algorithm." + Function that generates new random real number using Knuth algorithm." (if (pair? new-seed) (set! seed (car new-seed)) (set! seed (modulo (+ (* seed a) c) m))) @@ -2881,7 +2880,7 @@ (define (eof-object? obj) "(eof-object? arg) - Function check if value is eof object, returned from input string + Checks if value is eof object, returned from input string port when there are no more data to read." (eq? obj eof)) @@ -2889,14 +2888,14 @@ (define (output-port? obj) "(output-port? arg) - Function return true if argument is output port." + Returns true if argument is output port." (instanceof lips.OutputPort obj)) ;; ----------------------------------------------------------------------------- (define (input-port? obj) "(input-port? arg) - Function return true if argument is input port." + Returns true if argument is input port." (instanceof lips.InputPort obj)) ;; ----------------------------------------------------------------------------- @@ -2904,7 +2903,7 @@ "(char-ready?) (char-ready? port) - Function checks if characters is ready in input port. This is useful mostly + Checks if characters is ready in input port. This is useful mostly for interactive ports that return false if it would wait for user input. It return false if port is closed." (let ((port (if (null? rest) (current-input-port) (car rest)))) @@ -2917,7 +2916,7 @@ (lambda(filename) "(open-input-file filename) - Function return new Input Port with given filename. In Browser user need to + Returns new Input Port with given filename. In Browser user need to provide global fs variable that is instance of FS interface." (new lips.InputFilePort (%read-file false filename) filename)))) @@ -3029,7 +3028,7 @@ (lambda (filename) "(open-output-file filename) - Function open file and return port that can be used for writing. If file + Function that opens file and return port that can be used for writing. If file exists it will throw an Error." (typecheck "open-output-file" filename "string") (if (not (procedure? open)) @@ -3042,7 +3041,7 @@ (define (scheme-report-environment version) "(scheme-report-environment version) - Function return new Environment object for given Scheme Spec version. + Returns new Environment object for given Scheme Spec version. Only argument 5 is supported that create environemnt for R5RS." (typecheck "scheme-report-environment" version "number") (case version @@ -3092,8 +3091,8 @@ (define-macro (%make-vector prefix type help) "(%make-vector prefix type help) - Mega helper macro that create list of functions for single byte vector - based on typed array from JavaScript" + Mega-helper macro that creates a list of functions for single byte vectors + based on typed arrays from JavaScript." (letrec ((prefix-str (symbol->string prefix)) (type-str (symbol->string type)) (l-type (--> type-str (toLowerCase))) @@ -3144,7 +3143,7 @@ (define (,vector? x) ,(format "(~a x) - Function return #t of argument is ~a otherwise it return #f." + Returns #t of argument is ~a otherwise it return #f." vector? help) (and (object? x) (equal? (. x 'constructor) ,type))) @@ -3152,7 +3151,7 @@ (define (,vector-in-range? vector k) ,(format "(~a vector k) - Function test if index is range for ~a." + Function that tests if index is range for ~a." vector-in-range? help) (typecheck ,(symbol->string vector-in-range?) vector ,l-type) @@ -3163,7 +3162,7 @@ (define (,vector-ref vector k) ,(format "(~a vector k) - Function return value frome vector at index k. If index is out of range it throw exception." + Returns value frome vector at index k. If index is out of range it throw exception." vector-ref help) (typecheck ,(symbol->string vector-ref) vector ,l-type) @@ -3203,14 +3202,14 @@ (string-append ,repr-str (repr (,vector->list x) _quote)))) ))) ;; ----------------------------------------------------------------------------- -(%make-vector u8 Uint8Array "usigned 8-bit integer vector") -(%make-vector s8 Int8Array "signed 8-bit integer vector") -(%make-vector u16 Uint16Array "usigned 16-bit integer vector") -(%make-vector s16 Int16Array "signed 16-bit integer vector") -(%make-vector u32 Uint32Array "usigned 32-bit integer vector") -(%make-vector s32 Int32Array "signed 32-bit integer vector") -(%make-vector f32 Float32Array "32-bit IEEE floating point number vector") -(%make-vector f64 Float64Array "64-bit IEEE floating point number vector") +(%make-vector u8 Uint8Array "unsigned 8-bit integer vector (C unsigned char)") +(%make-vector s8 Int8Array "signed 8-bit integer vector (C signed char)") +(%make-vector u16 Uint16Array "unsigned 16-bit integer vector (C unsigned short)") +(%make-vector s16 Int16Array "signed 16-bit integer vector (C short)") +(%make-vector u32 Uint32Array "unsigned 32-bit integer vector (C int)") +(%make-vector s32 Int32Array "signed 32-bit integer vector (C unsigned int)") +(%make-vector f32 Float32Array "32-bit IEEE-754 floating point number vector (C float)") +(%make-vector f64 Float64Array "64-bit IEEE-754 floating point number vector (C double)") ;;vector->[type]vector! ;;list->[type]vector! @@ -3236,7 +3235,7 @@ (define (list-match? predicate list) "(list-match? predicate list) - Function check if consecutive elements of the list match the predicate function." + Checks if consecutive elements of the list match the predicate function." (typecheck "list-match?" predicate #("function" "macro")) (typecheck "list-match?" list "pair") (or (or (null? list) @@ -3248,7 +3247,7 @@ (define (symbol=? . args) "(symbol=? s1 s2 ...) - Function check if each value is symbol and it's the same acording to string=? predicate." + Checks if each value is symbol and it's the same acording to string=? predicate." (list-match? (lambda (a b) (and (symbol? a) (symbol? b) (equal? a b))) args)) @@ -3259,7 +3258,7 @@ (define (values-ref values n) "(values-ref values n) - Function return n value of values object which is result of value function." + Returns n value of values object which is result of value function." (typecheck "values-ref" values "values" 1) (typecheck "values-ref" n "number" 1) (--> values (valueOf) n)) @@ -3283,7 +3282,7 @@ (define (vector-append . args) "(vector-append v1 v2 ...) - Function return new vector by combining it's arguments that should be vectors." + Returns new vector by combining it's arguments that should be vectors." (if (null? args) (vector) (begin @@ -3294,7 +3293,7 @@ (define-macro (%range-function spec . body) "(%range-function spec . body) - Macro that creates R7RS vector functions that have range start end." + Creates R7RS vector functions that have range start end." (let* ((name (car spec)) (name-str (symbol->string name)) (args (append (cdr spec) 'rest))) @@ -3318,7 +3317,7 @@ (vector->list vector start) (vector->list vector start end) - Function copy given range of vector to list. If no start is specified it use + Function that copies given range of vector to list. If no start is specified it use start of the vector, if no end is specified it convert to the end of the vector." (typecheck "vector->list" vector "array") (array->list (vector.slice start end))) @@ -3330,7 +3329,7 @@ (string->list string start) (string->list string start end) - Function copy given range of string to list. If no start is specified it use + Function that copies given range of string to list. If no start is specified it use start of the string, if no end is specified it convert to the end of the string." (typecheck "string->vector" string "string") (--> (string.substring start end) @@ -3344,7 +3343,7 @@ (vector->string vector start) (vector->string vector start end) - Function return new string created from vector of characters in given range. + Returns new string created from vector of characters in given range. If no start is given it create string from 0, if no end is given it return string to the end." (typecheck "vector->string" vector "array") @@ -3453,7 +3452,7 @@ (define (boolean=? . args) "(boolean=? b1 b2 ...) - Function check if all arguments are boolean and if they are the same." + Checks if all arguments are boolean and if they are the same." (if (< (length args) 2) (error "boolean=?: too few arguments") (reduce (lambda (acc item) @@ -3465,7 +3464,7 @@ (define (port? x) "(port? x) - Function return true of argumet is nput or output port port object." + Returns true if the argument is an input or output port object." (or (output-port? x) (input-port? x))) ;; ----------------------------------------------------------------------------- @@ -3483,7 +3482,7 @@ (begin result1 result2 ...)))) "(when test body ...) - Macro execute body when test expression is true.") + Executes body when test expression is true.") ;; ----------------------------------------------------------------------------- (define-syntax unless @@ -3493,7 +3492,7 @@ (begin result1 result2 ...)))) "(unless test body ...) - Macro execute body when test expression is false.") + Executes body when test expression is false.") ;; ----------------------------------------------------------------------------- (define inexact exact->inexact) @@ -3503,7 +3502,7 @@ (define (exact-integer? n) "(exact-integer? n) - Function returns #t if z is both exact and an integer; otherwise + Returns #t if z is both exact and an integer; otherwise returns #f." (and (integer? n) (exact? n))) @@ -3511,7 +3510,7 @@ (define (vector-map fn . rest) "(vector-map fn vector1 vector2 ...) - Function return new vector from applying function fn to each element + Returns new vector from applying function fn to each element of the vectors, similar to map for lists." (if (or (= (length rest) 0) (not (every vector? rest))) (error "vector-map: function require at least 1 vector") @@ -3527,7 +3526,7 @@ (define (string-map fn . rest) "(string-map fn string1 stringr2 ...) - Function return new string from applying function fn to each element + Returns new string from applying function fn to each element of the strings, similar to map for lists." (if (or (= (length rest) 0) (not (every string? rest))) (error "string-map: function require at least 1 string") @@ -3537,11 +3536,12 @@ (define (dynamic-wind before thunk after) "(dynamic-wind before thunk after) - Function accept 3 procedures/lambdas and execute thunk with before and always - after even if error accur" + Accepts 3 procedures/lambdas and executes before, then thunk, and + always after even if an error occurs in thunk." (before) (let ((result (try (thunk) (catch (e) + (after) (error e))))) (after) result)) @@ -3599,14 +3599,14 @@ list)))) "(define-values (a b ...) expr) - Function evaluate expression expr and if it evaluates to result of values + Evaluates expression expr and if it evaluates to result of values then it will defined each value as variable like with define.") ;; ----------------------------------------------------------------------------- (define-macro (include . files) "(include file ...) - Macro that load at least one file content and insert them into one, + Load at least one file content and insert them into one, body expression." (if (null? files) (throw (new Error "include: at least one file path required")) @@ -3778,7 +3778,7 @@ (bytevector-copy v start) (bytevector-copy v start end) - Function and return new vector from start to end. If no start and end is provided + Returns a new vector from start to end. If no start and end is provided whole vector is copied and returned." (if (null? rest) (new Uint8Array v) @@ -3822,7 +3822,7 @@ (string->utf8 string start) (string->utf8 string start end) - Function converts string into u8 bytevector using utf8 encoding. + Converts string into u8 bytevector using utf8 encoding. The start and end is the range of the input string for the conversion." (typecheck "string->utf8" string "string") (if (null? rest) @@ -3840,7 +3840,7 @@ (utf8->string u8vector start) (utf8->string u8vector start end) - Function converts u8 bytevector into string using utf8 encoding. + Converts u8 bytevector into string using utf8 encoding. The start and end is the range of the input byte vector for the conversion." (typecheck "utf8->string" v "uint8array") (if (null? rest) @@ -3854,7 +3854,7 @@ (define (open-input-string string) "(open-input-string string) - Function create new string port as input that can be used to + Creates new string port as input that can be used to read S-exressions from this port using `read` function." (typecheck "open-input-string" string "string") (new lips.InputStringPort string (interaction-environment))) @@ -3863,7 +3863,7 @@ (define (open-output-string) "(open-output-string) - Function create new output port that can used to write string into + Creates new output port that can used to write string into and after finish get the whole string using `get-output-string`." (new lips.OutputStringPort repr)) @@ -3880,7 +3880,7 @@ (define (get-output-bytevector port) "(get-output-string port) - Function get full string from string port. If nothing was wrote + Gets full string from string port. If nothing was wrote to given port it will return empty string." (if (not (instanceof lips.OutputByteVectorPort port)) (throw (new Error (string-append @@ -3892,7 +3892,7 @@ (define (get-output-string port) "(get-output-string port) - Function get full string from string port. If nothing was wrote + Gets full string from string port. If nothing was wrote to given port it will return empty string." (if (not (instanceof lips.OutputStringPort port)) (throw (new Error (string-append "get-output-string: expecting output-string-port get " @@ -3911,7 +3911,7 @@ (define (open-binary-input-file filename) "(open-binary-input-file filename) - Function return new Input Binary Port with given filename. In Browser + Returns new Input Binary Port with given filename. In Browser user need to provide global fs variable that is instance of FS interface." (let ((u8vector (buffer->u8vector (%read-binary-file filename)))) (new lips.InputBinaryFilePort u8vector filename))) @@ -3920,14 +3920,14 @@ (define (binary-port? port) "(binary-port? port) - Function test if argument is binary port." + Function that tests if argument is binary port." (and (port? port) (eq? port.__type__ (Symbol.for "binary")))) ;; ----------------------------------------------------------------------------- (define (textual-port? port) "(textual-port? port) - Function test if argument is string port." + Function that tests if argument is string port." (and (port? port) (eq? port.__type__ (Symbol.for "text")))) ;; ----------------------------------------------------------------------------- @@ -4040,7 +4040,7 @@ (lambda (filename) "(open-binary-output-file filename) - Function open file and return port that can be used for writing. If file + Opens file and return port that can be used for writing. If file exists it will throw an Error." (typecheck "open-output-file" filename "string") (if (not (procedure? open)) @@ -4056,7 +4056,7 @@ (read-bytevector! bytevector port start) (read-bytevector! bytevector port start end) - Function read next bytes from binary input port and write them into byte vector. + Reads next bytes from binary input port and write them into byte vector. if not start is specified it start to write into 0 position of the vector until the end or end the vector if no end is specified." (typecheck "read-bytevector!" vector "uint8array") @@ -4080,7 +4080,7 @@ (lambda (filename) "(delete-file filename) - Function delete the file of given name." + Deletes the file of given name." (typecheck "delete-file" filename "string") (if (not (procedure? unlink)) (set! unlink (%fs-promisify-proc 'unlink "delete-file"))) @@ -4116,14 +4116,14 @@ (define (output-port-open? port) "(output-port-open? port) - Function check if argument is output-port and if you can write to it." + Checks if argument is output-port and if you can write to it." (and (output-port? port) (port.is_open))) ;; ----------------------------------------------------------------------------- (define (input-port-open? port) "(input-port-open? port) - Function check if argument is input-port and if you can read from it." + Checks if argument is input-port and if you can read from it." (and (input-port? port) (port.is_open))) ;; ----------------------------------------------------------------------------- @@ -4255,7 +4255,7 @@ (define (nan? x) "(nan? x) - Function check if argument x is Not a Number (NaN) value." + Checks if argument x is Not a Number (NaN) value." (and (number? x) (or (x.isNaN) (and (%number-type "complex" x) @@ -4266,7 +4266,7 @@ (define (infinite? x) "(infinite? x) - Function check if value is infinite." + Checks if value is infinite." (or (eq? x Number.NEGATIVE_INFINITY) (eq? x Number.POSITIVE_INFINITY) (and (number? x) @@ -4279,7 +4279,7 @@ (define (finite? x) "(finite? x) - Function check if value is finite." + Checks if value is finite." (not (infinite? x))) ;; ----------------------------------------------------------------------------- @@ -4425,12 +4425,12 @@ (lambda () "(current-directory) - Return corrent working directory, default it's corrent URL." + Return current working directory, default is the current URL." cwd) (lambda (value) "(set-current-directory! string) - Function change current working directory to provided string." + Changes the current working directory to provided string." (typecheck "set-current-directory!" value "string") (set! cwd value)))) (let ((process (require "process"))) @@ -4438,13 +4438,13 @@ (lambda () "(current-directory) - Return corrent working directory, default it's path from where + Returns the current working directory, default is the path from where the script was executed." (string-append (process.cwd) "/")) (lambda (value) "(set-current-directory! string) - Function change current working directory to provided string." + Changes the current working directory to provided string." (typecheck "set-current-directory!" value "string") (process.chdir value)))))) @@ -4460,7 +4460,7 @@ (define (error-object? obj) "(error-object? obj) - Function check if object is of Error object throwed by error function." + Checks if object is of Error object throwed by error function." (instanceof lips.Error obj)) ;; ----------------------------------------------------------------------------- @@ -4483,7 +4483,7 @@ (define (get-environment-variables) "(get-environment-variables) - Function returns all variables as alist. This funtion throws exception + Returns all process environment variables as an alist. This funtion throws exception when called in browser." (if (eq? self window) (throw "get-environment-variables: Node.js only funtion") @@ -4493,7 +4493,7 @@ (define (get-environment-variable name) "(get-environment-variable name) - Function return given environment variable. This funtion throws exception + Returns given environment variable. This funtion throws exception when called in browser." (. process.env name)) @@ -4538,7 +4538,7 @@ (resolve (BrowserFS.BFSRequire "fs")) (reject e))))))) ((not (null? self.BrowserFS)) - (console.warn (string-append "BrowserFS not initilalized " + (console.warn (string-append "BrowserFS is not initilalized and " "IndexedDB is not available")) nil))) (Buffer (cond ((eq? self global) diff --git a/dist/std.xcb b/dist/std.xcb index 630d6a6a6..d3fac1407 100644 Binary files a/dist/std.xcb and b/dist/std.xcb differ diff --git a/lib/R5RS.scm b/lib/R5RS.scm index a63eadaa6..9defc653d 100755 --- a/lib/R5RS.scm +++ b/lib/R5RS.scm @@ -216,14 +216,14 @@ (define (promise? obj) "(promise? obj) - Function that checks if the value is a promise created with delay or make-promise." + Checks if the value is a promise created with delay or make-promise." (string=? (type obj) "promise")) ;; ----------------------------------------------------------------------------- (define (positive? x) "(positive? x) - Function that checks if the number is larger then 0" + Checks if the number is larger then 0" (typecheck "positive?" x "number") (> x 0)) @@ -231,7 +231,7 @@ (define (negative? x) "(negative? x) - Function that checks if the number is smaller then 0" + Checks if the number is smaller then 0" (typecheck "negative?" x "number") (< x 0)) @@ -239,7 +239,7 @@ (define (zero? x) "(zero? x) - Function that checks if the number is equal to 0" + Checks if the number is equal to 0" (typecheck "zero?" x "number") (= x 0)) @@ -310,7 +310,7 @@ (define (real? x) "(real? x) - Function that checks if the argument x is real." + Checks if the argument x is real." (and (number? x) (or (eq? x NaN) (eq? x Number.NEGATIVE_INFINITY) (eq? x Number.POSITIVE_INFINITY) @@ -323,7 +323,7 @@ (define (integer? x) "(integer? x) - Function that checks if the argument x is integer." + Checks if the argument x is integer." (and (number? x) (not (eq? x NaN)) (not (eq? x Number.NEGATIVE_INFINITY)) @@ -336,7 +336,7 @@ (define (complex? x) "(complex? x) - Function that checks if argument x is complex." + Checks if argument x is complex." (and (number? x) (or (eq? x NaN) (eq? x Number.NEGATIVE_INFINITY) (eq? x Number.POSITIVE_INFINITY) @@ -346,7 +346,7 @@ (define (rational? x) "(rational? x) - Function that checks if the value is rational." + Checks if the value is rational." (and (number? x) (not (eq? x NaN)) (not (eq? x Number.NEGATIVE_INFINITY)) @@ -818,7 +818,7 @@ (define (string=? string1 string2) "(string=? string1 string2) - Function that checks if two strings are equal." + Checks if two strings are equal." (= (%string-cmp "string=?" string1 string2) 0)) ;; ----------------------------------------------------------------------------- @@ -864,7 +864,7 @@ (define (string-ci=? string1 string2) "(string-ci=? string1 string2) - Function that checks if two strings are equal, ignoring case." + Checks if two strings are equal, ignoring case." (= (%string-ci-cmp "string-ci=?" string1 string2) 0)) ;; ----------------------------------------------------------------------------- @@ -904,7 +904,7 @@ (define char? (%doc "(char? obj) - Function that checks if the object is a character." + Checks if the object is a character." (curry instanceof lips.LCharacter))) ;; ----------------------------------------------------------------------------- @@ -978,7 +978,7 @@ (define (char=? chr1 chr2) "(char=? chr1 chr2) - Function that checks if two characters are equal." + Checks if two characters are equal." (= (%char-cmp "char=?" chr1 chr2) 0)) ;; ----------------------------------------------------------------------------- @@ -1024,7 +1024,7 @@ (define (char-ci=? chr1 chr2) "(char-ci=? chr1 chr2) - Function that checks if two characters are equal." + Checks if two characters are equal." (= (%char-ci-cmp "char-ci=?" chr1 chr2) 0)) ;; ----------------------------------------------------------------------------- @@ -1075,7 +1075,7 @@ (define (char-upper-case? char) "(char-upper-case? char) - Function that checks if character is upper case." + Checks if character is upper case." (typecheck "char-upper-case?" char "character") (and (char-alphabetic? char) (char=? (char-upcase char) char))) @@ -1084,7 +1084,7 @@ (define (char-lower-case? char) "(char-upper-case? char) - Function that checks if character is lower case." + Checks if character is lower case." (typecheck "char-lower-case?" char "character") (and (char-alphabetic? char) (char=? (char-downcase char) char))) @@ -1316,7 +1316,7 @@ (define (eof-object? obj) "(eof-object? arg) - Function that checks if value is eof object, returned from input string + Checks if value is eof object, returned from input string port when there are no more data to read." (eq? obj eof)) @@ -1339,7 +1339,7 @@ "(char-ready?) (char-ready? port) - Function that checks if characters is ready in input port. This is useful mostly + Checks if characters is ready in input port. This is useful mostly for interactive ports that return false if it would wait for user input. It return false if port is closed." (let ((port (if (null? rest) (current-input-port) (car rest)))) diff --git a/lib/R7RS.scm b/lib/R7RS.scm index fcf308d6d..2fb913047 100755 --- a/lib/R7RS.scm +++ b/lib/R7RS.scm @@ -20,7 +20,7 @@ (define (list-match? predicate list) "(list-match? predicate list) - Function that checks if consecutive elements of the list match the predicate function." + Checks if consecutive elements of the list match the predicate function." (typecheck "list-match?" predicate #("function" "macro")) (typecheck "list-match?" list "pair") (or (or (null? list) @@ -32,7 +32,7 @@ (define (symbol=? . args) "(symbol=? s1 s2 ...) - Function that checks if each value is symbol and it's the same acording to string=? predicate." + Checks if each value is symbol and it's the same acording to string=? predicate." (list-match? (lambda (a b) (and (symbol? a) (symbol? b) (equal? a b))) args)) @@ -237,7 +237,7 @@ (define (boolean=? . args) "(boolean=? b1 b2 ...) - Function that checks if all arguments are boolean and if they are the same." + Checks if all arguments are boolean and if they are the same." (if (< (length args) 2) (error "boolean=?: too few arguments") (reduce (lambda (acc item) @@ -901,14 +901,14 @@ (define (output-port-open? port) "(output-port-open? port) - Function that checks if argument is output-port and if you can write to it." + Checks if argument is output-port and if you can write to it." (and (output-port? port) (port.is_open))) ;; ----------------------------------------------------------------------------- (define (input-port-open? port) "(input-port-open? port) - Function that checks if argument is input-port and if you can read from it." + Checks if argument is input-port and if you can read from it." (and (input-port? port) (port.is_open))) ;; ----------------------------------------------------------------------------- @@ -1040,7 +1040,7 @@ (define (nan? x) "(nan? x) - Function that checks if argument x is Not a Number (NaN) value." + Checks if argument x is Not a Number (NaN) value." (and (number? x) (or (x.isNaN) (and (%number-type "complex" x) @@ -1051,7 +1051,7 @@ (define (infinite? x) "(infinite? x) - Function that checks if value is infinite." + Checks if value is infinite." (or (eq? x Number.NEGATIVE_INFINITY) (eq? x Number.POSITIVE_INFINITY) (and (number? x) @@ -1064,7 +1064,7 @@ (define (finite? x) "(finite? x) - Function that checks if value is finite." + Checks if value is finite." (not (infinite? x))) ;; ----------------------------------------------------------------------------- @@ -1245,7 +1245,7 @@ (define (error-object? obj) "(error-object? obj) - Function that checks if object is of Error object throwed by error function." + Checks if object is of Error object throwed by error function." (instanceof lips.Error obj)) ;; ----------------------------------------------------------------------------- diff --git a/lib/bootstrap.scm b/lib/bootstrap.scm index b60d2c0bf..cf91aa8e4 100755 --- a/lib/bootstrap.scm +++ b/lib/bootstrap.scm @@ -159,14 +159,14 @@ (define (single list) "(single list) - Function that checks if argument is list with one element." + Checks if argument is list with one element." (and (pair? list) (not (cdr list)))) ;; ----------------------------------------------------------------------------- (define (iterator? x) "(iterator? x) - Function that checks if value is JavaScript iterator object." + Checks if value is JavaScript iterator object." (and (object? x) (procedure? (. x Symbol.iterator)))) ;; ----------------------------------------------------------------------------- @@ -195,7 +195,7 @@ (define (plain-object? x) "(plain-object? x) - Function that checks if value is a plain JavaScript object created using the object macro." + Checks if value is a plain JavaScript object created using the object macro." ;; here we don't use string=? or equal? because it may not be defined (and (== (--> (type x) (cmp "object")) 0) (eq? (. x 'constructor) Object))) @@ -378,7 +378,7 @@ (define (key? symbol) "(key? symbol) - Function that checks if symbol is a keyword (has a colon as first character)." + Checks if symbol is a keyword (has a colon as first character)." ;; we can't use string=? because it's in R5RS.scm we use same code that use cmp (and (symbol? symbol) (== (--> (substring (symbol->string symbol) 0 1) (cmp ":")) 0))) @@ -709,7 +709,7 @@ (define (environment-bound? env x) "(environment-bound? env symbol) - Function that checks if symbol is a bound variable similar to bound?." + Checks if symbol is a bound variable similar to bound?." (typecheck "environment-bound?" env "environment" 1) (typecheck "environment-bound?" x "symbol" 2) (bound? x env)) @@ -804,7 +804,7 @@ (define (defmacro? obj) "(defmacro? expression) - Function that checks if object is a macro and it's expandable." + Checks if object is a macro and it's expandable." (and (macro? obj) (. obj 'defmacro))) ;; ----------------------------------------------------------------------------- @@ -1347,7 +1347,7 @@ (define (environment? obj) "(environment? obj) - Function that checks if object is a LIPS environment." + Checks if object is a LIPS environment." (instanceof lips.Environment obj)) ;; ----------------------------------------------------------------------------- diff --git a/src/lips.js b/src/lips.js index f9b1438b6..1e4b0c1fc 100644 --- a/src/lips.js +++ b/src/lips.js @@ -8599,7 +8599,7 @@ var global_env = new Environment({ typecheck, `(typecheck label value type [position]) - Function that checks the type of value and errors if the type is not one allowed. + Checks the type of value and errors if the type is not one allowed. Type can be string or list of strings. The position optional argument is used to create a proper error message for the nth argument of function calls.`), // ------------------------------------------------------------------ @@ -9181,13 +9181,13 @@ var global_env = new Environment({ return LNumber(num).isOdd(); }), `(odd? number) - Function that checks if number is odd.`), + Checks if number is odd.`), // ------------------------------------------------------------------ 'even?': doc('even?', single_math_op(function(num) { return LNumber(num).isEven(); }), `(even? number) - Function that checks if number is even.`), + Checks if number is even.`), // ------------------------------------------------------------------ // math functions '*': doc('*', reduce_math_op(function(a, b) {