diff --git a/.codespellrc b/.codespellrc
index 230b89609..bb755833a 100644
--- a/.codespellrc
+++ b/.codespellrc
@@ -1,2 +1,2 @@
[codespell]
-skip = ./node_modules*,./dist/*,./package-lock.json,./lib/srfi/*,./assets/UnicodeData.txt,./assets/CaseFolding.txt,./scripts/numerals.scm
+skip = build,coverage,node_modules*,./dist/*,package-lock.json,./lib/srfi/*,./assets/UnicodeData.txt,./assets/CaseFolding.txt,./scripts/numerals.scm
diff --git a/.gitattributes b/.gitattributes
index 96aed74a3..cdf075204 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -10,6 +10,7 @@ tests/snapshots/* binary
*.xcm binary
*.xcb binary
dist/** linguist-generated
+docs/reference.json linguist-generated binary
*config.js linguist-vendored
docs/** linguist-documentation
**/*.lips linguist-language=scheme
diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml
index 415e4f67c..7544416c1 100644
--- a/.github/workflows/build.yaml
+++ b/.github/workflows/build.yaml
@@ -39,7 +39,7 @@ jobs:
- name: checkout
uses: actions/checkout@v4
- name: setup node
- uses: actions/setup-node@v3
+ uses: actions/setup-node@v4
with:
node-version: '20'
- run: npm ci
@@ -48,6 +48,6 @@ jobs:
- run: make test
- run: make coverage
- name: Coveralls
- uses: coverallsapp/github-action@master
+ uses: coverallsapp/github-action@v2
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7f28b6332..db80f8cc6 100755
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,27 @@
+## 1.0.0-beta.20
+### Feature
+* allow to call `load` with `@lips` prefix [#354](https://github.com/jcubic/lips/issues/354)
+* add string interpolation [#321](https://github.com/jcubic/lips/issues/321)
+* add default repr for R7RS records
+* add parenthesis matching in Node.js REPL
+### Bugfix
+* fix duplicated identifiers in syntax-rules (case of SRFI-239 example implementation)
+* fix `load` of absolute path in Node
+* fix require of LIPS package from Node
+* fix transforming `syntax-rules` ellipsis that expand into #void
+* fix improper lists in `syntax-rules` [#360](https://github.com/LIPS-scheme/lips/issues/360)
+* fix handling of REPL in Emacs (`run-scheme`)
+* fix `promise?` predicate
+* fix handling of `|1|1` and `|a|b|c|` symbols
+* fix repr of anonymous classes [#361](https://github.com/LIPS-scheme/lips/issues/361)
+* fix handling of escape characters in symbols
+* fix processing list with nested unquote-splicing [#362](https://github.com/LIPS-scheme/lips/issues/362)
+* fix exception during error from eval [#362](https://github.com/LIPS-scheme/lips/issues/362)
+* allow to catch exceptions from eval
+* fix else keyword as only expression in cond [#366](https://github.com/LIPS-scheme/lips/issues/366)
+* fix clash of variable named `list` in named `let` [#398](https://github.com/LIPS-scheme/lips/issues/398)
+* fix Node REPL flickering
+
## 1.0.0-beta.19
### Breaking
* change `get-environment-variables` and `get-environment-variable` returns nil and undefined in the browser
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c4bd22a07..a33e988f4 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -109,3 +109,21 @@ run ESLint execute:
```bash
make lint
```
+
+## Codepell
+
+LIPS use [Codespell](https://github.com/codespell-project/codespell) to catch
+grammar mistakes. It runs as GitHub Action. But you can test locally so you can
+fix the type before it will give error from Action.
+
+You can install Codespell using PIP (you need to have Python installed):
+
+```bash
+pip install codespell
+```
+
+The run:
+
+```bash
+make codespell
+```
diff --git a/Makefile b/Makefile
index e692ab114..319f63744 100644
--- a/Makefile
+++ b/Makefile
@@ -11,6 +11,7 @@ COMMIT=`git rev-parse HEAD`
URL=`git config --get remote.origin.url`
UNICODE_ALL=https://unicode.org/Public/UNIDATA/UnicodeData.txt
UNICODE_FOLD=https://www.unicode.org/Public/UCD/latest/ucd/CaseFolding.txt
+WORK_TREE=`git worktree list | cut -f1 -d' ' | grep -v "\`pwd\`$$" | xargs -I{} basename {} | tr $$'\n' ',' | sed 's/,$$//'`
MAKE=make
GIT=git
@@ -131,7 +132,7 @@ coverage:
$(NPM) run coverage
codespell:
- $(CODESPELL) -S 'package-lock.json,node_modules,build,coverage'
+ @$(CODESPELL) -S $(WORK_TREE)
lint:
- $(ESLINT) src/lips.js lib/js/bookmark.js
+ $(ESLINT) src/lips.js lib/js/bookmark.js bin/lips.js
diff --git a/README.md b/README.md
index 7ba347e3b..55cef2930 100644
--- a/README.md
+++ b/README.md
@@ -1,13 +1,13 @@
-
[![X (formerly Twitter) Follow](https://img.shields.io/twitter/follow/lips_lang)](https://twitter.com/lips_lang)
[![npm](https://img.shields.io/badge/npm-1.0.0%E2%80%93beta.19-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=master&event=push)](https://github.com/jcubic/lips/actions/workflows/build.yaml)
-[![Coverage Status](https://coveralls.io/repos/github/jcubic/lips/badge.svg?branch=master&80a731f28ad563e153f52942314ee16b)](https://coveralls.io/github/jcubic/lips?branch=master)
+[![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&d99e59bdd4421bb215d5bb781449d63f)](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)
@@ -162,7 +162,7 @@ npm install -g @jcubic/lips@beta
you can run the interpreter from the terminal:
-![LIPS: Scheme interactive terminal](https://github.com/jcubic/lips/blob/master/assets/screencast.gif?raw=true)
+![LIPS: Scheme interactive terminal](https://github.com/jcubic/lips/blob/devel/assets/screencast.gif?raw=true)
You can also run code in a string with:
@@ -201,7 +201,7 @@ Executables also return a S-Expression according to SRFI-176 use `lips --version
## FOSDEM'23 Presentation [Video]
-[![FOSDEM 2023 - LIPS Scheme: Powerful introspection and extensibility](https://github.com/jcubic/lips/blob/master/assets/fosdem-intro.png?raw=true)](https://fosdem.org/2023/schedule/event/lipsscheme/)
+[![FOSDEM 2023 - LIPS Scheme: Powerful introspection and extensibility](https://github.com/jcubic/lips/blob/devel/assets/fosdem-intro.png?raw=true)](https://fosdem.org/2023/schedule/event/lipsscheme/)
## Limitations
@@ -210,7 +210,7 @@ Because LIPS is tree walking interpreter, sometimes it may be slow. Especially i
process long arrays and use callback function. If the array is quite large each piece of code
inside the callback may slow down the processing. For example see:
-script [reference.scm](https://github.com/jcubic/lips/blob/master/scripts/reference.scm)
+script [reference.scm](https://github.com/jcubic/lips/blob/devel/scripts/reference.scm)
That generates reference documentation for all builtin functions and macros.
The slow part is `(names.sort name-compare)` (`Array::sort`) that take quite time to calculate,
@@ -260,8 +260,16 @@ This can happen with React/Preact and when the component returns a Promise. Some
| Custom macro transformers | [SRFI-147](https://srfi.schemers.org/srfi-147/) |
| Version flag | [SRFI-176](https://srfi.schemers.org/srfi-176/) |
| Command line | [SRFI-193](https://srfi.schemers.org/srfi-193/) |
+| Mixing groups of definitions with expressions within bodies | [SRFI-251](https://srfi.schemers.org/srfi-251/) |
-### require `(load "./lib/srfi/.scm")`
+### require manual loading
+
+You can load the SRFI with special syntax that start with `@lips`
+which points to root LIPS directory:
+
+```scheme
+(load "@lips/lib/srfi/.scm")
+```
They should be loaded as R7RS libraries in final 1.0.0 version
@@ -278,8 +286,9 @@ They should be loaded as R7RS libraries in final 1.0.0 version
| Multiple-value boxes | [SRFI-195](https://srfi.schemers.org/srfi-195) |
| Procedures and Syntax for Multiple Values | [SRFI-210](https://srfi.schemers.org/srfi-210/) |
| Evaluating expressions in an unspecified order | [SRFI-236](https://srfi.schemers.org/srfi-236) |
+| Destructuring Lists | [SRFI 239](https://srfi.schemers.org/srfi-239/) |
-in Web (e.g. in Web REPL) you can use URL:
+in Web (e.g. in Web REPL) you can also use full URL:
```scheme
(load "https://cdn.jsdelivr.net/npm/@jcubic/lips@beta/lib/srfi/.scm")
@@ -300,8 +309,7 @@ in Web (e.g. in Web REPL) you can use URL:
* [Brian Lovin](https://brianlovin.com/hn/38819212) (HN clone)
## Projects that use LIPS
-* [Conzept](https://conze.pt) - Topic exploration system for the 21st century (see also their [Twitter account](https://twitter.com/conzept__) and [Command API Documentation](https://conze.pt/guide/command_api)).
-* [Logoi](https://logoi.website/) - a minimalist "superdialect" of the Prolog and Lisp programming languages.
+* [Conzept](https://conze.pt) - Topic exploration system for the 21st century (see also their [Twitter account](https://twitter.com/conzept__) and [Command API Documentation](https://conze.pt/guide/command_api))
## Roadmap
### 1.0
@@ -365,6 +373,8 @@ I would also love to see if you use the library, I may even share the links of p
Special thanks to [Lassi Kortela](https://github.com/lassik) for helping with Scheme code.
+Thanks for [Algolia DocSearch](https://docsearch.algolia.com/) for providing free search on LIPS website.
+
## License
Released under [MIT](http://opensource.org/licenses/MIT) license
diff --git a/bin/lips.js b/bin/lips.js
index f72f1d070..75f9d740d 100755
--- a/bin/lips.js
+++ b/bin/lips.js
@@ -67,8 +67,13 @@ function log_error(message) {
message = message.split('\n').map(line => {
return `${date}: ${line}`;
}).join('\n');
- fs.appendFileSync(path.join(os.homedir(), 'lips.error.log'), message + '\n');
+ fs.appendFileSync(home_file('lips.error.log'), message + '\n');
}
+
+function home_file(filename) {
+ return path.join(os.homedir(), filename);
+}
+
// -----------------------------------------------------------------------------
function debug(message) {
console.log(message);
@@ -122,7 +127,8 @@ function print(result) {
if (last !== undefined) {
try {
const ret = env.get('repr')(last, true);
- console.log('\x1b[K' + ret.toString());
+ process.stdout.write('\x1b[K' + ret.toString());
+ return true;
} catch(e) {
print_error(e, options.t || options.trace);
}
@@ -211,8 +217,9 @@ function log(message) {
}
// -----------------------------------------------------------------------------
-var strace;
-var rl;
+let strace;
+let rl;
+let buffer;
var newline;
const moduleURL = new URL(import.meta.url);
const __dirname = path.dirname(moduleURL.pathname);
@@ -416,21 +423,20 @@ if (options.version || options.V) {
console.log(banner.replace(/(\n\nLIPS.+)/m, entry)); // '
}
var prompt = 'lips> ';
- var continuePrompt = '... ';
+ var continue_prompt = '... ';
var terminal = !!process.stdin.isTTY && !(process.env.EMACS || process.env.INSIDE_EMACS);
+ buffer = make_buffer(process.stdout);
rl = readline.createInterface({
input: process.stdin,
- output: process.stdout,
+ output: buffer,
prompt: prompt,
terminal
});
- rl._writeToOutput = function _writeToOutput(string) {
- rl.output.write(scheme(string));
- };
- process.stdin.on('keypress', (c, k) => {
- setTimeout(function() {
- rl._refreshLine(); // force refresh colors
- }, 0);
+ rl.on('close', () => {
+ setTimeout(() => {
+ rl.setPrompt('');
+ buffer.flush('\n');
+ }, 10);
});
const historySize = Number(env.LIPS_REPL_HISTORY_SIZE);
if (!Number.isNaN(historySize) && historySize > 0) {
@@ -441,12 +447,123 @@ if (options.version || options.V) {
setupHistory(rl, terminal ? env.LIPS_REPL_HISTORY : '', run_repl);
}
-function unify_prompt(a, b) {
- var result = a;
- if (a.length < b.length) {
- result += new Array((b.length - a.length) + 1).join(' ');
+function is_open(token) {
+ return ['(', '['].includes(token);
+}
+
+function is_close(token) {
+ return [')', ']'].includes(token);
+}
+
+function debug_log(filename) {
+ return (message) => {
+ const payload = message.replace(/\n/g, '\\n') + '\n';
+ fs.appendFile(filename, payload, function (err) {
+ if (err) throw err;
+ });
+ };
+}
+
+// buffer Proxy to prevent flicker when Node writes to stdout
+function make_buffer(stream) {
+ const DEBUG = false;
+ const buffer = [];
+ const fname = home_file('lips__debug.log');
+ if (DEBUG) {
+ fs.truncate(fname, 0, () => {});
}
- return result;
+ const log = DEBUG ? debug_log(fname) : () => {};
+ function flush(data, ...args) {
+ if (buffer.length) {
+ const payload = buffer.join('') + data;
+ buffer.length = 0;
+ log(`flush ::: ${payload}`);
+ stream.write(payload, ...args);
+ } else {
+ log('write :::');
+ stream.write(data, ...args);
+ }
+ }
+ return new Proxy(stream, {
+ get(target, prop) {
+ if (prop === 'flush') {
+ return flush;
+ }
+ if (prop === 'write') {
+ return function(data, ...args) {
+ log(data);
+ if (data.match(/\x1b\[(?:1G|0J)|(^(?:lips>|\.\.\.) )/)) {
+ buffer.push(data);
+ log('buffer :::');
+ } else {
+ flush(data, ...args);
+ }
+ }
+ }
+ return target[prop];
+ }
+ });
+}
+
+// find matching open parentheses. The last token is always
+// a closing parenthesis
+function matched_token(code) {
+ try {
+ let count = 0;
+ // true to tokenize return tokens with meta data
+ return tokenize(code, true).reverse().find(token => {
+ if (is_open(token.token)) {
+ count--;
+ } else if (is_close(token.token)) {
+ count++;
+ }
+ return is_open(token.token) && count === 0;
+ });
+ } catch(e) {
+ if (!(e instanceof Parser.Unterminated)) {
+ throw e;
+ }
+ }
+}
+
+// highlight the open parentheses based on token metadata
+function mark_paren(code, token) {
+ const re = /(\x1b\[[0-9;]*m)/;
+ let str_len = 0, found;
+ return code.split(re).reduce((acc, str) => {
+ let result
+ if (str.match(re)) {
+ result = str;
+ } else if (found) {
+ result = str;
+ } else if (str_len + str.length <= token.offset) {
+ result = str;
+ str_len += str.length;
+ } else {
+ const pos = token.offset - str_len;
+ const before = str.substring(0, pos);
+ const after = str.substring(pos + 1);
+ result = `${before}\x1b[7m(\x1b[m${after}`;
+ found = true;
+ }
+ return acc + result;
+ }, '');
+}
+
+// function accept ANSI (syntax highlighted code) and
+// return ANSI escapes to overwrite the code
+// this is needed to make sure that syntax highlighting
+// is always correct
+function ansi_rewrite_above(ansi_code) {
+ const lines = ansi_code.split('\n');
+ const stdout = lines.map((line, i) => {
+ const prefix = i === 0 ? prompt : continue_prompt;
+ return prefix + line;
+ }).join('\x1b[E') + '\x1b[E';
+ const len = lines.length;
+ // overwrite all lines to get rid of any artifacts left my stdin
+ // mostly because of parenthesis matching
+ return `\x1b[${len}F${stdout}`;
}
function run_repl(err, rl) {
@@ -454,6 +571,7 @@ function run_repl(err, rl) {
let cmd = '';
let multiline = false;
let resolve;
+ const brackets_re = /\x1b\[(200|201)~/g;
// we use promise loop to fix issue when copy paste list of S-Expression
let prev_eval = Promise.resolve();
if (process.stdin.isTTY) {
@@ -461,69 +579,134 @@ function run_repl(err, rl) {
}
let prev_line;
const is_emacs = process.env.INSIDE_EMACS;
- function continue_multiline() {
+ function is_brackets_mode() {
+ return !!cmd.match(brackets_re);
+ }
+ function continue_multiline(code) {
multiline = true;
- if (cmd.match(/\x1b\[200~/) || !supports_paste_brackets) {
+ // we don't do indentation for paste bracket mode
+ // indentation will also not work for old Node.js
+ // because it's too problematice to make it right
+ if ((is_brackets_mode() || !supports_paste_brackets)) {
rl.prompt();
if (is_emacs) {
rl.setPrompt('');
} else {
- rl.setPrompt(continuePrompt);
+ rl.setPrompt(continue_prompt);
}
if (terminal) {
- rl.write(' '.repeat(prompt.length - continuePrompt.length));
+ rl.write(' '.repeat(prompt.length - continue_prompt.length));
}
} else {
let ind;
try {
- ind = indent(code, 2, prompt.length - continuePrompt.length);
+ ind = indent(code, 2, prompt.length - continue_prompt.length);
} catch (e) {
ind = 0;
}
- const spaces = new Array(ind + 1).join(' ');
+ const spaces = ' '.repeat(ind);
if (is_emacs) {
rl.setPrompt('');
rl.prompt();
} else {
- rl.setPrompt(continuePrompt);
+ rl.setPrompt(continue_prompt);
rl.prompt();
rl.write(spaces);
}
}
}
+ function char_before_cursor() {
+ return rl.line[rl.cursor - 1];
+ }
+ function format_input_code(code) {
+ if (code) {
+ // we remove trailing newline from code
+ code = code.substring(0, code.length - 1);
+ return scheme(code);
+ }
+ }
+ let prev_token;
+ rl._writeToOutput = function _writeToOutput(string) {
+ function should_update() {
+ return (token || prev_token) && code_above && !string.match(/^[\n\r]+$/);
+ }
+ let token, code_above, code;
+ try {
+ const prefix = multiline ? continue_prompt : prompt;
+ const current_line = prefix + rl.line;
+ code = scheme(string);
+ const bracket_mode = cmd.match(brackets_re);
+ const full_copy_paste = bracket_mode?.length == 2;
+ if ((!bracket_mode || full_copy_paste) && !is_emacs) {
+ // clean bracket mode markers
+ const clean_cmd = cmd.replace(brackets_re, '');
+ code_above = format_input_code(clean_cmd);
+ if (char_before_cursor() === ')') {
+ const substring = rl.line.substring(0, rl.cursor);
+ const input = prefix + substring;
+ token = matched_token(input);
+ if (token) {
+ code = mark_paren(code, token);
+ } else if (clean_cmd) {
+ const input = clean_cmd + substring;
+ // we match paren above the current line
+ // but we need whole code with rl.line
+ // so we need to ignore rl.line
+ token = matched_token(input);
+ if (token) {
+ // code_above don't include the current line that
+ // is added after user press enter
+ code_above = mark_paren(code_above, token);
+ }
+ }
+ }
+ if (should_update()) {
+ // overwrite lines above the cursor this is side effect
+ process.stdout.write('\x1b7' + ansi_rewrite_above(code_above) + '\x1b8');
+ }
+ prev_token = token;
+ }
+ // this always need to be executed inside rl._writeToOutput
+ // even if nothing changes, this make sure that the input
+ // stay intact while editing the command line
+ rl.output.write(code);
+ } catch(e) {
+ console.error(e);
+ }
+ };
+ process.stdin.on('keypress', (c, k) => {
+ setTimeout(function() {
+ // we force triggering rl._writeToOutput function
+ // so we have the change to syntax highlight the command line
+ // this needs to happen on next tick so the string have time
+ // to updated with a given key
+ rl._refreshLine();
+ }, 0);
+ });
bootstrap(interp).then(function() {
if (supports_paste_brackets) {
+ // this make sure that the paste brackets ANSI escape
+ // is added to cmd so they can be processed in 'line' event
process.stdin.on('keypress', (c, k) => {
if (k?.name?.match(/^paste-/)) {
cmd += k.sequence;
}
});
+ // enable paste bracket mode by the terminal
process.stdout.write('\x1b[?2004h');
}
- const re = /\x1b\[(200|201)~/g;
rl.on('line', function(line) {
- cmd += line;
- if (cmd.match(/\x1b\[201~$/)) {
- cmd = cmd.replace(re, '');
- }
- const code = cmd.replace(re, '');
- const lines = code.split('\n');
- if (terminal) {
- const stdout = scheme(code).split('\n').map((line, i) => {
- let prefix;
- if (i === 0) {
- prefix = unify_prompt(prompt, continuePrompt);
- } else {
- prefix = unify_prompt(continuePrompt, prompt);
- }
- return '\x1b[K' + prefix + line;
- }).join('\n');
- let num = lines.length;
- const format = `\x1b[${num}F${stdout}\n`;
- process.stdout.write(format);
- }
- cmd += '\n';
try {
+ cmd += line;
+ const code = cmd.replace(brackets_re, '');
+ if (cmd.match(/\x1b\[201~$/)) {
+ cmd = code;
+ }
+ if (terminal) {
+ const output = ansi_rewrite_above(scheme(code));
+ process.stdout.write(output);
+ }
+ cmd += '\n';
if (balanced_parenthesis(code)) {
// we need to clear the prompt because resume
// is adding the prompt that was present when pause was called
@@ -536,11 +719,10 @@ function run_repl(err, rl) {
return result;
}).then(function(result) {
if (process.stdin.isTTY) {
- print(result);
- if (newline || is_emacs) {
+ if (print(result) || newline) {
// readline doesn't work with not ended lines
// it ignore those, so we end them ourselves
- process.stdout.write("\n");
+ process.stdout.write('\n');
newline = false;
}
if (multiline) {
@@ -559,7 +741,7 @@ function run_repl(err, rl) {
rl.resume();
});
} else {
- continue_multiline();
+ continue_multiline(code);
}
} catch (e) {
console.error(e.message);
diff --git a/dist/lips.cjs b/dist/lips.cjs
index b8fc51190..e64df1374 100644
--- a/dist/lips.cjs
+++ b/dist/lips.cjs
@@ -4,7 +4,7 @@
* | | \ \ | | | || . \/ __> | |
* | | > \ | |_ | || _/\__ \ | |
* | | / ^ \ |___||_||_| <___/ | |
- * \_\ /_/ \_\ /_/ v. 1.0.0-beta.19
+ * \_\ /_/ \_\ /_/ v. DEV
*
* LIPS is Pretty Simple - Scheme based Powerful LISP in JavaScript
*
@@ -31,7 +31,7 @@
* Copyright (c) 2014-present, Facebook, Inc.
* released under MIT license
*
- * build: Mon, 27 May 2024 11:41:47 +0000
+ * build: Fri, 08 Nov 2024 13:26:12 +0000
*/
'use strict';
@@ -105,6 +105,10 @@ function _construct(t, e, r) {
return r && _setPrototypeOf(p, r.prototype), p;
}
+function _readOnlyError(name) {
+ throw new TypeError("\"" + name + "\" is read-only");
+}
+
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
@@ -3502,25 +3506,23 @@ function contentLoaded(win, fn) {
}
}
// -------------------------------------------------------------------------
-/* eslint-disable */
/* c8 ignore next 13 */
function log(x) {
- if (is_debug()) {
- if (is_plain_object(x)) {
- console.log(map_object(x, function (value) {
- return toString(value, true);
- }));
- } else {
- var _console;
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- args[_key - 1] = arguments[_key];
- }
- (_console = console).log.apply(_console, [toString(x, true)].concat(_toConsumableArray(args.map(function (item) {
- return toString(item, true);
- }))));
- }
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ args[_key - 1] = arguments[_key];
+ }
+ if (is_plain_object(x) && is_debug(args[0])) {
+ console.log(map_object(x, function (value) {
+ return toString(value, true);
+ }));
+ } else if (is_debug()) {
+ var _console;
+ (_console = console).log.apply(_console, [toString(x, true)].concat(_toConsumableArray(args.map(function (item) {
+ return toString(item, true);
+ }))));
}
}
+/* eslint-enable */
// ----------------------------------------------------------------------
/* c8 ignore next */
function is_debug() {
@@ -3909,8 +3911,25 @@ function parse_string(string) {
}
// ----------------------------------------------------------------------
function parse_symbol(arg) {
- if (arg.match(/^\|.*\|$/)) {
- arg = arg.replace(/(^\|)|(\|$)/g, '');
+ arg.match(/^name/);
+ var re = /(^|.)\|/g;
+ if (arg.match(re)) {
+ // handle escaped bar and escaped slash
+ arg = arg.split('|').filter(Boolean).reduce(function (acc, str) {
+ var result = '';
+ if (str.match(/^\\+$/)) {
+ if (str.length > 1) {
+ var count = Math.floor(str.length / 2);
+ result = '\\'.repeat(count);
+ }
+ if (str.length % 2 !== 0) {
+ result += '|';
+ }
+ } else {
+ result = str;
+ }
+ return acc + result;
+ });
var chars = {
t: '\t',
r: '\r',
@@ -3918,8 +3937,8 @@ function parse_symbol(arg) {
};
arg = arg.replace(/\\(x[^;]+);/g, function (_, chr) {
return String.fromCharCode(parseInt('0' + chr, 16));
- }).replace(/\\(.)/g, function (_, chr) {
- return chars[chr] || chr;
+ }).replace(/\\([trn])/g, function (_, chr) {
+ return chars[chr];
});
}
return new LSymbol(arg);
@@ -4220,6 +4239,18 @@ var gensym = function () {
return with_props(count, Symbol("#:g".concat(count)));
};
}();
+// ----------------------------------------------------------------------
+// :: helper function that make symbols in names array hygienic
+// ----------------------------------------------------------------------
+function hygienic_begin(envs, expr) {
+ var begin = global_env.get('begin');
+ var g_begin = gensym('begin');
+ envs.forEach(function (env) {
+ env.set(g_begin, begin);
+ });
+ return new Pair(g_begin, expr);
+}
+
// ----------------------------------------------------------------------
// Class used to escape promises: feature #54
// ----------------------------------------------------------------------
@@ -4517,6 +4548,11 @@ var Lexer = /*#__PURE__*/function () {
var found = this.next_token();
if (found) {
this._token = this.__input__.substring(this._i, this._next);
+ if (!this.__token__) {
+ // handle case when accessing __token__ from the syntax extension
+ // (e.g. string interpolation) as the first expression in a REPL
+ read_only(this, '__token__', this.token(true));
+ }
return this.token(meta);
}
return eof;
@@ -4765,6 +4801,7 @@ Lexer.regex_class = Symbol["for"]('regex_class');
Lexer.character = Symbol["for"]('character');
Lexer.bracket = Symbol["for"]('bracket');
Lexer.b_symbol = Symbol["for"]('b_symbol');
+Lexer.b_symbol_ex = Symbol["for"]('b_symbol_ex');
Lexer.b_comment = Symbol["for"]('b_comment');
Lexer.i_comment = Symbol["for"]('i_comment');
Lexer.l_datum = Symbol["for"]('l_datum');
@@ -4795,7 +4832,7 @@ Lexer._rules = [
// for dot comma `(a .,b)
[/\./, Lexer.boundary, /,/, null, null],
// block symbols
-[/\|/, null, null, null, Lexer.b_symbol], [/\s/, null, null, Lexer.b_symbol, Lexer.b_symbol], [/\|/, null, Lexer.boundary, Lexer.b_symbol, null]];
+[/\|/, null, null, null, Lexer.b_symbol], [/\s/, null, null, Lexer.b_symbol, Lexer.b_symbol], [/\|/, null, Lexer.boundary, Lexer.b_symbol, null], [/\|/, null, /\S/, Lexer.b_symbol, Lexer.b_symbol_ex], [/\S/, null, Lexer.boundary, Lexer.b_symbol_ex, null]];
// ----------------------------------------------------------------------
Lexer._brackets = [[/[()[\]]/, null, null, null, null]];
// ----------------------------------------------------------------------
@@ -4897,17 +4934,16 @@ var Parser = /*#__PURE__*/function () {
_createClass(Parser, [{
key: "_with_syntax_scope",
value: function _with_syntax_scope(fn) {
- var _this5 = this;
// expose parser and change stdin so parser extension can use current-input
// to read data from the parser stream #150
var internal = get_internal(this.__env__);
var stdin = internal.get('stdin');
- this.__env__.set('lips', _objectSpread(_objectSpread({}, lips), {}, {
+ global_env.set('lips', _objectSpread(_objectSpread({}, lips), {}, {
__parser__: this
}));
internal.set('stdin', new ParserInputPort(this, this.__env__));
var cleanup = function cleanup() {
- _this5.__env__.set('lips', lips);
+ global_env.set('lips', lips);
internal.set('stdin', stdin);
};
return unpromise(fn(), function (result) {
@@ -5246,7 +5282,7 @@ var Parser = /*#__PURE__*/function () {
key: "_resolve_object",
value: function () {
var _resolve_object2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(object) {
- var _this6 = this;
+ var _this5 = this;
var result;
return _regeneratorRuntime.wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
@@ -5256,7 +5292,7 @@ var Parser = /*#__PURE__*/function () {
break;
}
return _context6.abrupt("return", object.map(function (item) {
- return _this6._resolve_object(item);
+ return _this5._resolve_object(item);
}));
case 2:
if (!is_plain_object(object)) {
@@ -5265,7 +5301,7 @@ var Parser = /*#__PURE__*/function () {
}
result = {};
Object.keys(object).forEach(function (key) {
- result[key] = _this6._resolve_object(object[key]);
+ result[key] = _this5._resolve_object(object[key]);
});
return _context6.abrupt("return", result);
case 6:
@@ -5340,7 +5376,7 @@ var Parser = /*#__PURE__*/function () {
key: "_read_object",
value: function () {
var _read_object3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() {
- var _this7 = this;
+ var _this6 = this;
var token, special, builtin, expr, extension, is_symbol, was_close_paren, object, args, result, ref, ref_label;
return _regeneratorRuntime.wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
@@ -5418,8 +5454,8 @@ var Parser = /*#__PURE__*/function () {
}
return _context8.abrupt("return", this._with_syntax_scope(function () {
return call_function(extension, is_symbol ? [] : args, {
- env: _this7.__env__,
- dynamic_env: _this7.__env__,
+ env: _this6.__env__,
+ dynamic_env: _this6.__env__,
use_dynamic: false
});
}));
@@ -5454,7 +5490,7 @@ var Parser = /*#__PURE__*/function () {
}
_context8.next = 44;
return this._with_syntax_scope(function () {
- return _this7.evaluate(expr);
+ return _this6.evaluate(expr);
});
case 44:
result = _context8.sent;
@@ -6191,7 +6227,7 @@ function keywords_re() {
return new RegExp("^(?:#:)?(?:".concat(args.join('|'), ")$"));
}
// line breaking rules
-Formatter.rules = [[[sexp], 0, not_close], [[p_o, keywords_re('begin', 'cond-expand')], 1], [[p_o, let_re, symbol, p_o, let_value, p_e], 1], [[p_o, let_re, symbol, sexp_or_atom], 1, not_close], [[p_o, let_re, p_o, let_value], 1, not_close], [[p_o, keywords_re('define-syntax'), /.+/], 1], [[p_o, syntax_rules, not_p, identifiers], 1], [[p_o, syntax_rules, not_p, identifiers, sexp], 1, not_close], [[p_o, syntax_rules, identifiers], 1], [[p_o, syntax_rules, identifiers, sexp], 1, not_close], [[p_o, non_def, new Pattern([/[^()[\]]/], '+'), sexp], 1, not_close], [[p_o, sexp], 1, not_close], [[p_o, not_p, sexp], 1, not_close], [[p_o, keywords_re('lambda', 'if'), not_p], 1, not_close], [[p_o, keywords_re('while'), not_p, sexp], 1, not_close], [[p_o, keywords_re('if'), not_p, glob], 1], [[p_o, def_lambda_re, identifiers], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re, sexp], 0, not_close], [[p_o, def_lambda_re, identifiers, sexp], 0, not_close]];
+Formatter.rules = [[[sexp], 0, not_close], [[p_o, keywords_re('begin', 'cond-expand')], 1, not_close], [[p_o, let_re, symbol, p_o, let_value, p_e], 1, not_close], [[p_o, let_re, symbol, sexp_or_atom], 1, not_close], [[p_o, let_re, p_o, let_value], 1, not_close], [[p_o, keywords_re('define-syntax'), /.+/], 1], [[p_o, syntax_rules, not_p, identifiers], 1], [[p_o, syntax_rules, not_p, identifiers, sexp], 1, not_close], [[p_o, syntax_rules, identifiers], 1], [[p_o, syntax_rules, identifiers, sexp], 1, not_close], [[p_o, non_def, new Pattern([/[^()[\]]/], '+'), sexp], 1, not_close], [[p_o, sexp], 1, not_close], [[p_o, not_p, sexp], 1, not_close], [[p_o, keywords_re('lambda', 'if'), not_p], 1, not_close], [[p_o, keywords_re('while'), not_p, sexp], 1, not_close], [[p_o, keywords_re('if'), not_p, glob], 1, not_close], [[p_o, def_lambda_re, identifiers], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re, sexp], 0, not_close], [[p_o, def_lambda_re, identifiers, sexp], 0, not_close]];
// ----------------------------------------------------------------------
Formatter.prototype["break"] = function () {
var code = this.__code__.replace(/\n[ \t]*/g, '\n ').replace(/^\s+/, '');
@@ -8156,7 +8192,7 @@ function user_repr(obj) {
// if key is Object it should only work for plain_object
// because otherwise it will match every object
// we don't use instanceof so it don't work for subclasses
- if (obj instanceof key && (key === Object && plain_object && !iterator || key !== Object)) {
+ if (constructor === key && (key === Object && plain_object && !iterator || key !== Object)) {
fn = value;
}
});
@@ -8363,6 +8399,9 @@ function toString(obj, quote, skip_cycles) {
if (type(obj) === 'instance') {
if (is_lambda(constructor) && constructor.__name__) {
name = constructor.__name__.valueOf();
+ if (_typeof$1(name) === 'symbol') {
+ name = name.toString().replace(/^Symbol\((?:#:)?([^\)]+)\)$/, '$1');
+ }
} else if (!is_native_function(constructor)) {
name = 'instance';
}
@@ -9083,8 +9122,13 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
log(symbols);
/* eslint-disable complexity */
function traverse(pattern, code) {
- var pattern_names = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
- var ellipsis = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
+ var state = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+ var _state$ellipsis = state.ellipsis,
+ ellipsis = _state$ellipsis === void 0 ? false : _state$ellipsis,
+ _state$trailing = state.trailing,
+ trailing = _state$trailing === void 0 ? false : _state$trailing,
+ _state$pattern_names = state.pattern_names,
+ pattern_names = _state$pattern_names === void 0 ? [] : _state$pattern_names;
log({
code: code,
pattern: pattern
@@ -9092,13 +9136,15 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
if (is_atom(pattern) && !(pattern instanceof LSymbol)) {
return same_atom(pattern, code);
}
- if (pattern instanceof LSymbol && symbols.includes(pattern.literal())) {
- // TODO: literal() may be SLOW
- if (!LSymbol.is(code, pattern)) {
- return false;
+ if (pattern instanceof LSymbol) {
+ var literal = pattern.literal(); // TODO: literal() may be SLOW
+ if (symbols.includes(literal)) {
+ if (!LSymbol.is(code, literal) && !LSymbol.is(pattern, code)) {
+ return false;
+ }
+ var ref = expansion.ref(literal);
+ return !ref || ref === define || ref === global_env;
}
- var ref = expansion.ref(pattern);
- return !ref || ref === define || ref === global_env;
}
if (Array.isArray(pattern) && Array.isArray(code)) {
log('<<< a 1');
@@ -9124,25 +9170,29 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
} else if (Array.isArray(pattern[0])) {
log('<<< a 3');
var _names = _toConsumableArray(pattern_names);
+ var new_state = _objectSpread(_objectSpread({}, state), {}, {
+ pattern_names: _names,
+ ellipsis: true
+ });
if (!code.every(function (node) {
- return traverse(pattern[0], node, _names, true);
+ return traverse(pattern[0], node, new_state);
})) {
return false;
}
}
if (pattern.length > 2) {
var pat = pattern.slice(2);
- return traverse(pat, code.slice(-pat.length), pattern_names, ellipsis);
+ return traverse(pat, code.slice(-pat.length), state);
}
return true;
}
- var first = traverse(pattern[0], code[0], pattern_names, ellipsis);
+ var first = traverse(pattern[0], code[0], state);
log({
first: first,
pattern: pattern[0],
code: code[0]
});
- var rest = traverse(pattern.slice(1), code.slice(1), pattern_names, ellipsis);
+ var rest = traverse(pattern.slice(1), code.slice(1), state);
log({
first: first,
rest: rest
@@ -9166,23 +9216,30 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
}
}
if (is_pair(pattern) && is_pair(pattern.cdr) && LSymbol.is(pattern.cdr.car, ellipsis_symbol)) {
+ log('>> 1 (a)');
// pattern (... ???) - SRFI-46
if (!is_nil(pattern.cdr.cdr)) {
if (is_pair(pattern.cdr.cdr)) {
+ log('>> 1 (b)');
// if we have (x ... a b) we need to remove two from the end
var list_len = pattern.cdr.cdr.length();
+ var improper_list = !is_nil(pattern.last_pair().cdr);
if (!is_pair(code)) {
return false;
}
var code_len = code.length();
var list = code;
- while (code_len - 1 > list_len) {
+ var _trailing = improper_list ? 1 : 1;
+ while (code_len - _trailing > list_len) {
list = list.cdr;
code_len--;
}
var _rest5 = list.cdr;
list.cdr = _nil;
- if (!traverse(pattern.cdr.cdr, _rest5, pattern_names, ellipsis)) {
+ var new_sate = _objectSpread(_objectSpread({}, state), {}, {
+ trailing: improper_list
+ });
+ if (!traverse(pattern.cdr.cdr, _rest5, new_sate)) {
return false;
}
}
@@ -9192,7 +9249,7 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
if (bindings['...'].symbols[_name3] && !pattern_names.includes(_name3) && !ellipsis) {
throw new Error('syntax: named ellipsis can only appear onces');
}
- log('>> 1');
+ log('>> 1 (next)');
if (is_nil(code)) {
log('>> 2');
if (ellipsis) {
@@ -9223,6 +9280,7 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
} else {
log('>> 6');
if (is_pair(code)) {
+ log('>> 7 ' + ellipsis);
// cons (a . b) => (var ... . x)
if (!is_pair(code.cdr) && !is_nil(code.cdr)) {
log('>> 7 (b)');
@@ -9230,28 +9288,34 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
return false;
} else if (!bindings['...'].symbols[_name3]) {
bindings['...'].symbols[_name3] = new Pair(code.car, _nil);
- return traverse(pattern.cdr.cdr, code.cdr);
+ return traverse(pattern.cdr.cdr, code.cdr, state);
}
}
// code as improper list
var last_pair = code.last_pair();
+ log({
+ last_pair: last_pair
+ });
if (!is_nil(last_pair.cdr)) {
+ log('>> 7 (c)');
if (is_nil(pattern.cdr.cdr)) {
// case (a ...) for (a b . x)
return false;
} else {
+ log('>> 7 (d)');
// case (a ... . b) for (a b . x)
var copy = code.clone();
copy.last_pair().cdr = _nil;
bindings['...'].symbols[_name3] = copy;
- return traverse(pattern.cdr.cdr, last_pair.cdr);
+ return traverse(pattern.cdr.cdr, last_pair.cdr, state);
}
}
- log('>> 7 ' + ellipsis);
pattern_names.push(_name3);
if (!bindings['...'].symbols[_name3]) {
+ log('>> 7 (e)');
bindings['...'].symbols[_name3] = new Pair(code, _nil);
} else {
+ log('>> 7 (f)');
var _node2 = bindings['...'].symbols[_name3];
bindings['...'].symbols[_name3] = _node2.append(new Pair(code, _nil));
}
@@ -9262,7 +9326,7 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
// empty ellipsis with rest (a b ... . d) #290
log('>> 8');
bindings['...'].symbols[_name3] = null;
- return traverse(pattern.cdr.cdr, code);
+ return traverse(pattern.cdr.cdr, code, state);
} else {
log('>> 9');
return false;
@@ -9279,8 +9343,12 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
}
log('>> 11');
var _node3 = code;
+ var _new_state = _objectSpread(_objectSpread({}, state), {}, {
+ pattern_names: names,
+ ellipsis: true
+ });
while (is_pair(_node3)) {
- if (!traverse(pattern.car, _node3.car, names, true)) {
+ if (!traverse(pattern.car, _node3.car, _new_state)) {
return false;
}
_node3 = _node3.cdr;
@@ -9290,8 +9358,12 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
if (Array.isArray(pattern.car)) {
var names = _toConsumableArray(pattern_names);
var _node4 = code;
+ var _new_state2 = _objectSpread(_objectSpread({}, state), {}, {
+ pattern_names: names,
+ ellipsis: true
+ });
while (is_pair(_node4)) {
- if (!traverse(pattern.car, _node4.car, names, true)) {
+ if (!traverse(pattern.car, _node4.car, _new_state2)) {
return false;
}
_node4 = _node4.cdr;
@@ -9326,15 +9398,29 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
code: code,
pattern: pattern
});
+ var rest_pattern = pattern.car instanceof LSymbol && pattern.cdr instanceof LSymbol;
+ if (trailing && rest_pattern) {
+ log('>> 13 (a)');
+ // handle (x ... y . z)
+ if (!is_nil(code.cdr)) {
+ return false;
+ }
+ var _car = pattern.car.valueOf();
+ var _cdr = pattern.cdr.valueOf();
+ bindings.symbols[_car] = code.car;
+ bindings.symbols[_cdr] = _nil;
+ return true;
+ //return is_pair(code.cdr) && code.cdr.length() > 1;
+ }
if (is_nil(code.cdr)) {
+ log('>> 13 (b)');
// last item in in call using in recursive calls on
// last element of the list
// case of pattern (p . rest) and code (0)
- var rest_pattern = pattern.car instanceof LSymbol && pattern.cdr instanceof LSymbol;
if (rest_pattern) {
// fix for SRFI-26 in recursive call of (b) ==> (<> . x)
// where <> is symbol
- if (!traverse(pattern.car, code.car, pattern_names, ellipsis)) {
+ if (!traverse(pattern.car, code.car, state)) {
return false;
}
log('>> 14');
@@ -9354,7 +9440,10 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
code: code
});
// case (x y) ===> (var0 var1 ... warn) where var1 match nil
- if (is_pair(pattern.cdr) && is_pair(pattern.cdr.cdr) && pattern.cdr.car instanceof LSymbol && LSymbol.is(pattern.cdr.cdr.car, ellipsis_symbol) && is_pair(pattern.cdr.cdr.cdr) && !LSymbol.is(pattern.cdr.cdr.cdr.car, ellipsis_symbol) && traverse(pattern.car, code.car, pattern_names, ellipsis) && traverse(pattern.cdr.cdr.cdr, code.cdr, pattern_names, ellipsis)) {
+ // trailing: true start processing of (var ... x . y)
+ if (is_pair(pattern.cdr) && is_pair(pattern.cdr.cdr) && pattern.cdr.car instanceof LSymbol && LSymbol.is(pattern.cdr.cdr.car, ellipsis_symbol) && is_pair(pattern.cdr.cdr.cdr) && !LSymbol.is(pattern.cdr.cdr.cdr.car, ellipsis_symbol) && traverse(pattern.car, code.car, state) && traverse(pattern.cdr.cdr.cdr, code.cdr, _objectSpread(_objectSpread({}, state), {}, {
+ trailing: true
+ }))) {
var _name6 = pattern.cdr.car.__name__;
log({
pattern: pattern,
@@ -9372,15 +9461,14 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
pattern: pattern,
code: code
});
- var car = traverse(pattern.car, code.car, pattern_names, ellipsis);
- log({
- car: car,
- pattern: pattern.car,
- code: code.car
- });
- var cdr = traverse(pattern.cdr, code.cdr, pattern_names, ellipsis);
+ var car = traverse(pattern.car, code.car, state);
+ var cdr = traverse(pattern.cdr, code.cdr, state);
log({
+ $car_code: code.car,
+ $car_pattern: pattern.car,
car: car,
+ $cdr_code: code.cdr,
+ $cdr_pattern: pattern.cdr,
cdr: cdr
});
if (car && cdr) {
@@ -9573,46 +9661,47 @@ function transform_syntax() {
var item = bindings[_name7];
if (item === null) {
return;
- } else if (item) {
+ } else if (_name7 in bindings) {
log({
name: _name7,
binding: bindings[_name7]
});
if (is_pair(item)) {
log('[t 2 Pair ' + nested);
- var _car = item.car,
- _cdr = item.cdr;
+ var _car2 = item.car,
+ _cdr2 = item.cdr;
var _rest_expr = is_array ? expr.slice(2) : expr.cdr.cdr;
if (nested) {
- if (!is_nil(_cdr)) {
+ if (!is_nil(_cdr2)) {
log('|| next 1');
- next(_name7, _cdr);
+ next(_name7, _cdr2);
}
if (is_array && _rest_expr.length || !is_nil(_rest_expr) && !is_array) {
var _rest7 = transform_ellipsis_expr(_rest_expr, bindings, state, next);
if (is_array) {
- return _car.concat(_rest7);
- } else if (is_pair(_car)) {
- return _car.append(_rest7);
+ return _car2.concat(_rest7);
+ } else if (is_pair(_car2)) {
+ return _car2.append(_rest7);
} else {
log('UNKNOWN');
}
}
- return _car;
- } else if (is_pair(_car)) {
- if (!is_nil(_car.cdr)) {
+ return _car2;
+ } else if (is_pair(_car2)) {
+ if (!is_nil(_car2.cdr)) {
log('|| next 2');
- next(_name7, new Pair(_car.cdr, _cdr));
+ next(_name7, new Pair(_car2.cdr, _cdr2));
}
- return _car.car;
- } else if (is_nil(_cdr)) {
- return _car;
+ // wrap with Value to handle undefined
+ return new Value(_car2.car);
+ } else if (is_nil(_cdr2)) {
+ return _car2;
} else {
var last_pair = expr.last_pair();
if (last_pair.cdr instanceof LSymbol) {
log('|| next 3');
next(_name7, item.last_pair());
- return _car;
+ return _car2;
}
}
} else if (item instanceof Array) {
@@ -9675,6 +9764,7 @@ function transform_syntax() {
return expr;
}
if (is_pair(expr) || is_array) {
+ log('>> 0');
var first = is_array ? expr[0] : expr.car;
var second, rest_second;
if (is_array) {
@@ -9759,6 +9849,9 @@ function transform_syntax() {
// undefined can be null caused by null binding
// on empty ellipsis
if (car !== undefined) {
+ if (car instanceof Value) {
+ car.valueOf(), _readOnlyError("car");
+ }
if (is_spread) {
if (is_array) {
if (Array.isArray(car)) {
@@ -9815,6 +9908,9 @@ function transform_syntax() {
nested: true
});
if (car) {
+ if (car instanceof Value) {
+ car.valueOf(), _readOnlyError("car");
+ }
return new Pair(car, _nil);
}
return _nil;
@@ -9853,6 +9949,9 @@ function transform_syntax() {
value: value
});
if (typeof value !== 'undefined') {
+ if (value instanceof Value) {
+ value = value.valueOf();
+ }
if (is_array) {
_result3.push(value);
} else {
@@ -9893,6 +9992,9 @@ function transform_syntax() {
}
}
log('<<<< 2');
+ log({
+ result: _result3
+ });
return _result3;
}
}
@@ -10026,8 +10128,12 @@ function is_undef(value) {
return typeof value === 'undefined';
}
// -------------------------------------------------------------------------
+function get_proto(obj) {
+ return Object.getPrototypeOf(obj);
+}
+// -------------------------------------------------------------------------
function is_iterator(obj, symbol) {
- if (has_own_symbol(obj, symbol) || has_own_symbol(obj.__proto__, symbol)) {
+ if (has_own_symbol(obj, symbol) || has_own_symbol(get_proto(obj), symbol)) {
return is_function(obj[symbol]);
}
}
@@ -10322,8 +10428,7 @@ function let_macro(symbol) {
return pair.cdr.car;
});
}
- var args_name = gensym('args');
- return Pair.fromArray([LSymbol('let'), [[args_name, Pair(LSymbol('list'), args)]], [LSymbol('letrec'), [[code.car, Pair(LSymbol('lambda'), Pair(params, code.cdr.cdr))]], [LSymbol('apply'), code.car, args_name]]]);
+ return new Pair(Pair.fromArray([LSymbol('letrec'), [[code.car, Pair(LSymbol('lambda'), Pair(params, code.cdr.cdr))]], code.car]), args);
} else if (macro_expand) {
// Macro.defmacro are special macros that should return lips code
// here we use evaluate, so we need to check special flag set by
@@ -10341,7 +10446,7 @@ function let_macro(symbol) {
}
var i = 0;
function exec() {
- var output = new Pair(new LSymbol('begin'), code.cdr);
+ var output = hygienic_begin([env], code.cdr);
return _evaluate(output, {
env: env,
dynamic_env: env,
@@ -10461,7 +10566,7 @@ function guard_math_call(fn) {
}
// ----------------------------------------------------------------------
function pipe() {
- var _this8 = this;
+ var _this7 = this;
for (var _len8 = arguments.length, fns = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
fns[_key8] = arguments[_key8];
}
@@ -10473,7 +10578,7 @@ function pipe() {
args[_key9] = arguments[_key9];
}
return fns.reduce(function (args, f) {
- return [f.apply(_this8, args)];
+ return [f.apply(_this7, args)];
}, args)[0];
};
}
@@ -10538,7 +10643,7 @@ function curry(fn) {
typecheck('curry', fn, 'function');
var len = fn.length;
return function () {
- var _this9 = this;
+ var _this8 = this;
var args = init_args.slice();
// HACK: we use IIFE here to get rid of the name of the function.
// The JavaScript is smart and add name property to a function
@@ -10551,7 +10656,7 @@ function curry(fn) {
}
args = args.concat(more_args);
if (args.length >= len) {
- return fn.apply(_this9, args);
+ return fn.apply(_this8, args);
} else {
return curried;
}
@@ -11614,9 +11719,9 @@ LComplex.prototype.mul = function (n) {
};
// -------------------------------------------------------------------------
LComplex.prototype.complex_op = function (name, n, fn) {
- var _this10 = this;
+ var _this9 = this;
var calc = function calc(re, im) {
- var result = fn(_this10.__re__, re, _this10.__im__, im);
+ var result = fn(_this9.__re__, re, _this9.__im__, im);
if ('im' in result && 're' in result) {
if (result.im.cmp(0) === 0) {
return result.re;
@@ -12212,7 +12317,7 @@ LComplex.i = LComplex({
// :: Port abstraction - read should be a function that return next line
// -------------------------------------------------------------------------
function InputPort(read) {
- var _this11 = this;
+ var _this10 = this;
var env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : global_env;
if (typeof this !== 'undefined' && !(this instanceof InputPort) || typeof this === 'undefined') {
return new InputPort(read);
@@ -12236,12 +12341,12 @@ function InputPort(read) {
return _regeneratorRuntime.wrap(function _callee14$(_context14) {
while (1) switch (_context14.prev = _context14.next) {
case 0:
- if (_this11.char_ready()) {
+ if (_this10.char_ready()) {
_context14.next = 6;
break;
}
_context14.next = 3;
- return _this11._read();
+ return _this10._read();
case 3:
line = _context14.sent;
parser = new Parser({
@@ -12249,7 +12354,7 @@ function InputPort(read) {
});
parser.parse(line);
case 6:
- return _context14.abrupt("return", _this11.__parser__);
+ return _context14.abrupt("return", _this10.__parser__);
case 7:
case "end":
return _context14.stop();
@@ -12312,13 +12417,13 @@ InputPort.prototype.is_open = function () {
return this._with_parser !== null;
};
InputPort.prototype.close = function () {
- var _this12 = this;
+ var _this11 = this;
this.__parser__ = null;
// make content garbage collected, we assign null,
// because the value is in prototype
this._with_parser = null;
['read', 'close', 'read_char', 'peek-char', 'read_line'].forEach(function (name) {
- _this12[name] = function () {
+ _this11[name] = function () {
throw new Error('input-port: port is closed');
};
});
@@ -12364,20 +12469,20 @@ OutputPort.prototype.toString = function () {
var BufferedOutputPort = /*#__PURE__*/function (_OutputPort) {
_inherits(BufferedOutputPort, _OutputPort);
function BufferedOutputPort(fn) {
- var _this13;
+ var _this12;
_classCallCheck(this, BufferedOutputPort);
- _this13 = _callSuper(this, BufferedOutputPort, [function () {
- var _this14;
- return (_this14 = _this13)._write.apply(_this14, arguments);
+ _this12 = _callSuper(this, BufferedOutputPort, [function () {
+ var _this13;
+ return (_this13 = _this12)._write.apply(_this13, arguments);
}]);
typecheck('BufferedOutputPort', fn, 'function');
- read_only(_assertThisInitialized(_this13), '_fn', fn, {
+ read_only(_assertThisInitialized(_this12), '_fn', fn, {
hidden: true
});
- read_only(_assertThisInitialized(_this13), '_buffer', [], {
+ read_only(_assertThisInitialized(_this12), '_buffer', [], {
hidden: true
});
- return _this13;
+ return _this12;
}
_createClass(BufferedOutputPort, [{
key: "flush",
@@ -12390,13 +12495,13 @@ var BufferedOutputPort = /*#__PURE__*/function (_OutputPort) {
}, {
key: "_write",
value: function _write() {
- var _this15 = this;
+ var _this14 = this;
for (var _len18 = arguments.length, args = new Array(_len18), _key18 = 0; _key18 < _len18; _key18++) {
args[_key18] = arguments[_key18];
}
if (args.length) {
args.forEach(function (arg) {
- _this15._buffer.push(arg);
+ _this14._buffer.push(arg);
});
var last_value = this._buffer[this._buffer.length - 1];
if (last_value.match(/\n$/)) {
@@ -12409,7 +12514,7 @@ var BufferedOutputPort = /*#__PURE__*/function (_OutputPort) {
return BufferedOutputPort;
}(OutputPort); // -------------------------------------------------------------------------
function OutputStringPort(toString) {
- var _this16 = this;
+ var _this15 = this;
if (typeof this !== 'undefined' && !(this instanceof OutputStringPort) || typeof this === 'undefined') {
return new OutputStringPort(toString);
}
@@ -12422,7 +12527,7 @@ function OutputStringPort(toString) {
} else {
x = x.valueOf();
}
- _this16.__buffer__.push(x);
+ _this15.__buffer__.push(x);
};
}
OutputStringPort.prototype = Object.create(OutputPort.prototype);
@@ -12437,7 +12542,7 @@ OutputStringPort.prototype.valueOf = function () {
};
// -------------------------------------------------------------------------
function OutputFilePort(filename, fd) {
- var _this17 = this;
+ var _this16 = this;
if (typeof this !== 'undefined' && !(this instanceof OutputFilePort) || typeof this === 'undefined') {
return new OutputFilePort(filename, fd);
}
@@ -12453,7 +12558,7 @@ function OutputFilePort(filename, fd) {
} else {
x = x.valueOf();
}
- _this17.fs().write(_this17._fd, x, function (err) {
+ _this16.fs().write(_this16._fd, x, function (err) {
if (err) {
throw err;
}
@@ -12472,16 +12577,16 @@ OutputFilePort.prototype.internal = function (name) {
return user_env.get('**internal-env**').get(name);
};
OutputFilePort.prototype.close = function () {
- var _this18 = this;
+ var _this17 = this;
return new Promise(function (resolve, reject) {
- _this18.fs().close(_this18._fd, function (err) {
+ _this17.fs().close(_this17._fd, function (err) {
if (err) {
reject(err);
} else {
- read_only(_this18, '_fd', null, {
+ read_only(_this17, '_fd', null, {
hidden: true
});
- OutputPort.prototype.close.call(_this18);
+ OutputPort.prototype.close.call(_this17);
resolve();
}
});
@@ -12492,7 +12597,7 @@ OutputFilePort.prototype.toString = function () {
};
// -------------------------------------------------------------------------
function InputStringPort(string) {
- var _this19 = this;
+ var _this18 = this;
var env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : global_env;
if (typeof this !== 'undefined' && !(this instanceof InputStringPort) || typeof this === 'undefined') {
return new InputStringPort(string);
@@ -12500,13 +12605,13 @@ function InputStringPort(string) {
typecheck('InputStringPort', string, 'string');
string = string.valueOf();
this._with_parser = this._with_init_parser.bind(this, function () {
- if (!_this19.__parser__) {
- _this19.__parser__ = new Parser({
+ if (!_this18.__parser__) {
+ _this18.__parser__ = new Parser({
env: env
});
- _this19.__parser__.parse(string);
+ _this18.__parser__.parse(string);
}
- return _this19.__parser__;
+ return _this18.__parser__;
});
read_only(this, '__type__', text_port);
this._make_defaults();
@@ -12573,13 +12678,13 @@ InputByteVectorPort.prototype.toString = function () {
return "#";
};
InputByteVectorPort.prototype.close = function () {
- var _this20 = this;
+ var _this19 = this;
read_only(this, '__vector__', _nil);
var err = function err() {
throw new Error('Input-binary-port: port is closed');
};
['read_u8', 'close', 'peek_u8', 'read_u8_vector'].forEach(function (name) {
- _this20[name] = err;
+ _this19[name] = err;
});
this.u8_ready = this.char_ready = function () {
return false;
@@ -12697,7 +12802,7 @@ InputBinaryFilePort.prototype.toString = function () {
};
// -------------------------------------------------------------------------
function OutputBinaryFilePort(filename, fd) {
- var _this21 = this;
+ var _this20 = this;
if (typeof this !== 'undefined' && !(this instanceof OutputBinaryFilePort) || typeof this === 'undefined') {
return new OutputBinaryFilePort(filename, fd);
}
@@ -12712,7 +12817,7 @@ function OutputBinaryFilePort(filename, fd) {
typecheck('write', x, ['number', 'uint8array']);
var buffer;
if (!fs) {
- fs = _this21.internal('fs');
+ fs = _this20.internal('fs');
}
if (LNumber.isNumber(x)) {
buffer = new Uint8Array([x.valueOf()]);
@@ -12720,7 +12825,7 @@ function OutputBinaryFilePort(filename, fd) {
buffer = new Uint8Array(Array.from(x));
}
return new Promise(function (resolve, reject) {
- fs.write(_this21._fd, buffer, function (err) {
+ fs.write(_this20._fd, buffer, function (err) {
if (err) {
reject(err);
} else {
@@ -12752,7 +12857,7 @@ EOF.prototype.toString = function () {
// Simpler way to create interpreter with interaction-environment
// -------------------------------------------------------------------------
function Interpreter(name) {
- var _this22 = this;
+ var _this21 = this;
var _ref27 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
stderr = _ref27.stderr,
stdin = _ref27.stdin,
@@ -12776,7 +12881,7 @@ function Interpreter(name) {
env: this.__env__
});
this.__env__.set('parent.frame', doc('parent.frame', function () {
- return _this22.__env__;
+ return _this21.__env__;
}, global_env.__env__['parent.frame'].__doc__));
var defaults_name = '**interaction-environment-defaults**';
this.set(defaults_name, get_props(obj).concat(defaults_name));
@@ -12796,7 +12901,7 @@ function Interpreter(name) {
// -------------------------------------------------------------------------
Interpreter.prototype.exec = /*#__PURE__*/function () {
var _ref28 = _asyncToGenerator(function (arg) {
- var _this23 = this;
+ var _this22 = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return /*#__PURE__*/_regeneratorRuntime.mark(function _callee16() {
var _options$use_dynamic, use_dynamic, dynamic_env, env;
@@ -12809,12 +12914,12 @@ Interpreter.prototype.exec = /*#__PURE__*/function () {
// simple solution to overwrite this variable in each interpreter
// before evaluation of user code
if (!env) {
- env = _this23.__env__;
+ env = _this22.__env__;
}
if (!dynamic_env) {
dynamic_env = env;
}
- global_env.set('**interaction-environment**', _this23.__env__);
+ global_env.set('**interaction-environment**', _this22.__env__);
if (!Array.isArray(arg)) {
_context16.next = 10;
break;
@@ -12825,8 +12930,8 @@ Interpreter.prototype.exec = /*#__PURE__*/function () {
use_dynamic: use_dynamic
}));
case 10:
- _this23.__parser__.parse(arg);
- return _context16.abrupt("return", exec(_this23.__parser__, {
+ _this22.__parser__.parse(arg);
+ return _context16.abrupt("return", exec(_this22.__parser__, {
env: env,
dynamic_env: dynamic_env,
use_dynamic: use_dynamic
@@ -13002,12 +13107,12 @@ Environment.prototype.toString = function () {
};
// -------------------------------------------------------------------------
Environment.prototype.clone = function () {
- var _this24 = this;
+ var _this23 = this;
// duplicate refs
var env = {};
// TODO: duplicated Symbols
Object.keys(this.__env__).forEach(function (key) {
- env[key] = _this24.__env__[key];
+ env[key] = _this23.__env__[key];
});
return new Environment(env, this.__parent__, this.__name__);
};
@@ -13141,14 +13246,14 @@ Environment.prototype.set = function (name, value) {
// For internal use only
// -------------------------------------------------------------------------
Environment.prototype.constant = function (name, value) {
- var _this25 = this;
+ var _this24 = this;
if (this.__env__.hasOwnProperty(name)) {
throw new Error("Environment::constant: ".concat(name, " already exists"));
}
if (arguments.length === 1 && is_plain_object(arguments[0])) {
var obj = arguments[0];
Object.keys(obj).forEach(function (key) {
- _this25.constant(name, obj[key]);
+ _this24.constant(name, obj[key]);
});
} else {
Object.defineProperty(this.__env__, name, {
@@ -13324,14 +13429,14 @@ var global_env = new Environment({
// ------------------------------------------------------------------
read: doc('read', /*#__PURE__*/function () {
var _read2 = _asyncToGenerator(function () {
- var _this26 = this;
+ var _this25 = this;
var arg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
return /*#__PURE__*/_regeneratorRuntime.mark(function _callee17() {
var env, port;
return _regeneratorRuntime.wrap(function _callee17$(_context17) {
while (1) switch (_context17.prev = _context17.next) {
case 0:
- env = _this26.env;
+ env = _this25.env;
if (arg === null) {
port = internal(env, 'stdin');
} else {
@@ -13419,6 +13524,19 @@ var global_env = new Environment({
return str;
}, "(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."),
// ------------------------------------------------------------------
+ newline: doc('newline', function newline() {
+ var port = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
+ var display = global_env.get('display');
+ var use_dynamic = this.use_dynamic;
+ var env = global_env;
+ var dynamic_env = global_env;
+ call_function(display, ['\n', port], {
+ env: env,
+ dynamic_env: dynamic_env,
+ use_dynamic: use_dynamic
+ });
+ }, "(newline [port])\n\n Write newline character to standard output or given port"),
+ // ------------------------------------------------------------------
display: doc('display', function display(arg) {
var port = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
if (port === null) {
@@ -13441,7 +13559,7 @@ var global_env = new Environment({
}
var value = args.map(repr).join(' ');
port.write.call(global_env, value);
- global_env.get('newline')(port);
+ global_env.get('newline').call(this, port);
}, "(display-error . args)\n\n Display an error message on stderr."),
// ------------------------------------------------------------------
'%foldcase-string': doc('%foldcase-string', foldcase_string, "(%foldcase-string string)\n\n Same as string-foldcase but without typechecking"),
@@ -13509,7 +13627,7 @@ var global_env = new Environment({
}, "(cdr pair)\n\n This function returns the cdr (all but first) of the list."),
// ------------------------------------------------------------------
'set!': doc(new Macro('set!', function (code) {
- var _this27 = this;
+ var _this26 = this;
var _ref30 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
use_dynamic = _ref30.use_dynamic,
rest = _objectWithoutProperties(_ref30, _excluded4);
@@ -13563,7 +13681,7 @@ var global_env = new Environment({
if (parts.length > 1) {
var key = parts.pop();
var name = parts.join('.');
- var obj = _this27.get(name, {
+ var obj = _this26.get(name, {
throwError: false
});
if (obj) {
@@ -13619,6 +13737,8 @@ var global_env = new Environment({
env = this.get('**interaction-environment**');
}
}
+ var package_name = '@lips';
+ var has_package = file.startsWith(package_name);
// TODO: move **module-path** to internal env
var PATH = '**module-path**';
var module_path = global_env.get(PATH, {
@@ -13660,42 +13780,61 @@ var global_env = new Environment({
return code;
});
}
+ function get_root_dir() {
+ var __dirname = global_env.get('__dirname');
+ return __dirname.replace(/[^/]+$/, '');
+ }
if (is_node()) {
return new Promise( /*#__PURE__*/function () {
var _ref31 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee18(resolve, reject) {
- var path, cmd, _args20;
+ var _path, _fs, root_dir, cmd, _args20;
return _regeneratorRuntime.wrap(function _callee18$(_context18) {
while (1) switch (_context18.prev = _context18.next) {
case 0:
- path = nodeRequire('path');
+ _context18.prev = 0;
+ _context18.next = 3;
+ return node_ready;
+ case 3:
+ _path = nodeRequire('path');
+ _fs = nodeRequire('fs');
+ root_dir = get_root_dir();
+ if (has_package) {
+ file = file.replace(package_name, root_dir);
+ }
if (!module_path) {
- _context18.next = 6;
+ _context18.next = 12;
break;
}
module_path = module_path.valueOf();
- file = path.join(module_path, file);
- _context18.next = 12;
+ if (!file.startsWith('/')) {
+ file = _path.join(module_path, file);
+ }
+ _context18.next = 19;
break;
- case 6:
+ case 12:
+ if (file.startsWith('/')) {
+ _context18.next = 19;
+ break;
+ }
cmd = g_env.get('command-line', {
throwError: false
});
if (!cmd) {
- _context18.next = 11;
+ _context18.next = 18;
break;
}
- _context18.next = 10;
+ _context18.next = 17;
return cmd();
- case 10:
+ case 17:
_args20 = _context18.sent;
- case 11:
+ case 18:
if (_args20 && !is_nil(_args20)) {
process.cwd();
- file = path.join(path.dirname(_args20.car.valueOf()), file);
+ file = _path.join(_path.dirname(_args20.car.valueOf()), file);
}
- case 12:
- global_env.set(PATH, path.dirname(file));
- nodeRequire('fs').readFile(file, function (err, data) {
+ case 19:
+ global_env.set(PATH, _path.dirname(file));
+ _fs.readFile(file, function (err, data) {
if (err) {
reject(err);
global_env.set(PATH, module_path);
@@ -13710,20 +13849,37 @@ var global_env = new Environment({
}
}
});
- case 14:
+ _context18.next = 26;
+ break;
+ case 23:
+ _context18.prev = 23;
+ _context18.t0 = _context18["catch"](0);
+ console.error(_context18.t0);
+ case 26:
case "end":
return _context18.stop();
}
- }, _callee18);
+ }, _callee18, null, [[0, 23]]);
}));
return function (_x14, _x15) {
return _ref31.apply(this, arguments);
};
}());
}
+ if (has_package) {
+ var _global_env$get, _path3;
+ var _path2 = (_global_env$get = global_env.get('__dirname', {
+ throwError: false
+ })) !== null && _global_env$get !== void 0 ? _global_env$get : current_script;
+ (_path3 = _path2) !== null && _path3 !== void 0 ? _path3 : _path2 = current_script;
+ var _root = _path2.replace(/dist\/?[^\/]*$/, '');
+ file = file.replace(package_name, _root);
+ }
if (module_path) {
module_path = module_path.valueOf();
- file = module_path + '/' + file.replace(/^\.?\/?/, '');
+ if (!file.startsWith('/')) {
+ file = module_path + '/' + file.replace(/^\.?\/?/, '');
+ }
}
return fetch(file).then(function (code) {
global_env.set(PATH, file.replace(/\/[^/]*$/, ''));
@@ -13750,7 +13906,7 @@ var global_env = new Environment({
// ------------------------------------------------------------------
'do': doc(new Macro('do', /*#__PURE__*/function () {
var _ref32 = _asyncToGenerator(function (code, _ref33) {
- var _this28 = this;
+ var _this27 = this;
var use_dynamic = _ref33.use_dynamic,
error = _ref33.error;
return /*#__PURE__*/_regeneratorRuntime.mark(function _callee19() {
@@ -13758,7 +13914,7 @@ var global_env = new Environment({
return _regeneratorRuntime.wrap(function _callee19$(_context20) {
while (1) switch (_context20.prev = _context20.next) {
case 0:
- self = _this28;
+ self = _this27;
dynamic_env = self;
scope = self.inherit('do');
vars = code.car;
@@ -14090,8 +14246,8 @@ var global_env = new Environment({
}
env.set(name, parameter);
}
- var body = new Pair(new LSymbol('begin'), code.cdr);
- return _evaluate(body, _objectSpread(_objectSpread({}, eval_args), {}, {
+ var expr = hygienic_begin([env, eval_args.dynamic_env], code.cdr);
+ return _evaluate(expr, _objectSpread(_objectSpread({}, eval_args), {}, {
env: env
}));
}), "(syntax-parameterize (bindings) body)\n\n Macro work similar to let-syntax but the the bindnds will be exposed to the user.\n With syntax-parameterize you can define anaphoric macros."),
@@ -14195,21 +14351,14 @@ var global_env = new Environment({
}, "(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 _this29 = this;
env = env || this.get('interaction-environment').call(this);
- return _evaluate(code, {
- env: env,
- dynamic_env: env,
- error: function error(e) {
- var error = global_env.get('display-error');
- error.call(_this29, e.message);
- if (e.code) {
- var stack = e.code.map(function (line, i) {
- return "[".concat(i + 1, "]: ").concat(line);
- }).join('\n');
- error.call(_this29, stack);
- }
- }
+ return new Promise(function (resolve, reject) {
+ var result = _evaluate(code, {
+ env: env,
+ dynamic_env: env,
+ error: reject
+ });
+ resolve(result);
});
}, "(eval expr)\n (eval expr environment)\n\n Function that evaluates LIPS Scheme code. If the second argument is provided\n it will be the environment that the code is evaluated in."),
// ------------------------------------------------------------------
@@ -14287,7 +14436,7 @@ var global_env = new Environment({
}
}
var rest = __doc__ ? code.cdr.cdr : code.cdr;
- var output = new Pair(new LSymbol('begin'), rest);
+ var output = hygienic_begin([env, dynamic_env], rest);
var eval_args = {
env: env,
dynamic_env: dynamic_env,
@@ -14620,7 +14769,11 @@ var global_env = new Environment({
// -----------------------------------------------------------------
function unquote_splice(pair, unquote_cnt, max_unq) {
if (unquote_cnt < max_unq) {
- return new Pair(new Pair(pair.car.car, recur(pair.car.cdr, unquote_cnt, max_unq)), _nil);
+ var cdr = _nil;
+ if (!is_nil(pair.cdr)) {
+ cdr = recur(pair.cdr, unquote_cnt - 1, max_unq);
+ }
+ return new Pair(new Pair(pair.car.car, recur(pair.car.cdr, unquote_cnt, max_unq)), cdr);
}
var lists = [];
return function next(node) {
@@ -14819,7 +14972,7 @@ var global_env = new Environment({
}, "(clone list)\n\n Function that returns a clone of the list, that does not share any pairs with the\n original, so the clone can be safely mutated without affecting the original."),
// ------------------------------------------------------------------
append: doc('append', function append() {
- var _global_env$get;
+ var _global_env$get2;
for (var _len25 = arguments.length, items = new Array(_len25), _key25 = 0; _key25 < _len25; _key25++) {
items[_key25] = arguments[_key25];
}
@@ -14829,7 +14982,7 @@ var global_env = new Environment({
}
return item;
});
- return (_global_env$get = global_env.get('append!')).call.apply(_global_env$get, [this].concat(_toConsumableArray(items)));
+ return (_global_env$get2 = global_env.get('append!')).call.apply(_global_env$get2, [this].concat(_toConsumableArray(items)));
}, "(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 () {
@@ -15166,7 +15319,7 @@ var global_env = new Environment({
}, "(string->number number [radix])\n\n Function that parses a string into a number."),
// ------------------------------------------------------------------
'try': doc(new Macro('try', function (code, _ref41) {
- var _this30 = this;
+ var _this28 = this;
var use_dynamic = _ref41.use_dynamic;
_ref41.error;
return new Promise(function (resolve, reject) {
@@ -15202,15 +15355,15 @@ var global_env = new Environment({
};
}
var args = {
- env: _this30,
+ env: _this28,
use_dynamic: use_dynamic,
- dynamic_env: _this30,
+ dynamic_env: _this28,
error: function error(e) {
if (e instanceof IgnoreException) {
throw e;
}
if (catch_clause) {
- var env = _this30.inherit('try');
+ var env = _this28.inherit('try');
var name = catch_clause.cdr.car.car;
if (!(name instanceof LSymbol)) {
throw new Error('try: invalid syntax: catch require variable name');
@@ -15220,7 +15373,7 @@ var global_env = new Environment({
var catch_args = {
env: env,
use_dynamic: use_dynamic,
- dynamic_env: _this30,
+ dynamic_env: _this28,
error: function error(e) {
catch_error = true;
reject(e);
@@ -15270,7 +15423,7 @@ var global_env = new Environment({
}, "(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;
+ var _global_env$get3;
typecheck('for-each', fn, 'function');
for (var _len32 = arguments.length, lists = new Array(_len32 > 1 ? _len32 - 1 : 0), _key32 = 1; _key32 < _len32; _key32++) {
lists[_key32 - 1] = arguments[_key32];
@@ -15281,14 +15434,14 @@ var global_env = new Environment({
// we need to use call(this because babel transpile this code into:
// var ret = map.apply(void 0, [fn].concat(lists));
// it don't work with weakBind
- var ret = (_global_env$get2 = global_env.get('map')).call.apply(_global_env$get2, [this, fn].concat(lists));
+ var ret = (_global_env$get3 = global_env.get('map')).call.apply(_global_env$get3, [this, fn].concat(lists));
if (is_promise(ret)) {
return ret.then(function () {});
}
}, "(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 _this31 = this;
+ var _this29 = this;
for (var _len33 = arguments.length, lists = new Array(_len33 > 1 ? _len33 - 1 : 0), _key33 = 1; _key33 < _len33; _key33++) {
lists[_key33 - 1] = arguments[_key33];
}
@@ -15297,7 +15450,7 @@ var global_env = new Environment({
lists.forEach(function (arg, i) {
typecheck('map', arg, ['pair', 'nil'], i + 1);
// detect cycles
- if (is_pair(arg) && !is_list.call(_this31, arg)) {
+ if (is_pair(arg) && !is_list.call(_this29, arg)) {
throw new Error("map: argument ".concat(i + 1, " is not a list"));
}
});
@@ -15319,7 +15472,7 @@ var global_env = new Environment({
use_dynamic: use_dynamic
});
return unpromise(result, function (head) {
- return unpromise(map.call.apply(map, [_this31, fn].concat(_toConsumableArray(lists.map(function (l) {
+ return unpromise(map.call.apply(map, [_this29, fn].concat(_toConsumableArray(lists.map(function (l) {
return l.cdr;
})))), function (rest) {
return new Pair(head, rest);
@@ -15343,18 +15496,6 @@ var global_env = new Environment({
}
}, "(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');
- typecheck('some', list, ['pair', 'nil']);
- if (is_null(list)) {
- return false;
- } else {
- return unpromise(fn(list.car), function (value) {
- return value || some(fn, list.cdr);
- });
- }
- }, "(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 Analogous to Python any(map(fn, list))."),
- // ------------------------------------------------------------------
fold: doc('fold', fold('fold', function (fold, fn, init) {
for (var _len34 = arguments.length, lists = new Array(_len34 > 3 ? _len34 - 3 : 0), _key34 = 3; _key34 < _len34; _key34++) {
lists[_key34 - 3] = arguments[_key34];
@@ -15401,7 +15542,7 @@ var global_env = new Environment({
}, "(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 _this32 = this;
+ var _this30 = this;
for (var _len36 = arguments.length, lists = new Array(_len36 > 3 ? _len36 - 3 : 0), _key37 = 3; _key37 < _len36; _key37++) {
lists[_key37 - 3] = arguments[_key37];
}
@@ -15415,7 +15556,7 @@ var global_env = new Environment({
return unpromise(fn.apply(void 0, _toConsumableArray(lists.map(function (l) {
return l.car;
})).concat([init])), function (value) {
- return reduce.call.apply(reduce, [_this32, fn, value].concat(_toConsumableArray(lists.map(function (l) {
+ return reduce.call.apply(reduce, [_this30, fn, value].concat(_toConsumableArray(lists.map(function (l) {
return l.cdr;
}))));
});
@@ -15809,8 +15950,8 @@ combinations(['d', 'a'], 2, 5).forEach(function (spec) {
function reversseFind(dir, fn) {
var parts = dir.split(path.sep).filter(Boolean);
for (var i = parts.length; i--;) {
- var _path;
- var p = (_path = path).join.apply(_path, ['/'].concat(_toConsumableArray(parts.slice(0, i + 1))));
+ var _path4;
+ var p = (_path4 = path).join.apply(_path4, ['/'].concat(_toConsumableArray(parts.slice(0, i + 1))));
if (fn(p)) {
return p;
}
@@ -15834,7 +15975,7 @@ var noop = function noop() {};
function node_specific() {
return _node_specific.apply(this, arguments);
} // -------------------------------------------------------------------------
-/* c8 ignore next 11 */
+/* c8 ignore next 15 */
function _node_specific() {
_node_specific = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee23() {
var _yield$import, createRequire, moduleURL, __dirname__, __filename__;
@@ -15908,16 +16049,20 @@ function _node_specific() {
}));
return _node_specific.apply(this, arguments);
}
+var node_ready; // Scheme load function need to wait for node_specific
if (is_node()) {
- node_specific();
-} else if (typeof window !== 'undefined' && window === root) {
- global_env.set('window', window);
- global_env.set('global', undefined);
- global_env.set('self', window);
-} else if (typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined') {
- global_env.set('self', self);
- global_env.set('window', undefined);
- global_env.set('global', undefined);
+ node_ready = node_specific();
+} else {
+ node_ready = Promise.resolve();
+ if (typeof window !== 'undefined' && window === root) {
+ global_env.set('window', window);
+ global_env.set('global', undefined);
+ global_env.set('self', window);
+ } else if (typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined') {
+ global_env.set('self', self);
+ global_env.set('window', undefined);
+ global_env.set('global', undefined);
+ }
}
// -------------------------------------------------------------------------
function typeErrorMessage(fn, got, expected) {
@@ -16833,6 +16978,7 @@ function bootstrap() {
url = "https://cdn.jsdelivr.net/npm/@jcubic/lips@".concat(lips.version, "/").concat(std);
}
}
+ global_env.set('__dirname', url.replace(/[^/]+$/, ''));
var load = global_env.get('load');
return load.call(user_env, url, global_env);
}
@@ -17246,17 +17392,17 @@ if (typeof window !== 'undefined') {
// -------------------------------------------------------------------------
var banner = function () {
// Rollup tree-shaking is removing the variable if it's normal string because
- // obviously 'Mon, 27 May 2024 11:41:47 +0000' == '{{' + 'DATE}}'; can be removed
+ // obviously 'Fri, 08 Nov 2024 13:26:12 +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('Mon, 27 May 2024 11:41:47 +0000').valueOf();
+ var date = LString('Fri, 08 Nov 2024 13:26:12 +0000').valueOf();
var _date = date === '{{' + 'DATE}}' ? new Date() : new Date(date);
var _format = function _format(x) {
return x.toString().padStart(2, '0');
};
var _year = _date.getFullYear();
var _build = [_year, _format(_date.getMonth() + 1), _format(_date.getDate())].join('-');
- var banner = "\n __ __ __\n / / \\ \\ _ _ ___ ___ \\ \\\n| | \\ \\ | | | || . \\/ __> | |\n| | > \\ | |_ | || _/\\__ \\ | |\n| | / ^ \\ |___||_||_| <___/ | |\n \\_\\ /_/ \\_\\ /_/\n\nLIPS Interpreter 1.0.0-beta.19 (".concat(_build, ") \nCopyright (c) 2018-").concat(_year, " Jakub T. Jankiewicz\n\nType (env) to see environment with functions macros and variables. You can also\nuse (help name) to display help for specific 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/, '');
+ var banner = "\n __ __ __\n / / \\ \\ _ _ ___ ___ \\ \\\n| | \\ \\ | | | || . \\/ __> | |\n| | > \\ | |_ | || _/\\__ \\ | |\n| | / ^ \\ |___||_||_| <___/ | |\n \\_\\ /_/ \\_\\ /_/\n\nLIPS Interpreter DEV (".concat(_build, ") \nCopyright (c) 2018-").concat(_year, " Jakub T. Jankiewicz\n\nType (env) to see environment with functions macros and variables. You can also\nuse (help name) to display help for specific 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 banner;
}();
// -------------------------------------------------------------------------
@@ -17288,8 +17434,8 @@ read_only(LString, '__class__', 'string');
read_only(QuotedPromise, '__class__', 'promise');
read_only(Parameter, '__class__', 'parameter');
// -------------------------------------------------------------------------
-var version = '1.0.0-beta.19';
-var date = 'Mon, 27 May 2024 11:41:47 +0000';
+var version = 'DEV';
+var date = 'Fri, 08 Nov 2024 13:26:12 +0000';
// unwrap async generator into Promise
var parse = compose(uniterate_async, _parse);
diff --git a/dist/lips.esm.js b/dist/lips.esm.js
index b2121145e..60aba343c 100644
--- a/dist/lips.esm.js
+++ b/dist/lips.esm.js
@@ -4,7 +4,7 @@
* | | \ \ | | | || . \/ __> | |
* | | > \ | |_ | || _/\__ \ | |
* | | / ^ \ |___||_||_| <___/ | |
- * \_\ /_/ \_\ /_/ v. 1.0.0-beta.19
+ * \_\ /_/ \_\ /_/ v. DEV
*
* LIPS is Pretty Simple - Scheme based Powerful LISP in JavaScript
*
@@ -31,7 +31,7 @@
* Copyright (c) 2014-present, Facebook, Inc.
* released under MIT license
*
- * build: Mon, 27 May 2024 11:41:47 +0000
+ * build: Fri, 08 Nov 2024 13:26:12 +0000
*/
function _classApplyDescriptorGet(receiver, descriptor) {
@@ -102,6 +102,10 @@ function _construct(t, e, r) {
return r && _setPrototypeOf(p, r.prototype), p;
}
+function _readOnlyError(name) {
+ throw new TypeError("\"" + name + "\" is read-only");
+}
+
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
@@ -3499,25 +3503,23 @@ function contentLoaded(win, fn) {
}
}
// -------------------------------------------------------------------------
-/* eslint-disable */
/* c8 ignore next 13 */
function log(x) {
- if (is_debug()) {
- if (is_plain_object(x)) {
- console.log(map_object(x, function (value) {
- return toString(value, true);
- }));
- } else {
- var _console;
- for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
- args[_key - 1] = arguments[_key];
- }
- (_console = console).log.apply(_console, [toString(x, true)].concat(_toConsumableArray(args.map(function (item) {
- return toString(item, true);
- }))));
- }
+ for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
+ args[_key - 1] = arguments[_key];
+ }
+ if (is_plain_object(x) && is_debug(args[0])) {
+ console.log(map_object(x, function (value) {
+ return toString(value, true);
+ }));
+ } else if (is_debug()) {
+ var _console;
+ (_console = console).log.apply(_console, [toString(x, true)].concat(_toConsumableArray(args.map(function (item) {
+ return toString(item, true);
+ }))));
}
}
+/* eslint-enable */
// ----------------------------------------------------------------------
/* c8 ignore next */
function is_debug() {
@@ -3906,8 +3908,25 @@ function parse_string(string) {
}
// ----------------------------------------------------------------------
function parse_symbol(arg) {
- if (arg.match(/^\|.*\|$/)) {
- arg = arg.replace(/(^\|)|(\|$)/g, '');
+ arg.match(/^name/);
+ var re = /(^|.)\|/g;
+ if (arg.match(re)) {
+ // handle escaped bar and escaped slash
+ arg = arg.split('|').filter(Boolean).reduce(function (acc, str) {
+ var result = '';
+ if (str.match(/^\\+$/)) {
+ if (str.length > 1) {
+ var count = Math.floor(str.length / 2);
+ result = '\\'.repeat(count);
+ }
+ if (str.length % 2 !== 0) {
+ result += '|';
+ }
+ } else {
+ result = str;
+ }
+ return acc + result;
+ });
var chars = {
t: '\t',
r: '\r',
@@ -3915,8 +3934,8 @@ function parse_symbol(arg) {
};
arg = arg.replace(/\\(x[^;]+);/g, function (_, chr) {
return String.fromCharCode(parseInt('0' + chr, 16));
- }).replace(/\\(.)/g, function (_, chr) {
- return chars[chr] || chr;
+ }).replace(/\\([trn])/g, function (_, chr) {
+ return chars[chr];
});
}
return new LSymbol(arg);
@@ -4217,6 +4236,18 @@ var gensym = function () {
return with_props(count, Symbol("#:g".concat(count)));
};
}();
+// ----------------------------------------------------------------------
+// :: helper function that make symbols in names array hygienic
+// ----------------------------------------------------------------------
+function hygienic_begin(envs, expr) {
+ var begin = global_env.get('begin');
+ var g_begin = gensym('begin');
+ envs.forEach(function (env) {
+ env.set(g_begin, begin);
+ });
+ return new Pair(g_begin, expr);
+}
+
// ----------------------------------------------------------------------
// Class used to escape promises: feature #54
// ----------------------------------------------------------------------
@@ -4514,6 +4545,11 @@ var Lexer = /*#__PURE__*/function () {
var found = this.next_token();
if (found) {
this._token = this.__input__.substring(this._i, this._next);
+ if (!this.__token__) {
+ // handle case when accessing __token__ from the syntax extension
+ // (e.g. string interpolation) as the first expression in a REPL
+ read_only(this, '__token__', this.token(true));
+ }
return this.token(meta);
}
return eof;
@@ -4762,6 +4798,7 @@ Lexer.regex_class = Symbol["for"]('regex_class');
Lexer.character = Symbol["for"]('character');
Lexer.bracket = Symbol["for"]('bracket');
Lexer.b_symbol = Symbol["for"]('b_symbol');
+Lexer.b_symbol_ex = Symbol["for"]('b_symbol_ex');
Lexer.b_comment = Symbol["for"]('b_comment');
Lexer.i_comment = Symbol["for"]('i_comment');
Lexer.l_datum = Symbol["for"]('l_datum');
@@ -4792,7 +4829,7 @@ Lexer._rules = [
// for dot comma `(a .,b)
[/\./, Lexer.boundary, /,/, null, null],
// block symbols
-[/\|/, null, null, null, Lexer.b_symbol], [/\s/, null, null, Lexer.b_symbol, Lexer.b_symbol], [/\|/, null, Lexer.boundary, Lexer.b_symbol, null]];
+[/\|/, null, null, null, Lexer.b_symbol], [/\s/, null, null, Lexer.b_symbol, Lexer.b_symbol], [/\|/, null, Lexer.boundary, Lexer.b_symbol, null], [/\|/, null, /\S/, Lexer.b_symbol, Lexer.b_symbol_ex], [/\S/, null, Lexer.boundary, Lexer.b_symbol_ex, null]];
// ----------------------------------------------------------------------
Lexer._brackets = [[/[()[\]]/, null, null, null, null]];
// ----------------------------------------------------------------------
@@ -4894,17 +4931,16 @@ var Parser = /*#__PURE__*/function () {
_createClass(Parser, [{
key: "_with_syntax_scope",
value: function _with_syntax_scope(fn) {
- var _this5 = this;
// expose parser and change stdin so parser extension can use current-input
// to read data from the parser stream #150
var internal = get_internal(this.__env__);
var stdin = internal.get('stdin');
- this.__env__.set('lips', _objectSpread(_objectSpread({}, lips), {}, {
+ global_env.set('lips', _objectSpread(_objectSpread({}, lips), {}, {
__parser__: this
}));
internal.set('stdin', new ParserInputPort(this, this.__env__));
var cleanup = function cleanup() {
- _this5.__env__.set('lips', lips);
+ global_env.set('lips', lips);
internal.set('stdin', stdin);
};
return unpromise(fn(), function (result) {
@@ -5243,7 +5279,7 @@ var Parser = /*#__PURE__*/function () {
key: "_resolve_object",
value: function () {
var _resolve_object2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(object) {
- var _this6 = this;
+ var _this5 = this;
var result;
return _regeneratorRuntime.wrap(function _callee6$(_context6) {
while (1) switch (_context6.prev = _context6.next) {
@@ -5253,7 +5289,7 @@ var Parser = /*#__PURE__*/function () {
break;
}
return _context6.abrupt("return", object.map(function (item) {
- return _this6._resolve_object(item);
+ return _this5._resolve_object(item);
}));
case 2:
if (!is_plain_object(object)) {
@@ -5262,7 +5298,7 @@ var Parser = /*#__PURE__*/function () {
}
result = {};
Object.keys(object).forEach(function (key) {
- result[key] = _this6._resolve_object(object[key]);
+ result[key] = _this5._resolve_object(object[key]);
});
return _context6.abrupt("return", result);
case 6:
@@ -5337,7 +5373,7 @@ var Parser = /*#__PURE__*/function () {
key: "_read_object",
value: function () {
var _read_object3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8() {
- var _this7 = this;
+ var _this6 = this;
var token, special, builtin, expr, extension, is_symbol, was_close_paren, object, args, result, ref, ref_label;
return _regeneratorRuntime.wrap(function _callee8$(_context8) {
while (1) switch (_context8.prev = _context8.next) {
@@ -5415,8 +5451,8 @@ var Parser = /*#__PURE__*/function () {
}
return _context8.abrupt("return", this._with_syntax_scope(function () {
return call_function(extension, is_symbol ? [] : args, {
- env: _this7.__env__,
- dynamic_env: _this7.__env__,
+ env: _this6.__env__,
+ dynamic_env: _this6.__env__,
use_dynamic: false
});
}));
@@ -5451,7 +5487,7 @@ var Parser = /*#__PURE__*/function () {
}
_context8.next = 44;
return this._with_syntax_scope(function () {
- return _this7.evaluate(expr);
+ return _this6.evaluate(expr);
});
case 44:
result = _context8.sent;
@@ -6188,7 +6224,7 @@ function keywords_re() {
return new RegExp("^(?:#:)?(?:".concat(args.join('|'), ")$"));
}
// line breaking rules
-Formatter.rules = [[[sexp], 0, not_close], [[p_o, keywords_re('begin', 'cond-expand')], 1], [[p_o, let_re, symbol, p_o, let_value, p_e], 1], [[p_o, let_re, symbol, sexp_or_atom], 1, not_close], [[p_o, let_re, p_o, let_value], 1, not_close], [[p_o, keywords_re('define-syntax'), /.+/], 1], [[p_o, syntax_rules, not_p, identifiers], 1], [[p_o, syntax_rules, not_p, identifiers, sexp], 1, not_close], [[p_o, syntax_rules, identifiers], 1], [[p_o, syntax_rules, identifiers, sexp], 1, not_close], [[p_o, non_def, new Pattern([/[^()[\]]/], '+'), sexp], 1, not_close], [[p_o, sexp], 1, not_close], [[p_o, not_p, sexp], 1, not_close], [[p_o, keywords_re('lambda', 'if'), not_p], 1, not_close], [[p_o, keywords_re('while'), not_p, sexp], 1, not_close], [[p_o, keywords_re('if'), not_p, glob], 1], [[p_o, def_lambda_re, identifiers], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re, sexp], 0, not_close], [[p_o, def_lambda_re, identifiers, sexp], 0, not_close]];
+Formatter.rules = [[[sexp], 0, not_close], [[p_o, keywords_re('begin', 'cond-expand')], 1, not_close], [[p_o, let_re, symbol, p_o, let_value, p_e], 1, not_close], [[p_o, let_re, symbol, sexp_or_atom], 1, not_close], [[p_o, let_re, p_o, let_value], 1, not_close], [[p_o, keywords_re('define-syntax'), /.+/], 1], [[p_o, syntax_rules, not_p, identifiers], 1], [[p_o, syntax_rules, not_p, identifiers, sexp], 1, not_close], [[p_o, syntax_rules, identifiers], 1], [[p_o, syntax_rules, identifiers, sexp], 1, not_close], [[p_o, non_def, new Pattern([/[^()[\]]/], '+'), sexp], 1, not_close], [[p_o, sexp], 1, not_close], [[p_o, not_p, sexp], 1, not_close], [[p_o, keywords_re('lambda', 'if'), not_p], 1, not_close], [[p_o, keywords_re('while'), not_p, sexp], 1, not_close], [[p_o, keywords_re('if'), not_p, glob], 1, not_close], [[p_o, def_lambda_re, identifiers], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re], 0, not_close], [[p_o, def_lambda_re, identifiers, string_re, sexp], 0, not_close], [[p_o, def_lambda_re, identifiers, sexp], 0, not_close]];
// ----------------------------------------------------------------------
Formatter.prototype["break"] = function () {
var code = this.__code__.replace(/\n[ \t]*/g, '\n ').replace(/^\s+/, '');
@@ -8153,7 +8189,7 @@ function user_repr(obj) {
// if key is Object it should only work for plain_object
// because otherwise it will match every object
// we don't use instanceof so it don't work for subclasses
- if (obj instanceof key && (key === Object && plain_object && !iterator || key !== Object)) {
+ if (constructor === key && (key === Object && plain_object && !iterator || key !== Object)) {
fn = value;
}
});
@@ -8360,6 +8396,9 @@ function toString(obj, quote, skip_cycles) {
if (type(obj) === 'instance') {
if (is_lambda(constructor) && constructor.__name__) {
name = constructor.__name__.valueOf();
+ if (_typeof$1(name) === 'symbol') {
+ name = name.toString().replace(/^Symbol\((?:#:)?([^\)]+)\)$/, '$1');
+ }
} else if (!is_native_function(constructor)) {
name = 'instance';
}
@@ -9080,8 +9119,13 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
log(symbols);
/* eslint-disable complexity */
function traverse(pattern, code) {
- var pattern_names = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
- var ellipsis = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
+ var state = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
+ var _state$ellipsis = state.ellipsis,
+ ellipsis = _state$ellipsis === void 0 ? false : _state$ellipsis,
+ _state$trailing = state.trailing,
+ trailing = _state$trailing === void 0 ? false : _state$trailing,
+ _state$pattern_names = state.pattern_names,
+ pattern_names = _state$pattern_names === void 0 ? [] : _state$pattern_names;
log({
code: code,
pattern: pattern
@@ -9089,13 +9133,15 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
if (is_atom(pattern) && !(pattern instanceof LSymbol)) {
return same_atom(pattern, code);
}
- if (pattern instanceof LSymbol && symbols.includes(pattern.literal())) {
- // TODO: literal() may be SLOW
- if (!LSymbol.is(code, pattern)) {
- return false;
+ if (pattern instanceof LSymbol) {
+ var literal = pattern.literal(); // TODO: literal() may be SLOW
+ if (symbols.includes(literal)) {
+ if (!LSymbol.is(code, literal) && !LSymbol.is(pattern, code)) {
+ return false;
+ }
+ var ref = expansion.ref(literal);
+ return !ref || ref === define || ref === global_env;
}
- var ref = expansion.ref(pattern);
- return !ref || ref === define || ref === global_env;
}
if (Array.isArray(pattern) && Array.isArray(code)) {
log('<<< a 1');
@@ -9121,25 +9167,29 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
} else if (Array.isArray(pattern[0])) {
log('<<< a 3');
var _names = _toConsumableArray(pattern_names);
+ var new_state = _objectSpread(_objectSpread({}, state), {}, {
+ pattern_names: _names,
+ ellipsis: true
+ });
if (!code.every(function (node) {
- return traverse(pattern[0], node, _names, true);
+ return traverse(pattern[0], node, new_state);
})) {
return false;
}
}
if (pattern.length > 2) {
var pat = pattern.slice(2);
- return traverse(pat, code.slice(-pat.length), pattern_names, ellipsis);
+ return traverse(pat, code.slice(-pat.length), state);
}
return true;
}
- var first = traverse(pattern[0], code[0], pattern_names, ellipsis);
+ var first = traverse(pattern[0], code[0], state);
log({
first: first,
pattern: pattern[0],
code: code[0]
});
- var rest = traverse(pattern.slice(1), code.slice(1), pattern_names, ellipsis);
+ var rest = traverse(pattern.slice(1), code.slice(1), state);
log({
first: first,
rest: rest
@@ -9163,23 +9213,30 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
}
}
if (is_pair(pattern) && is_pair(pattern.cdr) && LSymbol.is(pattern.cdr.car, ellipsis_symbol)) {
+ log('>> 1 (a)');
// pattern (... ???) - SRFI-46
if (!is_nil(pattern.cdr.cdr)) {
if (is_pair(pattern.cdr.cdr)) {
+ log('>> 1 (b)');
// if we have (x ... a b) we need to remove two from the end
var list_len = pattern.cdr.cdr.length();
+ var improper_list = !is_nil(pattern.last_pair().cdr);
if (!is_pair(code)) {
return false;
}
var code_len = code.length();
var list = code;
- while (code_len - 1 > list_len) {
+ var _trailing = improper_list ? 1 : 1;
+ while (code_len - _trailing > list_len) {
list = list.cdr;
code_len--;
}
var _rest5 = list.cdr;
list.cdr = _nil;
- if (!traverse(pattern.cdr.cdr, _rest5, pattern_names, ellipsis)) {
+ var new_sate = _objectSpread(_objectSpread({}, state), {}, {
+ trailing: improper_list
+ });
+ if (!traverse(pattern.cdr.cdr, _rest5, new_sate)) {
return false;
}
}
@@ -9189,7 +9246,7 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
if (bindings['...'].symbols[_name3] && !pattern_names.includes(_name3) && !ellipsis) {
throw new Error('syntax: named ellipsis can only appear onces');
}
- log('>> 1');
+ log('>> 1 (next)');
if (is_nil(code)) {
log('>> 2');
if (ellipsis) {
@@ -9220,6 +9277,7 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
} else {
log('>> 6');
if (is_pair(code)) {
+ log('>> 7 ' + ellipsis);
// cons (a . b) => (var ... . x)
if (!is_pair(code.cdr) && !is_nil(code.cdr)) {
log('>> 7 (b)');
@@ -9227,28 +9285,34 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
return false;
} else if (!bindings['...'].symbols[_name3]) {
bindings['...'].symbols[_name3] = new Pair(code.car, _nil);
- return traverse(pattern.cdr.cdr, code.cdr);
+ return traverse(pattern.cdr.cdr, code.cdr, state);
}
}
// code as improper list
var last_pair = code.last_pair();
+ log({
+ last_pair: last_pair
+ });
if (!is_nil(last_pair.cdr)) {
+ log('>> 7 (c)');
if (is_nil(pattern.cdr.cdr)) {
// case (a ...) for (a b . x)
return false;
} else {
+ log('>> 7 (d)');
// case (a ... . b) for (a b . x)
var copy = code.clone();
copy.last_pair().cdr = _nil;
bindings['...'].symbols[_name3] = copy;
- return traverse(pattern.cdr.cdr, last_pair.cdr);
+ return traverse(pattern.cdr.cdr, last_pair.cdr, state);
}
}
- log('>> 7 ' + ellipsis);
pattern_names.push(_name3);
if (!bindings['...'].symbols[_name3]) {
+ log('>> 7 (e)');
bindings['...'].symbols[_name3] = new Pair(code, _nil);
} else {
+ log('>> 7 (f)');
var _node2 = bindings['...'].symbols[_name3];
bindings['...'].symbols[_name3] = _node2.append(new Pair(code, _nil));
}
@@ -9259,7 +9323,7 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
// empty ellipsis with rest (a b ... . d) #290
log('>> 8');
bindings['...'].symbols[_name3] = null;
- return traverse(pattern.cdr.cdr, code);
+ return traverse(pattern.cdr.cdr, code, state);
} else {
log('>> 9');
return false;
@@ -9276,8 +9340,12 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
}
log('>> 11');
var _node3 = code;
+ var _new_state = _objectSpread(_objectSpread({}, state), {}, {
+ pattern_names: names,
+ ellipsis: true
+ });
while (is_pair(_node3)) {
- if (!traverse(pattern.car, _node3.car, names, true)) {
+ if (!traverse(pattern.car, _node3.car, _new_state)) {
return false;
}
_node3 = _node3.cdr;
@@ -9287,8 +9355,12 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
if (Array.isArray(pattern.car)) {
var names = _toConsumableArray(pattern_names);
var _node4 = code;
+ var _new_state2 = _objectSpread(_objectSpread({}, state), {}, {
+ pattern_names: names,
+ ellipsis: true
+ });
while (is_pair(_node4)) {
- if (!traverse(pattern.car, _node4.car, names, true)) {
+ if (!traverse(pattern.car, _node4.car, _new_state2)) {
return false;
}
_node4 = _node4.cdr;
@@ -9323,15 +9395,29 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
code: code,
pattern: pattern
});
+ var rest_pattern = pattern.car instanceof LSymbol && pattern.cdr instanceof LSymbol;
+ if (trailing && rest_pattern) {
+ log('>> 13 (a)');
+ // handle (x ... y . z)
+ if (!is_nil(code.cdr)) {
+ return false;
+ }
+ var _car = pattern.car.valueOf();
+ var _cdr = pattern.cdr.valueOf();
+ bindings.symbols[_car] = code.car;
+ bindings.symbols[_cdr] = _nil;
+ return true;
+ //return is_pair(code.cdr) && code.cdr.length() > 1;
+ }
if (is_nil(code.cdr)) {
+ log('>> 13 (b)');
// last item in in call using in recursive calls on
// last element of the list
// case of pattern (p . rest) and code (0)
- var rest_pattern = pattern.car instanceof LSymbol && pattern.cdr instanceof LSymbol;
if (rest_pattern) {
// fix for SRFI-26 in recursive call of (b) ==> (<> . x)
// where <> is symbol
- if (!traverse(pattern.car, code.car, pattern_names, ellipsis)) {
+ if (!traverse(pattern.car, code.car, state)) {
return false;
}
log('>> 14');
@@ -9351,7 +9437,10 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
code: code
});
// case (x y) ===> (var0 var1 ... warn) where var1 match nil
- if (is_pair(pattern.cdr) && is_pair(pattern.cdr.cdr) && pattern.cdr.car instanceof LSymbol && LSymbol.is(pattern.cdr.cdr.car, ellipsis_symbol) && is_pair(pattern.cdr.cdr.cdr) && !LSymbol.is(pattern.cdr.cdr.cdr.car, ellipsis_symbol) && traverse(pattern.car, code.car, pattern_names, ellipsis) && traverse(pattern.cdr.cdr.cdr, code.cdr, pattern_names, ellipsis)) {
+ // trailing: true start processing of (var ... x . y)
+ if (is_pair(pattern.cdr) && is_pair(pattern.cdr.cdr) && pattern.cdr.car instanceof LSymbol && LSymbol.is(pattern.cdr.cdr.car, ellipsis_symbol) && is_pair(pattern.cdr.cdr.cdr) && !LSymbol.is(pattern.cdr.cdr.cdr.car, ellipsis_symbol) && traverse(pattern.car, code.car, state) && traverse(pattern.cdr.cdr.cdr, code.cdr, _objectSpread(_objectSpread({}, state), {}, {
+ trailing: true
+ }))) {
var _name6 = pattern.cdr.car.__name__;
log({
pattern: pattern,
@@ -9369,15 +9458,14 @@ function extract_patterns(pattern, code, symbols, ellipsis_symbol) {
pattern: pattern,
code: code
});
- var car = traverse(pattern.car, code.car, pattern_names, ellipsis);
- log({
- car: car,
- pattern: pattern.car,
- code: code.car
- });
- var cdr = traverse(pattern.cdr, code.cdr, pattern_names, ellipsis);
+ var car = traverse(pattern.car, code.car, state);
+ var cdr = traverse(pattern.cdr, code.cdr, state);
log({
+ $car_code: code.car,
+ $car_pattern: pattern.car,
car: car,
+ $cdr_code: code.cdr,
+ $cdr_pattern: pattern.cdr,
cdr: cdr
});
if (car && cdr) {
@@ -9570,46 +9658,47 @@ function transform_syntax() {
var item = bindings[_name7];
if (item === null) {
return;
- } else if (item) {
+ } else if (_name7 in bindings) {
log({
name: _name7,
binding: bindings[_name7]
});
if (is_pair(item)) {
log('[t 2 Pair ' + nested);
- var _car = item.car,
- _cdr = item.cdr;
+ var _car2 = item.car,
+ _cdr2 = item.cdr;
var _rest_expr = is_array ? expr.slice(2) : expr.cdr.cdr;
if (nested) {
- if (!is_nil(_cdr)) {
+ if (!is_nil(_cdr2)) {
log('|| next 1');
- next(_name7, _cdr);
+ next(_name7, _cdr2);
}
if (is_array && _rest_expr.length || !is_nil(_rest_expr) && !is_array) {
var _rest7 = transform_ellipsis_expr(_rest_expr, bindings, state, next);
if (is_array) {
- return _car.concat(_rest7);
- } else if (is_pair(_car)) {
- return _car.append(_rest7);
+ return _car2.concat(_rest7);
+ } else if (is_pair(_car2)) {
+ return _car2.append(_rest7);
} else {
log('UNKNOWN');
}
}
- return _car;
- } else if (is_pair(_car)) {
- if (!is_nil(_car.cdr)) {
+ return _car2;
+ } else if (is_pair(_car2)) {
+ if (!is_nil(_car2.cdr)) {
log('|| next 2');
- next(_name7, new Pair(_car.cdr, _cdr));
+ next(_name7, new Pair(_car2.cdr, _cdr2));
}
- return _car.car;
- } else if (is_nil(_cdr)) {
- return _car;
+ // wrap with Value to handle undefined
+ return new Value(_car2.car);
+ } else if (is_nil(_cdr2)) {
+ return _car2;
} else {
var last_pair = expr.last_pair();
if (last_pair.cdr instanceof LSymbol) {
log('|| next 3');
next(_name7, item.last_pair());
- return _car;
+ return _car2;
}
}
} else if (item instanceof Array) {
@@ -9672,6 +9761,7 @@ function transform_syntax() {
return expr;
}
if (is_pair(expr) || is_array) {
+ log('>> 0');
var first = is_array ? expr[0] : expr.car;
var second, rest_second;
if (is_array) {
@@ -9756,6 +9846,9 @@ function transform_syntax() {
// undefined can be null caused by null binding
// on empty ellipsis
if (car !== undefined) {
+ if (car instanceof Value) {
+ car.valueOf(), _readOnlyError("car");
+ }
if (is_spread) {
if (is_array) {
if (Array.isArray(car)) {
@@ -9812,6 +9905,9 @@ function transform_syntax() {
nested: true
});
if (car) {
+ if (car instanceof Value) {
+ car.valueOf(), _readOnlyError("car");
+ }
return new Pair(car, _nil);
}
return _nil;
@@ -9850,6 +9946,9 @@ function transform_syntax() {
value: value
});
if (typeof value !== 'undefined') {
+ if (value instanceof Value) {
+ value = value.valueOf();
+ }
if (is_array) {
_result3.push(value);
} else {
@@ -9890,6 +9989,9 @@ function transform_syntax() {
}
}
log('<<<< 2');
+ log({
+ result: _result3
+ });
return _result3;
}
}
@@ -10023,8 +10125,12 @@ function is_undef(value) {
return typeof value === 'undefined';
}
// -------------------------------------------------------------------------
+function get_proto(obj) {
+ return Object.getPrototypeOf(obj);
+}
+// -------------------------------------------------------------------------
function is_iterator(obj, symbol) {
- if (has_own_symbol(obj, symbol) || has_own_symbol(obj.__proto__, symbol)) {
+ if (has_own_symbol(obj, symbol) || has_own_symbol(get_proto(obj), symbol)) {
return is_function(obj[symbol]);
}
}
@@ -10319,8 +10425,7 @@ function let_macro(symbol) {
return pair.cdr.car;
});
}
- var args_name = gensym('args');
- return Pair.fromArray([LSymbol('let'), [[args_name, Pair(LSymbol('list'), args)]], [LSymbol('letrec'), [[code.car, Pair(LSymbol('lambda'), Pair(params, code.cdr.cdr))]], [LSymbol('apply'), code.car, args_name]]]);
+ return new Pair(Pair.fromArray([LSymbol('letrec'), [[code.car, Pair(LSymbol('lambda'), Pair(params, code.cdr.cdr))]], code.car]), args);
} else if (macro_expand) {
// Macro.defmacro are special macros that should return lips code
// here we use evaluate, so we need to check special flag set by
@@ -10338,7 +10443,7 @@ function let_macro(symbol) {
}
var i = 0;
function exec() {
- var output = new Pair(new LSymbol('begin'), code.cdr);
+ var output = hygienic_begin([env], code.cdr);
return _evaluate(output, {
env: env,
dynamic_env: env,
@@ -10458,7 +10563,7 @@ function guard_math_call(fn) {
}
// ----------------------------------------------------------------------
function pipe() {
- var _this8 = this;
+ var _this7 = this;
for (var _len8 = arguments.length, fns = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
fns[_key8] = arguments[_key8];
}
@@ -10470,7 +10575,7 @@ function pipe() {
args[_key9] = arguments[_key9];
}
return fns.reduce(function (args, f) {
- return [f.apply(_this8, args)];
+ return [f.apply(_this7, args)];
}, args)[0];
};
}
@@ -10535,7 +10640,7 @@ function curry(fn) {
typecheck('curry', fn, 'function');
var len = fn.length;
return function () {
- var _this9 = this;
+ var _this8 = this;
var args = init_args.slice();
// HACK: we use IIFE here to get rid of the name of the function.
// The JavaScript is smart and add name property to a function
@@ -10548,7 +10653,7 @@ function curry(fn) {
}
args = args.concat(more_args);
if (args.length >= len) {
- return fn.apply(_this9, args);
+ return fn.apply(_this8, args);
} else {
return curried;
}
@@ -11611,9 +11716,9 @@ LComplex.prototype.mul = function (n) {
};
// -------------------------------------------------------------------------
LComplex.prototype.complex_op = function (name, n, fn) {
- var _this10 = this;
+ var _this9 = this;
var calc = function calc(re, im) {
- var result = fn(_this10.__re__, re, _this10.__im__, im);
+ var result = fn(_this9.__re__, re, _this9.__im__, im);
if ('im' in result && 're' in result) {
if (result.im.cmp(0) === 0) {
return result.re;
@@ -12209,7 +12314,7 @@ LComplex.i = LComplex({
// :: Port abstraction - read should be a function that return next line
// -------------------------------------------------------------------------
function InputPort(read) {
- var _this11 = this;
+ var _this10 = this;
var env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : global_env;
if (typeof this !== 'undefined' && !(this instanceof InputPort) || typeof this === 'undefined') {
return new InputPort(read);
@@ -12233,12 +12338,12 @@ function InputPort(read) {
return _regeneratorRuntime.wrap(function _callee14$(_context14) {
while (1) switch (_context14.prev = _context14.next) {
case 0:
- if (_this11.char_ready()) {
+ if (_this10.char_ready()) {
_context14.next = 6;
break;
}
_context14.next = 3;
- return _this11._read();
+ return _this10._read();
case 3:
line = _context14.sent;
parser = new Parser({
@@ -12246,7 +12351,7 @@ function InputPort(read) {
});
parser.parse(line);
case 6:
- return _context14.abrupt("return", _this11.__parser__);
+ return _context14.abrupt("return", _this10.__parser__);
case 7:
case "end":
return _context14.stop();
@@ -12309,13 +12414,13 @@ InputPort.prototype.is_open = function () {
return this._with_parser !== null;
};
InputPort.prototype.close = function () {
- var _this12 = this;
+ var _this11 = this;
this.__parser__ = null;
// make content garbage collected, we assign null,
// because the value is in prototype
this._with_parser = null;
['read', 'close', 'read_char', 'peek-char', 'read_line'].forEach(function (name) {
- _this12[name] = function () {
+ _this11[name] = function () {
throw new Error('input-port: port is closed');
};
});
@@ -12361,20 +12466,20 @@ OutputPort.prototype.toString = function () {
var BufferedOutputPort = /*#__PURE__*/function (_OutputPort) {
_inherits(BufferedOutputPort, _OutputPort);
function BufferedOutputPort(fn) {
- var _this13;
+ var _this12;
_classCallCheck(this, BufferedOutputPort);
- _this13 = _callSuper(this, BufferedOutputPort, [function () {
- var _this14;
- return (_this14 = _this13)._write.apply(_this14, arguments);
+ _this12 = _callSuper(this, BufferedOutputPort, [function () {
+ var _this13;
+ return (_this13 = _this12)._write.apply(_this13, arguments);
}]);
typecheck('BufferedOutputPort', fn, 'function');
- read_only(_assertThisInitialized(_this13), '_fn', fn, {
+ read_only(_assertThisInitialized(_this12), '_fn', fn, {
hidden: true
});
- read_only(_assertThisInitialized(_this13), '_buffer', [], {
+ read_only(_assertThisInitialized(_this12), '_buffer', [], {
hidden: true
});
- return _this13;
+ return _this12;
}
_createClass(BufferedOutputPort, [{
key: "flush",
@@ -12387,13 +12492,13 @@ var BufferedOutputPort = /*#__PURE__*/function (_OutputPort) {
}, {
key: "_write",
value: function _write() {
- var _this15 = this;
+ var _this14 = this;
for (var _len18 = arguments.length, args = new Array(_len18), _key18 = 0; _key18 < _len18; _key18++) {
args[_key18] = arguments[_key18];
}
if (args.length) {
args.forEach(function (arg) {
- _this15._buffer.push(arg);
+ _this14._buffer.push(arg);
});
var last_value = this._buffer[this._buffer.length - 1];
if (last_value.match(/\n$/)) {
@@ -12406,7 +12511,7 @@ var BufferedOutputPort = /*#__PURE__*/function (_OutputPort) {
return BufferedOutputPort;
}(OutputPort); // -------------------------------------------------------------------------
function OutputStringPort(toString) {
- var _this16 = this;
+ var _this15 = this;
if (typeof this !== 'undefined' && !(this instanceof OutputStringPort) || typeof this === 'undefined') {
return new OutputStringPort(toString);
}
@@ -12419,7 +12524,7 @@ function OutputStringPort(toString) {
} else {
x = x.valueOf();
}
- _this16.__buffer__.push(x);
+ _this15.__buffer__.push(x);
};
}
OutputStringPort.prototype = Object.create(OutputPort.prototype);
@@ -12434,7 +12539,7 @@ OutputStringPort.prototype.valueOf = function () {
};
// -------------------------------------------------------------------------
function OutputFilePort(filename, fd) {
- var _this17 = this;
+ var _this16 = this;
if (typeof this !== 'undefined' && !(this instanceof OutputFilePort) || typeof this === 'undefined') {
return new OutputFilePort(filename, fd);
}
@@ -12450,7 +12555,7 @@ function OutputFilePort(filename, fd) {
} else {
x = x.valueOf();
}
- _this17.fs().write(_this17._fd, x, function (err) {
+ _this16.fs().write(_this16._fd, x, function (err) {
if (err) {
throw err;
}
@@ -12469,16 +12574,16 @@ OutputFilePort.prototype.internal = function (name) {
return user_env.get('**internal-env**').get(name);
};
OutputFilePort.prototype.close = function () {
- var _this18 = this;
+ var _this17 = this;
return new Promise(function (resolve, reject) {
- _this18.fs().close(_this18._fd, function (err) {
+ _this17.fs().close(_this17._fd, function (err) {
if (err) {
reject(err);
} else {
- read_only(_this18, '_fd', null, {
+ read_only(_this17, '_fd', null, {
hidden: true
});
- OutputPort.prototype.close.call(_this18);
+ OutputPort.prototype.close.call(_this17);
resolve();
}
});
@@ -12489,7 +12594,7 @@ OutputFilePort.prototype.toString = function () {
};
// -------------------------------------------------------------------------
function InputStringPort(string) {
- var _this19 = this;
+ var _this18 = this;
var env = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : global_env;
if (typeof this !== 'undefined' && !(this instanceof InputStringPort) || typeof this === 'undefined') {
return new InputStringPort(string);
@@ -12497,13 +12602,13 @@ function InputStringPort(string) {
typecheck('InputStringPort', string, 'string');
string = string.valueOf();
this._with_parser = this._with_init_parser.bind(this, function () {
- if (!_this19.__parser__) {
- _this19.__parser__ = new Parser({
+ if (!_this18.__parser__) {
+ _this18.__parser__ = new Parser({
env: env
});
- _this19.__parser__.parse(string);
+ _this18.__parser__.parse(string);
}
- return _this19.__parser__;
+ return _this18.__parser__;
});
read_only(this, '__type__', text_port);
this._make_defaults();
@@ -12570,13 +12675,13 @@ InputByteVectorPort.prototype.toString = function () {
return "#";
};
InputByteVectorPort.prototype.close = function () {
- var _this20 = this;
+ var _this19 = this;
read_only(this, '__vector__', _nil);
var err = function err() {
throw new Error('Input-binary-port: port is closed');
};
['read_u8', 'close', 'peek_u8', 'read_u8_vector'].forEach(function (name) {
- _this20[name] = err;
+ _this19[name] = err;
});
this.u8_ready = this.char_ready = function () {
return false;
@@ -12694,7 +12799,7 @@ InputBinaryFilePort.prototype.toString = function () {
};
// -------------------------------------------------------------------------
function OutputBinaryFilePort(filename, fd) {
- var _this21 = this;
+ var _this20 = this;
if (typeof this !== 'undefined' && !(this instanceof OutputBinaryFilePort) || typeof this === 'undefined') {
return new OutputBinaryFilePort(filename, fd);
}
@@ -12709,7 +12814,7 @@ function OutputBinaryFilePort(filename, fd) {
typecheck('write', x, ['number', 'uint8array']);
var buffer;
if (!fs) {
- fs = _this21.internal('fs');
+ fs = _this20.internal('fs');
}
if (LNumber.isNumber(x)) {
buffer = new Uint8Array([x.valueOf()]);
@@ -12717,7 +12822,7 @@ function OutputBinaryFilePort(filename, fd) {
buffer = new Uint8Array(Array.from(x));
}
return new Promise(function (resolve, reject) {
- fs.write(_this21._fd, buffer, function (err) {
+ fs.write(_this20._fd, buffer, function (err) {
if (err) {
reject(err);
} else {
@@ -12749,7 +12854,7 @@ EOF.prototype.toString = function () {
// Simpler way to create interpreter with interaction-environment
// -------------------------------------------------------------------------
function Interpreter(name) {
- var _this22 = this;
+ var _this21 = this;
var _ref27 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
stderr = _ref27.stderr,
stdin = _ref27.stdin,
@@ -12773,7 +12878,7 @@ function Interpreter(name) {
env: this.__env__
});
this.__env__.set('parent.frame', doc('parent.frame', function () {
- return _this22.__env__;
+ return _this21.__env__;
}, global_env.__env__['parent.frame'].__doc__));
var defaults_name = '**interaction-environment-defaults**';
this.set(defaults_name, get_props(obj).concat(defaults_name));
@@ -12793,7 +12898,7 @@ function Interpreter(name) {
// -------------------------------------------------------------------------
Interpreter.prototype.exec = /*#__PURE__*/function () {
var _ref28 = _asyncToGenerator(function (arg) {
- var _this23 = this;
+ var _this22 = this;
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return /*#__PURE__*/_regeneratorRuntime.mark(function _callee16() {
var _options$use_dynamic, use_dynamic, dynamic_env, env;
@@ -12806,12 +12911,12 @@ Interpreter.prototype.exec = /*#__PURE__*/function () {
// simple solution to overwrite this variable in each interpreter
// before evaluation of user code
if (!env) {
- env = _this23.__env__;
+ env = _this22.__env__;
}
if (!dynamic_env) {
dynamic_env = env;
}
- global_env.set('**interaction-environment**', _this23.__env__);
+ global_env.set('**interaction-environment**', _this22.__env__);
if (!Array.isArray(arg)) {
_context16.next = 10;
break;
@@ -12822,8 +12927,8 @@ Interpreter.prototype.exec = /*#__PURE__*/function () {
use_dynamic: use_dynamic
}));
case 10:
- _this23.__parser__.parse(arg);
- return _context16.abrupt("return", exec(_this23.__parser__, {
+ _this22.__parser__.parse(arg);
+ return _context16.abrupt("return", exec(_this22.__parser__, {
env: env,
dynamic_env: dynamic_env,
use_dynamic: use_dynamic
@@ -12999,12 +13104,12 @@ Environment.prototype.toString = function () {
};
// -------------------------------------------------------------------------
Environment.prototype.clone = function () {
- var _this24 = this;
+ var _this23 = this;
// duplicate refs
var env = {};
// TODO: duplicated Symbols
Object.keys(this.__env__).forEach(function (key) {
- env[key] = _this24.__env__[key];
+ env[key] = _this23.__env__[key];
});
return new Environment(env, this.__parent__, this.__name__);
};
@@ -13138,14 +13243,14 @@ Environment.prototype.set = function (name, value) {
// For internal use only
// -------------------------------------------------------------------------
Environment.prototype.constant = function (name, value) {
- var _this25 = this;
+ var _this24 = this;
if (this.__env__.hasOwnProperty(name)) {
throw new Error("Environment::constant: ".concat(name, " already exists"));
}
if (arguments.length === 1 && is_plain_object(arguments[0])) {
var obj = arguments[0];
Object.keys(obj).forEach(function (key) {
- _this25.constant(name, obj[key]);
+ _this24.constant(name, obj[key]);
});
} else {
Object.defineProperty(this.__env__, name, {
@@ -13321,14 +13426,14 @@ var global_env = new Environment({
// ------------------------------------------------------------------
read: doc('read', /*#__PURE__*/function () {
var _read2 = _asyncToGenerator(function () {
- var _this26 = this;
+ var _this25 = this;
var arg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
return /*#__PURE__*/_regeneratorRuntime.mark(function _callee17() {
var env, port;
return _regeneratorRuntime.wrap(function _callee17$(_context17) {
while (1) switch (_context17.prev = _context17.next) {
case 0:
- env = _this26.env;
+ env = _this25.env;
if (arg === null) {
port = internal(env, 'stdin');
} else {
@@ -13416,6 +13521,19 @@ var global_env = new Environment({
return str;
}, "(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."),
// ------------------------------------------------------------------
+ newline: doc('newline', function newline() {
+ var port = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
+ var display = global_env.get('display');
+ var use_dynamic = this.use_dynamic;
+ var env = global_env;
+ var dynamic_env = global_env;
+ call_function(display, ['\n', port], {
+ env: env,
+ dynamic_env: dynamic_env,
+ use_dynamic: use_dynamic
+ });
+ }, "(newline [port])\n\n Write newline character to standard output or given port"),
+ // ------------------------------------------------------------------
display: doc('display', function display(arg) {
var port = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
if (port === null) {
@@ -13438,7 +13556,7 @@ var global_env = new Environment({
}
var value = args.map(repr).join(' ');
port.write.call(global_env, value);
- global_env.get('newline')(port);
+ global_env.get('newline').call(this, port);
}, "(display-error . args)\n\n Display an error message on stderr."),
// ------------------------------------------------------------------
'%foldcase-string': doc('%foldcase-string', foldcase_string, "(%foldcase-string string)\n\n Same as string-foldcase but without typechecking"),
@@ -13506,7 +13624,7 @@ var global_env = new Environment({
}, "(cdr pair)\n\n This function returns the cdr (all but first) of the list."),
// ------------------------------------------------------------------
'set!': doc(new Macro('set!', function (code) {
- var _this27 = this;
+ var _this26 = this;
var _ref30 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
use_dynamic = _ref30.use_dynamic,
rest = _objectWithoutProperties(_ref30, _excluded4);
@@ -13560,7 +13678,7 @@ var global_env = new Environment({
if (parts.length > 1) {
var key = parts.pop();
var name = parts.join('.');
- var obj = _this27.get(name, {
+ var obj = _this26.get(name, {
throwError: false
});
if (obj) {
@@ -13616,6 +13734,8 @@ var global_env = new Environment({
env = this.get('**interaction-environment**');
}
}
+ var package_name = '@lips';
+ var has_package = file.startsWith(package_name);
// TODO: move **module-path** to internal env
var PATH = '**module-path**';
var module_path = global_env.get(PATH, {
@@ -13657,42 +13777,61 @@ var global_env = new Environment({
return code;
});
}
+ function get_root_dir() {
+ var __dirname = global_env.get('__dirname');
+ return __dirname.replace(/[^/]+$/, '');
+ }
if (is_node()) {
return new Promise( /*#__PURE__*/function () {
var _ref31 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee18(resolve, reject) {
- var path, cmd, _args20;
+ var _path, _fs, root_dir, cmd, _args20;
return _regeneratorRuntime.wrap(function _callee18$(_context18) {
while (1) switch (_context18.prev = _context18.next) {
case 0:
- path = nodeRequire('path');
+ _context18.prev = 0;
+ _context18.next = 3;
+ return node_ready;
+ case 3:
+ _path = nodeRequire('path');
+ _fs = nodeRequire('fs');
+ root_dir = get_root_dir();
+ if (has_package) {
+ file = file.replace(package_name, root_dir);
+ }
if (!module_path) {
- _context18.next = 6;
+ _context18.next = 12;
break;
}
module_path = module_path.valueOf();
- file = path.join(module_path, file);
- _context18.next = 12;
+ if (!file.startsWith('/')) {
+ file = _path.join(module_path, file);
+ }
+ _context18.next = 19;
break;
- case 6:
+ case 12:
+ if (file.startsWith('/')) {
+ _context18.next = 19;
+ break;
+ }
cmd = g_env.get('command-line', {
throwError: false
});
if (!cmd) {
- _context18.next = 11;
+ _context18.next = 18;
break;
}
- _context18.next = 10;
+ _context18.next = 17;
return cmd();
- case 10:
+ case 17:
_args20 = _context18.sent;
- case 11:
+ case 18:
if (_args20 && !is_nil(_args20)) {
process.cwd();
- file = path.join(path.dirname(_args20.car.valueOf()), file);
+ file = _path.join(_path.dirname(_args20.car.valueOf()), file);
}
- case 12:
- global_env.set(PATH, path.dirname(file));
- nodeRequire('fs').readFile(file, function (err, data) {
+ case 19:
+ global_env.set(PATH, _path.dirname(file));
+ _fs.readFile(file, function (err, data) {
if (err) {
reject(err);
global_env.set(PATH, module_path);
@@ -13707,20 +13846,37 @@ var global_env = new Environment({
}
}
});
- case 14:
+ _context18.next = 26;
+ break;
+ case 23:
+ _context18.prev = 23;
+ _context18.t0 = _context18["catch"](0);
+ console.error(_context18.t0);
+ case 26:
case "end":
return _context18.stop();
}
- }, _callee18);
+ }, _callee18, null, [[0, 23]]);
}));
return function (_x14, _x15) {
return _ref31.apply(this, arguments);
};
}());
}
+ if (has_package) {
+ var _global_env$get, _path3;
+ var _path2 = (_global_env$get = global_env.get('__dirname', {
+ throwError: false
+ })) !== null && _global_env$get !== void 0 ? _global_env$get : current_script;
+ (_path3 = _path2) !== null && _path3 !== void 0 ? _path3 : _path2 = current_script;
+ var _root = _path2.replace(/dist\/?[^\/]*$/, '');
+ file = file.replace(package_name, _root);
+ }
if (module_path) {
module_path = module_path.valueOf();
- file = module_path + '/' + file.replace(/^\.?\/?/, '');
+ if (!file.startsWith('/')) {
+ file = module_path + '/' + file.replace(/^\.?\/?/, '');
+ }
}
return fetch(file).then(function (code) {
global_env.set(PATH, file.replace(/\/[^/]*$/, ''));
@@ -13747,7 +13903,7 @@ var global_env = new Environment({
// ------------------------------------------------------------------
'do': doc(new Macro('do', /*#__PURE__*/function () {
var _ref32 = _asyncToGenerator(function (code, _ref33) {
- var _this28 = this;
+ var _this27 = this;
var use_dynamic = _ref33.use_dynamic,
error = _ref33.error;
return /*#__PURE__*/_regeneratorRuntime.mark(function _callee19() {
@@ -13755,7 +13911,7 @@ var global_env = new Environment({
return _regeneratorRuntime.wrap(function _callee19$(_context20) {
while (1) switch (_context20.prev = _context20.next) {
case 0:
- self = _this28;
+ self = _this27;
dynamic_env = self;
scope = self.inherit('do');
vars = code.car;
@@ -14087,8 +14243,8 @@ var global_env = new Environment({
}
env.set(name, parameter);
}
- var body = new Pair(new LSymbol('begin'), code.cdr);
- return _evaluate(body, _objectSpread(_objectSpread({}, eval_args), {}, {
+ var expr = hygienic_begin([env, eval_args.dynamic_env], code.cdr);
+ return _evaluate(expr, _objectSpread(_objectSpread({}, eval_args), {}, {
env: env
}));
}), "(syntax-parameterize (bindings) body)\n\n Macro work similar to let-syntax but the the bindnds will be exposed to the user.\n With syntax-parameterize you can define anaphoric macros."),
@@ -14192,21 +14348,14 @@ var global_env = new Environment({
}, "(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 _this29 = this;
env = env || this.get('interaction-environment').call(this);
- return _evaluate(code, {
- env: env,
- dynamic_env: env,
- error: function error(e) {
- var error = global_env.get('display-error');
- error.call(_this29, e.message);
- if (e.code) {
- var stack = e.code.map(function (line, i) {
- return "[".concat(i + 1, "]: ").concat(line);
- }).join('\n');
- error.call(_this29, stack);
- }
- }
+ return new Promise(function (resolve, reject) {
+ var result = _evaluate(code, {
+ env: env,
+ dynamic_env: env,
+ error: reject
+ });
+ resolve(result);
});
}, "(eval expr)\n (eval expr environment)\n\n Function that evaluates LIPS Scheme code. If the second argument is provided\n it will be the environment that the code is evaluated in."),
// ------------------------------------------------------------------
@@ -14284,7 +14433,7 @@ var global_env = new Environment({
}
}
var rest = __doc__ ? code.cdr.cdr : code.cdr;
- var output = new Pair(new LSymbol('begin'), rest);
+ var output = hygienic_begin([env, dynamic_env], rest);
var eval_args = {
env: env,
dynamic_env: dynamic_env,
@@ -14617,7 +14766,11 @@ var global_env = new Environment({
// -----------------------------------------------------------------
function unquote_splice(pair, unquote_cnt, max_unq) {
if (unquote_cnt < max_unq) {
- return new Pair(new Pair(pair.car.car, recur(pair.car.cdr, unquote_cnt, max_unq)), _nil);
+ var cdr = _nil;
+ if (!is_nil(pair.cdr)) {
+ cdr = recur(pair.cdr, unquote_cnt - 1, max_unq);
+ }
+ return new Pair(new Pair(pair.car.car, recur(pair.car.cdr, unquote_cnt, max_unq)), cdr);
}
var lists = [];
return function next(node) {
@@ -14816,7 +14969,7 @@ var global_env = new Environment({
}, "(clone list)\n\n Function that returns a clone of the list, that does not share any pairs with the\n original, so the clone can be safely mutated without affecting the original."),
// ------------------------------------------------------------------
append: doc('append', function append() {
- var _global_env$get;
+ var _global_env$get2;
for (var _len25 = arguments.length, items = new Array(_len25), _key25 = 0; _key25 < _len25; _key25++) {
items[_key25] = arguments[_key25];
}
@@ -14826,7 +14979,7 @@ var global_env = new Environment({
}
return item;
});
- return (_global_env$get = global_env.get('append!')).call.apply(_global_env$get, [this].concat(_toConsumableArray(items)));
+ return (_global_env$get2 = global_env.get('append!')).call.apply(_global_env$get2, [this].concat(_toConsumableArray(items)));
}, "(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 () {
@@ -15163,7 +15316,7 @@ var global_env = new Environment({
}, "(string->number number [radix])\n\n Function that parses a string into a number."),
// ------------------------------------------------------------------
'try': doc(new Macro('try', function (code, _ref41) {
- var _this30 = this;
+ var _this28 = this;
var use_dynamic = _ref41.use_dynamic;
_ref41.error;
return new Promise(function (resolve, reject) {
@@ -15199,15 +15352,15 @@ var global_env = new Environment({
};
}
var args = {
- env: _this30,
+ env: _this28,
use_dynamic: use_dynamic,
- dynamic_env: _this30,
+ dynamic_env: _this28,
error: function error(e) {
if (e instanceof IgnoreException) {
throw e;
}
if (catch_clause) {
- var env = _this30.inherit('try');
+ var env = _this28.inherit('try');
var name = catch_clause.cdr.car.car;
if (!(name instanceof LSymbol)) {
throw new Error('try: invalid syntax: catch require variable name');
@@ -15217,7 +15370,7 @@ var global_env = new Environment({
var catch_args = {
env: env,
use_dynamic: use_dynamic,
- dynamic_env: _this30,
+ dynamic_env: _this28,
error: function error(e) {
catch_error = true;
reject(e);
@@ -15267,7 +15420,7 @@ var global_env = new Environment({
}, "(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;
+ var _global_env$get3;
typecheck('for-each', fn, 'function');
for (var _len32 = arguments.length, lists = new Array(_len32 > 1 ? _len32 - 1 : 0), _key32 = 1; _key32 < _len32; _key32++) {
lists[_key32 - 1] = arguments[_key32];
@@ -15278,14 +15431,14 @@ var global_env = new Environment({
// we need to use call(this because babel transpile this code into:
// var ret = map.apply(void 0, [fn].concat(lists));
// it don't work with weakBind
- var ret = (_global_env$get2 = global_env.get('map')).call.apply(_global_env$get2, [this, fn].concat(lists));
+ var ret = (_global_env$get3 = global_env.get('map')).call.apply(_global_env$get3, [this, fn].concat(lists));
if (is_promise(ret)) {
return ret.then(function () {});
}
}, "(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 _this31 = this;
+ var _this29 = this;
for (var _len33 = arguments.length, lists = new Array(_len33 > 1 ? _len33 - 1 : 0), _key33 = 1; _key33 < _len33; _key33++) {
lists[_key33 - 1] = arguments[_key33];
}
@@ -15294,7 +15447,7 @@ var global_env = new Environment({
lists.forEach(function (arg, i) {
typecheck('map', arg, ['pair', 'nil'], i + 1);
// detect cycles
- if (is_pair(arg) && !is_list.call(_this31, arg)) {
+ if (is_pair(arg) && !is_list.call(_this29, arg)) {
throw new Error("map: argument ".concat(i + 1, " is not a list"));
}
});
@@ -15316,7 +15469,7 @@ var global_env = new Environment({
use_dynamic: use_dynamic
});
return unpromise(result, function (head) {
- return unpromise(map.call.apply(map, [_this31, fn].concat(_toConsumableArray(lists.map(function (l) {
+ return unpromise(map.call.apply(map, [_this29, fn].concat(_toConsumableArray(lists.map(function (l) {
return l.cdr;
})))), function (rest) {
return new Pair(head, rest);
@@ -15340,18 +15493,6 @@ var global_env = new Environment({
}
}, "(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');
- typecheck('some', list, ['pair', 'nil']);
- if (is_null(list)) {
- return false;
- } else {
- return unpromise(fn(list.car), function (value) {
- return value || some(fn, list.cdr);
- });
- }
- }, "(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 Analogous to Python any(map(fn, list))."),
- // ------------------------------------------------------------------
fold: doc('fold', fold('fold', function (fold, fn, init) {
for (var _len34 = arguments.length, lists = new Array(_len34 > 3 ? _len34 - 3 : 0), _key34 = 3; _key34 < _len34; _key34++) {
lists[_key34 - 3] = arguments[_key34];
@@ -15398,7 +15539,7 @@ var global_env = new Environment({
}, "(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 _this32 = this;
+ var _this30 = this;
for (var _len36 = arguments.length, lists = new Array(_len36 > 3 ? _len36 - 3 : 0), _key37 = 3; _key37 < _len36; _key37++) {
lists[_key37 - 3] = arguments[_key37];
}
@@ -15412,7 +15553,7 @@ var global_env = new Environment({
return unpromise(fn.apply(void 0, _toConsumableArray(lists.map(function (l) {
return l.car;
})).concat([init])), function (value) {
- return reduce.call.apply(reduce, [_this32, fn, value].concat(_toConsumableArray(lists.map(function (l) {
+ return reduce.call.apply(reduce, [_this30, fn, value].concat(_toConsumableArray(lists.map(function (l) {
return l.cdr;
}))));
});
@@ -15806,8 +15947,8 @@ combinations(['d', 'a'], 2, 5).forEach(function (spec) {
function reversseFind(dir, fn) {
var parts = dir.split(path.sep).filter(Boolean);
for (var i = parts.length; i--;) {
- var _path;
- var p = (_path = path).join.apply(_path, ['/'].concat(_toConsumableArray(parts.slice(0, i + 1))));
+ var _path4;
+ var p = (_path4 = path).join.apply(_path4, ['/'].concat(_toConsumableArray(parts.slice(0, i + 1))));
if (fn(p)) {
return p;
}
@@ -15831,7 +15972,7 @@ var noop = function noop() {};
function node_specific() {
return _node_specific.apply(this, arguments);
} // -------------------------------------------------------------------------
-/* c8 ignore next 11 */
+/* c8 ignore next 15 */
function _node_specific() {
_node_specific = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee23() {
var _yield$import, createRequire, moduleURL, __dirname__, __filename__;
@@ -15905,16 +16046,20 @@ function _node_specific() {
}));
return _node_specific.apply(this, arguments);
}
+var node_ready; // Scheme load function need to wait for node_specific
if (is_node()) {
- node_specific();
-} else if (typeof window !== 'undefined' && window === root) {
- global_env.set('window', window);
- global_env.set('global', undefined);
- global_env.set('self', window);
-} else if (typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined') {
- global_env.set('self', self);
- global_env.set('window', undefined);
- global_env.set('global', undefined);
+ node_ready = node_specific();
+} else {
+ node_ready = Promise.resolve();
+ if (typeof window !== 'undefined' && window === root) {
+ global_env.set('window', window);
+ global_env.set('global', undefined);
+ global_env.set('self', window);
+ } else if (typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined') {
+ global_env.set('self', self);
+ global_env.set('window', undefined);
+ global_env.set('global', undefined);
+ }
}
// -------------------------------------------------------------------------
function typeErrorMessage(fn, got, expected) {
@@ -16830,6 +16975,7 @@ function bootstrap() {
url = "https://cdn.jsdelivr.net/npm/@jcubic/lips@".concat(lips.version, "/").concat(std);
}
}
+ global_env.set('__dirname', url.replace(/[^/]+$/, ''));
var load = global_env.get('load');
return load.call(user_env, url, global_env);
}
@@ -17243,17 +17389,17 @@ if (typeof window !== 'undefined') {
// -------------------------------------------------------------------------
var banner = function () {
// Rollup tree-shaking is removing the variable if it's normal string because
- // obviously 'Mon, 27 May 2024 11:41:47 +0000' == '{{' + 'DATE}}'; can be removed
+ // obviously 'Fri, 08 Nov 2024 13:26:12 +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('Mon, 27 May 2024 11:41:47 +0000').valueOf();
+ var date = LString('Fri, 08 Nov 2024 13:26:12 +0000').valueOf();
var _date = date === '{{' + 'DATE}}' ? new Date() : new Date(date);
var _format = function _format(x) {
return x.toString().padStart(2, '0');
};
var _year = _date.getFullYear();
var _build = [_year, _format(_date.getMonth() + 1), _format(_date.getDate())].join('-');
- var banner = "\n __ __ __\n / / \\ \\ _ _ ___ ___ \\ \\\n| | \\ \\ | | | || . \\/ __> | |\n| | > \\ | |_ | || _/\\__ \\ | |\n| | / ^ \\ |___||_||_| <___/ | |\n \\_\\ /_/ \\_\\ /_/\n\nLIPS Interpreter 1.0.0-beta.19 (".concat(_build, ") \nCopyright (c) 2018-").concat(_year, " Jakub T. Jankiewicz\n\nType (env) to see environment with functions macros and variables. You can also\nuse (help name) to display help for specific 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/, '');
+ var banner = "\n __ __ __\n / / \\ \\ _ _ ___ ___ \\ \\\n| | \\ \\ | | | || . \\/ __> | |\n| | > \\ | |_ | || _/\\__ \\ | |\n| | / ^ \\ |___||_||_| <___/ | |\n \\_\\ /_/ \\_\\ /_/\n\nLIPS Interpreter DEV (".concat(_build, ") \nCopyright (c) 2018-").concat(_year, " Jakub T. Jankiewicz\n\nType (env) to see environment with functions macros and variables. You can also\nuse (help name) to display help for specific 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 banner;
}();
// -------------------------------------------------------------------------
@@ -17285,8 +17431,8 @@ read_only(LString, '__class__', 'string');
read_only(QuotedPromise, '__class__', 'promise');
read_only(Parameter, '__class__', 'parameter');
// -------------------------------------------------------------------------
-var version = '1.0.0-beta.19';
-var date = 'Mon, 27 May 2024 11:41:47 +0000';
+var version = 'DEV';
+var date = 'Fri, 08 Nov 2024 13:26:12 +0000';
// unwrap async generator into Promise
var parse = compose(uniterate_async, _parse);
diff --git a/dist/lips.esm.min.js b/dist/lips.esm.min.js
index 228184631..4a486c70e 100644
--- a/dist/lips.esm.min.js
+++ b/dist/lips.esm.min.js
@@ -4,7 +4,7 @@
* | | \ \ | | | || . \/ __> | |
* | | > \ | |_ | || _/\__ \ | |
* | | / ^ \ |___||_||_| <___/ | |
- * \_\ /_/ \_\ /_/ v. 1.0.0-beta.19
+ * \_\ /_/ \_\ /_/ v. DEV
*
* LIPS is Pretty Simple - Scheme based Powerful LISP in JavaScript
*
@@ -31,9 +31,9 @@
* Copyright (c) 2014-present, Facebook, Inc.
* released under MIT license
*
- * build: Mon, 27 May 2024 11:41:47 +0000
+ * build: Fri, 08 Nov 2024 13:26:12 +0000
*/
-function _classApplyDescriptorGet(e,t){if(t.get){return t.get.call(e)}return t.value}function _classExtractFieldDescriptor(e,t,r){if(!t.has(e)){throw new TypeError("attempted to "+r+" private field on non-instance")}return t.get(e)}function _classPrivateFieldGet(e,t){var r=_classExtractFieldDescriptor(e,t,"get");return _classApplyDescriptorGet(e,r)}function _classApplyDescriptorSet(e,t,r){if(t.set){t.set.call(e,r)}else{if(!t.writable){throw new TypeError("attempted to set read only private field")}t.value=r}}function _classPrivateFieldSet(e,t,r){var n=_classExtractFieldDescriptor(e,t,"set");_classApplyDescriptorSet(e,n,r);return r}function _assertThisInitialized(e){if(e===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return e}function _setPrototypeOf(e,t){_setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function e(t,r){t.__proto__=r;return t};return _setPrototypeOf(e,t)}function _isNativeReflectConstruct$1(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct$1=function e(){return!!t})()}function _construct(e,t,r){if(_isNativeReflectConstruct$1())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var i=new(e.bind.apply(e,n));return r&&_setPrototypeOf(i,r.prototype),i}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _iterableToArray(e){if(typeof Symbol!=="undefined"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function _arrayLikeToArray$1(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 _objectWithoutProperties(e,t){if(e==null)return{};var r=_objectWithoutPropertiesLoose(e,t);var n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i=0)continue;if(!Object.prototype.propertyIsEnumerable.call(e,n))continue;r[n]=e[n]}}return r}function _iterableToArrayLimit(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,a,o,u=[],s=!0,c=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);s=!0);}catch(e){c=!0,i=e}finally{try{if(!s&&null!=r["return"]&&(o=r["return"](),Object(o)!==o))return}finally{if(c)throw i}}return u}}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray$1(e,t)||_nonIterableRest()}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray$1(e)}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray$1(e)||_nonIterableSpread()}function _OverloadYield(e,t){this.v=e,this.k=t}function _awaitAsyncGenerator(e){return new _OverloadYield(e,0)}function AsyncGenerator(o){var a,u;function s(r,e){try{var n=o[r](e),i=n.value,a=i instanceof _OverloadYield;Promise.resolve(a?i.v:i).then(function(e){if(a){var t="return"===r?"return":"next";if(!i.k||e.done)return s(t,e);e=o[t](e).value}c(n.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:!0});break;case"throw":a.reject(t);break;default:a.resolve({value:t,done:!1})}(a=a.next)?s(a.key,a.arg):u=null}this._invoke=function(n,i){return new Promise(function(e,t){var r={key:n,arg:i,resolve:e,reject:t,next:null};u?u=u.next=r:(a=u=r,s(n,i))})},"function"!=typeof o["return"]&&(this["return"]=void 0)}AsyncGenerator.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},AsyncGenerator.prototype.next=function(e){return this._invoke("next",e)},AsyncGenerator.prototype["throw"]=function(e){return this._invoke("throw",e)},AsyncGenerator.prototype["return"]=function(e){return this._invoke("return",e)};function _wrapAsyncGenerator(e){return function(){return new AsyncGenerator(e.apply(this,arguments))}}function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e["default"]:e}var regeneratorRuntime$1={exports:{}};var _typeof={exports:{}};(function(t){function r(e){"@babel/helpers - typeof";return t.exports=r="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},t.exports.__esModule=true,t.exports["default"]=t.exports,r(e)}t.exports=r,t.exports.__esModule=true,t.exports["default"]=t.exports})(_typeof);var _typeofExports=_typeof.exports;(function(P){var N=_typeofExports["default"];function B(){P.exports=B=function e(){return o},P.exports.__esModule=true,P.exports["default"]=P.exports;var c,o={},e=Object.prototype,l=e.hasOwnProperty,f=Object.defineProperty||function(e,t,r){e[t]=r.value},t="function"==typeof Symbol?Symbol:{},i=t.iterator||"@@iterator",r=t.asyncIterator||"@@asyncIterator",n=t.toStringTag||"@@toStringTag";function a(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{a({},"")}catch(c){a=function e(t,r,n){return t[r]=n}}function u(e,t,r,n){var i=t&&t.prototype instanceof s?t:s,a=Object.create(i.prototype),o=new C(n||[]);return f(a,"_invoke",{value:S(e,r,o)}),a}function _(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}o.wrap=u;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",y={};function s(){}function v(){}function b(){}var g={};a(g,i,function(){return this});var w=Object.getPrototypeOf,D=w&&w(w(O([])));D&&D!==e&&l.call(D,i)&&(g=D);var x=b.prototype=s.prototype=Object.create(g);function L(e){["next","throw","return"].forEach(function(t){a(e,t,function(e){return this._invoke(t,e)})})}function E(u,s){function c(e,t,r,n){var i=_(u[e],u,t);if("throw"!==i.type){var a=i.arg,o=a.value;return o&&"object"==N(o)&&l.call(o,"__await")?s.resolve(o.__await).then(function(e){c("next",e,r,n)},function(e){c("throw",e,r,n)}):s.resolve(o).then(function(e){a.value=e,r(a)},function(e){return c("throw",e,r,n)})}n(i.arg)}var i;f(this,"_invoke",{value:function e(r,n){function t(){return new s(function(e,t){c(r,n,e,t)})}return i=i?i.then(t,t):t()}})}function S(a,o,u){var s=p;return function(e,t){if(s===h)throw new Error("Generator is already running");if(s===m){if("throw"===e)throw t;return{value:c,done:!0}}for(u.method=e,u.arg=t;;){var r=u.delegate;if(r){var n=A(r,u);if(n){if(n===y)continue;return n}}if("next"===u.method)u.sent=u._sent=u.arg;else if("throw"===u.method){if(s===p)throw s=m,u.arg;u.dispatchException(u.arg)}else"return"===u.method&&u.abrupt("return",u.arg);s=h;var i=_(a,o,u);if("normal"===i.type){if(s=u.done?m:d,i.arg===y)continue;return{value:i.arg,done:u.done}}"throw"===i.type&&(s=m,u.method="throw",u.arg=i.arg)}}}function A(e,t){var r=t.method,n=e.iterator[r];if(n===c)return t.delegate=null,"throw"===r&&e.iterator["return"]&&(t.method="return",t.arg=c,A(e,t),"throw"===t.method)||"return"!==r&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+r+"' method")),y;var i=_(n,e.iterator,t.arg);if("throw"===i.type)return t.method="throw",t.arg=i.arg,t.delegate=null,y;var a=i.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=c),t.delegate=null,y):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,y)}function F(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),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 C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(F,this),this.reset(!0)}function O(t){if(t||""===t){var e=t[i];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,n=function e(){for(;++r=0;--i){var a=this.tryEntries[i],o=a.completion;if("root"===a.tryLoc)return t("end");if(a.tryLoc<=this.prev){var u=l.call(a,"catchLoc"),s=l.call(a,"finallyLoc");if(u&&s){if(this.prev=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&l.call(i,"finallyLoc")&&this.prev=0;--r){var n=this.tryEntries[r];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),k(n),y}},catch:function e(t){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc===t){var i=n.completion;if("throw"===i.type){var a=i.arg;k(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function e(t,r,n){return this.delegate={iterator:O(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=c),y}},o}P.exports=B,P.exports.__esModule=true,P.exports["default"]=P.exports})(regeneratorRuntime$1);var regeneratorRuntimeExports=regeneratorRuntime$1.exports;var runtime=regeneratorRuntimeExports();var regenerator=runtime;try{regeneratorRuntime=runtime}catch(e){if(typeof globalThis==="object"){globalThis.regeneratorRuntime=runtime}else{Function("r","regeneratorRuntime = r")(runtime)}}var _regeneratorRuntime=getDefaultExportFromCjs(regenerator);let decoder;try{decoder=new TextDecoder}catch(e){}let src;let srcEnd;let position$1=0;const LEGACY_RECORD_INLINE_ID=105;const RECORD_DEFINITIONS_ID=57342;const RECORD_INLINE_ID=57343;const BUNDLED_STRINGS_ID=57337;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;try{new Function("")}catch(e){inlineObjectReadThreshold=Infinity}class Decoder{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[safeKey(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(src){return saveState(()=>{clearSource();return this?this.decode(t,e):Decoder.prototype.decode.call(defaultOptions,t,e)})}srcEnd=e>-1?e:t.length;position$1=0;srcStringEnd=0;srcString=null;bundledStrings$1=null;src=t;try{dataView=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))}catch(e){src=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 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(r,n){let i,a=0;try{let e=r.length;sequentialMode=true;let t=this?this.decode(r,e):defaultDecoder.decode(r,e);if(n){if(n(t)===false){return}while(position$1=bundledStrings$1.postBundlePosition){let e=new Error("Unexpected bundle position");e.incomplete=true;throw e}position$1=bundledStrings$1.postBundlePosition;bundledStrings$1=null}if(position$1==srcEnd){currentStructures=null;src=null;if(referenceMap)referenceMap=null}else if(position$1>srcEnd){let e=new Error("Unexpected end of CBOR data");e.incomplete=true;throw e}else if(!sequentialMode){throw new Error("Data read, but end of buffer not reached")}return e}catch(e){clearSource();if(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")){e.incomplete=true}throw e}}function read(){let n=src[position$1++];let i=n>>5;n=n&31;if(n>23){switch(n){case 24:n=src[position$1++];break;case 25:if(i==7){return getFloat16()}n=dataView.getUint16(position$1);position$1+=2;break;case 26:if(i==7){let t=dataView.getFloat32(position$1);if(currentDecoder.useFloat32>2){let e=mult10[(src[position$1]&127)<<1|src[position$1+1]>>7];position$1+=4;return(e*t+(t>0?.5:-.5)>>0)/e}position$1+=4;return t}n=dataView.getUint32(position$1);position$1+=4;break;case 27:if(i==7){let e=dataView.getFloat64(position$1);position$1+=8;return e}if(i>1){if(dataView.getUint32(position$1)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");n=dataView.getUint32(position$1+4)}else if(currentDecoder.int64AsNumber){n=dataView.getUint32(position$1)*4294967296;n+=dataView.getUint32(position$1+4)}else n=dataView.getBigUint64(position$1);position$1+=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=read())!=STOP_CODE){e[r++]=t}return i==4?e:i==3?e.join(""):Buffer.concat(e);case 5:let n;if(currentDecoder.mapsAsObjects){let e={};if(currentDecoder.keyMap)while((n=read())!=STOP_CODE)e[safeKey(currentDecoder.decodeKey(n))]=read();else while((n=read())!=STOP_CODE)e[safeKey(n)]=read();return e}else{if(restoreMapsAsObject){currentDecoder.mapsAsObjects=true;restoreMapsAsObject=false}let e=new Map;if(currentDecoder.keyMap)while((n=read())!=STOP_CODE)e.set(currentDecoder.decodeKey(n),read());else while((n=read())!=STOP_CODE)e.set(n,read());return e}case 7:return STOP_CODE;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 readBin(n);case 3:if(srcStringEnd>=position$1){return srcString.slice(position$1-srcStringStart,(position$1+=n)-srcStringStart)}if(srcStringEnd==0&&srcEnd<140&&n<32){let e=n<16?shortStringInJS(n):longStringInJS(n);if(e!=null)return e}return readFixedString(n);case 4:let t=new Array(n);for(let e=0;e=BUNDLED_STRINGS_ID){let e=currentStructures[n&8191];if(e){if(!e.read)e.read=createStructureReader(e);return e.read()}if(n<65536){if(n==RECORD_INLINE_ID){let e=readJustLength();let t=read();let r=read();recordDefinition(t,r);let n={};if(currentDecoder.keyMap)for(let t=2;t23){switch(t){case 24:t=src[position$1++];break;case 25:t=dataView.getUint16(position$1);position$1+=2;break;case 26:t=dataView.getUint32(position$1);position$1+=4;break;default:throw new Error("Expected array header, but got "+src[position$1-1])}}let r=this.compiledReader;while(r){if(r.propertyCount===t)return r(read);r=r.next}if(this.slowReads++>=inlineObjectReadThreshold){let e=this.length==t?this:this.slice(0,t);r=currentDecoder.keyMap?new Function("r","return {"+e.map(e=>currentDecoder.decodeKey(e)).map(e=>validName.test(e)?safeKey(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}"):new Function("r","return {"+e.map(e=>validName.test(e)?safeKey(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}");if(this.compiledReader)r.next=this.compiledReader;r.propertyCount=t;this.compiledReader=r;return r(read)}let n={};if(currentDecoder.keyMap)for(let e=0;e64&&decoder)return decoder.decode(src.subarray(position$1,position$1+=e));const r=position$1+e;const n=[];t="";while(position$165535){e-=65536;n.push(e>>>10&1023|55296);e=56320|e&1023}n.push(e)}else{n.push(i)}if(n.length>=4096){t+=fromCharCode.apply(String,n);n.length=0}}if(n.length>0){t+=fromCharCode.apply(String,n)}return t}let fromCharCode=String.fromCharCode;function longStringInJS(t){let r=position$1;let n=new Array(t);for(let e=0;e0){position$1=r;return}n[e]=i}return fromCharCode.apply(String,n)}function shortStringInJS(h){if(h<4){if(h<2){if(h===0)return"";else{let e=src[position$1++];if((e&128)>1){position$1-=1;return}return fromCharCode(e)}}else{let e=src[position$1++];let t=src[position$1++];if((e&128)>0||(t&128)>0){position$1-=2;return}if(h<3)return fromCharCode(e,t);let r=src[position$1++];if((r&128)>0){position$1-=3;return}return fromCharCode(e,t,r)}}else{let f=src[position$1++];let _=src[position$1++];let p=src[position$1++];let d=src[position$1++];if((f&128)>0||(_&128)>0||(p&128)>0||(d&128)>0){position$1-=4;return}if(h<6){if(h===4)return fromCharCode(f,_,p,d);else{let e=src[position$1++];if((e&128)>0){position$1-=5;return}return fromCharCode(f,_,p,d,e)}}else if(h<8){let e=src[position$1++];let t=src[position$1++];if((e&128)>0||(t&128)>0){position$1-=6;return}if(h<7)return fromCharCode(f,_,p,d,e,t);let r=src[position$1++];if((r&128)>0){position$1-=7;return}return fromCharCode(f,_,p,d,e,t,r)}else{let u=src[position$1++];let s=src[position$1++];let c=src[position$1++];let l=src[position$1++];if((u&128)>0||(s&128)>0||(c&128)>0||(l&128)>0){position$1-=8;return}if(h<10){if(h===8)return fromCharCode(f,_,p,d,u,s,c,l);else{let e=src[position$1++];if((e&128)>0){position$1-=9;return}return fromCharCode(f,_,p,d,u,s,c,l,e)}}else if(h<12){let e=src[position$1++];let t=src[position$1++];if((e&128)>0||(t&128)>0){position$1-=10;return}if(h<11)return fromCharCode(f,_,p,d,u,s,c,l,e,t);let r=src[position$1++];if((r&128)>0){position$1-=11;return}return fromCharCode(f,_,p,d,u,s,c,l,e,t,r)}else{let n=src[position$1++];let i=src[position$1++];let a=src[position$1++];let o=src[position$1++];if((n&128)>0||(i&128)>0||(a&128)>0||(o&128)>0){position$1-=12;return}if(h<14){if(h===12)return fromCharCode(f,_,p,d,u,s,c,l,n,i,a,o);else{let e=src[position$1++];if((e&128)>0){position$1-=13;return}return fromCharCode(f,_,p,d,u,s,c,l,n,i,a,o,e)}}else{let e=src[position$1++];let t=src[position$1++];if((e&128)>0||(t&128)>0){position$1-=14;return}if(h<15)return fromCharCode(f,_,p,d,u,s,c,l,n,i,a,o,e,t);let r=src[position$1++];if((r&128)>0){position$1-=15;return}return fromCharCode(f,_,p,d,u,s,c,l,n,i,a,o,e,t,r)}}}}}function readBin(e){return currentDecoder.copyBuffers?Uint8Array.prototype.slice.call(src,position$1,position$1+=e):src.subarray(position$1,position$1+=e)}let f32Array=new Float32Array(1);let u8Array=new Uint8Array(f32Array.buffer,0,4);function getFloat16(){let t=src[position$1++];let r=src[position$1++];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}u8Array[3]=t&128|(e>>1)+56;u8Array[2]=(t&7)<<5|r>>3;u8Array[1]=r<<5;u8Array[0]=0;return f32Array[0]}new Array(4096);class Tag{constructor(e,t){this.value=e;this.tag=t}}currentExtensions[0]=e=>{return new Date(e)};currentExtensions[1]=e=>{return new Date(Math.round(e*1e3))};currentExtensions[2]=r=>{let n=BigInt(0);for(let e=0,t=r.byteLength;e{return BigInt(-1)-currentExtensions[2](e)};currentExtensions[4]=e=>{return+(e[1]+"e"+e[0])};currentExtensions[5]=e=>{return e[1]*Math.exp(e[0]*Math.log(2))};const recordDefinition=(e,t)=>{e=e-57344;let r=currentStructures[e];if(r&&r.isShared){(currentStructures.restoreStructures||(currentStructures.restoreStructures=[]))[e]=r}currentStructures[e]=t;t.read=createStructureReader(t)};currentExtensions[LEGACY_RECORD_INLINE_ID]=r=>{let e=r.length;let n=r[1];recordDefinition(r[0],n);let i={};for(let t=2;t{if(bundledStrings$1)return bundledStrings$1[0].slice(bundledStrings$1.position0,bundledStrings$1.position0+=e);return new Tag(e,14)};currentExtensions[15]=e=>{if(bundledStrings$1)return bundledStrings$1[1].slice(bundledStrings$1.position1,bundledStrings$1.position1+=e);return new Tag(e,15)};let glbl={Error:Error,RegExp:RegExp};currentExtensions[27]=e=>{return(glbl[e[0]]||Error)(e[1],e[2])};const packedTable=e=>{if(src[position$1++]!=132){let e=new Error("Packed values structure must be followed by a 4 element array");if(src.length{if(!packedValues){if(currentDecoder.getShared)loadShared();else return new Tag(e,PACKED_REFERENCE_TAG_ID)}if(typeof e=="number")return packedValues[16+(e>=0?2*e:-2*e-1)];let t=new Error("No support for non-integer packed references yet");if(e===undefined)t.incomplete=true;throw t};currentExtensions[28]=e=>{if(!referenceMap){referenceMap=new Map;referenceMap.id=0}let t=referenceMap.id++;let r=src[position$1];let n;if(r>>5==4)n=[];else n={};let i={target:n};referenceMap.set(t,i);let a=e();if(i.used)return Object.assign(n,a);i.target=a;return a};currentExtensions[28].handlesRead=true;currentExtensions[29]=e=>{let t=referenceMap.get(e);t.used=true;return t.target};currentExtensions[258]=e=>new Set(e);(currentExtensions[259]=e=>{if(currentDecoder.mapsAsObjects){currentDecoder.mapsAsObjects=false;restoreMapsAsObject=true}return e()}).handlesRead=true;function combine(e,t){if(typeof e==="string")return e+t;if(e instanceof Array)return e.concat(t);return Object.assign({},e,t)}function getPackedValues(){if(!packedValues){if(currentDecoder.getShared)loadShared();else throw new Error("No packed values available")}return packedValues}const SHARED_DATA_TAG_ID=1399353956;currentExtensionRanges.push((e,t)=>{if(e>=225&&e<=255)return combine(getPackedValues().prefixes[e-224],t);if(e>=28704&&e<=32767)return combine(getPackedValues().prefixes[e-28672],t);if(e>=1879052288&&e<=2147483647)return combine(getPackedValues().prefixes[e-1879048192],t);if(e>=216&&e<=223)return combine(t,getPackedValues().suffixes[e-216]);if(e>=27647&&e<=28671)return combine(t,getPackedValues().suffixes[e-27639]);if(e>=1811940352&&e<=1879048191)return combine(t,getPackedValues().suffixes[e-1811939328]);if(e==SHARED_DATA_TAG_ID){return{packedValues:packedValues,structures:currentStructures.slice(0),version:t}}if(e==55799)return t});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 e=0;e{if(!u)throw new Error("Could not find typed array for code "+s);if(!currentDecoder.copyBuffers){if(t===1||t===2&&!(e.byteOffset&1)||t===4&&!(e.byteOffset&3)||t===8&&!(e.byteOffset&7))return new u(e.buffer,e.byteOffset,e.byteLength)}return new u(Uint8Array.prototype.slice.call(e,0).buffer)}:e=>{if(!u)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>>a;let n=new u(r);let i=t[c];for(let e=0;e23){switch(e){case 24:e=src[position$1++];break;case 25:e=dataView.getUint16(position$1);position$1+=2;break;case 26:e=dataView.getUint32(position$1);position$1+=4;break}}return e}function loadShared(){if(currentDecoder.getShared){let e=saveState(()=>{src=null;return currentDecoder.getShared()})||{};let t=e.structures||[];currentDecoder.sharedVersion=e.version;packedValues=currentDecoder.sharedValues=e.packedValues;if(currentStructures===true)currentDecoder.structures=currentStructures=t;else currentStructures.splice.apply(currentStructures,[0,t.length].concat(t))}}function saveState(e){let t=srcEnd;let r=position$1;let n=srcStringStart;let i=srcStringEnd;let a=srcString;let o=referenceMap;let u=bundledStrings$1;let s=new Uint8Array(src.slice(0,srcEnd));let c=currentStructures;let l=currentDecoder;let f=sequentialMode;let _=e();srcEnd=t;position$1=r;srcStringStart=n;srcStringEnd=i;srcString=a;referenceMap=o;bundledStrings$1=u;src=s;sequentialMode=f;currentStructures=c;currentDecoder=l;dataView=new DataView(src.buffer,src.byteOffset,src.byteLength);return _}function clearSource(){src=null;referenceMap=null;currentStructures=null}function addExtension$1(e){currentExtensions[e.tag]=e.decode}const mult10=new Array(147);for(let e=0;e<256;e++){mult10[e]=+("1e"+Math.floor(45.15-e*.30103))}let defaultDecoder=new Decoder({useRecords:false});defaultDecoder.decode;defaultDecoder.decodeMultiple;let textEncoder;try{textEncoder=new TextEncoder}catch(e){}let extensions,extensionClasses;const Buffer$1=typeof globalThis==="object"&&globalThis.Buffer;const hasNodeBuffer=typeof Buffer$1!=="undefined";const ByteArrayAllocate=hasNodeBuffer?Buffer$1.allocUnsafeSlow:Uint8Array;const ByteArray=hasNodeBuffer?Buffer$1:Uint8Array;const MAX_STRUCTURES=256;const MAX_BUFFER_SIZE=hasNodeBuffer?4294967296:2144337920;let throwOnIterable;let target;let targetView;let position=0;let safeEnd;let bundledStrings=null;const MAX_BUNDLE_SIZE=61440;const hasNonLatin=/[\u0080-\uFFFF]/;const RECORD_SYMBOL=Symbol("record-id");class Encoder extends Decoder{constructor(r){super(r);this.offset=0;let s;let o;let l;let f;let n;r=r||{};let c=ByteArray.prototype.utf8Write?function(e,t,r){return target.utf8Write(e,t,r)}:textEncoder&&textEncoder.encodeInto?function(e,t){return textEncoder.encodeInto(e,target.subarray(t)).written}:false;let a=this;let e=r.structures||r.saveStructures;let _=r.maxSharedStructures;if(_==null)_=e?128:0;if(_>8190)throw new Error("Maximum maxSharedStructure is 8190");let i=r.sequential;if(i){_=0}if(!this.structures)this.structures=[];if(this.saveStructures)this.saveShared=this.saveStructures;let p,d,u=r.sharedValues;let h;if(u){h=Object.create(null);for(let e=0,t=u.length;ethis.encodeKeys(e));break}}return this.encode(e,t)};this.encode=function(t,e){if(!target){target=new ByteArrayAllocate(8192);targetView=new DataView(target.buffer,0,8192);position=0}safeEnd=target.length-10;if(safeEnd-position<2048){target=new ByteArrayAllocate(target.length);targetView=new DataView(target.buffer,0,target.length);safeEnd=target.length-10;position=0}else if(e===REUSE_BUFFER_MODE)position=position+7&2147483640;s=position;if(a.useSelfDescribedHeader){targetView.setUint32(position,3654940416);position+=3}n=a.structuredClone?new Map:null;if(a.bundleStrings&&typeof t!=="string"){bundledStrings=[];bundledStrings.size=Infinity}else bundledStrings=null;o=a.structures;if(o){if(o.uninitialized){let e=a.getShared()||{};a.structures=o=e.structures||[];a.sharedVersion=e.version;let r=a.sharedValues=e.packedValues;if(r){h={};for(let e=0,t=r.length;e_&&!i)e=_;if(!o.transitions){o.transitions=Object.create(null);for(let a=0;a0){target[position++]=216;target[position++]=51;writeArrayHeader(4);let r=e.values;b(r);writeArrayHeader(0);writeArrayHeader(0);d=Object.create(h||null);for(let e=0,t=r.length;esafeEnd)w(position);a.offset=position;let e=insertIds(target.subarray(s,position),n.idsToInsert);n=null;return e}if(e&REUSE_BUFFER_MODE){target.start=s;target.end=position;return target}return target.subarray(s,position)}finally{if(o){if(v<10)v++;if(o.length>_)o.length=_;if(y>1e4){o.transitions=null;v=0;y=0;if(m.length>0)m=[]}else if(m.length>0&&!i){for(let e=0,t=m.length;e_){a.structures=a.structures.slice(0,_)}let e=target.subarray(s,position);if(a.updateSharedData()===false)return a.encode(t);return e}if(e&RESET_BUFFER_MODE)position=s}};this.findCommonStringsToPack=()=>{p=new Map;if(!h)h=Object.create(null);return e=>{let r=e&&e.threshold||4;let n=this.pack?e.maxPrivatePackedValues||16:0;if(!u)u=this.sharedValues=[];for(let[e,t]of p){if(t.count>r){h[e]=n++;u.push(e);l=true}}while(this.saveShared&&this.updateSharedData()===false){}p=null}};const b=o=>{if(position>safeEnd)target=w(position);var e=typeof o;var u;if(e==="string"){if(d){let e=d[o];if(e>=0){if(e<16)target[position++]=e+224;else{target[position++]=198;if(e&1)b(15-e>>1);else b(e-16>>1)}return}else if(p&&!r.pack){let e=p.get(o);if(e)e.count++;else p.set(o,{count:1})}}let i=o.length;if(bundledStrings&&i>=4&&i<1024){if((bundledStrings.size+=i)>MAX_BUNDLE_SIZE){let e;let t=(bundledStrings[0]?bundledStrings[0].length*3+bundledStrings[1].length:0)+10;if(position+t>safeEnd)target=w(position+t);target[position++]=217;target[position++]=223;target[position++]=249;target[position++]=bundledStrings.position?132:130;target[position++]=26;e=position-s;position+=4;if(bundledStrings.position){writeBundles(s,b)}bundledStrings=["",""];bundledStrings.size=0;bundledStrings.position=e}let e=hasNonLatin.test(o);bundledStrings[e?0:1]+=o;target[position++]=e?206:207;b(i);return}let a;if(i<32){a=1}else if(i<256){a=2}else if(i<65536){a=3}else{a=5}let e=i*3;if(position+e>safeEnd)target=w(position+e);if(i<64||!c){let e,t,r,n=position+a;for(e=0;e>6|192;target[n++]=t&63|128}else if((t&64512)===55296&&((r=o.charCodeAt(e+1))&64512)===56320){t=65536+((t&1023)<<10)+(r&1023);e++;target[n++]=t>>18|240;target[n++]=t>>12&63|128;target[n++]=t>>6&63|128;target[n++]=t&63|128}else{target[n++]=t>>12|224;target[n++]=t>>6&63|128;target[n++]=t&63|128}}u=n-position-a}else{u=c(o,position+a,e)}if(u<24){target[position++]=96|u}else if(u<256){if(a<2){target.copyWithin(position+2,position+1,position+1+u)}target[position++]=120;target[position++]=u}else if(u<65536){if(a<3){target.copyWithin(position+3,position+2,position+2+u)}target[position++]=121;target[position++]=u>>8;target[position++]=u&255}else{if(a<5){target.copyWithin(position+5,position+3,position+3+u)}target[position++]=122;targetView.setUint32(position,u);position+=4}position+=u}else if(e==="number"){if(!this.alwaysUseFloat&&o>>>0===o){if(o<24){target[position++]=o}else if(o<256){target[position++]=24;target[position++]=o}else if(o<65536){target[position++]=25;target[position++]=o>>8;target[position++]=o&255}else{target[position++]=26;targetView.setUint32(position,o);position+=4}}else if(!this.alwaysUseFloat&&o>>0===o){if(o>=-24){target[position++]=31-o}else if(o>=-256){target[position++]=56;target[position++]=~o}else if(o>=-65536){target[position++]=57;targetView.setUint16(position,~o);position+=2}else{target[position++]=58;targetView.setUint32(position,~o);position+=4}}else{let t;if((t=this.useFloat32)>0&&o<4294967296&&o>=-2147483648){target[position++]=250;targetView.setFloat32(position,o);let e;if(t<4||(e=o*mult10[(target[position]&127)<<1|target[position+1]>>7])>>0===e){position+=4;return}else position--}target[position++]=251;targetView.setFloat64(position,o);position+=8}}else if(e==="object"){if(!o)target[position++]=246;else{if(n){let t=n.get(o);if(t){target[position++]=216;target[position++]=29;target[position++]=25;if(!t.references){let e=n.idsToInsert||(n.idsToInsert=[]);t.references=[];e.push(t)}t.references.push(position-s);position+=2;return}else n.set(o,{offset:position-s})}let e=o.constructor;if(e===Object){g(o,true)}else if(e===Array){u=o.length;if(u<24){target[position++]=128|u}else{writeArrayHeader(u)}for(let e=0;e>8;target[position++]=u&255}else{target[position++]=186;targetView.setUint32(position,u);position+=4}if(a.keyMap){for(let[e,t]of o){b(a.encodeKey(e));b(t)}}else{for(let[e,t]of o){b(e);b(t)}}}else{for(let r=0,e=extensions.length;r>8;target[position++]=t&255}else if(t>-1){target[position++]=218;targetView.setUint32(position,t);position+=4}e.encode.call(this,o,b,w);return}}if(o[Symbol.iterator]){if(throwOnIterable){let e=new Error("Iterable should be serialized as iterator");e.iteratorNotHandled=true;throw e}target[position++]=159;for(let e of o){b(e)}target[position++]=255;return}if(o[Symbol.asyncIterator]||isBlob(o)){let e=new Error("Iterable/blob should be serialized as iterator");e.iteratorNotHandled=true;throw e}if(this.useToJSON&&o.toJSON){const t=o.toJSON();if(t!==o)return b(t)}g(o,!o.hasOwnProperty)}}}else if(e==="boolean"){target[position++]=o?245:244}else if(e==="bigint"){if(o=0){target[position++]=27;targetView.setBigUint64(position,o)}else if(o>-(BigInt(1)<{let t=Object.keys(e);let r=Object.values(e);let n=t.length;if(n<24){target[position++]=160|n}else if(n<256){target[position++]=184;target[position++]=n}else if(n<65536){target[position++]=185;target[position++]=n>>8;target[position++]=n&255}else{target[position++]=186;targetView.setUint32(position,n);position+=4}if(a.keyMap){for(let e=0;e{target[position++]=185;let e=position-s;position+=2;let n=0;if(a.keyMap){for(let e in t)if(r||t.hasOwnProperty(e)){b(a.encodeKey(e));b(t[e]);n++}}else{for(let e in t)if(r||t.hasOwnProperty(e)){b(e);b(t[e]);n++}}target[e+++s]=n>>8;target[e+s]=n&255}:(t,r)=>{let n,i=f.transitions||(f.transitions=Object.create(null));let a=0;let o=0;let u;let s;if(this.keyMap){s=Object.keys(t).map(e=>this.encodeKey(e));o=s.length;for(let t=0;t>8|224;target[position++]=c&255}else{if(!s)s=i.__keys__||(i.__keys__=Object.keys(t));if(u===undefined){c=f.nextId++;if(!c){c=0;f.nextId=1}if(c>=MAX_STRUCTURES){f.nextId=(c=_)+1}}else{c=u}f[c]=s;if(c<_){target[position++]=217;target[position++]=c>>8|224;target[position++]=c&255;i=f.transitions;for(let e=0;e=MAX_STRUCTURES-_)m.shift()[RECORD_SYMBOL]=undefined;m.push(i);writeArrayHeader(o+2);b(57344+c);b(s);if(r===null)return;for(let e in t)if(r||t.hasOwnProperty(e))b(t[e]);return}}if(o<24){target[position++]=128|o}else{writeArrayHeader(o)}if(r===null)return;for(let e in t)if(r||t.hasOwnProperty(e))b(t[e])};const w=e=>{let t;if(e>16777216){if(e-s>MAX_BUFFER_SIZE)throw new Error("Encoded buffer would be larger than maximum buffer size");t=Math.min(MAX_BUFFER_SIZE,Math.round(Math.max((e-s)*(e>67108864?1.25:2),4194304)/4096)*4096)}else t=(Math.max(e-s<<2,target.length-1)>>12)+1<<12;let r=new ByteArrayAllocate(t);targetView=new DataView(r.buffer,0,t);if(target.copy)target.copy(r,0,s,e);else r.set(target.slice(s,e));position-=s;s=0;safeEnd=r.length-10;return target=r};let D=100;let x=1e3;this.encodeAsIterable=function(e,t){return A(e,t,L)};this.encodeAsAsyncIterable=function(e,t){return A(e,t,F)};function*L(n,i,e){let t=n.constructor;if(t===Object){let r=a.useRecords!==false;if(r)g(n,null);else writeEntityLength(Object.keys(n).length,160);for(let t in n){let e=n[t];if(!r)b(t);if(e&&typeof e==="object"){if(i[t])yield*L(e,i[t]);else yield*E(e,i,t)}else b(e)}}else if(t===Array){let e=n.length;writeArrayHeader(e);for(let t=0;tD)){if(i.element)yield*L(e,i.element);else yield*E(e,i,"element")}else b(e)}}else if(n[Symbol.iterator]){target[position++]=159;for(let e of n){if(e&&(typeof e==="object"||position-s>D)){if(i.element)yield*L(e,i.element);else yield*E(e,i,"element")}else b(e)}target[position++]=255}else if(isBlob(n)){writeEntityLength(n.size,64);yield target.subarray(s,position);yield n;S()}else if(n[Symbol.asyncIterator]){target[position++]=159;yield target.subarray(s,position);yield n;S();target[position++]=255}else{b(n)}if(e&&position>s)yield target.subarray(s,position);else if(position-s>D){yield target.subarray(s,position);S()}}function*E(t,r,n){let i=position-s;try{b(t);if(position-s>D){yield target.subarray(s,position);S()}}catch(e){if(e.iteratorNotHandled){r[n]={};position=s+i;yield*L.call(this,t,r[n])}else throw e}}function S(){D=x;a.encode(null,THROW_ON_ITERABLE)}function A(e,t,r){if(t&&t.chunkThreshold)D=x=t.chunkThreshold;else D=100;if(e&&typeof e==="object"){a.encode(null,THROW_ON_ITERABLE);return r(e,a.iterateProperties||(a.iterateProperties={}),true)}return[a.encode(e)]}async function*F(e,t){for(let r of L(e,t,true)){let e=r.constructor;if(e===ByteArray||e===Uint8Array)yield r;else if(isBlob(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){S();if(e)yield*F(e,t.async||(t.async={}));else yield a.encode(e)}}else{yield r}}}}useBuffer(e){target=e;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 t=this.sharedVersion||0;this.sharedVersion=t+1;let e=this.structures.slice(0);let r=new SharedData(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 writeEntityLength(e,t){if(e<24)target[position++]=t|e;else if(e<256){target[position++]=t|24;target[position++]=e}else if(e<65536){target[position++]=t|25;target[position++]=e>>8;target[position++]=e&255}else{target[position++]=t|26;targetView.setUint32(position,e);position+=4}}class SharedData{constructor(e,t,r){this.structures=e;this.packedValues=t;this.version=r}}function writeArrayHeader(e){if(e<24)target[position++]=128|e;else if(e<256){target[position++]=152;target[position++]=e}else if(e<65536){target[position++]=153;target[position++]=e>>8;target[position++]=e&255}else{target[position++]=154;targetView.setUint32(position,e);position+=4}}const BlobConstructor=typeof Blob==="undefined"?function(){}:Blob;function isBlob(e){if(e instanceof BlobConstructor)return true;let t=e[Symbol.toStringTag];return t==="Blob"||t==="File"}function findRepetitiveStrings(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){target[position++]=26;targetView.setUint32(position,r);position+=4}else{target[position++]=251;targetView.setFloat64(position,r);position+=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){writeBuffer(e,r)}},{getTag(e){if(e.constructor===Uint8Array){if(this.tagUint8Array||hasNodeBuffer&&this.tagUint8Array!==false)return 64}},encode(e,t,r){writeBuffer(e,r)}},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(t,n){let e=t.packedValues||[];let r=t.structures||[];if(e.values.length>0){target[position++]=216;target[position++]=51;writeArrayHeader(4);let r=e.values;n(r);writeArrayHeader(0);writeArrayHeader(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 a=t.buffer||t;r(hasNodeBuffer?Buffer$1.from(a,i,n):new Uint8Array(a,i,n))}}}function writeBuffer(e,t){let r=e.byteLength;if(r<24){target[position++]=64+r}else if(r<256){target[position++]=88;target[position++]=r}else if(r<65536){target[position++]=89;target[position++]=r>>8;target[position++]=r&255}else{target[position++]=90;targetView.setUint32(position,r);position+=4}if(position+r>=target.length){t(position+r)}target.set(e.buffer?e:new Uint8Array(e),position);position+=r}function insertIds(n,e){let r;let i=e.length*2;let a=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,a);i-=2;let t=e+i;n[t++]=216;n[t++]=28;a=e}return n}function writeBundles(e,t){targetView.setUint32(bundledStrings.position+e,position-bundledStrings.position-e+1);let r=bundledStrings;bundledStrings=null;t(r[0]);t(r[1])}function addExtension(e){if(e.Class){if(!e.encode)throw new Error("Extension has no encode function");extensionClasses.unshift(e.Class);extensions.unshift(e)}addExtension$1(e)}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={};
+function _classApplyDescriptorGet(e,t){if(t.get){return t.get.call(e)}return t.value}function _classExtractFieldDescriptor(e,t,r){if(!t.has(e)){throw new TypeError("attempted to "+r+" private field on non-instance")}return t.get(e)}function _classPrivateFieldGet(e,t){var r=_classExtractFieldDescriptor(e,t,"get");return _classApplyDescriptorGet(e,r)}function _classApplyDescriptorSet(e,t,r){if(t.set){t.set.call(e,r)}else{if(!t.writable){throw new TypeError("attempted to set read only private field")}t.value=r}}function _classPrivateFieldSet(e,t,r){var n=_classExtractFieldDescriptor(e,t,"set");_classApplyDescriptorSet(e,n,r);return r}function _assertThisInitialized(e){if(e===void 0){throw new ReferenceError("this hasn't been initialised - super() hasn't been called")}return e}function _setPrototypeOf(e,t){_setPrototypeOf=Object.setPrototypeOf?Object.setPrototypeOf.bind():function e(t,r){t.__proto__=r;return t};return _setPrototypeOf(e,t)}function _isNativeReflectConstruct$1(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct$1=function e(){return!!t})()}function _construct(e,t,r){if(_isNativeReflectConstruct$1())return Reflect.construct.apply(null,arguments);var n=[null];n.push.apply(n,t);var i=new(e.bind.apply(e,n));return r&&_setPrototypeOf(i,r.prototype),i}function _readOnlyError(e){throw new TypeError('"'+e+'" is read-only')}function _arrayWithHoles(e){if(Array.isArray(e))return e}function _iterableToArray(e){if(typeof Symbol!=="undefined"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function _arrayLikeToArray$1(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 _objectWithoutProperties(e,t){if(e==null)return{};var r=_objectWithoutPropertiesLoose(e,t);var n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i=0)continue;if(!Object.prototype.propertyIsEnumerable.call(e,n))continue;r[n]=e[n]}}return r}function _iterableToArrayLimit(e,t){var r=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=r){var n,i,a,o,u=[],s=!0,c=!1;try{if(a=(r=r.call(e)).next,0===t){if(Object(r)!==r)return;s=!1}else for(;!(s=(n=a.call(r)).done)&&(u.push(n.value),u.length!==t);s=!0);}catch(e){c=!0,i=e}finally{try{if(!s&&null!=r["return"]&&(o=r["return"](),Object(o)!==o))return}finally{if(c)throw i}}return u}}function _slicedToArray(e,t){return _arrayWithHoles(e)||_iterableToArrayLimit(e,t)||_unsupportedIterableToArray$1(e,t)||_nonIterableRest()}function _arrayWithoutHoles(e){if(Array.isArray(e))return _arrayLikeToArray$1(e)}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_unsupportedIterableToArray$1(e)||_nonIterableSpread()}function _OverloadYield(e,t){this.v=e,this.k=t}function _awaitAsyncGenerator(e){return new _OverloadYield(e,0)}function AsyncGenerator(o){var a,u;function s(r,e){try{var n=o[r](e),i=n.value,a=i instanceof _OverloadYield;Promise.resolve(a?i.v:i).then(function(e){if(a){var t="return"===r?"return":"next";if(!i.k||e.done)return s(t,e);e=o[t](e).value}c(n.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:!0});break;case"throw":a.reject(t);break;default:a.resolve({value:t,done:!1})}(a=a.next)?s(a.key,a.arg):u=null}this._invoke=function(n,i){return new Promise(function(e,t){var r={key:n,arg:i,resolve:e,reject:t,next:null};u?u=u.next=r:(a=u=r,s(n,i))})},"function"!=typeof o["return"]&&(this["return"]=void 0)}AsyncGenerator.prototype["function"==typeof Symbol&&Symbol.asyncIterator||"@@asyncIterator"]=function(){return this},AsyncGenerator.prototype.next=function(e){return this._invoke("next",e)},AsyncGenerator.prototype["throw"]=function(e){return this._invoke("throw",e)},AsyncGenerator.prototype["return"]=function(e){return this._invoke("return",e)};function _wrapAsyncGenerator(e){return function(){return new AsyncGenerator(e.apply(this,arguments))}}function getDefaultExportFromCjs(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e["default"]:e}var regeneratorRuntime$1={exports:{}};var _typeof={exports:{}};(function(t){function r(e){"@babel/helpers - typeof";return t.exports=r="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},t.exports.__esModule=true,t.exports["default"]=t.exports,r(e)}t.exports=r,t.exports.__esModule=true,t.exports["default"]=t.exports})(_typeof);var _typeofExports=_typeof.exports;(function(P){var N=_typeofExports["default"];function B(){P.exports=B=function e(){return o},P.exports.__esModule=true,P.exports["default"]=P.exports;var c,o={},e=Object.prototype,l=e.hasOwnProperty,f=Object.defineProperty||function(e,t,r){e[t]=r.value},t="function"==typeof Symbol?Symbol:{},i=t.iterator||"@@iterator",r=t.asyncIterator||"@@asyncIterator",n=t.toStringTag||"@@toStringTag";function a(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}),e[t]}try{a({},"")}catch(c){a=function e(t,r,n){return t[r]=n}}function u(e,t,r,n){var i=t&&t.prototype instanceof s?t:s,a=Object.create(i.prototype),o=new C(n||[]);return f(a,"_invoke",{value:S(e,r,o)}),a}function _(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}o.wrap=u;var p="suspendedStart",d="suspendedYield",h="executing",m="completed",y={};function s(){}function v(){}function b(){}var g={};a(g,i,function(){return this});var w=Object.getPrototypeOf,D=w&&w(w(O([])));D&&D!==e&&l.call(D,i)&&(g=D);var x=b.prototype=s.prototype=Object.create(g);function L(e){["next","throw","return"].forEach(function(t){a(e,t,function(e){return this._invoke(t,e)})})}function E(u,s){function c(e,t,r,n){var i=_(u[e],u,t);if("throw"!==i.type){var a=i.arg,o=a.value;return o&&"object"==N(o)&&l.call(o,"__await")?s.resolve(o.__await).then(function(e){c("next",e,r,n)},function(e){c("throw",e,r,n)}):s.resolve(o).then(function(e){a.value=e,r(a)},function(e){return c("throw",e,r,n)})}n(i.arg)}var i;f(this,"_invoke",{value:function e(r,n){function t(){return new s(function(e,t){c(r,n,e,t)})}return i=i?i.then(t,t):t()}})}function S(a,o,u){var s=p;return function(e,t){if(s===h)throw new Error("Generator is already running");if(s===m){if("throw"===e)throw t;return{value:c,done:!0}}for(u.method=e,u.arg=t;;){var r=u.delegate;if(r){var n=A(r,u);if(n){if(n===y)continue;return n}}if("next"===u.method)u.sent=u._sent=u.arg;else if("throw"===u.method){if(s===p)throw s=m,u.arg;u.dispatchException(u.arg)}else"return"===u.method&&u.abrupt("return",u.arg);s=h;var i=_(a,o,u);if("normal"===i.type){if(s=u.done?m:d,i.arg===y)continue;return{value:i.arg,done:u.done}}"throw"===i.type&&(s=m,u.method="throw",u.arg=i.arg)}}}function A(e,t){var r=t.method,n=e.iterator[r];if(n===c)return t.delegate=null,"throw"===r&&e.iterator["return"]&&(t.method="return",t.arg=c,A(e,t),"throw"===t.method)||"return"!==r&&(t.method="throw",t.arg=new TypeError("The iterator does not provide a '"+r+"' method")),y;var i=_(n,e.iterator,t.arg);if("throw"===i.type)return t.method="throw",t.arg=i.arg,t.delegate=null,y;var a=i.arg;return a?a.done?(t[e.resultName]=a.value,t.next=e.nextLoc,"return"!==t.method&&(t.method="next",t.arg=c),t.delegate=null,y):a:(t.method="throw",t.arg=new TypeError("iterator result is not an object"),t.delegate=null,y)}function F(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),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 C(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(F,this),this.reset(!0)}function O(t){if(t||""===t){var e=t[i];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,n=function e(){for(;++r=0;--i){var a=this.tryEntries[i],o=a.completion;if("root"===a.tryLoc)return t("end");if(a.tryLoc<=this.prev){var u=l.call(a,"catchLoc"),s=l.call(a,"finallyLoc");if(u&&s){if(this.prev=0;--n){var i=this.tryEntries[n];if(i.tryLoc<=this.prev&&l.call(i,"finallyLoc")&&this.prev=0;--r){var n=this.tryEntries[r];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),k(n),y}},catch:function e(t){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc===t){var i=n.completion;if("throw"===i.type){var a=i.arg;k(n)}return a}}throw new Error("illegal catch attempt")},delegateYield:function e(t,r,n){return this.delegate={iterator:O(t),resultName:r,nextLoc:n},"next"===this.method&&(this.arg=c),y}},o}P.exports=B,P.exports.__esModule=true,P.exports["default"]=P.exports})(regeneratorRuntime$1);var regeneratorRuntimeExports=regeneratorRuntime$1.exports;var runtime=regeneratorRuntimeExports();var regenerator=runtime;try{regeneratorRuntime=runtime}catch(e){if(typeof globalThis==="object"){globalThis.regeneratorRuntime=runtime}else{Function("r","regeneratorRuntime = r")(runtime)}}var _regeneratorRuntime=getDefaultExportFromCjs(regenerator);let decoder;try{decoder=new TextDecoder}catch(e){}let src;let srcEnd;let position$1=0;const LEGACY_RECORD_INLINE_ID=105;const RECORD_DEFINITIONS_ID=57342;const RECORD_INLINE_ID=57343;const BUNDLED_STRINGS_ID=57337;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;try{new Function("")}catch(e){inlineObjectReadThreshold=Infinity}class Decoder{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[safeKey(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(src){return saveState(()=>{clearSource();return this?this.decode(t,e):Decoder.prototype.decode.call(defaultOptions,t,e)})}srcEnd=e>-1?e:t.length;position$1=0;srcStringEnd=0;srcString=null;bundledStrings$1=null;src=t;try{dataView=t.dataView||(t.dataView=new DataView(t.buffer,t.byteOffset,t.byteLength))}catch(e){src=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 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(r,n){let i,a=0;try{let e=r.length;sequentialMode=true;let t=this?this.decode(r,e):defaultDecoder.decode(r,e);if(n){if(n(t)===false){return}while(position$1=bundledStrings$1.postBundlePosition){let e=new Error("Unexpected bundle position");e.incomplete=true;throw e}position$1=bundledStrings$1.postBundlePosition;bundledStrings$1=null}if(position$1==srcEnd){currentStructures=null;src=null;if(referenceMap)referenceMap=null}else if(position$1>srcEnd){let e=new Error("Unexpected end of CBOR data");e.incomplete=true;throw e}else if(!sequentialMode){throw new Error("Data read, but end of buffer not reached")}return e}catch(e){clearSource();if(e instanceof RangeError||e.message.startsWith("Unexpected end of buffer")){e.incomplete=true}throw e}}function read(){let n=src[position$1++];let i=n>>5;n=n&31;if(n>23){switch(n){case 24:n=src[position$1++];break;case 25:if(i==7){return getFloat16()}n=dataView.getUint16(position$1);position$1+=2;break;case 26:if(i==7){let t=dataView.getFloat32(position$1);if(currentDecoder.useFloat32>2){let e=mult10[(src[position$1]&127)<<1|src[position$1+1]>>7];position$1+=4;return(e*t+(t>0?.5:-.5)>>0)/e}position$1+=4;return t}n=dataView.getUint32(position$1);position$1+=4;break;case 27:if(i==7){let e=dataView.getFloat64(position$1);position$1+=8;return e}if(i>1){if(dataView.getUint32(position$1)>0)throw new Error("JavaScript does not support arrays, maps, or strings with length over 4294967295");n=dataView.getUint32(position$1+4)}else if(currentDecoder.int64AsNumber){n=dataView.getUint32(position$1)*4294967296;n+=dataView.getUint32(position$1+4)}else n=dataView.getBigUint64(position$1);position$1+=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=read())!=STOP_CODE){e[r++]=t}return i==4?e:i==3?e.join(""):Buffer.concat(e);case 5:let n;if(currentDecoder.mapsAsObjects){let e={};if(currentDecoder.keyMap)while((n=read())!=STOP_CODE)e[safeKey(currentDecoder.decodeKey(n))]=read();else while((n=read())!=STOP_CODE)e[safeKey(n)]=read();return e}else{if(restoreMapsAsObject){currentDecoder.mapsAsObjects=true;restoreMapsAsObject=false}let e=new Map;if(currentDecoder.keyMap)while((n=read())!=STOP_CODE)e.set(currentDecoder.decodeKey(n),read());else while((n=read())!=STOP_CODE)e.set(n,read());return e}case 7:return STOP_CODE;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 readBin(n);case 3:if(srcStringEnd>=position$1){return srcString.slice(position$1-srcStringStart,(position$1+=n)-srcStringStart)}if(srcStringEnd==0&&srcEnd<140&&n<32){let e=n<16?shortStringInJS(n):longStringInJS(n);if(e!=null)return e}return readFixedString(n);case 4:let t=new Array(n);for(let e=0;e=BUNDLED_STRINGS_ID){let e=currentStructures[n&8191];if(e){if(!e.read)e.read=createStructureReader(e);return e.read()}if(n<65536){if(n==RECORD_INLINE_ID){let e=readJustLength();let t=read();let r=read();recordDefinition(t,r);let n={};if(currentDecoder.keyMap)for(let t=2;t23){switch(t){case 24:t=src[position$1++];break;case 25:t=dataView.getUint16(position$1);position$1+=2;break;case 26:t=dataView.getUint32(position$1);position$1+=4;break;default:throw new Error("Expected array header, but got "+src[position$1-1])}}let r=this.compiledReader;while(r){if(r.propertyCount===t)return r(read);r=r.next}if(this.slowReads++>=inlineObjectReadThreshold){let e=this.length==t?this:this.slice(0,t);r=currentDecoder.keyMap?new Function("r","return {"+e.map(e=>currentDecoder.decodeKey(e)).map(e=>validName.test(e)?safeKey(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}"):new Function("r","return {"+e.map(e=>validName.test(e)?safeKey(e)+":r()":"["+JSON.stringify(e)+"]:r()").join(",")+"}");if(this.compiledReader)r.next=this.compiledReader;r.propertyCount=t;this.compiledReader=r;return r(read)}let n={};if(currentDecoder.keyMap)for(let e=0;e64&&decoder)return decoder.decode(src.subarray(position$1,position$1+=e));const r=position$1+e;const n=[];t="";while(position$165535){e-=65536;n.push(e>>>10&1023|55296);e=56320|e&1023}n.push(e)}else{n.push(i)}if(n.length>=4096){t+=fromCharCode.apply(String,n);n.length=0}}if(n.length>0){t+=fromCharCode.apply(String,n)}return t}let fromCharCode=String.fromCharCode;function longStringInJS(t){let r=position$1;let n=new Array(t);for(let e=0;e0){position$1=r;return}n[e]=i}return fromCharCode.apply(String,n)}function shortStringInJS(h){if(h<4){if(h<2){if(h===0)return"";else{let e=src[position$1++];if((e&128)>1){position$1-=1;return}return fromCharCode(e)}}else{let e=src[position$1++];let t=src[position$1++];if((e&128)>0||(t&128)>0){position$1-=2;return}if(h<3)return fromCharCode(e,t);let r=src[position$1++];if((r&128)>0){position$1-=3;return}return fromCharCode(e,t,r)}}else{let f=src[position$1++];let _=src[position$1++];let p=src[position$1++];let d=src[position$1++];if((f&128)>0||(_&128)>0||(p&128)>0||(d&128)>0){position$1-=4;return}if(h<6){if(h===4)return fromCharCode(f,_,p,d);else{let e=src[position$1++];if((e&128)>0){position$1-=5;return}return fromCharCode(f,_,p,d,e)}}else if(h<8){let e=src[position$1++];let t=src[position$1++];if((e&128)>0||(t&128)>0){position$1-=6;return}if(h<7)return fromCharCode(f,_,p,d,e,t);let r=src[position$1++];if((r&128)>0){position$1-=7;return}return fromCharCode(f,_,p,d,e,t,r)}else{let u=src[position$1++];let s=src[position$1++];let c=src[position$1++];let l=src[position$1++];if((u&128)>0||(s&128)>0||(c&128)>0||(l&128)>0){position$1-=8;return}if(h<10){if(h===8)return fromCharCode(f,_,p,d,u,s,c,l);else{let e=src[position$1++];if((e&128)>0){position$1-=9;return}return fromCharCode(f,_,p,d,u,s,c,l,e)}}else if(h<12){let e=src[position$1++];let t=src[position$1++];if((e&128)>0||(t&128)>0){position$1-=10;return}if(h<11)return fromCharCode(f,_,p,d,u,s,c,l,e,t);let r=src[position$1++];if((r&128)>0){position$1-=11;return}return fromCharCode(f,_,p,d,u,s,c,l,e,t,r)}else{let n=src[position$1++];let i=src[position$1++];let a=src[position$1++];let o=src[position$1++];if((n&128)>0||(i&128)>0||(a&128)>0||(o&128)>0){position$1-=12;return}if(h<14){if(h===12)return fromCharCode(f,_,p,d,u,s,c,l,n,i,a,o);else{let e=src[position$1++];if((e&128)>0){position$1-=13;return}return fromCharCode(f,_,p,d,u,s,c,l,n,i,a,o,e)}}else{let e=src[position$1++];let t=src[position$1++];if((e&128)>0||(t&128)>0){position$1-=14;return}if(h<15)return fromCharCode(f,_,p,d,u,s,c,l,n,i,a,o,e,t);let r=src[position$1++];if((r&128)>0){position$1-=15;return}return fromCharCode(f,_,p,d,u,s,c,l,n,i,a,o,e,t,r)}}}}}function readBin(e){return currentDecoder.copyBuffers?Uint8Array.prototype.slice.call(src,position$1,position$1+=e):src.subarray(position$1,position$1+=e)}let f32Array=new Float32Array(1);let u8Array=new Uint8Array(f32Array.buffer,0,4);function getFloat16(){let t=src[position$1++];let r=src[position$1++];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}u8Array[3]=t&128|(e>>1)+56;u8Array[2]=(t&7)<<5|r>>3;u8Array[1]=r<<5;u8Array[0]=0;return f32Array[0]}new Array(4096);class Tag{constructor(e,t){this.value=e;this.tag=t}}currentExtensions[0]=e=>{return new Date(e)};currentExtensions[1]=e=>{return new Date(Math.round(e*1e3))};currentExtensions[2]=r=>{let n=BigInt(0);for(let e=0,t=r.byteLength;e{return BigInt(-1)-currentExtensions[2](e)};currentExtensions[4]=e=>{return+(e[1]+"e"+e[0])};currentExtensions[5]=e=>{return e[1]*Math.exp(e[0]*Math.log(2))};const recordDefinition=(e,t)=>{e=e-57344;let r=currentStructures[e];if(r&&r.isShared){(currentStructures.restoreStructures||(currentStructures.restoreStructures=[]))[e]=r}currentStructures[e]=t;t.read=createStructureReader(t)};currentExtensions[LEGACY_RECORD_INLINE_ID]=r=>{let e=r.length;let n=r[1];recordDefinition(r[0],n);let i={};for(let t=2;t{if(bundledStrings$1)return bundledStrings$1[0].slice(bundledStrings$1.position0,bundledStrings$1.position0+=e);return new Tag(e,14)};currentExtensions[15]=e=>{if(bundledStrings$1)return bundledStrings$1[1].slice(bundledStrings$1.position1,bundledStrings$1.position1+=e);return new Tag(e,15)};let glbl={Error:Error,RegExp:RegExp};currentExtensions[27]=e=>{return(glbl[e[0]]||Error)(e[1],e[2])};const packedTable=e=>{if(src[position$1++]!=132){let e=new Error("Packed values structure must be followed by a 4 element array");if(src.length{if(!packedValues){if(currentDecoder.getShared)loadShared();else return new Tag(e,PACKED_REFERENCE_TAG_ID)}if(typeof e=="number")return packedValues[16+(e>=0?2*e:-2*e-1)];let t=new Error("No support for non-integer packed references yet");if(e===undefined)t.incomplete=true;throw t};currentExtensions[28]=e=>{if(!referenceMap){referenceMap=new Map;referenceMap.id=0}let t=referenceMap.id++;let r=src[position$1];let n;if(r>>5==4)n=[];else n={};let i={target:n};referenceMap.set(t,i);let a=e();if(i.used)return Object.assign(n,a);i.target=a;return a};currentExtensions[28].handlesRead=true;currentExtensions[29]=e=>{let t=referenceMap.get(e);t.used=true;return t.target};currentExtensions[258]=e=>new Set(e);(currentExtensions[259]=e=>{if(currentDecoder.mapsAsObjects){currentDecoder.mapsAsObjects=false;restoreMapsAsObject=true}return e()}).handlesRead=true;function combine(e,t){if(typeof e==="string")return e+t;if(e instanceof Array)return e.concat(t);return Object.assign({},e,t)}function getPackedValues(){if(!packedValues){if(currentDecoder.getShared)loadShared();else throw new Error("No packed values available")}return packedValues}const SHARED_DATA_TAG_ID=1399353956;currentExtensionRanges.push((e,t)=>{if(e>=225&&e<=255)return combine(getPackedValues().prefixes[e-224],t);if(e>=28704&&e<=32767)return combine(getPackedValues().prefixes[e-28672],t);if(e>=1879052288&&e<=2147483647)return combine(getPackedValues().prefixes[e-1879048192],t);if(e>=216&&e<=223)return combine(t,getPackedValues().suffixes[e-216]);if(e>=27647&&e<=28671)return combine(t,getPackedValues().suffixes[e-27639]);if(e>=1811940352&&e<=1879048191)return combine(t,getPackedValues().suffixes[e-1811939328]);if(e==SHARED_DATA_TAG_ID){return{packedValues:packedValues,structures:currentStructures.slice(0),version:t}}if(e==55799)return t});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 e=0;e{if(!u)throw new Error("Could not find typed array for code "+s);if(!currentDecoder.copyBuffers){if(t===1||t===2&&!(e.byteOffset&1)||t===4&&!(e.byteOffset&3)||t===8&&!(e.byteOffset&7))return new u(e.buffer,e.byteOffset,e.byteLength)}return new u(Uint8Array.prototype.slice.call(e,0).buffer)}:e=>{if(!u)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>>a;let n=new u(r);let i=t[c];for(let e=0;e23){switch(e){case 24:e=src[position$1++];break;case 25:e=dataView.getUint16(position$1);position$1+=2;break;case 26:e=dataView.getUint32(position$1);position$1+=4;break}}return e}function loadShared(){if(currentDecoder.getShared){let e=saveState(()=>{src=null;return currentDecoder.getShared()})||{};let t=e.structures||[];currentDecoder.sharedVersion=e.version;packedValues=currentDecoder.sharedValues=e.packedValues;if(currentStructures===true)currentDecoder.structures=currentStructures=t;else currentStructures.splice.apply(currentStructures,[0,t.length].concat(t))}}function saveState(e){let t=srcEnd;let r=position$1;let n=srcStringStart;let i=srcStringEnd;let a=srcString;let o=referenceMap;let u=bundledStrings$1;let s=new Uint8Array(src.slice(0,srcEnd));let c=currentStructures;let l=currentDecoder;let f=sequentialMode;let _=e();srcEnd=t;position$1=r;srcStringStart=n;srcStringEnd=i;srcString=a;referenceMap=o;bundledStrings$1=u;src=s;sequentialMode=f;currentStructures=c;currentDecoder=l;dataView=new DataView(src.buffer,src.byteOffset,src.byteLength);return _}function clearSource(){src=null;referenceMap=null;currentStructures=null}function addExtension$1(e){currentExtensions[e.tag]=e.decode}const mult10=new Array(147);for(let e=0;e<256;e++){mult10[e]=+("1e"+Math.floor(45.15-e*.30103))}let defaultDecoder=new Decoder({useRecords:false});defaultDecoder.decode;defaultDecoder.decodeMultiple;let textEncoder;try{textEncoder=new TextEncoder}catch(e){}let extensions,extensionClasses;const Buffer$1=typeof globalThis==="object"&&globalThis.Buffer;const hasNodeBuffer=typeof Buffer$1!=="undefined";const ByteArrayAllocate=hasNodeBuffer?Buffer$1.allocUnsafeSlow:Uint8Array;const ByteArray=hasNodeBuffer?Buffer$1:Uint8Array;const MAX_STRUCTURES=256;const MAX_BUFFER_SIZE=hasNodeBuffer?4294967296:2144337920;let throwOnIterable;let target;let targetView;let position=0;let safeEnd;let bundledStrings=null;const MAX_BUNDLE_SIZE=61440;const hasNonLatin=/[\u0080-\uFFFF]/;const RECORD_SYMBOL=Symbol("record-id");class Encoder extends Decoder{constructor(r){super(r);this.offset=0;let s;let o;let l;let f;let n;r=r||{};let c=ByteArray.prototype.utf8Write?function(e,t,r){return target.utf8Write(e,t,r)}:textEncoder&&textEncoder.encodeInto?function(e,t){return textEncoder.encodeInto(e,target.subarray(t)).written}:false;let a=this;let e=r.structures||r.saveStructures;let _=r.maxSharedStructures;if(_==null)_=e?128:0;if(_>8190)throw new Error("Maximum maxSharedStructure is 8190");let i=r.sequential;if(i){_=0}if(!this.structures)this.structures=[];if(this.saveStructures)this.saveShared=this.saveStructures;let p,d,u=r.sharedValues;let h;if(u){h=Object.create(null);for(let e=0,t=u.length;ethis.encodeKeys(e));break}}return this.encode(e,t)};this.encode=function(t,e){if(!target){target=new ByteArrayAllocate(8192);targetView=new DataView(target.buffer,0,8192);position=0}safeEnd=target.length-10;if(safeEnd-position<2048){target=new ByteArrayAllocate(target.length);targetView=new DataView(target.buffer,0,target.length);safeEnd=target.length-10;position=0}else if(e===REUSE_BUFFER_MODE)position=position+7&2147483640;s=position;if(a.useSelfDescribedHeader){targetView.setUint32(position,3654940416);position+=3}n=a.structuredClone?new Map:null;if(a.bundleStrings&&typeof t!=="string"){bundledStrings=[];bundledStrings.size=Infinity}else bundledStrings=null;o=a.structures;if(o){if(o.uninitialized){let e=a.getShared()||{};a.structures=o=e.structures||[];a.sharedVersion=e.version;let r=a.sharedValues=e.packedValues;if(r){h={};for(let e=0,t=r.length;e_&&!i)e=_;if(!o.transitions){o.transitions=Object.create(null);for(let a=0;a0){target[position++]=216;target[position++]=51;writeArrayHeader(4);let r=e.values;b(r);writeArrayHeader(0);writeArrayHeader(0);d=Object.create(h||null);for(let e=0,t=r.length;esafeEnd)w(position);a.offset=position;let e=insertIds(target.subarray(s,position),n.idsToInsert);n=null;return e}if(e&REUSE_BUFFER_MODE){target.start=s;target.end=position;return target}return target.subarray(s,position)}finally{if(o){if(v<10)v++;if(o.length>_)o.length=_;if(y>1e4){o.transitions=null;v=0;y=0;if(m.length>0)m=[]}else if(m.length>0&&!i){for(let e=0,t=m.length;e_){a.structures=a.structures.slice(0,_)}let e=target.subarray(s,position);if(a.updateSharedData()===false)return a.encode(t);return e}if(e&RESET_BUFFER_MODE)position=s}};this.findCommonStringsToPack=()=>{p=new Map;if(!h)h=Object.create(null);return e=>{let r=e&&e.threshold||4;let n=this.pack?e.maxPrivatePackedValues||16:0;if(!u)u=this.sharedValues=[];for(let[e,t]of p){if(t.count>r){h[e]=n++;u.push(e);l=true}}while(this.saveShared&&this.updateSharedData()===false){}p=null}};const b=o=>{if(position>safeEnd)target=w(position);var e=typeof o;var u;if(e==="string"){if(d){let e=d[o];if(e>=0){if(e<16)target[position++]=e+224;else{target[position++]=198;if(e&1)b(15-e>>1);else b(e-16>>1)}return}else if(p&&!r.pack){let e=p.get(o);if(e)e.count++;else p.set(o,{count:1})}}let i=o.length;if(bundledStrings&&i>=4&&i<1024){if((bundledStrings.size+=i)>MAX_BUNDLE_SIZE){let e;let t=(bundledStrings[0]?bundledStrings[0].length*3+bundledStrings[1].length:0)+10;if(position+t>safeEnd)target=w(position+t);target[position++]=217;target[position++]=223;target[position++]=249;target[position++]=bundledStrings.position?132:130;target[position++]=26;e=position-s;position+=4;if(bundledStrings.position){writeBundles(s,b)}bundledStrings=["",""];bundledStrings.size=0;bundledStrings.position=e}let e=hasNonLatin.test(o);bundledStrings[e?0:1]+=o;target[position++]=e?206:207;b(i);return}let a;if(i<32){a=1}else if(i<256){a=2}else if(i<65536){a=3}else{a=5}let e=i*3;if(position+e>safeEnd)target=w(position+e);if(i<64||!c){let e,t,r,n=position+a;for(e=0;e>6|192;target[n++]=t&63|128}else if((t&64512)===55296&&((r=o.charCodeAt(e+1))&64512)===56320){t=65536+((t&1023)<<10)+(r&1023);e++;target[n++]=t>>18|240;target[n++]=t>>12&63|128;target[n++]=t>>6&63|128;target[n++]=t&63|128}else{target[n++]=t>>12|224;target[n++]=t>>6&63|128;target[n++]=t&63|128}}u=n-position-a}else{u=c(o,position+a,e)}if(u<24){target[position++]=96|u}else if(u<256){if(a<2){target.copyWithin(position+2,position+1,position+1+u)}target[position++]=120;target[position++]=u}else if(u<65536){if(a<3){target.copyWithin(position+3,position+2,position+2+u)}target[position++]=121;target[position++]=u>>8;target[position++]=u&255}else{if(a<5){target.copyWithin(position+5,position+3,position+3+u)}target[position++]=122;targetView.setUint32(position,u);position+=4}position+=u}else if(e==="number"){if(!this.alwaysUseFloat&&o>>>0===o){if(o<24){target[position++]=o}else if(o<256){target[position++]=24;target[position++]=o}else if(o<65536){target[position++]=25;target[position++]=o>>8;target[position++]=o&255}else{target[position++]=26;targetView.setUint32(position,o);position+=4}}else if(!this.alwaysUseFloat&&o>>0===o){if(o>=-24){target[position++]=31-o}else if(o>=-256){target[position++]=56;target[position++]=~o}else if(o>=-65536){target[position++]=57;targetView.setUint16(position,~o);position+=2}else{target[position++]=58;targetView.setUint32(position,~o);position+=4}}else{let t;if((t=this.useFloat32)>0&&o<4294967296&&o>=-2147483648){target[position++]=250;targetView.setFloat32(position,o);let e;if(t<4||(e=o*mult10[(target[position]&127)<<1|target[position+1]>>7])>>0===e){position+=4;return}else position--}target[position++]=251;targetView.setFloat64(position,o);position+=8}}else if(e==="object"){if(!o)target[position++]=246;else{if(n){let t=n.get(o);if(t){target[position++]=216;target[position++]=29;target[position++]=25;if(!t.references){let e=n.idsToInsert||(n.idsToInsert=[]);t.references=[];e.push(t)}t.references.push(position-s);position+=2;return}else n.set(o,{offset:position-s})}let e=o.constructor;if(e===Object){g(o,true)}else if(e===Array){u=o.length;if(u<24){target[position++]=128|u}else{writeArrayHeader(u)}for(let e=0;e>8;target[position++]=u&255}else{target[position++]=186;targetView.setUint32(position,u);position+=4}if(a.keyMap){for(let[e,t]of o){b(a.encodeKey(e));b(t)}}else{for(let[e,t]of o){b(e);b(t)}}}else{for(let r=0,e=extensions.length;r>8;target[position++]=t&255}else if(t>-1){target[position++]=218;targetView.setUint32(position,t);position+=4}e.encode.call(this,o,b,w);return}}if(o[Symbol.iterator]){if(throwOnIterable){let e=new Error("Iterable should be serialized as iterator");e.iteratorNotHandled=true;throw e}target[position++]=159;for(let e of o){b(e)}target[position++]=255;return}if(o[Symbol.asyncIterator]||isBlob(o)){let e=new Error("Iterable/blob should be serialized as iterator");e.iteratorNotHandled=true;throw e}if(this.useToJSON&&o.toJSON){const t=o.toJSON();if(t!==o)return b(t)}g(o,!o.hasOwnProperty)}}}else if(e==="boolean"){target[position++]=o?245:244}else if(e==="bigint"){if(o=0){target[position++]=27;targetView.setBigUint64(position,o)}else if(o>-(BigInt(1)<{let t=Object.keys(e);let r=Object.values(e);let n=t.length;if(n<24){target[position++]=160|n}else if(n<256){target[position++]=184;target[position++]=n}else if(n<65536){target[position++]=185;target[position++]=n>>8;target[position++]=n&255}else{target[position++]=186;targetView.setUint32(position,n);position+=4}if(a.keyMap){for(let e=0;e{target[position++]=185;let e=position-s;position+=2;let n=0;if(a.keyMap){for(let e in t)if(r||t.hasOwnProperty(e)){b(a.encodeKey(e));b(t[e]);n++}}else{for(let e in t)if(r||t.hasOwnProperty(e)){b(e);b(t[e]);n++}}target[e+++s]=n>>8;target[e+s]=n&255}:(t,r)=>{let n,i=f.transitions||(f.transitions=Object.create(null));let a=0;let o=0;let u;let s;if(this.keyMap){s=Object.keys(t).map(e=>this.encodeKey(e));o=s.length;for(let t=0;t>8|224;target[position++]=c&255}else{if(!s)s=i.__keys__||(i.__keys__=Object.keys(t));if(u===undefined){c=f.nextId++;if(!c){c=0;f.nextId=1}if(c>=MAX_STRUCTURES){f.nextId=(c=_)+1}}else{c=u}f[c]=s;if(c<_){target[position++]=217;target[position++]=c>>8|224;target[position++]=c&255;i=f.transitions;for(let e=0;e=MAX_STRUCTURES-_)m.shift()[RECORD_SYMBOL]=undefined;m.push(i);writeArrayHeader(o+2);b(57344+c);b(s);if(r===null)return;for(let e in t)if(r||t.hasOwnProperty(e))b(t[e]);return}}if(o<24){target[position++]=128|o}else{writeArrayHeader(o)}if(r===null)return;for(let e in t)if(r||t.hasOwnProperty(e))b(t[e])};const w=e=>{let t;if(e>16777216){if(e-s>MAX_BUFFER_SIZE)throw new Error("Encoded buffer would be larger than maximum buffer size");t=Math.min(MAX_BUFFER_SIZE,Math.round(Math.max((e-s)*(e>67108864?1.25:2),4194304)/4096)*4096)}else t=(Math.max(e-s<<2,target.length-1)>>12)+1<<12;let r=new ByteArrayAllocate(t);targetView=new DataView(r.buffer,0,t);if(target.copy)target.copy(r,0,s,e);else r.set(target.slice(s,e));position-=s;s=0;safeEnd=r.length-10;return target=r};let D=100;let x=1e3;this.encodeAsIterable=function(e,t){return A(e,t,L)};this.encodeAsAsyncIterable=function(e,t){return A(e,t,F)};function*L(n,i,e){let t=n.constructor;if(t===Object){let r=a.useRecords!==false;if(r)g(n,null);else writeEntityLength(Object.keys(n).length,160);for(let t in n){let e=n[t];if(!r)b(t);if(e&&typeof e==="object"){if(i[t])yield*L(e,i[t]);else yield*E(e,i,t)}else b(e)}}else if(t===Array){let e=n.length;writeArrayHeader(e);for(let t=0;tD)){if(i.element)yield*L(e,i.element);else yield*E(e,i,"element")}else b(e)}}else if(n[Symbol.iterator]){target[position++]=159;for(let e of n){if(e&&(typeof e==="object"||position-s>D)){if(i.element)yield*L(e,i.element);else yield*E(e,i,"element")}else b(e)}target[position++]=255}else if(isBlob(n)){writeEntityLength(n.size,64);yield target.subarray(s,position);yield n;S()}else if(n[Symbol.asyncIterator]){target[position++]=159;yield target.subarray(s,position);yield n;S();target[position++]=255}else{b(n)}if(e&&position>s)yield target.subarray(s,position);else if(position-s>D){yield target.subarray(s,position);S()}}function*E(t,r,n){let i=position-s;try{b(t);if(position-s>D){yield target.subarray(s,position);S()}}catch(e){if(e.iteratorNotHandled){r[n]={};position=s+i;yield*L.call(this,t,r[n])}else throw e}}function S(){D=x;a.encode(null,THROW_ON_ITERABLE)}function A(e,t,r){if(t&&t.chunkThreshold)D=x=t.chunkThreshold;else D=100;if(e&&typeof e==="object"){a.encode(null,THROW_ON_ITERABLE);return r(e,a.iterateProperties||(a.iterateProperties={}),true)}return[a.encode(e)]}async function*F(e,t){for(let r of L(e,t,true)){let e=r.constructor;if(e===ByteArray||e===Uint8Array)yield r;else if(isBlob(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){S();if(e)yield*F(e,t.async||(t.async={}));else yield a.encode(e)}}else{yield r}}}}useBuffer(e){target=e;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 t=this.sharedVersion||0;this.sharedVersion=t+1;let e=this.structures.slice(0);let r=new SharedData(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 writeEntityLength(e,t){if(e<24)target[position++]=t|e;else if(e<256){target[position++]=t|24;target[position++]=e}else if(e<65536){target[position++]=t|25;target[position++]=e>>8;target[position++]=e&255}else{target[position++]=t|26;targetView.setUint32(position,e);position+=4}}class SharedData{constructor(e,t,r){this.structures=e;this.packedValues=t;this.version=r}}function writeArrayHeader(e){if(e<24)target[position++]=128|e;else if(e<256){target[position++]=152;target[position++]=e}else if(e<65536){target[position++]=153;target[position++]=e>>8;target[position++]=e&255}else{target[position++]=154;targetView.setUint32(position,e);position+=4}}const BlobConstructor=typeof Blob==="undefined"?function(){}:Blob;function isBlob(e){if(e instanceof BlobConstructor)return true;let t=e[Symbol.toStringTag];return t==="Blob"||t==="File"}function findRepetitiveStrings(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){target[position++]=26;targetView.setUint32(position,r);position+=4}else{target[position++]=251;targetView.setFloat64(position,r);position+=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){writeBuffer(e,r)}},{getTag(e){if(e.constructor===Uint8Array){if(this.tagUint8Array||hasNodeBuffer&&this.tagUint8Array!==false)return 64}},encode(e,t,r){writeBuffer(e,r)}},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(t,n){let e=t.packedValues||[];let r=t.structures||[];if(e.values.length>0){target[position++]=216;target[position++]=51;writeArrayHeader(4);let r=e.values;n(r);writeArrayHeader(0);writeArrayHeader(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 a=t.buffer||t;r(hasNodeBuffer?Buffer$1.from(a,i,n):new Uint8Array(a,i,n))}}}function writeBuffer(e,t){let r=e.byteLength;if(r<24){target[position++]=64+r}else if(r<256){target[position++]=88;target[position++]=r}else if(r<65536){target[position++]=89;target[position++]=r>>8;target[position++]=r&255}else{target[position++]=90;targetView.setUint32(position,r);position+=4}if(position+r>=target.length){t(position+r)}target.set(e.buffer?e:new Uint8Array(e),position);position+=r}function insertIds(n,e){let r;let i=e.length*2;let a=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,a);i-=2;let t=e+i;n[t++]=216;n[t++]=28;a=e}return n}function writeBundles(e,t){targetView.setUint32(bundledStrings.position+e,position-bundledStrings.position-e+1);let r=bundledStrings;bundledStrings=null;t(r[0]);t(r[1])}function addExtension(e){if(e.Class){if(!e.encode)throw new Error("Extension has no encode function");extensionClasses.unshift(e.Class);extensions.unshift(e)}addExtension$1(e)}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={};
/**@license
*
* No Dependency fast and small LZJB Compression for Browser and Node
@@ -42,4 +42,4 @@ function _classApplyDescriptorGet(e,t){if(t.get){return t.get.call(e)}return t.v
* Released under BSD-3-Clause License
*
* build: Wed, 27 Oct 2021 10:43:10 GMT
- */Object.defineProperty(lzjbPack,"__esModule",{value:true});const NBBY=8,MATCH_BITS=6,MATCH_MIN=3,MATCH_MAX=(1<r-MATCH_MAX){t[i++]=e[n++];continue}l=(e[n]+13^e[n+1]-13^e[n+2])&LEMPEL_SIZE-1;c=n-f[l]&OFFSET_MASK;f[l]=n;a=n-c;if(a>=0&&a!=n&&e[n]==e[a]&&e[n+1]==e[a+1]&&e[n+2]==e[a+2]){t[o]|=u;for(s=MATCH_MIN;s>NBBY;t[i++]=c;n+=s}else{t[i++]=e[n++]}}console.assert(e.length>=n);return i}function decompress(e,t,r){t=t|0;var n=0,i=0,a=0,o=0,u=1<<(NBBY-1|0),s=0,c=0;while(n>(NBBY-MATCH_BITS|0))+MATCH_MIN|0;c=(e[n]<4){r[i]=r[a];i=i+1|0;a=a+1|0;r[i]=r[a];i=i+1|0;a=a+1|0;r[i]=r[a];i=i+1|0;a=a+1|0;r[i]=r[a];i=i+1|0;a=a+1|0;s=s-4|0}while(s>0){r[i]=r[a];i=i+1|0;a=a+1|0;s=s-1|0}}}else{r[i]=e[n];i=i+1|0;n=n+1|0}}return i}function encode_magic$1(){const e=new TextEncoder("utf-8");return e.encode(MAGIC_STRING)}const MAGIC_STRING="@lzjb";const MAGIC=encode_magic$1();function merge_uint8_array$1(...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 number_to_bytes(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 pack(e,{magic:t=true}={}){const r=new Uint8Array(Math.max(e.length*1.5|0,16*1024));const n=compress(e,r);const i=number_to_bytes(e.length);const a=[Uint8Array.of(i.length),i,r.slice(0,n)];if(t){a.unshift(MAGIC)}return merge_uint8_array$1(...a)}function unpack(t,{magic:e=true}={}){if(e){const e=new TextDecoder("utf-8");const s=e.decode(t.slice(0,MAGIC.length));if(s!==MAGIC_STRING){throw new Error("Invalid magic value")}}const r=e?MAGIC.length:0;const n=t[r];const i=r+1;const a=r+n+1;const o=bytes_to_number(t.slice(i,a));t=t.slice(a);const u=new Uint8Array(o);decompress(t,t.length,u);return u}var pack_1=lzjbPack.pack=pack;var unpack_1=lzjbPack.unpack=unpack;function unfetch(s,c){return c=c||{},new Promise(function(e,t){var r=new XMLHttpRequest,n=[],i=[],a={},o=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:o,headers:{keys:function(){return n},entries:function(){return i},get:function(e){return a[e.toLowerCase()]},has:function(e){return e.toLowerCase()in a}}}};for(var u 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]),a[t]=a[t]?a[t]+","+r:r}),e(o())},r.onerror=t,r.withCredentials="include"==c.credentials,c.headers)r.setRequestHeader(u,c.headers[u]);r.send(c.body||null)})}var _excluded=["token"],_excluded2=["env"],_excluded3=["stderr","stdin","stdout","command_line"],_excluded4=["use_dynamic"],_excluded5=["use_dynamic"],_excluded6=["env","dynamic_env","use_dynamic","error"];function _classPrivateFieldInitSpec(e,t,r){_checkPrivateRedeclaration(e,t);t.set(e,r)}function _checkPrivateRedeclaration(e,t){if(t.has(e)){throw new TypeError("Cannot initialize the same private elements twice on an object")}}function _callSuper(e,t,r){return t=_getPrototypeOf(t),_possibleConstructorReturn(e,_isNativeReflectConstruct()?Reflect.construct(t,r||[],_getPrototypeOf(e).constructor):t.apply(e,r))}function _isNativeReflectConstruct(){try{var t=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(t){}return(_isNativeReflectConstruct=function e(){return!!t})()}function _createForOfIteratorHelper(t,e){var r=typeof Symbol!=="undefined"&&t[Symbol.iterator]||t["@@iterator"];if(!r){if(Array.isArray(t)||(r=_unsupportedIterableToArray(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 a=true,o=false,u;return{s:function e(){r=r.call(t)},n:function e(){var t=r.next();a=t.done;return t},e:function e(t){o=true;u=t},f:function e(){try{if(!a&&r["return"]!=null)r["return"]()}finally{if(o)throw u}}}}function _unsupportedIterableToArray(e,t){if(!e)return;if(typeof e==="string")return _arrayLikeToArray(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 _arrayLikeToArray(e,t)}function _arrayLikeToArray(e,t){if(t==null||t>e.length)t=e.length;for(var r=0,n=new Array(t);r1?r-1:0),i=1;i0&&arguments[0]!==undefined?arguments[0]:null;var t=user_env&&user_env.get("DEBUG",{throwError:false});if(e===null){return t===true}return(t===null||t===void 0?void 0:t.valueOf())===e.valueOf()}function num_mnemicic_re(e){return e?"(?:#".concat(e,"(?:#[ie])?|#[ie]#").concat(e,")"):"(?:#[ie])?"}function gen_rational_re(e,t){return"".concat(num_mnemicic_re(e),"[+-]?").concat(t,"+/").concat(t,"+")}function gen_complex_re(e,t){return"".concat(num_mnemicic_re(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 gen_integer_re(e,t){return"".concat(num_mnemicic_re(e),"[+-]?").concat(t,"+")}var re_re=/^#\/((?:\\\/|[^/]|\[[^\]]*\/[^\]]*\])+)\/([gimyus]*)$/;var float_stre="(?:[-+]?(?:[0-9]+(?:[eE][-+]?[0-9]+)|(?:\\.[0-9]+|[0-9]+\\.[0-9]+)(?:[eE][-+]?[0-9]+)?)|[0-9]+\\.)";var complex_float_stre="(?:#[ie])?(?:[+-]?(?:[0-9][0-9_]*/[0-9][0-9_]*|nan.0|inf.0|".concat(float_stre,"|[+-]?[0-9]+))?(?:").concat(float_stre,"|[+-](?:[0-9]+/[0-9]+|[0-9]+|nan.0|inf.0))i");var float_re=new RegExp("^(#[ie])?".concat(float_stre,"$"),"i");function make_complex_match_re(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 complex_list_re=function(){var a={};[[10,"","[0-9]"],[16,"x","[0-9a-fA-F]"],[8,"o","[0-7]"],[2,"b","[01]"]].forEach(function(e){var t=_slicedToArray(e,3),r=t[0],n=t[1],i=t[2];a[r]=make_complex_match_re(n,i)});return a}();var characters={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 ucs2decode(e){var t=[];var r=0;var n=e.length;while(r=55296&&i<=56319&&r1&&arguments[1]!==undefined?arguments[1]:10;var r=num_pre_parse(e);var n=r.number.split("/");var i=LRational({num:LNumber([n[0],r.radix||t]),denom:LNumber([n[1],r.radix||t])});if(r.inexact){return i.valueOf()}else{return i}}function parse_integer(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;var r=num_pre_parse(e);if(r.inexact){return LFloat(parseInt(r.number,r.radix||t))}return LNumber([r.number,r.radix||t])}function parse_character(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(/#\\([\s\S]+)$/);if(t){r=t[1]}}if(r){return LCharacter(r)}throw new Error("Parse: invalid character")}function parse_complex(e){var i=arguments.length>1&&arguments[1]!==undefined?arguments[1]:10;function t(e){var t;if(e==="+"){t=LNumber(1)}else if(e==="-"){t=LNumber(-1)}else if(e.match(int_bare_re)){t=LNumber([e,i])}else if(e.match(rational_bare_re)){var r=e.split("/");t=LRational({num:LNumber([r[0],i]),denom:LNumber([r[1],i])})}else if(e.match(float_re)){var n=parse_float(e);if(a.exact){return n.toRational()}return n}else if(e.match(/nan.0$/)){return LNumber(NaN)}else if(e.match(/inf.0$/)){if(e[0]==="-"){return LNumber(Number.NEGATIVE_INFINITY)}return LNumber(Number.POSITIVE_INFINITY)}else{throw new Error("Internal Parser Error")}if(a.inexact){return LFloat(t.valueOf())}return t}var a=num_pre_parse(e);i=a.radix||i;var r;var n=a.number.match(complex_bare_match_re);if(i!==10&&n){r=n}else{r=a.number.match(complex_list_re[i])}var o,u;u=t(r[2]);if(r[1]){o=t(r[1])}else if(u instanceof LFloat){o=LFloat(0)}else{o=LNumber(0)}if(u.cmp(0)===0&&u.__type__==="bigint"){return o}return LComplex({im:u,re:o})}function is_int(e){return parseInt(e.toString(),10)===e}function parse_big_int(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 a=t[3]&&t[3].length;if(i0&&(t.exact||!t.number.match(/\./))){return LNumber(a).mul(u)}}}r=LFloat(r);if(t.exact){return r.toRational()}return r}function parse_string(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{var r=LString(JSON.parse(e));r.freeze();return r}catch(e){var n=e.message.replace(/in JSON /,"").replace(/.*Error: /,"");throw new Error("Invalid string literal: ".concat(n))}}function parse_symbol(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 LSymbol(e)}function parse_argument(e){if(constants.hasOwnProperty(e)){return constants[e]}if(e.match(/^"[\s\S]*"$/)){return parse_string(e)}else if(e[0]==="#"){var t=e.match(re_re);if(t){return new RegExp(t[1],t[2])}else if(e.match(char_re)){return parse_character(e)}var r=e.match(/#\\(.+)/);if(r&&ucs2decode(r[1]).length===1){return parse_character(e)}}if(e.match(/[0-9a-f]|[+-]i/i)){if(e.match(int_re)){return parse_integer(e)}else if(e.match(float_re)){return parse_float(e)}else if(e.match(rational_re)){return parse_rational(e)}else if(e.match(complex_re)){return parse_complex(e)}}if(e.match(/^#[iexobd]/)){throw new Error("Invalid numeric constant: "+e)}return parse_symbol(e)}function is_atom_string(e){return!(["(",")","[","]"].includes(e)||specials.names().includes(e))}function is_symbol_string(e){return is_atom_string(e)&&!(e.match(re_re)||e.match(/^"[\s\S]*"$/)||e.match(int_re)||e.match(float_re)||e.match(complex_re)||e.match(rational_re)||e.match(char_re)||["#t","#f","nil"].includes(e))}var string_re=/"(?:\\[\S\s]|[^"])*"?/g;function escape_regex(e){if(typeof e==="string"){var t=/([-\\^$[\]()+{}?*.|])/g;return e.replace(t,"\\$1")}return e}function Stack(){this.data=[]}Stack.prototype.push=function(e){this.data.push(e)};Stack.prototype.top=function(){return this.data[this.data.length-1]};Stack.prototype.pop=function(){return this.data.pop()};Stack.prototype.is_empty=function(){return!this.data.length};function tokens(e){if(e instanceof LString){e=e.valueOf()}var t=new Lexer(e,{whitespace:true});var r=[];while(true){var n=t.peek(true);if(n===eof){break}r.push(n);t.skip()}return r}function multiline_formatter(e){var t=e.token,r=_objectWithoutProperties(e,_excluded);if(t.match(/^"[\s\S]*"$/)&&t.match(/\n/)){var n=new RegExp("^ {1,"+(e.col+1)+"}","mg");t=t.replace(n,"")}return _objectSpread({token:t},r)}function Thunk(e){var t=arguments.length>1&&arguments[1]!==undefined?arguments[1]:function(){};this.fn=e;this.cont=t}Thunk.prototype.toString=function(){return"#"};function trampoline(n){return function(){for(var e=arguments.length,t=new Array(e),r=0;r1&&arguments[1]!==undefined?arguments[1]:false;if(e instanceof LString){e=e.toString()}if(t){return tokens(e)}else{var r=tokens(e).map(function(e){if(e.token==="#\\ "||e.token=="#\\\n"){return e.token}return e.token.trim()}).filter(function(e){return e&&!e.match(/^;/)&&!e.match(/^#\|[\s\S]*\|#$/)});return strip_s_comments(r)}}function strip_s_comments(e){var t=0;var r=null;var n=[];for(var i=0;i0&&arguments[0]!==undefined?arguments[0]:null;if(e instanceof LSymbol){if(e.is_gensym()){return e}e=e.valueOf()}if(is_gensym(e)){return LSymbol(e)}if(e!==null){return r(e,Symbol("#:".concat(e)))}t++;return r(t,Symbol("#:g".concat(t)))}}();function QuotedPromise(e){var r=this;var n={pending:true,rejected:false,fulfilled:false,reason:undefined,type:undefined};e=e.then(function(e){n.type=type(e);n.fulfilled=true;n.pending=false;return e});read_only(this,"_promise",e,{hidden:true});if(is_function(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]}})});read_only(this,"__promise__",e);this.then=false}QuotedPromise.prototype.then=function(e){return new QuotedPromise(this.valueOf().then(e))};QuotedPromise.prototype["catch"]=function(e){return new QuotedPromise(this.valueOf()["catch"](e))};QuotedPromise.prototype.valueOf=function(){if(!this._promise){throw new Error("QuotedPromise: invalid promise created")}return this._promise};QuotedPromise.prototype.toString=function(){if(this.__pending__){return QuotedPromise.pending_str}if(this.__rejected__){return QuotedPromise.rejected_str}return"#")};QuotedPromise.pending_str="#";QuotedPromise.rejected_str="#";function promise_all(e){if(Array.isArray(e)){return Promise.all(escape_quoted_promises(e)).then(unescape_quoted_promises)}return e}function escape_quoted_promises(e){var t=new Array(e.length),r=e.length;while(r--){var n=e[r];if(n instanceof QuotedPromise){t[r]=new Value(n)}else{t[r]=n}}return t}function unescape_quoted_promises(e){var t=new Array(e.length),r=e.length;while(r--){var n=e[r];if(n instanceof Value){t[r]=n.valueOf()}else{t[r]=n}}return t}var specials={LITERAL:Symbol["for"]("literal"),SPLICE:Symbol["for"]("splice"),SYMBOL:Symbol["for"]("symbol"),names:function e(){return Object.keys(this.__list__)},type:function e(t){try{return this.get(t).type}catch(e){console.log({name:t});console.log(e);return null}},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 LSymbol("quote-promise"),specials.LITERAL]];var builtins=defined_specials.map(function(e){return e[0]});Object.freeze(builtins);Object.defineProperty(specials,"__builtins__",{writable:false,value:builtins});defined_specials.forEach(function(e){var t=_slicedToArray(e,3),r=t[0],n=t[1],i=t[2];specials.append(r,n,i)});var Lexer=function(){function v(e){var t=this;var r=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{},n=r.whitespace,i=n===void 0?false:n;_classCallCheck(this,v);read_only(this,"__input__",e.replace(/\r/g,""));var a={};["_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 a[r]},set:function e(t){a[r]=t}})});this._whitespace=i;this._i=this._line=this._col=this._newline=0;this._state=this._next=this._token=null;this._prev_char=""}_createClass(v,[{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 eof}if(this._token){read_only(this,"__token__",this.token(true));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 eof}},{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 eof}for(var r=this._i;r=r){return eof}if(t+this._i>=r){return this.read_rest()}var n=this._i+t;var i=this.__input__.substring(this._i,n);var a=i.match(/\n/g);if(a){this._line+=a.length}this._i=n;return i}},{key:"peek_char",value:function e(){if(this._i>=this.__input__.length){return eof}return LCharacter(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]:{},n=r.prev_char,i=r["char"],a=r.next_char;var o=_slicedToArray(t,4),u=o[0],s=o[1],c=o[2],l=o[3];if(t.length!==5){throw new Error("Lexer: Invalid rule of length ".concat(t.length))}if(is_string(u)){if(u!==i){return false}}else if(!i.match(u)){return false}if(!match_or_null(s,n)){return false}if(!match_or_null(c,a)){return false}if(l!==this._state){return false}return true}},{key:"next_token",value:function e(){if(this._i>=this.__input__.length){return false}var t=true;e:for(var r=this._i,n=this.__input__.length;r2&&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 a=[];for(var o=0,u=t.length;o0&&arguments[0]!==undefined?arguments[0]:{},t=e.env,r=e.meta,n=r===void 0?false:r,i=e.formatter,a=i===void 0?multiline_formatter:i;_classCallCheck(this,o);read_only(this,"_formatter",a,{hidden:true});read_only(this,"__env__",t);read_only(this,"_meta",n,{hidden:true});read_only(this,"_refs",[],{hidden:true});read_only(this,"_state",{parentheses:0,fold_case:false},{hidden:true})}_createClass(o,[{key:"_with_syntax_scope",value:function e(t){var r=this;var n=get_internal(this.__env__);var i=n.get("stdin");this.__env__.set("lips",_objectSpread(_objectSpread({},lips),{},{__parser__:this}));n.set("stdin",new ParserInputPort(this,this.__env__));var a=function e(){r.__env__.set("lips",lips);n.set("stdin",i)};return unpromise(t(),function(e){a();return e},a)}},{key:"parse",value:function e(t){if(t instanceof LString){t=t.toString()}read_only(this,"__lexer__",new Lexer(t))}},{key:"resolve",value:function e(t){return this.__env__&&this.__env__.get(t,{throwError:false})}},{key:"peek",value:function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=this.__lexer__.peek(true);if(!(r===eof)){t.next=4;break}return t.abrupt("return",eof);case 4:if(!this.is_comment(r.token)){t.next=7;break}this.skip();return t.abrupt("continue",0);case 7:if(!is_directive(r.token)){t.next=11;break}this.skip();if(r.token==="#!fold-case"){this._state.fold_case=true}else if(r.token==="#!no-fold-case"){this._state.fold_case=false}return t.abrupt("continue",0);case 11:if(!(r.token==="#;")){t.next=18;break}this.skip();if(!(this.__lexer__.peek()===eof)){t.next=15;break}throw new Error("Lexer: syntax error eof found after comment");case 15:t.next=17;return this._read_object();case 17:return t.abrupt("continue",0);case 18:return t.abrupt("break",21);case 21:r=this._formatter(r);if(this._state.fold_case){r.token=foldcase_string(r.token)}if(!this._meta){t.next=25;break}return t.abrupt("return",r);case 25:return t.abrupt("return",r.token);case 26: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=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r;return _regeneratorRuntime.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){return["(","["].includes(t)}},{key:"is_close",value:function e(t){return[")","]"].includes(t)}},{key:"read_list",value:function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r,n,i,a,o,u;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:r=_nil,n=r;case 1:t.next=4;return this.peek();case 4:a=t.sent;if(!(a===eof)){t.next=7;break}return t.abrupt("break",31);case 7:if(!this.is_close(a)){t.next=11;break}--this._state.parentheses;this.skip();return t.abrupt("break",31);case 11:if(!(a==="."&&!is_nil(r))){t.next=19;break}this.skip();t.next=15;return this._read_object();case 15:n.cdr=t.sent;i=true;t.next=29;break;case 19:if(!i){t.next=23;break}throw new Error("Parser: syntax error more than one element after dot");case 23:t.next=25;return this._read_object();case 25:o=t.sent;u=new Pair(o,_nil);if(is_nil(r)){r=u}else{n.cdr=u}n=u;case 29:t.next=1;break;case 31:return t.abrupt("return",r);case 32:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()},{key:"read_value",value:function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r;return _regeneratorRuntime.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===eof)){t.next=5;break}throw new Error("Parser: Expected token eof found");case 5:return t.abrupt("return",parse_argument(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 _evaluate(t,{env:this.__env__,error:function e(t){throw t}})}},{key:"read_object",value:function(){var e=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r;return _regeneratorRuntime.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 DatumReference){r=r.valueOf()}if(!this._refs.length){t.next=7;break}return t.abrupt("return",unpromise(this._resolve_object(r),function(e){if(is_pair(e)){e.mark_cycles()}return e}));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:"balanced",value:function e(){return this._state.parentheses===0}},{key:"ballancing_error",value:function e(t,r){var n=this._state.parentheses;var i;if(n<0){i=new Error("Parser: unexpected parenthesis");i.__code__=[r.toString()+")"]}else{i=new Error("Parser: expected parenthesis but eof found");var a=new RegExp("\\){".concat(n,"}$"));i.__code__=[t.toString().replace(a,"")]}throw i}},{key:"_resolve_object",value:function(){var t=_asyncToGenerator(_regeneratorRuntime.mark(function e(r){var n=this;var i;return _regeneratorRuntime.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(!is_plain_object(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(!is_pair(r)){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=_asyncToGenerator(_regeneratorRuntime.mark(function e(r){return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!is_pair(r)){t.next=15;break}if(!(r.car instanceof DatumReference)){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 DatumReference)){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=_asyncToGenerator(_regeneratorRuntime.mark(function e(){var r=this;var n,i,a,o,u,s,c,l,f,_,p,d;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:t.next=2;return this.peek();case 2:n=t.sent;if(!(n===eof)){t.next=5;break}return t.abrupt("return",n);case 5:if(!is_special(n)){t.next=51;break}i=specials.get(n);a=is_builtin(n);this.skip();s=is_symbol_extension(n);t.t0=this;t.next=13;return this.peek();case 13:t.t1=t.sent;c=t.t0.is_close.call(t.t0,t.t1);if(!s){t.next=19;break}t.t2=undefined;t.next=22;break;case 19:t.next=21;return this._read_object();case 21:t.t2=t.sent;case 22:l=t.t2;if(!(l===eof)){t.next=25;break}throw new Unterminated("Expecting expression eof found");case 25:if(a){t.next=32;break}u=this.__env__.get(i.symbol);if(!(typeof u==="function")){t.next=32;break}if(is_literal(n)){f=[l]}else if(is_nil(l)){f=[]}else if(is_pair(l)){f=l.to_array(false)}if(!(f||s)){t.next=31;break}return t.abrupt("return",this._with_syntax_scope(function(){return call_function(u,s?[]:f,{env:r.__env__,dynamic_env:r.__env__,use_dynamic:false})}));case 31:throw new Error("Parse Error: Invalid parser extension "+"invocation ".concat(i.symbol));case 32:if(!is_literal(n)){t.next=38;break}if(!c){t.next=35;break}throw new Error("Parse Error: expecting datum");case 35:o=new Pair(i.symbol,new Pair(l,_nil));t.next=39;break;case 38:o=new Pair(i.symbol,l);case 39:if(!a){t.next=41;break}return t.abrupt("return",o);case 41:if(!(u instanceof Macro)){t.next=50;break}t.next=44;return this._with_syntax_scope(function(){return r.evaluate(o)});case 44:_=t.sent;if(!(is_pair(_)||_ instanceof LSymbol)){t.next=47;break}return t.abrupt("return",Pair.fromArray([LSymbol("quote"),_]));case 47:return t.abrupt("return",_);case 50:throw new Error("Parse Error: invalid parser extension: "+i.symbol);case 51:p=this.match_datum_ref(n);if(!(p!==null)){t.next=57;break}this.skip();if(!this._refs[p]){t.next=56;break}return t.abrupt("return",new DatumReference(p,this._refs[p]));case 56:throw new Error("Parse Error: invalid datum label #".concat(p,"#"));case 57:d=this.match_datum_label(n);if(!(d!==null)){t.next=64;break}this.skip();this._refs[d]=this._read_object();return t.abrupt("return",this._refs[d]);case 64:if(!this.is_close(n)){t.next=69;break}--this._state.parentheses;this.skip();t.next=76;break;case 69:if(!this.is_open(n)){t.next=75;break}++this._state.parentheses;this.skip();return t.abrupt("return",this.read_list());case 75:return t.abrupt("return",this.read_value());case 76:case"end":return t.stop()}},e,this)}));function t(){return e.apply(this,arguments)}return t}()}]);return o}();var Unterminated=function(e){_inherits(t,e);function t(){_classCallCheck(this,t);return _callSuper(this,t,arguments)}return _createClass(t)}(_wrapNativeSuper(Error));Parser.Unterminated=Unterminated;var DatumReference=function(){function r(e,t){_classCallCheck(this,r);this.name=e;this.data=t}_createClass(r,[{key:"valueOf",value:function e(){return this.data}}]);return r}();function _parse(e,t){return _parse2.apply(this,arguments)}function _parse2(){_parse2=_wrapAsyncGenerator(_regeneratorRuntime.mark(function e(r,n){var i,a,o;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:if(!n){if(global_env){n=global_env.get("**interaction-environment**",{throwError:false})}else{n=user_env}}if(r instanceof Parser){i=r}else{i=new Parser({env:n});i.parse(r)}case 2:t.next=5;return _awaitAsyncGenerator(i.read_object());case 5:o=t.sent;if(!i.balanced()){i.ballancing_error(o,a)}if(!(o===eof)){t.next=9;break}return t.abrupt("break",14);case 9:a=o;t.next=12;return o;case 12:t.next=2;break;case 14:case"end":return t.stop()}},e)}));return _parse2.apply(this,arguments)}function unpromise(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(is_promise(e)){var n=e.then(t);if(r===null){return n}else{return n["catch"](r)}}if(e instanceof Array){return unpromise_array(e,t,r)}if(is_plain_object(e)){return unpromise_object(e,t,r)}return t(e)}function unpromise_array(t,r,e){if(t.find(is_promise)){return unpromise(promise_all(t),function(e){if(Object.isFrozen(t)){Object.freeze(e)}return r(e)},e)}return r(t)}function unpromise_object(t,e,r){var i=Object.keys(t);var n=[],a=[];var o=i.length;while(o--){var u=i[o];var s=t[u];n[o]=s;if(is_promise(s)){a.push(s)}}if(a.length){return unpromise(promise_all(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 read_only(e,t,r){var n=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{},i=n.hidden,a=i===void 0?false:i;Object.defineProperty(e,t,{value:r,configurable:true,enumerable:!a})}function uniterate_async(e){return _uniterate_async.apply(this,arguments)}function _uniterate_async(){_uniterate_async=_asyncToGenerator(_regeneratorRuntime.mark(function e(r){var n,i,a,o,u,s,c;return _regeneratorRuntime.wrap(function e(t){while(1)switch(t.prev=t.next){case 0:n=[];i=false;a=false;t.prev=3;u=_asyncIterator(r);case 5:t.next=7;return u.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);a=true;o=t.t0;case 19:t.prev=19;t.prev=20;if(!(i&&u["return"]!=null)){t.next=24;break}t.next=24;return u["return"]();case 24:t.prev=24;if(!a){t.next=27;break}throw o;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 _uniterate_async.apply(this,arguments)}function matcher(e,t){if(t instanceof RegExp){return function(e){return String(e).match(t)}}else if(is_function(t)){return t}throw new Error("Invalid matcher")}function doc(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__=trim_lines(r)}}if(e){t.__name__=e}else if(t.name&&!is_lambda(t)){t.__name__=t.name}return t}function trim_lines(e){return e.split("\n").map(function(e){return e.trim()}).join("\n")}function previousSexp(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 lineIndent(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 match(e,t){return l(e,t)===t.length;function l(r,n){function e(e,t){var r=_createForOfIteratorHelper(e),n;try{for(r.s();!(n=r.n()).done;){var i=n.value;var a=l(i,t);if(a!==-1){return a}}}catch(e){r.e(e)}finally{r.f()}return-1}function t(){return r[a]===Symbol["for"]("symbol")&&!is_symbol_string(n[u])}function i(){var e=r[a+1];var t=n[u+1];if(e!==undefined&&t!==undefined){return l([e],[t])}}var a=0;var o={};for(var u=0;u0){continue}}else if(t()){return-1}}else if(r[a]instanceof Array){var c=l(r[a],n.slice(u));if(c===-1||c+u>n.length){return-1}u+=c-1;a++;continue}else{return-1}a++}if(r.length!==a){return-1}return n.length}}function Formatter(e){this.__code__=e.replace(/\r/g,"")}Formatter.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|\*?-values|\*)?)$/],shift:{1:["&","#"]}}};Formatter.match=match;Formatter.prototype._options=function e(t){var r=Formatter.defaults;if(typeof t==="undefined"){return Object.assign({},r)}var n=t&&t.exceptions||{};var i=n.specials||[];var a=n.shift||{1:[]};return _objectSpread(_objectSpread(_objectSpread({},r),t),{},{exceptions:{specials:[].concat(_toConsumableArray(r.exceptions.specials),_toConsumableArray(i)),shift:_objectSpread(_objectSpread({},a),{},{1:[].concat(_toConsumableArray(r.exceptions.shift[1]),_toConsumableArray(a[1]))})}})};Formatter.prototype.indent=function e(t){var r=tokenize(this.__code__,true);return this._indent(r,t)};Formatter.exception_shift=function(a,e){function t(e){if(!e.length){return false}if(e.indexOf(a)!==-1){return true}else{var t=e.filter(function(e){return e instanceof RegExp});if(!t.length){return false}var r=_createForOfIteratorHelper(t),n;try{for(r.s();!(n=r.n()).done;){var i=n.value;if(a.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){n.offset=0}if(a.toString()===t.toString()&&balanced(a)){return n.offset+a[0].col}else if(a.length===1){return n.offset+a[0].col+1}else{var s=-1;if(o){var c=Formatter.exception_shift(o.token,n);if(c!==-1){s=c}}if(s===-1){s=Formatter.exception_shift(a[1].token,n)}if(s!==-1){return n.offset+a[0].col+s}else if(a[0].line3&&a[1].line===a[3].line){if(a[1].token==="("||a[1].token==="["){return n.offset+a[1].col}return n.offset+a[3].col}else if(a[0].line===a[1].line){return n.offset+n.indent+a[0].col}else{var l=a.slice(2);for(var f=0;f")};Ahead.prototype.match=function(e){return e.match(this.pattern)};function Pattern(){for(var e=arguments.length,t=new Array(e),r=0;r")};Formatter.Pattern=Pattern;Formatter.Ahead=Ahead;var p_o=/^[[(]$/;var p_e=/^[\])]$/;var not_p=/[^()[\]]/;var not_close=new Ahead(/[^)\]]/);var glob=Symbol["for"]("*");var sexp_or_atom=new Pattern([p_o,glob,p_e],[not_p],"+");var sexp=new Pattern([p_o,glob,p_e],"+");var symbol=new Pattern([Symbol["for"]("symbol")],"?");var symbols=new Pattern([Symbol["for"]("symbol")],"*");var identifiers=[p_o,symbols,p_e];var let_value=new Pattern([p_o,Symbol["for"]("symbol"),glob,p_e],"+");var syntax_rules=keywords_re("syntax-rules");var def_lambda_re=keywords_re("define","lambda","define-macro","syntax-rules");var non_def=/^(?!.*\b(?:[()[\]]|define(?:-macro)?|let(?:\*|rec|-env|-syntax|)?|lambda|syntax-rules)\b).*$/;var let_re=/^(?:#:)?(let(?:\*|rec|-env|-syntax)?)$/;function keywords_re(){for(var e=arguments.length,t=new Array(e),r=0;r0&&!u[e]){u[e]=previousSexp(o,e)}});var s=_createForOfIteratorHelper(i),c;try{for(s.s();!(c=s.n()).done;){var l=_slicedToArray(c.value,3),f=l[0],_=l[1],p=l[2];_=_.valueOf();var d=_>0?u[_]:o;var h=d.filter(function(e){return e.trim()&&!is_special(e)});var m=r(d);var y=match(f,h);var v=n.slice(a).find(function(e){return e.trim()&&!is_special(e)});if(y&&(p instanceof Ahead&&p.match(v)||!p)){var b=a-m;if(n[b]!=="\n"){if(!n[b].trim()){n[b]="\n"}else{n.splice(b,0,"\n");a++}}a+=m;continue e}}}catch(e){s.e(e)}finally{s.f()}}this.__code__=n.join("");return this};Formatter.prototype._spaces=function(e){return" ".repeat(e)};Formatter.prototype.format=function e(t){var r=this.__code__.replace(/[ \t]*\n[ \t]*/g,"\n ");var n=tokenize(r,true);var i=this._options(t);var a=0;var o=0;for(var u=0;u0){n=Math.floor(t()*r);r--;var i=[e[n],e[r]];e[r]=i[0];e[n]=i[1]}return e}function Nil(){}Nil.prototype.toString=function(){return"()"};Nil.prototype.valueOf=function(){return undefined};Nil.prototype.serialize=function(){return 0};Nil.prototype.to_object=function(){return{}};Nil.prototype.append=function(e){return new Pair(e,_nil)};Nil.prototype.to_array=function(){return[]};var _nil=new Nil;function Pair(e,t){if(typeof this!=="undefined"&&this.constructor!==Pair||typeof this==="undefined"){return new Pair(e,t)}this.car=e;this.cdr=t}function to_array(a,o){return function e(t){typecheck(a,t,["pair","nil"]);if(is_nil(t)){return[]}var r=[];var n=t;while(true){if(is_pair(n)){if(n.have_cycles("cdr")){break}var i=n.car;if(o&&is_pair(i)){i=this.get(a).call(this,i)}r.push(i);n=n.cdr}else if(is_nil(n)){break}else{throw new Error("".concat(a,": can't convert improper list"))}}return r}}Pair.prototype.flatten=function(){return Pair.fromArray(flatten(this.to_array()))};Pair.prototype.length=function(){var e=0;var t=this;while(true){if(!t||is_nil(t)||!is_pair(t)||t.have_cycles("cdr")){break}e++;t=t.cdr}return e};Pair.match=function(e,t){if(e instanceof LSymbol){return LSymbol.is(e,t)}else if(is_pair(e)){return Pair.match(e.car,t)||Pair.match(e.cdr,t)}else if(Array.isArray(e)){return e.some(function(e){return Pair.match(e,t)})}else if(is_plain_object(e)){return Object.values(e).some(function(e){return Pair.match(e,t)})}return false};Pair.prototype.find=function(e){return Pair.match(this,e)};Pair.prototype.clone=function(){var r=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var n=new Map;function i(e){if(is_pair(e)){if(n.has(e)){return n.get(e)}var t=new Pair;n.set(e,t);if(r){t.car=i(e.car)}else{t.car=e.car}t.cdr=i(e.cdr);t[__cycles__]=e[__cycles__];return t}return e}return i(this)};Pair.prototype.last_pair=function(){var e=this;while(true){if(!is_pair(e.cdr)){return e}if(e.have_cycles("cdr")){break}e=e.cdr}};Pair.prototype.to_array=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;var t=[];if(is_pair(this.car)){if(e){t.push(this.car.to_array())}else{t.push(this.car)}}else{t.push(this.car.valueOf())}if(is_pair(this.cdr)){t=t.concat(this.cdr.to_array(e))}return t};Pair.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(is_pair(e)||r&&e instanceof Array&&e[__data__]){return e}if(t===false){var n=_nil;for(var i=e.length;i--;){n=new Pair(e[i],n)}return n}if(e.length&&!(e instanceof Array)){e=_toConsumableArray(e)}var a=_nil;var o=e.length;while(o--){var u=e[o];if(u instanceof Array){u=Pair.fromArray(u,t,r)}else if(typeof u==="string"){u=LString(u)}else if(typeof u==="number"&&!Number.isNaN(u)){u=LNumber(u)}a=new Pair(u,a)}return a};Pair.prototype.to_object=function(){var e=arguments.length>0&&arguments[0]!==undefined?arguments[0]:false;var t=this;var r={};while(true){if(is_pair(t)&&is_pair(t.car)){var n=t.car;var i=n.car;if(i instanceof LSymbol){i=i.__name__}if(i instanceof LString){i=i.valueOf()}var a=n.cdr;if(is_pair(a)){a=a.to_object(e)}if(is_native(a)){if(!e){a=a.valueOf()}}r[i]=a;t=t.cdr}else{break}}return r};Pair.fromPairs=function(e){return e.reduce(function(e,t){return new Pair(new Pair(new LSymbol(t[0]),t[1]),e)},_nil)};Pair.fromObject=function(t){var e=Object.keys(t).map(function(e){return[e,t[e]]});return Pair.fromPairs(e)};Pair.prototype.reduce=function(e){var t=this;var r=_nil;while(true){if(!is_nil(t)){r=e(r,t.car);t=t.cdr}else{break}}return r};Pair.prototype.reverse=function(){if(this.have_cycles()){throw new Error("You can't reverse list that have cycles")}var e=this;var t=_nil;while(!is_nil(e)){var r=e.cdr;e.cdr=t;t=e;e=r}return t};Pair.prototype.transform=function(n){function i(e){if(is_pair(e)){if(e.replace){delete e.replace;return e}var t=n(e.car);if(is_pair(t)){t=i(t)}var r=n(e.cdr);if(is_pair(r)){r=i(r)}return new Pair(t,r)}return e}return i(this)};Pair.prototype.map=function(e){if(typeof this.car!=="undefined"){return new Pair(e(this.car),is_nil(this.cdr)?_nil:this.cdr.map(e))}else{return _nil}};var repr=new Map;function is_plain_object(e){return e&&_typeof$1(e)==="object"&&e.constructor===Object}var props=Object.getOwnPropertyNames(Array.prototype);var array_methods=[];props.forEach(function(e){array_methods.push(Array[e],Array.prototype[e])});function is_array_method(e){e=unbind(e);return array_methods.includes(e)}function is_lips_function(e){return is_function(e)&&(is_lambda(e)||e.__doc__)}function user_repr(r){var e=r.constructor||Object;var n=is_plain_object(r);var i=is_function(r[Symbol.asyncIterator])||is_function(r[Symbol.iterator]);var a;if(repr.has(e)){a=repr.get(e)}else{repr.forEach(function(e,t){t=unbind(t);if(r instanceof t&&(t===Object&&n&&!i||t!==Object)){a=e}})}return a}var str_mapping=new Map;[[true,"#t"],[false,"#f"],[null,"#null"],[undefined,"#void"]].forEach(function(e){var t=_slicedToArray(e,2),r=t[0],n=t[1];str_mapping.set(r,n)});function symbolize(r){if(r&&_typeof$1(r)==="object"){var n={};var e=Object.getOwnPropertySymbols(r);e.forEach(function(e){var t=e.toString().replace(/Symbol\(([^)]+)\)/,"$1");n[t]=toString(r[e])});var t=Object.getOwnPropertyNames(r);t.forEach(function(e){var t=r[e];if(t&&_typeof$1(t)==="object"&&t.constructor===Object){n[e]=symbolize(t)}else{n[e]=toString(t)}});return n}return r}function get_props(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function has_own_function(e,t){return e.hasOwnProperty(t)&&is_function(e.toString)}function function_to_string(e){if(is_native_function(e)){return"#"}var t=e.prototype&&e.prototype.constructor;if(is_function(t)&&is_lambda(t)){if(e[__class__]&&t.hasOwnProperty("__name__")){var r=t.__name__;if(LString.isString(r)){r=r.toString();return"#")}return"#"}}if(e.hasOwnProperty("__name__")){var n=e.__name__;if(_typeof$1(n)==="symbol"){n=symbol_to_string(n)}if(typeof n==="string"){return"#")}}if(has_own_function(e,"toString")){return e.toString()}else if(e.name&&!is_lambda(e)){return"#")}else{return"#"}}var instances=new Map;[[Error,function(e){return e.message}],[Pair,function(e,t){var r=t.quote,n=t.skip_cycles,i=t.pair_args;if(!n){e.mark_cycles()}return e.toString.apply(e,[r].concat(_toConsumableArray(i)))}],[LCharacter,function(e,t){var r=t.quote;if(r){return e.toString()}return e.valueOf()}],[LString,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=_slicedToArray(e,2),r=t[0],n=t[1];instances.set(r,n)});var native_types=[LSymbol,Macro,Values,InputPort,OutputPort,Environment,QuotedPromise];function toString(e,t,r){if(typeof jQuery!=="undefined"&&e instanceof jQuery.fn.init){return"#"}if(str_mapping.has(e)){return str_mapping.get(e)}if(is_prototype(e)){return"#"}if(e){var n=e.constructor;if(instances.has(n)){for(var i=arguments.length,a=new Array(i>3?i-3:0),o=3;o"}if(e===null){return"null"}if(is_function(e)){if(is_function(e.toString)&&e.hasOwnProperty("toString")){return e.toString().valueOf()}return function_to_string(e)}if(_typeof$1(e)==="object"){var l=e.constructor;if(!l){l=Object}var f;if(typeof l.__class__==="string"){f=l.__class__}else{var _=user_repr(e);if(_){if(is_function(_)){return _(e,t)}else{throw new Error("toString: Invalid repr value")}}f=l.name}if(is_function(e.toString)&&e.hasOwnProperty("toString")){return e.toString().valueOf()}if(type(e)==="instance"){if(is_lambda(l)&&l.__name__){f=l.__name__.valueOf()}else if(!is_native_function(l)){f="instance"}}if(is_iterator(e,Symbol.iterator)){if(f){return"#")}return"#"}if(is_iterator(e,Symbol.asyncIterator)){if(f){return"#")}return"#"}if(f!==""){return"#<"+f+">"}return"#