From 2147caff498f771eaa3d1cb13b9bdee8d32bf87d Mon Sep 17 00:00:00 2001 From: Kristofers Solo Date: Sun, 1 May 2022 13:41:30 +0300 Subject: [PATCH 1/4] Changed alacritty --- alacritty/alacritty.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/alacritty/alacritty.yml b/alacritty/alacritty.yml index 4edcd710..fa774870 100644 --- a/alacritty/alacritty.yml +++ b/alacritty/alacritty.yml @@ -38,7 +38,7 @@ window: dimensions: columns: 0 lines: 0 - + opacity: 0.9 @@ -73,7 +73,7 @@ window: decorations: none - + # Startup Mode (changes require restart) # @@ -162,7 +162,7 @@ font: style: Bold Italic # Point size - size: 9.0 + size: 11.0 # Offset is the extra space around each character. `offset.y` can be thought # of as modifying the line spacing, and `offset.x` as modifying the letter From 822078509d1ae160f818ac2f90c22e580a1a7d24 Mon Sep 17 00:00:00 2001 From: Kristofers Solo Date: Sun, 1 May 2022 13:41:50 +0300 Subject: [PATCH 2/4] Changed vscodium --- .../extensions/yzhang.markdown-all-in-one-3.5.0/welcome/WELCOMED | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 vscodium/extensions/yzhang.markdown-all-in-one-3.5.0/welcome/WELCOMED diff --git a/vscodium/extensions/yzhang.markdown-all-in-one-3.5.0/welcome/WELCOMED b/vscodium/extensions/yzhang.markdown-all-in-one-3.5.0/welcome/WELCOMED new file mode 100644 index 00000000..e69de29b From 314bc1f53fd77002a4d81941eb694ae931faa323 Mon Sep 17 00:00:00 2001 From: Kristofers Solo Date: Wed, 4 May 2022 23:29:01 +0300 Subject: [PATCH 3/4] Minor changes --- awesome/desktop/rc.lua | 17 +- fastfetch/config.conf | 2 +- vscodium/extensions/.obsolete | 2 +- .../.vsixmanifest | 43 + .../CHANGELOG.md | 96 + .../DEV_README.md | 120 + .../mechatroner.rainbow-csv-2.3.0/LICENSE.txt | 21 + .../mechatroner.rainbow-csv-2.3.0/README.md | 175 ++ .../contrib/textarea-caret-position/LICENSE | 9 + .../contrib/textarea-caret-position/index.js | 155 ++ .../dist/web/extension.js | 1 + .../dist/web/extension.js.map | 1 + .../dist/web/test/suite/index.js | 2 + .../dist/web/test/suite/index.js.LICENSE.txt | 6 + .../dist/web/test/suite/index.js.map | 1 + .../extension.js | 1586 ++++++++++++++ .../package.json | 433 ++++ .../rainbow_csv_logo.png | Bin 0 -> 2550 bytes .../rainbow_utils.js | 675 ++++++ .../rbql mock/rbql_mock.py | 77 + .../rbql_client.html | 620 ++++++ .../rbql_client.js | 437 ++++ .../rbql_core/LICENSE | 21 + .../rbql_core/README.md | 200 ++ .../rbql_core/rbql-js/.eslintrc.json | 26 + .../rbql_core/rbql-js/cli_parser.js | 74 + .../rbql_core/rbql-js/cli_rbql.js | 387 ++++ .../rbql_core/rbql-js/csv_utils.js | 151 ++ .../rbql_core/rbql-js/rbql.js | 1951 +++++++++++++++++ .../rbql_core/rbql-js/rbql_csv.js | 731 ++++++ .../rbql_core/rbql/__init__.py | 11 + .../rbql_core/rbql/__main__.py | 2 + .../rbql_core/rbql/_version.py | 3 + .../rbql_core/rbql/csv_utils.py | 114 + .../rbql_core/rbql/rbql_csv.py | 584 +++++ .../rbql_core/rbql/rbql_engine.py | 1662 ++++++++++++++ .../rbql_core/rbql/rbql_ipython.py | 117 + .../rbql_core/rbql/rbql_main.py | 519 +++++ .../rbql_core/rbql/rbql_pandas.py | 96 + .../rbql_core/rbql/rbql_sqlite.py | 105 + .../rbql_core/rbql_logo.png | Bin 0 -> 113463 bytes .../rbql_core/vscode_rbql.py | 51 + .../rbql_logo.svg | 1 + .../rbql_suggest.js | 286 +++ .../syntaxes/clnsv.tmLanguage.json | 23 + .../syntaxes/crtsv.tmLanguage.json | 23 + .../syntaxes/csv.tmLanguage.json | 23 + .../syntaxes/dbqsv.tmLanguage.json | 23 + .../syntaxes/dotsv.tmLanguage.json | 23 + .../syntaxes/eqlsv.tmLanguage.json | 23 + .../syntaxes/hypsv.tmLanguage.json | 23 + .../syntaxes/pipe_simple.tmLanguage.json | 23 + .../syntaxes/rb_hover.tmLanguage.json | 91 + .../syntaxes/scsv.tmLanguage.json | 23 + .../syntaxes/tldsv.tmLanguage.json | 23 + .../syntaxes/tsv.tmLanguage.json | 23 + .../syntaxes/wspcsv.tmLanguage.json | 23 + .../cache/models.json | 2 +- vscodium/settings.json | 9 +- zsh/.zshrc | 2 +- 60 files changed, 11930 insertions(+), 21 deletions(-) create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/.vsixmanifest create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/CHANGELOG.md create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/DEV_README.md create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/LICENSE.txt create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/README.md create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/contrib/textarea-caret-position/LICENSE create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/contrib/textarea-caret-position/index.js create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/dist/web/extension.js create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/dist/web/extension.js.map create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/dist/web/test/suite/index.js create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/dist/web/test/suite/index.js.LICENSE.txt create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/dist/web/test/suite/index.js.map create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/extension.js create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/package.json create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rainbow_csv_logo.png create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rainbow_utils.js create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql mock/rbql_mock.py create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_client.html create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_client.js create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/LICENSE create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/README.md create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/.eslintrc.json create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/cli_parser.js create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/cli_rbql.js create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/csv_utils.js create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/rbql.js create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/rbql_csv.js create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/__init__.py create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/__main__.py create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/_version.py create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/csv_utils.py create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_csv.py create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_engine.py create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_ipython.py create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_main.py create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_pandas.py create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_sqlite.py create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql_logo.png create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/vscode_rbql.py create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_logo.svg create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_suggest.js create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/clnsv.tmLanguage.json create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/crtsv.tmLanguage.json create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/csv.tmLanguage.json create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/dbqsv.tmLanguage.json create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/dotsv.tmLanguage.json create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/eqlsv.tmLanguage.json create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/hypsv.tmLanguage.json create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/pipe_simple.tmLanguage.json create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/rb_hover.tmLanguage.json create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/scsv.tmLanguage.json create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/tldsv.tmLanguage.json create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/tsv.tmLanguage.json create mode 100644 vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/wspcsv.tmLanguage.json diff --git a/awesome/desktop/rc.lua b/awesome/desktop/rc.lua index 4785bc2a..4b0b4812 100644 --- a/awesome/desktop/rc.lua +++ b/awesome/desktop/rc.lua @@ -235,7 +235,7 @@ awful.screen.connect_for_each_screen(function(s) s.mytasklist, -- Middle widget { -- Right widgets layout = wibox.layout.fixed.horizontal, - wibox.widget.systray(), + wibox.widget.systray(), cpu_widget(), ram_widget(), net_speed_widget(), @@ -253,7 +253,7 @@ awful.screen.connect_for_each_screen(function(s) --widget_type = 'arc', --mixer_cmd = 'pulsemixer', --}, - logout_menu_widget(), + logout_menu_widget(), mytextclock, s.mylayoutbox, }, @@ -552,7 +552,7 @@ awful.rules.rules = { { rule_any = {type = { "normal", "dialog" } }, properties = { titlebars_enabled = false } }, - + { rule_any = { class = { "discord", "telegram-desktop", "TelegramDesktop" } @@ -564,7 +564,7 @@ awful.rules.rules = { class = { "firefox" } }, properties = { screen = 1, tag = "7" } }, - + { rule_any = { class = { "spotify", "Spotify" }, @@ -572,11 +572,6 @@ awful.rules.rules = { }, properties = { screen = 2, tag = "9" } }, - { - rule_any = { - name = { "Apex Legends" } - }, properties = { screen = 1, tag = "5", fullscreen = true } - }, } -- {{{ Signals @@ -653,10 +648,10 @@ awful.spawn.with_shell("xinput --set-prop 'COOLERMASTER CM310' 'libinput Accel S --awful.spawn.with_shell("xrandr --output DP-0 --mode 1920x1080 --output HDMI-0 --mode 1920x1080 --right-of DP-0") --awful.spawn.with_shell("xrandr --output DP-0 --mode 1920x1080 --output HDMI-0 --mode 1920x1080 --left-of DP-0") awful.spawn.with_shell("dropbox") -awful.spawn.with_shell("discord") awful.spawn.with_shell("telegram-desktop") awful.spawn.with_shell("flameshot") ---awful.spawn.with_shell("discord-development") +awful.spawn.with_shell("discord") +-- awful.spawn.with_shell("discord-development") --awful.spawn.with_shell("xrandr --output HDMI-0 --off") awful.spawn.with_shell("setxkbmap lv") diff --git a/fastfetch/config.conf b/fastfetch/config.conf index 0c581f03..923f8b0e 100644 --- a/fastfetch/config.conf +++ b/fastfetch/config.conf @@ -26,7 +26,7 @@ # List available modules with "fastfetch --list-modules". # Get the default structure with "fastfetch --print-structure". # --structure Title:Separator:OS:Host:Kernel:Uptime:Packages:Shell:Resolution:DE:WM:WMTheme:Theme:Icons:Font:Cursor:Terminal:TerminalFont:CPU:GPU:Memory:Disk:Battery:Locale:Break:Colors ---structure Title:Separator:OS:Host:Kernel:Uptime:Packages:Resolution:DE:WM:WMTheme:Theme:Icons:CPU:GPU:Memory:Disk:Battery:Player:Song:Break +--structure Title:Separator:OS:Host:Kernel:Uptime:Packages:Resolution:DE:WM:WMTheme:Theme:Icons:CPU:GPU:Memory:Disk:Battery:Song:Break # Multithreading option: # Sets if fastfetch should use multiple threads to detect the values. diff --git a/vscodium/extensions/.obsolete b/vscodium/extensions/.obsolete index 7f9a7521..b39d8e7f 100644 --- a/vscodium/extensions/.obsolete +++ b/vscodium/extensions/.obsolete @@ -1 +1 @@ -{"ms-vscode.references-view-0.0.86":true,"ms-vscode.js-debug-companion-1.0.16":true} \ No newline at end of file +{"ms-vscode.references-view-0.0.86":true,"ms-vscode.js-debug-companion-1.0.16":true,"mechatroner.rainbow-csv-2.2.0":true} \ No newline at end of file diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/.vsixmanifest b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/.vsixmanifest new file mode 100644 index 00000000..6ec651da --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/.vsixmanifest @@ -0,0 +1,43 @@ + + + + + Rainbow CSV + Highlight CSV and TSV files, Run SQL-like queries + csv,tsv,highlight,CSV,__ext_csv,TSV,__ext_tsv,__ext_tab,csv (pipe),CSV (pipe),csv (tilde),CSV (tilde),csv (whitespace),CSV (whitespace),csv (caret),CSV (caret),csv (colon),CSV (colon),csv (double quote),CSV (double quote),csv (equals),CSV (equals),csv (dot),CSV (dot),csv (hyphen),CSV (hyphen),csv (semicolon),CSV (semicolon),rainbow hover markup,plaintext,sql,__web_extension + Data Science,Other,Programming Languages + Public + + + + + + + + + + + + + + + + + + + + extension/LICENSE.txt + extension/rainbow_csv_logo.png + + + + + + + + + + + + + \ No newline at end of file diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/CHANGELOG.md b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/CHANGELOG.md new file mode 100644 index 00000000..a96ce80e --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/CHANGELOG.md @@ -0,0 +1,96 @@ +# Rainbow CSV for Visual Studio Code Change Log + +## 2.3.0 +* Improve alignment algorithm: special handling of numeric columns, see [#106](https://github.com/mechatroner/vscode_rainbow_csv/issues/106). +* Show alignment progress indicator which is very nice for large files. + +## 2.2.0 +* UI and UX improvements by [@anthroid](https://github.com/anthroid). + +## 2.1.0 +* Support RBQL and column edit mode in web version of VSCode. +* Support RBQL result set output dir customization [#101](https://github.com/mechatroner/vscode_rainbow_csv/issues/101). +* Slightly reduce startup time by moving non-critical code into a lazy-loaded module. +* Internal code refactoring. + +## 2.0.0 +* Enable web/browser version for vscode.dev +* RBQL: improve join table path handling. + +## 1.10.0 +* RBQL update: improved console UI. + +## 1.9.0 +* RBQL update: improved CSV header support. + +## 1.8.1 +* Minor RBQL update + +## 1.8.0 +* New command: "SetHeaderLine" by @WetDesertRock, see [#71](https://github.com/mechatroner/vscode_rainbow_csv/issues/71) +* Updated RBQL +* Added integration tests + + +## 1.7.0 +* Updated RBQL +* Improved RBQL UI + + +## 1.6.0 +* Updated RBQL + + +## 1.5.0 +* Highlight column info tooltip with the same color as the column itself + + +## 1.4.0 +* Run CSV autodetection whenever a text chunk is copied into a new untitled buffer +* Improve startup performance +* RBQL: Support column names as variables +* RBQL: Support newlines in double-quoted CSV fields +* RBQL: Change default encoding to UTF-8 +* RBQL: Enable for untitled buffers +* RBQL: Improve UI/UX, add history, built-in docs + + +## 1.3.0 +* Updated RBQL to version 0.9.0 +* Restricted usage of Align/Shrink commands in files with unbalanced double quotes +* Fixed incorrect dialect name: "tilda" -> "tilde", see [#40](https://github.com/mechatroner/vscode_rainbow_csv/issues/40) +* Added an eror message when RBQL console is used with unsaved file [#41](https://github.com/mechatroner/vscode_rainbow_csv/issues/41) + + +## 1.2.0 +* Added frequency-based fallback content-based autodetection algorithm for .csv files +* Adjusted default parameters: added '|' to the list of autodetected separators +* Fixed "Align/Shrink" button logic [#38](https://github.com/mechatroner/vscode_rainbow_csv/issues/38) +* Fixed bug: incorrect RBQL result set dialect when output dialect doesn't match input +* Improved documentation + + +## 1.1.0 +* Special treatment of comment lines by [@larsonmars](https://github.com/larsonmars) +* RBQL encoding customization by [@mandel59](https://github.com/mandel59) +* Implemented Whitespace-separated dialect +* Linter: detect trailing whitespaces in fields [#15](https://github.com/mechatroner/vscode_rainbow_csv/issues/15) +* Added commands: remove trailing whitespaces from all fields and allign columns with trailing whitespaces +* Implemented RBQL result set copy-back command +* Improved RBQL console UI +* Customizable "Preview big CSV: head/tail" context menu options [#32](https://github.com/mechatroner/vscode_rainbow_csv/issues/32) +* Improved autodetection algorithm for files with multiple candidate separators + + +## 0.8.0 +* Large files preview functionality implemented by [@neilsustc](https://github.com/neilsustc) see [#24](https://github.com/mechatroner/vscode_rainbow_csv/issues/24) +* Fix single-autodetection per file limit, see [#26](https://github.com/mechatroner/vscode_rainbow_csv/issues/26) +* Enable content-based autodetection for .csv files +* Support tooltip message customizations, see [#12](https://github.com/mechatroner/vscode_rainbow_csv/issues/12) +* Fix RBQL warnings +* Various minor improvements + + +## 0.7.1 +* Fix: Added safety check to RBQL that would prevent accidental usage of assignment operator "=" instead of comparison "==" or "===" in JS (In Python this was not possible before the fix due to Python's own syntatic checker). +* Added "Rainbow CSV" category to all extension commands by [@yozlet](https://github.com/yozlet) request, see [#22](https://github.com/mechatroner/vscode_rainbow_csv/issues/22) diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/DEV_README.md b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/DEV_README.md new file mode 100644 index 00000000..dbf26501 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/DEV_README.md @@ -0,0 +1,120 @@ +## Instructions + +### Debugging the extension: +#### For standard VSCode: +1. Open rainbow_csv directory in VSCode +2. Make sure you have "Extension" run mode enabled +3. Click "Run" or F5 + + +#### For web-based VSCode: +1. Run `npm install --only=dev` - OK to run in WSL +2. Run `npm run compile-web && npm run start-web-server` - OK to run in WSL. - This should start a local server at http://localhost:3000/ +3. Point your browser to http://localhost:3000/ +It is possible to run this in windows cmd too, but it could be that the node_modules dir has to be deleted and installed from scratch. +The difference between running in win and in WSL is that in WSL it would only run with `--browser=none` option and this option doesn't run unit tests automatically which could be an issue if you want to run tests instead of manual debugging. + + +### Running unit tests for the extension inside VSCode: +#### For standard VSCode: +1. **IMPORTANT** Make sure you have no open VSCode instances running, all VSCode windows are closed! +2. run `npm install --only=dev` (If you have WSL - run in Windows, don't run in WSL). +3. run `npm run test` in Windows (If you have WSL - run in Windows, don't run in WSL). Make sure that the tests are successful. + +#### For web-based VSCode: +1. run `npm install` (If you have WSL - run in Windows, don't run in WSL). +2. run `compile-web` (If you have WSL - run in Windows, don't run in WSL). This will combine all scripts into a single web script and put it into the `dist` folder. +3. run `npm run test-in-browser` (If you have WSL - run in Windows, don't run in WSL). This will open a new browser windows and run all the unit tests. Make sure that the tests are successful. + + +### Running unit tests for the extension inside VSCode: +1. In console in rainbow_csv directory run `npm install --only=dev` - OK to run the command in WSL while launching in Windows. This will install the dependencies, including `vscode/lib/testrunner` +2. Open rainbow_csv directory in VSCode switch to "Extension Tests" mode and click run + +Example of minimalistic test setup: +https://github.com/microsoft/vscode-extension-samples/tree/main/helloworld-test-sample + + + +#### Debuging +Looks like it is possible to directly run scripts from package.json with `npx` like this: +``` +npx vscode-test-web --help +``` +And apparently another option to execute this command is (never tested): +``` +npx @vscode/test-web --extensionDevelopmentPath=$extensionFolderPath $testDataPath +``` + +Options available for vscode-test-web +* version +`'insiders' | 'stable' | 'sources' [Optional, default 'insiders']` + +* browser +`'chromium' | 'firefox' | 'webkit' | 'none': The browser to launch. [Optional, defaults to 'chromium']` +If `none` is provided it wouldn't run unit test and it wouldn't kill the server when the browser window is closed. + +If exceptions happens in extension.js you will be able to see it in the browser console (but the line number would be wrong). + + +#### Issues +* FS mount not working: https://github.com/microsoft/vscode-test-web/issues/16 + + +### Running the browser version for vscode.dev +The npx command `npx serve --cors -l 5000` failed in WSL with `cb.apply is not a function` error. +The same command worked as expected from Windows cmd. +Steps: +1. Run `npx serve --cors -l 5000` - this may not work in WSL, in this case run in windows cmd. This local server uses `http` instead of `https` and because of that VSCode will not work with it directly, although the docs say otherwise (https://code.visualstudio.com/api/extension-guides/web-extensions#test-your-web-extension-in-on-vscode.dev) - it will just produce some cors/wss content security policy related errors in the log. So you need to do step 2. +2. In another cmd tab run another commmand: `npx localtunnel -p 5000` - this will create a "tunnel" server pointing to the server from the first command - this will produce a link like `https://rotten-snake-42.loca.lt/` +3. Follow the `https://rotten-snake-42.loca.lt/` link and press the button - this will show the content of your extension folder - https server is working. +4. Go to vscode.dev -> Ctrl+Shift+P -> run Developer: Install Web Extension... -> Copy the `https://rotten-snake-42.loca.lt/` link. In my experience this will work only with https urls. If you use http, the extension will be sort of "installed" - it will be listed in the installed extension pannel but the main extension.js won't be loaded so all the logic will be missing from it. + + +### Publishing +1. Make sure you have webpack installed: run `npm install --only=dev` (Better to avoid running this in WSL). + Although this would create `node_modules/` and `package-lock.json` file this is not a problem because they are excluded from final package via the `.vscodeignore` file. +2. Run vsce publish as usual. vsce will also automatically run `vscode:prepublish` / `npm run package-web` command. + + +### Generating documentation with showdown +In order to generate RBQL documentation use showdown - based markdown_to_html.js script from junk/rainbow_stuff +Usage: `node markdown_to_html.js ~/vscode_rainbow_csv/rbql_core/README.md out.html` + + +## TODO LIST +* Improve RBQL encoding handling logic when VScode encoding info API is implemented, see https://github.com/microsoft/vscode/issues/824. + +* Consider keeping only one open RBQL console at any time - if another one opens automatically close the previous one. + +* DEBUG: Add a huge no-op loop on startup in order to reproduce/emulate high-cpu load error from #55. + +* Support virtual header for rbql_csv. + +* Consider replacing the RBQL query text input with scrollable textarea - it has a drawback that on enter it will go to the next line instead running the query. + +* Figure out if it is possible to convert to a web extension. + +* Make the `is_web_ext` check more reliable and explicit. + +* Replace callbacks with async where possible + +* Store VSCode documents instead of file paths in result_set_parent_map so that the map can be used in web version. And the autodetection_stoplist also should be doc based to work in web. + +* Support JOIN queries in web version. + +* Get rid of typescript files and infra, but add comments explaining how you obtained the js versions of the files. + +* Try to get rid of `@types/vscode` dev dependency. + +* Support all commands in web version + +* Use `await save_to_global_state()` everywhere. + +* Use `await vscode.workspace.openTextDocument` everywhere. + +* Get rid of `then` entirely + +* Merge rbql_query_web and rbql_query_node + +* Add comment prefix handling in RBQL, unit tests (and web_ui entry?) diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/LICENSE.txt b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/LICENSE.txt new file mode 100644 index 00000000..6a82aa1c --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Dmitry Ignatovich + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/README.md b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/README.md new file mode 100644 index 00000000..71d46689 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/README.md @@ -0,0 +1,175 @@ +# Rainbow CSV + +## Main Features +* Highlight columns in comma (.csv), tab (.tsv), semicolon and pipe - separated files in different colors +* Transform and filter tables using built-in SQL-like query language +* Provide info about column on hover +* Automatic consistency check for csv files (CSVLint) +* Multi-cursor column edit +* Align columns with spaces and Shrink (trim spaces from fields) +* Works in browser (vscode.dev) with limited functionality + +![screenshot](https://i.imgur.com/6eJqeUN.png) + +## Usage + +If your csv, semicolon-separated or tab-separated file doesn't have .csv or .tsv extension, you can manually enable highlighting by clicking on the current language label mark in the right bottom corner and then choosing "CSV", "TSV", "CSV (semicolon)" or "CSV (pipe)" depending on the file content, see this [screenshot](https://stackoverflow.com/a/30776845/2898283) +Another way to do this: select one separator character with mouse cursor -> right click -> "Set as Rainbow separator" + +#### Supported separators + +|Language name | Separator | Extension | Properties | +|-----------------|----------------------|-----------|-------------------------------------| +|csv | , (comma) | .csv | Ignored inside double-quoted fields | +|tsv | \t (TAB) | .tsv .tab | | +|csv (semicolon) | ; (semicolon) | | Ignored inside double-quoted fields | +|csv (whitespace) | whitespace | | Consecutive whitespaces are merged | +|csv (pipe) | | (pipe) | | | +|csv (...) | ~ ^ : " = . - | | | + + +#### Content-based separator autodetection +Rainbow CSV runs table autodetection algorithm for all "Plain Text" and "*.csv" files. In most cases this is a very cheap operation because autodetection usually stops after checking only 1 or 2 topmost lines. +Autodetection can be disabled at the extension settings page. +The autodetection algorithm skips files that have less than N=10 non-comment lines; value of N can be adjusted in the settings. +By default only comma, tab, semicolon and pipe are tried during autodetection, but you can adjust the list of candidate separators: add the following line to your VSCode config and edit it by removing or including any of the supported separators: +``` +"rainbow_csv.autodetect_separators": ["\t", ",", ";", "|"], +``` +If the autodetection algorithm makes an error and highlights a non-csv file, you can press "Rainbow OFF" button inside the status line. + + +#### Customizing file extension - separator association +If you often work with spreadsheet files with one specific extension (e.g. ".dat") and you don't want to rely on the autodetection algorithm, you can associate that extension with one of the supported separators. +For example to associate ".dat" extension with pipe-separated files and ".csv" with semicolon-separated files add the following lines to your VS Code json config: + +``` +"files.associations": { + "*.dat": "csv (pipe)", + "*.csv": "csv (semicolon)" +}, +``` + +Important: language identifiers in the config must be specified in **lower case**! E.g. use `csv (semicolon)`, not `CSV (semicolon)`. +List of supported language ids: `"csv", "tsv", "csv (semicolon)", "csv (pipe)", "csv (whitespace)", "csv (tilde)", "csv (caret)", "csv (colon)", "csv (double quote)", "csv (equals)", "csv (dot)", "csv (hyphen)"` + + +#### CSVLint consistency check + +The linter checks the following: +* consistency of double quotes usage in CSV rows +* consistency of number of fields per CSV row + +To recheck a csv file click on "CSVLint" button. + + +#### Working with large files +To enable Rainbow CSV for very big files (more than 300K lines or 20MB) disable "Editor:Large File Optimizations" option in VS Code settings. +You can preview huge files by clicking "Preview... " option in VS Code File Explorer context menu. +All Rainbow CSV features would be disabled by VSCode if file is bigger than 50MB. + + +#### Working with CSV files with comments +Some CSV files can contain comment lines e.g. metadata before the header line. +To allow CSVLint, content-based autodetection algorithms and _Align_, _Shrink_, _ColumnEdit_ commands work properly with such files you need to adjust your settings. + + +#### Aligning/Shrinking table +You can align columns in CSV files by clicking "Align" statusline button or use _Align_ command +To shrink the table, i.e. remove leading and trailing whitespaces, click "Shrink" statusline button or use _Shrink_ command + + +### Settings +You can customize Rainbow CSV at the extension settings section of VSCode settings. +There you can find the list of available options and their description. + + +### Commands: + +#### RBQL +Enter RBQL - SQL-like language query editing mode. + +#### Align, Shrink +Align columns with whitespaces or shrink them (remove leading/trailing whitespaces) + +#### ColumnEditBefore, ColumnEditAfter, ColumnEditSelect +Activate multi-cursor column editing for column under the cursor. Works only for files with less than 10000 lines. For larger files you can use an RBQL query. +**WARNING**: This is a dangerous mode. It is possible to accidentally corrupt table structure by incorrectly using "Backspace" or entering separator or double quote characters. Use RBQL if you are not sure. +To remove cursor/selection from the header line use "Alt+Click" on it. + +#### SetVirtualHeader +Input a comma-separated string with column names to adjust column names displayed in hover tooltips. Actual header line and file content won't be affected. +"Virtual" header is persistent and will be associated with the parent file across VSCode sessions. + +#### SetHeaderLine +Uses the current line to adjust column names displayed in hover tooltips. Actual header line and file content won't be affected. +This is a "Virtual" header and will be persistent and will be associated with the parent file across VSCode sessions. + +#### SetJoinTableName +Set a custom name for the current file so you can use it instead of the file path in RBQL JOIN queries + + +### Colors customization +You can customize Rainbow CSV colors to increase contrast. [Instructions](https://github.com/mechatroner/vscode_rainbow_csv/blob/HEAD/test/color_customization_example.md#colors-customization) + +## SQL-like "RBQL" query language + +Rainbow CSV has built-in RBQL query language interpreter that allows you to run SQL-like queries using a1, a2, a3, ... column names. +Example: +``` +SELECT a1, a2 * 10 WHERE a1 == "Buy" && a4.indexOf('oil') != -1 ORDER BY parseInt(a2), a4 LIMIT 100 +``` +To enter query-editing mode, execute _RBQL_ VSCode command. +RBQL is a very simple and powerful tool which would allow you to quickly and easily perform most common data-manipulation tasks and convert your csv tables to bash scripts, single-lines json, single-line xml files, etc. +It is very easy to start using RBQL even if you don't know SQL. For example to cut out third and first columns use `SELECT a3, a1` +You can use RBQL command for all possible types of files (e.g. .js, .xml, .html), but for non-table files only two variables: _NR_ and _a1_ would be available. + +[Full Documentation](https://github.com/mechatroner/vscode_rainbow_csv/blob/master/rbql_core/README.md#rbql-rainbow-query-language-description) + + +Screenshot of RBQL Console: +![VSCode RBQL Console](https://i.imgur.com/cQGJ8Vq.png) + + +## Other +### Comparison of Rainbow CSV technology with traditional graphical column alignment + +#### Advantages: + +* WYSIWYG +* Familiar editing environment of your favorite text editor +* Zero-cost abstraction: Syntax highlighting is essentially free, while graphical column alignment can be computationally expensive +* High information density: Rainbow CSV shows more data per screen because it doesn't insert column-aligning whitespaces. +* Color -> column association allows to locate the column of interest more quickly when looking back and forth between the data and other objects on the screen (with column alignment one has to locate the header or count the columns to find the right one) +* Ability to visually associate two same-colored columns from two different windows. This is not possible with graphical column alignment + +#### Disadvantages: + +* Rainbow CSV may be less effective for CSV files with many (> 10) columns. +* Rainbow CSV can't correctly handle newlines inside double-quoted CSV fields (well, theorethically it can, but only under specific conditions) + + +### References + +#### Related VSCode extensions +These extensions can work well together with Rainbow CSV and provide additional functionality e.g. export to Excel format: +* [Excel Viewer](https://marketplace.visualstudio.com/items?itemName=GrapeCity.gc-excelviewer) +* [Edit CSV](https://marketplace.visualstudio.com/items?itemName=janisdd.vscode-edit-csv) +* [Data Preview](https://marketplace.visualstudio.com/items?itemName=RandomFractalsInc.vscode-data-preview) + + +#### Rainbow CSV and similar plugins in other editors: + +* Rainbow CSV extension in [Vim](https://github.com/mechatroner/rainbow_csv) +* rainbow-csv package in [Atom](https://atom.io/packages/rainbow-csv) +* rainbow_csv plugin in [Sublime Text](https://packagecontrol.io/packages/rainbow_csv) +* rainbow_csv plugin in [gedit](https://github.com/mechatroner/gtk_gedit_rainbow_csv) - doesn't support quoted commas in csv +* rainbow_csv_4_nedit in [NEdit](https://github.com/DmitTrix/rainbow_csv_4_nedit) +* CSV highlighting in [Nano](https://github.com/scopatz/nanorc) +* Rainbow CSV in [IntelliJ IDEA](https://plugins.jetbrains.com/plugin/12896-rainbow-csv/) + +#### RBQL +* [RBQL](https://github.com/mechatroner/RBQL) +* Library and CLI App for Python [RBQL](https://pypi.org/project/rbql/) +* Library and CLI App for JavaScript [RBQL](https://www.npmjs.com/package/rbql) + diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/contrib/textarea-caret-position/LICENSE b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/contrib/textarea-caret-position/LICENSE new file mode 100644 index 00000000..f29f4b44 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/contrib/textarea-caret-position/LICENSE @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2015 Jonathan Ong me@jongleberry.com + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/contrib/textarea-caret-position/index.js b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/contrib/textarea-caret-position/index.js new file mode 100644 index 00000000..7ce57686 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/contrib/textarea-caret-position/index.js @@ -0,0 +1,155 @@ +/* jshint browser: true */ + +(function () { + +// We'll copy the properties below into the mirror div. +// Note that some browsers, such as Firefox, do not concatenate properties +// into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), +// so we have to list every single property explicitly. +var properties = [ + 'direction', // RTL support + 'boxSizing', + 'width', // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does + 'height', + 'overflowX', + 'overflowY', // copy the scrollbar for IE + + 'borderTopWidth', + 'borderRightWidth', + 'borderBottomWidth', + 'borderLeftWidth', + 'borderStyle', + + 'paddingTop', + 'paddingRight', + 'paddingBottom', + 'paddingLeft', + + // https://developer.mozilla.org/en-US/docs/Web/CSS/font + 'fontStyle', + 'fontVariant', + 'fontWeight', + 'fontStretch', + 'fontSize', + 'fontSizeAdjust', + 'lineHeight', + 'fontFamily', + + 'textAlign', + 'textTransform', + 'textIndent', + 'textDecoration', // might not make a difference, but better be safe + + 'letterSpacing', + 'wordSpacing', + + 'tabSize', + 'MozTabSize' + +]; + +var isBrowser = (typeof window !== 'undefined'); +var isFirefox = (isBrowser && window.mozInnerScreenX != null); + +function getCaretCoordinates(element, position, options) { + if (!isBrowser) { + throw new Error('textarea-caret-position#getCaretCoordinates should only be called in a browser'); + } + + var debug = options && options.debug || false; + if (debug) { + var el = document.querySelector('#input-textarea-caret-position-mirror-div'); + if (el) el.parentNode.removeChild(el); + } + + // The mirror div will replicate the textarea's style + var div = document.createElement('div'); + div.id = 'input-textarea-caret-position-mirror-div'; + document.body.appendChild(div); + + var style = div.style; + var computed = window.getComputedStyle ? window.getComputedStyle(element) : element.currentStyle; // currentStyle for IE < 9 + var isInput = element.nodeName === 'INPUT'; + + // Default textarea styles + style.whiteSpace = 'pre-wrap'; + if (!isInput) + style.wordWrap = 'break-word'; // only for textarea-s + + // Position off-screen + style.position = 'absolute'; // required to return coordinates properly + if (!debug) + style.visibility = 'hidden'; // not 'display: none' because we want rendering + + // Transfer the element's properties to the div + properties.forEach(function (prop) { + if (isInput && prop === 'lineHeight') { + // Special case for s because text is rendered centered and line height may be != height + if (computed.boxSizing === "border-box") { + var height = parseInt(computed.height); + var outerHeight = + parseInt(computed.paddingTop) + + parseInt(computed.paddingBottom) + + parseInt(computed.borderTopWidth) + + parseInt(computed.borderBottomWidth); + var targetHeight = outerHeight + parseInt(computed.lineHeight); + if (height > targetHeight) { + style.lineHeight = height - outerHeight + "px"; + } else if (height === targetHeight) { + style.lineHeight = computed.lineHeight; + } else { + style.lineHeight = 0; + } + } else { + style.lineHeight = computed.height; + } + } else { + style[prop] = computed[prop]; + } + }); + + if (isFirefox) { + // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 + if (element.scrollHeight > parseInt(computed.height)) + style.overflowY = 'scroll'; + } else { + style.overflow = 'hidden'; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' + } + + div.textContent = element.value.substring(0, position); + // The second special handling for input type="text" vs textarea: + // spaces need to be replaced with non-breaking spaces - http://stackoverflow.com/a/13402035/1269037 + if (isInput) + div.textContent = div.textContent.replace(/\s/g, '\u00a0'); + + var span = document.createElement('span'); + // Wrapping must be replicated *exactly*, including when a long word gets + // onto the next line, with whitespace at the end of the line before (#7). + // The *only* reliable way to do that is to copy the *entire* rest of the + // textarea's content into the created at the caret position. + // For inputs, just '.' would be enough, but no need to bother. + span.textContent = element.value.substring(position) || '.'; // || because a completely empty faux span doesn't render at all + div.appendChild(span); + + var coordinates = { + top: span.offsetTop + parseInt(computed['borderTopWidth']), + left: span.offsetLeft + parseInt(computed['borderLeftWidth']), + height: parseInt(computed['lineHeight']) + }; + + if (debug) { + span.style.backgroundColor = '#aaa'; + } else { + document.body.removeChild(div); + } + + return coordinates; +} + +if (typeof module != 'undefined' && typeof module.exports != 'undefined') { + module.exports = getCaretCoordinates; +} else if(isBrowser) { + window.getCaretCoordinates = getCaretCoordinates; +} + +}()); diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/dist/web/extension.js b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/dist/web/extension.js new file mode 100644 index 00000000..e5623b0b --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/dist/web/extension.js @@ -0,0 +1 @@ +(()=>{var __webpack_modules__={1924:(e,t,r)=>{"use strict";var n=r(210),i=r(5559),o=i(n("String.prototype.indexOf"));e.exports=function(e,t){var r=n(e,!!t);return"function"==typeof r&&o(e,".prototype.")>-1?i(r):r}},5559:(e,t,r)=>{"use strict";var n=r(8612),i=r(210),o=i("%Function.prototype.apply%"),s=i("%Function.prototype.call%"),a=i("%Reflect.apply%",!0)||n.call(s,o),l=i("%Object.getOwnPropertyDescriptor%",!0),u=i("%Object.defineProperty%",!0),c=i("%Math.max%");if(u)try{u({},"a",{value:1})}catch(e){u=null}e.exports=function(e){var t=a(n,s,arguments);if(l&&u){var r=l(t,"length");r.configurable&&u(t,"length",{value:1+c(0,e.length-(arguments.length-1))})}return t};var _=function(){return a(n,o,arguments)};u?u(e.exports,"apply",{value:_}):e.exports.apply=_},9804:e=>{var t=Object.prototype.hasOwnProperty,r=Object.prototype.toString;e.exports=function(e,n,i){if("[object Function]"!==r.call(n))throw new TypeError("iterator must be a function");var o=e.length;if(o===+o)for(var s=0;s{"use strict";var t="Function.prototype.bind called on incompatible ",r=Array.prototype.slice,n=Object.prototype.toString,i="[object Function]";e.exports=function(e){var o=this;if("function"!=typeof o||n.call(o)!==i)throw new TypeError(t+o);for(var s,a=r.call(arguments,1),l=function(){if(this instanceof s){var t=o.apply(this,a.concat(r.call(arguments)));return Object(t)===t?t:this}return o.apply(e,a.concat(r.call(arguments)))},u=Math.max(0,o.length-a.length),c=[],_=0;_{"use strict";var n=r(7648);e.exports=Function.prototype.bind||n},210:(e,t,r)=>{"use strict";var n,i=SyntaxError,o=Function,s=TypeError,a=function(e){try{return o('"use strict"; return ('+e+").constructor;")()}catch(e){}},l=Object.getOwnPropertyDescriptor;if(l)try{l({},"")}catch(e){l=null}var u=function(){throw new s},c=l?function(){try{return u}catch(e){try{return l(arguments,"callee").get}catch(e){return u}}}():u,_=r(1405)(),p=Object.getPrototypeOf||function(e){return e.__proto__},f={},h="undefined"==typeof Uint8Array?n:p(Uint8Array),d={"%AggregateError%":"undefined"==typeof AggregateError?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?n:ArrayBuffer,"%ArrayIteratorPrototype%":_?p([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":f,"%AsyncGenerator%":f,"%AsyncGeneratorFunction%":f,"%AsyncIteratorPrototype%":f,"%Atomics%":"undefined"==typeof Atomics?n:Atomics,"%BigInt%":"undefined"==typeof BigInt?n:BigInt,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?n:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?n:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?n:FinalizationRegistry,"%Function%":o,"%GeneratorFunction%":f,"%Int8Array%":"undefined"==typeof Int8Array?n:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?n:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":_?p(p([][Symbol.iterator]())):n,"%JSON%":"object"==typeof JSON?JSON:n,"%Map%":"undefined"==typeof Map?n:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&_?p((new Map)[Symbol.iterator]()):n,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?n:Promise,"%Proxy%":"undefined"==typeof Proxy?n:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?n:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?n:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&_?p((new Set)[Symbol.iterator]()):n,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":_?p(""[Symbol.iterator]()):n,"%Symbol%":_?Symbol:n,"%SyntaxError%":i,"%ThrowTypeError%":c,"%TypedArray%":h,"%TypeError%":s,"%Uint8Array%":"undefined"==typeof Uint8Array?n:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?n:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?n:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?n:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?n:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?n:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?n:WeakSet},g=function e(t){var r;if("%AsyncFunction%"===t)r=a("async function () {}");else if("%GeneratorFunction%"===t)r=a("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=a("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&(r=p(i.prototype))}return d[t]=r,r},y={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},m=r(8612),b=r(7642),w=m.call(Function.call,Array.prototype.concat),x=m.call(Function.apply,Array.prototype.splice),v=m.call(Function.call,String.prototype.replace),E=m.call(Function.call,String.prototype.slice),O=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,S=/\\(\\)?/g,R=function(e){var t=E(e,0,1),r=E(e,-1);if("%"===t&&"%"!==r)throw new i("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new i("invalid intrinsic syntax, expected opening `%`");var n=[];return v(e,O,(function(e,t,r,i){n[n.length]=r?v(i,S,"$1"):t||e})),n},A=function(e,t){var r,n=e;if(b(y,n)&&(n="%"+(r=y[n])[0]+"%"),b(d,n)){var o=d[n];if(o===f&&(o=g(n)),void 0===o&&!t)throw new s("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:o}}throw new i("intrinsic "+e+" does not exist!")};e.exports=function(e,t){if("string"!=typeof e||0===e.length)throw new s("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new s('"allowMissing" argument must be a boolean');var r=R(e),n=r.length>0?r[0]:"",o=A("%"+n+"%",t),a=o.name,u=o.value,c=!1,_=o.alias;_&&(n=_[0],x(r,w([0,1],_)));for(var p=1,f=!0;p=r.length){var m=l(u,h);u=(f=!!m)&&"get"in m&&!("originalValue"in m.get)?m.get:u[h]}else f=b(u,h),u=u[h];f&&!c&&(d[a]=u)}}return u}},1405:(e,t,r)=>{"use strict";var n="undefined"!=typeof Symbol&&Symbol,i=r(5419);e.exports=function(){return"function"==typeof n&&"function"==typeof Symbol&&"symbol"==typeof n("foo")&&"symbol"==typeof Symbol("bar")&&i()}},5419:e=>{"use strict";e.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var n=Object.getOwnPropertySymbols(e);if(1!==n.length||n[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var i=Object.getOwnPropertyDescriptor(e,t);if(42!==i.value||!0!==i.enumerable)return!1}return!0}},6410:(e,t,r)=>{"use strict";var n=r(5419);e.exports=function(){return n()&&!!Symbol.toStringTag}},7642:(e,t,r)=>{"use strict";var n=r(8612);e.exports=n.call(Function.call,Object.prototype.hasOwnProperty)},5717:e=>{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},2584:(e,t,r)=>{"use strict";var n=r(6410)(),i=r(1924)("Object.prototype.toString"),o=function(e){return!(n&&e&&"object"==typeof e&&Symbol.toStringTag in e)&&"[object Arguments]"===i(e)},s=function(e){return!!o(e)||null!==e&&"object"==typeof e&&"number"==typeof e.length&&e.length>=0&&"[object Array]"!==i(e)&&"[object Function]"===i(e.callee)},a=function(){return o(arguments)}();o.isLegacyArguments=s,e.exports=a?o:s},8662:(e,t,r)=>{"use strict";var n,i=Object.prototype.toString,o=Function.prototype.toString,s=/^\s*(?:function)?\*/,a=r(6410)(),l=Object.getPrototypeOf;e.exports=function(e){if("function"!=typeof e)return!1;if(s.test(o.call(e)))return!0;if(!a)return"[object GeneratorFunction]"===i.call(e);if(!l)return!1;if(void 0===n){var t=function(){if(!a)return!1;try{return Function("return function*() {}")()}catch(e){}}();n=!!t&&l(t)}return l(e)===n}},5692:(e,t,r)=>{"use strict";var n=r(9804),i=r(3083),o=r(1924),s=o("Object.prototype.toString"),a=r(6410)(),l="undefined"==typeof globalThis?r.g:globalThis,u=i(),c=o("Array.prototype.indexOf",!0)||function(e,t){for(var r=0;r-1}return!!f&&function(e){var t=!1;return n(p,(function(r,n){if(!t)try{t=r.call(e)===n}catch(e){}})),t}(e)}},4155:e=>{var t,r,n=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function s(e){if(t===setTimeout)return setTimeout(e,0);if((t===i||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:i}catch(e){t=i}try{r="function"==typeof clearTimeout?clearTimeout:o}catch(e){r=o}}();var a,l=[],u=!1,c=-1;function _(){u&&a&&(u=!1,a.length?l=a.concat(l):c=-1,l.length&&p())}function p(){if(!u){var e=s(_);u=!0;for(var t=l.length;t;){for(a=l,l=[];++c1)for(var r=1;r{e.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},5955:(e,t,r)=>{"use strict";var n=r(2584),i=r(8662),o=r(6430),s=r(5692);function a(e){return e.call.bind(e)}var l="undefined"!=typeof BigInt,u="undefined"!=typeof Symbol,c=a(Object.prototype.toString),_=a(Number.prototype.valueOf),p=a(String.prototype.valueOf),f=a(Boolean.prototype.valueOf);if(l)var h=a(BigInt.prototype.valueOf);if(u)var d=a(Symbol.prototype.valueOf);function g(e,t){if("object"!=typeof e)return!1;try{return t(e),!0}catch(e){return!1}}function y(e){return"[object Map]"===c(e)}function m(e){return"[object Set]"===c(e)}function b(e){return"[object WeakMap]"===c(e)}function w(e){return"[object WeakSet]"===c(e)}function x(e){return"[object ArrayBuffer]"===c(e)}function v(e){return"undefined"!=typeof ArrayBuffer&&(x.working?x(e):e instanceof ArrayBuffer)}function E(e){return"[object DataView]"===c(e)}function O(e){return"undefined"!=typeof DataView&&(E.working?E(e):e instanceof DataView)}t.isArgumentsObject=n,t.isGeneratorFunction=i,t.isTypedArray=s,t.isPromise=function(e){return"undefined"!=typeof Promise&&e instanceof Promise||null!==e&&"object"==typeof e&&"function"==typeof e.then&&"function"==typeof e.catch},t.isArrayBufferView=function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):s(e)||O(e)},t.isUint8Array=function(e){return"Uint8Array"===o(e)},t.isUint8ClampedArray=function(e){return"Uint8ClampedArray"===o(e)},t.isUint16Array=function(e){return"Uint16Array"===o(e)},t.isUint32Array=function(e){return"Uint32Array"===o(e)},t.isInt8Array=function(e){return"Int8Array"===o(e)},t.isInt16Array=function(e){return"Int16Array"===o(e)},t.isInt32Array=function(e){return"Int32Array"===o(e)},t.isFloat32Array=function(e){return"Float32Array"===o(e)},t.isFloat64Array=function(e){return"Float64Array"===o(e)},t.isBigInt64Array=function(e){return"BigInt64Array"===o(e)},t.isBigUint64Array=function(e){return"BigUint64Array"===o(e)},y.working="undefined"!=typeof Map&&y(new Map),t.isMap=function(e){return"undefined"!=typeof Map&&(y.working?y(e):e instanceof Map)},m.working="undefined"!=typeof Set&&m(new Set),t.isSet=function(e){return"undefined"!=typeof Set&&(m.working?m(e):e instanceof Set)},b.working="undefined"!=typeof WeakMap&&b(new WeakMap),t.isWeakMap=function(e){return"undefined"!=typeof WeakMap&&(b.working?b(e):e instanceof WeakMap)},w.working="undefined"!=typeof WeakSet&&w(new WeakSet),t.isWeakSet=function(e){return w(e)},x.working="undefined"!=typeof ArrayBuffer&&x(new ArrayBuffer),t.isArrayBuffer=v,E.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&E(new DataView(new ArrayBuffer(1),0,1)),t.isDataView=O;var S="undefined"!=typeof SharedArrayBuffer?SharedArrayBuffer:void 0;function R(e){return"[object SharedArrayBuffer]"===c(e)}function A(e){return void 0!==S&&(void 0===R.working&&(R.working=R(new S)),R.working?R(e):e instanceof S)}function q(e){return g(e,_)}function P(e){return g(e,p)}function j(e){return g(e,f)}function T(e){return l&&g(e,h)}function k(e){return u&&g(e,d)}t.isSharedArrayBuffer=A,t.isAsyncFunction=function(e){return"[object AsyncFunction]"===c(e)},t.isMapIterator=function(e){return"[object Map Iterator]"===c(e)},t.isSetIterator=function(e){return"[object Set Iterator]"===c(e)},t.isGeneratorObject=function(e){return"[object Generator]"===c(e)},t.isWebAssemblyCompiledModule=function(e){return"[object WebAssembly.Module]"===c(e)},t.isNumberObject=q,t.isStringObject=P,t.isBooleanObject=j,t.isBigIntObject=T,t.isSymbolObject=k,t.isBoxedPrimitive=function(e){return q(e)||P(e)||j(e)||T(e)||k(e)},t.isAnyArrayBuffer=function(e){return"undefined"!=typeof Uint8Array&&(v(e)||A(e))},["isProxy","isExternal","isModuleNamespaceObject"].forEach((function(e){Object.defineProperty(t,e,{enumerable:!1,value:function(){throw new Error(e+" is not supported in userland")}})}))},9539:(e,t,r)=>{var n=r(4155),i=Object.getOwnPropertyDescriptors||function(e){for(var t=Object.keys(e),r={},n=0;n=i)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}})),a=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),g(r)?n.showHidden=r:r&&t._extend(n,r),w(n.showHidden)&&(n.showHidden=!1),w(n.depth)&&(n.depth=2),w(n.colors)&&(n.colors=!1),w(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=c),p(n,e,n.depth)}function c(e,t){var r=u.styles[t];return r?"["+u.colors[r][0]+"m"+e+"["+u.colors[r][1]+"m":e}function _(e,t){return e}function p(e,r,n){if(e.customInspect&&r&&S(r.inspect)&&r.inspect!==t.inspect&&(!r.constructor||r.constructor.prototype!==r)){var i=r.inspect(n,e);return b(i)||(i=p(e,i,n)),i}var o=function(e,t){if(w(t))return e.stylize("undefined","undefined");if(b(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}return m(t)?e.stylize(""+t,"number"):g(t)?e.stylize(""+t,"boolean"):y(t)?e.stylize("null","null"):void 0}(e,r);if(o)return o;var s=Object.keys(r),a=function(e){var t={};return e.forEach((function(e,r){t[e]=!0})),t}(s);if(e.showHidden&&(s=Object.getOwnPropertyNames(r)),O(r)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return f(r);if(0===s.length){if(S(r)){var l=r.name?": "+r.name:"";return e.stylize("[Function"+l+"]","special")}if(x(r))return e.stylize(RegExp.prototype.toString.call(r),"regexp");if(E(r))return e.stylize(Date.prototype.toString.call(r),"date");if(O(r))return f(r)}var u,c="",_=!1,v=["{","}"];return d(r)&&(_=!0,v=["[","]"]),S(r)&&(c=" [Function"+(r.name?": "+r.name:"")+"]"),x(r)&&(c=" "+RegExp.prototype.toString.call(r)),E(r)&&(c=" "+Date.prototype.toUTCString.call(r)),O(r)&&(c=" "+f(r)),0!==s.length||_&&0!=r.length?n<0?x(r)?e.stylize(RegExp.prototype.toString.call(r),"regexp"):e.stylize("[Object]","special"):(e.seen.push(r),u=_?function(e,t,r,n,i){for(var o=[],s=0,a=t.length;s60?r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1]:r[0]+t+" "+e.join(", ")+" "+r[1]}(u,c,v)):v[0]+c+v[1]}function f(e){return"["+Error.prototype.toString.call(e)+"]"}function h(e,t,r,n,i,o){var s,a,l;if((l=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?a=l.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):l.set&&(a=e.stylize("[Setter]","special")),j(n,i)||(s="["+i+"]"),a||(e.seen.indexOf(l.value)<0?(a=y(r)?p(e,l.value,null):p(e,l.value,r-1)).indexOf("\n")>-1&&(a=o?a.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+a.split("\n").map((function(e){return" "+e})).join("\n")):a=e.stylize("[Circular]","special")),w(s)){if(o&&i.match(/^\d+$/))return a;(s=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(s=s.substr(1,s.length-2),s=e.stylize(s,"name")):(s=s.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),s=e.stylize(s,"string"))}return s+": "+a}function d(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function y(e){return null===e}function m(e){return"number"==typeof e}function b(e){return"string"==typeof e}function w(e){return void 0===e}function x(e){return v(e)&&"[object RegExp]"===R(e)}function v(e){return"object"==typeof e&&null!==e}function E(e){return v(e)&&"[object Date]"===R(e)}function O(e){return v(e)&&("[object Error]"===R(e)||e instanceof Error)}function S(e){return"function"==typeof e}function R(e){return Object.prototype.toString.call(e)}function A(e){return e<10?"0"+e.toString(10):e.toString(10)}t.debuglog=function(e){if(e=e.toUpperCase(),!s[e])if(a.test(e)){var r=n.pid;s[e]=function(){var n=t.format.apply(t,arguments);console.error("%s %d: %s",e,r,n)}}else s[e]=function(){};return s[e]},t.inspect=u,u.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},u.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},t.types=r(5955),t.isArray=d,t.isBoolean=g,t.isNull=y,t.isNullOrUndefined=function(e){return null==e},t.isNumber=m,t.isString=b,t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=w,t.isRegExp=x,t.types.isRegExp=x,t.isObject=v,t.isDate=E,t.types.isDate=E,t.isError=O,t.types.isNativeError=O,t.isFunction=S,t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=r(384);var q=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function P(){var e=new Date,t=[A(e.getHours()),A(e.getMinutes()),A(e.getSeconds())].join(":");return[e.getDate(),q[e.getMonth()],t].join(" ")}function j(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.log=function(){console.log("%s - %s",P(),t.format.apply(t,arguments))},t.inherits=r(5717),t._extend=function(e,t){if(!t||!v(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e};var T="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function k(e,t){if(!e){var r=new Error("Promise was rejected with a falsy value");r.reason=e,e=r}return t(e)}t.promisify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');if(T&&e[T]){var t;if("function"!=typeof(t=e[T]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(t,T,{value:t,enumerable:!1,writable:!1,configurable:!0}),t}function t(){for(var t,r,n=new Promise((function(e,n){t=e,r=n})),i=[],o=0;o{"use strict";var n=r(9804),i=r(3083),o=r(1924),s=o("Object.prototype.toString"),a=r(6410)(),l="undefined"==typeof globalThis?r.g:globalThis,u=i(),c=o("String.prototype.slice"),_={},p=r(882),f=Object.getPrototypeOf;a&&p&&f&&n(u,(function(e){if("function"==typeof l[e]){var t=new l[e];if(Symbol.toStringTag in t){var r=f(t),n=p(r,Symbol.toStringTag);if(!n){var i=f(r);n=p(i,Symbol.toStringTag)}_[e]=n.get}}}));var h=r(5692);e.exports=function(e){return!!h(e)&&(a&&Symbol.toStringTag in e?function(e){var t=!1;return n(_,(function(r,n){if(!t)try{var i=r.call(e);i===n&&(t=i)}catch(e){}})),t}(e):c(s(e),8,-1))}},45:(e,t,r)=>{var n=r(4155);const i=r(4949),o=r(5174),s=r(7857),a=r(6987),l=r(371),u=r(8594),c=/^([0-9]+)(\.[0-9]+)?$/;class _ extends Error{}function p(e,t,r){if(e.length>r[0]&&(r[0]=e.length),-1==r[1])return;let n=c.exec(e);if(null===n)return void(!t&&e.length&&(r[1]=-1,r[2]=-1));let i=n[1].length;r[1]=Math.max(r[1],i);let o=void 0===n[2]?0:n[2].length;r[2]=Math.max(r[2],o)}function f(e,t,r,n){if(e=e.trim(),-1==r[1]){let t=Math.max(r[0]-e.length,0);return n?e:e+" ".repeat(t+1)}if(t&&null===c.exec(e)){let t=Math.max(r[0]-e.length,0);return n?e:e+" ".repeat(t+1)}let i=e.indexOf("."),o=-1==i?e.length:i,s=-1==i?0:e.length-i,a=Math.max(r[1]-o,0),l=Math.max(r[2]-s),u=n?"":" ".repeat(l+1);return" ".repeat(a)+e+u}function h(e){return"rbql_table_name:"+e}function d(e,t,r){var n,a="~"===(n=r).charAt(0)?s.join(i.homedir(),n.slice(1)):n;if(o.existsSync(a))return a;if(t&&!s.isAbsolute(a)&&(a=s.join(t,a),o.existsSync(a)))return a;let l=e?e.get(h(r)):null;return l&&o.existsSync(l)?l:null}function g(e,t){const r=e.lineCount;for(let n=0;n1&&e.push(function(e,t){let r=Object.keys(t),n=[];for(let e=0;e1);let[i,o]=n[0],[s,a]=n[1],l=`Number of fields in "${e}" table is not consistent: `;return l+=`e.g. record ${i} -> ${o} fields, record ${s} -> ${a} fields`,l}(this.table_name,this.fields_info)),e}}class b extends a.RBQLOutputWriter{constructor(e,t){if(super(),this.delim=e,this.policy=t,this.header_len=null,this.null_in_output=!1,this.delim_in_simple_output=!1,this.output_lines=[],"simple"==t)this.polymorphic_join=this.simple_join;else if("quoted"==t)this.polymorphic_join=this.quoted_join;else if("quoted_rfc"==t)this.polymorphic_join=this.quoted_join_rfc;else if("monocolumn"==t)this.polymorphic_join=this.mono_join;else{if("whitespace"!=t)throw new y("Unknown output csv policy");this.polymorphic_join=this.simple_join}}set_header(e){null!==e&&(this.header_len=e.length,this.write(e))}quoted_join(e){let t=this.delim;return e.map((function(e){return u.quote_field(String(e),t)})).join(this.delim)}quoted_join_rfc(e){let t=this.delim;return e.map((function(e){return u.rfc_quote_field(String(e),t)})).join(this.delim)}mono_join(e){if(e.length>1)throw new y('Unable to use "Monocolumn" output format: some records have more than one field');return e[0]}simple_join(e){var t=e.join(this.delim);return-1!=e.join("").indexOf(this.delim)&&(this.delim_in_simple_output=!0),t}normalize_fields(e){for(var t=0;t{i||(i=!0,n.close(),s(e))})),n.on("error",(e=>{a(e)})),l},e.exports.rbql_query_web=async function(e,t,r,n,i,o,s,l,u=null){let c=new w,_=new m(t,r,n,l,u),p=new b(i,o);return await a.query(e,_,p,s,c,""),p.output_lines},e.exports.rbql_query_node=async function(e,t,r,u,c,_,p,f,h,d,g=!1,m=null,b="",w=null){let v=null,E=null;w&&w.bulk_read&&r?E=r:v=null===r?n.stdin:o.createReadStream(r);let[O,S]=null===_?[n.stdout,!1]:[o.createWriteStream(_),!0];if('"'==u&&"quoted"==c)throw new y('Double quote delimiter is incompatible with "quoted" policy');if("latin-1"==h&&(h="binary"),!l.is_ascii(t)&&"binary"==h)throw new y("To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary");if(!(l.is_ascii(u)&&l.is_ascii(p)||"binary"!=h))throw new y("To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary");let R=s.join(i.homedir(),".rbql_init_source.js");""==b&&o.existsSync(R)&&(b=l.read_user_init_code(R));let A=r?s.dirname(r):null,q=new x(e,A,u,c,h,g,m,w),P=new l.CSVRecordIterator(v,E,h,u,c,g,m),j=new l.CSVWriter(O,S,h,p,f);await a.query(t,P,j,d,q,b),q.get_warnings(d)},e.exports.get_header_line=g,e.exports.populate_optimistic_rfc_csv_record_map=function(e,t,r,n=null){let i=e.lineCount,o=null;var s;for(let a=r.length?(s=r,s[s.length-1])[1]:0;a=i&&""==t)break;if(n&&t.startsWith(n))continue;let s=t.match(/"/g),l=s&&s.length%2==1;if(null!==o||l)if(null===o&&l)o=a;else{if(!l)continue;r.push([o,a+1]),o=null}else r.push([a,a+1])}null!==o&&r.push([o,i])},e.exports.get_default_js_udf_content=function(){return"// This file can be used to store RBQL UDFs. Example:\n //\n // function foo(value) {\n // return 'foo ' + String(value.length);\n // }\n // \n // Functions defined in this file can be used in RBQL queries e.g. \n // SELECT foo(a1), a2 WHERE foo(a3) != 'foo 5' LIMIT 10\n //\n // Don't forget to save this file after editing!\n //\n // Write your own functions bellow this line:\n ".replace(new RegExp(/^ */,"mg"),"")},e.exports.get_default_python_udf_content=function(){return"# This file can be used to store RBQL UDFs. Example:\n #\n # def foo(value):\n # return 'foo ' + str(len(value))\n # \n # \n # Functions defined in this file can be used in RBQL queries e.g. \n # SELECT foo(a1), a2 WHERE foo(a3) != 'foo 5' LIMIT 10\n #\n # Don't forget to save this file after editing!\n #\n # Write your own functions bellow this line:\n ".replace(new RegExp(/^ */,"mg"),"")},e.exports.align_columns=function(e,t,r,n,i){let o=[],s=e.lineCount,a=!1,l=!0;for(let c=0;c=i.length);e++){let t=e+1==i.length,r=f(p[e],l,i[e],t);p[e]!=r&&(p[e]=r,a=!0)}l=!1,o.push(p.join(t))}return a?o.join("\n"):null},e.exports.shrink_columns=function(e,t,r,n){let i=[],o=e.lineCount,s=!1;for(let a=0;a0&&(r[1]+r[2]>r[0]&&(r[0]=r[1]+r[2]),r[0]-r[2]>r[1]&&(r[1]=r[0]-r[2]),r[0]!=r[1]+r[2]))return null;t.push(r)}return t},e.exports.update_subcomponent_stats=p,e.exports.align_field=f},8594:e=>{let t=new RegExp('^"((?:[^"]*"")*[^"]*)"'),r=new RegExp('^ *"((?:[^"]*"")*[^"]*)" *');function n(e,n,i,o,s,a){var l=!1;let u=e.substring(s),c=(o?r:t).exec(u);if(null!==c){let t=c[0].length;if(s+t==e.length||e[s+t]==n)return i?a.push(c[0]):a.push(c[1].replace(/""/g,'"')),[s+t+1,!1];l=!0}var _=e.indexOf(n,s);-1==_&&(_=e.length);var p=e.substring(s,_);return l=l||-1!=p.indexOf('"'),a.push(p),[_+1,l]}function i(e,t,r=!1){if(-1==e.indexOf('"'))return[e.split(t),!1];var i=[],o=0,s=!1;let a=" "!=t;for(;o{(function(exports){class RbqlParsingError extends Error{}class RbqlRuntimeError extends Error{}class AssertionError extends Error{}class RbqlIOHandlingError extends Error{}class InternalBadFieldError extends Error{constructor(e,...t){super(...t),this.bad_idx=e}}function assert(e,t=null){if(!e)throw t||(t="Assertion error"),new AssertionError(t)}function replace_all(e,t,r){return e.split(t).join(r)}class RBQLContext{constructor(e,t,r,n){this.query_text=e,this.input_iterator=t,this.writer=r,this.user_init_code=n,this.unnest_list=null,this.top_count=null,this.like_regex_cache=new Map,this.sort_key_expression=null,this.aggregation_stage=0,this.aggregation_key_expression=null,this.functional_aggregators=[],this.join_map_impl=null,this.join_map=null,this.lhs_join_var_expression=null,this.where_expression=null,this.select_expression=null,this.update_expressions=null,this.variables_init_code=null}}var query_context=null;const wrong_aggregation_usage_error="Usage of RBQL aggregation functions inside JavaScript expressions is not allowed, see the docs",RBQL_VERSION="0.25.0";function check_if_brackets_match(e,t){return"["==e&&"]"==t||"("==e&&")"==t||"{"==e&&"}"==t}function parse_root_bracket_level_text_spans(e){let t=[],r=0,n=[];for(let i=0;ie.trim())),t}function unquote_string(e){return!e||e.length<2?null:"'"==e[0]&&"'"==e[e.length-1]?e.substring(1,e.length-1).replace(/\\'/g,"'").replace(/\\\\/g,"\\"):'"'==e[0]&&'"'==e[e.length-1]?e.substring(1,e.length-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"):null}function column_info_from_text_span(e,t){e=e.trim();let r="__RBQL_INTERNAL_STAR",n=/^[_a-zA-Z][_a-zA-Z0-9]*$/.exec(e),i=/^([ab])\.([_a-zA-Z][_a-zA-Z0-9]*)$/.exec(e),o=/^([ab])\[([0-9]+)\]$/.exec(e),s=/^([ab])\[___RBQL_STRING_LITERAL([0-9]+)___\]$/.exec(e);if(null!==n){if(e==r)return{table_name:null,column_index:null,column_name:null,is_star:!0};if(e.startsWith("___RBQL_STRING_LITERAL"))return null;let t=/^([ab])([0-9]+)$/.exec(e);return null!==t?{table_name:t[1],column_index:parseInt(t[2])-1,column_name:null,is_star:!1}:{table_name:null,column_index:null,column_name:e,is_star:!1}}if(null!==i){let e=i[1],t=i[2];return t==r?{table_name:e,column_index:null,column_name:null,is_star:!0}:{table_name:null,column_index:null,column_name:t,is_star:!1}}if(null!=o)return{table_name:o[1],column_index:parseInt(o[2])-1,column_name:null,is_star:!1};if(null!=s){s[1];let e=s[2];if(ecolumn_info_from_text_span(e,t)))}function stable_compare(e,t){for(var r=0;r=this.top_count||(await this.subwriter.write(e),this.NW+=1,0))}async finish(){await this.subwriter.finish()}}class UniqWriter{constructor(e){this.subwriter=e,this.seen=new Set}async write(e){return!add_to_set(this.seen,JSON.stringify(e))||!!await this.subwriter.write(e)}async finish(){await this.subwriter.finish()}}class UniqCountWriter{constructor(e){this.subwriter=e,this.records=new Map}async write(e){var t=JSON.stringify(e),r=this.records.get(t);return r?r[0]+=1:this.records.set(t,[1,e]),!0}async finish(){for(var[e,t]of this.records){let[e,r]=t;if(r.unshift(e),!await this.subwriter.write(r))break}await this.subwriter.finish()}}class SortedWriter{constructor(e,t){this.subwriter=e,this.reverse_sort=t,this.unsorted_entries=[]}async write(e){return this.unsorted_entries.push(e),!0}async finish(){var e=this.unsorted_entries;e.sort(stable_compare),this.reverse_sort&&e.reverse();for(var t=0;te instanceof UnnestMarker));for(var o=0;oo+e)),n.slice(0,e).concat(i).concat(n.slice(e+1)).join("\n")+"\n"}assert(!1)}function generate_main_loop_code(e){let t=null!==e.select_expression,r=null!==e.join_map,n=null===e.where_expression?"true":e.where_expression,i=null===e.aggregation_key_expression?"null":e.aggregation_key_expression,o=null===e.sort_key_expression?"null":e.sort_key_expression,s=embed_code(MAIN_LOOP_BODY,"__USER_INIT_CODE__",e.user_init_code);return t?(r?(s=embed_code(embed_code(s,"__CODE__",PROCESS_SELECT_JOIN),"__CODE__",PROCESS_SELECT_COMMON),s=embed_expression(s,"__RBQLMP__lhs_join_var_expression",e.lhs_join_var_expression)):s=embed_code(embed_code(s,"__CODE__",PROCESS_SELECT_SIMPLE),"__CODE__",PROCESS_SELECT_COMMON),s=embed_code(s,"__RBQLMP__variables_init_code",e.variables_init_code),s=embed_expression(s,"__RBQLMP__select_expression",e.select_expression),s=embed_expression(s,"__RBQLMP__where_expression",n),s=embed_expression(s,"__RBQLMP__aggregation_key_expression",i),s=embed_expression(s,"__RBQLMP__sort_key_expression",o)):(r?(s=embed_code(s,"__CODE__",PROCESS_UPDATE_JOIN),s=embed_expression(s,"__RBQLMP__lhs_join_var_expression",e.lhs_join_var_expression)):s=embed_code(s,"__CODE__",PROCESS_UPDATE_SIMPLE),s=embed_code(s,"__RBQLMP__variables_init_code",e.variables_init_code),s=embed_code(s,"__RBQLMP__update_expressions",e.update_expressions),s=embed_expression(s,"__RBQLMP__where_expression",n)),"(async () => {"+s+"})()"}async function compile_and_run(query_context){let main_loop_body=generate_main_loop_code(query_context);try{let main_loop_promise=eval(main_loop_body);await main_loop_promise}catch(e){if(e instanceof SyntaxError){let t=query_context.query_text.toLowerCase();if(-1!=t.indexOf(" having "))throw new SyntaxError(e.message+'\nRBQL doesn\'t support "HAVING" keyword');if(-1!=t.indexOf(" like "))throw new SyntaxError(e.message+"\nRBQL doesn't support \"LIKE\" operator, use like() function instead e.g. ... WHERE like(a1, 'foo%bar') ... ");if(-1!=t.indexOf(" from "))throw new SyntaxError(e.message+'\nTip: If input table is defined by the environment, RBQL query should not have "FROM" keyword');if(e&&e.message&&-1!=String(e.message).toLowerCase().indexOf("unexpected identifier")){if(-1!=t.indexOf(" and "))throw new SyntaxError(e.message+"\nDid you use 'and' keyword in your query?\nJavaScript backend doesn't support 'and' keyword, use '&&' operator instead!");if(-1!=t.indexOf(" or "))throw new SyntaxError(e.message+"\nDid you use 'or' keyword in your query?\nJavaScript backend doesn't support 'or' keyword, use '||' operator instead!")}}if(e&&e.message&&-1!=e.message.indexOf("Received an instance of RBQLAggregationToken"))throw new RbqlParsingError(wrong_aggregation_usage_error);throw e}}const GROUP_BY="GROUP BY",UPDATE="UPDATE",SELECT="SELECT",JOIN="JOIN",INNER_JOIN="INNER JOIN",LEFT_JOIN="LEFT JOIN",LEFT_OUTER_JOIN="LEFT OUTER JOIN",STRICT_LEFT_JOIN="STRICT LEFT JOIN",ORDER_BY="ORDER BY",WHERE="WHERE",LIMIT="LIMIT",EXCEPT="EXCEPT",WITH="WITH";function get_ambiguous_error_msg(e){return`Ambiguous variable name: "${e}" is present both in input and in join tables`}function get_all_matches(e,t){var r=[];let n=null;for(;null!==(n=e.exec(t));)r.push(n);return r}function str_strip(e){return e.replace(/^ +| +$/g,"")}function strip_comments(e){return(e=e.trim()).startsWith("//")?"":e}function combine_string_literals(e,t){for(var r=0;re[1]));for(let e of o){let o=r.indexOf(e);if(-1==o)throw new RbqlParsingError(`Unable to find column "${e}" in ${"a"==t?"input":"join"} ${n}`);i[`${t}.${e}`]={initialize:!0,index:o}}}function map_variables_directly(e,t,r){for(let n=0;n1)throw new RbqlParsingError(`More than one "${o}" statements found`);assert(1==s.length);var a=s[0],l=a[0];r.push([a.index,a.index+l.length,o]);break}}return r.sort((function(e,t){return e[0]-t[0]})),r}function separate_actions(e){e=str_strip(e);var t={};let r=/^(.*) *[Ww][Ii][Tt][Hh] *\(([a-z]{4,20})\) *$/.exec(e);null!==r&&(e=r[1],t[WITH]=r[2]);for(var n=locate_statements(e),i=0;ie-t)),[null===n?null:select_except(n,o),`select_except(record_a, [${o.join(",")}])`]}class HashJoinMap{constructor(e,t){this.max_record_len=0,this.hash_map=new Map,this.record_iterator=e,this.nr=0,1==t.length?(this.key_index=t[0],this.key_indices=null,this.polymorphic_get_key=this.get_single_key):(this.key_index=null,this.key_indices=t,this.polymorphic_get_key=this.get_multi_key)}get_single_key(e,t){if(this.key_index>=t.length)throw new RbqlRuntimeError(`No field with index ${this.key_index+1} at record ${this.nr} in "B" table`);return-1===this.key_index?this.nr:t[this.key_index]}get_multi_key(e,t){let r=[];for(let e of this.key_indices){if(e>=t.length)throw new RbqlRuntimeError(`No field with index ${e+1} at record ${this.nr} in "B" table`);r.push(-1===e?this.nr:t[e])}return JSON.stringify(r)}async build(){for(;;){let e=await this.record_iterator.get_record();if(null===e)break;this.nr+=1;let t=e.length;this.max_record_len=Math.max(this.max_record_len,t);let r=this.polymorphic_get_key(this.nr,e),n=this.hash_map.get(r);void 0===n?this.hash_map.set(r,[[this.nr,t,e]]):n.push([this.nr,t,e])}}get_join_records(e){let t=this.hash_map.get(e);return void 0===t?[]:t}get_warnings(){return this.record_iterator.get_warnings()}}function cleanup_query(e){return e.split("\n").map(strip_comments).filter((e=>e.length)).join(" ").replace(/;+$/g,"")}function remove_redundant_table_name(e){return e=str_strip(e.replace(/ +from +a(?: +|$)/gi," ")),str_strip(e.replace(/^ *update +a +set /gi,"update "))}function select_output_header(e,t,r){if(null===e&&null===t)return null;null===e&&(e=[]),null===t&&(t=[]);let n=[];for(let i of r)null===i?n.push("col"+(n.length+1)):i.is_star?null===i.table_name?n=n.concat(e).concat(t):"a"===i.table_name?n=n.concat(e):"b"===i.table_name&&(n=n.concat(t)):null!==i.column_name?n.push(i.column_name):null!==i.column_index?"a"==i.table_name&&i.column_index1);let[i,o]=n[0],[s,a]=n[1],l=`Number of fields in "${e}" table is not consistent: `;return l+=`e.g. record ${i} -> ${o} fields, record ${s} -> ${a} fields`,l}class RBQLInputIterator{constructor(){}stop(){throw new Error("Unable to call the interface method")}async get_variables_map(e){throw new Error("Unable to call the interface method")}async get_record(){throw new Error("Unable to call the interface method")}handle_query_modifier(){}get_warnings(){return[]}async get_header(){return null}}class RBQLOutputWriter{constructor(){}async write(e){throw new Error("Unable to call the interface method")}async finish(){}get_warnings(){return[]}set_header(){}}class RBQLTableRegistry{constructor(){}get_iterator_by_table_id(e){throw new Error("Unable to call the interface method")}get_warnings(){return[]}}class TableIterator extends RBQLInputIterator{constructor(e,t=null,r=!0,n="a"){super(),this.table=e,this.column_names=t,this.normalize_column_names=r,this.variable_prefix=n,this.nr=0,this.fields_info=new Object,this.stopped=!1}stop(){this.stopped=!0}async get_variables_map(e){let t=new Object;if(parse_basic_variables(e,this.variable_prefix,t),parse_array_variables(e,this.variable_prefix,t),null!==this.column_names){if(this.table.length&&this.column_names.length!=this.table[0].length)throw new RbqlIOHandlingError("List of column names and table records have different lengths");this.normalize_column_names?(parse_dictionary_variables(e,this.variable_prefix,this.column_names,t),parse_attribute_variables(e,this.variable_prefix,this.column_names,"column names list",t)):map_variables_directly(e,this.column_names,t)}return t}async get_record(){if(this.stopped)return null;if(this.nr>=this.table.length)return null;let e=this.table[this.nr];this.nr+=1;let t=e.length;return this.fields_info.hasOwnProperty(t)||(this.fields_info[t]=this.nr),e}get_warnings(){return Object.keys(this.fields_info).length>1?[make_inconsistent_num_fields_warning("input",this.fields_info)]:[]}async get_header(){return this.column_names}}class TableWriter extends RBQLOutputWriter{constructor(e){super(),this.table=e,this.header=null}async write(e){return this.table.push(e),!0}set_header(e){this.header=e}}class SingleTableRegistry extends RBQLTableRegistry{constructor(e,t=null,r=!0,n="b"){super(),this.table=e,this.table_id=n,this.column_names=t,this.normalize_column_names=r}get_iterator_by_table_id(e){if(e.toLowerCase()!==this.table_id)throw new RbqlIOHandlingError(`Unable to find join table: "${e}"`);return new TableIterator(this.table,this.column_names,this.normalize_column_names,"b")}}async function shallow_parse_input_query(e,t,r,n){e=cleanup_query(e);var[i,o]=separate_string_literals(e),s=separate_actions(i=remove_redundant_table_name(i));s.hasOwnProperty(WITH)&&t.handle_query_modifier(s[WITH]);var a=await t.get_variables_map(e);if(s.hasOwnProperty(ORDER_BY)&&s.hasOwnProperty(UPDATE))throw new RbqlParsingError('"ORDER BY" is not allowed in "UPDATE" queries');if(s.hasOwnProperty(GROUP_BY)){if(s.hasOwnProperty(ORDER_BY)||s.hasOwnProperty(UPDATE))throw new RbqlParsingError('"ORDER BY", "UPDATE" and "DISTINCT" keywords are not allowed in aggregate queries');n.aggregation_key_expression="["+combine_string_literals(s[GROUP_BY].text,o)+"]"}let l=null,u=null;if(s.hasOwnProperty(JOIN)){var[c,_]=parse_join_expression(s[JOIN].text);if(null===r)throw new RbqlParsingError("JOIN operations are not supported by the application");let t=r.get_iterator_by_table_id(c);if(!t)throw new RbqlParsingError(`Unable to find join table: "${c}"`);s.hasOwnProperty(WITH)&&t.handle_query_modifier(s[WITH]),l=await t.get_variables_map(e),u=await t.get_header();let[i,p]=resolve_join_variables(a,l,_,o),f={JOIN:InnerJoiner,"INNER JOIN":InnerJoiner,"LEFT JOIN":LeftJoiner,"LEFT OUTER JOIN":LeftJoiner,"STRICT LEFT JOIN":StrictLeftJoiner}[s[JOIN].join_subtype];n.lhs_join_var_expression=1==i.length?i[0]:"JSON.stringify(["+i.join(",")+"])",n.join_map_impl=new HashJoinMap(t,p),await n.join_map_impl.build(),n.join_map=new f(n.join_map_impl)}if(n.variables_init_code=combine_string_literals(generate_init_statements(i,a,l," ".repeat(4)),o),s.hasOwnProperty(WHERE)){var p=s[WHERE].text;if(/[^>{var n=r(4155);const i=r(1606),o=r(4704),s=r(9426),a=r(9539),l=r(6987),u=r(8594),c="Unable to decode input table as UTF-8. Use binary (latin-1) encoding instead";class _ extends Error{}class p extends Error{}function f(e,t=null){if(!e)throw t||(t="Assertion error"),new p(t)}function h(e){return/^[\x00-\x7F]*$/.test(e)}function d(e){return i.readFileSync(e,"utf-8")}function g(e,t){var r,n="~"===(r=t).charAt(0)?s.join(o.homedir(),r.slice(1)):r;if(i.existsSync(n))return n;if(e&&!s.isAbsolute(n)&&(n=s.join(e,n),i.existsSync(n)))return n;var a=function(e,t){for(var r=function(e){var t=null;try{t=i.readFileSync(e,"utf-8")}catch(e){return[]}for(var r=t.split("\n"),n=[],o=0;o1&&i.existsSync(a[1])?a[1]:null}class y{constructor(){this.push_stack=[],this.pull_stack=[]}enqueue(e){this.push_stack.push(e)}dequeue(){if(!this.pull_stack.length){if(!this.push_stack.length)return null;this.pull_stack=this.push_stack,this.pull_stack.reverse(),this.push_stack=[]}return this.pull_stack.pop()}}class m extends l.RBQLInputIterator{constructor(e,t,r,n,i,o=!1,s=null,l="input",u="a"){super(),this.stream=e,this.csv_path=t,f(null===this.stream!=(null===this.csv_path)),this.encoding=r,this.delim=n,this.policy=i,this.has_header=o,this.first_record=null,this.first_record_should_be_emitted=!o,this.header_preread_complete=!1,this.table_name=l,this.variable_prefix=u,this.comment_prefix=null!==s&&s.length?s:null,this.decoder=null,"utf-8"==r&&null===this.csv_path&&(this.decoder=new a.TextDecoder(r,{fatal:!0,stream:!0})),this.input_exhausted=!1,this.started=!1,this.utf8_bom_removed=!1,this.first_defective_line=null,this.fields_info=new Object,this.NR=0,this.NL=0,this.rfc_line_buffer=[],this.partially_decoded_line="",this.partially_decoded_line_ends_with_cr=!1,this.resolve_current_record=null,this.reject_current_record=null,this.current_exception=null,this.produced_records_queue=new y,this.process_line_polymorphic="quoted_rfc"==i?this.process_partial_rfc_record_line:this.process_record_line}handle_query_modifier(e){-1!=["header","headers"].indexOf(e)&&(this.has_header=!0,this.first_record_should_be_emitted=!1),-1!=["noheader","noheaders"].indexOf(e)&&(this.has_header=!1,this.first_record_should_be_emitted=!0)}reset_external_callbacks(){this.reject_current_record=null,this.resolve_current_record=null}try_propagate_exception(){if(this.current_exception&&this.reject_current_record){let e=this.reject_current_record,t=this.current_exception;this.reset_external_callbacks(),this.current_exception=null,e(t)}}store_or_propagate_exception(e){null===this.current_exception&&(this.current_exception=e),this.try_propagate_exception()}async preread_first_record(){this.header_preread_complete||(this.first_record=await this.get_record(),this.header_preread_complete=!0,null!==this.first_record&&(this.stream&&this.stream.pause(),this.first_record=this.first_record.slice()))}async get_variables_map(e){let t=new Object;return l.parse_basic_variables(e,this.variable_prefix,t),l.parse_array_variables(e,this.variable_prefix,t),await this.preread_first_record(),this.has_header&&this.first_record&&(l.parse_attribute_variables(e,this.variable_prefix,this.first_record,"CSV header line",t),l.parse_dictionary_variables(e,this.variable_prefix,this.first_record,t)),t}async get_header(){return await this.preread_first_record(),this.has_header?this.first_record:null}try_resolve_next_record(){if(this.try_propagate_exception(),null===this.resolve_current_record)return;let e=null;if(this.first_record_should_be_emitted&&this.header_preread_complete?(this.first_record_should_be_emitted=!1,e=this.first_record):e=this.produced_records_queue.dequeue(),null===e&&!this.input_exhausted)return;let t=this.resolve_current_record;this.reset_external_callbacks(),t(e)}async get_record(){this.started||await this.start(),this.stream&&this.stream.isPaused()&&this.stream.resume();let e=this,t=new Promise((function(t,r){e.resolve_current_record=t,e.reject_current_record=r}));return this.try_resolve_next_record(),t}async get_all_records(e=null){let t=[];for(;;){let r=await this.get_record();if(null===r)break;if(t.push(r),e&&t.length>=e){this.stop();break}}return t}process_record_line(e){if(null!==this.comment_prefix&&e.startsWith(this.comment_prefix))return;this.NR+=1;var[t,r]=u.smart_split(e,this.delim,this.policy,!1);r&&null===this.first_defective_line&&(this.first_defective_line=this.NL,"quoted_rfc"==this.policy&&this.store_or_propagate_exception(new _(`Inconsistent double quote escaping in ${this.table_name} table at record ${this.NR}, line ${this.NL}`)));let n=t.length;this.fields_info.hasOwnProperty(n)||(this.fields_info[n]=this.NR),this.produced_records_queue.enqueue(t),this.try_resolve_next_record()}process_partial_rfc_record_line(e){let t=u.accumulate_rfc_line_into_record(this.rfc_line_buffer,e,this.comment_prefix);null!==t&&this.process_record_line(t)}process_line(e){if(this.NL+=1,1===this.NL){var t=function(e,t){return"binary"==t&&e.length>=3&&239===e.charCodeAt(0)&&187===e.charCodeAt(1)&&191===e.charCodeAt(2)?e.substring(3):"utf-8"==t&&e.length>=1&&65279===e.charCodeAt(0)?e.substring(1):e}(e,this.encoding);t!=e&&(e=t,this.utf8_bom_removed=!0)}this.process_line_polymorphic(e)}process_data_stream_chunk(e){let t=null;if(this.decoder)try{t=this.decoder.decode(e)}catch(e){return void(e instanceof TypeError?this.store_or_propagate_exception(new _(c)):this.store_or_propagate_exception(e))}else t=e.toString(this.encoding);let r=t.length&&"\n"==t[0]&&this.partially_decoded_line_ends_with_cr?1:0;this.partially_decoded_line_ends_with_cr=t.length&&"\r"==t[t.length-1];let n=u.split_lines(t);n[0]=this.partially_decoded_line+n[0],f(0==r||0==n[0].length),this.partially_decoded_line=n.pop();for(let e=r;e0&&this.process_record_line(this.rfc_line_buffer.join("\n")),this.input_exhausted=!0,this.try_resolve_next_record()}process_data_stream_end(){if(this.input_exhausted=!0,this.partially_decoded_line.length){let e=this.partially_decoded_line;this.partially_decoded_line="",this.process_line(e)}this.rfc_line_buffer.length>0&&this.process_record_line(this.rfc_line_buffer.join("\n")),this.try_resolve_next_record()}stop(){this.stream&&this.stream.destroy()}async start(){if(!this.started){if(this.started=!0,!this.stream){let e=this;return new Promise((function(t,r){i.readFile(e.csv_path,((n,i)=>{n?r(n):(e.process_data_bulk(i),t())}))}))}this.stream.on("data",(e=>{this.process_data_stream_chunk(e)})),this.stream.on("end",(()=>{this.process_data_stream_end()}))}}get_warnings(){let e=[];return null!==this.first_defective_line&&e.push(`Inconsistent double quote escaping in ${this.table_name} table. E.g. at line ${this.first_defective_line}`),this.utf8_bom_removed&&e.push(`UTF-8 Byte Order Mark (BOM) was found and skipped in ${this.table_name} table`),Object.keys(this.fields_info).length>1&&e.push(function(e,t){let r=Object.keys(t),n=[];for(let e=0;e1);let[i,o]=n[0],[s,a]=n[1],l=`Number of fields in "${e}" table is not consistent: `;return l+=`e.g. record ${i} -> ${o} fields, record ${s} -> ${a} fields`,l}(this.table_name,this.fields_info)),e}}class b extends l.RBQLOutputWriter{constructor(e,t,r,n,i,o="\n"){if(super(),this.stream=e,this.encoding=r,r&&this.stream.setDefaultEncoding(r),this.stream.on("error",(e=>{this.store_first_error(e)})),this.delim=n,this.policy=i,this.line_separator=o,this.sub_array_delim="|"==n?";":"|",this.close_stream_on_finish=t,this.null_in_output=!1,this.delim_in_simple_output=!1,this.header_len=null,this.first_error=null,"simple"==i)this.polymorphic_join=this.simple_join;else if("quoted"==i)this.polymorphic_join=this.quoted_join;else if("quoted_rfc"==i)this.polymorphic_join=this.quoted_join_rfc;else if("monocolumn"==i)this.polymorphic_join=this.mono_join;else{if("whitespace"!=i)throw new _("Unknown output csv policy");this.polymorphic_join=this.simple_join}}store_first_error(e){null===this.first_error&&(this.first_error=e)}set_header(e){null!==e&&(this.header_len=e.length,this.write(e))}quoted_join(e){let t=this.delim;return e.map((function(e){return u.quote_field(String(e),t)})).join(this.delim)}quoted_join_rfc(e){let t=this.delim;return e.map((function(e){return u.rfc_quote_field(String(e),t)})).join(this.delim)}mono_join(e){if(e.length>1)throw new _('Unable to use "Monocolumn" output format: some records have more than one field');return e[0]}simple_join(e){var t=e.join(this.delim);return-1!=e.join("").indexOf(this.delim)&&(this.delim_in_simple_output=!0),t}normalize_fields(e){for(var t=0;t{i()})):setTimeout((()=>{i()}),0)}))}get_warnings(){let e=[];return this.null_in_output&&e.push("null values in output were replaced by empty strings"),this.delim_in_simple_output&&e.push("Some output fields contain separator"),e}}class w extends l.RBQLTableRegistry{constructor(e,t,r,n,i=!1,o=null,s=null){super(),this.input_file_dir=e,this.delim=t,this.policy=r,this.encoding=n,this.has_header=i,this.comment_prefix=o,this.stream=null,this.record_iterator=null,this.options=s,this.bulk_input_path=null,this.table_path=null}get_iterator_by_table_id(e){if(this.table_path=g(this.input_file_dir,e),null===this.table_path)throw new _(`Unable to find join table "${e}"`);return this.options&&this.options.bulk_read?this.bulk_input_path=this.table_path:this.stream=i.createReadStream(this.table_path),this.record_iterator=new m(this.stream,this.bulk_input_path,this.encoding,this.delim,this.policy,this.has_header,this.comment_prefix,e,"b"),this.record_iterator}get_warnings(e){this.record_iterator&&this.has_header&&e.push(`The first record in JOIN file ${s.basename(this.table_path)} was also treated as header (and skipped)`)}}e.exports.is_ascii=h,e.exports.CSVRecordIterator=m,e.exports.CSVWriter=b,e.exports.FileSystemCSVRegistry=w,e.exports.interpret_named_csv_format=function(e){if("monocolumn"==(e=e.toLowerCase()))return["","monocolumn"];if("csv"==e)return[",","quoted"];if("tsv"==e)return["\t","simple"];throw new _(`Unknown format name: "${e}"`)},e.exports.read_user_init_code=d,e.exports.query_csv=async function(e,t,r,a,u,c,p,f,g,y=!1,x=null,v="",E=null){let O=null,S=null;E&&E.bulk_read&&t?S=t:O=null===t?n.stdin:i.createReadStream(t);let[R,A]=null===u?[n.stdout,!1]:[i.createWriteStream(u),!0];if('"'==r&&"quoted"==a)throw new _('Double quote delimiter is incompatible with "quoted" policy');if("latin-1"==f&&(f="binary"),!h(e)&&"binary"==f)throw new _("To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary");if(!(h(r)&&h(c)||"binary"!=f))throw new _("To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary");let q=s.join(o.homedir(),".rbql_init_source.js");""==v&&i.existsSync(q)&&(v=d(q));let P=t?s.dirname(t):null,j=new w(P,r,a,f,y,x,E),T=new m(O,S,f,r,a,y,x),k=new b(R,A,f,c,p);await l.query(e,T,k,g,j,v),j.get_warnings(g)},e.exports.RecordQueue=y,e.exports.exception_to_error_info=l.exception_to_error_info},9496:e=>{"use strict";e.exports=require("vscode")},1606:()=>{},4704:()=>{},9426:()=>{},2667:()=>{},5174:()=>{},4949:()=>{},7857:()=>{},8391:()=>{},3083:(e,t,r)=>{"use strict";var n=["BigInt64Array","BigUint64Array","Float32Array","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Uint8Array","Uint8ClampedArray"],i="undefined"==typeof globalThis?r.g:globalThis;e.exports=function(){for(var e=[],t=0;t{"use strict";var n=r(210)("%Object.getOwnPropertyDescriptor%",!0);if(n)try{n([],"length")}catch(e){n=null}e.exports=n}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](r,r.exports,__webpack_require__),r.exports}__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}();var __webpack_exports__={};(()=>{var e=__webpack_exports__;const t=__webpack_require__(9496),r=__webpack_require__(7857),n=__webpack_require__(5174),i=__webpack_require__(4949),o=__webpack_require__(2667),s=__webpack_require__(8594);var a=null,l=null;function u(){return null===l&&(l=__webpack_require__(45)),l}const c=void 0===i.homedir,_=100,p="vscode_rbql_scratch";let f=null;var h=new Map,d=new Set,g=new Set,y=new Map,m=new Map,b=null,w=null,x=null,v=null,E=null;let O=null;var S=null,R=new Map,A=null,q=null,P=null,j=null,T=null,k=null;const I={csv:[",","quoted"],tsv:["\t","simple"],"csv (semicolon)":[";","quoted"],"csv (pipe)":["|","simple"],"csv (tilde)":["~","simple"],"csv (caret)":["^","simple"],"csv (colon)":[":","simple"],"csv (double quote)":['"',"simple"],"csv (equals)":["=","simple"],"csv (dot)":[".","simple"],"csv (whitespace)":[" ","whitespace"],"csv (hyphen)":["-","simple"]};let N={"rbql_client.js":null,"contrib/textarea-caret-position/index.js":null,"rbql_suggest.js":null,"rbql_logo.svg":null,"rbql_client.html":null,"rbql mock/rbql_mock.py":null,"rbql_core/vscode_rbql.py":null};function L(e){var r=t.window;r&&r.showErrorMessage(e)}function C(e){return new Promise((t=>setTimeout(t,e)))}async function U(){await C(0)}function M(e){for(let t in I)if(I.hasOwnProperty(t)&&I[t][0]==e)return t;return null}function B(e,t){if(q){var r=q.get(e);if(null!=r)return r}return t}async function $(e,t){return!(!q||!e||(await q.update(e,t),0))}function D(e,t,r){let n=[];for(let i=t;ie.replace(o,n)))}function W(e,t){let r=e.input_document,n=e.delim,i=e.policy;e.requested_start_record=Math.max(e.requested_start_record,0);let o=[];if(e.enable_rfc_newlines){let a=e.requested_start_record+_;u().populate_optimistic_rfc_csv_record_map(r,a,e.rfc_record_map),e.requested_start_record=Math.max(0,Math.min(e.requested_start_record,e.rfc_record_map.length-_));for(let a=e.requested_start_record;a250&&(t[e]=t[e].substr(0,250)+"###UI_STRING_TRIM_MARKER###")}t.preview_records=o,t.start_record_zero_based=e.requested_start_record}function J(e){return"rbql_header:"+e}function Q(e){return"enable_rfc_newlines:"+e}function z(e){return"rbql_with_headers:"+e}function V(e,r){const n=t.workspace.getConfiguration("rainbow_csv");return n?n.get(e):r}function G(e,t,r){let n=V("comment_prefix",""),i=u().get_header_line(e,n);return s.smart_split(i,t,r,!1)[0]}function H(e,t,r){var n=e.fileName;if(n){let e=B(J(n),null);if(e)return JSON.parse(e)}return G(e,t,r)}function Y(e,t){if(!e.length)return null;for(var r=0,n=e[r].length+1;t>n&&r+1 "+n),await t.languages.setTextDocumentLanguage(e,n)),await async function(e){if(k=[],e&&e.length){var r=t.window;if(!r)return null;for(var n=0;n=1e4)L("Multicursor column edit works only for files smaller than 10000 lines.");else{for(let r=0;r=c.length)return void L(`Line ${r+1} doesn't have field number ${g+1}`);let _=c.slice(0,g).join("").length+g,p=c.slice(0,g+1).join("").length+g;if("ce_before"==e&&"quoted"==a&&-1!=i.substring(_-2,_+2).indexOf('"'))return void L(`Accidental data corruption prevention: Cursor at line ${r+1} will not be set: a double quote is in proximity.`);if("ce_after"==e&&"quoted"==a&&-1!=i.substring(p-2,p+2).indexOf('"'))return void L(`Accidental data corruption prevention: Cursor at line ${r+1} will not be set: a double quote is in proximity.`);if("ce_select"==e&&_==p)return void L(`Accidental data corruption prevention: The column can not be selected: field ${g+1} at line ${r+1} is empty.`);let f=new t.Position(r,_),h=new t.Position(r,p);"ce_before"==e&&y.push(new t.Selection(f,f)),"ce_after"==e&&y.push(new t.Selection(h,h)),"ce_select"==e&&y.push(new t.Selection(f,h))}r.selections=y,d&&t.window.showWarningMessage("Some lines have quoting issues: cursors positioning may be incorrect."),await t.window.showTextDocument(n)}}async function de(){let e=Z(),r=X(e);if(!r)return;let n=r.languageId;if(!I.hasOwnProperty(n))return;let[i,o]=I[n],s=V("comment_prefix",""),a={location:t.ProgressLocation.Window,title:"Rainbow CSV"};await t.window.withProgress(a,(async n=>{n.report({message:"Preparing"}),await U();let[a,l]=u().shrink_columns(r,i,o,s);l?L(`Unable to shrink: Inconsistent double quotes at line ${l}`):(d.delete(r.fileName),ee(r),null!==a?(n.report({message:"Shrinking columns"}),await U(),await F(e,r,a)):t.window.showWarningMessage("No trailing whitespaces found, skipping"))}))}async function ge(){let e=Z(),r=X(e);if(!r)return;let n=r.languageId;if(!I.hasOwnProperty(n))return;let[i,o]=I[n],s=V("comment_prefix",""),a={location:t.ProgressLocation.Window,title:"Rainbow CSV"};await t.window.withProgress(a,(async n=>{n.report({message:"Calculating column statistics"}),await U();let[a,l]=u().calc_column_stats(r,i,o,s);l?L(`Unable to align: Inconsistent double quotes at line ${l}`):(a=u().adjust_column_stats(a),null!==a?(n.report({message:"Preparing final alignment"}),await U(),aligned_doc_text=u().align_columns(r,i,o,s,a),d.add(r.fileName),ee(r),null!==aligned_doc_text?(n.report({message:"Aligning columns"}),await U(),await F(e,r,aligned_doc_text)):t.window.showWarningMessage("Table is already aligned, skipping")):L("Unable to allign: Internal Rainbow CSV Error"))}))}async function ye(){if(c)return void L("This command is currently unavailable in web mode.");let e=X();if(!e)return;let r=e.fileName,n=m.get(r.toLowerCase());if(!n)return;let i=await t.workspace.openTextDocument(n),o=await t.window.showTextDocument(i);await async function(e,t){let r=e.getText(),n=X(t);n&&await F(t,n,r)}(e,o)}async function me(e,o,l=null){let p=o.msg_type,f=async function(t,r){let n={msg_type:"rbql_report"};t&&(n.error_type=t),r&&(n.error_msg=r),T=n,await e.postMessage(n)};if("handshake"==p){var h={msg_type:"handshake",backend_language:B("rbql_backend_language","js"),encoding:B("rbql_encoding","utf-8")};W(S,h);let t=ae(S.input_document_path);R.has(t)&&(h.last_query=R.get(t));let r=B("rbql_query_history",[]);h.query_history=r,h.policy=S.policy,h.enable_rfc_newlines=S.enable_rfc_newlines,h.with_headers=S.with_headers,h.header=S.header,h.is_web_ext=c,l&&(h.integration_test_language=l.rbql_backend,h.integration_test_query=l.rbql_query,h.integration_test_with_headers=l.with_headers||!1,h.integration_test_enable_rfc_newlines=l.enable_rfc_newlines||!1),await e.postMessage(h)}if("fetch_table_header"==p)try{let t=o.table_id,n=o.encoding,i=S.input_document_path?r.dirname(S.input_document_path):null,a=u().find_table_path(q,i,t);if(!a)return;let l=await u().read_header(a,n),[c,_]=s.smart_split(l,S.delim,S.policy,!1);_||e.postMessage({msg_type:"fetch_table_header_response",header:c})}catch(e){console.error("Unable to get join table header: "+String(e))}if("update_query"==p){let e=o.query;if(!e)return;S.input_document_path&&R.set(ae(S.input_document_path),e)}if("newlines_policy_change"==p){S.enable_rfc_newlines=o.enable_rfc_newlines,S.input_document_path&&await $(Q(S.input_document_path),S.enable_rfc_newlines);let t={msg_type:"resample"};W(S,t),await e.postMessage(t)}if("with_headers_change"==p&&(S.with_headers=o.with_headers,S.input_document_path&&await $(z(S.input_document_path),S.with_headers)),"navigate"==p){var d=o.direction;"backward"==d?S.requested_start_record-=_:"forward"==d?S.requested_start_record+=_:"begin"==d?S.requested_start_record=0:"end"==d&&(S.requested_start_record=S.input_document.lineCount);let t={msg_type:"navigate"};W(S,t),await e.postMessage(t)}if("run"==p){let e=o.query,n=o.backend_language,s=o.encoding,l=o.output_dialect,_=o.enable_rfc_newlines,p=o.with_headers;await async function(e){let t=B("rbql_query_history",[]),r=t.indexOf(e);-1!=r?t.splice(r,1):t.length>=20&&t.splice(0,1),t.push(e),await $("rbql_query_history",t)}(e),await async function(e,n,o,s,l,_,p,f){R.set(ae(e),s);var h="python";let d={process_reported:!1},[y,b]=[S.delim,S.policy];"quoted"==b&&_&&(b="quoted_rfc");let[w,x]=[y,b];"csv"==l&&([w,x]=[",","quoted"]),"tsv"==l&&([w,x]=["\t","simple"]),S.output_delim=w;let v=c?null:r.join(function(e){let t=V("rbql_output_dir","TMP");return"TMP"==t?i.tmpdir():"INPUT"==t?r.dirname(e):t}(e),function(e,t){var n=r.basename(e),i=r.extname(n),o={"\t":".tsv",",":".csv"},s=".txt";o.hasOwnProperty(t)?s=o[t]:i.length>1&&(s=i);let a=n+s;return a==n&&(a+=".txt"),a}(e,w));if(s.startsWith("test "))return-1!=s.indexOf("nopython")&&(h="nopython"),void oe(h,[N["rbql mock/rbql_mock.py"],s],d,(function(t,r,n){se(e,v,t,r,n,f)}));if("js"==o){let r=[],i=null;try{if(c){let e={content:(await u().rbql_query_web(s,S.input_document,y,b,w,x,r,p,null)).join("\n"),language:M(w)};i=await t.workspace.openTextDocument(e)}else{let o={bulk_read:!0};await u().rbql_query_node(q,s,e,y,b,v,w,x,n,r,p,null,"",o),m.set(v.toLowerCase(),e),g.add(v),i=await t.workspace.openTextDocument(v)}}catch(e){let[t,r]=(null===a&&(a=__webpack_require__(371)),a).exception_to_error_info(e);return void f(t,r)}f(null,null),await ie(i,r)}else{if(c)return void f("Input error","Python backend for RBQL is not supported in web version, please use JavaScript backend.");let t=Buffer.from(s,"utf-8").toString("base64"),r=[N["rbql_core/vscode_rbql.py"],t,e,y,b,v,w,x,n];p&&r.push("--with_headers"),oe(h,r,d,(function(t,r,n){se(e,v,t,r,n,f)}))}}(S.input_document_path,s,n,e,l,_,p,f)}if("edit_udf"==p){if(c)return void f("Input error","UDFs are currently not supported in web version");let e=null,s="";"js"==o.backend_language?(e=r.join(i.homedir(),".rbql_init_source.js"),s=u().get_default_js_udf_content()):(e=r.join(i.homedir(),".rbql_init_source.py"),s=u().get_default_python_udf_content()),n.existsSync(e)||n.writeFileSync(e,s);let a=await t.workspace.openTextDocument(e);await t.window.showTextDocument(a)}"global_param_change"==p&&await $(o.key,o.value)}async function be(e=null){let o=t.window;if(!o)return;let s=o.activeTextEditor;if(!s)return;let a=s.document;if(!a)return;let l=a.uri;if(!l)return;if("file"!=l.scheme&&"untitled"!=l.scheme&&!c)return;if("file"==l.scheme&&a.isDirty&&!c)return void L("Unable to run RBQL: file has unsaved changes");let u=null;if("untitled"!=l.scheme||c)u=a.fileName;else{let e=a.getText(),t=String(Math.floor(1e6*Math.random()));u=r.join(i.tmpdir(),`vscode_rbql_scratch_${t}.txt`),n.writeFileSync(u,e)}if(!u)return void L("Unable to run RBQL for this file");let _=a.languageId,p="monocolumn",h="monocolumn";I.hasOwnProperty(_)&&([p,h]=I[_]);let d=B(Q(u),!1),g=V("rbql_with_headers_by_default",!1),y=B(z(u),g),m=G(a,p,h);S={input_document:a,input_document_path:u,requested_start_record:0,delim:p,policy:h,rfc_record_map:[],enable_rfc_newlines:d,with_headers:y,header:m},P=t.window.createWebviewPanel("rbql-console","RBQL Console",t.ViewColumn.Active,{enableScripts:!0}),A||(A=c?f:n.readFileSync(N["rbql_client.html"],"utf8"));let b=A;b=function(e,r){for(const e of["contrib/textarea-caret-position/index.js","rbql_suggest.js","rbql_client.js","rbql_logo.svg"]){let n=null;n=c?N[e]:P.webview.asWebviewUri(t.Uri.file(N[e])),r=r.replace(`src="${e}"`,`src="${n}"`)}return r}(0,b),P.webview.html=b,P.webview.onDidReceiveMessage((function(t){me(P.webview,t,e)}))}function we(e,t,r,n,i){var o=e.lineCount;let a=0,l=0,u=V("comment_prefix","");u||(u="#");for(var c=0;c=i?a:0}function xe(e,t){let r=V("autodetection_min_line_count",10);if(e.lineCounti&&(i=u,n=s)}return n}async function ve(e){if(!e)return;j&&(j.dispose(),j=null);let r=e.document;if(!r)return;let n=xe(r,V("autodetect_separators",[]));if(!n)return;let i=await t.languages.setTextDocumentLanguage(r,n);te(i,!1),ee(i)}function Ee(e){let t=X(e);te(t,!1),ee(t)}async function Oe(e){await async function(e){if(!e)return;if(!V("enable_separator_autodetection",!1))return;let r=V("autodetect_separators",[]);var n=e.languageId,i=e.fileName;if(!i||g.has(i))return;let o=i.endsWith(".csv")&&"csv"==n;if("plaintext"!=n&&!o)return;let s=xe(e,r);if(!s&&o&&(s=function(e,t){let r="csv",n=0,i=e.getText();if(!i)return r;for(let e=0;en&&(r=o,n=s)}return r}(e,r)),!s||s==n)return;let a=await t.languages.setTextDocumentLanguage(e,s);y.set(i,n),te(a,!1),ee(a)}(e),function(e){V("enable_separator_autodetection",!1)&&e&&!j&&(e.isUntitled||0==e.lineCount)&&(j=t.workspace.onDidChangeTextDocument(ve))}(e),te(e,!1),ee(e)}async function Se(e,o){if(c)return void L("This command is currently unavailable in web mode.");var s=e.fsPath;if(!s||!n.existsSync(s))return void t.window.showErrorMessage("Invalid file");var a=1024e3,l=n.statSync(s).size;if(l<=a){t.window.showWarningMessage("Rainbow CSV: The file is not big enough, showing the full file instead. Use this preview for files larger than 1MB");let e=await t.workspace.openTextDocument(s);return void await t.window.showTextDocument(e)}let u=r.basename(s);const _=r.join(i.tmpdir(),`.rb_csv_preview.${o}.${u}`);n.open(s,"r",((e,r)=>{if(e)return console.log(e.message),void t.window.showErrorMessage("Unable to preview file");var i=Buffer.alloc(a);let s="head"==o?0:Math.max(l-a,0);n.read(r,i,0,a,s,(function(e,r){if(e)return console.log(e.message),void t.window.showErrorMessage("Unable to preview file");const s=i.toString();let a=null;a="head"==o?s.substr(0,s.lastIndexOf(s.includes("\r\n")?"\r\n":"\n")):s.substr(s.indexOf("\n")+1),n.writeFileSync(_,a),t.workspace.openTextDocument(_).then((e=>t.window.showTextDocument(e)))}))}))}function Re(e,r){let n=t.languages.registerHoverProvider(e,{provideHover:(r,n,i)=>function(e,r,n,i){if(O!=e&&ee(e),V("enable_tooltip",!1)){var o=function(e,t,r,n,i){let[o,a]=I[r];var l=t.line,u=t.character,c=e.lineAt(l).text;let _=V("comment_prefix","");if(_&&c.startsWith(_))return"Comment";var p=s.smart_split(c,o,a,!0),f=p[0],h=p[1],d=Y(f,u+1);if(null==d)return null;var g="Col #"+(d+1),y=H(e,o,a);if(n&&d -1) {\n\t\treturn callBind(intrinsic);\n\t}\n\treturn intrinsic;\n};\n","'use strict';\n\nvar bind = require('function-bind');\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $apply = GetIntrinsic('%Function.prototype.apply%');\nvar $call = GetIntrinsic('%Function.prototype.call%');\nvar $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);\n\nvar $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);\nvar $defineProperty = GetIntrinsic('%Object.defineProperty%', true);\nvar $max = GetIntrinsic('%Math.max%');\n\nif ($defineProperty) {\n\ttry {\n\t\t$defineProperty({}, 'a', { value: 1 });\n\t} catch (e) {\n\t\t// IE 8 has a broken defineProperty\n\t\t$defineProperty = null;\n\t}\n}\n\nmodule.exports = function callBind(originalFunction) {\n\tvar func = $reflectApply(bind, $call, arguments);\n\tif ($gOPD && $defineProperty) {\n\t\tvar desc = $gOPD(func, 'length');\n\t\tif (desc.configurable) {\n\t\t\t// original length, plus the receiver, minus any additional arguments (after the receiver)\n\t\t\t$defineProperty(\n\t\t\t\tfunc,\n\t\t\t\t'length',\n\t\t\t\t{ value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }\n\t\t\t);\n\t\t}\n\t}\n\treturn func;\n};\n\nvar applyBind = function applyBind() {\n\treturn $reflectApply(bind, $apply, arguments);\n};\n\nif ($defineProperty) {\n\t$defineProperty(module.exports, 'apply', { value: applyBind });\n} else {\n\tmodule.exports.apply = applyBind;\n}\n","\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toString = Object.prototype.toString;\n\nmodule.exports = function forEach (obj, fn, ctx) {\n if (toString.call(fn) !== '[object Function]') {\n throw new TypeError('iterator must be a function');\n }\n var l = obj.length;\n if (l === +l) {\n for (var i = 0; i < l; i++) {\n fn.call(ctx, obj[i], i, obj);\n }\n } else {\n for (var k in obj) {\n if (hasOwn.call(obj, k)) {\n fn.call(ctx, obj[k], k, obj);\n }\n }\n }\n};\n\n","'use strict';\n\n/* eslint no-invalid-this: 1 */\n\nvar ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';\nvar slice = Array.prototype.slice;\nvar toStr = Object.prototype.toString;\nvar funcType = '[object Function]';\n\nmodule.exports = function bind(that) {\n var target = this;\n if (typeof target !== 'function' || toStr.call(target) !== funcType) {\n throw new TypeError(ERROR_MESSAGE + target);\n }\n var args = slice.call(arguments, 1);\n\n var bound;\n var binder = function () {\n if (this instanceof bound) {\n var result = target.apply(\n this,\n args.concat(slice.call(arguments))\n );\n if (Object(result) === result) {\n return result;\n }\n return this;\n } else {\n return target.apply(\n that,\n args.concat(slice.call(arguments))\n );\n }\n };\n\n var boundLength = Math.max(0, target.length - args.length);\n var boundArgs = [];\n for (var i = 0; i < boundLength; i++) {\n boundArgs.push('$' + i);\n }\n\n bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);\n\n if (target.prototype) {\n var Empty = function Empty() {};\n Empty.prototype = target.prototype;\n bound.prototype = new Empty();\n Empty.prototype = null;\n }\n\n return bound;\n};\n","'use strict';\n\nvar implementation = require('./implementation');\n\nmodule.exports = Function.prototype.bind || implementation;\n","'use strict';\n\nvar undefined;\n\nvar $SyntaxError = SyntaxError;\nvar $Function = Function;\nvar $TypeError = TypeError;\n\n// eslint-disable-next-line consistent-return\nvar getEvalledConstructor = function (expressionSyntax) {\n\ttry {\n\t\treturn $Function('\"use strict\"; return (' + expressionSyntax + ').constructor;')();\n\t} catch (e) {}\n};\n\nvar $gOPD = Object.getOwnPropertyDescriptor;\nif ($gOPD) {\n\ttry {\n\t\t$gOPD({}, '');\n\t} catch (e) {\n\t\t$gOPD = null; // this is IE 8, which has a broken gOPD\n\t}\n}\n\nvar throwTypeError = function () {\n\tthrow new $TypeError();\n};\nvar ThrowTypeError = $gOPD\n\t? (function () {\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties\n\t\t\targuments.callee; // IE 8 does not throw here\n\t\t\treturn throwTypeError;\n\t\t} catch (calleeThrows) {\n\t\t\ttry {\n\t\t\t\t// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')\n\t\t\t\treturn $gOPD(arguments, 'callee').get;\n\t\t\t} catch (gOPDthrows) {\n\t\t\t\treturn throwTypeError;\n\t\t\t}\n\t\t}\n\t}())\n\t: throwTypeError;\n\nvar hasSymbols = require('has-symbols')();\n\nvar getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto\n\nvar needsEval = {};\n\nvar TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);\n\nvar INTRINSICS = {\n\t'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,\n\t'%Array%': Array,\n\t'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,\n\t'%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,\n\t'%AsyncFromSyncIteratorPrototype%': undefined,\n\t'%AsyncFunction%': needsEval,\n\t'%AsyncGenerator%': needsEval,\n\t'%AsyncGeneratorFunction%': needsEval,\n\t'%AsyncIteratorPrototype%': needsEval,\n\t'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,\n\t'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,\n\t'%Boolean%': Boolean,\n\t'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,\n\t'%Date%': Date,\n\t'%decodeURI%': decodeURI,\n\t'%decodeURIComponent%': decodeURIComponent,\n\t'%encodeURI%': encodeURI,\n\t'%encodeURIComponent%': encodeURIComponent,\n\t'%Error%': Error,\n\t'%eval%': eval, // eslint-disable-line no-eval\n\t'%EvalError%': EvalError,\n\t'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,\n\t'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,\n\t'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,\n\t'%Function%': $Function,\n\t'%GeneratorFunction%': needsEval,\n\t'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,\n\t'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,\n\t'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,\n\t'%isFinite%': isFinite,\n\t'%isNaN%': isNaN,\n\t'%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,\n\t'%JSON%': typeof JSON === 'object' ? JSON : undefined,\n\t'%Map%': typeof Map === 'undefined' ? undefined : Map,\n\t'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),\n\t'%Math%': Math,\n\t'%Number%': Number,\n\t'%Object%': Object,\n\t'%parseFloat%': parseFloat,\n\t'%parseInt%': parseInt,\n\t'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,\n\t'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,\n\t'%RangeError%': RangeError,\n\t'%ReferenceError%': ReferenceError,\n\t'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,\n\t'%RegExp%': RegExp,\n\t'%Set%': typeof Set === 'undefined' ? undefined : Set,\n\t'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),\n\t'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,\n\t'%String%': String,\n\t'%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,\n\t'%Symbol%': hasSymbols ? Symbol : undefined,\n\t'%SyntaxError%': $SyntaxError,\n\t'%ThrowTypeError%': ThrowTypeError,\n\t'%TypedArray%': TypedArray,\n\t'%TypeError%': $TypeError,\n\t'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,\n\t'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,\n\t'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,\n\t'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,\n\t'%URIError%': URIError,\n\t'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,\n\t'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,\n\t'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet\n};\n\nvar doEval = function doEval(name) {\n\tvar value;\n\tif (name === '%AsyncFunction%') {\n\t\tvalue = getEvalledConstructor('async function () {}');\n\t} else if (name === '%GeneratorFunction%') {\n\t\tvalue = getEvalledConstructor('function* () {}');\n\t} else if (name === '%AsyncGeneratorFunction%') {\n\t\tvalue = getEvalledConstructor('async function* () {}');\n\t} else if (name === '%AsyncGenerator%') {\n\t\tvar fn = doEval('%AsyncGeneratorFunction%');\n\t\tif (fn) {\n\t\t\tvalue = fn.prototype;\n\t\t}\n\t} else if (name === '%AsyncIteratorPrototype%') {\n\t\tvar gen = doEval('%AsyncGenerator%');\n\t\tif (gen) {\n\t\t\tvalue = getProto(gen.prototype);\n\t\t}\n\t}\n\n\tINTRINSICS[name] = value;\n\n\treturn value;\n};\n\nvar LEGACY_ALIASES = {\n\t'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],\n\t'%ArrayPrototype%': ['Array', 'prototype'],\n\t'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],\n\t'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],\n\t'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],\n\t'%ArrayProto_values%': ['Array', 'prototype', 'values'],\n\t'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],\n\t'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],\n\t'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],\n\t'%BooleanPrototype%': ['Boolean', 'prototype'],\n\t'%DataViewPrototype%': ['DataView', 'prototype'],\n\t'%DatePrototype%': ['Date', 'prototype'],\n\t'%ErrorPrototype%': ['Error', 'prototype'],\n\t'%EvalErrorPrototype%': ['EvalError', 'prototype'],\n\t'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],\n\t'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],\n\t'%FunctionPrototype%': ['Function', 'prototype'],\n\t'%Generator%': ['GeneratorFunction', 'prototype'],\n\t'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],\n\t'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],\n\t'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],\n\t'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],\n\t'%JSONParse%': ['JSON', 'parse'],\n\t'%JSONStringify%': ['JSON', 'stringify'],\n\t'%MapPrototype%': ['Map', 'prototype'],\n\t'%NumberPrototype%': ['Number', 'prototype'],\n\t'%ObjectPrototype%': ['Object', 'prototype'],\n\t'%ObjProto_toString%': ['Object', 'prototype', 'toString'],\n\t'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],\n\t'%PromisePrototype%': ['Promise', 'prototype'],\n\t'%PromiseProto_then%': ['Promise', 'prototype', 'then'],\n\t'%Promise_all%': ['Promise', 'all'],\n\t'%Promise_reject%': ['Promise', 'reject'],\n\t'%Promise_resolve%': ['Promise', 'resolve'],\n\t'%RangeErrorPrototype%': ['RangeError', 'prototype'],\n\t'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],\n\t'%RegExpPrototype%': ['RegExp', 'prototype'],\n\t'%SetPrototype%': ['Set', 'prototype'],\n\t'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],\n\t'%StringPrototype%': ['String', 'prototype'],\n\t'%SymbolPrototype%': ['Symbol', 'prototype'],\n\t'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],\n\t'%TypedArrayPrototype%': ['TypedArray', 'prototype'],\n\t'%TypeErrorPrototype%': ['TypeError', 'prototype'],\n\t'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],\n\t'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],\n\t'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],\n\t'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],\n\t'%URIErrorPrototype%': ['URIError', 'prototype'],\n\t'%WeakMapPrototype%': ['WeakMap', 'prototype'],\n\t'%WeakSetPrototype%': ['WeakSet', 'prototype']\n};\n\nvar bind = require('function-bind');\nvar hasOwn = require('has');\nvar $concat = bind.call(Function.call, Array.prototype.concat);\nvar $spliceApply = bind.call(Function.apply, Array.prototype.splice);\nvar $replace = bind.call(Function.call, String.prototype.replace);\nvar $strSlice = bind.call(Function.call, String.prototype.slice);\n\n/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */\nvar rePropName = /[^%.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|%$))/g;\nvar reEscapeChar = /\\\\(\\\\)?/g; /** Used to match backslashes in property paths. */\nvar stringToPath = function stringToPath(string) {\n\tvar first = $strSlice(string, 0, 1);\n\tvar last = $strSlice(string, -1);\n\tif (first === '%' && last !== '%') {\n\t\tthrow new $SyntaxError('invalid intrinsic syntax, expected closing `%`');\n\t} else if (last === '%' && first !== '%') {\n\t\tthrow new $SyntaxError('invalid intrinsic syntax, expected opening `%`');\n\t}\n\tvar result = [];\n\t$replace(string, rePropName, function (match, number, quote, subString) {\n\t\tresult[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;\n\t});\n\treturn result;\n};\n/* end adaptation */\n\nvar getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {\n\tvar intrinsicName = name;\n\tvar alias;\n\tif (hasOwn(LEGACY_ALIASES, intrinsicName)) {\n\t\talias = LEGACY_ALIASES[intrinsicName];\n\t\tintrinsicName = '%' + alias[0] + '%';\n\t}\n\n\tif (hasOwn(INTRINSICS, intrinsicName)) {\n\t\tvar value = INTRINSICS[intrinsicName];\n\t\tif (value === needsEval) {\n\t\t\tvalue = doEval(intrinsicName);\n\t\t}\n\t\tif (typeof value === 'undefined' && !allowMissing) {\n\t\t\tthrow new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');\n\t\t}\n\n\t\treturn {\n\t\t\talias: alias,\n\t\t\tname: intrinsicName,\n\t\t\tvalue: value\n\t\t};\n\t}\n\n\tthrow new $SyntaxError('intrinsic ' + name + ' does not exist!');\n};\n\nmodule.exports = function GetIntrinsic(name, allowMissing) {\n\tif (typeof name !== 'string' || name.length === 0) {\n\t\tthrow new $TypeError('intrinsic name must be a non-empty string');\n\t}\n\tif (arguments.length > 1 && typeof allowMissing !== 'boolean') {\n\t\tthrow new $TypeError('\"allowMissing\" argument must be a boolean');\n\t}\n\n\tvar parts = stringToPath(name);\n\tvar intrinsicBaseName = parts.length > 0 ? parts[0] : '';\n\n\tvar intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);\n\tvar intrinsicRealName = intrinsic.name;\n\tvar value = intrinsic.value;\n\tvar skipFurtherCaching = false;\n\n\tvar alias = intrinsic.alias;\n\tif (alias) {\n\t\tintrinsicBaseName = alias[0];\n\t\t$spliceApply(parts, $concat([0, 1], alias));\n\t}\n\n\tfor (var i = 1, isOwn = true; i < parts.length; i += 1) {\n\t\tvar part = parts[i];\n\t\tvar first = $strSlice(part, 0, 1);\n\t\tvar last = $strSlice(part, -1);\n\t\tif (\n\t\t\t(\n\t\t\t\t(first === '\"' || first === \"'\" || first === '`')\n\t\t\t\t|| (last === '\"' || last === \"'\" || last === '`')\n\t\t\t)\n\t\t\t&& first !== last\n\t\t) {\n\t\t\tthrow new $SyntaxError('property names with quotes must have matching quotes');\n\t\t}\n\t\tif (part === 'constructor' || !isOwn) {\n\t\t\tskipFurtherCaching = true;\n\t\t}\n\n\t\tintrinsicBaseName += '.' + part;\n\t\tintrinsicRealName = '%' + intrinsicBaseName + '%';\n\n\t\tif (hasOwn(INTRINSICS, intrinsicRealName)) {\n\t\t\tvalue = INTRINSICS[intrinsicRealName];\n\t\t} else if (value != null) {\n\t\t\tif (!(part in value)) {\n\t\t\t\tif (!allowMissing) {\n\t\t\t\t\tthrow new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');\n\t\t\t\t}\n\t\t\t\treturn void undefined;\n\t\t\t}\n\t\t\tif ($gOPD && (i + 1) >= parts.length) {\n\t\t\t\tvar desc = $gOPD(value, part);\n\t\t\t\tisOwn = !!desc;\n\n\t\t\t\t// By convention, when a data property is converted to an accessor\n\t\t\t\t// property to emulate a data property that does not suffer from\n\t\t\t\t// the override mistake, that accessor's getter is marked with\n\t\t\t\t// an `originalValue` property. Here, when we detect this, we\n\t\t\t\t// uphold the illusion by pretending to see that original data\n\t\t\t\t// property, i.e., returning the value rather than the getter\n\t\t\t\t// itself.\n\t\t\t\tif (isOwn && 'get' in desc && !('originalValue' in desc.get)) {\n\t\t\t\t\tvalue = desc.get;\n\t\t\t\t} else {\n\t\t\t\t\tvalue = value[part];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tisOwn = hasOwn(value, part);\n\t\t\t\tvalue = value[part];\n\t\t\t}\n\n\t\t\tif (isOwn && !skipFurtherCaching) {\n\t\t\t\tINTRINSICS[intrinsicRealName] = value;\n\t\t\t}\n\t\t}\n\t}\n\treturn value;\n};\n","'use strict';\n\nvar origSymbol = typeof Symbol !== 'undefined' && Symbol;\nvar hasSymbolSham = require('./shams');\n\nmodule.exports = function hasNativeSymbols() {\n\tif (typeof origSymbol !== 'function') { return false; }\n\tif (typeof Symbol !== 'function') { return false; }\n\tif (typeof origSymbol('foo') !== 'symbol') { return false; }\n\tif (typeof Symbol('bar') !== 'symbol') { return false; }\n\n\treturn hasSymbolSham();\n};\n","'use strict';\n\n/* eslint complexity: [2, 18], max-statements: [2, 33] */\nmodule.exports = function hasSymbols() {\n\tif (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }\n\tif (typeof Symbol.iterator === 'symbol') { return true; }\n\n\tvar obj = {};\n\tvar sym = Symbol('test');\n\tvar symObj = Object(sym);\n\tif (typeof sym === 'string') { return false; }\n\n\tif (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }\n\tif (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }\n\n\t// temp disabled per https://github.com/ljharb/object.assign/issues/17\n\t// if (sym instanceof Symbol) { return false; }\n\t// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4\n\t// if (!(symObj instanceof Symbol)) { return false; }\n\n\t// if (typeof Symbol.prototype.toString !== 'function') { return false; }\n\t// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }\n\n\tvar symVal = 42;\n\tobj[sym] = symVal;\n\tfor (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop\n\tif (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }\n\n\tif (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }\n\n\tvar syms = Object.getOwnPropertySymbols(obj);\n\tif (syms.length !== 1 || syms[0] !== sym) { return false; }\n\n\tif (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }\n\n\tif (typeof Object.getOwnPropertyDescriptor === 'function') {\n\t\tvar descriptor = Object.getOwnPropertyDescriptor(obj, sym);\n\t\tif (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }\n\t}\n\n\treturn true;\n};\n","'use strict';\n\nvar hasSymbols = require('has-symbols/shams');\n\nmodule.exports = function hasToStringTagShams() {\n\treturn hasSymbols() && !!Symbol.toStringTag;\n};\n","'use strict';\n\nvar bind = require('function-bind');\n\nmodule.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n","'use strict';\n\nvar hasToStringTag = require('has-tostringtag/shams')();\nvar callBound = require('call-bind/callBound');\n\nvar $toString = callBound('Object.prototype.toString');\n\nvar isStandardArguments = function isArguments(value) {\n\tif (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) {\n\t\treturn false;\n\t}\n\treturn $toString(value) === '[object Arguments]';\n};\n\nvar isLegacyArguments = function isArguments(value) {\n\tif (isStandardArguments(value)) {\n\t\treturn true;\n\t}\n\treturn value !== null &&\n\t\ttypeof value === 'object' &&\n\t\ttypeof value.length === 'number' &&\n\t\tvalue.length >= 0 &&\n\t\t$toString(value) !== '[object Array]' &&\n\t\t$toString(value.callee) === '[object Function]';\n};\n\nvar supportsStandardArguments = (function () {\n\treturn isStandardArguments(arguments);\n}());\n\nisStandardArguments.isLegacyArguments = isLegacyArguments; // for tests\n\nmodule.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments;\n","'use strict';\n\nvar toStr = Object.prototype.toString;\nvar fnToStr = Function.prototype.toString;\nvar isFnRegex = /^\\s*(?:function)?\\*/;\nvar hasToStringTag = require('has-tostringtag/shams')();\nvar getProto = Object.getPrototypeOf;\nvar getGeneratorFunc = function () { // eslint-disable-line consistent-return\n\tif (!hasToStringTag) {\n\t\treturn false;\n\t}\n\ttry {\n\t\treturn Function('return function*() {}')();\n\t} catch (e) {\n\t}\n};\nvar GeneratorFunction;\n\nmodule.exports = function isGeneratorFunction(fn) {\n\tif (typeof fn !== 'function') {\n\t\treturn false;\n\t}\n\tif (isFnRegex.test(fnToStr.call(fn))) {\n\t\treturn true;\n\t}\n\tif (!hasToStringTag) {\n\t\tvar str = toStr.call(fn);\n\t\treturn str === '[object GeneratorFunction]';\n\t}\n\tif (!getProto) {\n\t\treturn false;\n\t}\n\tif (typeof GeneratorFunction === 'undefined') {\n\t\tvar generatorFunc = getGeneratorFunc();\n\t\tGeneratorFunction = generatorFunc ? getProto(generatorFunc) : false;\n\t}\n\treturn getProto(fn) === GeneratorFunction;\n};\n","'use strict';\n\nvar forEach = require('foreach');\nvar availableTypedArrays = require('available-typed-arrays');\nvar callBound = require('call-bind/callBound');\n\nvar $toString = callBound('Object.prototype.toString');\nvar hasToStringTag = require('has-tostringtag/shams')();\n\nvar g = typeof globalThis === 'undefined' ? global : globalThis;\nvar typedArrays = availableTypedArrays();\n\nvar $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) {\n\tfor (var i = 0; i < array.length; i += 1) {\n\t\tif (array[i] === value) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n};\nvar $slice = callBound('String.prototype.slice');\nvar toStrTags = {};\nvar gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor');\nvar getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');\nif (hasToStringTag && gOPD && getPrototypeOf) {\n\tforEach(typedArrays, function (typedArray) {\n\t\tvar arr = new g[typedArray]();\n\t\tif (Symbol.toStringTag in arr) {\n\t\t\tvar proto = getPrototypeOf(arr);\n\t\t\tvar descriptor = gOPD(proto, Symbol.toStringTag);\n\t\t\tif (!descriptor) {\n\t\t\t\tvar superProto = getPrototypeOf(proto);\n\t\t\t\tdescriptor = gOPD(superProto, Symbol.toStringTag);\n\t\t\t}\n\t\t\ttoStrTags[typedArray] = descriptor.get;\n\t\t}\n\t});\n}\n\nvar tryTypedArrays = function tryAllTypedArrays(value) {\n\tvar anyTrue = false;\n\tforEach(toStrTags, function (getter, typedArray) {\n\t\tif (!anyTrue) {\n\t\t\ttry {\n\t\t\t\tanyTrue = getter.call(value) === typedArray;\n\t\t\t} catch (e) { /**/ }\n\t\t}\n\t});\n\treturn anyTrue;\n};\n\nmodule.exports = function isTypedArray(value) {\n\tif (!value || typeof value !== 'object') { return false; }\n\tif (!hasToStringTag || !(Symbol.toStringTag in value)) {\n\t\tvar tag = $slice($toString(value), 8, -1);\n\t\treturn $indexOf(typedArrays, tag) > -1;\n\t}\n\tif (!gOPD) { return false; }\n\treturn tryTypedArrays(value);\n};\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","module.exports = function isBuffer(arg) {\n return arg && typeof arg === 'object'\n && typeof arg.copy === 'function'\n && typeof arg.fill === 'function'\n && typeof arg.readUInt8 === 'function';\n}","// Currently in sync with Node.js lib/internal/util/types.js\n// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9\n\n'use strict';\n\nvar isArgumentsObject = require('is-arguments');\nvar isGeneratorFunction = require('is-generator-function');\nvar whichTypedArray = require('which-typed-array');\nvar isTypedArray = require('is-typed-array');\n\nfunction uncurryThis(f) {\n return f.call.bind(f);\n}\n\nvar BigIntSupported = typeof BigInt !== 'undefined';\nvar SymbolSupported = typeof Symbol !== 'undefined';\n\nvar ObjectToString = uncurryThis(Object.prototype.toString);\n\nvar numberValue = uncurryThis(Number.prototype.valueOf);\nvar stringValue = uncurryThis(String.prototype.valueOf);\nvar booleanValue = uncurryThis(Boolean.prototype.valueOf);\n\nif (BigIntSupported) {\n var bigIntValue = uncurryThis(BigInt.prototype.valueOf);\n}\n\nif (SymbolSupported) {\n var symbolValue = uncurryThis(Symbol.prototype.valueOf);\n}\n\nfunction checkBoxedPrimitive(value, prototypeValueOf) {\n if (typeof value !== 'object') {\n return false;\n }\n try {\n prototypeValueOf(value);\n return true;\n } catch(e) {\n return false;\n }\n}\n\nexports.isArgumentsObject = isArgumentsObject;\nexports.isGeneratorFunction = isGeneratorFunction;\nexports.isTypedArray = isTypedArray;\n\n// Taken from here and modified for better browser support\n// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js\nfunction isPromise(input) {\n\treturn (\n\t\t(\n\t\t\ttypeof Promise !== 'undefined' &&\n\t\t\tinput instanceof Promise\n\t\t) ||\n\t\t(\n\t\t\tinput !== null &&\n\t\t\ttypeof input === 'object' &&\n\t\t\ttypeof input.then === 'function' &&\n\t\t\ttypeof input.catch === 'function'\n\t\t)\n\t);\n}\nexports.isPromise = isPromise;\n\nfunction isArrayBufferView(value) {\n if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {\n return ArrayBuffer.isView(value);\n }\n\n return (\n isTypedArray(value) ||\n isDataView(value)\n );\n}\nexports.isArrayBufferView = isArrayBufferView;\n\n\nfunction isUint8Array(value) {\n return whichTypedArray(value) === 'Uint8Array';\n}\nexports.isUint8Array = isUint8Array;\n\nfunction isUint8ClampedArray(value) {\n return whichTypedArray(value) === 'Uint8ClampedArray';\n}\nexports.isUint8ClampedArray = isUint8ClampedArray;\n\nfunction isUint16Array(value) {\n return whichTypedArray(value) === 'Uint16Array';\n}\nexports.isUint16Array = isUint16Array;\n\nfunction isUint32Array(value) {\n return whichTypedArray(value) === 'Uint32Array';\n}\nexports.isUint32Array = isUint32Array;\n\nfunction isInt8Array(value) {\n return whichTypedArray(value) === 'Int8Array';\n}\nexports.isInt8Array = isInt8Array;\n\nfunction isInt16Array(value) {\n return whichTypedArray(value) === 'Int16Array';\n}\nexports.isInt16Array = isInt16Array;\n\nfunction isInt32Array(value) {\n return whichTypedArray(value) === 'Int32Array';\n}\nexports.isInt32Array = isInt32Array;\n\nfunction isFloat32Array(value) {\n return whichTypedArray(value) === 'Float32Array';\n}\nexports.isFloat32Array = isFloat32Array;\n\nfunction isFloat64Array(value) {\n return whichTypedArray(value) === 'Float64Array';\n}\nexports.isFloat64Array = isFloat64Array;\n\nfunction isBigInt64Array(value) {\n return whichTypedArray(value) === 'BigInt64Array';\n}\nexports.isBigInt64Array = isBigInt64Array;\n\nfunction isBigUint64Array(value) {\n return whichTypedArray(value) === 'BigUint64Array';\n}\nexports.isBigUint64Array = isBigUint64Array;\n\nfunction isMapToString(value) {\n return ObjectToString(value) === '[object Map]';\n}\nisMapToString.working = (\n typeof Map !== 'undefined' &&\n isMapToString(new Map())\n);\n\nfunction isMap(value) {\n if (typeof Map === 'undefined') {\n return false;\n }\n\n return isMapToString.working\n ? isMapToString(value)\n : value instanceof Map;\n}\nexports.isMap = isMap;\n\nfunction isSetToString(value) {\n return ObjectToString(value) === '[object Set]';\n}\nisSetToString.working = (\n typeof Set !== 'undefined' &&\n isSetToString(new Set())\n);\nfunction isSet(value) {\n if (typeof Set === 'undefined') {\n return false;\n }\n\n return isSetToString.working\n ? isSetToString(value)\n : value instanceof Set;\n}\nexports.isSet = isSet;\n\nfunction isWeakMapToString(value) {\n return ObjectToString(value) === '[object WeakMap]';\n}\nisWeakMapToString.working = (\n typeof WeakMap !== 'undefined' &&\n isWeakMapToString(new WeakMap())\n);\nfunction isWeakMap(value) {\n if (typeof WeakMap === 'undefined') {\n return false;\n }\n\n return isWeakMapToString.working\n ? isWeakMapToString(value)\n : value instanceof WeakMap;\n}\nexports.isWeakMap = isWeakMap;\n\nfunction isWeakSetToString(value) {\n return ObjectToString(value) === '[object WeakSet]';\n}\nisWeakSetToString.working = (\n typeof WeakSet !== 'undefined' &&\n isWeakSetToString(new WeakSet())\n);\nfunction isWeakSet(value) {\n return isWeakSetToString(value);\n}\nexports.isWeakSet = isWeakSet;\n\nfunction isArrayBufferToString(value) {\n return ObjectToString(value) === '[object ArrayBuffer]';\n}\nisArrayBufferToString.working = (\n typeof ArrayBuffer !== 'undefined' &&\n isArrayBufferToString(new ArrayBuffer())\n);\nfunction isArrayBuffer(value) {\n if (typeof ArrayBuffer === 'undefined') {\n return false;\n }\n\n return isArrayBufferToString.working\n ? isArrayBufferToString(value)\n : value instanceof ArrayBuffer;\n}\nexports.isArrayBuffer = isArrayBuffer;\n\nfunction isDataViewToString(value) {\n return ObjectToString(value) === '[object DataView]';\n}\nisDataViewToString.working = (\n typeof ArrayBuffer !== 'undefined' &&\n typeof DataView !== 'undefined' &&\n isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1))\n);\nfunction isDataView(value) {\n if (typeof DataView === 'undefined') {\n return false;\n }\n\n return isDataViewToString.working\n ? isDataViewToString(value)\n : value instanceof DataView;\n}\nexports.isDataView = isDataView;\n\n// Store a copy of SharedArrayBuffer in case it's deleted elsewhere\nvar SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined;\nfunction isSharedArrayBufferToString(value) {\n return ObjectToString(value) === '[object SharedArrayBuffer]';\n}\nfunction isSharedArrayBuffer(value) {\n if (typeof SharedArrayBufferCopy === 'undefined') {\n return false;\n }\n\n if (typeof isSharedArrayBufferToString.working === 'undefined') {\n isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy());\n }\n\n return isSharedArrayBufferToString.working\n ? isSharedArrayBufferToString(value)\n : value instanceof SharedArrayBufferCopy;\n}\nexports.isSharedArrayBuffer = isSharedArrayBuffer;\n\nfunction isAsyncFunction(value) {\n return ObjectToString(value) === '[object AsyncFunction]';\n}\nexports.isAsyncFunction = isAsyncFunction;\n\nfunction isMapIterator(value) {\n return ObjectToString(value) === '[object Map Iterator]';\n}\nexports.isMapIterator = isMapIterator;\n\nfunction isSetIterator(value) {\n return ObjectToString(value) === '[object Set Iterator]';\n}\nexports.isSetIterator = isSetIterator;\n\nfunction isGeneratorObject(value) {\n return ObjectToString(value) === '[object Generator]';\n}\nexports.isGeneratorObject = isGeneratorObject;\n\nfunction isWebAssemblyCompiledModule(value) {\n return ObjectToString(value) === '[object WebAssembly.Module]';\n}\nexports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule;\n\nfunction isNumberObject(value) {\n return checkBoxedPrimitive(value, numberValue);\n}\nexports.isNumberObject = isNumberObject;\n\nfunction isStringObject(value) {\n return checkBoxedPrimitive(value, stringValue);\n}\nexports.isStringObject = isStringObject;\n\nfunction isBooleanObject(value) {\n return checkBoxedPrimitive(value, booleanValue);\n}\nexports.isBooleanObject = isBooleanObject;\n\nfunction isBigIntObject(value) {\n return BigIntSupported && checkBoxedPrimitive(value, bigIntValue);\n}\nexports.isBigIntObject = isBigIntObject;\n\nfunction isSymbolObject(value) {\n return SymbolSupported && checkBoxedPrimitive(value, symbolValue);\n}\nexports.isSymbolObject = isSymbolObject;\n\nfunction isBoxedPrimitive(value) {\n return (\n isNumberObject(value) ||\n isStringObject(value) ||\n isBooleanObject(value) ||\n isBigIntObject(value) ||\n isSymbolObject(value)\n );\n}\nexports.isBoxedPrimitive = isBoxedPrimitive;\n\nfunction isAnyArrayBuffer(value) {\n return typeof Uint8Array !== 'undefined' && (\n isArrayBuffer(value) ||\n isSharedArrayBuffer(value)\n );\n}\nexports.isAnyArrayBuffer = isAnyArrayBuffer;\n\n['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) {\n Object.defineProperty(exports, method, {\n enumerable: false,\n value: function() {\n throw new Error(method + ' is not supported in userland');\n }\n });\n});\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||\n function getOwnPropertyDescriptors(obj) {\n var keys = Object.keys(obj);\n var descriptors = {};\n for (var i = 0; i < keys.length; i++) {\n descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);\n }\n return descriptors;\n };\n\nvar formatRegExp = /%[sdj%]/g;\nexports.format = function(f) {\n if (!isString(f)) {\n var objects = [];\n for (var i = 0; i < arguments.length; i++) {\n objects.push(inspect(arguments[i]));\n }\n return objects.join(' ');\n }\n\n var i = 1;\n var args = arguments;\n var len = args.length;\n var str = String(f).replace(formatRegExp, function(x) {\n if (x === '%%') return '%';\n if (i >= len) return x;\n switch (x) {\n case '%s': return String(args[i++]);\n case '%d': return Number(args[i++]);\n case '%j':\n try {\n return JSON.stringify(args[i++]);\n } catch (_) {\n return '[Circular]';\n }\n default:\n return x;\n }\n });\n for (var x = args[i]; i < len; x = args[++i]) {\n if (isNull(x) || !isObject(x)) {\n str += ' ' + x;\n } else {\n str += ' ' + inspect(x);\n }\n }\n return str;\n};\n\n\n// Mark that a method should not be used.\n// Returns a modified function which warns once by default.\n// If --no-deprecation is set, then it is a no-op.\nexports.deprecate = function(fn, msg) {\n if (typeof process !== 'undefined' && process.noDeprecation === true) {\n return fn;\n }\n\n // Allow for deprecating things in the process of starting up.\n if (typeof process === 'undefined') {\n return function() {\n return exports.deprecate(fn, msg).apply(this, arguments);\n };\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (process.throwDeprecation) {\n throw new Error(msg);\n } else if (process.traceDeprecation) {\n console.trace(msg);\n } else {\n console.error(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n};\n\n\nvar debugs = {};\nvar debugEnvRegex = /^$/;\n\nif (process.env.NODE_DEBUG) {\n var debugEnv = process.env.NODE_DEBUG;\n debugEnv = debugEnv.replace(/[|\\\\{}()[\\]^$+?.]/g, '\\\\$&')\n .replace(/\\*/g, '.*')\n .replace(/,/g, '$|^')\n .toUpperCase();\n debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i');\n}\nexports.debuglog = function(set) {\n set = set.toUpperCase();\n if (!debugs[set]) {\n if (debugEnvRegex.test(set)) {\n var pid = process.pid;\n debugs[set] = function() {\n var msg = exports.format.apply(exports, arguments);\n console.error('%s %d: %s', set, pid, msg);\n };\n } else {\n debugs[set] = function() {};\n }\n }\n return debugs[set];\n};\n\n\n/**\n * Echos the value of a value. Trys to print the value out\n * in the best way possible given the different types.\n *\n * @param {Object} obj The object to print out.\n * @param {Object} opts Optional options object that alters the output.\n */\n/* legacy: obj, showHidden, depth, colors*/\nfunction inspect(obj, opts) {\n // default options\n var ctx = {\n seen: [],\n stylize: stylizeNoColor\n };\n // legacy...\n if (arguments.length >= 3) ctx.depth = arguments[2];\n if (arguments.length >= 4) ctx.colors = arguments[3];\n if (isBoolean(opts)) {\n // legacy...\n ctx.showHidden = opts;\n } else if (opts) {\n // got an \"options\" object\n exports._extend(ctx, opts);\n }\n // set default options\n if (isUndefined(ctx.showHidden)) ctx.showHidden = false;\n if (isUndefined(ctx.depth)) ctx.depth = 2;\n if (isUndefined(ctx.colors)) ctx.colors = false;\n if (isUndefined(ctx.customInspect)) ctx.customInspect = true;\n if (ctx.colors) ctx.stylize = stylizeWithColor;\n return formatValue(ctx, obj, ctx.depth);\n}\nexports.inspect = inspect;\n\n\n// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\ninspect.colors = {\n 'bold' : [1, 22],\n 'italic' : [3, 23],\n 'underline' : [4, 24],\n 'inverse' : [7, 27],\n 'white' : [37, 39],\n 'grey' : [90, 39],\n 'black' : [30, 39],\n 'blue' : [34, 39],\n 'cyan' : [36, 39],\n 'green' : [32, 39],\n 'magenta' : [35, 39],\n 'red' : [31, 39],\n 'yellow' : [33, 39]\n};\n\n// Don't use 'blue' not visible on cmd.exe\ninspect.styles = {\n 'special': 'cyan',\n 'number': 'yellow',\n 'boolean': 'yellow',\n 'undefined': 'grey',\n 'null': 'bold',\n 'string': 'green',\n 'date': 'magenta',\n // \"name\": intentionally not styling\n 'regexp': 'red'\n};\n\n\nfunction stylizeWithColor(str, styleType) {\n var style = inspect.styles[styleType];\n\n if (style) {\n return '\\u001b[' + inspect.colors[style][0] + 'm' + str +\n '\\u001b[' + inspect.colors[style][1] + 'm';\n } else {\n return str;\n }\n}\n\n\nfunction stylizeNoColor(str, styleType) {\n return str;\n}\n\n\nfunction arrayToHash(array) {\n var hash = {};\n\n array.forEach(function(val, idx) {\n hash[val] = true;\n });\n\n return hash;\n}\n\n\nfunction formatValue(ctx, value, recurseTimes) {\n // Provide a hook for user-specified inspect functions.\n // Check that value is an object with an inspect function on it\n if (ctx.customInspect &&\n value &&\n isFunction(value.inspect) &&\n // Filter out the util module, it's inspect function is special\n value.inspect !== exports.inspect &&\n // Also filter out any prototype objects using the circular check.\n !(value.constructor && value.constructor.prototype === value)) {\n var ret = value.inspect(recurseTimes, ctx);\n if (!isString(ret)) {\n ret = formatValue(ctx, ret, recurseTimes);\n }\n return ret;\n }\n\n // Primitive types cannot have properties\n var primitive = formatPrimitive(ctx, value);\n if (primitive) {\n return primitive;\n }\n\n // Look up the keys of the object.\n var keys = Object.keys(value);\n var visibleKeys = arrayToHash(keys);\n\n if (ctx.showHidden) {\n keys = Object.getOwnPropertyNames(value);\n }\n\n // IE doesn't make error fields non-enumerable\n // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx\n if (isError(value)\n && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {\n return formatError(value);\n }\n\n // Some type of object without properties can be shortcutted.\n if (keys.length === 0) {\n if (isFunction(value)) {\n var name = value.name ? ': ' + value.name : '';\n return ctx.stylize('[Function' + name + ']', 'special');\n }\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n }\n if (isDate(value)) {\n return ctx.stylize(Date.prototype.toString.call(value), 'date');\n }\n if (isError(value)) {\n return formatError(value);\n }\n }\n\n var base = '', array = false, braces = ['{', '}'];\n\n // Make Array say that they are Array\n if (isArray(value)) {\n array = true;\n braces = ['[', ']'];\n }\n\n // Make functions say that they are functions\n if (isFunction(value)) {\n var n = value.name ? ': ' + value.name : '';\n base = ' [Function' + n + ']';\n }\n\n // Make RegExps say that they are RegExps\n if (isRegExp(value)) {\n base = ' ' + RegExp.prototype.toString.call(value);\n }\n\n // Make dates with properties first say the date\n if (isDate(value)) {\n base = ' ' + Date.prototype.toUTCString.call(value);\n }\n\n // Make error with message first say the error\n if (isError(value)) {\n base = ' ' + formatError(value);\n }\n\n if (keys.length === 0 && (!array || value.length == 0)) {\n return braces[0] + base + braces[1];\n }\n\n if (recurseTimes < 0) {\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n } else {\n return ctx.stylize('[Object]', 'special');\n }\n }\n\n ctx.seen.push(value);\n\n var output;\n if (array) {\n output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);\n } else {\n output = keys.map(function(key) {\n return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);\n });\n }\n\n ctx.seen.pop();\n\n return reduceToSingleString(output, base, braces);\n}\n\n\nfunction formatPrimitive(ctx, value) {\n if (isUndefined(value))\n return ctx.stylize('undefined', 'undefined');\n if (isString(value)) {\n var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"') + '\\'';\n return ctx.stylize(simple, 'string');\n }\n if (isNumber(value))\n return ctx.stylize('' + value, 'number');\n if (isBoolean(value))\n return ctx.stylize('' + value, 'boolean');\n // For some reason typeof null is \"object\", so special case here.\n if (isNull(value))\n return ctx.stylize('null', 'null');\n}\n\n\nfunction formatError(value) {\n return '[' + Error.prototype.toString.call(value) + ']';\n}\n\n\nfunction formatArray(ctx, value, recurseTimes, visibleKeys, keys) {\n var output = [];\n for (var i = 0, l = value.length; i < l; ++i) {\n if (hasOwnProperty(value, String(i))) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n String(i), true));\n } else {\n output.push('');\n }\n }\n keys.forEach(function(key) {\n if (!key.match(/^\\d+$/)) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n key, true));\n }\n });\n return output;\n}\n\n\nfunction formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {\n var name, str, desc;\n desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };\n if (desc.get) {\n if (desc.set) {\n str = ctx.stylize('[Getter/Setter]', 'special');\n } else {\n str = ctx.stylize('[Getter]', 'special');\n }\n } else {\n if (desc.set) {\n str = ctx.stylize('[Setter]', 'special');\n }\n }\n if (!hasOwnProperty(visibleKeys, key)) {\n name = '[' + key + ']';\n }\n if (!str) {\n if (ctx.seen.indexOf(desc.value) < 0) {\n if (isNull(recurseTimes)) {\n str = formatValue(ctx, desc.value, null);\n } else {\n str = formatValue(ctx, desc.value, recurseTimes - 1);\n }\n if (str.indexOf('\\n') > -1) {\n if (array) {\n str = str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n').substr(2);\n } else {\n str = '\\n' + str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n');\n }\n }\n } else {\n str = ctx.stylize('[Circular]', 'special');\n }\n }\n if (isUndefined(name)) {\n if (array && key.match(/^\\d+$/)) {\n return str;\n }\n name = JSON.stringify('' + key);\n if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n name = name.substr(1, name.length - 2);\n name = ctx.stylize(name, 'name');\n } else {\n name = name.replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"')\n .replace(/(^\"|\"$)/g, \"'\");\n name = ctx.stylize(name, 'string');\n }\n }\n\n return name + ': ' + str;\n}\n\n\nfunction reduceToSingleString(output, base, braces) {\n var numLinesEst = 0;\n var length = output.reduce(function(prev, cur) {\n numLinesEst++;\n if (cur.indexOf('\\n') >= 0) numLinesEst++;\n return prev + cur.replace(/\\u001b\\[\\d\\d?m/g, '').length + 1;\n }, 0);\n\n if (length > 60) {\n return braces[0] +\n (base === '' ? '' : base + '\\n ') +\n ' ' +\n output.join(',\\n ') +\n ' ' +\n braces[1];\n }\n\n return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n}\n\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\nexports.types = require('./support/types');\n\nfunction isArray(ar) {\n return Array.isArray(ar);\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return isObject(re) && objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\nexports.types.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return isObject(d) && objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\nexports.types.isDate = isDate;\n\nfunction isError(e) {\n return isObject(e) &&\n (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\nexports.types.isNativeError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('./support/isBuffer');\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\nfunction pad(n) {\n return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n 'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n var d = new Date();\n var time = [pad(d.getHours()),\n pad(d.getMinutes()),\n pad(d.getSeconds())].join(':');\n return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\n\n// log is just a thin wrapper to console.log that prepends a timestamp\nexports.log = function() {\n console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * The Function.prototype.inherits from lang.js rewritten as a standalone\n * function (not on Function.prototype). NOTE: If this file is to be loaded\n * during bootstrapping this function needs to be rewritten using some native\n * functions as prototype setup using normal JavaScript does not work as\n * expected during bootstrapping (see mirror.js in r114903).\n *\n * @param {function} ctor Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nexports.inherits = require('inherits');\n\nexports._extend = function(origin, add) {\n // Don't do anything if add isn't an object\n if (!add || !isObject(add)) return origin;\n\n var keys = Object.keys(add);\n var i = keys.length;\n while (i--) {\n origin[keys[i]] = add[keys[i]];\n }\n return origin;\n};\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nvar kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;\n\nexports.promisify = function promisify(original) {\n if (typeof original !== 'function')\n throw new TypeError('The \"original\" argument must be of type Function');\n\n if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {\n var fn = original[kCustomPromisifiedSymbol];\n if (typeof fn !== 'function') {\n throw new TypeError('The \"util.promisify.custom\" argument must be of type Function');\n }\n Object.defineProperty(fn, kCustomPromisifiedSymbol, {\n value: fn, enumerable: false, writable: false, configurable: true\n });\n return fn;\n }\n\n function fn() {\n var promiseResolve, promiseReject;\n var promise = new Promise(function (resolve, reject) {\n promiseResolve = resolve;\n promiseReject = reject;\n });\n\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n args.push(function (err, value) {\n if (err) {\n promiseReject(err);\n } else {\n promiseResolve(value);\n }\n });\n\n try {\n original.apply(this, args);\n } catch (err) {\n promiseReject(err);\n }\n\n return promise;\n }\n\n Object.setPrototypeOf(fn, Object.getPrototypeOf(original));\n\n if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {\n value: fn, enumerable: false, writable: false, configurable: true\n });\n return Object.defineProperties(\n fn,\n getOwnPropertyDescriptors(original)\n );\n}\n\nexports.promisify.custom = kCustomPromisifiedSymbol\n\nfunction callbackifyOnRejected(reason, cb) {\n // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).\n // Because `null` is a special error value in callbacks which means \"no error\n // occurred\", we error-wrap so the callback consumer can distinguish between\n // \"the promise rejected with null\" or \"the promise fulfilled with undefined\".\n if (!reason) {\n var newReason = new Error('Promise was rejected with a falsy value');\n newReason.reason = reason;\n reason = newReason;\n }\n return cb(reason);\n}\n\nfunction callbackify(original) {\n if (typeof original !== 'function') {\n throw new TypeError('The \"original\" argument must be of type Function');\n }\n\n // We DO NOT return the promise as it gives the user a false sense that\n // the promise is actually somehow related to the callback's execution\n // and that the callback throwing will reject the promise.\n function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) },\n function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) });\n }\n\n Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));\n Object.defineProperties(callbackified,\n getOwnPropertyDescriptors(original));\n return callbackified;\n}\nexports.callbackify = callbackify;\n","'use strict';\n\nvar forEach = require('foreach');\nvar availableTypedArrays = require('available-typed-arrays');\nvar callBound = require('call-bind/callBound');\n\nvar $toString = callBound('Object.prototype.toString');\nvar hasToStringTag = require('has-tostringtag/shams')();\n\nvar g = typeof globalThis === 'undefined' ? global : globalThis;\nvar typedArrays = availableTypedArrays();\n\nvar $slice = callBound('String.prototype.slice');\nvar toStrTags = {};\nvar gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor');\nvar getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');\nif (hasToStringTag && gOPD && getPrototypeOf) {\n\tforEach(typedArrays, function (typedArray) {\n\t\tif (typeof g[typedArray] === 'function') {\n\t\t\tvar arr = new g[typedArray]();\n\t\t\tif (Symbol.toStringTag in arr) {\n\t\t\t\tvar proto = getPrototypeOf(arr);\n\t\t\t\tvar descriptor = gOPD(proto, Symbol.toStringTag);\n\t\t\t\tif (!descriptor) {\n\t\t\t\t\tvar superProto = getPrototypeOf(proto);\n\t\t\t\t\tdescriptor = gOPD(superProto, Symbol.toStringTag);\n\t\t\t\t}\n\t\t\t\ttoStrTags[typedArray] = descriptor.get;\n\t\t\t}\n\t\t}\n\t});\n}\n\nvar tryTypedArrays = function tryAllTypedArrays(value) {\n\tvar foundName = false;\n\tforEach(toStrTags, function (getter, typedArray) {\n\t\tif (!foundName) {\n\t\t\ttry {\n\t\t\t\tvar name = getter.call(value);\n\t\t\t\tif (name === typedArray) {\n\t\t\t\t\tfoundName = name;\n\t\t\t\t}\n\t\t\t} catch (e) {}\n\t\t}\n\t});\n\treturn foundName;\n};\n\nvar isTypedArray = require('is-typed-array');\n\nmodule.exports = function whichTypedArray(value) {\n\tif (!isTypedArray(value)) { return false; }\n\tif (!hasToStringTag || !(Symbol.toStringTag in value)) { return $slice($toString(value), 8, -1); }\n\treturn tryTypedArrays(value);\n};\n","const os = require('os');\nconst fs = require('fs');\nconst path = require('path');\n\nconst rbql = require('./rbql_core/rbql-js/rbql.js');\nconst rbql_csv = require('./rbql_core/rbql-js/rbql_csv.js');\nconst csv_utils = require('./rbql_core/rbql-js/csv_utils.js');\n\nconst non_numeric_sentinel = -1;\nconst number_regex = /^([0-9]+)(\\.[0-9]+)?$/;\n\nclass AssertionError extends Error {}\n\nfunction assert(condition, message=null) {\n if (!condition) {\n if (!message) {\n message = 'Assertion error';\n }\n throw new AssertionError(message);\n }\n}\n\n\nfunction get_default_js_udf_content() {\n let default_content = `// This file can be used to store RBQL UDFs. Example:\n //\n // function foo(value) {\n // return 'foo ' + String(value.length);\n // }\n // \n // Functions defined in this file can be used in RBQL queries e.g. \n // SELECT foo(a1), a2 WHERE foo(a3) != 'foo 5' LIMIT 10\n //\n // Don't forget to save this file after editing!\n //\n // Write your own functions bellow this line:\n `.replace(new RegExp(/^ */, 'mg'), '');\n return default_content;\n}\n\n\nfunction get_default_python_udf_content() {\n let default_content = `# This file can be used to store RBQL UDFs. Example:\n #\n # def foo(value):\n # return 'foo ' + str(len(value))\n # \n # \n # Functions defined in this file can be used in RBQL queries e.g. \n # SELECT foo(a1), a2 WHERE foo(a3) != 'foo 5' LIMIT 10\n #\n # Don't forget to save this file after editing!\n #\n # Write your own functions bellow this line:\n `.replace(new RegExp(/^ */, 'mg'), '');\n return default_content;\n}\n\n\nfunction update_subcomponent_stats(field, is_first_line, max_field_components_lens) {\n // Extract overall field length and length of integer and fractional parts of the field if it represents a number.\n // Here `max_field_components_lens` is a tuple: (max_field_length, max_integer_part_length, max_fractional_part_length)\n if (field.length > max_field_components_lens[0]) {\n max_field_components_lens[0] = field.length;\n }\n if (max_field_components_lens[1] == non_numeric_sentinel) {\n // Column is not a number, early return.\n return;\n }\n let match_result = number_regex.exec(field);\n if (match_result === null) {\n if (!is_first_line && field.length) { // Checking field_length here allows numeric columns to have some of the fields empty.\n // We only mark the column as non-header if we know that this is not a header line.\n max_field_components_lens[1] = non_numeric_sentinel;\n max_field_components_lens[2] = non_numeric_sentinel;\n }\n return;\n }\n let cur_integer_part_length = match_result[1].length;\n max_field_components_lens[1] = Math.max(max_field_components_lens[1], cur_integer_part_length);\n let cur_fractional_part_length = match_result[2] === undefined ? 0 : match_result[2].length;\n max_field_components_lens[2] = Math.max(max_field_components_lens[2], cur_fractional_part_length);\n}\n\n\nfunction calc_column_stats(active_doc, delim, policy, comment_prefix) {\n let column_stats = [];\n let num_lines = active_doc.lineCount;\n let is_first_line = true;\n for (let lnum = 0; lnum < num_lines; lnum++) {\n let line_text = active_doc.lineAt(lnum).text;\n if (comment_prefix && line_text.startsWith(comment_prefix))\n continue;\n let [fields, warning] = csv_utils.smart_split(line_text, delim, policy, true);\n if (warning) {\n return [null, lnum + 1];\n }\n for (let fnum = 0; fnum < fields.length; fnum++) {\n let field = fields[fnum].trim();\n if (column_stats.length <= fnum) {\n column_stats.push([0, 0, 0]);\n }\n update_subcomponent_stats(field, is_first_line, column_stats[fnum]);\n }\n is_first_line = false;\n }\n return [column_stats, null];\n}\n\n\nfunction adjust_column_stats(column_stats) {\n // Ensure that numeric components max widths are consistent with non-numeric (header) width.\n let adjusted_stats = [];\n for (let column_stat of column_stats) {\n if (column_stat[1] <= 0) {\n column_stat[1] = -1;\n column_stat[2] = -1;\n }\n if (column_stat[1] > 0) {\n // The sum of integer and float parts can be bigger than the max width, e.g. here:\n // value\n // 0.12\n // 1234\n if (column_stat[1] + column_stat[2] > column_stat[0]) {\n column_stat[0] = column_stat[1] + column_stat[2];\n }\n // This is needed when the header is wider than numeric components and/or their sum.\n if (column_stat[0] - column_stat[2] > column_stat[1]) {\n column_stat[1] = column_stat[0] - column_stat[2];\n }\n // Sanity check.\n if (column_stat[0] != column_stat[1] + column_stat[2]) {\n // Assertion Error, this can never happen.\n return null;\n }\n }\n adjusted_stats.push(column_stat);\n }\n return adjusted_stats;\n}\n\n\nfunction align_field(field, is_first_line, max_field_components_lens, is_last_column) {\n // Align field, use Math.max() to avoid negative delta_length which can happen theorethically due to async doc edit.\n const extra_readability_whitespace_length = 1;\n field = field.trim();\n if (max_field_components_lens[1] == non_numeric_sentinel) {\n let delta_length = Math.max(max_field_components_lens[0] - field.length, 0);\n return is_last_column ? field : field + ' '.repeat(delta_length + extra_readability_whitespace_length);\n }\n if (is_first_line) {\n if (number_regex.exec(field) === null) {\n // The line must be a header - align it using max_width rule.\n let delta_length = Math.max(max_field_components_lens[0] - field.length, 0);\n return is_last_column ? field : field + ' '.repeat(delta_length + extra_readability_whitespace_length);\n }\n }\n let dot_pos = field.indexOf('.');\n let cur_integer_part_length = dot_pos == -1 ? field.length : dot_pos;\n // Here cur_fractional_part_length includes the leading dot too.\n let cur_fractional_part_length = dot_pos == -1 ? 0 : field.length - dot_pos;\n let integer_delta_length = Math.max(max_field_components_lens[1] - cur_integer_part_length, 0);\n let fractional_delta_length = Math.max(max_field_components_lens[2] - cur_fractional_part_length);\n let trailing_spaces = is_last_column ? '' : ' '.repeat(fractional_delta_length + extra_readability_whitespace_length);\n return ' '.repeat(integer_delta_length) + field + trailing_spaces;\n}\n\n\nfunction align_columns(active_doc, delim, policy, comment_prefix, column_stats) {\n let result_lines = [];\n let num_lines = active_doc.lineCount;\n let has_edit = false;\n let is_first_line = true;\n for (let lnum = 0; lnum < num_lines; lnum++) {\n let line_text = active_doc.lineAt(lnum).text;\n if (comment_prefix && line_text.startsWith(comment_prefix)) {\n result_lines.push(line_text);\n continue;\n }\n if (lnum + 1 == num_lines && line_text == '') {\n // Skip the last empty line which corresponds to the trailing newline character.\n result_lines.push(line_text);\n continue;\n }\n let fields = csv_utils.smart_split(line_text, delim, policy, true)[0];\n for (let fnum = 0; fnum < fields.length; fnum++) {\n if (fnum >= column_stats.length) // Safeguard against async doc edit, should never happen.\n break;\n let is_last_column = fnum + 1 == column_stats.length;\n let adjusted = align_field(fields[fnum], is_first_line, column_stats[fnum], is_last_column);\n if (fields[fnum] != adjusted) {\n fields[fnum] = adjusted;\n has_edit = true;\n }\n }\n is_first_line = false;\n result_lines.push(fields.join(delim));\n }\n if (!has_edit)\n return null;\n return result_lines.join('\\n');\n}\n\n\nfunction shrink_columns(active_doc, delim, policy, comment_prefix) {\n let result_lines = [];\n let num_lines = active_doc.lineCount;\n let has_edit = false;\n for (let lnum = 0; lnum < num_lines; lnum++) {\n let line_text = active_doc.lineAt(lnum).text;\n if (comment_prefix && line_text.startsWith(comment_prefix)) {\n result_lines.push(line_text);\n continue;\n }\n let [fields, warning] = csv_utils.smart_split(line_text, delim, policy, true);\n if (warning) {\n return [null, lnum + 1];\n }\n for (let i = 0; i < fields.length; i++) {\n let adjusted = fields[i].trim();\n if (fields[i].length != adjusted.length) {\n fields[i] = adjusted;\n has_edit = true;\n }\n }\n result_lines.push(fields.join(delim));\n }\n if (!has_edit)\n return [null, null];\n return [result_lines.join('\\n'), null];\n}\n\n\nfunction get_last(arr) {\n return arr[arr.length - 1];\n}\n\n\nfunction populate_optimistic_rfc_csv_record_map(document, requested_end_record, dst_record_map, comment_prefix=null) {\n let num_lines = document.lineCount;\n let record_begin = null;\n let start_line_idx = dst_record_map.length ? get_last(dst_record_map)[1] : 0;\n for (let lnum = start_line_idx; lnum < num_lines && dst_record_map.length < requested_end_record; ++lnum) {\n let line_text = document.lineAt(lnum).text;\n if (lnum + 1 >= num_lines && line_text == \"\")\n break; // Skip the last empty line.\n if (comment_prefix && line_text.startsWith(comment_prefix))\n continue;\n let match_list = line_text.match(/\"/g);\n let has_unbalanced_double_quote = match_list && match_list.length % 2 == 1;\n if (record_begin === null && !has_unbalanced_double_quote) {\n dst_record_map.push([lnum, lnum + 1]);\n } else if (record_begin === null && has_unbalanced_double_quote) {\n record_begin = lnum;\n } else if (!has_unbalanced_double_quote) {\n continue;\n } else {\n dst_record_map.push([record_begin, lnum + 1]);\n record_begin = null;\n }\n }\n if (record_begin !== null) {\n dst_record_map.push([record_begin, num_lines]);\n }\n}\n\n\nfunction make_table_name_key(file_path) {\n return 'rbql_table_name:' + file_path;\n}\n\n\nfunction expanduser(filepath) {\n if (filepath.charAt(0) === '~') {\n return path.join(os.homedir(), filepath.slice(1));\n }\n return filepath;\n}\n\n\nfunction find_table_path(vscode_global_state, main_table_dir, table_id) {\n // If table_id is a relative path it could be relative either to the current directory or to the main table dir.\n var candidate_path = expanduser(table_id);\n if (fs.existsSync(candidate_path)) {\n return candidate_path;\n }\n if (main_table_dir && !path.isAbsolute(candidate_path)) {\n candidate_path = path.join(main_table_dir, candidate_path);\n if (fs.existsSync(candidate_path)) {\n return candidate_path;\n }\n }\n let table_path = vscode_global_state ? vscode_global_state.get(make_table_name_key(table_id)) : null;\n if (table_path && fs.existsSync(table_path)) {\n return table_path;\n }\n return null;\n}\n\n\nasync function read_header(table_path, encoding) {\n if (encoding == 'latin-1')\n encoding = 'binary';\n let readline = require('readline');\n let input_reader = readline.createInterface({ input: fs.createReadStream(table_path, {encoding: encoding}) });\n let closed = false;\n let promise_resolve = null;\n let promise_reject = null;\n let output_promise = new Promise(function(resolve, reject) {\n promise_resolve = resolve;\n promise_reject = reject;\n });\n input_reader.on('line', line => {\n if (!closed) {\n closed = true;\n input_reader.close();\n promise_resolve(line);\n }\n });\n input_reader.on('error', error => {\n promise_reject(error);\n });\n return output_promise;\n}\n\n\nfunction get_header_line(document, comment_prefix) {\n const num_lines = document.lineCount;\n for (let lnum = 0; lnum < num_lines; ++lnum) {\n const line_text = document.lineAt(lnum).text;\n if (!comment_prefix || !line_text.startsWith(comment_prefix)) {\n return line_text;\n }\n }\n return null;\n}\n\n\nfunction make_inconsistent_num_fields_warning(table_name, inconsistent_records_info) {\n let keys = Object.keys(inconsistent_records_info);\n let entries = [];\n for (let i = 0; i < keys.length; i++) {\n let key = keys[i];\n let record_id = inconsistent_records_info[key];\n entries.push([record_id, key]);\n }\n entries.sort(function(a, b) { return a[0] - b[0]; });\n assert(entries.length > 1);\n let [record_1, num_fields_1] = entries[0];\n let [record_2, num_fields_2] = entries[1];\n let warn_msg = `Number of fields in \"${table_name}\" table is not consistent: `;\n warn_msg += `e.g. record ${record_1} -> ${num_fields_1} fields, record ${record_2} -> ${num_fields_2} fields`;\n return warn_msg;\n}\n\n\n\nclass RbqlIOHandlingError extends Error {}\n\nclass VSCodeRecordIterator extends rbql.RBQLInputIterator {\n constructor(document, delim, policy, has_header=false, comment_prefix=null, table_name='input', variable_prefix='a') {\n // We could have done a hack here actually: convert the document to stream/buffer and then use the standard reader.\n super();\n this.document = document;\n this.delim = delim;\n this.policy = policy;\n this.has_header = has_header;\n this.comment_prefix = comment_prefix;\n this.table_name = table_name;\n this.variable_prefix = variable_prefix;\n this.NR = 0; // Record number.\n this.NL = 0; // Line number (NL != NR when the CSV file has comments or multiline fields).\n this.fields_info = new Object();\n this.first_defective_line = null;\n this.first_record = this.get_first_record();\n }\n\n stop() {\n }\n\n get_first_record() {\n let header_line = get_header_line(this.document, this.comment_prefix);\n let first_record = csv_utils.smart_split(header_line, this.delim, this.policy, /*preserve_quotes_and_whitespaces=*/false)[0];\n return first_record;\n }\n\n async get_variables_map(query_text) {\n let variable_map = new Object();\n rbql.parse_basic_variables(query_text, this.variable_prefix, variable_map);\n rbql.parse_array_variables(query_text, this.variable_prefix, variable_map);\n let header_line = get_header_line(this.document, this.comment_prefix);\n let first_record = csv_utils.smart_split(header_line, this.delim, this.policy, /*preserve_quotes_and_whitespaces=*/false)[0];\n if (this.has_header) {\n rbql.parse_attribute_variables(query_text, this.variable_prefix, first_record, 'CSV header line', variable_map);\n rbql.parse_dictionary_variables(query_text, this.variable_prefix, first_record, variable_map);\n }\n return variable_map;\n }\n\n async get_header() {\n return this.has_header ? this.first_record : null;\n }\n\n get_line_rfc() {\n let rfc_line_buffer = [];\n const num_lines = this.document.lineCount;\n while (this.NL < num_lines) {\n let line = this.document.lineAt(this.NL).text;\n this.NL += 1;\n if (this.NL == num_lines && line.length == 0)\n return null; // Skip the last line if it is empty - this can happen due to trailing newline.\n let record_line = csv_utils.accumulate_rfc_line_into_record(rfc_line_buffer, line, this.comment_prefix);\n if (record_line !== null)\n return record_line;\n }\n return null;\n }\n\n get_line_simple() {\n const num_lines = this.document.lineCount;\n while (this.NL < num_lines) {\n let line = this.document.lineAt(this.NL).text;\n this.NL += 1;\n if (this.NL == num_lines && line.length == 0)\n return null; // Skip the last line if it is empty - this can happen due to trailing newline.\n if (this.comment_prefix === null || !line.startsWith(this.comment_prefix))\n return line;\n }\n return null;\n }\n\n do_get_record() {\n let line = (this.policy == 'quoted_rfc') ? this.get_line_rfc() : this.get_line_simple();\n if (line === null)\n return null;\n let [record, warning] = csv_utils.smart_split(line, this.delim, this.policy, /*preserve_quotes_and_whitespaces=*/false);\n if (warning) {\n if (this.first_defective_line === null) {\n this.first_defective_line = this.NL;\n if (this.policy == 'quoted_rfc')\n throw new RbqlIOHandlingError(`Inconsistent double quote escaping in ${this.table_name} table at record ${this.NR}, line ${this.NL}`);\n }\n }\n let num_fields = record.length;\n if (!this.fields_info.hasOwnProperty(num_fields))\n this.fields_info[num_fields] = this.NR;\n return record;\n }\n\n async get_record() {\n if (this.NR == 0 && this.has_header) {\n this.do_get_record(); // Skip the header record.\n }\n this.NR += 1;\n let record = this.do_get_record();\n return record;\n }\n\n get_warnings() {\n let result = [];\n if (this.first_defective_line !== null)\n result.push(`Inconsistent double quote escaping in ${this.table_name} table. E.g. at line ${this.first_defective_line}`);\n if (Object.keys(this.fields_info).length > 1)\n result.push(make_inconsistent_num_fields_warning(this.table_name, this.fields_info));\n return result;\n }\n}\n\n\nclass VSCodeWriter extends rbql.RBQLOutputWriter {\n constructor(delim, policy) {\n super();\n this.delim = delim;\n this.policy = policy;\n this.header_len = null;\n this.null_in_output = false;\n this.delim_in_simple_output = false;\n this.output_lines = [];\n\n if (policy == 'simple') {\n this.polymorphic_join = this.simple_join;\n } else if (policy == 'quoted') {\n this.polymorphic_join = this.quoted_join;\n } else if (policy == 'quoted_rfc') {\n this.polymorphic_join = this.quoted_join_rfc;\n } else if (policy == 'monocolumn') {\n this.polymorphic_join = this.mono_join;\n } else if (policy == 'whitespace') {\n this.polymorphic_join = this.simple_join;\n } else {\n throw new RbqlIOHandlingError('Unknown output csv policy');\n }\n }\n\n set_header(header) {\n if (header !== null) {\n this.header_len = header.length;\n this.write(header);\n }\n }\n\n quoted_join(fields) {\n let delim = this.delim;\n var quoted_fields = fields.map(function(v) { return csv_utils.quote_field(String(v), delim); });\n return quoted_fields.join(this.delim);\n };\n\n\n quoted_join_rfc(fields) {\n let delim = this.delim;\n var quoted_fields = fields.map(function(v) { return csv_utils.rfc_quote_field(String(v), delim); });\n return quoted_fields.join(this.delim);\n };\n\n\n mono_join(fields) {\n if (fields.length > 1) {\n throw new RbqlIOHandlingError('Unable to use \"Monocolumn\" output format: some records have more than one field');\n }\n return fields[0];\n };\n\n\n simple_join(fields) {\n var res = fields.join(this.delim);\n if (fields.join('').indexOf(this.delim) != -1) {\n this.delim_in_simple_output = true;\n }\n return res;\n };\n\n\n normalize_fields(out_fields) {\n for (var i = 0; i < out_fields.length; i++) {\n if (out_fields[i] == null) {\n this.null_in_output = true;\n out_fields[i] = '';\n } else if (Array.isArray(out_fields[i])) {\n this.normalize_fields(out_fields[i]);\n out_fields[i] = out_fields[i].join(this.sub_array_delim);\n }\n }\n };\n\n\n write(fields) {\n if (this.header_len !== null && fields.length != this.header_len)\n throw new RbqlIOHandlingError(`Inconsistent number of columns in output header and the current record: ${this.header_len} != ${fields.length}`);\n this.normalize_fields(fields);\n this.output_lines.push(this.polymorphic_join(fields));\n return true;\n };\n\n async finish() {\n }\n\n get_warnings() {\n let result = [];\n if (this.null_in_output)\n result.push('null values in output were replaced by empty strings');\n if (this.delim_in_simple_output)\n result.push('Some output fields contain separator');\n return result;\n };\n}\n\nclass VSCodeTableRegistry {\n constructor(){}\n\n get_iterator_by_table_id(_table_id) {\n throw new RbqlIOHandlingError(\"JOIN queries are currently not supported in vscode.dev web version.\");\n }\n\n get_warnings() {\n return [];\n };\n}\n\nasync function rbql_query_web(query_text, input_document, input_delim, input_policy, output_delim, output_policy, output_warnings, with_headers, comment_prefix=null) {\n let user_init_code = ''; // TODO find a way to have init code.\n let join_tables_registry = new VSCodeTableRegistry(); // TODO find a way to have join registry.\n let input_iterator = new VSCodeRecordIterator(input_document, input_delim, input_policy, with_headers, comment_prefix);\n let output_writer = new VSCodeWriter(output_delim, output_policy);\n await rbql.query(query_text, input_iterator, output_writer, output_warnings, join_tables_registry, user_init_code);\n return output_writer.output_lines;\n}\n\n\nclass VSCodeFileSystemCSVRegistry extends rbql.RBQLTableRegistry {\n constructor(vscode_global_state, input_file_dir, delim, policy, encoding, has_header=false, comment_prefix=null, options=null) {\n super();\n this.vscode_global_state = vscode_global_state;\n this.input_file_dir = input_file_dir;\n this.delim = delim;\n this.policy = policy;\n this.encoding = encoding;\n this.has_header = has_header;\n this.comment_prefix = comment_prefix;\n this.stream = null;\n this.record_iterator = null;\n\n this.options = options;\n this.bulk_input_path = null;\n this.table_path = null;\n }\n\n get_iterator_by_table_id(table_id) {\n this.table_path = find_table_path(this.vscode_global_state, this.input_file_dir, table_id);\n if (this.table_path === null) {\n throw new RbqlIOHandlingError(`Unable to find join table \"${table_id}\"`);\n }\n if (this.options && this.options['bulk_read']) {\n this.bulk_input_path = this.table_path;\n } else {\n this.stream = fs.createReadStream(this.table_path);\n }\n this.record_iterator = new rbql_csv.CSVRecordIterator(this.stream, this.bulk_input_path, this.encoding, this.delim, this.policy, this.has_header, this.comment_prefix, table_id, 'b');\n return this.record_iterator;\n };\n\n get_warnings(output_warnings) {\n if (this.record_iterator && this.has_header) {\n output_warnings.push(`The first record in JOIN file ${path.basename(this.table_path)} was also treated as header (and skipped)`);\n }\n }\n}\n\n\nasync function rbql_query_node(vscode_global_state, query_text, input_path, input_delim, input_policy, output_path, output_delim, output_policy, csv_encoding, output_warnings, with_headers=false, comment_prefix=null, user_init_code='', options=null) {\n let input_stream = null;\n let bulk_input_path = null;\n if (options && options['bulk_read'] && input_path) {\n bulk_input_path = input_path;\n } else {\n input_stream = input_path === null ? process.stdin : fs.createReadStream(input_path);\n }\n let [output_stream, close_output_on_finish] = output_path === null ? [process.stdout, false] : [fs.createWriteStream(output_path), true];\n if (input_delim == '\"' && input_policy == 'quoted')\n throw new RbqlIOHandlingError('Double quote delimiter is incompatible with \"quoted\" policy');\n if (csv_encoding == 'latin-1')\n csv_encoding = 'binary';\n if (!rbql_csv.is_ascii(query_text) && csv_encoding == 'binary')\n throw new RbqlIOHandlingError('To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary');\n if ((!rbql_csv.is_ascii(input_delim) || !rbql_csv.is_ascii(output_delim)) && csv_encoding == 'binary')\n throw new RbqlIOHandlingError('To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary');\n\n let default_init_source_path = path.join(os.homedir(), '.rbql_init_source.js');\n if (user_init_code == '' && fs.existsSync(default_init_source_path)) {\n user_init_code = rbql_csv.read_user_init_code(default_init_source_path);\n }\n let input_file_dir = input_path ? path.dirname(input_path) : null;\n let join_tables_registry = new VSCodeFileSystemCSVRegistry(vscode_global_state, input_file_dir, input_delim, input_policy, csv_encoding, with_headers, comment_prefix, options);\n let input_iterator = new rbql_csv.CSVRecordIterator(input_stream, bulk_input_path, csv_encoding, input_delim, input_policy, with_headers, comment_prefix);\n let output_writer = new rbql_csv.CSVWriter(output_stream, close_output_on_finish, csv_encoding, output_delim, output_policy);\n\n await rbql.query(query_text, input_iterator, output_writer, output_warnings, join_tables_registry, user_init_code);\n join_tables_registry.get_warnings(output_warnings);\n}\n\n\nmodule.exports.make_table_name_key = make_table_name_key;\nmodule.exports.find_table_path = find_table_path;\nmodule.exports.read_header = read_header;\nmodule.exports.rbql_query_web = rbql_query_web;\nmodule.exports.rbql_query_node = rbql_query_node;\nmodule.exports.get_header_line = get_header_line;\nmodule.exports.populate_optimistic_rfc_csv_record_map = populate_optimistic_rfc_csv_record_map;\nmodule.exports.get_default_js_udf_content = get_default_js_udf_content;\nmodule.exports.get_default_python_udf_content = get_default_python_udf_content;\nmodule.exports.align_columns = align_columns;\nmodule.exports.shrink_columns = shrink_columns;\nmodule.exports.calc_column_stats = calc_column_stats;\nmodule.exports.adjust_column_stats = adjust_column_stats;\nmodule.exports.update_subcomponent_stats = update_subcomponent_stats;\nmodule.exports.align_field = align_field;\n","let field_regular_expression = '\"((?:[^\"]*\"\")*[^\"]*)\"';\nlet field_rgx = new RegExp('^' + field_regular_expression);\nlet field_rgx_external_whitespaces = new RegExp('^ *' + field_regular_expression + ' *');\n\n\n// TODO consider making this file (and rbql.js) both node and browser compatible: https://caolan.org/posts/writing_for_node_and_the_browser.html\n\n\nfunction split_lines(text) {\n return text.split(/\\r\\n|\\r|\\n/);\n}\n\n\nfunction extract_next_field(src, dlm, preserve_quotes_and_whitespaces, allow_external_whitespaces, cidx, result) {\n var warning = false;\n let src_cur = src.substring(cidx);\n let rgx = allow_external_whitespaces ? field_rgx_external_whitespaces : field_rgx;\n let match_obj = rgx.exec(src_cur);\n if (match_obj !== null) {\n let match_end = match_obj[0].length;\n if (cidx + match_end == src.length || src[cidx + match_end] == dlm) {\n if (preserve_quotes_and_whitespaces) {\n result.push(match_obj[0]);\n } else {\n result.push(match_obj[1].replace(/\"\"/g, '\"'));\n }\n return [cidx + match_end + 1, false];\n }\n warning = true;\n }\n var uidx = src.indexOf(dlm, cidx);\n if (uidx == -1)\n uidx = src.length;\n var field = src.substring(cidx, uidx);\n warning = warning || field.indexOf('\"') != -1;\n result.push(field);\n return [uidx + 1, warning];\n}\n\n\nfunction split_quoted_str(src, dlm, preserve_quotes_and_whitespaces=false) {\n // This function is newline-agnostic i.e. it can also split records with multiline fields.\n if (src.indexOf('\"') == -1) // Optimization for most common case\n return [src.split(dlm), false];\n var result = [];\n var cidx = 0;\n var warning = false;\n let allow_external_whitespaces = dlm != ' ';\n while (cidx < src.length) {\n var extraction_report = extract_next_field(src, dlm, preserve_quotes_and_whitespaces, allow_external_whitespaces, cidx, result);\n cidx = extraction_report[0];\n warning = warning || extraction_report[1];\n }\n if (src.charAt(src.length - 1) == dlm)\n result.push('');\n return [result, warning];\n}\n\n\nfunction quote_field(src, delim) {\n if (src.indexOf(delim) != -1 || src.indexOf('\"') != -1) {\n var escaped = src.replace(/\"/g, '\"\"');\n return `\"${escaped}\"`;\n }\n return src;\n}\n\n\nfunction rfc_quote_field(src, delim) {\n if (src.indexOf(delim) != -1 || src.indexOf('\"') != -1 || src.indexOf('\\n') != -1 || src.indexOf('\\r') != -1) {\n var escaped = src.replace(/\"/g, '\"\"');\n return `\"${escaped}\"`;\n }\n return src;\n}\n\n\nfunction unquote_field(field) {\n let rgx = new RegExp('^' + ' *' + field_regular_expression + ' *$');\n let match_obj = rgx.exec(field);\n if (match_obj !== null) {\n return match_obj[1].replace(/\"\"/g, '\"');\n }\n return field;\n}\n\n\nfunction unquote_fields(fields) {\n return fields.map(unquote_field);\n}\n\n\nfunction split_whitespace_separated_str(src, preserve_whitespaces=false) {\n var rgxp = preserve_whitespaces ? new RegExp(' *[^ ]+ *', 'g') : new RegExp('[^ ]+', 'g');\n let result = [];\n let match_obj = null;\n while((match_obj = rgxp.exec(src)) !== null) {\n result.push(match_obj[0]);\n }\n if (preserve_whitespaces) {\n for (let i = 0; i < result.length - 1; i++) {\n result[i] = result[i].slice(0, -1);\n }\n }\n return result;\n}\n\n\nfunction smart_split(src, dlm, policy, preserve_quotes_and_whitespaces) {\n if (policy === 'simple')\n return [src.split(dlm), false];\n if (policy === 'whitespace')\n return [split_whitespace_separated_str(src, preserve_quotes_and_whitespaces), false];\n if (policy === 'monocolumn')\n return [[src], false];\n return split_quoted_str(src, dlm, preserve_quotes_and_whitespaces);\n}\n\n\nfunction accumulate_rfc_line_into_record(external_rfc_line_buffer, current_line, comment_prefix=null) {\n // Return null if the current line yields no record.\n // Return a record string if the current line yields the record and cleans the external line buffer.\n if (comment_prefix !== null && external_rfc_line_buffer.length == 0 && current_line.startsWith(comment_prefix))\n return null;\n let match_list = current_line.match(/\"/g);\n let has_unbalanced_double_quote = match_list && match_list.length % 2 == 1;\n if (external_rfc_line_buffer.length == 0 && !has_unbalanced_double_quote) {\n return current_line;\n } else if (external_rfc_line_buffer.length == 0 && has_unbalanced_double_quote) {\n external_rfc_line_buffer.push(current_line);\n } else if (!has_unbalanced_double_quote) {\n external_rfc_line_buffer.push(current_line);\n } else {\n external_rfc_line_buffer.push(current_line);\n let multiline_row = external_rfc_line_buffer.join('\\n');\n external_rfc_line_buffer.splice(0, external_rfc_line_buffer.length); // Cleanup the external buffer.\n return multiline_row;\n }\n return null;\n}\n\n\nmodule.exports.split_quoted_str = split_quoted_str;\nmodule.exports.split_whitespace_separated_str = split_whitespace_separated_str;\nmodule.exports.smart_split = smart_split;\nmodule.exports.quote_field = quote_field;\nmodule.exports.rfc_quote_field = rfc_quote_field;\nmodule.exports.unquote_field = unquote_field;\nmodule.exports.unquote_fields = unquote_fields;\nmodule.exports.split_lines = split_lines;\nmodule.exports.accumulate_rfc_line_into_record = accumulate_rfc_line_into_record;\n","(function(exports){\n// The magic line above is to make the module both browser and Node compatible, see https://stackoverflow.com/questions/3225251/how-can-i-share-code-between-node-js-and-the-browser\n\n// This module works with records only. It is CSV-agnostic.\n// Do not add CSV-related logic or variables/functions/objects like \"delim\", \"separator\" etc\n\n\nclass RbqlParsingError extends Error {}\nclass RbqlRuntimeError extends Error {}\nclass AssertionError extends Error {}\nclass RbqlIOHandlingError extends Error {}\n\n\nclass InternalBadFieldError extends Error {\n constructor(bad_idx, ...params) {\n super(...params);\n this.bad_idx = bad_idx;\n }\n}\n\n\nfunction assert(condition, message=null) {\n if (!condition) {\n if (!message) {\n message = 'Assertion error';\n }\n throw new AssertionError(message);\n }\n}\n\n\nfunction replace_all(src, search, replacement) {\n return src.split(search).join(replacement);\n}\n\n\nclass RBQLContext {\n constructor(query_text, input_iterator, output_writer, user_init_code) {\n this.query_text = query_text;\n this.input_iterator = input_iterator;\n this.writer = output_writer;\n this.user_init_code = user_init_code;\n\n this.unnest_list = null;\n this.top_count = null;\n\n this.like_regex_cache = new Map();\n\n this.sort_key_expression = null;\n\n this.aggregation_stage = 0;\n this.aggregation_key_expression = null;\n this.functional_aggregators = [];\n\n this.join_map_impl = null;\n this.join_map = null;\n this.lhs_join_var_expression = null;\n\n this.where_expression = null;\n\n this.select_expression = null;\n\n this.update_expressions = null;\n\n this.variables_init_code = null;\n }\n}\n\nvar query_context = null; // Needs to be global for MIN(), MAX(), etc functions. TODO find a way to make it local.\n\n\nconst wrong_aggregation_usage_error = 'Usage of RBQL aggregation functions inside JavaScript expressions is not allowed, see the docs';\nconst RBQL_VERSION = '0.25.0';\n\n\nfunction check_if_brackets_match(opening_bracket, closing_bracket) {\n return (opening_bracket == '[' && closing_bracket == ']') || (opening_bracket == '(' && closing_bracket == ')') || (opening_bracket == '{' && closing_bracket == '}');\n}\n\n\nfunction parse_root_bracket_level_text_spans(select_expression) {\n let text_spans = []; // parts of text separated by commas at the root parenthesis level\n let last_pos = 0;\n let bracket_stack = [];\n for (let i = 0; i < select_expression.length; i++) {\n let cur_char = select_expression[i];\n if (cur_char == ',' && bracket_stack.length == 0) {\n text_spans.push(select_expression.substring(last_pos, i));\n last_pos = i + 1;\n } else if (['[', '{', '('].indexOf(cur_char) != -1) {\n bracket_stack.push(cur_char);\n } else if ([']', '}', ')'].indexOf(cur_char) != -1) {\n if (bracket_stack.length && check_if_brackets_match(bracket_stack[bracket_stack.length - 1], cur_char)) {\n bracket_stack.pop();\n } else {\n throw new RbqlParsingError(`Unable to parse column headers in SELECT expression: No matching opening bracket for closing \"${cur_char}\"`);\n }\n }\n }\n if (bracket_stack.length) {\n throw new RbqlParsingError(`Unable to parse column headers in SELECT expression: No matching closing bracket for opening \"${bracket_stack[0]}\"`);\n }\n text_spans.push(select_expression.substring(last_pos, select_expression.length));\n text_spans = text_spans.map(span => span.trim());\n return text_spans;\n}\n\n\nfunction unquote_string(quoted_str) {\n // It's possible to use eval here to unqoute the quoted_column_name, but it would be a little barbaric, let's do it manually instead\n if (!quoted_str || quoted_str.length < 2)\n return null;\n if (quoted_str[0] == \"'\" && quoted_str[quoted_str.length - 1] == \"'\") {\n return quoted_str.substring(1, quoted_str.length - 1).replace(/\\\\'/g, \"'\").replace(/\\\\\\\\/g, \"\\\\\");\n } else if (quoted_str[0] == '\"' && quoted_str[quoted_str.length - 1] == '\"') {\n return quoted_str.substring(1, quoted_str.length - 1).replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, \"\\\\\");\n } else {\n return null;\n }\n}\n\n\nfunction column_info_from_text_span(text_span, string_literals) {\n // This function is a rough equivalent of \"column_info_from_node()\" function in python version of RBQL\n text_span = text_span.trim();\n let rbql_star_marker = '__RBQL_INTERNAL_STAR';\n let simple_var_match = /^[_a-zA-Z][_a-zA-Z0-9]*$/.exec(text_span);\n let attribute_match = /^([ab])\\.([_a-zA-Z][_a-zA-Z0-9]*)$/.exec(text_span);\n let subscript_int_match = /^([ab])\\[([0-9]+)\\]$/.exec(text_span);\n let subscript_str_match = /^([ab])\\[___RBQL_STRING_LITERAL([0-9]+)___\\]$/.exec(text_span);\n if (simple_var_match !== null) {\n if (text_span == rbql_star_marker)\n return {table_name: null, column_index: null, column_name: null, is_star: true};\n if (text_span.startsWith('___RBQL_STRING_LITERAL'))\n return null;\n let match = /^([ab])([0-9]+)$/.exec(text_span);\n if (match !== null) {\n return {table_name: match[1], column_index: parseInt(match[2]) - 1, column_name: null, is_star: false};\n }\n // Some examples for this branch: NR, NF\n return {table_name: null, column_index: null, column_name: text_span, is_star: false};\n } else if (attribute_match !== null) {\n let table_name = attribute_match[1];\n let column_name = attribute_match[2];\n if (column_name == rbql_star_marker) {\n return {table_name: table_name, column_index: null, column_name: null, is_star: true};\n }\n return {table_name: null, column_index: null, column_name: column_name, is_star: false};\n } else if (subscript_int_match != null) {\n let table_name = subscript_int_match[1];\n let column_index = parseInt(subscript_int_match[2]) - 1;\n return {table_name: table_name, column_index: column_index, column_name: null, is_star: false};\n } else if (subscript_str_match != null) {\n let table_name = subscript_str_match[1];\n let replaced_string_literal_id = subscript_str_match[2];\n if (replaced_string_literal_id < string_literals.length) {\n let quoted_column_name = string_literals[replaced_string_literal_id];\n let unquoted_column_name = unquote_string(quoted_column_name);\n if (unquoted_column_name !== null && unquoted_column_name !== undefined) {\n return {table_name: null, column_index: null, column_name: unquoted_column_name, is_star: false};\n }\n }\n }\n return null;\n}\n\n\nfunction adhoc_parse_select_expression_to_column_infos(select_expression, string_literals) {\n // It is acceptable for the algorithm to provide null column name when it could be theorethically possible to deduce the name.\n // I.e. this algorithm guarantees precision but doesn't guarantee completeness in all theorethically possible queries.\n // Although the algorithm should be complete in all practical scenarios, i.e. it should be hard to come up with the query that doesn't produce complete set of column names.\n // The null column name just means that the output column will be named as col{i}, so the failure to detect the proper column name can be tolerated.\n // Specifically this function guarantees the following:\n // 1. The number of column_infos is correct and will match the number of fields in each record in the output - otherwise the exception should be thrown\n // 2. If column_info at pos j is not null, it is guaranteed to correctly represent that column name in the output\n let text_spans = parse_root_bracket_level_text_spans(select_expression);\n let column_infos = text_spans.map(ts => column_info_from_text_span(ts, string_literals));\n return column_infos;\n}\n\n\nfunction stable_compare(a, b) {\n for (var i = 0; i < a.length; i++) {\n if (a[i] !== b[i])\n return a[i] < b[i] ? -1 : 1;\n }\n}\n\n\nfunction safe_get(record, idx) {\n return idx < record.length ? record[idx] : null;\n}\n\n\nfunction safe_join_get(record, idx) {\n if (idx < record.length) {\n return record[idx];\n }\n throw new InternalBadFieldError(idx);\n}\n\n\nfunction safe_set(record, idx, value) {\n if (idx < record.length) {\n record[idx] = value;\n } else {\n throw new InternalBadFieldError(idx);\n }\n}\n\n\nfunction regexp_escape(text) {\n // From here: https://stackoverflow.com/a/6969486/2898283\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); // $& means the whole matched text\n}\n\n\nfunction like_to_regex(pattern) {\n let p = 0;\n let i = 0;\n let converted = '';\n while (i < pattern.length) {\n if (pattern.charAt(i) == '_' || pattern.charAt(i) == '%') {\n converted += regexp_escape(pattern.substring(p, i));\n p = i + 1;\n if (pattern.charAt(i) == '_') {\n converted += '.';\n } else {\n converted += '.*';\n }\n }\n i += 1;\n }\n converted += regexp_escape(pattern.substring(p, i));\n return '^' + converted + '$';\n}\n\n\nfunction like(text, pattern) {\n let matcher = query_context.like_regex_cache.get(pattern);\n if (matcher === undefined) {\n matcher = new RegExp(like_to_regex(pattern));\n query_context.like_regex_cache.set(pattern, matcher);\n }\n return matcher.test(text);\n}\nconst LIKE = like;\n\n\nclass RBQLAggregationToken {\n constructor(marker_id, value) {\n this.marker_id = marker_id;\n this.value = value;\n }\n\n toString() {\n throw new RbqlParsingError(wrong_aggregation_usage_error);\n }\n}\n\n\nclass UnnestMarker {}\n\n\nfunction UNNEST(vals) {\n if (query_context.unnest_list !== null) {\n // Technically we can support multiple UNNEST's but the implementation/algorithm is more complex and just doesn't worth it\n throw new RbqlParsingError('Only one UNNEST is allowed per query');\n }\n query_context.unnest_list = vals;\n return new UnnestMarker();\n}\nconst unnest = UNNEST;\nconst Unnest = UNNEST;\nconst UNFOLD = UNNEST; // \"UNFOLD\" is deprecated, just for backward compatibility\n\n\nfunction parse_number(val) {\n // We can do a more pedantic number test like `/^ *-{0,1}[0-9]+\\.{0,1}[0-9]* *$/.test(val)`, but user will probably use just Number(val) or parseInt/parseFloat\n let result = Number(val);\n if (isNaN(result)) {\n throw new RbqlRuntimeError(`Unable to convert value \"${val}\" to a number. MIN, MAX, SUM, AVG, MEDIAN and VARIANCE aggregate functions convert their string arguments to numeric values`);\n }\n return result;\n}\n\n\nclass MinAggregator {\n constructor() {\n this.stats = new Map();\n }\n\n increment(key, val) {\n val = parse_number(val);\n var cur_aggr = this.stats.get(key);\n if (cur_aggr === undefined) {\n this.stats.set(key, val);\n } else {\n this.stats.set(key, Math.min(cur_aggr, val));\n }\n }\n\n get_final(key) {\n return this.stats.get(key);\n }\n}\n\n\n\nclass MaxAggregator {\n constructor() {\n this.stats = new Map();\n }\n\n increment(key, val) {\n val = parse_number(val);\n var cur_aggr = this.stats.get(key);\n if (cur_aggr === undefined) {\n this.stats.set(key, val);\n } else {\n this.stats.set(key, Math.max(cur_aggr, val));\n }\n }\n\n get_final(key) {\n return this.stats.get(key);\n }\n}\n\n\nclass SumAggregator {\n constructor() {\n this.stats = new Map();\n }\n\n increment(key, val) {\n val = parse_number(val);\n var cur_aggr = this.stats.get(key);\n if (cur_aggr === undefined) {\n this.stats.set(key, val);\n } else {\n this.stats.set(key, cur_aggr + val);\n }\n }\n\n get_final(key) {\n return this.stats.get(key);\n }\n}\n\n\nclass AvgAggregator {\n constructor() {\n this.stats = new Map();\n }\n\n increment(key, val) {\n val = parse_number(val);\n var cur_aggr = this.stats.get(key);\n if (cur_aggr === undefined) {\n this.stats.set(key, [val, 1]);\n } else {\n var cur_sum = cur_aggr[0];\n var cur_cnt = cur_aggr[1];\n this.stats.set(key, [cur_sum + val, cur_cnt + 1]);\n }\n }\n\n get_final(key) {\n var cur_aggr = this.stats.get(key);\n var cur_sum = cur_aggr[0];\n var cur_cnt = cur_aggr[1];\n var avg = cur_sum / cur_cnt;\n return avg;\n }\n}\n\n\nclass VarianceAggregator {\n constructor() {\n this.stats = new Map();\n }\n\n increment(key, val) {\n val = parse_number(val);\n var cur_aggr = this.stats.get(key);\n if (cur_aggr === undefined) {\n this.stats.set(key, [val, val * val, 1]);\n } else {\n var cur_sum = cur_aggr[0];\n var cur_sum_sq = cur_aggr[1];\n var cur_cnt = cur_aggr[2];\n this.stats.set(key, [cur_sum + val, cur_sum_sq + val * val, cur_cnt + 1]);\n }\n }\n\n get_final(key) {\n var cur_aggr = this.stats.get(key);\n var cur_sum = cur_aggr[0];\n var cur_sum_sq = cur_aggr[1];\n var cur_cnt = cur_aggr[2];\n var avg_val = cur_sum / cur_cnt;\n var variance = cur_sum_sq / cur_cnt - avg_val * avg_val;\n return variance;\n }\n}\n\n\nclass MedianAggregator {\n constructor() {\n this.stats = new Map();\n }\n\n increment(key, val) {\n val = parse_number(val);\n var cur_aggr = this.stats.get(key);\n if (cur_aggr === undefined) {\n this.stats.set(key, [val]);\n } else {\n cur_aggr.push(val);\n }\n }\n\n get_final(key) {\n var cur_aggr = this.stats.get(key);\n cur_aggr.sort(function(a, b) { return a - b; });\n var m = Math.floor(cur_aggr.length / 2);\n if (cur_aggr.length % 2) {\n return cur_aggr[m];\n } else {\n return (cur_aggr[m - 1] + cur_aggr[m]) / 2.0;\n }\n }\n}\n\n\nclass CountAggregator {\n constructor() {\n this.stats = new Map();\n }\n\n increment(key, val) {\n var cur_aggr = this.stats.get(key);\n if (cur_aggr === undefined) {\n this.stats.set(key, 1);\n } else {\n this.stats.set(key, cur_aggr + 1);\n }\n }\n\n get_final(key) {\n return this.stats.get(key);\n }\n}\n\n\nclass ArrayAggAggregator {\n constructor(post_proc=null) {\n this.post_proc = post_proc;\n this.stats = new Map();\n }\n\n increment(key, val) {\n let cur_aggr = this.stats.get(key);\n if (cur_aggr === undefined) {\n this.stats.set(key, [val]);\n } else {\n cur_aggr.push(val);\n }\n }\n\n get_final(key) {\n let cur_aggr = this.stats.get(key);\n if (this.post_proc === null)\n return cur_aggr;\n return this.post_proc(cur_aggr);\n }\n}\n\n\nclass ConstGroupVerifier {\n constructor(output_index) {\n this.output_index = output_index;\n this.const_values = new Map();\n }\n\n increment(key, value) {\n var old_value = this.const_values.get(key);\n if (old_value === undefined) {\n this.const_values.set(key, value);\n } else if (old_value != value) {\n throw new RbqlRuntimeError(`Invalid aggregate expression: non-constant values in output column ${this.output_index + 1}. E.g. \"${old_value}\" and \"${value}\"`);\n }\n }\n\n get_final(key) {\n return this.const_values.get(key);\n }\n}\n\n\nfunction init_aggregator(generator_name, val, post_proc=null) {\n query_context.aggregation_stage = 1;\n var res = new RBQLAggregationToken(query_context.functional_aggregators.length, val);\n if (post_proc === null) {\n query_context.functional_aggregators.push(new generator_name());\n } else {\n query_context.functional_aggregators.push(new generator_name(post_proc));\n }\n return res;\n}\n\n\nfunction MIN(val) {\n return query_context.aggregation_stage < 2 ? init_aggregator(MinAggregator, val) : val;\n}\nconst min = MIN;\nconst Min = MIN;\n\n\nfunction MAX(val) {\n return query_context.aggregation_stage < 2 ? init_aggregator(MaxAggregator, val) : val;\n}\nconst max = MAX;\nconst Max = MAX;\n\nfunction COUNT(val) {\n return query_context.aggregation_stage < 2 ? init_aggregator(CountAggregator, 1) : 1;\n}\nconst count = COUNT;\nconst Count = COUNT;\n\nfunction SUM(val) {\n return query_context.aggregation_stage < 2 ? init_aggregator(SumAggregator, val) : val;\n}\nconst sum = SUM;\nconst Sum = SUM;\n\nfunction AVG(val) {\n return query_context.aggregation_stage < 2 ? init_aggregator(AvgAggregator, val) : val;\n}\nconst avg = AVG;\nconst Avg = AVG;\n\nfunction VARIANCE(val) {\n return query_context.aggregation_stage < 2 ? init_aggregator(VarianceAggregator, val) : val;\n}\nconst variance = VARIANCE;\nconst Variance = VARIANCE;\n\nfunction MEDIAN(val) {\n return query_context.aggregation_stage < 2 ? init_aggregator(MedianAggregator, val) : val;\n}\nconst median = MEDIAN;\nconst Median = MEDIAN;\n\nfunction ARRAY_AGG(val, post_proc=null) {\n return query_context.aggregation_stage < 2 ? init_aggregator(ArrayAggAggregator, val, post_proc) : val;\n}\nconst array_agg = ARRAY_AGG;\nconst FOLD = ARRAY_AGG; // \"FOLD\" is deprecated, just for backward compatibility\n\n\nfunction add_to_set(dst_set, value) {\n var len_before = dst_set.size;\n dst_set.add(value);\n return len_before != dst_set.size;\n}\n\n\nclass TopWriter {\n constructor(subwriter, top_count) {\n this.subwriter = subwriter;\n this.NW = 0;\n this.top_count = top_count;\n }\n\n async write(record) {\n if (this.top_count !== null && this.NW >= this.top_count)\n return false;\n await this.subwriter.write(record);\n this.NW += 1;\n return true;\n }\n\n async finish() {\n await this.subwriter.finish();\n }\n}\n\n\nclass UniqWriter {\n constructor(subwriter) {\n this.subwriter = subwriter;\n this.seen = new Set();\n }\n\n async write(record) {\n if (!add_to_set(this.seen, JSON.stringify(record)))\n return true;\n if (!await this.subwriter.write(record))\n return false;\n return true;\n }\n\n async finish() {\n await this.subwriter.finish();\n }\n}\n\n\nclass UniqCountWriter {\n constructor(subwriter) {\n this.subwriter = subwriter;\n this.records = new Map();\n }\n\n async write(record) {\n var key = JSON.stringify(record);\n var old_val = this.records.get(key);\n if (old_val) {\n old_val[0] += 1;\n } else {\n this.records.set(key, [1, record]);\n }\n return true;\n }\n\n async finish() {\n for (var [key, value] of this.records) {\n let [count, record] = value;\n record.unshift(count);\n if (!await this.subwriter.write(record))\n break;\n }\n await this.subwriter.finish();\n }\n}\n\n\nclass SortedWriter {\n constructor(subwriter, reverse_sort) {\n this.subwriter = subwriter;\n this.reverse_sort = reverse_sort;\n this.unsorted_entries = [];\n }\n\n async write(stable_entry) {\n this.unsorted_entries.push(stable_entry);\n return true;\n }\n\n async finish() {\n var unsorted_entries = this.unsorted_entries;\n unsorted_entries.sort(stable_compare);\n if (this.reverse_sort)\n unsorted_entries.reverse();\n for (var i = 0; i < unsorted_entries.length; i++) {\n var entry = unsorted_entries[i];\n if (!await this.subwriter.write(entry[entry.length - 1]))\n break;\n }\n await this.subwriter.finish();\n }\n}\n\n\nclass AggregateWriter {\n constructor(subwriter) {\n this.subwriter = subwriter;\n this.aggregators = [];\n this.aggregation_keys = new Set();\n }\n\n async finish() {\n var all_keys = Array.from(this.aggregation_keys);\n all_keys.sort();\n for (var i = 0; i < all_keys.length; i++) {\n var key = all_keys[i];\n var out_fields = [];\n for (var ag of this.aggregators) {\n out_fields.push(ag.get_final(key));\n }\n if (!await this.subwriter.write(out_fields))\n break;\n }\n await this.subwriter.finish();\n }\n}\n\n\nclass InnerJoiner {\n constructor(join_map) {\n this.join_map = join_map;\n }\n\n get_rhs(lhs_key) {\n return this.join_map.get_join_records(lhs_key);\n }\n}\n\n\nclass LeftJoiner {\n constructor(join_map) {\n this.join_map = join_map;\n this.null_record = [[null, join_map.max_record_len, Array(join_map.max_record_len).fill(null)]];\n }\n\n get_rhs(lhs_key) {\n let result = this.join_map.get_join_records(lhs_key);\n if (result.length == 0) {\n return this.null_record;\n }\n return result;\n }\n}\n\n\nclass StrictLeftJoiner {\n constructor(join_map) {\n this.join_map = join_map;\n }\n\n get_rhs(lhs_key) {\n let result = this.join_map.get_join_records(lhs_key);\n if (result.length != 1) {\n throw new RbqlRuntimeError('In \"STRICT LEFT JOIN\" each key in A must have exactly one match in B. Bad A key: \"' + lhs_key + '\"');\n }\n return result;\n }\n}\n\n\nfunction select_except(src, except_fields) {\n let result = [];\n for (let i = 0; i < src.length; i++) {\n if (except_fields.indexOf(i) == -1)\n result.push(src[i]);\n }\n return result;\n}\n\n\nasync function select_simple(sort_key, NR, out_fields) {\n if (query_context.sort_key_expression !== null) {\n var sort_entry = sort_key.concat([NR, out_fields]);\n if (!await query_context.writer.write(sort_entry))\n return false;\n } else {\n if (!await query_context.writer.write(out_fields))\n return false;\n }\n return true;\n}\n\n\nfunction select_aggregated(key, transparent_values) {\n if (key !== null) {\n key = JSON.stringify(key);\n }\n if (query_context.aggregation_stage === 1) {\n if (!(query_context.writer instanceof TopWriter)) {\n throw new RbqlParsingError('\"ORDER BY\", \"UPDATE\" and \"DISTINCT\" keywords are not allowed in aggregate queries');\n }\n query_context.writer = new AggregateWriter(query_context.writer);\n let num_aggregators_found = 0;\n for (var i = 0; i < transparent_values.length; i++) {\n var trans_value = transparent_values[i];\n if (trans_value instanceof RBQLAggregationToken) {\n query_context.writer.aggregators.push(query_context.functional_aggregators[trans_value.marker_id]);\n query_context.writer.aggregators[query_context.writer.aggregators.length - 1].increment(key, trans_value.value);\n num_aggregators_found += 1;\n } else {\n query_context.writer.aggregators.push(new ConstGroupVerifier(query_context.writer.aggregators.length));\n query_context.writer.aggregators[query_context.writer.aggregators.length - 1].increment(key, trans_value);\n }\n }\n if (num_aggregators_found != query_context.functional_aggregators.length) {\n throw new RbqlParsingError(wrong_aggregation_usage_error);\n }\n query_context.aggregation_stage = 2;\n } else {\n for (var i = 0; i < transparent_values.length; i++) {\n var trans_value = transparent_values[i];\n query_context.writer.aggregators[i].increment(key, trans_value);\n }\n }\n query_context.writer.aggregation_keys.add(key);\n}\n\n\nasync function select_unnested(sort_key, NR, folded_fields) {\n let out_fields = folded_fields.slice();\n let unnest_pos = folded_fields.findIndex(val => val instanceof UnnestMarker);\n for (var i = 0; i < query_context.unnest_list.length; i++) {\n out_fields[unnest_pos] = query_context.unnest_list[i];\n if (!await select_simple(sort_key, NR, out_fields.slice()))\n return false;\n }\n return true;\n}\n\n\nconst PROCESS_SELECT_COMMON = `\n__RBQLMP__variables_init_code\nif (__RBQLMP__where_expression) {\n let out_fields = __RBQLMP__select_expression;\n if (query_context.aggregation_stage > 0) {\n let key = __RBQLMP__aggregation_key_expression;\n select_aggregated(key, out_fields);\n } else {\n let sort_key = [__RBQLMP__sort_key_expression];\n if (query_context.unnest_list !== null) {\n if (!await select_unnested(sort_key, NR, out_fields))\n stop_flag = true;\n } else {\n if (!await select_simple(sort_key, NR, out_fields))\n stop_flag = true;\n }\n }\n}\n`;\n\n\nconst PROCESS_SELECT_SIMPLE = `\nlet star_fields = record_a;\n__CODE__\n`;\n\n\nconst PROCESS_SELECT_JOIN = `\nlet join_matches = query_context.join_map.get_rhs(__RBQLMP__lhs_join_var_expression);\nfor (let join_match of join_matches) {\n let [bNR, bNF, record_b] = join_match;\n let star_fields = record_a.concat(record_b);\n __CODE__\n if (stop_flag)\n break;\n}\n`;\n\n\nconst PROCESS_UPDATE_JOIN = `\nlet join_matches = query_context.join_map.get_rhs(__RBQLMP__lhs_join_var_expression);\nif (join_matches.length > 1)\n throw new RbqlRuntimeError('More than one record in UPDATE query matched a key from the input table in the join table');\nlet record_b = null;\nlet bNR = null;\nlet bNF = null;\nif (join_matches.length == 1)\n [bNR, bNF, record_b] = join_matches[0];\nlet up_fields = record_a;\n__RBQLMP__variables_init_code\nif (join_matches.length == 1 && (__RBQLMP__where_expression)) {\n NU += 1;\n __RBQLMP__update_expressions\n}\nif (!await query_context.writer.write(up_fields))\n stop_flag = true;\n`;\n\n\nconst PROCESS_UPDATE_SIMPLE = `\nlet up_fields = record_a;\n__RBQLMP__variables_init_code\nif (__RBQLMP__where_expression) {\n NU += 1;\n __RBQLMP__update_expressions\n}\nif (!await query_context.writer.write(up_fields))\n stop_flag = true;\n`;\n\n\nconst MAIN_LOOP_BODY = `\n__USER_INIT_CODE__\n\nlet NU = 0;\nlet NR = 0;\n\nlet stop_flag = false;\nwhile (!stop_flag) {\n let record_a = await query_context.input_iterator.get_record();\n if (record_a === null)\n break;\n NR += 1;\n let NF = record_a.length;\n query_context.unnest_list = null; // TODO optimize, don't need to set this every iteration\n try {\n __CODE__\n } catch (e) {\n if (e.constructor.name === 'InternalBadFieldError') {\n throw new RbqlRuntimeError(\\`No \"a\\${e.bad_idx + 1}\" field at record \\${NR}\\`);\n } else if (e.constructor.name === 'RbqlParsingError') {\n throw(e);\n } else {\n throw new RbqlRuntimeError(\\`At record \\${NR}, Details: \\${e.message}\\`);\n }\n }\n}\n`;\n\n\nfunction embed_expression(parent_code, child_placeholder, child_expression) {\n return replace_all(parent_code, child_placeholder, child_expression);\n}\n\n\nfunction embed_code(parent_code, child_placeholder, child_code) {\n let parent_lines = parent_code.split('\\n');\n let child_lines = child_code.split('\\n');\n for (let i = 0; i < parent_lines.length; i++) {\n let pos = parent_lines[i].indexOf(child_placeholder);\n if (pos == -1)\n continue;\n assert(pos % 4 == 0);\n let placeholder_indentation = parent_lines[i].substring(0, pos);\n child_lines = child_lines.map(l => placeholder_indentation + l);\n let result_lines = parent_lines.slice(0, i).concat(child_lines).concat(parent_lines.slice(i + 1));\n return result_lines.join('\\n') + '\\n';\n }\n assert(false);\n}\n\n\nfunction generate_main_loop_code(query_context) {\n let is_select_query = query_context.select_expression !== null;\n let is_join_query = query_context.join_map !== null;\n let where_expression = query_context.where_expression === null ? 'true' : query_context.where_expression;\n let aggregation_key_expression = query_context.aggregation_key_expression === null ? 'null' : query_context.aggregation_key_expression;\n let sort_key_expression = query_context.sort_key_expression === null ? 'null' : query_context.sort_key_expression;\n let js_code = embed_code(MAIN_LOOP_BODY, '__USER_INIT_CODE__', query_context.user_init_code);\n if (is_select_query) {\n if (is_join_query) {\n js_code = embed_code(embed_code(js_code, '__CODE__', PROCESS_SELECT_JOIN), '__CODE__', PROCESS_SELECT_COMMON);\n js_code = embed_expression(js_code, '__RBQLMP__lhs_join_var_expression', query_context.lhs_join_var_expression);\n } else {\n js_code = embed_code(embed_code(js_code, '__CODE__', PROCESS_SELECT_SIMPLE), '__CODE__', PROCESS_SELECT_COMMON);\n }\n js_code = embed_code(js_code, '__RBQLMP__variables_init_code', query_context.variables_init_code);\n js_code = embed_expression(js_code, '__RBQLMP__select_expression', query_context.select_expression);\n js_code = embed_expression(js_code, '__RBQLMP__where_expression', where_expression);\n js_code = embed_expression(js_code, '__RBQLMP__aggregation_key_expression', aggregation_key_expression);\n js_code = embed_expression(js_code, '__RBQLMP__sort_key_expression', sort_key_expression);\n } else {\n if (is_join_query) {\n js_code = embed_code(js_code, '__CODE__', PROCESS_UPDATE_JOIN);\n js_code = embed_expression(js_code, '__RBQLMP__lhs_join_var_expression', query_context.lhs_join_var_expression);\n } else {\n js_code = embed_code(js_code, '__CODE__', PROCESS_UPDATE_SIMPLE);\n }\n js_code = embed_code(js_code, '__RBQLMP__variables_init_code', query_context.variables_init_code);\n js_code = embed_code(js_code, '__RBQLMP__update_expressions', query_context.update_expressions);\n js_code = embed_expression(js_code, '__RBQLMP__where_expression', where_expression);\n }\n return \"(async () => {\" + js_code + \"})()\";\n}\n\n\nasync function compile_and_run(query_context) {\n let main_loop_body = generate_main_loop_code(query_context);\n try {\n let main_loop_promise = eval(main_loop_body);\n await main_loop_promise;\n } catch (e) {\n if (e instanceof SyntaxError) {\n // SyntaxError's from eval() function do not contain detailed explanation of what has caused the syntax error, so to guess what was wrong we can only use the original query\n // v8 issue to fix eval: https://bugs.chromium.org/p/v8/issues/detail?id=2589\n let lower_case_query = query_context.query_text.toLowerCase();\n if (lower_case_query.indexOf(' having ') != -1)\n throw new SyntaxError(e.message + \"\\nRBQL doesn't support \\\"HAVING\\\" keyword\");\n if (lower_case_query.indexOf(' like ') != -1)\n throw new SyntaxError(e.message + \"\\nRBQL doesn't support \\\"LIKE\\\" operator, use like() function instead e.g. ... WHERE like(a1, 'foo%bar') ... \"); // UT JSON\n if (lower_case_query.indexOf(' from ') != -1)\n throw new SyntaxError(e.message + \"\\nTip: If input table is defined by the environment, RBQL query should not have \\\"FROM\\\" keyword\"); // UT JSON\n if (e && e.message && String(e.message).toLowerCase().indexOf('unexpected identifier') != -1) {\n if (lower_case_query.indexOf(' and ') != -1)\n throw new SyntaxError(e.message + \"\\nDid you use 'and' keyword in your query?\\nJavaScript backend doesn't support 'and' keyword, use '&&' operator instead!\");\n if (lower_case_query.indexOf(' or ') != -1)\n throw new SyntaxError(e.message + \"\\nDid you use 'or' keyword in your query?\\nJavaScript backend doesn't support 'or' keyword, use '||' operator instead!\");\n }\n }\n if (e && e.message && e.message.indexOf('Received an instance of RBQLAggregationToken') != -1)\n throw new RbqlParsingError(wrong_aggregation_usage_error);\n throw e;\n }\n}\n\n\nconst GROUP_BY = 'GROUP BY';\nconst UPDATE = 'UPDATE';\nconst SELECT = 'SELECT';\nconst JOIN = 'JOIN';\nconst INNER_JOIN = 'INNER JOIN';\nconst LEFT_JOIN = 'LEFT JOIN';\nconst LEFT_OUTER_JOIN = 'LEFT OUTER JOIN';\nconst STRICT_LEFT_JOIN = 'STRICT LEFT JOIN';\nconst ORDER_BY = 'ORDER BY';\nconst WHERE = 'WHERE';\nconst LIMIT = 'LIMIT';\nconst EXCEPT = 'EXCEPT';\nconst WITH = 'WITH';\n\n\nfunction get_ambiguous_error_msg(variable_name) {\n return `Ambiguous variable name: \"${variable_name}\" is present both in input and in join tables`;\n}\n\n\nfunction get_all_matches(regexp, text) {\n var result = [];\n let match_obj = null;\n while((match_obj = regexp.exec(text)) !== null) {\n result.push(match_obj);\n }\n return result;\n}\n\n\nfunction str_strip(src) {\n return src.replace(/^ +| +$/g, '');\n}\n\n\nfunction strip_comments(cline) {\n cline = cline.trim();\n if (cline.startsWith('//'))\n return '';\n return cline;\n}\n\n\nfunction combine_string_literals(backend_expression, string_literals) {\n for (var i = 0; i < string_literals.length; i++) {\n backend_expression = replace_all(backend_expression, `___RBQL_STRING_LITERAL${i}___`, string_literals[i]);\n }\n return backend_expression;\n}\n\n\nfunction parse_basic_variables(query_text, prefix, dst_variables_map) {\n assert(prefix == 'a' || prefix == 'b');\n let rgx = new RegExp(`(?:^|[^_a-zA-Z0-9])${prefix}([1-9][0-9]*)(?:$|(?=[^_a-zA-Z0-9]))`, 'g');\n let matches = get_all_matches(rgx, query_text);\n for (let i = 0; i < matches.length; i++) {\n let field_num = parseInt(matches[i][1]);\n dst_variables_map[prefix + String(field_num)] = {initialize: true, index: field_num - 1};\n }\n}\n\n\nfunction parse_array_variables(query_text, prefix, dst_variables_map) {\n assert(prefix == 'a' || prefix == 'b');\n let rgx = new RegExp(`(?:^|[^_a-zA-Z0-9])${prefix}\\\\[([1-9][0-9]*)\\\\]`, 'g');\n let matches = get_all_matches(rgx, query_text);\n for (let i = 0; i < matches.length; i++) {\n let field_num = parseInt(matches[i][1]);\n dst_variables_map[`${prefix}[${field_num}]`] = {initialize: true, index: field_num - 1};\n }\n}\n\n\nfunction js_string_escape_column_name(column_name, quote_char) {\n column_name = column_name.replace(/\\\\/g, '\\\\\\\\');\n column_name = column_name.replace(/\\n/g, '\\\\n');\n column_name = column_name.replace(/\\r/g, '\\\\r');\n column_name = column_name.replace(/\\t/g, '\\\\t');\n if (quote_char === \"'\")\n return column_name.replace(/'/g, \"\\\\'\");\n if (quote_char === '\"')\n return column_name.replace(/\"/g, '\\\\\"');\n assert(quote_char === \"`\");\n return column_name.replace(/`/g, \"\\\\`\");\n}\n\n\nfunction query_probably_has_dictionary_variable(query_text, column_name) {\n let rgx = new RegExp('[-a-zA-Z0-9_:;+=!.,()%^#@&* ]+', 'g');\n let continuous_name_segments = get_all_matches(rgx, column_name);\n for (let continuous_segment of continuous_name_segments) {\n if (query_text.indexOf(continuous_segment) == -1)\n return false;\n }\n return true;\n}\n\n\nfunction parse_dictionary_variables(query_text, prefix, column_names, dst_variables_map) {\n // The purpose of this algorithm is to minimize number of variables in varibale_map to improve performance, ideally it should be only variables from the query\n\n // FIXME to prevent typos in attribute names either use query-based variable parsing which can properly handle back-tick strings or wrap \"a\" and \"b\" variables with ES6 Proxies https://stackoverflow.com/a/25658975/2898283\n assert(prefix === 'a' || prefix === 'b');\n let dict_test_rgx = new RegExp(`(?:^|[^_a-zA-Z0-9])${prefix}\\\\[`);\n if (query_text.search(dict_test_rgx) == -1)\n return;\n for (let i = 0; i < column_names.length; i++) {\n let column_name = column_names[i];\n if (query_probably_has_dictionary_variable(query_text, column_name)) {\n let escaped_column_name = js_string_escape_column_name(column_name, '\"');\n dst_variables_map[`${prefix}[\"${escaped_column_name}\"]`] = {initialize: true, index: i};\n escaped_column_name = js_string_escape_column_name(column_name, \"'\");\n dst_variables_map[`${prefix}['${escaped_column_name}']`] = {initialize: false, index: i};\n escaped_column_name = js_string_escape_column_name(column_name, \"`\");\n dst_variables_map[`${prefix}[\\`${escaped_column_name}\\`]`] = {initialize: false, index: i};\n }\n }\n}\n\n\nfunction parse_attribute_variables(query_text, prefix, column_names, column_names_source, dst_variables_map) {\n // The purpose of this algorithm is to minimize number of variables in varibale_map to improve performance, ideally it should be only variables from the query\n\n assert(prefix === 'a' || prefix === 'b');\n let rgx = new RegExp(`(?:^|[^_a-zA-Z0-9])${prefix}\\\\.([_a-zA-Z][_a-zA-Z0-9]*)`, 'g');\n let matches = get_all_matches(rgx, query_text);\n let column_names_from_query = matches.map(v => v[1]);\n for (let column_name of column_names_from_query) {\n let zero_based_idx = column_names.indexOf(column_name);\n if (zero_based_idx != -1) {\n dst_variables_map[`${prefix}.${column_name}`] = {initialize: true, index: zero_based_idx};\n } else {\n throw new RbqlParsingError(`Unable to find column \"${column_name}\" in ${prefix == 'a' ? 'input' : 'join'} ${column_names_source}`);\n }\n }\n}\n\n\nfunction map_variables_directly(query_text, column_names, dst_variables_map) {\n for (let i = 0; i < column_names.length; i++) {\n let column_name = column_names[i];\n if ( /^[_a-zA-Z][_a-zA-Z0-9]*$/.exec(column_name) === null)\n throw new RbqlIOHandlingError(`Unable to use column name \"${column_name}\" as RBQL/JS variable`);\n if (query_text.indexOf(column_name) != -1)\n dst_variables_map[column_name] = {initialize: true, index: i};\n }\n}\n\n\nfunction ensure_no_ambiguous_variables(query_text, input_column_names, join_column_names) {\n let join_column_names_set = new Set(join_column_names);\n for (let column_name of input_column_names) {\n if (join_column_names_set.has(column_name) && query_text.indexOf(column_name) != -1) // False positive is tolerable here\n throw new RbqlParsingError(get_ambiguous_error_msg(column_name));\n }\n}\n\n\nfunction parse_join_expression(src) {\n src = str_strip(src);\n const invalid_join_syntax_error = 'Invalid join syntax. Valid syntax: /path/to/B/table on a... == b... [and a... == b... [and ... ]]';\n let rgx = /^ *([^ ]+) +on +/i;\n let match = rgx.exec(src);\n if (match === null)\n throw new RbqlParsingError(invalid_join_syntax_error);\n let table_id = match[1];\n src = src.substr(match[0].length);\n\n let variable_pairs = [];\n var pair_rgx = /^([^ =]+) *==? *([^ =]+)/;\n var and_rgx = /^ +(and|&&) +/i;\n while (true) {\n match = pair_rgx.exec(src);\n if (match === null)\n throw new RbqlParsingError(invalid_join_syntax_error);\n variable_pairs.push([match[1], match[2]]);\n src = src.substr(match[0].length);\n if (!src.length)\n break;\n match = and_rgx.exec(src);\n if (match === null)\n throw new RbqlParsingError(invalid_join_syntax_error);\n src = src.substr(match[0].length);\n }\n return [table_id, variable_pairs];\n}\n\n\nfunction resolve_join_variables(input_variables_map, join_variables_map, variable_pairs, string_literals) {\n let lhs_variables = [];\n let rhs_indices = [];\n const valid_join_syntax_msg = 'Valid JOIN syntax: /path/to/B/table on a... == b... [and a... == b... [and ... ]]';\n for (let variable_pair of variable_pairs) {\n let [join_var_1, join_var_2] = variable_pair;\n join_var_1 = combine_string_literals(join_var_1, string_literals);\n join_var_2 = combine_string_literals(join_var_2, string_literals);\n if (input_variables_map.hasOwnProperty(join_var_1) && join_variables_map.hasOwnProperty(join_var_1))\n throw new RbqlParsingError(get_ambiguous_error_msg(join_var_1));\n if (input_variables_map.hasOwnProperty(join_var_2) && join_variables_map.hasOwnProperty(join_var_2))\n throw new RbqlParsingError(get_ambiguous_error_msg(join_var_2));\n if (input_variables_map.hasOwnProperty(join_var_2))\n [join_var_1, join_var_2] = [join_var_2, join_var_1];\n\n let [lhs_key_index, rhs_key_index] = [null, null];\n if (['NR', 'a.NR', 'aNR'].indexOf(join_var_1) != -1) {\n lhs_key_index = -1;\n } else if (input_variables_map.hasOwnProperty(join_var_1)) {\n lhs_key_index = input_variables_map[join_var_1].index;\n } else {\n throw new RbqlParsingError(`Unable to parse JOIN expression: Input table does not have field \"${join_var_1}\"\\n${valid_join_syntax_msg}`);\n }\n\n if (['b.NR', 'bNR'].indexOf(join_var_2) != -1) {\n rhs_key_index = -1;\n } else if (join_variables_map.hasOwnProperty(join_var_2)) {\n rhs_key_index = join_variables_map[join_var_2].index;\n } else {\n throw new RbqlParsingError(`Unable to parse JOIN expression: Join table does not have field \"${join_var_2}\"\\n${valid_join_syntax_msg}`);\n }\n\n let lhs_join_var_expression = lhs_key_index == -1 ? 'NR' : `safe_join_get(record_a, ${lhs_key_index})`;\n rhs_indices.push(rhs_key_index);\n lhs_variables.push(lhs_join_var_expression);\n }\n return [lhs_variables, rhs_indices];\n}\n\n\nfunction generate_common_init_code(query_text, variable_prefix) {\n assert(variable_prefix == 'a' || variable_prefix == 'b');\n let result = [];\n result.push(`${variable_prefix} = new Object();`);\n let base_var = variable_prefix == 'a' ? 'NR' : 'bNR';\n let attr_var = `${variable_prefix}.NR`;\n if (query_text.indexOf(attr_var) != -1)\n result.push(`${attr_var} = ${base_var};`);\n if (variable_prefix == 'a' && query_text.indexOf('aNR') != -1)\n result.push('aNR = NR;');\n return result;\n}\n\n\nfunction generate_init_statements(query_text, variables_map, join_variables_map, indent) {\n let code_lines = generate_common_init_code(query_text, 'a');\n let simple_var_name_rgx = /^[_0-9a-zA-Z]+$/;\n for (const [variable_name, var_info] of Object.entries(variables_map)) {\n if (var_info.initialize) {\n let variable_declaration_keyword = simple_var_name_rgx.exec(variable_name) ? 'var ' : '';\n code_lines.push(`${variable_declaration_keyword}${variable_name} = safe_get(record_a, ${var_info.index});`);\n }\n }\n if (join_variables_map) {\n code_lines = code_lines.concat(generate_common_init_code(query_text, 'b'));\n for (const [variable_name, var_info] of Object.entries(join_variables_map)) {\n if (var_info.initialize) {\n let variable_declaration_keyword = simple_var_name_rgx.exec(variable_name) ? 'var ' : '';\n code_lines.push(`${variable_declaration_keyword}${variable_name} = record_b === null ? null : safe_get(record_b, ${var_info.index});`);\n }\n }\n }\n for (let i = 1; i < code_lines.length; i++) {\n code_lines[i] = indent + code_lines[i];\n }\n return code_lines.join('\\n');\n}\n\n\nfunction replace_star_count(aggregate_expression) {\n var rgx = /(^|,) *COUNT\\( *\\* *\\) *(?:$|(?=,))/ig;\n var result = aggregate_expression.replace(rgx, '$1 COUNT(1)');\n return str_strip(result);\n}\n\n\nfunction replace_star_vars(rbql_expression) {\n let star_rgx = /(?:^|,) *(\\*|a\\.\\*|b\\.\\*) *(?=$|,)/g;\n let matches = get_all_matches(star_rgx, rbql_expression);\n let last_pos = 0;\n let result = '';\n for (let match of matches) {\n let star_expression = match[1];\n let replacement_expression = ']).concat(' + {'*': 'star_fields', 'a.*': 'record_a', 'b.*': 'record_b'}[star_expression] + ').concat([';\n if (last_pos < match.index)\n result += rbql_expression.substring(last_pos, match.index);\n result += replacement_expression;\n last_pos = match.index + match[0].length + 1; // Adding one to skip the lookahead comma\n }\n result += rbql_expression.substring(last_pos);\n return result;\n}\n\n\nfunction replace_star_vars_for_header_parsing(rbql_expression) {\n let star_rgx = /(?:(?<=^)|(?<=,)) *(\\*|a\\.\\*|b\\.\\*) *(?=$|,)/g;\n let matches = get_all_matches(star_rgx, rbql_expression);\n let last_pos = 0;\n let result = '';\n for (let match of matches) {\n let star_expression = match[1];\n let replacement_expression = {'*': '__RBQL_INTERNAL_STAR', 'a.*': 'a.__RBQL_INTERNAL_STAR', 'b.*': 'b.__RBQL_INTERNAL_STAR'}[star_expression];\n if (last_pos < match.index)\n result += rbql_expression.substring(last_pos, match.index);\n result += replacement_expression;\n last_pos = match.index + match[0].length;\n }\n result += rbql_expression.substring(last_pos);\n return result;\n}\n\n\nfunction translate_update_expression(update_expression, input_variables_map, string_literals, indent) {\n let first_assignment = str_strip(update_expression.split('=')[0]);\n let first_assignment_error = `Unable to parse \"UPDATE\" expression: the expression must start with assignment, but \"${first_assignment}\" does not look like an assignable field name`;\n\n let assignment_looking_rgx = /(?:^|,) *(a[.#a-zA-Z0-9\\[\\]_]*) *=(?=[^=])/g;\n let update_expressions = [];\n let pos = 0;\n while (true) {\n let match = assignment_looking_rgx.exec(update_expression);\n if (update_expressions.length == 0 && (match === null || match.index != 0)) {\n throw new RbqlParsingError(first_assignment_error);\n }\n if (match === null) {\n update_expressions[update_expressions.length - 1] += str_strip(update_expression.substr(pos)) + ');';\n break;\n }\n if (update_expressions.length)\n update_expressions[update_expressions.length - 1] += str_strip(update_expression.substring(pos, match.index)) + ');';\n let dst_var_name = combine_string_literals(str_strip(match[1]), string_literals);\n if (!input_variables_map.hasOwnProperty(dst_var_name))\n throw new RbqlParsingError(`Unable to parse \"UPDATE\" expression: Unknown field name: \"${dst_var_name}\"`);\n let var_index = input_variables_map[dst_var_name].index;\n let current_indent = update_expressions.length ? indent : '';\n update_expressions.push(`${current_indent}safe_set(up_fields, ${var_index}, `);\n pos = match.index + match[0].length;\n }\n return combine_string_literals(update_expressions.join('\\n'), string_literals);\n}\n\n\nfunction translate_select_expression(select_expression) {\n let expression_without_stars = replace_star_count(select_expression);\n let translated = str_strip(replace_star_vars(expression_without_stars));\n let translated_for_header = str_strip(replace_star_vars_for_header_parsing(expression_without_stars));\n if (!translated.length)\n throw new RbqlParsingError('\"SELECT\" expression is empty');\n return [`[].concat([${translated}])`, translated_for_header];\n}\n\n\nfunction separate_string_literals(rbql_expression) {\n // The regex consists of 3 almost identicall parts, the only difference is quote type\n var rgx = /('(\\\\(\\\\\\\\)*'|[^'])*')|(\"(\\\\(\\\\\\\\)*\"|[^\"])*\")|(`(\\\\(\\\\\\\\)*`|[^`])*`)/g;\n var match_obj = null;\n var format_parts = [];\n var string_literals = [];\n var idx_before = 0;\n while((match_obj = rgx.exec(rbql_expression)) !== null) {\n var literal_id = string_literals.length;\n var string_literal = match_obj[0];\n string_literals.push(string_literal);\n var start_index = match_obj.index;\n format_parts.push(rbql_expression.substring(idx_before, start_index));\n format_parts.push(`___RBQL_STRING_LITERAL${literal_id}___`);\n idx_before = rgx.lastIndex;\n }\n format_parts.push(rbql_expression.substring(idx_before));\n var format_expression = format_parts.join('');\n format_expression = format_expression.replace(/\\t/g, ' ');\n return [format_expression, string_literals];\n}\n\n\nfunction locate_statements(rbql_expression) {\n let statement_groups = [];\n statement_groups.push([STRICT_LEFT_JOIN, LEFT_OUTER_JOIN, LEFT_JOIN, INNER_JOIN, JOIN]);\n statement_groups.push([SELECT]);\n statement_groups.push([ORDER_BY]);\n statement_groups.push([WHERE]);\n statement_groups.push([UPDATE]);\n statement_groups.push([GROUP_BY]);\n statement_groups.push([LIMIT]);\n statement_groups.push([EXCEPT]);\n var result = [];\n for (var ig = 0; ig < statement_groups.length; ig++) {\n for (var is = 0; is < statement_groups[ig].length; is++) {\n var statement = statement_groups[ig][is];\n var rgxp = new RegExp('(?:^| )' + replace_all(statement, ' ', ' *') + '(?= )', 'ig');\n var matches = get_all_matches(rgxp, rbql_expression);\n if (!matches.length)\n continue;\n if (matches.length > 1)\n throw new RbqlParsingError(`More than one \"${statement}\" statements found`);\n assert(matches.length == 1);\n var match = matches[0];\n var match_str = match[0];\n result.push([match.index, match.index + match_str.length, statement]);\n break; // Break to avoid matching a sub-statement from the same group e.g. \"INNER JOIN\" -> \"JOIN\"\n }\n }\n result.sort(function(a, b) { return a[0] - b[0]; });\n return result;\n}\n\n\nfunction separate_actions(rbql_expression) {\n rbql_expression = str_strip(rbql_expression);\n var result = {};\n let with_match = /^(.*) *[Ww][Ii][Tt][Hh] *\\(([a-z]{4,20})\\) *$/.exec(rbql_expression);\n if (with_match !== null) {\n rbql_expression = with_match[1];\n result[WITH] = with_match[2];\n }\n var ordered_statements = locate_statements(rbql_expression);\n for (var i = 0; i < ordered_statements.length; i++) {\n var statement_start = ordered_statements[i][0];\n var span_start = ordered_statements[i][1];\n var statement = ordered_statements[i][2];\n var span_end = i + 1 < ordered_statements.length ? ordered_statements[i + 1][0] : rbql_expression.length;\n assert(statement_start < span_start);\n assert(span_start <= span_end);\n var span = rbql_expression.substring(span_start, span_end);\n var statement_params = {};\n if ([STRICT_LEFT_JOIN, LEFT_OUTER_JOIN, LEFT_JOIN, INNER_JOIN, JOIN].indexOf(statement) != -1) {\n statement_params['join_subtype'] = statement;\n statement = JOIN;\n }\n\n if (statement == UPDATE) {\n if (statement_start != 0)\n throw new RbqlParsingError('UPDATE keyword must be at the beginning of the query');\n span = span.replace(/^ *SET/i, '');\n }\n\n if (statement == ORDER_BY) {\n span = span.replace(/ ASC *$/i, '');\n var new_span = span.replace(/ DESC *$/i, '');\n if (new_span != span) {\n span = new_span;\n statement_params['reverse'] = true;\n } else {\n statement_params['reverse'] = false;\n }\n }\n\n if (statement == SELECT) {\n if (statement_start != 0)\n throw new RbqlParsingError('SELECT keyword must be at the beginning of the query');\n let match = /^ *TOP *([0-9]+) /i.exec(span);\n if (match !== null) {\n statement_params['top'] = parseInt(match[1]);\n span = span.substr(match.index + match[0].length);\n }\n match = /^ *DISTINCT *(COUNT)? /i.exec(span);\n if (match !== null) {\n statement_params['distinct'] = true;\n if (match[1]) {\n statement_params['distinct_count'] = true;\n }\n span = span.substr(match.index + match[0].length);\n }\n }\n statement_params['text'] = str_strip(span);\n result[statement] = statement_params;\n }\n if (!result.hasOwnProperty(SELECT) && !result.hasOwnProperty(UPDATE)) {\n throw new RbqlParsingError('Query must contain either SELECT or UPDATE statement');\n }\n assert(result.hasOwnProperty(SELECT) != result.hasOwnProperty(UPDATE));\n return result;\n}\n\n\nfunction find_top(rb_actions) {\n if (rb_actions.hasOwnProperty(LIMIT)) {\n var rgx = /^[0-9]+$/;\n if (rgx.exec(rb_actions[LIMIT]['text']) === null) {\n throw new RbqlParsingError('LIMIT keyword must be followed by an integer');\n }\n var result = parseInt(rb_actions[LIMIT]['text']);\n return result;\n }\n var select_action = rb_actions[SELECT];\n if (select_action && select_action.hasOwnProperty('top')) {\n return select_action['top'];\n }\n return null;\n}\n\n\nfunction translate_except_expression(except_expression, input_variables_map, string_literals, input_header) {\n let skip_vars = except_expression.split(',');\n skip_vars = skip_vars.map(str_strip);\n let skip_indices = [];\n for (let var_name of skip_vars) {\n var_name = combine_string_literals(var_name, string_literals);\n if (!input_variables_map.hasOwnProperty(var_name))\n throw new RbqlParsingError(`Unknown field in EXCEPT expression: \"${var_name}\"`);\n skip_indices.push(input_variables_map[var_name].index);\n }\n skip_indices = skip_indices.sort((a, b) => a - b);\n let output_header = input_header === null ? null : select_except(input_header, skip_indices);\n let indices_str = skip_indices.join(',');\n return [output_header, `select_except(record_a, [${indices_str}])`];\n}\n\n\nclass HashJoinMap {\n constructor(record_iterator, key_indices) {\n this.max_record_len = 0;\n this.hash_map = new Map();\n this.record_iterator = record_iterator;\n this.nr = 0;\n if (key_indices.length == 1) {\n this.key_index = key_indices[0];\n this.key_indices = null;\n this.polymorphic_get_key = this.get_single_key;\n } else {\n this.key_index = null;\n this.key_indices = key_indices;\n this.polymorphic_get_key = this.get_multi_key;\n }\n }\n\n get_single_key(nr, fields) {\n if (this.key_index >= fields.length)\n throw new RbqlRuntimeError(`No field with index ${this.key_index + 1} at record ${this.nr} in \"B\" table`);\n return this.key_index === -1 ? this.nr : fields[this.key_index];\n };\n\n get_multi_key(nr, fields) {\n let result = [];\n for (let ki of this.key_indices) {\n if (ki >= fields.length)\n throw new RbqlRuntimeError(`No field with index ${ki + 1} at record ${this.nr} in \"B\" table`);\n result.push(ki === -1 ? this.nr : fields[ki]);\n }\n return JSON.stringify(result);\n };\n\n async build() {\n while (true) {\n let fields = await this.record_iterator.get_record();\n if (fields === null)\n break;\n this.nr += 1;\n let nf = fields.length;\n this.max_record_len = Math.max(this.max_record_len, nf);\n let key = this.polymorphic_get_key(this.nr, fields);\n let key_records = this.hash_map.get(key);\n if (key_records === undefined) {\n this.hash_map.set(key, [[this.nr, nf, fields]]);\n } else {\n key_records.push([this.nr, nf, fields]);\n }\n }\n };\n\n get_join_records(key) {\n let result = this.hash_map.get(key);\n if (result === undefined)\n return [];\n return result;\n };\n\n get_warnings() {\n return this.record_iterator.get_warnings();\n };\n}\n\n\nfunction cleanup_query(query_text) {\n return query_text.split('\\n').map(strip_comments).filter(line => line.length).join(' ').replace(/;+$/g, '');\n}\n\n\nfunction remove_redundant_table_name(query_text) {\n query_text = str_strip(query_text.replace(/ +from +a(?: +|$)/gi, ' '));\n query_text = str_strip(query_text.replace(/^ *update +a +set /gi, 'update '));\n return query_text;\n}\n\n\nfunction select_output_header(input_header, join_header, query_column_infos) {\n if (input_header === null && join_header === null)\n return null;\n if (input_header === null)\n input_header = [];\n if (join_header === null)\n join_header = [];\n let output_header = [];\n for (let qci of query_column_infos) {\n // TODO refactor this and python version: extract this code into a function instead to always return something\n if (qci === null) {\n output_header.push('col' + (output_header.length + 1));\n } else if (qci.is_star) {\n if (qci.table_name === null) {\n output_header = output_header.concat(input_header).concat(join_header);\n } else if (qci.table_name === 'a') {\n output_header = output_header.concat(input_header);\n } else if (qci.table_name === 'b') {\n output_header = output_header.concat(join_header);\n }\n } else if (qci.column_name !== null) {\n output_header.push(qci.column_name);\n } else if (qci.column_index !== null) {\n if (qci.table_name == 'a' && qci.column_index < input_header.length) {\n output_header.push(input_header[qci.column_index]);\n } else if (qci.table_name == 'b' && qci.column_index < join_header.length) {\n output_header.push(join_header[qci.column_index]);\n } else {\n output_header.push('col' + (output_header.length + 1));\n }\n } else { // Should never happen\n output_header.push('col' + (output_header.length + 1));\n }\n }\n return output_header;\n}\n\n\nfunction make_inconsistent_num_fields_warning(table_name, inconsistent_records_info) {\n let keys = Object.keys(inconsistent_records_info);\n let entries = [];\n for (let i = 0; i < keys.length; i++) {\n let key = keys[i];\n let record_id = inconsistent_records_info[key];\n entries.push([record_id, key]);\n }\n entries.sort(function(a, b) { return a[0] - b[0]; });\n assert(entries.length > 1);\n let [record_1, num_fields_1] = entries[0];\n let [record_2, num_fields_2] = entries[1];\n let warn_msg = `Number of fields in \"${table_name}\" table is not consistent: `;\n warn_msg += `e.g. record ${record_1} -> ${num_fields_1} fields, record ${record_2} -> ${num_fields_2} fields`;\n return warn_msg;\n}\n\n\nclass RBQLInputIterator {\n constructor(){}\n stop() {\n throw new Error(\"Unable to call the interface method\");\n }\n async get_variables_map(query_text) {\n throw new Error(\"Unable to call the interface method\");\n }\n async get_record() {\n throw new Error(\"Unable to call the interface method\");\n }\n handle_query_modifier() {\n return; // Reimplement if you need to handle a boolean query modifier that can be used like this: `SELECT * WITH (modifiername)`\n }\n get_warnings() {\n return []; // Reimplement if your class can produce warnings\n }\n async get_header() {\n return null; // Reimplement if your class can provide input header\n }\n}\n\n\nclass RBQLOutputWriter {\n constructor(){}\n\n async write(fields) {\n throw new Error(\"Unable to call the interface method\");\n }\n\n async finish() {\n // Reimplement if your class needs to do something on finish e.g. cleanup\n };\n\n get_warnings() {\n return []; // Reimplement if your class can produce warnings\n };\n\n set_header() {\n return; // Reimplement if your class can handle output headers in a meaningful way\n }\n}\n\n\nclass RBQLTableRegistry {\n constructor(){}\n\n get_iterator_by_table_id(table_id) {\n throw new Error(\"Unable to call the interface method\");\n }\n\n get_warnings() {\n return []; // Reimplement if your class can produce warnings\n };\n}\n\n\nclass TableIterator extends RBQLInputIterator {\n constructor(table, column_names=null, normalize_column_names=true, variable_prefix='a') {\n super();\n this.table = table;\n this.column_names = column_names;\n this.normalize_column_names = normalize_column_names;\n this.variable_prefix = variable_prefix;\n this.nr = 0;\n this.fields_info = new Object();\n this.stopped = false;\n }\n\n\n stop() {\n this.stopped = true;\n };\n\n\n async get_variables_map(query_text) {\n let variable_map = new Object();\n parse_basic_variables(query_text, this.variable_prefix, variable_map);\n parse_array_variables(query_text, this.variable_prefix, variable_map);\n if (this.column_names !== null) {\n if (this.table.length && this.column_names.length != this.table[0].length)\n throw new RbqlIOHandlingError('List of column names and table records have different lengths');\n if (this.normalize_column_names) {\n parse_dictionary_variables(query_text, this.variable_prefix, this.column_names, variable_map);\n parse_attribute_variables(query_text, this.variable_prefix, this.column_names, 'column names list', variable_map);\n } else {\n map_variables_directly(query_text, this.column_names, variable_map);\n }\n }\n return variable_map;\n };\n\n\n async get_record() {\n if (this.stopped)\n return null;\n if (this.nr >= this.table.length)\n return null;\n let record = this.table[this.nr];\n this.nr += 1;\n let num_fields = record.length;\n if (!this.fields_info.hasOwnProperty(num_fields))\n this.fields_info[num_fields] = this.nr;\n return record;\n };\n\n get_warnings() {\n if (Object.keys(this.fields_info).length > 1)\n return [make_inconsistent_num_fields_warning('input', this.fields_info)];\n return [];\n };\n\n async get_header() {\n return this.column_names;\n }\n}\n\n\nclass TableWriter extends RBQLOutputWriter {\n constructor(external_table) {\n super();\n this.table = external_table;\n this.header = null;\n }\n\n async write(fields) {\n this.table.push(fields);\n return true;\n };\n\n set_header(header) {\n this.header = header;\n }\n}\n\n\nclass SingleTableRegistry extends RBQLTableRegistry {\n constructor(table, column_names=null, normalize_column_names=true, table_id='b') {\n super();\n this.table = table;\n this.table_id = table_id;\n this.column_names = column_names;\n this.normalize_column_names = normalize_column_names;\n }\n\n get_iterator_by_table_id(table_id) {\n if (table_id.toLowerCase() !== this.table_id)\n throw new RbqlIOHandlingError(`Unable to find join table: \"${table_id}\"`);\n return new TableIterator(this.table, this.column_names, this.normalize_column_names, 'b');\n };\n}\n\n\nasync function shallow_parse_input_query(query_text, input_iterator, join_tables_registry, query_context) {\n query_text = cleanup_query(query_text);\n var [format_expression, string_literals] = separate_string_literals(query_text);\n format_expression = remove_redundant_table_name(format_expression);\n\n var rb_actions = separate_actions(format_expression);\n if (rb_actions.hasOwnProperty(WITH)) {\n input_iterator.handle_query_modifier(rb_actions[WITH]);\n }\n var input_variables_map = await input_iterator.get_variables_map(query_text);\n\n if (rb_actions.hasOwnProperty(ORDER_BY) && rb_actions.hasOwnProperty(UPDATE))\n throw new RbqlParsingError('\"ORDER BY\" is not allowed in \"UPDATE\" queries');\n\n if (rb_actions.hasOwnProperty(GROUP_BY)) {\n if (rb_actions.hasOwnProperty(ORDER_BY) || rb_actions.hasOwnProperty(UPDATE))\n throw new RbqlParsingError('\"ORDER BY\", \"UPDATE\" and \"DISTINCT\" keywords are not allowed in aggregate queries');\n query_context.aggregation_key_expression = '[' + combine_string_literals(rb_actions[GROUP_BY]['text'], string_literals) + ']';\n }\n\n let join_variables_map = null;\n let join_header = null;\n if (rb_actions.hasOwnProperty(JOIN)) {\n var [rhs_table_id, variable_pairs] = parse_join_expression(rb_actions[JOIN]['text']);\n if (join_tables_registry === null)\n throw new RbqlParsingError('JOIN operations are not supported by the application');\n let join_record_iterator = join_tables_registry.get_iterator_by_table_id(rhs_table_id);\n if (!join_record_iterator)\n throw new RbqlParsingError(`Unable to find join table: \"${rhs_table_id}\"`);\n if (rb_actions.hasOwnProperty(WITH)) {\n join_record_iterator.handle_query_modifier(rb_actions[WITH]);\n }\n join_variables_map = await join_record_iterator.get_variables_map(query_text);\n join_header = await join_record_iterator.get_header();\n let [lhs_variables, rhs_indices] = resolve_join_variables(input_variables_map, join_variables_map, variable_pairs, string_literals);\n let sql_join_type = {'JOIN': InnerJoiner, 'INNER JOIN': InnerJoiner, 'LEFT JOIN': LeftJoiner, 'LEFT OUTER JOIN': LeftJoiner, 'STRICT LEFT JOIN': StrictLeftJoiner}[rb_actions[JOIN]['join_subtype']];\n query_context.lhs_join_var_expression = lhs_variables.length == 1 ? lhs_variables[0] : 'JSON.stringify([' + lhs_variables.join(',') + '])';\n query_context.join_map_impl = new HashJoinMap(join_record_iterator, rhs_indices);\n await query_context.join_map_impl.build();\n query_context.join_map = new sql_join_type(query_context.join_map_impl);\n }\n\n query_context.variables_init_code = combine_string_literals(generate_init_statements(format_expression, input_variables_map, join_variables_map, ' '.repeat(4)), string_literals);\n\n if (rb_actions.hasOwnProperty(WHERE)) {\n var where_expression = rb_actions[WHERE]['text'];\n if (/[^>= 3 && line.charCodeAt(0) === 0xEF && line.charCodeAt(1) === 0xBB && line.charCodeAt(2) === 0xBF) {\n return line.substring(3);\n }\n if (assumed_source_encoding == 'utf-8' && line.length >= 1 && line.charCodeAt(0) === 0xFEFF) {\n return line.substring(1);\n }\n return line;\n}\n\n\nfunction make_inconsistent_num_fields_warning(table_name, inconsistent_records_info) {\n let keys = Object.keys(inconsistent_records_info);\n let entries = [];\n for (let i = 0; i < keys.length; i++) {\n let key = keys[i];\n let record_id = inconsistent_records_info[key];\n entries.push([record_id, key]);\n }\n entries.sort(function(a, b) { return a[0] - b[0]; });\n assert(entries.length > 1);\n let [record_1, num_fields_1] = entries[0];\n let [record_2, num_fields_2] = entries[1];\n let warn_msg = `Number of fields in \"${table_name}\" table is not consistent: `;\n warn_msg += `e.g. record ${record_1} -> ${num_fields_1} fields, record ${record_2} -> ${num_fields_2} fields`;\n return warn_msg;\n}\n\n\nfunction expanduser(filepath) {\n if (filepath.charAt(0) === '~') {\n return path.join(os.homedir(), filepath.slice(1));\n }\n return filepath;\n}\n\n\nfunction try_read_index(index_path) {\n var content = null;\n try {\n content = fs.readFileSync(index_path, 'utf-8');\n } catch (e) {\n return [];\n }\n var lines = content.split('\\n');\n var records = [];\n for (var i = 0; i < lines.length; i++) {\n if (!lines[i])\n continue;\n var record = lines[i].split('\\t');\n records.push(record);\n }\n return records;\n}\n\n\nfunction get_index_record(index_path, key) {\n var records = try_read_index(index_path);\n for (var i = 0; i < records.length; i++) {\n if (records[i].length && records[i][0] == key) {\n return records[i];\n }\n }\n return null;\n}\n\n\nfunction find_table_path(main_table_dir, table_id) {\n // If table_id is a relative path it could be relative either to the current directory or to the main table dir.\n var candidate_path = expanduser(table_id);\n if (fs.existsSync(candidate_path)) {\n return candidate_path;\n }\n if (main_table_dir && !path.isAbsolute(candidate_path)) {\n candidate_path = path.join(main_table_dir, candidate_path);\n if (fs.existsSync(candidate_path)) {\n return candidate_path;\n }\n }\n let table_names_settings_path = path.join(os.homedir(), '.rbql_table_names');\n var name_record = get_index_record(table_names_settings_path, table_id);\n if (name_record && name_record.length > 1 && fs.existsSync(name_record[1])) {\n return name_record[1];\n }\n return null;\n}\n\n\nclass RecordQueue {\n // TODO compare performance with a linked list\n constructor() {\n this.push_stack = [];\n this.pull_stack = [];\n }\n\n enqueue(record) {\n this.push_stack.push(record);\n }\n\n dequeue() {\n if (!this.pull_stack.length) {\n if (!this.push_stack.length)\n return null;\n this.pull_stack = this.push_stack;\n this.pull_stack.reverse();\n this.push_stack = [];\n }\n return this.pull_stack.pop();\n }\n}\n\n\nclass CSVRecordIterator extends rbql.RBQLInputIterator {\n // CSVRecordIterator implements a typical async producer-consumer model with an internal buffer:\n // get_record() - consumer\n // stream.on('data') - producer\n constructor(stream, csv_path, encoding, delim, policy, has_header=false, comment_prefix=null, table_name='input', variable_prefix='a') {\n super();\n this.stream = stream;\n this.csv_path = csv_path;\n assert((this.stream === null) != (this.csv_path === null));\n this.encoding = encoding;\n this.delim = delim;\n this.policy = policy;\n\n this.has_header = has_header;\n this.first_record = null;\n this.first_record_should_be_emitted = !has_header;\n this.header_preread_complete = false;\n\n this.table_name = table_name;\n this.variable_prefix = variable_prefix;\n this.comment_prefix = (comment_prefix !== null && comment_prefix.length) ? comment_prefix : null;\n\n this.decoder = null;\n if (encoding == 'utf-8' && this.csv_path === null) {\n // Unfortunately util.TextDecoder has serious flaws:\n // 1. It doesn't work in Node without ICU: https://nodejs.org/api/util.html#util_new_textdecoder_encoding_options\n // 2. It is broken in Electron: https://github.com/electron/electron/issues/18733\n\n // Technically we can implement our own custom streaming text decoder, using the 3 following technologies:\n // 1. decode-encode validation method from https://stackoverflow.com/a/32279283/2898283\n // 2. Scanning buffer chunks for non-continuation utf-8 bytes from the end of the buffer:\n // src_buffer -> (buffer_before, buffer_after) where buffer_after is very small(a couple of bytes) and buffer_before is large and ends with a non-continuation bytes\n // 3. Internal buffer to store small tail part from the previous buffer\n this.decoder = new util.TextDecoder(encoding, {fatal: true, stream: true});\n }\n\n this.input_exhausted = false;\n this.started = false;\n\n this.utf8_bom_removed = false; // BOM doesn't get automatically removed by the decoder when utf-8 file is treated as latin-1\n this.first_defective_line = null;\n\n this.fields_info = new Object();\n this.NR = 0; // Record number\n this.NL = 0; // Line number (NL != NR when the CSV file has comments or multiline fields)\n\n this.rfc_line_buffer = [];\n\n this.partially_decoded_line = '';\n this.partially_decoded_line_ends_with_cr = false;\n\n // Holds an external \"resolve\" function which is called when everything is fine.\n this.resolve_current_record = null;\n // Holds an external \"reject\" function which is called when error has occured.\n this.reject_current_record = null;\n // Holds last exception if we don't have any reject callbacks from clients yet.\n this.current_exception = null;\n\n this.produced_records_queue = new RecordQueue();\n\n this.process_line_polymorphic = policy == 'quoted_rfc' ? this.process_partial_rfc_record_line : this.process_record_line;\n }\n\n\n handle_query_modifier(modifier) {\n // For `... WITH (header) ...` syntax\n if (['header', 'headers'].indexOf(modifier) != -1) {\n this.has_header = true;\n this.first_record_should_be_emitted = false;\n }\n if (['noheader', 'noheaders'].indexOf(modifier) != -1) {\n this.has_header = false;\n this.first_record_should_be_emitted = true;\n }\n }\n\n\n reset_external_callbacks() {\n // Drop external callbacks simultaneously since promises can only resolve once, see: https://stackoverflow.com/a/18218542/2898283\n this.reject_current_record = null;\n this.resolve_current_record = null;\n }\n\n try_propagate_exception() {\n if (this.current_exception && this.reject_current_record) {\n let reject = this.reject_current_record;\n let exception = this.current_exception;\n this.reset_external_callbacks();\n this.current_exception = null;\n reject(exception);\n }\n }\n\n\n store_or_propagate_exception(exception) {\n if (this.current_exception === null)\n // Ignore subsequent exceptions if we already have an unreported error. This way we prioritize earlier errors over the more recent ones.\n this.current_exception = exception;\n this.try_propagate_exception();\n }\n\n\n async preread_first_record() {\n if (this.header_preread_complete)\n return;\n this.first_record = await this.get_record();\n this.header_preread_complete = true; // We must set header_preread_complete to true after calling get_record(), because get_record() uses it internally.\n if (this.first_record === null) {\n return;\n }\n if (this.stream)\n this.stream.pause();\n this.first_record = this.first_record.slice();\n };\n\n\n async get_variables_map(query_text) {\n let variable_map = new Object();\n rbql.parse_basic_variables(query_text, this.variable_prefix, variable_map);\n rbql.parse_array_variables(query_text, this.variable_prefix, variable_map);\n\n await this.preread_first_record();\n if (this.has_header && this.first_record) {\n rbql.parse_attribute_variables(query_text, this.variable_prefix, this.first_record, 'CSV header line', variable_map);\n rbql.parse_dictionary_variables(query_text, this.variable_prefix, this.first_record, variable_map);\n }\n return variable_map;\n };\n\n async get_header() {\n await this.preread_first_record();\n return this.has_header ? this.first_record : null;\n }\n\n\n try_resolve_next_record() {\n this.try_propagate_exception();\n if (this.resolve_current_record === null)\n return;\n\n let record = null;\n if (this.first_record_should_be_emitted && this.header_preread_complete) {\n this.first_record_should_be_emitted = false;\n record = this.first_record;\n } else {\n record = this.produced_records_queue.dequeue();\n }\n\n if (record === null && !this.input_exhausted)\n return;\n let resolve = this.resolve_current_record;\n this.reset_external_callbacks();\n resolve(record);\n };\n\n\n async get_record() {\n if (!this.started)\n await this.start();\n if (this.stream && this.stream.isPaused())\n this.stream.resume();\n\n let parent_iterator = this;\n let current_record_promise = new Promise(function(resolve, reject) {\n parent_iterator.resolve_current_record = resolve;\n parent_iterator.reject_current_record = reject;\n });\n this.try_resolve_next_record();\n return current_record_promise;\n };\n\n\n async get_all_records(num_records=null) {\n let records = [];\n while (true) {\n let record = await this.get_record();\n if (record === null)\n break;\n records.push(record);\n if (num_records && records.length >= num_records) {\n this.stop();\n break;\n }\n }\n return records;\n };\n\n\n process_record_line(line) {\n if (this.comment_prefix !== null && line.startsWith(this.comment_prefix))\n return; // Just skip the line\n this.NR += 1;\n var [record, warning] = csv_utils.smart_split(line, this.delim, this.policy, false);\n if (warning) {\n if (this.first_defective_line === null) {\n this.first_defective_line = this.NL;\n if (this.policy == 'quoted_rfc')\n this.store_or_propagate_exception(new RbqlIOHandlingError(`Inconsistent double quote escaping in ${this.table_name} table at record ${this.NR}, line ${this.NL}`));\n }\n }\n let num_fields = record.length;\n if (!this.fields_info.hasOwnProperty(num_fields))\n this.fields_info[num_fields] = this.NR;\n this.produced_records_queue.enqueue(record);\n this.try_resolve_next_record();\n };\n\n\n process_partial_rfc_record_line(line) {\n let record_line = csv_utils.accumulate_rfc_line_into_record(this.rfc_line_buffer, line, this.comment_prefix);\n if (record_line !== null)\n this.process_record_line(record_line);\n };\n\n\n process_line(line) {\n this.NL += 1;\n if (this.NL === 1) {\n var clean_line = remove_utf8_bom(line, this.encoding);\n if (clean_line != line) {\n line = clean_line;\n this.utf8_bom_removed = true;\n }\n }\n this.process_line_polymorphic(line);\n };\n\n\n process_data_stream_chunk(data_chunk) {\n let decoded_string = null;\n if (this.decoder) {\n try {\n decoded_string = this.decoder.decode(data_chunk);\n } catch (e) {\n if (e instanceof TypeError) {\n this.store_or_propagate_exception(new RbqlIOHandlingError(utf_decoding_error));\n } else {\n this.store_or_propagate_exception(e);\n }\n return;\n }\n } else {\n decoded_string = data_chunk.toString(this.encoding);\n }\n let line_starts_with_lf = decoded_string.length && decoded_string[0] == '\\n';\n let first_line_index = line_starts_with_lf && this.partially_decoded_line_ends_with_cr ? 1 : 0;\n this.partially_decoded_line_ends_with_cr = decoded_string.length && decoded_string[decoded_string.length - 1] == '\\r';\n let lines = csv_utils.split_lines(decoded_string);\n lines[0] = this.partially_decoded_line + lines[0];\n assert(first_line_index == 0 || lines[0].length == 0);\n this.partially_decoded_line = lines.pop();\n for (let i = first_line_index; i < lines.length; i++) {\n this.process_line(lines[i]);\n }\n };\n\n\n process_data_bulk(data_chunk) {\n let decoded_string = data_chunk.toString(this.encoding);\n if (this.encoding == 'utf-8') {\n // Using hacky comparison method from here: https://stackoverflow.com/a/32279283/2898283\n // TODO get rid of this once TextDecoder is really fixed or when alternative method of reliable decoding appears\n let control_buffer = Buffer.from(decoded_string, 'utf-8');\n if (Buffer.compare(data_chunk, control_buffer) != 0) {\n this.store_or_propagate_exception(new RbqlIOHandlingError(utf_decoding_error));\n return;\n }\n }\n let lines = csv_utils.split_lines(decoded_string);\n if (lines.length && lines[lines.length - 1].length == 0)\n lines.pop();\n for (let i = 0; i < lines.length; i++) {\n this.process_line(lines[i]);\n }\n if (this.rfc_line_buffer.length > 0) {\n this.process_record_line(this.rfc_line_buffer.join('\\n'));\n }\n this.input_exhausted = true;\n this.try_resolve_next_record(); // Should be a NOOP here?\n }\n\n\n process_data_stream_end() {\n this.input_exhausted = true;\n if (this.partially_decoded_line.length) {\n let last_line = this.partially_decoded_line;\n this.partially_decoded_line = '';\n this.process_line(last_line);\n }\n if (this.rfc_line_buffer.length > 0) {\n this.process_record_line(this.rfc_line_buffer.join('\\n'));\n }\n this.try_resolve_next_record();\n };\n\n\n stop() {\n if (this.stream)\n this.stream.destroy(); // TODO consider using pause() instead\n };\n\n\n async start() {\n if (this.started)\n return;\n this.started = true;\n if (this.stream) {\n this.stream.on('data', (data_chunk) => { this.process_data_stream_chunk(data_chunk); });\n this.stream.on('end', () => { this.process_data_stream_end(); });\n } else {\n let parent_iterator = this;\n return new Promise(function(resolve, reject) {\n fs.readFile(parent_iterator.csv_path, (err, data_chunk) => {\n if (err) {\n reject(err);\n } else {\n parent_iterator.process_data_bulk(data_chunk);\n resolve();\n }\n });\n });\n }\n };\n\n\n get_warnings() {\n let result = [];\n if (this.first_defective_line !== null)\n result.push(`Inconsistent double quote escaping in ${this.table_name} table. E.g. at line ${this.first_defective_line}`);\n if (this.utf8_bom_removed)\n result.push(`UTF-8 Byte Order Mark (BOM) was found and skipped in ${this.table_name} table`);\n if (Object.keys(this.fields_info).length > 1)\n result.push(make_inconsistent_num_fields_warning(this.table_name, this.fields_info));\n return result;\n };\n}\n\n\nclass CSVWriter extends rbql.RBQLOutputWriter {\n constructor(stream, close_stream_on_finish, encoding, delim, policy, line_separator='\\n') {\n super();\n this.stream = stream;\n this.encoding = encoding;\n if (encoding)\n this.stream.setDefaultEncoding(encoding);\n this.stream.on('error', (error_obj) => { this.store_first_error(error_obj); })\n this.delim = delim;\n this.policy = policy;\n this.line_separator = line_separator;\n this.sub_array_delim = delim == '|' ? ';' : '|';\n\n this.close_stream_on_finish = close_stream_on_finish;\n\n this.null_in_output = false;\n this.delim_in_simple_output = false;\n this.header_len = null;\n this.first_error = null;\n\n if (policy == 'simple') {\n this.polymorphic_join = this.simple_join;\n } else if (policy == 'quoted') {\n this.polymorphic_join = this.quoted_join;\n } else if (policy == 'quoted_rfc') {\n this.polymorphic_join = this.quoted_join_rfc;\n } else if (policy == 'monocolumn') {\n this.polymorphic_join = this.mono_join;\n } else if (policy == 'whitespace') {\n this.polymorphic_join = this.simple_join;\n } else {\n throw new RbqlIOHandlingError('Unknown output csv policy');\n }\n }\n\n\n store_first_error(error_obj) {\n // Store only first error because it is typically more important than the subsequent ones.\n if (this.first_error === null)\n this.first_error = error_obj;\n }\n\n set_header(header) {\n if (header !== null) {\n this.header_len = header.length;\n this.write(header);\n }\n }\n\n\n quoted_join(fields) {\n let delim = this.delim;\n var quoted_fields = fields.map(function(v) { return csv_utils.quote_field(String(v), delim); });\n return quoted_fields.join(this.delim);\n };\n\n\n quoted_join_rfc(fields) {\n let delim = this.delim;\n var quoted_fields = fields.map(function(v) { return csv_utils.rfc_quote_field(String(v), delim); });\n return quoted_fields.join(this.delim);\n };\n\n\n mono_join(fields) {\n if (fields.length > 1) {\n throw new RbqlIOHandlingError('Unable to use \"Monocolumn\" output format: some records have more than one field');\n }\n return fields[0];\n };\n\n\n simple_join(fields) {\n var res = fields.join(this.delim);\n if (fields.join('').indexOf(this.delim) != -1) {\n this.delim_in_simple_output = true;\n }\n return res;\n };\n\n\n normalize_fields(out_fields) {\n for (var i = 0; i < out_fields.length; i++) {\n if (out_fields[i] == null) {\n this.null_in_output = true;\n out_fields[i] = '';\n } else if (Array.isArray(out_fields[i])) {\n this.normalize_fields(out_fields[i]);\n out_fields[i] = out_fields[i].join(this.sub_array_delim);\n }\n }\n };\n\n\n async write(fields) {\n if (this.header_len !== null && fields.length != this.header_len)\n throw new RbqlIOHandlingError(`Inconsistent number of columns in output header and the current record: ${this.header_len} != ${fields.length}`);\n this.normalize_fields(fields);\n this.stream.write(this.polymorphic_join(fields));\n this.stream.write(this.line_separator);\n let writer_error = this.first_error;\n return new Promise(function(resolve, reject) {\n if (writer_error !== null) {\n reject(writer_error);\n } else {\n resolve(true);\n }\n });\n };\n\n\n _write_all(table) {\n for (let i = 0; i < table.length; i++) {\n this.write(table[i]);\n }\n };\n\n\n async finish() {\n let close_stream_on_finish = this.close_stream_on_finish;\n let output_stream = this.stream;\n let output_encoding = this.encoding;\n let writer_error = this.first_error;\n let finish_promise = new Promise(function(resolve, reject) {\n if (writer_error !== null) {\n reject(writer_error);\n }\n if (close_stream_on_finish) {\n output_stream.end('', output_encoding, () => { resolve(); });\n } else {\n setTimeout(() => { resolve(); }, 0);\n }\n });\n return finish_promise;\n };\n\n\n get_warnings() {\n let result = [];\n if (this.null_in_output)\n result.push('null values in output were replaced by empty strings');\n if (this.delim_in_simple_output)\n result.push('Some output fields contain separator');\n return result;\n };\n\n}\n\n\nclass FileSystemCSVRegistry extends rbql.RBQLTableRegistry {\n constructor(input_file_dir, delim, policy, encoding, has_header=false, comment_prefix=null, options=null) {\n super();\n this.input_file_dir = input_file_dir;\n this.delim = delim;\n this.policy = policy;\n this.encoding = encoding;\n this.has_header = has_header;\n this.comment_prefix = comment_prefix;\n this.stream = null;\n this.record_iterator = null;\n\n this.options = options;\n this.bulk_input_path = null;\n this.table_path = null;\n }\n\n get_iterator_by_table_id(table_id) {\n this.table_path = find_table_path(this.input_file_dir, table_id);\n if (this.table_path === null) {\n throw new RbqlIOHandlingError(`Unable to find join table \"${table_id}\"`);\n }\n if (this.options && this.options['bulk_read']) {\n this.bulk_input_path = this.table_path;\n } else {\n this.stream = fs.createReadStream(this.table_path);\n }\n this.record_iterator = new CSVRecordIterator(this.stream, this.bulk_input_path, this.encoding, this.delim, this.policy, this.has_header, this.comment_prefix, table_id, 'b');\n return this.record_iterator;\n };\n\n get_warnings(output_warnings) {\n if (this.record_iterator && this.has_header) {\n output_warnings.push(`The first record in JOIN file ${path.basename(this.table_path)} was also treated as header (and skipped)`);\n }\n }\n}\n\n\nasync function query_csv(query_text, input_path, input_delim, input_policy, output_path, output_delim, output_policy, csv_encoding, output_warnings, with_headers=false, comment_prefix=null, user_init_code='', options=null) {\n let input_stream = null;\n let bulk_input_path = null;\n if (options && options['bulk_read'] && input_path) {\n bulk_input_path = input_path;\n } else {\n input_stream = input_path === null ? process.stdin : fs.createReadStream(input_path);\n }\n let [output_stream, close_output_on_finish] = output_path === null ? [process.stdout, false] : [fs.createWriteStream(output_path), true];\n if (input_delim == '\"' && input_policy == 'quoted')\n throw new RbqlIOHandlingError('Double quote delimiter is incompatible with \"quoted\" policy');\n if (csv_encoding == 'latin-1')\n csv_encoding = 'binary';\n if (!is_ascii(query_text) && csv_encoding == 'binary')\n throw new RbqlIOHandlingError('To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary');\n if ((!is_ascii(input_delim) || !is_ascii(output_delim)) && csv_encoding == 'binary')\n throw new RbqlIOHandlingError('To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary');\n\n let default_init_source_path = path.join(os.homedir(), '.rbql_init_source.js');\n if (user_init_code == '' && fs.existsSync(default_init_source_path)) {\n user_init_code = read_user_init_code(default_init_source_path);\n }\n let input_file_dir = input_path ? path.dirname(input_path) : null;\n let join_tables_registry = new FileSystemCSVRegistry(input_file_dir, input_delim, input_policy, csv_encoding, with_headers, comment_prefix, options);\n let input_iterator = new CSVRecordIterator(input_stream, bulk_input_path, csv_encoding, input_delim, input_policy, with_headers, comment_prefix);\n let output_writer = new CSVWriter(output_stream, close_output_on_finish, csv_encoding, output_delim, output_policy);\n\n await rbql.query(query_text, input_iterator, output_writer, output_warnings, join_tables_registry, user_init_code);\n join_tables_registry.get_warnings(output_warnings);\n}\n\n\nmodule.exports.is_ascii = is_ascii;\nmodule.exports.CSVRecordIterator = CSVRecordIterator;\nmodule.exports.CSVWriter = CSVWriter;\nmodule.exports.FileSystemCSVRegistry = FileSystemCSVRegistry;\nmodule.exports.interpret_named_csv_format = interpret_named_csv_format;\nmodule.exports.read_user_init_code = read_user_init_code;\nmodule.exports.query_csv = query_csv;\nmodule.exports.RecordQueue = RecordQueue;\nmodule.exports.exception_to_error_info = rbql.exception_to_error_info;\n","module.exports = require(\"vscode\");","'use strict';\n\nvar possibleNames = [\n\t'BigInt64Array',\n\t'BigUint64Array',\n\t'Float32Array',\n\t'Float64Array',\n\t'Int16Array',\n\t'Int32Array',\n\t'Int8Array',\n\t'Uint16Array',\n\t'Uint32Array',\n\t'Uint8Array',\n\t'Uint8ClampedArray'\n];\n\nvar g = typeof globalThis === 'undefined' ? global : globalThis;\n\nmodule.exports = function availableTypedArrays() {\n\tvar out = [];\n\tfor (var i = 0; i < possibleNames.length; i++) {\n\t\tif (typeof g[possibleNames[i]] === 'function') {\n\t\t\tout[out.length] = possibleNames[i];\n\t\t}\n\t}\n\treturn out;\n};\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);\nif ($gOPD) {\n\ttry {\n\t\t$gOPD([], 'length');\n\t} catch (e) {\n\t\t// IE 8 has a broken gOPD\n\t\t$gOPD = null;\n\t}\n}\n\nmodule.exports = $gOPD;\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","const vscode = require('vscode');\n\nconst path = require('path');\nconst fs = require('fs');\nconst os = require('os');\nconst child_process = require('child_process');\n\n// Please see DEV_README.md file for additional info.\n\nconst csv_utils = require('./rbql_core/rbql-js/csv_utils.js');\n\nvar rbql_csv = null; // Using lazy load to improve startup performance.\nfunction ll_rbql_csv() {\n if (rbql_csv === null)\n rbql_csv = require('./rbql_core/rbql-js/rbql_csv.js');\n return rbql_csv;\n}\n\n\nvar rainbow_utils = null; // Using lazy load to improve startup performance.\nfunction ll_rainbow_utils() {\n if (rainbow_utils === null)\n rainbow_utils = require('./rainbow_utils.js');\n return rainbow_utils;\n}\n\n\nconst is_web_ext = (os.homedir === undefined); // Runs as web extension in browser.\nconst preview_window_size = 100;\nconst max_preview_field_length = 250;\nconst scratch_buf_marker = 'vscode_rbql_scratch';\n\nlet client_html_template_web = null;\n\nvar lint_results = new Map();\nvar aligned_files = new Set();\nvar autodetection_stoplist = new Set();\nvar original_language_ids = new Map();\nvar result_set_parent_map = new Map();\n\nvar lint_status_bar_button = null;\nvar rbql_status_bar_button = null;\nvar align_shrink_button = null;\nvar rainbow_off_status_bar_button = null;\nvar copy_back_button = null;\n\nlet last_statusbar_doc = null;\n\nvar rbql_context = null;\n\nvar last_rbql_queries = new Map(); // Query history does not replace this structure, it is also used to store partially entered queries for preview window switch.\n\nvar client_html_template = null;\n\nvar global_state = null;\n\nvar preview_panel = null;\n\nvar doc_edit_subscription = null;\n\nvar _unit_test_last_rbql_report = null; // For unit tests only.\nvar _unit_test_last_warnings = null; // For unit tests only.\n\nconst dialect_map = {\n 'csv': [',', 'quoted'],\n 'tsv': ['\\t', 'simple'],\n 'csv (semicolon)': [';', 'quoted'],\n 'csv (pipe)': ['|', 'simple'],\n 'csv (tilde)': ['~', 'simple'],\n 'csv (caret)': ['^', 'simple'],\n 'csv (colon)': [':', 'simple'],\n 'csv (double quote)': ['\"', 'simple'],\n 'csv (equals)': ['=', 'simple'],\n 'csv (dot)': ['.', 'simple'],\n 'csv (whitespace)': [' ', 'whitespace'],\n 'csv (hyphen)': ['-', 'simple']\n};\n\n\n// This structure will get properly initialized during the startup.\nlet absolute_path_map = {\n 'rbql_client.js': null,\n 'contrib/textarea-caret-position/index.js': null,\n 'rbql_suggest.js': null,\n 'rbql_logo.svg': null,\n 'rbql_client.html': null,\n 'rbql mock/rbql_mock.py': null,\n 'rbql_core/vscode_rbql.py': null\n};\n\n\nfunction show_single_line_error(error_msg) {\n var active_window = vscode.window;\n if (!active_window)\n return;\n // Do not \"await\" error messages because the promise gets resolved only on error dismissal.\n active_window.showErrorMessage(error_msg);\n}\n\n\nfunction sleep(ms) {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n\nasync function push_current_stack_to_js_callback_queue_to_allow_ui_update() {\n await sleep(0);\n}\n\n\nfunction map_separator_to_language_id(separator) {\n for (let language_id in dialect_map) {\n if (!dialect_map.hasOwnProperty(language_id))\n continue;\n if (dialect_map[language_id][0] == separator)\n return language_id;\n }\n return null;\n}\n\n\nfunction get_from_global_state(key, default_value) {\n if (global_state) {\n var value = global_state.get(key);\n if (value !== null && value !== undefined)\n return value;\n }\n return default_value;\n}\n\n\nasync function save_to_global_state(key, value) {\n if (global_state && key) {\n await global_state.update(key, value);\n return true;\n }\n return false;\n}\n\n\nfunction get_rfc_record_text(document, record_start, record_end) {\n let result = [];\n for (let i = record_start; i < record_end && i < document.lineCount; i++) {\n result.push(document.lineAt(i).text);\n }\n return result.join('\\n');\n}\n\n\nasync function replace_doc_content(active_editor, active_doc, new_content) {\n let invalid_range = new vscode.Range(0, 0, active_doc.lineCount /* Intentionally missing the '-1' */, 0);\n let full_range = active_doc.validateRange(invalid_range);\n await active_editor.edit(edit => edit.replace(full_range, new_content));\n}\n\n\nfunction sample_preview_records_from_context(rbql_context, dst_message) {\n let document = rbql_context.input_document;\n let delim = rbql_context.delim;\n let policy = rbql_context.policy;\n\n rbql_context.requested_start_record = Math.max(rbql_context.requested_start_record, 0);\n\n let preview_records = [];\n if (rbql_context.enable_rfc_newlines) {\n let requested_end_record = rbql_context.requested_start_record + preview_window_size;\n ll_rainbow_utils().populate_optimistic_rfc_csv_record_map(document, requested_end_record, rbql_context.rfc_record_map);\n rbql_context.requested_start_record = Math.max(0, Math.min(rbql_context.requested_start_record, rbql_context.rfc_record_map.length - preview_window_size));\n for (let nr = rbql_context.requested_start_record; nr < rbql_context.rfc_record_map.length && preview_records.length < preview_window_size; nr++) {\n let [record_start, record_end] = rbql_context.rfc_record_map[nr];\n let record_text = get_rfc_record_text(document, record_start, record_end);\n let [cur_record, warning] = csv_utils.smart_split(record_text, delim, policy, false);\n if (warning) {\n dst_message.preview_sampling_error = `Double quotes are not consistent in record ${nr + 1} which starts at line ${record_start + 1}`;\n return;\n }\n preview_records.push(cur_record);\n }\n } else {\n let num_records = document.lineCount;\n if (document.lineAt(Math.max(num_records - 1, 0)).text == '')\n num_records -= 1;\n rbql_context.requested_start_record = Math.max(0, Math.min(rbql_context.requested_start_record, num_records - preview_window_size));\n for (let nr = rbql_context.requested_start_record; nr < num_records && preview_records.length < preview_window_size; nr++) {\n let line_text = document.lineAt(nr).text;\n let cur_record = csv_utils.smart_split(line_text, delim, policy, false)[0];\n preview_records.push(cur_record);\n }\n }\n\n for (let r = 0; r < preview_records.length; r++) {\n let cur_record = preview_records[r];\n for (let c = 0; c < cur_record.length; c++) {\n if (cur_record[c].length > max_preview_field_length) {\n cur_record[c] = cur_record[c].substr(0, max_preview_field_length) + '###UI_STRING_TRIM_MARKER###';\n }\n }\n }\n dst_message.preview_records = preview_records;\n dst_message.start_record_zero_based = rbql_context.requested_start_record;\n}\n\n\nfunction make_header_key(file_path) {\n return 'rbql_header:' + file_path;\n}\n\n\nfunction make_rfc_policy_key(file_path) {\n return 'enable_rfc_newlines:' + file_path;\n}\n\n\nfunction make_with_headers_key(file_path) {\n return 'rbql_with_headers:' + file_path;\n}\n\n\nfunction get_from_config(param_name, default_value) {\n const config = vscode.workspace.getConfiguration('rainbow_csv');\n return config ? config.get(param_name) : default_value;\n}\n\n\nfunction get_header_from_document(document, delim, policy) {\n let comment_prefix = get_from_config('comment_prefix', '');\n let header_line = ll_rainbow_utils().get_header_line(document, comment_prefix);\n return csv_utils.smart_split(header_line, delim, policy, /*preserve_quotes_and_whitespaces=*/false)[0];\n}\n\n\nfunction get_header(document, delim, policy) {\n var file_path = document.fileName;\n if (file_path) {\n let raw_header = get_from_global_state(make_header_key(file_path), null);\n if (raw_header) {\n return JSON.parse(raw_header);\n }\n }\n return get_header_from_document(document, delim, policy);\n}\n\n\nfunction get_field_by_line_position(fields, query_pos) {\n if (!fields.length)\n return null;\n var col_num = 0;\n var cpos = fields[col_num].length + 1;\n while (query_pos > cpos && col_num + 1 < fields.length) {\n col_num += 1;\n cpos = cpos + fields[col_num].length + 1;\n }\n return col_num;\n}\n\n\nfunction make_hover_text(document, position, language_id, enable_tooltip_column_names, enable_tooltip_warnings) {\n let [delim, policy] = dialect_map[language_id];\n var lnum = position.line;\n var cnum = position.character;\n var line = document.lineAt(lnum).text;\n\n let comment_prefix = get_from_config('comment_prefix', '');\n if (comment_prefix && line.startsWith(comment_prefix))\n return 'Comment';\n\n var report = csv_utils.smart_split(line, delim, policy, true);\n\n var entries = report[0];\n var warning = report[1];\n var col_num = get_field_by_line_position(entries, cnum + 1);\n\n if (col_num == null)\n return null;\n var result = 'Col #' + (col_num + 1);\n\n var header = get_header(document, delim, policy);\n if (enable_tooltip_column_names && col_num < header.length) {\n const max_label_len = 50;\n let column_label = header[col_num].trim();\n var short_column_label = column_label.substr(0, max_label_len);\n if (short_column_label != column_label)\n short_column_label = short_column_label + '...';\n result += ', Header: \"' + short_column_label + '\"';\n }\n if (enable_tooltip_warnings) {\n if (warning) {\n result += '; ERR: Inconsistent double quotes in line';\n } else if (header.length != entries.length) {\n result += `; WARN: Inconsistent num of fields, header: ${header.length}, this line: ${entries.length}`;\n }\n }\n return result;\n}\n\n\nfunction make_hover(document, position, language_id, cancellation_token) {\n if (last_statusbar_doc != document) {\n refresh_status_bar_buttons(document); // Being paranoid and making sure that the buttons are visible.\n }\n if (!get_from_config('enable_tooltip', false)) {\n return;\n }\n let enable_tooltip_column_names = get_from_config('enable_tooltip_column_names', false);\n let enable_tooltip_warnings = get_from_config('enable_tooltip_warnings', false);\n var hover_text = make_hover_text(document, position, language_id, enable_tooltip_column_names, enable_tooltip_warnings);\n if (hover_text && !cancellation_token.isCancellationRequested) {\n let mds = null;\n try {\n mds = new vscode.MarkdownString();\n mds.appendCodeblock(hover_text, 'rainbow hover markup');\n } catch (e) {\n mds = hover_text; // Older VSCode versions may not have MarkdownString/appendCodeblock functionality.\n }\n return new vscode.Hover(mds);\n } else {\n return null;\n }\n}\n\n\nfunction produce_lint_report(active_doc, delim, policy) {\n let comment_prefix = get_from_config('comment_prefix', '');\n let detect_trailing_spaces = get_from_config('csv_lint_detect_trailing_spaces', false);\n let first_trailing_space_line = null;\n var num_lines = active_doc.lineCount;\n var num_fields = null;\n for (var lnum = 0; lnum < num_lines; lnum++) {\n var line_text = active_doc.lineAt(lnum).text;\n if (lnum + 1 == num_lines && !line_text)\n break;\n if (comment_prefix && line_text.startsWith(comment_prefix))\n continue;\n var split_result = csv_utils.smart_split(line_text, delim, policy, true);\n if (split_result[1]) {\n return 'Error. Line ' + (lnum + 1) + ' has formatting error: double quote chars are not consistent';\n }\n if (detect_trailing_spaces && first_trailing_space_line === null) {\n let fields = split_result[0];\n for (let i = 0; i < fields.length; i++) {\n if (fields[i].length && (fields[i].charAt(0) == ' ' || fields[i].slice(-1) == ' ')) {\n first_trailing_space_line = lnum;\n }\n }\n }\n if (!num_fields) {\n num_fields = split_result[0].length;\n }\n if (num_fields != split_result[0].length) {\n return 'Error. Number of fields is not consistent: e.g. line 1 has ' + num_fields + ' fields, and line ' + (lnum + 1) + ' has ' + split_result[0].length + ' fields.';\n }\n }\n if (first_trailing_space_line !== null) {\n return 'Leading/Trailing spaces detected: e.g. at line ' + (first_trailing_space_line + 1) + '. Run \"Shrink\" command to remove them.';\n }\n return 'OK';\n}\n\n\nfunction get_active_editor() {\n var active_window = vscode.window;\n if (!active_window)\n return null;\n var active_editor = active_window.activeTextEditor;\n if (!active_editor)\n return null;\n return active_editor;\n}\n\n\nfunction get_active_doc(active_editor=null) {\n if (!active_editor)\n active_editor = get_active_editor();\n if (!active_editor)\n return null;\n var active_doc = active_editor.document;\n if (!active_doc)\n return null;\n return active_doc;\n}\n\n\nfunction show_lint_status_bar_button(file_path, language_id) {\n let lint_cache_key = `${file_path}.${language_id}`;\n if (!lint_results.has(lint_cache_key))\n return;\n var lint_report = lint_results.get(lint_cache_key);\n if (!lint_status_bar_button)\n lint_status_bar_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);\n lint_status_bar_button.text = 'CSVLint';\n if (lint_report === 'OK') {\n lint_status_bar_button.color = '#62f442';\n } else if (lint_report == 'Processing...') {\n lint_status_bar_button.color = '#A0A0A0';\n } else if (lint_report.indexOf('spaces detected') != -1) {\n lint_status_bar_button.color = '#ffff28';\n } else {\n lint_status_bar_button.color = '#f44242';\n }\n lint_status_bar_button.tooltip = lint_report + '\\nClick to recheck';\n lint_status_bar_button.command = 'rainbow-csv.CSVLint';\n lint_status_bar_button.show();\n}\n\n\nfunction show_align_shrink_button(file_path) {\n if (!align_shrink_button)\n align_shrink_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);\n if (aligned_files.has(file_path)) {\n align_shrink_button.text = 'Shrink';\n align_shrink_button.tooltip = 'Click to shrink table (Then you can click again to align)';\n align_shrink_button.command = 'rainbow-csv.Shrink';\n } else {\n align_shrink_button.text = 'Align';\n align_shrink_button.tooltip = 'Click to align table (Then you can click again to shrink)';\n align_shrink_button.command = 'rainbow-csv.Align';\n }\n align_shrink_button.show();\n}\n\n\nfunction show_rainbow_off_status_bar_button() {\n if (!rainbow_off_status_bar_button)\n rainbow_off_status_bar_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);\n rainbow_off_status_bar_button.text = 'Rainbow OFF';\n rainbow_off_status_bar_button.tooltip = 'Click to restore original file type and syntax';\n rainbow_off_status_bar_button.command = 'rainbow-csv.RainbowSeparatorOff';\n rainbow_off_status_bar_button.show();\n}\n\n\nfunction show_rbql_status_bar_button() {\n if (!rbql_status_bar_button)\n rbql_status_bar_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);\n rbql_status_bar_button.text = 'Query';\n rbql_status_bar_button.tooltip = 'Click to run SQL-like RBQL query';\n rbql_status_bar_button.command = 'rainbow-csv.RBQL';\n rbql_status_bar_button.show();\n}\n\n\nfunction hide_status_bar_buttons() {\n let all_buttons = [lint_status_bar_button, rbql_status_bar_button, rainbow_off_status_bar_button, copy_back_button, align_shrink_button];\n for (let i = 0; i < all_buttons.length; i++) {\n if (all_buttons[i])\n all_buttons[i].hide();\n }\n}\n\n\nfunction show_rbql_copy_to_source_button(file_path) {\n let parent_table_path = result_set_parent_map.get(file_path.toLowerCase());\n if (!parent_table_path || parent_table_path.indexOf(scratch_buf_marker) != -1)\n return;\n let parent_basename = path.basename(parent_table_path);\n if (!copy_back_button)\n copy_back_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left);\n copy_back_button.text = 'Copy Back';\n copy_back_button.tooltip = `Copy to parent table: ${parent_basename}`;\n copy_back_button.command = 'rainbow-csv.CopyBack';\n copy_back_button.show();\n}\n\n\nfunction refresh_status_bar_buttons(active_doc=null) {\n if (!active_doc)\n active_doc = get_active_doc();\n last_statusbar_doc = active_doc;\n var file_path = active_doc ? active_doc.fileName : null;\n if (!active_doc || !file_path) {\n hide_status_bar_buttons();\n return;\n }\n if (file_path.endsWith('.git')) {\n return; // Sometimes for git-controlled dirs VSCode opens mysterious .git files. Skip them, don't hide buttons.\n }\n hide_status_bar_buttons();\n var language_id = active_doc.languageId;\n if (!dialect_map.hasOwnProperty(language_id))\n return;\n show_lint_status_bar_button(file_path, language_id);\n show_rbql_status_bar_button();\n show_align_shrink_button(file_path);\n show_rainbow_off_status_bar_button();\n show_rbql_copy_to_source_button(file_path);\n}\n\n\nfunction csv_lint(active_doc, is_manual_op) {\n if (!active_doc)\n active_doc = get_active_doc();\n if (!active_doc)\n return null;\n var file_path = active_doc.fileName; // For new unitled scratch documents this would be \"Untitled-1\", \"Untitled-2\", etc...\n if (!file_path)\n return null;\n var language_id = active_doc.languageId;\n if (!dialect_map.hasOwnProperty(language_id))\n return null;\n let lint_cache_key = `${file_path}.${language_id}`;\n if (!is_manual_op) {\n if (lint_results.has(lint_cache_key))\n return null;\n if (!get_from_config('enable_auto_csv_lint', false))\n return null;\n }\n lint_results.set(lint_cache_key, 'Processing...');\n refresh_status_bar_buttons(active_doc); // Visual feedback.\n let [delim, policy] = dialect_map[language_id];\n var lint_report = produce_lint_report(active_doc, delim, policy);\n lint_results.set(lint_cache_key, lint_report);\n return lint_report;\n}\n\n\nasync function csv_lint_cmd() {\n // TODO re-run on each file save with content change.\n let lint_report = csv_lint(null, true);\n // Need timeout here to give user enough time to notice green -> yellow -> green switch, this is a sort of visual feedback.\n await sleep(500);\n refresh_status_bar_buttons();\n return lint_report;\n}\n\n\nasync function run_internal_test_cmd(integration_test_options) {\n if (integration_test_options && integration_test_options.check_initialization_state) {\n // This mode is to ensure that the most basic operations do not cause rainbow csv to load extra (potentially heavy) code.\n // Vim uses the same approach with its plugin/autoload folder layout design.\n return {initialized: global_state !== null, lazy_loaded: rainbow_utils !== null};\n }\n if (integration_test_options && integration_test_options.check_last_rbql_report) {\n return _unit_test_last_rbql_report;\n }\n if (integration_test_options && integration_test_options.check_last_rbql_warnings) {\n return {'warnings': _unit_test_last_warnings};\n }\n return null;\n}\n\n\nasync function show_warnings(warnings) {\n _unit_test_last_warnings = [];\n if (!warnings || !warnings.length)\n return;\n var active_window = vscode.window;\n if (!active_window)\n return null;\n for (var i = 0; i < warnings.length; i++) {\n // Do not \"await\" warning messages because the promise gets resolved only on warning dismissal.\n active_window.showWarningMessage('RBQL warning: ' + warnings[i]);\n }\n _unit_test_last_warnings = warnings;\n}\n\n\nasync function handle_rbql_result_file(text_doc, warnings) {\n var out_delim = rbql_context.output_delim;\n let language_id = map_separator_to_language_id(out_delim);\n var active_window = vscode.window;\n if (!active_window)\n return;\n try {\n await active_window.showTextDocument(text_doc);\n } catch (error) {\n show_single_line_error('Unable to open RBQL result document');\n return;\n }\n if (language_id && text_doc.language_id != language_id) {\n console.log('changing RBQL result language ' + text_doc.language_id + ' -> ' + language_id);\n await vscode.languages.setTextDocumentLanguage(text_doc, language_id);\n }\n await show_warnings(warnings);\n}\n\n\nfunction run_command(cmd, args, close_and_error_guard, callback_func) {\n var command = child_process.spawn(cmd, args, {'windowsHide': true});\n var stdout = '';\n var stderr = '';\n command.stdout.on('data', function(data) {\n stdout += data.toString();\n });\n command.stderr.on('data', function(data) {\n stderr += data.toString();\n });\n command.on('close', function(code) {\n if (!close_and_error_guard['process_reported']) {\n close_and_error_guard['process_reported'] = true;\n callback_func(code, stdout, stderr);\n }\n });\n command.on('error', function(error) {\n var error_msg = error ? error.name + ': ' + error.message : '';\n if (!close_and_error_guard['process_reported']) {\n close_and_error_guard['process_reported'] = true;\n callback_func(1, '', 'Something went wrong. Make sure you have python installed and added to PATH variable in your OS. Or you can use it with JavaScript instead - it should work out of the box\\nDetails:\\n' + error_msg);\n }\n });\n}\n\n\nasync function handle_command_result(src_table_path, dst_table_path, error_code, stdout, stderr, webview_report_handler) {\n let json_report = stdout;\n let error_type = null;\n let error_msg = null;\n let warnings = [];\n if (error_code || !json_report || stderr) {\n error_type = 'Integration';\n error_msg = stderr ? stderr : 'empty error';\n } else {\n try {\n let report = JSON.parse(json_report);\n if (report.hasOwnProperty('error_type'))\n error_type = report['error_type'];\n if (report.hasOwnProperty('error_msg'))\n error_msg = report['error_msg'];\n if (report.hasOwnProperty('warnings'))\n warnings = report['warnings'];\n } catch (e) {\n error_type = 'Integration';\n error_msg = 'Unable to parse JSON report';\n }\n }\n webview_report_handler(error_type, error_msg);\n if (error_type || error_msg) {\n return; // Just exit: error would be shown in the preview window.\n }\n // No need to close the RBQL console here, better to leave it open so it can be used to quickly adjust the query if needed.\n autodetection_stoplist.add(dst_table_path);\n result_set_parent_map.set(dst_table_path.toLowerCase(), src_table_path);\n let doc = await vscode.workspace.openTextDocument(dst_table_path);\n await handle_rbql_result_file(doc, warnings);\n}\n\n\nfunction get_dst_table_name(input_path, output_delim) {\n var table_name = path.basename(input_path);\n var orig_extension = path.extname(table_name);\n var delim_ext_map = {'\\t': '.tsv', ',': '.csv'};\n var dst_extension = '.txt';\n if (delim_ext_map.hasOwnProperty(output_delim)) {\n dst_extension = delim_ext_map[output_delim];\n } else if (orig_extension.length > 1) {\n dst_extension = orig_extension;\n }\n let result_table_name = table_name + dst_extension;\n if (result_table_name == table_name) { // Just being paranoid to avoid overwriting input table accidentally when output dir configured to be the same as input.\n result_table_name += '.txt';\n }\n return result_table_name;\n}\n\n\nfunction file_path_to_query_key(file_path) {\n return (file_path && file_path.indexOf(scratch_buf_marker) != -1) ? scratch_buf_marker : file_path;\n}\n\nfunction get_dst_table_dir(input_table_path) {\n let rbql_output_dir = get_from_config('rbql_output_dir', 'TMP')\n if (rbql_output_dir == 'TMP') {\n return os.tmpdir();\n } else if (rbql_output_dir == 'INPUT') {\n return path.dirname(input_table_path);\n } else {\n // Return custom directory. If the directory does not exist or isn't writable RBQL itself will report more or less clear error.\n return rbql_output_dir;\n }\n}\n\n\nasync function run_rbql_query(input_path, csv_encoding, backend_language, rbql_query, output_dialect, enable_rfc_newlines, with_headers, webview_report_handler) {\n last_rbql_queries.set(file_path_to_query_key(input_path), rbql_query);\n var cmd = 'python';\n const test_marker = 'test ';\n let close_and_error_guard = {'process_reported': false};\n\n let [input_delim, input_policy] = [rbql_context.delim, rbql_context.policy];\n if (input_policy == 'quoted' && enable_rfc_newlines)\n input_policy = 'quoted_rfc';\n let [output_delim, output_policy] = [input_delim, input_policy];\n if (output_dialect == 'csv')\n [output_delim, output_policy] = [',', 'quoted']; // XXX should it be \"quoted_rfc\" instead?\n if (output_dialect == 'tsv')\n [output_delim, output_policy] = ['\\t', 'simple'];\n rbql_context.output_delim = output_delim;\n\n let output_path = is_web_ext ? null : path.join(get_dst_table_dir(input_path), get_dst_table_name(input_path, output_delim));\n\n if (rbql_query.startsWith(test_marker)) {\n if (rbql_query.indexOf('nopython') != -1) {\n cmd = 'nopython';\n }\n let args = [absolute_path_map['rbql mock/rbql_mock.py'], rbql_query];\n run_command(cmd, args, close_and_error_guard, function(error_code, stdout, stderr) { handle_command_result(input_path, output_path, error_code, stdout, stderr, webview_report_handler); });\n return;\n }\n if (backend_language == 'js') {\n let warnings = [];\n let result_doc = null;\n try {\n if (is_web_ext) {\n let result_lines = await ll_rainbow_utils().rbql_query_web(rbql_query, rbql_context.input_document, input_delim, input_policy, output_delim, output_policy, warnings, with_headers, null);\n let output_doc_cfg = {content: result_lines.join('\\n'), language: map_separator_to_language_id(output_delim)};\n result_doc = await vscode.workspace.openTextDocument(output_doc_cfg);\n } else {\n let csv_options = {'bulk_read': true};\n await ll_rainbow_utils().rbql_query_node(global_state, rbql_query, input_path, input_delim, input_policy, output_path, output_delim, output_policy, csv_encoding, warnings, with_headers, null, '', csv_options);\n result_set_parent_map.set(output_path.toLowerCase(), input_path);\n autodetection_stoplist.add(output_path);\n result_doc = await vscode.workspace.openTextDocument(output_path);\n }\n } catch (e) {\n let [error_type, error_msg] = ll_rbql_csv().exception_to_error_info(e);\n webview_report_handler(error_type, error_msg);\n return;\n }\n webview_report_handler(null, null);\n await handle_rbql_result_file(result_doc, warnings);\n } else {\n if (is_web_ext) {\n webview_report_handler('Input error', 'Python backend for RBQL is not supported in web version, please use JavaScript backend.');\n return;\n }\n let cmd_safe_query = Buffer.from(rbql_query, \"utf-8\").toString(\"base64\");\n let args = [absolute_path_map['rbql_core/vscode_rbql.py'], cmd_safe_query, input_path, input_delim, input_policy, output_path, output_delim, output_policy, csv_encoding];\n if (with_headers)\n args.push('--with_headers');\n run_command(cmd, args, close_and_error_guard, function(error_code, stdout, stderr) { handle_command_result(input_path, output_path, error_code, stdout, stderr, webview_report_handler); });\n }\n}\n\n\nfunction get_dialect(document) {\n var language_id = document.languageId;\n if (!dialect_map.hasOwnProperty(language_id))\n return ['monocolumn', 'monocolumn'];\n return dialect_map[language_id];\n}\n\n\nasync function set_header_line() {\n let active_editor = get_active_editor();\n if (!active_editor)\n return;\n var active_doc = get_active_doc(active_editor);\n if (!active_doc)\n return;\n\n var dialect = get_dialect(active_doc);\n var delim = dialect[0];\n var policy = dialect[1];\n if (policy == 'monocolumn') {\n show_single_line_error('Unable to set header line: no separator specified');\n return;\n }\n let file_path = active_doc.fileName;\n if (!file_path) {\n show_single_line_error('Unable to set header line for non-file documents');\n return;\n }\n let selection = active_editor.selection;\n let raw_header = active_doc.lineAt(selection.start.line).text;\n\n let header = csv_utils.smart_split(raw_header, delim, policy, false)[0];\n await save_to_global_state(make_header_key(file_path), JSON.stringify(header));\n}\n\n\nasync function set_rainbow_separator() {\n let active_editor = get_active_editor();\n if (!active_editor)\n return;\n var active_doc = get_active_doc(active_editor);\n if (!active_doc)\n return;\n let original_language_id = active_doc.languageId;\n let selection = active_editor.selection;\n if (!selection) {\n show_single_line_error(\"Selection is empty\");\n return;\n }\n if (selection.start.line != selection.end.line || selection.start.character + 1 != selection.end.character) {\n show_single_line_error(\"Selection must contain exactly one separator character\");\n return;\n }\n let separator = active_doc.lineAt(selection.start.line).text.charAt(selection.start.character);\n let language_id = map_separator_to_language_id(separator);\n if (!language_id) {\n show_single_line_error(\"Selected separator is not supported\");\n return;\n }\n\n let doc = await vscode.languages.setTextDocumentLanguage(active_doc, language_id);\n original_language_ids.set(doc.fileName, original_language_id);\n csv_lint(doc, false);\n refresh_status_bar_buttons(doc);\n}\n\n\nasync function restore_original_language() {\n var active_doc = get_active_doc();\n if (!active_doc)\n return;\n let file_path = active_doc.fileName;\n autodetection_stoplist.add(file_path);\n let original_language_id = 'plaintext';\n if (original_language_ids.has(file_path)) {\n original_language_id = original_language_ids.get(file_path);\n }\n if (!original_language_id || original_language_id == active_doc.languageId) {\n show_single_line_error(\"Unable to restore original language\");\n return;\n }\n\n let doc = await vscode.languages.setTextDocumentLanguage(active_doc, original_language_id);\n original_language_ids.delete(file_path);\n refresh_status_bar_buttons(doc);\n}\n\n\nasync function set_join_table_name() {\n if (is_web_ext) {\n show_single_line_error('This command is currently unavailable in web mode.');\n return;\n }\n var active_doc = get_active_doc();\n if (!active_doc)\n return;\n let file_path = active_doc.fileName;\n if (!file_path) {\n show_single_line_error('Unable to use this document as join table');\n return;\n }\n var title = \"Input table name to use in RBQL JOIN expressions instead of table path\";\n var input_box_props = {\"prompt\": title, \"value\": 'b'};\n let table_name = await vscode.window.showInputBox(input_box_props);\n if (!table_name)\n return; // User pressed Esc and closed the input box.\n save_to_global_state(ll_rainbow_utils().make_table_name_key(table_name), file_path);\n}\n\n\nasync function set_virtual_header() {\n var active_doc = get_active_doc();\n var dialect = get_dialect(active_doc);\n var delim = dialect[0];\n var policy = dialect[1];\n var file_path = active_doc.fileName;\n if (!file_path) {\n show_single_line_error('Unable to edit column names for non-file documents');\n return;\n }\n if (policy == 'monocolumn') {\n show_single_line_error('Unable to set virtual header: no separator specified');\n return;\n }\n var old_header = get_header(active_doc, delim, policy);\n var title = \"Adjust column names displayed in hover tooltips. Actual header line and file content won't be affected.\";\n var old_header_str = quoted_join(old_header, delim);\n var input_box_props = {\"prompt\": title, \"value\": old_header_str};\n let raw_new_header = await vscode.window.showInputBox(input_box_props);\n if (!raw_new_header)\n return; // User pressed Esc and closed the input box.\n let new_header = csv_utils.smart_split(raw_new_header, delim, policy, false)[0];\n await save_to_global_state(make_header_key(file_path), JSON.stringify(new_header));\n}\n\n\nasync function column_edit(edit_mode) {\n let active_editor = get_active_editor();\n if (!active_editor || !active_editor.selection)\n return;\n let active_doc = active_editor.document;\n if (!active_doc)\n return;\n let dialect = get_dialect(active_doc);\n let delim = dialect[0];\n let policy = dialect[1];\n let comment_prefix = get_from_config('comment_prefix', '');\n\n let position = active_editor.selection.active;\n let lnum = position.line;\n let cnum = position.character;\n let line = active_doc.lineAt(lnum).text;\n\n let report = csv_utils.smart_split(line, delim, policy, true);\n\n let entries = report[0];\n let quoting_warning = report[1];\n let col_num = get_field_by_line_position(entries, cnum + 1);\n\n let selections = [];\n let num_lines = active_doc.lineCount;\n if (num_lines >= 10000) {\n show_single_line_error('Multicursor column edit works only for files smaller than 10000 lines.');\n return;\n }\n for (let lnum = 0; lnum < num_lines; lnum++) {\n let line_text = active_doc.lineAt(lnum).text;\n if (lnum + 1 == num_lines && !line_text)\n break;\n if (comment_prefix && line_text.startsWith(comment_prefix))\n continue;\n let report = csv_utils.smart_split(line_text, delim, policy, true);\n let entries = report[0];\n quoting_warning = quoting_warning || report[1];\n if (col_num >= entries.length) {\n show_single_line_error(`Line ${lnum + 1} doesn't have field number ${col_num + 1}`);\n return;\n }\n let char_pos_before = entries.slice(0, col_num).join('').length + col_num;\n let char_pos_after = entries.slice(0, col_num + 1).join('').length + col_num;\n if (edit_mode == 'ce_before' && policy == 'quoted' && line_text.substring(char_pos_before - 2, char_pos_before + 2).indexOf('\"') != -1) {\n show_single_line_error(`Accidental data corruption prevention: Cursor at line ${lnum + 1} will not be set: a double quote is in proximity.`);\n return;\n }\n if (edit_mode == 'ce_after' && policy == 'quoted' && line_text.substring(char_pos_after - 2, char_pos_after + 2).indexOf('\"') != -1) {\n show_single_line_error(`Accidental data corruption prevention: Cursor at line ${lnum + 1} will not be set: a double quote is in proximity.`);\n return;\n }\n if (edit_mode == 'ce_select' && char_pos_before == char_pos_after) {\n show_single_line_error(`Accidental data corruption prevention: The column can not be selected: field ${col_num + 1} at line ${lnum + 1} is empty.`);\n return;\n }\n let position_before = new vscode.Position(lnum, char_pos_before);\n let position_after = new vscode.Position(lnum, char_pos_after);\n if (edit_mode == 'ce_before') {\n selections.push(new vscode.Selection(position_before, position_before));\n }\n if (edit_mode == 'ce_after') {\n selections.push(new vscode.Selection(position_after, position_after));\n }\n if (edit_mode == 'ce_select') {\n selections.push(new vscode.Selection(position_before, position_after));\n }\n }\n active_editor.selections = selections;\n if (quoting_warning) {\n vscode.window.showWarningMessage('Some lines have quoting issues: cursors positioning may be incorrect.');\n }\n // Call showTextDocument so that the editor will gain focus and the cursors will become active and blinking. This is a critical step here!\n await vscode.window.showTextDocument(active_doc);\n}\n\n\nasync function shrink_table() {\n let active_editor = get_active_editor();\n let active_doc = get_active_doc(active_editor);\n if (!active_doc)\n return;\n let language_id = active_doc.languageId;\n if (!dialect_map.hasOwnProperty(language_id))\n return;\n let [delim, policy] = dialect_map[language_id];\n let comment_prefix = get_from_config('comment_prefix', '');\n let progress_options = {location: vscode.ProgressLocation.Window, title: 'Rainbow CSV'};\n await vscode.window.withProgress(progress_options, async (progress) => {\n progress.report({message: 'Preparing'});\n await push_current_stack_to_js_callback_queue_to_allow_ui_update();\n let [shrinked_doc_text, first_failed_line] = ll_rainbow_utils().shrink_columns(active_doc, delim, policy, comment_prefix);\n if (first_failed_line) {\n show_single_line_error(`Unable to shrink: Inconsistent double quotes at line ${first_failed_line}`);\n return;\n }\n aligned_files.delete(active_doc.fileName);\n refresh_status_bar_buttons(active_doc);\n if (shrinked_doc_text === null) {\n vscode.window.showWarningMessage('No trailing whitespaces found, skipping');\n return;\n }\n progress.report({message: 'Shrinking columns'});\n await push_current_stack_to_js_callback_queue_to_allow_ui_update();\n await replace_doc_content(active_editor, active_doc, shrinked_doc_text);\n });\n}\n\n\nasync function align_table() {\n let active_editor = get_active_editor();\n let active_doc = get_active_doc(active_editor);\n if (!active_doc)\n return;\n let language_id = active_doc.languageId;\n if (!dialect_map.hasOwnProperty(language_id))\n return;\n let [delim, policy] = dialect_map[language_id];\n let comment_prefix = get_from_config('comment_prefix', '');\n let progress_options = {location: vscode.ProgressLocation.Window, title: 'Rainbow CSV'};\n await vscode.window.withProgress(progress_options, async (progress) => {\n progress.report({message: 'Calculating column statistics'});\n await push_current_stack_to_js_callback_queue_to_allow_ui_update();\n let [column_stats, first_failed_line] = ll_rainbow_utils().calc_column_stats(active_doc, delim, policy, comment_prefix);\n if (first_failed_line) {\n show_single_line_error(`Unable to align: Inconsistent double quotes at line ${first_failed_line}`);\n return;\n }\n column_stats = ll_rainbow_utils().adjust_column_stats(column_stats);\n if (column_stats === null) {\n show_single_line_error('Unable to allign: Internal Rainbow CSV Error');\n return;\n }\n progress.report({message: 'Preparing final alignment'});\n await push_current_stack_to_js_callback_queue_to_allow_ui_update();\n aligned_doc_text = ll_rainbow_utils().align_columns(active_doc, delim, policy, comment_prefix, column_stats);\n aligned_files.add(active_doc.fileName);\n refresh_status_bar_buttons(active_doc);\n if (aligned_doc_text === null) {\n vscode.window.showWarningMessage('Table is already aligned, skipping');\n return;\n }\n // The last stage of actually applying the edits takes almost 80% of the whole alignment runtime.\n progress.report({message: 'Aligning columns'});\n await push_current_stack_to_js_callback_queue_to_allow_ui_update();\n await replace_doc_content(active_editor, active_doc, aligned_doc_text);\n });\n}\n\n\nasync function do_copy_back(query_result_doc, active_editor) {\n let data = query_result_doc.getText();\n let active_doc = get_active_doc(active_editor);\n if (!active_doc)\n return;\n await replace_doc_content(active_editor, active_doc, data);\n}\n\n\nasync function copy_back() {\n if (is_web_ext) {\n show_single_line_error('This command is currently unavailable in web mode.');\n return;\n }\n let result_doc = get_active_doc();\n if (!result_doc)\n return;\n let file_path = result_doc.fileName;\n let parent_table_path = result_set_parent_map.get(file_path.toLowerCase());\n if (!parent_table_path)\n return;\n let parent_doc = await vscode.workspace.openTextDocument(parent_table_path);\n let parent_editor = await vscode.window.showTextDocument(parent_doc);\n await do_copy_back(result_doc, parent_editor);\n}\n\n\nasync function update_query_history(query) {\n let history_list = get_from_global_state('rbql_query_history', []);\n let old_index = history_list.indexOf(query);\n if (old_index != -1) {\n history_list.splice(old_index, 1);\n } else if (history_list.length >= 20) {\n history_list.splice(0, 1);\n }\n history_list.push(query);\n await save_to_global_state('rbql_query_history', history_list);\n}\n\n\nasync function handle_rbql_client_message(webview, message, integration_test_options=null) {\n let message_type = message['msg_type'];\n\n let webview_report_handler = async function(error_type, error_msg) {\n let report_msg = {'msg_type': 'rbql_report'};\n if (error_type)\n report_msg[\"error_type\"] = error_type;\n if (error_msg)\n report_msg[\"error_msg\"] = error_msg;\n _unit_test_last_rbql_report = report_msg;\n await webview.postMessage(report_msg);\n };\n\n if (message_type == 'handshake') {\n var backend_language = get_from_global_state('rbql_backend_language', 'js');\n var encoding = get_from_global_state('rbql_encoding', 'utf-8');\n var init_msg = {'msg_type': 'handshake', 'backend_language': backend_language, 'encoding': encoding};\n sample_preview_records_from_context(rbql_context, init_msg);\n let path_key = file_path_to_query_key(rbql_context.input_document_path);\n if (last_rbql_queries.has(path_key))\n init_msg['last_query'] = last_rbql_queries.get(path_key);\n let history_list = get_from_global_state('rbql_query_history', []);\n init_msg['query_history'] = history_list;\n init_msg['policy'] = rbql_context.policy;\n init_msg['enable_rfc_newlines'] = rbql_context.enable_rfc_newlines;\n init_msg['with_headers'] = rbql_context.with_headers;\n init_msg['header'] = rbql_context.header;\n init_msg['is_web_ext'] = is_web_ext;\n if (integration_test_options) {\n init_msg['integration_test_language'] = integration_test_options.rbql_backend;\n init_msg['integration_test_query'] = integration_test_options.rbql_query;\n init_msg['integration_test_with_headers'] = integration_test_options.with_headers || false;\n init_msg['integration_test_enable_rfc_newlines'] = integration_test_options.enable_rfc_newlines || false;\n }\n await webview.postMessage(init_msg);\n }\n\n if (message_type == 'fetch_table_header') {\n try {\n let table_id = message['table_id'];\n let encoding = message['encoding'];\n\n let input_table_dir = rbql_context.input_document_path ? path.dirname(rbql_context.input_document_path) : null;\n let table_path = ll_rainbow_utils().find_table_path(global_state, input_table_dir, table_id);\n if (!table_path)\n return;\n let header_line = await ll_rainbow_utils().read_header(table_path, encoding);\n let [fields, warning] = csv_utils.smart_split(header_line, rbql_context.delim, rbql_context.policy, false);\n if (!warning) {\n webview.postMessage({'msg_type': 'fetch_table_header_response', 'header': fields});\n }\n } catch (e) {\n console.error('Unable to get join table header: ' + String(e));\n }\n }\n\n if (message_type == 'update_query') {\n let rbql_query = message['query'];\n if (!rbql_query)\n return;\n if (rbql_context.input_document_path)\n last_rbql_queries.set(file_path_to_query_key(rbql_context.input_document_path), rbql_query);\n }\n\n if (message_type == 'newlines_policy_change') {\n rbql_context.enable_rfc_newlines = message['enable_rfc_newlines'];\n if (rbql_context.input_document_path)\n await save_to_global_state(make_rfc_policy_key(rbql_context.input_document_path), rbql_context.enable_rfc_newlines);\n let protocol_message = {'msg_type': 'resample'};\n sample_preview_records_from_context(rbql_context, protocol_message);\n await webview.postMessage(protocol_message);\n }\n\n if (message_type == 'with_headers_change') {\n rbql_context.with_headers = message['with_headers'];\n if (rbql_context.input_document_path)\n await save_to_global_state(make_with_headers_key(rbql_context.input_document_path), rbql_context.with_headers);\n }\n\n if (message_type == 'navigate') {\n var navig_direction = message['direction'];\n if (navig_direction == 'backward') {\n rbql_context.requested_start_record -= preview_window_size;\n } else if (navig_direction == 'forward') {\n rbql_context.requested_start_record += preview_window_size;\n } else if (navig_direction == 'begin') {\n rbql_context.requested_start_record = 0;\n } else if (navig_direction == 'end') {\n rbql_context.requested_start_record = rbql_context.input_document.lineCount; // This is just max possible value which is incorrect and will be adjusted later.\n }\n let protocol_message = {'msg_type': 'navigate'};\n sample_preview_records_from_context(rbql_context, protocol_message);\n await webview.postMessage(protocol_message);\n }\n\n if (message_type == 'run') {\n let rbql_query = message['query'];\n let backend_language = message['backend_language'];\n let encoding = message['encoding'];\n let output_dialect = message['output_dialect'];\n let enable_rfc_newlines = message['enable_rfc_newlines'];\n let with_headers = message['with_headers'];\n await update_query_history(rbql_query);\n await run_rbql_query(rbql_context.input_document_path, encoding, backend_language, rbql_query, output_dialect, enable_rfc_newlines, with_headers, webview_report_handler);\n }\n\n if (message_type == 'edit_udf') {\n if (is_web_ext) {\n webview_report_handler('Input error', 'UDFs are currently not supported in web version');\n return;\n }\n let backend_language = message['backend_language'];\n let udf_file_path = null;\n let default_content = '';\n if (backend_language == 'js') {\n udf_file_path = path.join(os.homedir(), '.rbql_init_source.js');\n default_content = ll_rainbow_utils().get_default_js_udf_content();\n } else {\n udf_file_path = path.join(os.homedir(), '.rbql_init_source.py');\n default_content = ll_rainbow_utils().get_default_python_udf_content();\n }\n if (!fs.existsSync(udf_file_path)) {\n fs.writeFileSync(udf_file_path, default_content);\n }\n let udf_doc = await vscode.workspace.openTextDocument(udf_file_path);\n await vscode.window.showTextDocument(udf_doc);\n }\n\n if (message_type == 'global_param_change') {\n await save_to_global_state(message['key'], message['value']);\n }\n}\n\n\nfunction adjust_webview_paths(paths_list, client_html) {\n for (const local_path of paths_list) {\n let adjusted_webview_url = null;\n if (is_web_ext) {\n adjusted_webview_url = absolute_path_map[local_path];\n } else {\n adjusted_webview_url = preview_panel.webview.asWebviewUri(vscode.Uri.file(absolute_path_map[local_path]));\n }\n client_html = client_html.replace(`src=\"${local_path}\"`, `src=\"${adjusted_webview_url}\"`);\n }\n return client_html;\n}\n\n\nasync function edit_rbql(integration_test_options=null) {\n let active_window = vscode.window;\n if (!active_window)\n return;\n let active_editor = active_window.activeTextEditor;\n if (!active_editor)\n return;\n let active_doc = active_editor.document;\n if (!active_doc)\n return;\n let orig_uri = active_doc.uri;\n if (!orig_uri)\n return;\n // For web orig_uri.scheme can have other valid values e.g. `vscode-test-web` when testing the browser integration.\n if (orig_uri.scheme != 'file' && orig_uri.scheme != 'untitled' && !is_web_ext)\n return;\n if (orig_uri.scheme == 'file' && active_doc.isDirty && !is_web_ext) {\n show_single_line_error(\"Unable to run RBQL: file has unsaved changes\");\n return;\n }\n let input_path = null;\n if (orig_uri.scheme == 'untitled' && !is_web_ext) {\n // Scheme 'untitled' means that the document is a scratch buffer that hasn't been saved yet, see https://code.visualstudio.com/api/references/document-selector\n let data = active_doc.getText();\n let rnd_suffix = String(Math.floor(Math.random() * 1000000));\n input_path = path.join(os.tmpdir(), `${scratch_buf_marker}_${rnd_suffix}.txt`);\n // TODO consider adding username to the input_path and using chmod 600 on it.\n fs.writeFileSync(input_path, data);\n } else {\n input_path = active_doc.fileName;\n }\n\n if (!input_path) {\n show_single_line_error(\"Unable to run RBQL for this file\");\n return;\n }\n let language_id = active_doc.languageId;\n let delim = 'monocolumn';\n let policy = 'monocolumn';\n if (dialect_map.hasOwnProperty(language_id)) {\n [delim, policy] = dialect_map[language_id];\n }\n let enable_rfc_newlines = get_from_global_state(make_rfc_policy_key(input_path), false);\n let with_headers_by_default = get_from_config('rbql_with_headers_by_default', false);\n let with_headers = get_from_global_state(make_with_headers_key(input_path), with_headers_by_default);\n let header = get_header_from_document(active_doc, delim, policy);\n rbql_context = {\n \"input_document\": active_doc,\n \"input_document_path\": input_path,\n \"requested_start_record\": 0,\n \"delim\": delim,\n \"policy\": policy,\n \"rfc_record_map\": [],\n \"enable_rfc_newlines\": enable_rfc_newlines,\n \"with_headers\": with_headers,\n \"header\": header\n };\n\n preview_panel = vscode.window.createWebviewPanel('rbql-console', 'RBQL Console', vscode.ViewColumn.Active, {enableScripts: true});\n if (!client_html_template) {\n if (is_web_ext) {\n client_html_template = client_html_template_web;\n } else {\n client_html_template = fs.readFileSync(absolute_path_map['rbql_client.html'], \"utf8\");\n }\n }\n let client_html = client_html_template;\n client_html = adjust_webview_paths(['contrib/textarea-caret-position/index.js', 'rbql_suggest.js', 'rbql_client.js', 'rbql_logo.svg'], client_html);\n preview_panel.webview.html = client_html;\n preview_panel.webview.onDidReceiveMessage(function(message) { handle_rbql_client_message(preview_panel.webview, message, integration_test_options); });\n}\n\n\nfunction get_num_columns_if_delimited(active_doc, delim, policy, min_num_columns, min_num_lines) {\n var num_lines = active_doc.lineCount;\n let num_fields = 0;\n let num_lines_checked = 0;\n let comment_prefix_for_autodetection = get_from_config('comment_prefix', '');\n if (!comment_prefix_for_autodetection)\n comment_prefix_for_autodetection = '#';\n for (var lnum = 0; lnum < num_lines; lnum++) {\n var line_text = active_doc.lineAt(lnum).text;\n if (lnum + 1 == num_lines && !line_text)\n break;\n if (line_text.startsWith(comment_prefix_for_autodetection))\n continue;\n let [fields, warning] = csv_utils.smart_split(line_text, delim, policy, true);\n if (warning)\n return 0; // TODO don't fail on warnings?\n if (!num_fields)\n num_fields = fields.length;\n if (num_fields < min_num_columns || num_fields != fields.length)\n return 0;\n num_lines_checked += 1;\n }\n return num_lines_checked >= min_num_lines ? num_fields : 0;\n}\n\n\nfunction autodetect_dialect(active_doc, candidate_separators) {\n let min_num_lines = get_from_config('autodetection_min_line_count', 10);\n if (active_doc.lineCount < min_num_lines)\n return null;\n\n let best_dialect = null;\n let best_dialect_num_columns = 1;\n for (let i = 0; i < candidate_separators.length; i++) {\n let dialect_id = map_separator_to_language_id(candidate_separators[i]);\n if (!dialect_id)\n continue;\n let [delim, policy] = dialect_map[dialect_id];\n let cur_dialect_num_columns = get_num_columns_if_delimited(active_doc, delim, policy, best_dialect_num_columns + 1, min_num_lines);\n if (cur_dialect_num_columns > best_dialect_num_columns) {\n best_dialect_num_columns = cur_dialect_num_columns;\n best_dialect = dialect_id;\n }\n }\n return best_dialect;\n}\n\n\nfunction autodetect_dialect_frequency_based(active_doc, candidate_separators) {\n let best_dialect = 'csv';\n let best_dialect_frequency = 0;\n let data = active_doc.getText();\n if (!data)\n return best_dialect;\n for (let i = 0; i < candidate_separators.length; i++) {\n if (candidate_separators[i] == ' ' || candidate_separators[i] == '.')\n continue; // Whitespace and dot have advantage over other separators in this algorithm, so we just skip them.\n let dialect_id = map_separator_to_language_id(candidate_separators[i]);\n let frequency = 0;\n for (let j = 0; j < 10000 && j < data.length; j++) {\n if (data[j] == candidate_separators[i])\n frequency += 1;\n }\n if (frequency > best_dialect_frequency) {\n best_dialect = dialect_id;\n best_dialect_frequency = frequency;\n }\n }\n return best_dialect;\n}\n\n\nasync function autoenable_rainbow_csv(active_doc) {\n if (!active_doc)\n return;\n if (!get_from_config('enable_separator_autodetection', false))\n return;\n let candidate_separators = get_from_config('autodetect_separators', []);\n var original_language_id = active_doc.languageId;\n var file_path = active_doc.fileName;\n if (!file_path || autodetection_stoplist.has(file_path)) {\n return;\n }\n let is_default_csv = file_path.endsWith('.csv') && original_language_id == 'csv';\n if (original_language_id != 'plaintext' && !is_default_csv)\n return;\n let rainbow_csv_language_id = autodetect_dialect(active_doc, candidate_separators);\n if (!rainbow_csv_language_id && is_default_csv) {\n // Smart autodetection method has failed, but we need to choose a separator because this is a csv file. Let's just find the most popular one.\n rainbow_csv_language_id = autodetect_dialect_frequency_based(active_doc, candidate_separators);\n }\n if (!rainbow_csv_language_id || rainbow_csv_language_id == original_language_id)\n return;\n\n let doc = await vscode.languages.setTextDocumentLanguage(active_doc, rainbow_csv_language_id);\n original_language_ids.set(file_path, original_language_id);\n csv_lint(doc, false);\n refresh_status_bar_buttons(doc);\n}\n\n\nasync function handle_doc_edit(change_event) {\n if (!change_event)\n return;\n if (doc_edit_subscription) {\n doc_edit_subscription.dispose();\n doc_edit_subscription = null;\n }\n let active_doc = change_event.document;\n if (!active_doc)\n return;\n let candidate_separators = get_from_config('autodetect_separators', []);\n let rainbow_csv_language_id = autodetect_dialect(active_doc, candidate_separators);\n if (!rainbow_csv_language_id)\n return;\n let doc = await vscode.languages.setTextDocumentLanguage(active_doc, rainbow_csv_language_id);\n csv_lint(doc, false);\n refresh_status_bar_buttons(doc);\n}\n\n\nfunction register_csv_copy_paste(active_doc) {\n if (!get_from_config('enable_separator_autodetection', false))\n return;\n if (!active_doc || doc_edit_subscription)\n return;\n if (!active_doc.isUntitled && active_doc.lineCount != 0)\n return;\n doc_edit_subscription = vscode.workspace.onDidChangeTextDocument(handle_doc_edit);\n return;\n}\n\n\nfunction handle_editor_switch(editor) {\n let active_doc = get_active_doc(editor);\n csv_lint(active_doc, false);\n refresh_status_bar_buttons(active_doc);\n}\n\n\nasync function handle_doc_open(active_doc) {\n await autoenable_rainbow_csv(active_doc);\n register_csv_copy_paste(active_doc);\n csv_lint(active_doc, false);\n refresh_status_bar_buttons(active_doc);\n}\n\n\nfunction quote_field(field, delim) {\n if (field.indexOf('\"') != -1 || field.indexOf(delim) != -1) {\n return '\"' + field.replace(/\"/g, '\"\"') + '\"';\n }\n return field;\n}\n\n\nfunction quoted_join(fields, delim) {\n var quoted_fields = fields.map(function(val) { return quote_field(val, delim); });\n return quoted_fields.join(delim);\n}\n\n\nasync function make_preview(uri, preview_mode) {\n if (is_web_ext) {\n show_single_line_error('This command is currently unavailable in web mode.');\n return;\n }\n var file_path = uri.fsPath;\n if (!file_path || !fs.existsSync(file_path)) {\n vscode.window.showErrorMessage('Invalid file');\n return;\n }\n\n var size_limit = 1024000; // ~1MB\n var file_size_in_bytes = fs.statSync(file_path)['size'];\n if (file_size_in_bytes <= size_limit) {\n vscode.window.showWarningMessage('Rainbow CSV: The file is not big enough, showing the full file instead. Use this preview for files larger than 1MB');\n let full_orig_doc = await vscode.workspace.openTextDocument(file_path);\n await vscode.window.showTextDocument(full_orig_doc);\n return;\n }\n\n let file_basename = path.basename(file_path);\n const out_path = path.join(os.tmpdir(), `.rb_csv_preview.${preview_mode}.${file_basename}`);\n\n fs.open(file_path, 'r', (err, fd) => {\n if (err) {\n console.log(err.message);\n vscode.window.showErrorMessage('Unable to preview file');\n return;\n }\n\n var buffer = Buffer.alloc(size_limit);\n let read_begin_pos = preview_mode == 'head' ? 0 : Math.max(file_size_in_bytes - size_limit, 0);\n fs.read(fd, buffer, 0, size_limit, read_begin_pos, function(err, _num) {\n if (err) {\n console.log(err.message);\n vscode.window.showErrorMessage('Unable to preview file');\n return;\n }\n\n const buffer_str = buffer.toString();\n // TODO handle old mac '\\r' line endings - still used by Mac version of Excel.\n let content = null;\n if (preview_mode == 'head') {\n content = buffer_str.substr(0, buffer_str.lastIndexOf(buffer_str.includes('\\r\\n') ? '\\r\\n' : '\\n'));\n } else {\n content = buffer_str.substr(buffer_str.indexOf('\\n') + 1);\n }\n fs.writeFileSync(out_path, content);\n vscode.workspace.openTextDocument(out_path).then(doc => vscode.window.showTextDocument(doc));\n });\n });\n}\n\n\nfunction register_csv_hover_info_provider(language_id, context) {\n let hover_provider = vscode.languages.registerHoverProvider(language_id, {\n provideHover(document, position, token) {\n return make_hover(document, position, language_id, token);\n }\n });\n context.subscriptions.push(hover_provider);\n}\n\n\nasync function activate(context) {\n global_state = context.globalState;\n\n if (is_web_ext) {\n let rbql_client_uri = vscode.Uri.joinPath(context.extensionUri, 'rbql_client.html');\n let bytes = await vscode.workspace.fs.readFile(rbql_client_uri);\n // Using TextDecoder because it should work fine in web extension.\n client_html_template_web = new TextDecoder().decode(bytes);\n }\n\n for (let local_path in absolute_path_map) {\n if (absolute_path_map.hasOwnProperty(local_path)) {\n if (is_web_ext) {\n absolute_path_map[local_path] = vscode.Uri.joinPath(context.extensionUri, local_path);\n } else {\n absolute_path_map[local_path] = context.asAbsolutePath(local_path);\n }\n }\n }\n\n for (let language_id in dialect_map) {\n if (dialect_map.hasOwnProperty(language_id)) {\n register_csv_hover_info_provider(language_id, context);\n }\n }\n\n var lint_cmd = vscode.commands.registerCommand('rainbow-csv.CSVLint', csv_lint_cmd);\n var rbql_cmd = vscode.commands.registerCommand('rainbow-csv.RBQL', edit_rbql);\n var set_header_line_cmd = vscode.commands.registerCommand('rainbow-csv.SetHeaderLine', set_header_line);\n var edit_column_names_cmd = vscode.commands.registerCommand('rainbow-csv.SetVirtualHeader', set_virtual_header);\n var set_join_table_name_cmd = vscode.commands.registerCommand('rainbow-csv.SetJoinTableName', set_join_table_name); // WEB_DISABLED\n var column_edit_before_cmd = vscode.commands.registerCommand('rainbow-csv.ColumnEditBefore', async function() { await column_edit('ce_before'); });\n var column_edit_after_cmd = vscode.commands.registerCommand('rainbow-csv.ColumnEditAfter', async function() { await column_edit('ce_after'); });\n var column_edit_select_cmd = vscode.commands.registerCommand('rainbow-csv.ColumnEditSelect', async function() { await column_edit('ce_select'); });\n var set_separator_cmd = vscode.commands.registerCommand('rainbow-csv.RainbowSeparator', set_rainbow_separator);\n var rainbow_off_cmd = vscode.commands.registerCommand('rainbow-csv.RainbowSeparatorOff', restore_original_language);\n var sample_head_cmd = vscode.commands.registerCommand('rainbow-csv.SampleHead', async function(uri) { await make_preview(uri, 'head'); }); // WEB_DISABLED\n var sample_tail_cmd = vscode.commands.registerCommand('rainbow-csv.SampleTail', async function(uri) { await make_preview(uri, 'tail'); }); // WEB_DISABLED\n var align_cmd = vscode.commands.registerCommand('rainbow-csv.Align', align_table);\n var shrink_cmd = vscode.commands.registerCommand('rainbow-csv.Shrink', shrink_table);\n var copy_back_cmd = vscode.commands.registerCommand('rainbow-csv.CopyBack', copy_back); // WEB_DISABLED\n var internal_test_cmd = vscode.commands.registerCommand('rainbow-csv.InternalTest', run_internal_test_cmd);\n\n var doc_open_event = vscode.workspace.onDidOpenTextDocument(handle_doc_open);\n var switch_event = vscode.window.onDidChangeActiveTextEditor(handle_editor_switch);\n\n context.subscriptions.push(lint_cmd);\n context.subscriptions.push(rbql_cmd);\n context.subscriptions.push(edit_column_names_cmd);\n context.subscriptions.push(column_edit_before_cmd);\n context.subscriptions.push(column_edit_after_cmd);\n context.subscriptions.push(column_edit_select_cmd);\n context.subscriptions.push(doc_open_event);\n context.subscriptions.push(switch_event);\n context.subscriptions.push(set_separator_cmd);\n context.subscriptions.push(rainbow_off_cmd);\n context.subscriptions.push(sample_head_cmd);\n context.subscriptions.push(sample_tail_cmd);\n context.subscriptions.push(set_join_table_name_cmd);\n context.subscriptions.push(align_cmd);\n context.subscriptions.push(shrink_cmd);\n context.subscriptions.push(copy_back_cmd);\n context.subscriptions.push(set_header_line_cmd);\n context.subscriptions.push(internal_test_cmd);\n\n // Need this because \"onDidOpenTextDocument()\" doesn't get called for the first open document.\n // Another issue is when dev debug logging mode is enabled, the first document would be \"Log\" because it is printing something and gets VSCode focus.\n await sleep(1000);\n let active_doc = get_active_doc();\n handle_doc_open(active_doc);\n}\n\n\nfunction deactivate() {\n // This method is called when extension is deactivated.\n}\n\n\nexports.activate = activate;\nexports.deactivate = deactivate;\n"],"names":["GetIntrinsic","callBind","$indexOf","module","exports","name","allowMissing","intrinsic","bind","$apply","$call","$reflectApply","call","$gOPD","$defineProperty","$max","value","e","originalFunction","func","arguments","desc","configurable","length","applyBind","apply","hasOwn","Object","prototype","hasOwnProperty","toString","obj","fn","ctx","TypeError","l","i","k","ERROR_MESSAGE","slice","Array","toStr","funcType","that","target","this","bound","args","binder","result","concat","boundLength","Math","max","boundArgs","push","Function","join","Empty","implementation","undefined","$SyntaxError","SyntaxError","$Function","$TypeError","getEvalledConstructor","expressionSyntax","getOwnPropertyDescriptor","throwTypeError","ThrowTypeError","calleeThrows","get","gOPDthrows","hasSymbols","getProto","getPrototypeOf","x","__proto__","needsEval","TypedArray","Uint8Array","INTRINSICS","AggregateError","ArrayBuffer","Symbol","iterator","Atomics","BigInt","Boolean","DataView","Date","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","Error","eval","EvalError","Float32Array","Float64Array","FinalizationRegistry","Int8Array","Int16Array","Int32Array","isFinite","isNaN","JSON","Map","Number","parseFloat","parseInt","Promise","Proxy","RangeError","ReferenceError","Reflect","RegExp","Set","SharedArrayBuffer","String","Uint8ClampedArray","Uint16Array","Uint32Array","URIError","WeakMap","WeakRef","WeakSet","doEval","gen","LEGACY_ALIASES","$concat","$spliceApply","splice","$replace","replace","$strSlice","rePropName","reEscapeChar","stringToPath","string","first","last","match","number","quote","subString","getBaseIntrinsic","alias","intrinsicName","parts","intrinsicBaseName","intrinsicRealName","skipFurtherCaching","isOwn","part","origSymbol","hasSymbolSham","getOwnPropertySymbols","sym","symObj","keys","getOwnPropertyNames","syms","propertyIsEnumerable","descriptor","enumerable","toStringTag","create","ctor","superCtor","super_","constructor","writable","TempCtor","hasToStringTag","$toString","callBound","isStandardArguments","isLegacyArguments","callee","supportsStandardArguments","GeneratorFunction","fnToStr","isFnRegex","test","generatorFunc","getGeneratorFunc","forEach","availableTypedArrays","g","globalThis","typedArrays","array","$slice","toStrTags","gOPD","typedArray","arr","proto","superProto","tag","anyTrue","getter","tryTypedArrays","cachedSetTimeout","cachedClearTimeout","process","defaultSetTimout","defaultClearTimeout","runTimeout","fun","setTimeout","clearTimeout","currentQueue","queue","draining","queueIndex","cleanUpNextTick","drainQueue","timeout","len","run","marker","runClearTimeout","Item","noop","nextTick","title","browser","env","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","arg","copy","fill","readUInt8","isArgumentsObject","isGeneratorFunction","whichTypedArray","isTypedArray","uncurryThis","f","BigIntSupported","SymbolSupported","ObjectToString","numberValue","valueOf","stringValue","booleanValue","bigIntValue","symbolValue","checkBoxedPrimitive","prototypeValueOf","isMapToString","isSetToString","isWeakMapToString","isWeakSetToString","isArrayBufferToString","isArrayBuffer","working","isDataViewToString","isDataView","isPromise","input","then","catch","isArrayBufferView","isView","isUint8Array","isUint8ClampedArray","isUint16Array","isUint32Array","isInt8Array","isInt16Array","isInt32Array","isFloat32Array","isFloat64Array","isBigInt64Array","isBigUint64Array","isMap","isSet","isWeakMap","isWeakSet","SharedArrayBufferCopy","isSharedArrayBufferToString","isSharedArrayBuffer","isNumberObject","isStringObject","isBooleanObject","isBigIntObject","isSymbolObject","isAsyncFunction","isMapIterator","isSetIterator","isGeneratorObject","isWebAssemblyCompiledModule","isBoxedPrimitive","isAnyArrayBuffer","method","defineProperty","getOwnPropertyDescriptors","descriptors","formatRegExp","format","isString","objects","inspect","str","stringify","_","isNull","isObject","deprecate","msg","noDeprecation","warned","throwDeprecation","traceDeprecation","console","trace","error","debugs","debugEnvRegex","NODE_DEBUG","debugEnv","toUpperCase","opts","seen","stylize","stylizeNoColor","depth","colors","isBoolean","showHidden","_extend","isUndefined","customInspect","stylizeWithColor","formatValue","styleType","style","styles","recurseTimes","isFunction","ret","primitive","simple","isNumber","formatPrimitive","visibleKeys","hash","val","idx","arrayToHash","isError","indexOf","formatError","isRegExp","isDate","output","base","braces","isArray","toUTCString","formatProperty","key","formatArray","map","pop","reduce","prev","cur","reduceToSingleString","set","split","line","substr","ar","re","objectToString","d","o","pad","n","debuglog","pid","types","isNullOrUndefined","isSymbol","isNativeError","isPrimitive","isBuffer","months","timestamp","time","getHours","getMinutes","getSeconds","getDate","getMonth","prop","log","inherits","origin","add","kCustomPromisifiedSymbol","callbackifyOnRejected","reason","cb","newReason","promisify","original","promiseResolve","promiseReject","promise","resolve","reject","err","setPrototypeOf","defineProperties","custom","callbackify","callbackified","maybeCb","self","rej","foundName","os","fs","path","rbql","rbql_csv","csv_utils","number_regex","AssertionError","update_subcomponent_stats","field","is_first_line","max_field_components_lens","match_result","exec","cur_integer_part_length","cur_fractional_part_length","align_field","is_last_column","trim","delta_length","repeat","dot_pos","integer_delta_length","fractional_delta_length","trailing_spaces","make_table_name_key","file_path","find_table_path","vscode_global_state","main_table_dir","table_id","filepath","candidate_path","charAt","homedir","existsSync","isAbsolute","table_path","get_header_line","document","comment_prefix","num_lines","lineCount","lnum","line_text","lineAt","text","startsWith","RbqlIOHandlingError","VSCodeRecordIterator","RBQLInputIterator","delim","policy","has_header","table_name","variable_prefix","super","NR","NL","fields_info","first_defective_line","first_record","get_first_record","stop","header_line","smart_split","async","query_text","variable_map","parse_basic_variables","parse_array_variables","parse_attribute_variables","parse_dictionary_variables","get_line_rfc","rfc_line_buffer","record_line","accumulate_rfc_line_into_record","get_line_simple","do_get_record","record","warning","num_fields","get_warnings","inconsistent_records_info","entries","record_id","sort","a","b","condition","message","assert","record_1","num_fields_1","record_2","num_fields_2","warn_msg","make_inconsistent_num_fields_warning","VSCodeWriter","RBQLOutputWriter","header_len","null_in_output","delim_in_simple_output","output_lines","polymorphic_join","simple_join","quoted_join","quoted_join_rfc","mono_join","set_header","header","write","fields","v","quote_field","rfc_quote_field","res","normalize_fields","out_fields","sub_array_delim","VSCodeTableRegistry","get_iterator_by_table_id","_table_id","VSCodeFileSystemCSVRegistry","RBQLTableRegistry","input_file_dir","encoding","options","stream","record_iterator","bulk_input_path","createReadStream","CSVRecordIterator","output_warnings","basename","read_header","input_reader","createInterface","closed","promise_resolve","promise_reject","output_promise","close","rbql_query_web","input_document","input_delim","input_policy","output_delim","output_policy","with_headers","join_tables_registry","input_iterator","output_writer","query","rbql_query_node","input_path","output_path","csv_encoding","user_init_code","input_stream","stdin","output_stream","close_output_on_finish","stdout","createWriteStream","is_ascii","default_init_source_path","read_user_init_code","dirname","CSVWriter","populate_optimistic_rfc_csv_record_map","requested_end_record","dst_record_map","record_begin","match_list","has_unbalanced_double_quote","get_default_js_udf_content","get_default_python_udf_content","align_columns","active_doc","column_stats","result_lines","has_edit","fnum","adjusted","shrink_columns","calc_column_stats","adjust_column_stats","adjusted_stats","column_stat","field_rgx","field_rgx_external_whitespaces","extract_next_field","src","dlm","preserve_quotes_and_whitespaces","allow_external_whitespaces","cidx","src_cur","substring","match_obj","match_end","uidx","split_quoted_str","extraction_report","unquote_field","split_whitespace_separated_str","preserve_whitespaces","rgxp","unquote_fields","split_lines","external_rfc_line_buffer","current_line","multiline_row","RbqlParsingError","RbqlRuntimeError","InternalBadFieldError","bad_idx","params","replace_all","search","replacement","RBQLContext","writer","unnest_list","top_count","like_regex_cache","sort_key_expression","aggregation_stage","aggregation_key_expression","functional_aggregators","join_map_impl","join_map","lhs_join_var_expression","where_expression","select_expression","update_expressions","variables_init_code","query_context","wrong_aggregation_usage_error","RBQL_VERSION","check_if_brackets_match","opening_bracket","closing_bracket","parse_root_bracket_level_text_spans","text_spans","last_pos","bracket_stack","cur_char","span","unquote_string","quoted_str","column_info_from_text_span","text_span","string_literals","rbql_star_marker","simple_var_match","attribute_match","subscript_int_match","subscript_str_match","column_index","column_name","is_star","replaced_string_literal_id","unquoted_column_name","adhoc_parse_select_expression_to_column_infos","ts","stable_compare","safe_get","safe_join_get","safe_set","regexp_escape","like_to_regex","pattern","p","converted","like","matcher","LIKE","RBQLAggregationToken","marker_id","UnnestMarker","UNNEST","vals","unnest","Unnest","UNFOLD","parse_number","MinAggregator","stats","increment","cur_aggr","min","get_final","MaxAggregator","SumAggregator","AvgAggregator","cur_sum","cur_cnt","VarianceAggregator","cur_sum_sq","avg_val","MedianAggregator","m","floor","CountAggregator","ArrayAggAggregator","post_proc","ConstGroupVerifier","output_index","const_values","old_value","init_aggregator","generator_name","MIN","Min","MAX","Max","COUNT","count","Count","SUM","sum","Sum","AVG","avg","Avg","VARIANCE","variance","Variance","MEDIAN","median","Median","ARRAY_AGG","array_agg","FOLD","add_to_set","dst_set","len_before","size","TopWriter","subwriter","NW","finish","UniqWriter","UniqCountWriter","records","old_val","unshift","SortedWriter","reverse_sort","unsorted_entries","stable_entry","reverse","entry","AggregateWriter","aggregators","aggregation_keys","all_keys","from","ag","InnerJoiner","get_rhs","lhs_key","get_join_records","LeftJoiner","null_record","max_record_len","StrictLeftJoiner","select_except","except_fields","select_simple","sort_key","sort_entry","select_aggregated","transparent_values","num_aggregators_found","trans_value","select_unnested","folded_fields","unnest_pos","findIndex","PROCESS_SELECT_COMMON","PROCESS_SELECT_SIMPLE","PROCESS_SELECT_JOIN","PROCESS_UPDATE_JOIN","PROCESS_UPDATE_SIMPLE","MAIN_LOOP_BODY","embed_expression","parent_code","child_placeholder","child_expression","embed_code","child_code","parent_lines","child_lines","pos","placeholder_indentation","generate_main_loop_code","is_select_query","is_join_query","js_code","compile_and_run","main_loop_body","main_loop_promise","lower_case_query","toLowerCase","GROUP_BY","UPDATE","SELECT","JOIN","INNER_JOIN","LEFT_JOIN","LEFT_OUTER_JOIN","STRICT_LEFT_JOIN","ORDER_BY","WHERE","LIMIT","EXCEPT","WITH","get_ambiguous_error_msg","variable_name","get_all_matches","regexp","str_strip","strip_comments","cline","combine_string_literals","backend_expression","prefix","dst_variables_map","matches","field_num","initialize","index","js_string_escape_column_name","quote_char","query_probably_has_dictionary_variable","continuous_name_segments","continuous_segment","column_names","dict_test_rgx","escaped_column_name","column_names_source","column_names_from_query","zero_based_idx","map_variables_directly","ensure_no_ambiguous_variables","input_column_names","join_column_names","join_column_names_set","has","parse_join_expression","invalid_join_syntax_error","variable_pairs","pair_rgx","and_rgx","resolve_join_variables","input_variables_map","join_variables_map","lhs_variables","rhs_indices","valid_join_syntax_msg","variable_pair","join_var_1","join_var_2","lhs_key_index","rhs_key_index","generate_common_init_code","base_var","attr_var","generate_init_statements","variables_map","indent","code_lines","simple_var_name_rgx","var_info","variable_declaration_keyword","replace_star_count","aggregate_expression","replace_star_vars","rbql_expression","replacement_expression","replace_star_vars_for_header_parsing","translate_update_expression","update_expression","first_assignment_error","assignment_looking_rgx","dst_var_name","var_index","current_indent","translate_select_expression","expression_without_stars","translated","translated_for_header","separate_string_literals","rgx","format_parts","idx_before","literal_id","string_literal","start_index","lastIndex","format_expression","locate_statements","statement_groups","ig","is","statement","match_str","separate_actions","with_match","ordered_statements","statement_start","span_start","span_end","statement_params","new_span","find_top","rb_actions","select_action","translate_except_expression","except_expression","input_header","skip_vars","skip_indices","var_name","HashJoinMap","key_indices","hash_map","nr","key_index","polymorphic_get_key","get_single_key","get_multi_key","ki","get_record","nf","key_records","cleanup_query","filter","remove_redundant_table_name","select_output_header","join_header","query_column_infos","output_header","qci","handle_query_modifier","TableIterator","table","normalize_column_names","stopped","TableWriter","external_table","SingleTableRegistry","shallow_parse_input_query","get_variables_map","rhs_table_id","join_record_iterator","get_header","sql_join_type","build","select_expression_for_ast","query_table","input_table","output_table","join_table","output_column_names","exception_to_error_info","exceptions_type_map","error_type","util","utf_decoding_error","rbql_init_source_path","readFileSync","name_record","index_path","content","lines","try_read_index","get_index_record","RecordQueue","push_stack","pull_stack","enqueue","dequeue","csv_path","first_record_should_be_emitted","header_preread_complete","decoder","TextDecoder","fatal","input_exhausted","started","utf8_bom_removed","partially_decoded_line","partially_decoded_line_ends_with_cr","resolve_current_record","reject_current_record","current_exception","produced_records_queue","process_line_polymorphic","process_partial_rfc_record_line","process_record_line","modifier","reset_external_callbacks","try_propagate_exception","exception","store_or_propagate_exception","pause","preread_first_record","try_resolve_next_record","start","isPaused","resume","parent_iterator","current_record_promise","num_records","process_line","clean_line","assumed_source_encoding","charCodeAt","remove_utf8_bom","process_data_stream_chunk","data_chunk","decoded_string","decode","first_line_index","process_data_bulk","control_buffer","Buffer","compare","process_data_stream_end","last_line","destroy","readFile","close_stream_on_finish","line_separator","setDefaultEncoding","error_obj","store_first_error","first_error","writer_error","_write_all","output_encoding","end","FileSystemCSVRegistry","interpret_named_csv_format","format_name","query_csv","require","possibleNames","out","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","window","vscode","child_process","rainbow_utils","ll_rainbow_utils","is_web_ext","preview_window_size","scratch_buf_marker","client_html_template_web","lint_results","aligned_files","autodetection_stoplist","original_language_ids","result_set_parent_map","lint_status_bar_button","rbql_status_bar_button","align_shrink_button","rainbow_off_status_bar_button","copy_back_button","last_statusbar_doc","rbql_context","last_rbql_queries","client_html_template","global_state","preview_panel","doc_edit_subscription","_unit_test_last_rbql_report","_unit_test_last_warnings","dialect_map","absolute_path_map","show_single_line_error","error_msg","active_window","showErrorMessage","sleep","ms","push_current_stack_to_js_callback_queue_to_allow_ui_update","map_separator_to_language_id","separator","language_id","get_from_global_state","default_value","save_to_global_state","update","get_rfc_record_text","record_start","record_end","replace_doc_content","active_editor","new_content","invalid_range","Range","full_range","validateRange","edit","sample_preview_records_from_context","dst_message","requested_start_record","preview_records","enable_rfc_newlines","rfc_record_map","record_text","cur_record","preview_sampling_error","r","c","start_record_zero_based","make_header_key","make_rfc_policy_key","make_with_headers_key","get_from_config","param_name","config","workspace","getConfiguration","get_header_from_document","fileName","raw_header","parse","get_field_by_line_position","query_pos","col_num","cpos","get_active_editor","activeTextEditor","get_active_doc","hide_status_bar_buttons","all_buttons","hide","refresh_status_bar_buttons","endsWith","languageId","lint_cache_key","lint_report","createStatusBarItem","StatusBarAlignment","Left","color","tooltip","command","show","show_lint_status_bar_button","show_align_shrink_button","parent_table_path","parent_basename","show_rbql_copy_to_source_button","csv_lint","is_manual_op","detect_trailing_spaces","first_trailing_space_line","split_result","produce_lint_report","csv_lint_cmd","run_internal_test_cmd","integration_test_options","check_initialization_state","initialized","lazy_loaded","check_last_rbql_report","check_last_rbql_warnings","handle_rbql_result_file","text_doc","warnings","showTextDocument","languages","setTextDocumentLanguage","showWarningMessage","show_warnings","run_command","cmd","close_and_error_guard","callback_func","spawn","stderr","data","code","handle_command_result","src_table_path","dst_table_path","error_code","webview_report_handler","json_report","report","doc","openTextDocument","file_path_to_query_key","get_dialect","set_header_line","dialect","selection","set_rainbow_separator","original_language_id","character","restore_original_language","delete","set_join_table_name","showInputBox","set_virtual_header","old_header_str","input_box_props","raw_new_header","new_header","column_edit","edit_mode","position","active","cnum","quoting_warning","selections","char_pos_before","char_pos_after","position_before","Position","position_after","Selection","shrink_table","progress_options","location","ProgressLocation","Window","withProgress","progress","shrinked_doc_text","first_failed_line","align_table","aligned_doc_text","copy_back","result_doc","parent_doc","parent_editor","query_result_doc","getText","do_copy_back","handle_rbql_client_message","webview","message_type","report_msg","postMessage","init_msg","path_key","input_document_path","history_list","rbql_backend","rbql_query","input_table_dir","protocol_message","navig_direction","backend_language","output_dialect","old_index","update_query_history","input_table_path","rbql_output_dir","tmpdir","get_dst_table_dir","orig_extension","extname","delim_ext_map","dst_extension","result_table_name","get_dst_table_name","output_doc_cfg","language","csv_options","cmd_safe_query","run_rbql_query","udf_file_path","default_content","writeFileSync","udf_doc","edit_rbql","orig_uri","uri","scheme","isDirty","rnd_suffix","random","with_headers_by_default","createWebviewPanel","ViewColumn","Active","enableScripts","client_html","paths_list","local_path","adjusted_webview_url","asWebviewUri","Uri","file","adjust_webview_paths","html","onDidReceiveMessage","get_num_columns_if_delimited","min_num_columns","min_num_lines","num_lines_checked","comment_prefix_for_autodetection","autodetect_dialect","candidate_separators","best_dialect","best_dialect_num_columns","dialect_id","cur_dialect_num_columns","handle_doc_edit","change_event","dispose","rainbow_csv_language_id","handle_editor_switch","editor","handle_doc_open","is_default_csv","best_dialect_frequency","frequency","j","autodetect_dialect_frequency_based","autoenable_rainbow_csv","isUntitled","onDidChangeTextDocument","register_csv_copy_paste","make_preview","preview_mode","fsPath","size_limit","file_size_in_bytes","statSync","full_orig_doc","file_basename","out_path","open","fd","buffer","alloc","read_begin_pos","read","_num","buffer_str","lastIndexOf","includes","register_csv_hover_info_provider","context","hover_provider","registerHoverProvider","provideHover","token","cancellation_token","hover_text","enable_tooltip_column_names","enable_tooltip_warnings","max_label_len","column_label","short_column_label","make_hover_text","isCancellationRequested","mds","MarkdownString","appendCodeblock","Hover","make_hover","subscriptions","activate","globalState","rbql_client_uri","joinPath","extensionUri","bytes","asAbsolutePath","lint_cmd","commands","registerCommand","rbql_cmd","set_header_line_cmd","edit_column_names_cmd","set_join_table_name_cmd","column_edit_before_cmd","column_edit_after_cmd","column_edit_select_cmd","set_separator_cmd","rainbow_off_cmd","sample_head_cmd","sample_tail_cmd","align_cmd","shrink_cmd","copy_back_cmd","internal_test_cmd","doc_open_event","onDidOpenTextDocument","switch_event","onDidChangeActiveTextEditor","deactivate"],"sourceRoot":""} \ No newline at end of file diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/dist/web/test/suite/index.js b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/dist/web/test/suite/index.js new file mode 100644 index 00000000..591ae1f0 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/dist/web/test/suite/index.js @@ -0,0 +1,2 @@ +/*! For license information please see index.js.LICENSE.txt */ +(()=>{var __webpack_modules__={9282:(e,t,r)=>{"use strict";var n=r(4155);function i(e){return i="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},i(e)}var o,a,s=r(2136).codes,l=s.ERR_AMBIGUOUS_ARGUMENT,c=s.ERR_INVALID_ARG_TYPE,u=s.ERR_INVALID_ARG_VALUE,p=s.ERR_INVALID_RETURN_VALUE,_=s.ERR_MISSING_ARGS,f=r(5961),h=r(9539).inspect,d=r(9539).types,g=d.isPromise,y=d.isRegExp,m=Object.assign?Object.assign:r(8091).assign,b=Object.is?Object.is:r(609);function w(){var e=r(9158);o=e.isDeepEqual,a=e.isDeepStrictEqual}new Map;var x=!1,v=e.exports=S,E={};function O(e){if(e.message instanceof Error)throw e.message;throw new f(e)}function j(e,t,r,n){if(!r){var i=!1;if(0===t)i=!0,n="No value argument passed to `assert.ok()`";else if(n instanceof Error)throw n;var o=new f({actual:r,expected:!0,message:n,operator:"==",stackStartFn:e});throw o.generatedMessage=i,o}}function S(){for(var e=arguments.length,t=new Array(e),r=0;r1?r-1:0),i=1;i1?r-1:0),i=1;i1?r-1:0),i=1;i1?r-1:0),i=1;i{"use strict";var n=r(4155);function i(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e,t){for(var r=0;re.length)&&(r=e.length),e.substring(r-t.length,r)===t}var y="",m="",b="",w="",x={deepStrictEqual:"Expected values to be strictly deep-equal:",strictEqual:"Expected values to be strictly equal:",strictEqualObject:'Expected "actual" to be reference-equal to "expected":',deepEqual:"Expected values to be loosely deep-equal:",equal:"Expected values to be loosely equal:",notDeepStrictEqual:'Expected "actual" not to be strictly deep-equal to:',notStrictEqual:'Expected "actual" to be strictly unequal to:',notStrictEqualObject:'Expected "actual" not to be reference-equal to "expected":',notDeepEqual:'Expected "actual" not to be loosely deep-equal to:',notEqual:'Expected "actual" to be loosely unequal to:',notIdentical:"Values identical but not reference-equal:"};function v(e){var t=Object.keys(e),r=Object.create(Object.getPrototypeOf(e));return t.forEach((function(t){r[t]=e[t]})),Object.defineProperty(r,"message",{value:e.message}),r}function E(e){return h(e,{compact:!1,customInspect:!1,depth:1e3,maxArrayLength:1/0,showHidden:!1,breakLength:1/0,showProxy:!1,sorted:!0,getters:!0})}var O=function(e){function t(e){var r;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),"object"!==f(e)||null===e)throw new d("options","Object",e);var i=e.message,o=e.operator,l=e.stackStartFn,c=e.actual,u=e.expected,p=Error.stackTraceLimit;if(Error.stackTraceLimit=0,null!=i)r=a(this,_(t).call(this,String(i)));else if(n.stderr&&n.stderr.isTTY&&(n.stderr&&n.stderr.getColorDepth&&1!==n.stderr.getColorDepth()?(y="",m="",w="",b=""):(y="",m="",w="",b="")),"object"===f(c)&&null!==c&&"object"===f(u)&&null!==u&&"stack"in c&&c instanceof Error&&"stack"in u&&u instanceof Error&&(c=v(c),u=v(u)),"deepStrictEqual"===o||"strictEqual"===o)r=a(this,_(t).call(this,function(e,t,r){var i="",o="",a=0,s="",l=!1,c=E(e),u=c.split("\n"),p=E(t).split("\n"),_=0,h="";if("strictEqual"===r&&"object"===f(e)&&"object"===f(t)&&null!==e&&null!==t&&(r="strictEqualObject"),1===u.length&&1===p.length&&u[0]!==p[0]){var d=u[0].length+p[0].length;if(d<=10){if(!("object"===f(e)&&null!==e||"object"===f(t)&&null!==t||0===e&&0===t))return"".concat(x[r],"\n\n")+"".concat(u[0]," !== ").concat(p[0],"\n")}else if("strictEqualObject"!==r&&d<(n.stderr&&n.stderr.isTTY?n.stderr.columns:80)){for(;u[0][_]===p[0][_];)_++;_>2&&(h="\n ".concat(function(e,t){if(t=Math.floor(t),0==e.length||0==t)return"";var r=e.length*t;for(t=Math.floor(Math.log(t)/Math.log(2));t;)e+=e,t--;return e+e.substring(0,r-e.length)}(" ",_),"^"),_=0)}}for(var v=u[u.length-1],O=p[p.length-1];v===O&&(_++<2?s="\n ".concat(v).concat(s):i=v,u.pop(),p.pop(),0!==u.length&&0!==p.length);)v=u[u.length-1],O=p[p.length-1];var j=Math.max(u.length,p.length);if(0===j){var S=c.split("\n");if(S.length>30)for(S[26]="".concat(y,"...").concat(w);S.length>27;)S.pop();return"".concat(x.notIdentical,"\n\n").concat(S.join("\n"),"\n")}_>3&&(s="\n".concat(y,"...").concat(w).concat(s),l=!0),""!==i&&(s="\n ".concat(i).concat(s),i="");var R=0,A=x[r]+"\n".concat(m,"+ actual").concat(w," ").concat(b,"- expected").concat(w),q=" ".concat(y,"...").concat(w," Lines skipped");for(_=0;_1&&_>2&&(T>4?(o+="\n".concat(y,"...").concat(w),l=!0):T>3&&(o+="\n ".concat(p[_-2]),R++),o+="\n ".concat(p[_-1]),R++),a=_,i+="\n".concat(b,"-").concat(w," ").concat(p[_]),R++;else if(p.length<_+1)T>1&&_>2&&(T>4?(o+="\n".concat(y,"...").concat(w),l=!0):T>3&&(o+="\n ".concat(u[_-2]),R++),o+="\n ".concat(u[_-1]),R++),a=_,o+="\n".concat(m,"+").concat(w," ").concat(u[_]),R++;else{var k=p[_],P=u[_],I=P!==k&&(!g(P,",")||P.slice(0,-1)!==k);I&&g(k,",")&&k.slice(0,-1)===P&&(I=!1,P+=","),I?(T>1&&_>2&&(T>4?(o+="\n".concat(y,"...").concat(w),l=!0):T>3&&(o+="\n ".concat(u[_-2]),R++),o+="\n ".concat(u[_-1]),R++),a=_,o+="\n".concat(m,"+").concat(w," ").concat(P),i+="\n".concat(b,"-").concat(w," ").concat(k),R+=2):(o+=i,i="",1!==T&&0!==_||(o+="\n ".concat(P),R++))}if(R>20&&_30)for(O[26]="".concat(y,"...").concat(w);O.length>27;)O.pop();r=1===O.length?a(this,_(t).call(this,"".concat(h," ").concat(O[0]))):a(this,_(t).call(this,"".concat(h,"\n\n").concat(O.join("\n"),"\n")))}else{var j=E(c),S="",R=x[o];"notDeepEqual"===o||"notEqual"===o?(j="".concat(x[o],"\n\n").concat(j)).length>1024&&(j="".concat(j.slice(0,1021),"...")):(S="".concat(E(u)),j.length>512&&(j="".concat(j.slice(0,509),"...")),S.length>512&&(S="".concat(S.slice(0,509),"...")),"deepEqual"===o||"equal"===o?j="".concat(R,"\n\n").concat(j,"\n\nshould equal\n\n"):S=" ".concat(o," ").concat(S)),r=a(this,_(t).call(this,"".concat(j).concat(S)))}return Error.stackTraceLimit=p,r.generatedMessage=!i,Object.defineProperty(s(r),"name",{value:"AssertionError [ERR_ASSERTION]",enumerable:!1,writable:!0,configurable:!0}),r.code="ERR_ASSERTION",r.actual=c,r.expected=u,r.operator=o,Error.captureStackTrace&&Error.captureStackTrace(s(r),l),r.stack,r.name="AssertionError",a(r)}var r,l;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&p(e,t)}(t,e),r=t,l=[{key:"toString",value:function(){return"".concat(this.name," [").concat(this.code,"]: ").concat(this.message)}},{key:h.custom,value:function(e,t){return h(this,function(e){for(var t=1;t{"use strict";function n(e){return n="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},n(e)}function i(e){return i=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},i(e)}function o(e,t){return o=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},o(e,t)}var a,s,l={};function c(e,t,r){r||(r=Error);var a=function(r){function a(r,o,s){var l,c,u;return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,a),c=this,u=i(a).call(this,function(e,r,n){return"string"==typeof t?t:t(e,r,n)}(r,o,s)),l=!u||"object"!==n(u)&&"function"!=typeof u?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(c):u,l.code=e,l}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&o(e,t)}(a,r),a}(r);l[e]=a}function u(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map((function(e){return String(e)})),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:2===r?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}c("ERR_AMBIGUOUS_ARGUMENT",'The "%s" argument is ambiguous. %s',TypeError),c("ERR_INVALID_ARG_TYPE",(function(e,t,i){var o,s,l,c,p;if(void 0===a&&(a=r(9282)),a("string"==typeof e,"'name' must be a string"),"string"==typeof t&&(s="not ",t.substr(0,s.length)===s)?(o="must not be",t=t.replace(/^not /,"")):o="must be",function(e,t,r){return(void 0===r||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}(e," argument"))l="The ".concat(e," ").concat(o," ").concat(u(t,"type"));else{var _=("number"!=typeof p&&(p=0),p+".".length>(c=e).length||-1===c.indexOf(".",p)?"argument":"property");l='The "'.concat(e,'" ').concat(_," ").concat(o," ").concat(u(t,"type"))}return l+". Received type ".concat(n(i))}),TypeError),c("ERR_INVALID_ARG_VALUE",(function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"is invalid";void 0===s&&(s=r(9539));var i=s.inspect(t);return i.length>128&&(i="".concat(i.slice(0,128),"...")),"The argument '".concat(e,"' ").concat(n,". Received ").concat(i)}),TypeError,RangeError),c("ERR_INVALID_RETURN_VALUE",(function(e,t,r){var i;return i=r&&r.constructor&&r.constructor.name?"instance of ".concat(r.constructor.name):"type ".concat(n(r)),"Expected ".concat(e,' to be returned from the "').concat(t,'"')+" function but got ".concat(i,".")}),TypeError),c("ERR_MISSING_ARGS",(function(){for(var e=arguments.length,t=new Array(e),n=0;n0,"At least one arg needs to be specified");var i="The ",o=t.length;switch(t=t.map((function(e){return'"'.concat(e,'"')})),o){case 1:i+="".concat(t[0]," argument");break;case 2:i+="".concat(t[0]," and ").concat(t[1]," arguments");break;default:i+=t.slice(0,o-1).join(", "),i+=", and ".concat(t[o-1]," arguments")}return"".concat(i," must be specified")}),TypeError),e.exports.codes=l},9158:(e,t,r)=>{"use strict";function n(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var r=[],n=!0,i=!1,o=void 0;try{for(var a,s=e[Symbol.iterator]();!(n=(a=s.next()).done)&&(r.push(a.value),!t||r.length!==t);n=!0);}catch(e){i=!0,o=e}finally{try{n||null==s.return||s.return()}finally{if(i)throw o}}return r}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function i(e){return i="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},i(e)}var o=void 0!==/a/g.flags,a=function(e){var t=[];return e.forEach((function(e){return t.push(e)})),t},s=function(e){var t=[];return e.forEach((function(e,r){return t.push([r,e])})),t},l=Object.is?Object.is:r(609),c=Object.getOwnPropertySymbols?Object.getOwnPropertySymbols:function(){return[]},u=Number.isNaN?Number.isNaN:r(360);function p(e){return e.call.bind(e)}var _=p(Object.prototype.hasOwnProperty),f=p(Object.prototype.propertyIsEnumerable),h=p(Object.prototype.toString),d=r(9539).types,g=d.isAnyArrayBuffer,y=d.isArrayBufferView,m=d.isDate,b=d.isMap,w=d.isRegExp,x=d.isSet,v=d.isNativeError,E=d.isBoxedPrimitive,O=d.isNumberObject,j=d.isStringObject,S=d.isBooleanObject,R=d.isBigIntObject,A=d.isSymbolObject,q=d.isFloat32Array,T=d.isFloat64Array;function k(e){if(0===e.length||e.length>10)return!0;for(var t=0;t57)return!0}return 10===e.length&&e>=Math.pow(2,32)}function P(e){return Object.keys(e).filter(k).concat(c(e).filter(Object.prototype.propertyIsEnumerable.bind(e)))}function I(e,t){if(e===t)return 0;for(var r=e.length,n=t.length,i=0,o=Math.min(r,n);i{"use strict";var n=r(210),i=r(5559),o=i(n("String.prototype.indexOf"));e.exports=function(e,t){var r=n(e,!!t);return"function"==typeof r&&o(e,".prototype.")>-1?i(r):r}},5559:(e,t,r)=>{"use strict";var n=r(8612),i=r(210),o=i("%Function.prototype.apply%"),a=i("%Function.prototype.call%"),s=i("%Reflect.apply%",!0)||n.call(a,o),l=i("%Object.getOwnPropertyDescriptor%",!0),c=i("%Object.defineProperty%",!0),u=i("%Math.max%");if(c)try{c({},"a",{value:1})}catch(e){c=null}e.exports=function(e){var t=s(n,a,arguments);if(l&&c){var r=l(t,"length");r.configurable&&c(t,"length",{value:1+u(0,e.length-(arguments.length-1))})}return t};var p=function(){return s(n,o,arguments)};c?c(e.exports,"apply",{value:p}):e.exports.apply=p},4289:(e,t,r)=>{"use strict";var n=r(2215),i="function"==typeof Symbol&&"symbol"==typeof Symbol("foo"),o=Object.prototype.toString,a=Array.prototype.concat,s=Object.defineProperty,l=r(1044)(),c=s&&l,u=function(e,t,r,n){var i;(!(t in e)||"function"==typeof(i=n)&&"[object Function]"===o.call(i)&&n())&&(c?s(e,t,{configurable:!0,enumerable:!1,value:r,writable:!0}):e[t]=r)},p=function(e,t){var r=arguments.length>2?arguments[2]:{},o=n(t);i&&(o=a.call(o,Object.getOwnPropertySymbols(t)));for(var s=0;s{"use strict";function t(e,t){if(null==e)throw new TypeError("Cannot convert first argument to object");for(var r=Object(e),n=1;n{var t=Object.prototype.hasOwnProperty,r=Object.prototype.toString;e.exports=function(e,n,i){if("[object Function]"!==r.call(n))throw new TypeError("iterator must be a function");var o=e.length;if(o===+o)for(var a=0;a{"use strict";var t="Function.prototype.bind called on incompatible ",r=Array.prototype.slice,n=Object.prototype.toString,i="[object Function]";e.exports=function(e){var o=this;if("function"!=typeof o||n.call(o)!==i)throw new TypeError(t+o);for(var a,s=r.call(arguments,1),l=function(){if(this instanceof a){var t=o.apply(this,s.concat(r.call(arguments)));return Object(t)===t?t:this}return o.apply(e,s.concat(r.call(arguments)))},c=Math.max(0,o.length-s.length),u=[],p=0;p{"use strict";var n=r(7648);e.exports=Function.prototype.bind||n},210:(e,t,r)=>{"use strict";var n,i=SyntaxError,o=Function,a=TypeError,s=function(e){try{return o('"use strict"; return ('+e+").constructor;")()}catch(e){}},l=Object.getOwnPropertyDescriptor;if(l)try{l({},"")}catch(e){l=null}var c=function(){throw new a},u=l?function(){try{return c}catch(e){try{return l(arguments,"callee").get}catch(e){return c}}}():c,p=r(1405)(),_=Object.getPrototypeOf||function(e){return e.__proto__},f={},h="undefined"==typeof Uint8Array?n:_(Uint8Array),d={"%AggregateError%":"undefined"==typeof AggregateError?n:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?n:ArrayBuffer,"%ArrayIteratorPrototype%":p?_([][Symbol.iterator]()):n,"%AsyncFromSyncIteratorPrototype%":n,"%AsyncFunction%":f,"%AsyncGenerator%":f,"%AsyncGeneratorFunction%":f,"%AsyncIteratorPrototype%":f,"%Atomics%":"undefined"==typeof Atomics?n:Atomics,"%BigInt%":"undefined"==typeof BigInt?n:BigInt,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?n:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?n:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?n:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?n:FinalizationRegistry,"%Function%":o,"%GeneratorFunction%":f,"%Int8Array%":"undefined"==typeof Int8Array?n:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?n:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?n:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":p?_(_([][Symbol.iterator]())):n,"%JSON%":"object"==typeof JSON?JSON:n,"%Map%":"undefined"==typeof Map?n:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&p?_((new Map)[Symbol.iterator]()):n,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?n:Promise,"%Proxy%":"undefined"==typeof Proxy?n:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?n:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?n:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&p?_((new Set)[Symbol.iterator]()):n,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?n:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":p?_(""[Symbol.iterator]()):n,"%Symbol%":p?Symbol:n,"%SyntaxError%":i,"%ThrowTypeError%":u,"%TypedArray%":h,"%TypeError%":a,"%Uint8Array%":"undefined"==typeof Uint8Array?n:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?n:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?n:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?n:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?n:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?n:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?n:WeakSet},g=function e(t){var r;if("%AsyncFunction%"===t)r=s("async function () {}");else if("%GeneratorFunction%"===t)r=s("function* () {}");else if("%AsyncGeneratorFunction%"===t)r=s("async function* () {}");else if("%AsyncGenerator%"===t){var n=e("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&(r=_(i.prototype))}return d[t]=r,r},y={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},m=r(8612),b=r(7642),w=m.call(Function.call,Array.prototype.concat),x=m.call(Function.apply,Array.prototype.splice),v=m.call(Function.call,String.prototype.replace),E=m.call(Function.call,String.prototype.slice),O=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,j=/\\(\\)?/g,S=function(e){var t=E(e,0,1),r=E(e,-1);if("%"===t&&"%"!==r)throw new i("invalid intrinsic syntax, expected closing `%`");if("%"===r&&"%"!==t)throw new i("invalid intrinsic syntax, expected opening `%`");var n=[];return v(e,O,(function(e,t,r,i){n[n.length]=r?v(i,j,"$1"):t||e})),n},R=function(e,t){var r,n=e;if(b(y,n)&&(n="%"+(r=y[n])[0]+"%"),b(d,n)){var o=d[n];if(o===f&&(o=g(n)),void 0===o&&!t)throw new a("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:r,name:n,value:o}}throw new i("intrinsic "+e+" does not exist!")};e.exports=function(e,t){if("string"!=typeof e||0===e.length)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new a('"allowMissing" argument must be a boolean');var r=S(e),n=r.length>0?r[0]:"",o=R("%"+n+"%",t),s=o.name,c=o.value,u=!1,p=o.alias;p&&(n=p[0],x(r,w([0,1],p)));for(var _=1,f=!0;_=r.length){var m=l(c,h);c=(f=!!m)&&"get"in m&&!("originalValue"in m.get)?m.get:c[h]}else f=b(c,h),c=c[h];f&&!u&&(d[s]=c)}}return c}},1044:(e,t,r)=>{"use strict";var n=r(210)("%Object.defineProperty%",!0),i=function(){if(n)try{return n({},"a",{value:1}),!0}catch(e){return!1}return!1};i.hasArrayLengthDefineBug=function(){if(!i())return null;try{return 1!==n([],"length",{value:1}).length}catch(e){return!0}},e.exports=i},1405:(e,t,r)=>{"use strict";var n="undefined"!=typeof Symbol&&Symbol,i=r(5419);e.exports=function(){return"function"==typeof n&&"function"==typeof Symbol&&"symbol"==typeof n("foo")&&"symbol"==typeof Symbol("bar")&&i()}},5419:e=>{"use strict";e.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),r=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(r))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var n=Object.getOwnPropertySymbols(e);if(1!==n.length||n[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var i=Object.getOwnPropertyDescriptor(e,t);if(42!==i.value||!0!==i.enumerable)return!1}return!0}},6410:(e,t,r)=>{"use strict";var n=r(5419);e.exports=function(){return n()&&!!Symbol.toStringTag}},7642:(e,t,r)=>{"use strict";var n=r(8612);e.exports=n.call(Function.call,Object.prototype.hasOwnProperty)},5717:e=>{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}},2584:(e,t,r)=>{"use strict";var n=r(6410)(),i=r(1924)("Object.prototype.toString"),o=function(e){return!(n&&e&&"object"==typeof e&&Symbol.toStringTag in e)&&"[object Arguments]"===i(e)},a=function(e){return!!o(e)||null!==e&&"object"==typeof e&&"number"==typeof e.length&&e.length>=0&&"[object Array]"!==i(e)&&"[object Function]"===i(e.callee)},s=function(){return o(arguments)}();o.isLegacyArguments=a,e.exports=s?o:a},8662:(e,t,r)=>{"use strict";var n,i=Object.prototype.toString,o=Function.prototype.toString,a=/^\s*(?:function)?\*/,s=r(6410)(),l=Object.getPrototypeOf;e.exports=function(e){if("function"!=typeof e)return!1;if(a.test(o.call(e)))return!0;if(!s)return"[object GeneratorFunction]"===i.call(e);if(!l)return!1;if(void 0===n){var t=function(){if(!s)return!1;try{return Function("return function*() {}")()}catch(e){}}();n=!!t&&l(t)}return l(e)===n}},8611:e=>{"use strict";e.exports=function(e){return e!=e}},360:(e,t,r)=>{"use strict";var n=r(5559),i=r(4289),o=r(8611),a=r(9415),s=r(3194),l=n(a(),Number);i(l,{getPolyfill:a,implementation:o,shim:s}),e.exports=l},9415:(e,t,r)=>{"use strict";var n=r(8611);e.exports=function(){return Number.isNaN&&Number.isNaN(NaN)&&!Number.isNaN("a")?Number.isNaN:n}},3194:(e,t,r)=>{"use strict";var n=r(4289),i=r(9415);e.exports=function(){var e=i();return n(Number,{isNaN:e},{isNaN:function(){return Number.isNaN!==e}}),e}},5692:(e,t,r)=>{"use strict";var n=r(9804),i=r(3083),o=r(1924),a=o("Object.prototype.toString"),s=r(6410)(),l="undefined"==typeof globalThis?r.g:globalThis,c=i(),u=o("Array.prototype.indexOf",!0)||function(e,t){for(var r=0;r-1}return!!f&&function(e){var t=!1;return n(_,(function(r,n){if(!t)try{t=r.call(e)===n}catch(e){}})),t}(e)}},4244:e=>{"use strict";var t=function(e){return e!=e};e.exports=function(e,r){return 0===e&&0===r?1/e==1/r:e===r||!(!t(e)||!t(r))}},609:(e,t,r)=>{"use strict";var n=r(4289),i=r(5559),o=r(4244),a=r(5624),s=r(2281),l=i(a(),Object);n(l,{getPolyfill:a,implementation:o,shim:s}),e.exports=l},5624:(e,t,r)=>{"use strict";var n=r(4244);e.exports=function(){return"function"==typeof Object.is?Object.is:n}},2281:(e,t,r)=>{"use strict";var n=r(5624),i=r(4289);e.exports=function(){var e=n();return i(Object,{is:e},{is:function(){return Object.is!==e}}),e}},8987:(e,t,r)=>{"use strict";var n;if(!Object.keys){var i=Object.prototype.hasOwnProperty,o=Object.prototype.toString,a=r(1414),s=Object.prototype.propertyIsEnumerable,l=!s.call({toString:null},"toString"),c=s.call((function(){}),"prototype"),u=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],p=function(e){var t=e.constructor;return t&&t.prototype===e},_={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},f=function(){if("undefined"==typeof window)return!1;for(var e in window)try{if(!_["$"+e]&&i.call(window,e)&&null!==window[e]&&"object"==typeof window[e])try{p(window[e])}catch(e){return!0}}catch(e){return!0}return!1}();n=function(e){var t=null!==e&&"object"==typeof e,r="[object Function]"===o.call(e),n=a(e),s=t&&"[object String]"===o.call(e),_=[];if(!t&&!r&&!n)throw new TypeError("Object.keys called on a non-object");var h=c&&r;if(s&&e.length>0&&!i.call(e,0))for(var d=0;d0)for(var g=0;g{"use strict";var n=Array.prototype.slice,i=r(1414),o=Object.keys,a=o?function(e){return o(e)}:r(8987),s=Object.keys;a.shim=function(){if(Object.keys){var e=function(){var e=Object.keys(arguments);return e&&e.length===arguments.length}(1,2);e||(Object.keys=function(e){return i(e)?s(n.call(e)):s(e)})}else Object.keys=a;return Object.keys||a},e.exports=a},1414:e=>{"use strict";var t=Object.prototype.toString;e.exports=function(e){var r=t.call(e),n="[object Arguments]"===r;return n||(n="[object Array]"!==r&&null!==e&&"object"==typeof e&&"number"==typeof e.length&&e.length>=0&&"[object Function]"===t.call(e.callee)),n}},4155:e=>{var t,r,n=e.exports={};function i(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function a(e){if(t===setTimeout)return setTimeout(e,0);if((t===i||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(r){try{return t.call(null,e,0)}catch(r){return t.call(this,e,0)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:i}catch(e){t=i}try{r="function"==typeof clearTimeout?clearTimeout:o}catch(e){r=o}}();var s,l=[],c=!1,u=-1;function p(){c&&s&&(c=!1,s.length?l=s.concat(l):u=-1,l.length&&_())}function _(){if(!c){var e=a(p);c=!0;for(var t=l.length;t;){for(s=l,l=[];++u1)for(var r=1;r{e.exports=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8}},5955:(e,t,r)=>{"use strict";var n=r(2584),i=r(8662),o=r(6430),a=r(5692);function s(e){return e.call.bind(e)}var l="undefined"!=typeof BigInt,c="undefined"!=typeof Symbol,u=s(Object.prototype.toString),p=s(Number.prototype.valueOf),_=s(String.prototype.valueOf),f=s(Boolean.prototype.valueOf);if(l)var h=s(BigInt.prototype.valueOf);if(c)var d=s(Symbol.prototype.valueOf);function g(e,t){if("object"!=typeof e)return!1;try{return t(e),!0}catch(e){return!1}}function y(e){return"[object Map]"===u(e)}function m(e){return"[object Set]"===u(e)}function b(e){return"[object WeakMap]"===u(e)}function w(e){return"[object WeakSet]"===u(e)}function x(e){return"[object ArrayBuffer]"===u(e)}function v(e){return"undefined"!=typeof ArrayBuffer&&(x.working?x(e):e instanceof ArrayBuffer)}function E(e){return"[object DataView]"===u(e)}function O(e){return"undefined"!=typeof DataView&&(E.working?E(e):e instanceof DataView)}t.isArgumentsObject=n,t.isGeneratorFunction=i,t.isTypedArray=a,t.isPromise=function(e){return"undefined"!=typeof Promise&&e instanceof Promise||null!==e&&"object"==typeof e&&"function"==typeof e.then&&"function"==typeof e.catch},t.isArrayBufferView=function(e){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):a(e)||O(e)},t.isUint8Array=function(e){return"Uint8Array"===o(e)},t.isUint8ClampedArray=function(e){return"Uint8ClampedArray"===o(e)},t.isUint16Array=function(e){return"Uint16Array"===o(e)},t.isUint32Array=function(e){return"Uint32Array"===o(e)},t.isInt8Array=function(e){return"Int8Array"===o(e)},t.isInt16Array=function(e){return"Int16Array"===o(e)},t.isInt32Array=function(e){return"Int32Array"===o(e)},t.isFloat32Array=function(e){return"Float32Array"===o(e)},t.isFloat64Array=function(e){return"Float64Array"===o(e)},t.isBigInt64Array=function(e){return"BigInt64Array"===o(e)},t.isBigUint64Array=function(e){return"BigUint64Array"===o(e)},y.working="undefined"!=typeof Map&&y(new Map),t.isMap=function(e){return"undefined"!=typeof Map&&(y.working?y(e):e instanceof Map)},m.working="undefined"!=typeof Set&&m(new Set),t.isSet=function(e){return"undefined"!=typeof Set&&(m.working?m(e):e instanceof Set)},b.working="undefined"!=typeof WeakMap&&b(new WeakMap),t.isWeakMap=function(e){return"undefined"!=typeof WeakMap&&(b.working?b(e):e instanceof WeakMap)},w.working="undefined"!=typeof WeakSet&&w(new WeakSet),t.isWeakSet=function(e){return w(e)},x.working="undefined"!=typeof ArrayBuffer&&x(new ArrayBuffer),t.isArrayBuffer=v,E.working="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof DataView&&E(new DataView(new ArrayBuffer(1),0,1)),t.isDataView=O;var j="undefined"!=typeof SharedArrayBuffer?SharedArrayBuffer:void 0;function S(e){return"[object SharedArrayBuffer]"===u(e)}function R(e){return void 0!==j&&(void 0===S.working&&(S.working=S(new j)),S.working?S(e):e instanceof j)}function A(e){return g(e,p)}function q(e){return g(e,_)}function T(e){return g(e,f)}function k(e){return l&&g(e,h)}function P(e){return c&&g(e,d)}t.isSharedArrayBuffer=R,t.isAsyncFunction=function(e){return"[object AsyncFunction]"===u(e)},t.isMapIterator=function(e){return"[object Map Iterator]"===u(e)},t.isSetIterator=function(e){return"[object Set Iterator]"===u(e)},t.isGeneratorObject=function(e){return"[object Generator]"===u(e)},t.isWebAssemblyCompiledModule=function(e){return"[object WebAssembly.Module]"===u(e)},t.isNumberObject=A,t.isStringObject=q,t.isBooleanObject=T,t.isBigIntObject=k,t.isSymbolObject=P,t.isBoxedPrimitive=function(e){return A(e)||q(e)||T(e)||k(e)||P(e)},t.isAnyArrayBuffer=function(e){return"undefined"!=typeof Uint8Array&&(v(e)||R(e))},["isProxy","isExternal","isModuleNamespaceObject"].forEach((function(e){Object.defineProperty(t,e,{enumerable:!1,value:function(){throw new Error(e+" is not supported in userland")}})}))},9539:(e,t,r)=>{var n=r(4155),i=Object.getOwnPropertyDescriptors||function(e){for(var t=Object.keys(e),r={},n=0;n=i)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}})),s=n[r];r=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),g(r)?n.showHidden=r:r&&t._extend(n,r),w(n.showHidden)&&(n.showHidden=!1),w(n.depth)&&(n.depth=2),w(n.colors)&&(n.colors=!1),w(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=u),_(n,e,n.depth)}function u(e,t){var r=c.styles[t];return r?"["+c.colors[r][0]+"m"+e+"["+c.colors[r][1]+"m":e}function p(e,t){return e}function _(e,r,n){if(e.customInspect&&r&&j(r.inspect)&&r.inspect!==t.inspect&&(!r.constructor||r.constructor.prototype!==r)){var i=r.inspect(n,e);return b(i)||(i=_(e,i,n)),i}var o=function(e,t){if(w(t))return e.stylize("undefined","undefined");if(b(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}return m(t)?e.stylize(""+t,"number"):g(t)?e.stylize(""+t,"boolean"):y(t)?e.stylize("null","null"):void 0}(e,r);if(o)return o;var a=Object.keys(r),s=function(e){var t={};return e.forEach((function(e,r){t[e]=!0})),t}(a);if(e.showHidden&&(a=Object.getOwnPropertyNames(r)),O(r)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return f(r);if(0===a.length){if(j(r)){var l=r.name?": "+r.name:"";return e.stylize("[Function"+l+"]","special")}if(x(r))return e.stylize(RegExp.prototype.toString.call(r),"regexp");if(E(r))return e.stylize(Date.prototype.toString.call(r),"date");if(O(r))return f(r)}var c,u="",p=!1,v=["{","}"];return d(r)&&(p=!0,v=["[","]"]),j(r)&&(u=" [Function"+(r.name?": "+r.name:"")+"]"),x(r)&&(u=" "+RegExp.prototype.toString.call(r)),E(r)&&(u=" "+Date.prototype.toUTCString.call(r)),O(r)&&(u=" "+f(r)),0!==a.length||p&&0!=r.length?n<0?x(r)?e.stylize(RegExp.prototype.toString.call(r),"regexp"):e.stylize("[Object]","special"):(e.seen.push(r),c=p?function(e,t,r,n,i){for(var o=[],a=0,s=t.length;a60?r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1]:r[0]+t+" "+e.join(", ")+" "+r[1]}(c,u,v)):v[0]+u+v[1]}function f(e){return"["+Error.prototype.toString.call(e)+"]"}function h(e,t,r,n,i,o){var a,s,l;if((l=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?s=l.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):l.set&&(s=e.stylize("[Setter]","special")),T(n,i)||(a="["+i+"]"),s||(e.seen.indexOf(l.value)<0?(s=y(r)?_(e,l.value,null):_(e,l.value,r-1)).indexOf("\n")>-1&&(s=o?s.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+s.split("\n").map((function(e){return" "+e})).join("\n")):s=e.stylize("[Circular]","special")),w(a)){if(o&&i.match(/^\d+$/))return s;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function d(e){return Array.isArray(e)}function g(e){return"boolean"==typeof e}function y(e){return null===e}function m(e){return"number"==typeof e}function b(e){return"string"==typeof e}function w(e){return void 0===e}function x(e){return v(e)&&"[object RegExp]"===S(e)}function v(e){return"object"==typeof e&&null!==e}function E(e){return v(e)&&"[object Date]"===S(e)}function O(e){return v(e)&&("[object Error]"===S(e)||e instanceof Error)}function j(e){return"function"==typeof e}function S(e){return Object.prototype.toString.call(e)}function R(e){return e<10?"0"+e.toString(10):e.toString(10)}t.debuglog=function(e){if(e=e.toUpperCase(),!a[e])if(s.test(e)){var r=n.pid;a[e]=function(){var n=t.format.apply(t,arguments);console.error("%s %d: %s",e,r,n)}}else a[e]=function(){};return a[e]},t.inspect=c,c.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},c.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},t.types=r(5955),t.isArray=d,t.isBoolean=g,t.isNull=y,t.isNullOrUndefined=function(e){return null==e},t.isNumber=m,t.isString=b,t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=w,t.isRegExp=x,t.types.isRegExp=x,t.isObject=v,t.isDate=E,t.types.isDate=E,t.isError=O,t.types.isNativeError=O,t.isFunction=j,t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=r(384);var A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function q(){var e=new Date,t=[R(e.getHours()),R(e.getMinutes()),R(e.getSeconds())].join(":");return[e.getDate(),A[e.getMonth()],t].join(" ")}function T(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.log=function(){console.log("%s - %s",q(),t.format.apply(t,arguments))},t.inherits=r(5717),t._extend=function(e,t){if(!t||!v(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e};var k="undefined"!=typeof Symbol?Symbol("util.promisify.custom"):void 0;function P(e,t){if(!e){var r=new Error("Promise was rejected with a falsy value");r.reason=e,e=r}return t(e)}t.promisify=function(e){if("function"!=typeof e)throw new TypeError('The "original" argument must be of type Function');if(k&&e[k]){var t;if("function"!=typeof(t=e[k]))throw new TypeError('The "util.promisify.custom" argument must be of type Function');return Object.defineProperty(t,k,{value:t,enumerable:!1,writable:!1,configurable:!0}),t}function t(){for(var t,r,n=new Promise((function(e,n){t=e,r=n})),i=[],o=0;o{"use strict";var n=r(9804),i=r(3083),o=r(1924),a=o("Object.prototype.toString"),s=r(6410)(),l="undefined"==typeof globalThis?r.g:globalThis,c=i(),u=o("String.prototype.slice"),p={},_=r(882),f=Object.getPrototypeOf;s&&_&&f&&n(c,(function(e){if("function"==typeof l[e]){var t=new l[e];if(Symbol.toStringTag in t){var r=f(t),n=_(r,Symbol.toStringTag);if(!n){var i=f(r);n=_(i,Symbol.toStringTag)}p[e]=n.get}}}));var h=r(5692);e.exports=function(e){return!!h(e)&&(s&&Symbol.toStringTag in e?function(e){var t=!1;return n(p,(function(r,n){if(!t)try{var i=r.call(e);i===n&&(t=i)}catch(e){}})),t}(e):u(a(e),8,-1))}},45:(e,t,r)=>{var n=r(4155);const i=r(4949),o=r(5174),a=r(7857),s=r(6987),l=r(371),c=r(8594),u=/^([0-9]+)(\.[0-9]+)?$/;class p extends Error{}function _(e,t,r){if(e.length>r[0]&&(r[0]=e.length),-1==r[1])return;let n=u.exec(e);if(null===n)return void(!t&&e.length&&(r[1]=-1,r[2]=-1));let i=n[1].length;r[1]=Math.max(r[1],i);let o=void 0===n[2]?0:n[2].length;r[2]=Math.max(r[2],o)}function f(e,t,r,n){if(e=e.trim(),-1==r[1]){let t=Math.max(r[0]-e.length,0);return n?e:e+" ".repeat(t+1)}if(t&&null===u.exec(e)){let t=Math.max(r[0]-e.length,0);return n?e:e+" ".repeat(t+1)}let i=e.indexOf("."),o=-1==i?e.length:i,a=-1==i?0:e.length-i,s=Math.max(r[1]-o,0),l=Math.max(r[2]-a),c=n?"":" ".repeat(l+1);return" ".repeat(s)+e+c}function h(e){return"rbql_table_name:"+e}function d(e,t,r){var n,s="~"===(n=r).charAt(0)?a.join(i.homedir(),n.slice(1)):n;if(o.existsSync(s))return s;if(t&&!a.isAbsolute(s)&&(s=a.join(t,s),o.existsSync(s)))return s;let l=e?e.get(h(r)):null;return l&&o.existsSync(l)?l:null}function g(e,t){const r=e.lineCount;for(let n=0;n1&&e.push(function(e,t){let r=Object.keys(t),n=[];for(let e=0;e1);let[i,o]=n[0],[a,s]=n[1],l=`Number of fields in "${e}" table is not consistent: `;return l+=`e.g. record ${i} -> ${o} fields, record ${a} -> ${s} fields`,l}(this.table_name,this.fields_info)),e}}class b extends s.RBQLOutputWriter{constructor(e,t){if(super(),this.delim=e,this.policy=t,this.header_len=null,this.null_in_output=!1,this.delim_in_simple_output=!1,this.output_lines=[],"simple"==t)this.polymorphic_join=this.simple_join;else if("quoted"==t)this.polymorphic_join=this.quoted_join;else if("quoted_rfc"==t)this.polymorphic_join=this.quoted_join_rfc;else if("monocolumn"==t)this.polymorphic_join=this.mono_join;else{if("whitespace"!=t)throw new y("Unknown output csv policy");this.polymorphic_join=this.simple_join}}set_header(e){null!==e&&(this.header_len=e.length,this.write(e))}quoted_join(e){let t=this.delim;return e.map((function(e){return c.quote_field(String(e),t)})).join(this.delim)}quoted_join_rfc(e){let t=this.delim;return e.map((function(e){return c.rfc_quote_field(String(e),t)})).join(this.delim)}mono_join(e){if(e.length>1)throw new y('Unable to use "Monocolumn" output format: some records have more than one field');return e[0]}simple_join(e){var t=e.join(this.delim);return-1!=e.join("").indexOf(this.delim)&&(this.delim_in_simple_output=!0),t}normalize_fields(e){for(var t=0;t{i||(i=!0,n.close(),a(e))})),n.on("error",(e=>{s(e)})),l},e.exports.rbql_query_web=async function(e,t,r,n,i,o,a,l,c=null){let u=new w,p=new m(t,r,n,l,c),_=new b(i,o);return await s.query(e,p,_,a,u,""),_.output_lines},e.exports.rbql_query_node=async function(e,t,r,c,u,p,_,f,h,d,g=!1,m=null,b="",w=null){let v=null,E=null;w&&w.bulk_read&&r?E=r:v=null===r?n.stdin:o.createReadStream(r);let[O,j]=null===p?[n.stdout,!1]:[o.createWriteStream(p),!0];if('"'==c&&"quoted"==u)throw new y('Double quote delimiter is incompatible with "quoted" policy');if("latin-1"==h&&(h="binary"),!l.is_ascii(t)&&"binary"==h)throw new y("To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary");if(!(l.is_ascii(c)&&l.is_ascii(_)||"binary"!=h))throw new y("To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary");let S=a.join(i.homedir(),".rbql_init_source.js");""==b&&o.existsSync(S)&&(b=l.read_user_init_code(S));let R=r?a.dirname(r):null,A=new x(e,R,c,u,h,g,m,w),q=new l.CSVRecordIterator(v,E,h,c,u,g,m),T=new l.CSVWriter(O,j,h,_,f);await s.query(t,q,T,d,A,b),A.get_warnings(d)},e.exports.get_header_line=g,e.exports.populate_optimistic_rfc_csv_record_map=function(e,t,r,n=null){let i=e.lineCount,o=null;var a;for(let s=r.length?(a=r,a[a.length-1])[1]:0;s=i&&""==t)break;if(n&&t.startsWith(n))continue;let a=t.match(/"/g),l=a&&a.length%2==1;if(null!==o||l)if(null===o&&l)o=s;else{if(!l)continue;r.push([o,s+1]),o=null}else r.push([s,s+1])}null!==o&&r.push([o,i])},e.exports.get_default_js_udf_content=function(){return"// This file can be used to store RBQL UDFs. Example:\n //\n // function foo(value) {\n // return 'foo ' + String(value.length);\n // }\n // \n // Functions defined in this file can be used in RBQL queries e.g. \n // SELECT foo(a1), a2 WHERE foo(a3) != 'foo 5' LIMIT 10\n //\n // Don't forget to save this file after editing!\n //\n // Write your own functions bellow this line:\n ".replace(new RegExp(/^ */,"mg"),"")},e.exports.get_default_python_udf_content=function(){return"# This file can be used to store RBQL UDFs. Example:\n #\n # def foo(value):\n # return 'foo ' + str(len(value))\n # \n # \n # Functions defined in this file can be used in RBQL queries e.g. \n # SELECT foo(a1), a2 WHERE foo(a3) != 'foo 5' LIMIT 10\n #\n # Don't forget to save this file after editing!\n #\n # Write your own functions bellow this line:\n ".replace(new RegExp(/^ */,"mg"),"")},e.exports.align_columns=function(e,t,r,n,i){let o=[],a=e.lineCount,s=!1,l=!0;for(let u=0;u=i.length);e++){let t=e+1==i.length,r=f(_[e],l,i[e],t);_[e]!=r&&(_[e]=r,s=!0)}l=!1,o.push(_.join(t))}return s?o.join("\n"):null},e.exports.shrink_columns=function(e,t,r,n){let i=[],o=e.lineCount,a=!1;for(let s=0;s0&&(r[1]+r[2]>r[0]&&(r[0]=r[1]+r[2]),r[0]-r[2]>r[1]&&(r[1]=r[0]-r[2]),r[0]!=r[1]+r[2]))return null;t.push(r)}return t},e.exports.update_subcomponent_stats=_,e.exports.align_field=f},8594:e=>{let t=new RegExp('^"((?:[^"]*"")*[^"]*)"'),r=new RegExp('^ *"((?:[^"]*"")*[^"]*)" *');function n(e,n,i,o,a,s){var l=!1;let c=e.substring(a),u=(o?r:t).exec(c);if(null!==u){let t=u[0].length;if(a+t==e.length||e[a+t]==n)return i?s.push(u[0]):s.push(u[1].replace(/""/g,'"')),[a+t+1,!1];l=!0}var p=e.indexOf(n,a);-1==p&&(p=e.length);var _=e.substring(a,p);return l=l||-1!=_.indexOf('"'),s.push(_),[p+1,l]}function i(e,t,r=!1){if(-1==e.indexOf('"'))return[e.split(t),!1];var i=[],o=0,a=!1;let s=" "!=t;for(;o{(function(exports){class RbqlParsingError extends Error{}class RbqlRuntimeError extends Error{}class AssertionError extends Error{}class RbqlIOHandlingError extends Error{}class InternalBadFieldError extends Error{constructor(e,...t){super(...t),this.bad_idx=e}}function assert(e,t=null){if(!e)throw t||(t="Assertion error"),new AssertionError(t)}function replace_all(e,t,r){return e.split(t).join(r)}class RBQLContext{constructor(e,t,r,n){this.query_text=e,this.input_iterator=t,this.writer=r,this.user_init_code=n,this.unnest_list=null,this.top_count=null,this.like_regex_cache=new Map,this.sort_key_expression=null,this.aggregation_stage=0,this.aggregation_key_expression=null,this.functional_aggregators=[],this.join_map_impl=null,this.join_map=null,this.lhs_join_var_expression=null,this.where_expression=null,this.select_expression=null,this.update_expressions=null,this.variables_init_code=null}}var query_context=null;const wrong_aggregation_usage_error="Usage of RBQL aggregation functions inside JavaScript expressions is not allowed, see the docs",RBQL_VERSION="0.25.0";function check_if_brackets_match(e,t){return"["==e&&"]"==t||"("==e&&")"==t||"{"==e&&"}"==t}function parse_root_bracket_level_text_spans(e){let t=[],r=0,n=[];for(let i=0;ie.trim())),t}function unquote_string(e){return!e||e.length<2?null:"'"==e[0]&&"'"==e[e.length-1]?e.substring(1,e.length-1).replace(/\\'/g,"'").replace(/\\\\/g,"\\"):'"'==e[0]&&'"'==e[e.length-1]?e.substring(1,e.length-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"):null}function column_info_from_text_span(e,t){e=e.trim();let r="__RBQL_INTERNAL_STAR",n=/^[_a-zA-Z][_a-zA-Z0-9]*$/.exec(e),i=/^([ab])\.([_a-zA-Z][_a-zA-Z0-9]*)$/.exec(e),o=/^([ab])\[([0-9]+)\]$/.exec(e),a=/^([ab])\[___RBQL_STRING_LITERAL([0-9]+)___\]$/.exec(e);if(null!==n){if(e==r)return{table_name:null,column_index:null,column_name:null,is_star:!0};if(e.startsWith("___RBQL_STRING_LITERAL"))return null;let t=/^([ab])([0-9]+)$/.exec(e);return null!==t?{table_name:t[1],column_index:parseInt(t[2])-1,column_name:null,is_star:!1}:{table_name:null,column_index:null,column_name:e,is_star:!1}}if(null!==i){let e=i[1],t=i[2];return t==r?{table_name:e,column_index:null,column_name:null,is_star:!0}:{table_name:null,column_index:null,column_name:t,is_star:!1}}if(null!=o)return{table_name:o[1],column_index:parseInt(o[2])-1,column_name:null,is_star:!1};if(null!=a){a[1];let e=a[2];if(ecolumn_info_from_text_span(e,t)))}function stable_compare(e,t){for(var r=0;r=this.top_count||(await this.subwriter.write(e),this.NW+=1,0))}async finish(){await this.subwriter.finish()}}class UniqWriter{constructor(e){this.subwriter=e,this.seen=new Set}async write(e){return!add_to_set(this.seen,JSON.stringify(e))||!!await this.subwriter.write(e)}async finish(){await this.subwriter.finish()}}class UniqCountWriter{constructor(e){this.subwriter=e,this.records=new Map}async write(e){var t=JSON.stringify(e),r=this.records.get(t);return r?r[0]+=1:this.records.set(t,[1,e]),!0}async finish(){for(var[e,t]of this.records){let[e,r]=t;if(r.unshift(e),!await this.subwriter.write(r))break}await this.subwriter.finish()}}class SortedWriter{constructor(e,t){this.subwriter=e,this.reverse_sort=t,this.unsorted_entries=[]}async write(e){return this.unsorted_entries.push(e),!0}async finish(){var e=this.unsorted_entries;e.sort(stable_compare),this.reverse_sort&&e.reverse();for(var t=0;te instanceof UnnestMarker));for(var o=0;oo+e)),n.slice(0,e).concat(i).concat(n.slice(e+1)).join("\n")+"\n"}assert(!1)}function generate_main_loop_code(e){let t=null!==e.select_expression,r=null!==e.join_map,n=null===e.where_expression?"true":e.where_expression,i=null===e.aggregation_key_expression?"null":e.aggregation_key_expression,o=null===e.sort_key_expression?"null":e.sort_key_expression,a=embed_code(MAIN_LOOP_BODY,"__USER_INIT_CODE__",e.user_init_code);return t?(r?(a=embed_code(embed_code(a,"__CODE__",PROCESS_SELECT_JOIN),"__CODE__",PROCESS_SELECT_COMMON),a=embed_expression(a,"__RBQLMP__lhs_join_var_expression",e.lhs_join_var_expression)):a=embed_code(embed_code(a,"__CODE__",PROCESS_SELECT_SIMPLE),"__CODE__",PROCESS_SELECT_COMMON),a=embed_code(a,"__RBQLMP__variables_init_code",e.variables_init_code),a=embed_expression(a,"__RBQLMP__select_expression",e.select_expression),a=embed_expression(a,"__RBQLMP__where_expression",n),a=embed_expression(a,"__RBQLMP__aggregation_key_expression",i),a=embed_expression(a,"__RBQLMP__sort_key_expression",o)):(r?(a=embed_code(a,"__CODE__",PROCESS_UPDATE_JOIN),a=embed_expression(a,"__RBQLMP__lhs_join_var_expression",e.lhs_join_var_expression)):a=embed_code(a,"__CODE__",PROCESS_UPDATE_SIMPLE),a=embed_code(a,"__RBQLMP__variables_init_code",e.variables_init_code),a=embed_code(a,"__RBQLMP__update_expressions",e.update_expressions),a=embed_expression(a,"__RBQLMP__where_expression",n)),"(async () => {"+a+"})()"}async function compile_and_run(query_context){let main_loop_body=generate_main_loop_code(query_context);try{let main_loop_promise=eval(main_loop_body);await main_loop_promise}catch(e){if(e instanceof SyntaxError){let t=query_context.query_text.toLowerCase();if(-1!=t.indexOf(" having "))throw new SyntaxError(e.message+'\nRBQL doesn\'t support "HAVING" keyword');if(-1!=t.indexOf(" like "))throw new SyntaxError(e.message+"\nRBQL doesn't support \"LIKE\" operator, use like() function instead e.g. ... WHERE like(a1, 'foo%bar') ... ");if(-1!=t.indexOf(" from "))throw new SyntaxError(e.message+'\nTip: If input table is defined by the environment, RBQL query should not have "FROM" keyword');if(e&&e.message&&-1!=String(e.message).toLowerCase().indexOf("unexpected identifier")){if(-1!=t.indexOf(" and "))throw new SyntaxError(e.message+"\nDid you use 'and' keyword in your query?\nJavaScript backend doesn't support 'and' keyword, use '&&' operator instead!");if(-1!=t.indexOf(" or "))throw new SyntaxError(e.message+"\nDid you use 'or' keyword in your query?\nJavaScript backend doesn't support 'or' keyword, use '||' operator instead!")}}if(e&&e.message&&-1!=e.message.indexOf("Received an instance of RBQLAggregationToken"))throw new RbqlParsingError(wrong_aggregation_usage_error);throw e}}const GROUP_BY="GROUP BY",UPDATE="UPDATE",SELECT="SELECT",JOIN="JOIN",INNER_JOIN="INNER JOIN",LEFT_JOIN="LEFT JOIN",LEFT_OUTER_JOIN="LEFT OUTER JOIN",STRICT_LEFT_JOIN="STRICT LEFT JOIN",ORDER_BY="ORDER BY",WHERE="WHERE",LIMIT="LIMIT",EXCEPT="EXCEPT",WITH="WITH";function get_ambiguous_error_msg(e){return`Ambiguous variable name: "${e}" is present both in input and in join tables`}function get_all_matches(e,t){var r=[];let n=null;for(;null!==(n=e.exec(t));)r.push(n);return r}function str_strip(e){return e.replace(/^ +| +$/g,"")}function strip_comments(e){return(e=e.trim()).startsWith("//")?"":e}function combine_string_literals(e,t){for(var r=0;re[1]));for(let e of o){let o=r.indexOf(e);if(-1==o)throw new RbqlParsingError(`Unable to find column "${e}" in ${"a"==t?"input":"join"} ${n}`);i[`${t}.${e}`]={initialize:!0,index:o}}}function map_variables_directly(e,t,r){for(let n=0;n1)throw new RbqlParsingError(`More than one "${o}" statements found`);assert(1==a.length);var s=a[0],l=s[0];r.push([s.index,s.index+l.length,o]);break}}return r.sort((function(e,t){return e[0]-t[0]})),r}function separate_actions(e){e=str_strip(e);var t={};let r=/^(.*) *[Ww][Ii][Tt][Hh] *\(([a-z]{4,20})\) *$/.exec(e);null!==r&&(e=r[1],t[WITH]=r[2]);for(var n=locate_statements(e),i=0;ie-t)),[null===n?null:select_except(n,o),`select_except(record_a, [${o.join(",")}])`]}class HashJoinMap{constructor(e,t){this.max_record_len=0,this.hash_map=new Map,this.record_iterator=e,this.nr=0,1==t.length?(this.key_index=t[0],this.key_indices=null,this.polymorphic_get_key=this.get_single_key):(this.key_index=null,this.key_indices=t,this.polymorphic_get_key=this.get_multi_key)}get_single_key(e,t){if(this.key_index>=t.length)throw new RbqlRuntimeError(`No field with index ${this.key_index+1} at record ${this.nr} in "B" table`);return-1===this.key_index?this.nr:t[this.key_index]}get_multi_key(e,t){let r=[];for(let e of this.key_indices){if(e>=t.length)throw new RbqlRuntimeError(`No field with index ${e+1} at record ${this.nr} in "B" table`);r.push(-1===e?this.nr:t[e])}return JSON.stringify(r)}async build(){for(;;){let e=await this.record_iterator.get_record();if(null===e)break;this.nr+=1;let t=e.length;this.max_record_len=Math.max(this.max_record_len,t);let r=this.polymorphic_get_key(this.nr,e),n=this.hash_map.get(r);void 0===n?this.hash_map.set(r,[[this.nr,t,e]]):n.push([this.nr,t,e])}}get_join_records(e){let t=this.hash_map.get(e);return void 0===t?[]:t}get_warnings(){return this.record_iterator.get_warnings()}}function cleanup_query(e){return e.split("\n").map(strip_comments).filter((e=>e.length)).join(" ").replace(/;+$/g,"")}function remove_redundant_table_name(e){return e=str_strip(e.replace(/ +from +a(?: +|$)/gi," ")),str_strip(e.replace(/^ *update +a +set /gi,"update "))}function select_output_header(e,t,r){if(null===e&&null===t)return null;null===e&&(e=[]),null===t&&(t=[]);let n=[];for(let i of r)null===i?n.push("col"+(n.length+1)):i.is_star?null===i.table_name?n=n.concat(e).concat(t):"a"===i.table_name?n=n.concat(e):"b"===i.table_name&&(n=n.concat(t)):null!==i.column_name?n.push(i.column_name):null!==i.column_index?"a"==i.table_name&&i.column_index1);let[i,o]=n[0],[a,s]=n[1],l=`Number of fields in "${e}" table is not consistent: `;return l+=`e.g. record ${i} -> ${o} fields, record ${a} -> ${s} fields`,l}class RBQLInputIterator{constructor(){}stop(){throw new Error("Unable to call the interface method")}async get_variables_map(e){throw new Error("Unable to call the interface method")}async get_record(){throw new Error("Unable to call the interface method")}handle_query_modifier(){}get_warnings(){return[]}async get_header(){return null}}class RBQLOutputWriter{constructor(){}async write(e){throw new Error("Unable to call the interface method")}async finish(){}get_warnings(){return[]}set_header(){}}class RBQLTableRegistry{constructor(){}get_iterator_by_table_id(e){throw new Error("Unable to call the interface method")}get_warnings(){return[]}}class TableIterator extends RBQLInputIterator{constructor(e,t=null,r=!0,n="a"){super(),this.table=e,this.column_names=t,this.normalize_column_names=r,this.variable_prefix=n,this.nr=0,this.fields_info=new Object,this.stopped=!1}stop(){this.stopped=!0}async get_variables_map(e){let t=new Object;if(parse_basic_variables(e,this.variable_prefix,t),parse_array_variables(e,this.variable_prefix,t),null!==this.column_names){if(this.table.length&&this.column_names.length!=this.table[0].length)throw new RbqlIOHandlingError("List of column names and table records have different lengths");this.normalize_column_names?(parse_dictionary_variables(e,this.variable_prefix,this.column_names,t),parse_attribute_variables(e,this.variable_prefix,this.column_names,"column names list",t)):map_variables_directly(e,this.column_names,t)}return t}async get_record(){if(this.stopped)return null;if(this.nr>=this.table.length)return null;let e=this.table[this.nr];this.nr+=1;let t=e.length;return this.fields_info.hasOwnProperty(t)||(this.fields_info[t]=this.nr),e}get_warnings(){return Object.keys(this.fields_info).length>1?[make_inconsistent_num_fields_warning("input",this.fields_info)]:[]}async get_header(){return this.column_names}}class TableWriter extends RBQLOutputWriter{constructor(e){super(),this.table=e,this.header=null}async write(e){return this.table.push(e),!0}set_header(e){this.header=e}}class SingleTableRegistry extends RBQLTableRegistry{constructor(e,t=null,r=!0,n="b"){super(),this.table=e,this.table_id=n,this.column_names=t,this.normalize_column_names=r}get_iterator_by_table_id(e){if(e.toLowerCase()!==this.table_id)throw new RbqlIOHandlingError(`Unable to find join table: "${e}"`);return new TableIterator(this.table,this.column_names,this.normalize_column_names,"b")}}async function shallow_parse_input_query(e,t,r,n){e=cleanup_query(e);var[i,o]=separate_string_literals(e),a=separate_actions(i=remove_redundant_table_name(i));a.hasOwnProperty(WITH)&&t.handle_query_modifier(a[WITH]);var s=await t.get_variables_map(e);if(a.hasOwnProperty(ORDER_BY)&&a.hasOwnProperty(UPDATE))throw new RbqlParsingError('"ORDER BY" is not allowed in "UPDATE" queries');if(a.hasOwnProperty(GROUP_BY)){if(a.hasOwnProperty(ORDER_BY)||a.hasOwnProperty(UPDATE))throw new RbqlParsingError('"ORDER BY", "UPDATE" and "DISTINCT" keywords are not allowed in aggregate queries');n.aggregation_key_expression="["+combine_string_literals(a[GROUP_BY].text,o)+"]"}let l=null,c=null;if(a.hasOwnProperty(JOIN)){var[u,p]=parse_join_expression(a[JOIN].text);if(null===r)throw new RbqlParsingError("JOIN operations are not supported by the application");let t=r.get_iterator_by_table_id(u);if(!t)throw new RbqlParsingError(`Unable to find join table: "${u}"`);a.hasOwnProperty(WITH)&&t.handle_query_modifier(a[WITH]),l=await t.get_variables_map(e),c=await t.get_header();let[i,_]=resolve_join_variables(s,l,p,o),f={JOIN:InnerJoiner,"INNER JOIN":InnerJoiner,"LEFT JOIN":LeftJoiner,"LEFT OUTER JOIN":LeftJoiner,"STRICT LEFT JOIN":StrictLeftJoiner}[a[JOIN].join_subtype];n.lhs_join_var_expression=1==i.length?i[0]:"JSON.stringify(["+i.join(",")+"])",n.join_map_impl=new HashJoinMap(t,_),await n.join_map_impl.build(),n.join_map=new f(n.join_map_impl)}if(n.variables_init_code=combine_string_literals(generate_init_statements(i,s,l," ".repeat(4)),o),a.hasOwnProperty(WHERE)){var _=a[WHERE].text;if(/[^>{var n=r(4155);const i=r(1606),o=r(4704),a=r(9426),s=r(9539),l=r(6987),c=r(8594),u="Unable to decode input table as UTF-8. Use binary (latin-1) encoding instead";class p extends Error{}class _ extends Error{}function f(e,t=null){if(!e)throw t||(t="Assertion error"),new _(t)}function h(e){return/^[\x00-\x7F]*$/.test(e)}function d(e){return i.readFileSync(e,"utf-8")}function g(e,t){var r,n="~"===(r=t).charAt(0)?a.join(o.homedir(),r.slice(1)):r;if(i.existsSync(n))return n;if(e&&!a.isAbsolute(n)&&(n=a.join(e,n),i.existsSync(n)))return n;var s=function(e,t){for(var r=function(e){var t=null;try{t=i.readFileSync(e,"utf-8")}catch(e){return[]}for(var r=t.split("\n"),n=[],o=0;o1&&i.existsSync(s[1])?s[1]:null}class y{constructor(){this.push_stack=[],this.pull_stack=[]}enqueue(e){this.push_stack.push(e)}dequeue(){if(!this.pull_stack.length){if(!this.push_stack.length)return null;this.pull_stack=this.push_stack,this.pull_stack.reverse(),this.push_stack=[]}return this.pull_stack.pop()}}class m extends l.RBQLInputIterator{constructor(e,t,r,n,i,o=!1,a=null,l="input",c="a"){super(),this.stream=e,this.csv_path=t,f(null===this.stream!=(null===this.csv_path)),this.encoding=r,this.delim=n,this.policy=i,this.has_header=o,this.first_record=null,this.first_record_should_be_emitted=!o,this.header_preread_complete=!1,this.table_name=l,this.variable_prefix=c,this.comment_prefix=null!==a&&a.length?a:null,this.decoder=null,"utf-8"==r&&null===this.csv_path&&(this.decoder=new s.TextDecoder(r,{fatal:!0,stream:!0})),this.input_exhausted=!1,this.started=!1,this.utf8_bom_removed=!1,this.first_defective_line=null,this.fields_info=new Object,this.NR=0,this.NL=0,this.rfc_line_buffer=[],this.partially_decoded_line="",this.partially_decoded_line_ends_with_cr=!1,this.resolve_current_record=null,this.reject_current_record=null,this.current_exception=null,this.produced_records_queue=new y,this.process_line_polymorphic="quoted_rfc"==i?this.process_partial_rfc_record_line:this.process_record_line}handle_query_modifier(e){-1!=["header","headers"].indexOf(e)&&(this.has_header=!0,this.first_record_should_be_emitted=!1),-1!=["noheader","noheaders"].indexOf(e)&&(this.has_header=!1,this.first_record_should_be_emitted=!0)}reset_external_callbacks(){this.reject_current_record=null,this.resolve_current_record=null}try_propagate_exception(){if(this.current_exception&&this.reject_current_record){let e=this.reject_current_record,t=this.current_exception;this.reset_external_callbacks(),this.current_exception=null,e(t)}}store_or_propagate_exception(e){null===this.current_exception&&(this.current_exception=e),this.try_propagate_exception()}async preread_first_record(){this.header_preread_complete||(this.first_record=await this.get_record(),this.header_preread_complete=!0,null!==this.first_record&&(this.stream&&this.stream.pause(),this.first_record=this.first_record.slice()))}async get_variables_map(e){let t=new Object;return l.parse_basic_variables(e,this.variable_prefix,t),l.parse_array_variables(e,this.variable_prefix,t),await this.preread_first_record(),this.has_header&&this.first_record&&(l.parse_attribute_variables(e,this.variable_prefix,this.first_record,"CSV header line",t),l.parse_dictionary_variables(e,this.variable_prefix,this.first_record,t)),t}async get_header(){return await this.preread_first_record(),this.has_header?this.first_record:null}try_resolve_next_record(){if(this.try_propagate_exception(),null===this.resolve_current_record)return;let e=null;if(this.first_record_should_be_emitted&&this.header_preread_complete?(this.first_record_should_be_emitted=!1,e=this.first_record):e=this.produced_records_queue.dequeue(),null===e&&!this.input_exhausted)return;let t=this.resolve_current_record;this.reset_external_callbacks(),t(e)}async get_record(){this.started||await this.start(),this.stream&&this.stream.isPaused()&&this.stream.resume();let e=this,t=new Promise((function(t,r){e.resolve_current_record=t,e.reject_current_record=r}));return this.try_resolve_next_record(),t}async get_all_records(e=null){let t=[];for(;;){let r=await this.get_record();if(null===r)break;if(t.push(r),e&&t.length>=e){this.stop();break}}return t}process_record_line(e){if(null!==this.comment_prefix&&e.startsWith(this.comment_prefix))return;this.NR+=1;var[t,r]=c.smart_split(e,this.delim,this.policy,!1);r&&null===this.first_defective_line&&(this.first_defective_line=this.NL,"quoted_rfc"==this.policy&&this.store_or_propagate_exception(new p(`Inconsistent double quote escaping in ${this.table_name} table at record ${this.NR}, line ${this.NL}`)));let n=t.length;this.fields_info.hasOwnProperty(n)||(this.fields_info[n]=this.NR),this.produced_records_queue.enqueue(t),this.try_resolve_next_record()}process_partial_rfc_record_line(e){let t=c.accumulate_rfc_line_into_record(this.rfc_line_buffer,e,this.comment_prefix);null!==t&&this.process_record_line(t)}process_line(e){if(this.NL+=1,1===this.NL){var t=function(e,t){return"binary"==t&&e.length>=3&&239===e.charCodeAt(0)&&187===e.charCodeAt(1)&&191===e.charCodeAt(2)?e.substring(3):"utf-8"==t&&e.length>=1&&65279===e.charCodeAt(0)?e.substring(1):e}(e,this.encoding);t!=e&&(e=t,this.utf8_bom_removed=!0)}this.process_line_polymorphic(e)}process_data_stream_chunk(e){let t=null;if(this.decoder)try{t=this.decoder.decode(e)}catch(e){return void(e instanceof TypeError?this.store_or_propagate_exception(new p(u)):this.store_or_propagate_exception(e))}else t=e.toString(this.encoding);let r=t.length&&"\n"==t[0]&&this.partially_decoded_line_ends_with_cr?1:0;this.partially_decoded_line_ends_with_cr=t.length&&"\r"==t[t.length-1];let n=c.split_lines(t);n[0]=this.partially_decoded_line+n[0],f(0==r||0==n[0].length),this.partially_decoded_line=n.pop();for(let e=r;e0&&this.process_record_line(this.rfc_line_buffer.join("\n")),this.input_exhausted=!0,this.try_resolve_next_record()}process_data_stream_end(){if(this.input_exhausted=!0,this.partially_decoded_line.length){let e=this.partially_decoded_line;this.partially_decoded_line="",this.process_line(e)}this.rfc_line_buffer.length>0&&this.process_record_line(this.rfc_line_buffer.join("\n")),this.try_resolve_next_record()}stop(){this.stream&&this.stream.destroy()}async start(){if(!this.started){if(this.started=!0,!this.stream){let e=this;return new Promise((function(t,r){i.readFile(e.csv_path,((n,i)=>{n?r(n):(e.process_data_bulk(i),t())}))}))}this.stream.on("data",(e=>{this.process_data_stream_chunk(e)})),this.stream.on("end",(()=>{this.process_data_stream_end()}))}}get_warnings(){let e=[];return null!==this.first_defective_line&&e.push(`Inconsistent double quote escaping in ${this.table_name} table. E.g. at line ${this.first_defective_line}`),this.utf8_bom_removed&&e.push(`UTF-8 Byte Order Mark (BOM) was found and skipped in ${this.table_name} table`),Object.keys(this.fields_info).length>1&&e.push(function(e,t){let r=Object.keys(t),n=[];for(let e=0;e1);let[i,o]=n[0],[a,s]=n[1],l=`Number of fields in "${e}" table is not consistent: `;return l+=`e.g. record ${i} -> ${o} fields, record ${a} -> ${s} fields`,l}(this.table_name,this.fields_info)),e}}class b extends l.RBQLOutputWriter{constructor(e,t,r,n,i,o="\n"){if(super(),this.stream=e,this.encoding=r,r&&this.stream.setDefaultEncoding(r),this.stream.on("error",(e=>{this.store_first_error(e)})),this.delim=n,this.policy=i,this.line_separator=o,this.sub_array_delim="|"==n?";":"|",this.close_stream_on_finish=t,this.null_in_output=!1,this.delim_in_simple_output=!1,this.header_len=null,this.first_error=null,"simple"==i)this.polymorphic_join=this.simple_join;else if("quoted"==i)this.polymorphic_join=this.quoted_join;else if("quoted_rfc"==i)this.polymorphic_join=this.quoted_join_rfc;else if("monocolumn"==i)this.polymorphic_join=this.mono_join;else{if("whitespace"!=i)throw new p("Unknown output csv policy");this.polymorphic_join=this.simple_join}}store_first_error(e){null===this.first_error&&(this.first_error=e)}set_header(e){null!==e&&(this.header_len=e.length,this.write(e))}quoted_join(e){let t=this.delim;return e.map((function(e){return c.quote_field(String(e),t)})).join(this.delim)}quoted_join_rfc(e){let t=this.delim;return e.map((function(e){return c.rfc_quote_field(String(e),t)})).join(this.delim)}mono_join(e){if(e.length>1)throw new p('Unable to use "Monocolumn" output format: some records have more than one field');return e[0]}simple_join(e){var t=e.join(this.delim);return-1!=e.join("").indexOf(this.delim)&&(this.delim_in_simple_output=!0),t}normalize_fields(e){for(var t=0;t{i()})):setTimeout((()=>{i()}),0)}))}get_warnings(){let e=[];return this.null_in_output&&e.push("null values in output were replaced by empty strings"),this.delim_in_simple_output&&e.push("Some output fields contain separator"),e}}class w extends l.RBQLTableRegistry{constructor(e,t,r,n,i=!1,o=null,a=null){super(),this.input_file_dir=e,this.delim=t,this.policy=r,this.encoding=n,this.has_header=i,this.comment_prefix=o,this.stream=null,this.record_iterator=null,this.options=a,this.bulk_input_path=null,this.table_path=null}get_iterator_by_table_id(e){if(this.table_path=g(this.input_file_dir,e),null===this.table_path)throw new p(`Unable to find join table "${e}"`);return this.options&&this.options.bulk_read?this.bulk_input_path=this.table_path:this.stream=i.createReadStream(this.table_path),this.record_iterator=new m(this.stream,this.bulk_input_path,this.encoding,this.delim,this.policy,this.has_header,this.comment_prefix,e,"b"),this.record_iterator}get_warnings(e){this.record_iterator&&this.has_header&&e.push(`The first record in JOIN file ${a.basename(this.table_path)} was also treated as header (and skipped)`)}}e.exports.is_ascii=h,e.exports.CSVRecordIterator=m,e.exports.CSVWriter=b,e.exports.FileSystemCSVRegistry=w,e.exports.interpret_named_csv_format=function(e){if("monocolumn"==(e=e.toLowerCase()))return["","monocolumn"];if("csv"==e)return[",","quoted"];if("tsv"==e)return["\t","simple"];throw new p(`Unknown format name: "${e}"`)},e.exports.read_user_init_code=d,e.exports.query_csv=async function(e,t,r,s,c,u,_,f,g,y=!1,x=null,v="",E=null){let O=null,j=null;E&&E.bulk_read&&t?j=t:O=null===t?n.stdin:i.createReadStream(t);let[S,R]=null===c?[n.stdout,!1]:[i.createWriteStream(c),!0];if('"'==r&&"quoted"==s)throw new p('Double quote delimiter is incompatible with "quoted" policy');if("latin-1"==f&&(f="binary"),!h(e)&&"binary"==f)throw new p("To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary");if(!(h(r)&&h(u)||"binary"!=f))throw new p("To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary");let A=a.join(o.homedir(),".rbql_init_source.js");""==v&&i.existsSync(A)&&(v=d(A));let q=t?a.dirname(t):null,T=new w(q,r,s,f,y,x,E),k=new m(O,j,f,r,s,y,x),P=new b(S,R,f,u,_);await l.query(e,k,P,g,T,v),T.get_warnings(g)},e.exports.RecordQueue=y,e.exports.exception_to_error_info=l.exception_to_error_info},9496:e=>{"use strict";e.exports=require("vscode")},1606:()=>{},4704:()=>{},9426:()=>{},7666:()=>{},5174:()=>{},4949:()=>{},7857:()=>{},8391:()=>{},3083:(e,t,r)=>{"use strict";var n=["BigInt64Array","BigUint64Array","Float32Array","Float64Array","Int16Array","Int32Array","Int8Array","Uint16Array","Uint32Array","Uint8Array","Uint8ClampedArray"],i="undefined"==typeof globalThis?r.g:globalThis;e.exports=function(){for(var e=[],t=0;t{"use strict";var n=r(210)("%Object.getOwnPropertyDescriptor%",!0);if(n)try{n([],"length")}catch(e){n=null}e.exports=n}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(void 0!==t)return t.exports;var r=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](r,r.exports,__webpack_require__),r.exports}__webpack_require__.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}();var __webpack_exports__={};(()=>{var e=__webpack_exports__;const t=__webpack_require__(9282),r=__webpack_require__(7666),n=__webpack_require__(9496),i=__webpack_require__(45),o=void 0===r.homedir,a=6e3;function s(e){return new Promise((t=>setTimeout(t,e)))}function l(e){console.log("###RAINBOW_CSV_UNIT_TEST_MESSAGE### "+e)}e.run=async function(){try{l("Starting tests"),t.equal(-1,[1,2,3].indexOf(0)),t(n.workspace.workspaceFolders),t.equal(1,n.workspace.workspaceFolders.length);let e=n.workspace.workspaceFolders[0].uri;if(await(function(){let e="foobar",r=0,n=[5,2,3];i.update_subcomponent_stats(e,r,n),t.deepEqual(n,[6,-1,-1]),e="foobar",r=1,n=[0,0,0],i.update_subcomponent_stats(e,r,n),t.deepEqual(n,[6,0,0]),e="100000",r=0,n=[2,-1,-1],i.update_subcomponent_stats(e,r,n),t.deepEqual(n,[6,-1,-1]),e="",r=0,n=[5,2,3],i.update_subcomponent_stats(e,r,n),t.deepEqual(n,[5,2,3]),e="100.3",r=0,n=[7,4,3],i.update_subcomponent_stats(e,r,n),t.deepEqual(n,[7,4,3]),e="100000",r=0,n=[5,2,3],i.update_subcomponent_stats(e,r,n),t.deepEqual(n,[6,6,3]),e="1000.23",r=0,n=[3,3,0],i.update_subcomponent_stats(e,r,n),t.deepEqual(n,[7,4,3])}(),function(){let e="foobar",r=0,n=[10,-1,-1];n=i.adjust_column_stats([n])[0];let o=0,a=i.align_field(e,r,n,o);t.deepEqual("foobar ",a),e="foobar",r=0,n=[10,-1,-1],n=i.adjust_column_stats([n])[0],o=1,a=i.align_field(e,r,n,o),t.deepEqual("foobar",a),e="foobar",r=1,n=[10,4,6],n=i.adjust_column_stats([n])[0],o=0,a=i.align_field(e,r,n,o),t.deepEqual("foobar ",a),e="10.1",r=1,n=[10,4,6],n=i.adjust_column_stats([n])[0],o=0,a=i.align_field(e,r,n,o),t.deepEqual(" 10.1 ",a),e="10.1",r=1,n=[10,-1,-1],n=i.adjust_column_stats([n])[0],o=0,a=i.align_field(e,r,n,o),t.deepEqual("10.1 ",a),e="10.1",r=0,n=[10,-1,-1],n=i.adjust_column_stats([n])[0],o=0,a=i.align_field(e,r,n,o),t.deepEqual("10.1 ",a),e="10.1",r=0,n=[10,4,6],n=i.adjust_column_stats([n])[0],o=0,a=i.align_field(e,r,n,o),t.deepEqual(" 10.1 ",a),e="10.1",r=0,n=[10,4,6],n=i.adjust_column_stats([n])[0],o=1,a=i.align_field(e,r,n,o),t.deepEqual(" 10.1",a),e="1000",r=0,n=[10,4,6],n=i.adjust_column_stats([n])[0],o=0,a=i.align_field(e,r,n,o),t.deepEqual("1000 ",a),e="1000",r=0,n=[10,4,6],n=i.adjust_column_stats([n])[0],o=1,a=i.align_field(e,r,n,o),t.deepEqual("1000",a),e="1000",r=0,n=[4,4,0],n=i.adjust_column_stats([n])[0],o=0,a=i.align_field(e,r,n,o),t.deepEqual("1000 ",a),e="1000",r=0,n=[6,4,0],n=i.adjust_column_stats([n])[0],o=0,a=i.align_field(e,r,n,o),t.deepEqual(" 1000 ",a),e="10.1",r=0,n=[12,4,6],n=i.adjust_column_stats([n])[0],o=0,a=i.align_field(e,r,n,o),t.deepEqual(" 10.1 ",a)}(),void function(){let e=[10,-1,-1],r=i.adjust_column_stats([e])[0];t.deepEqual([10,-1,-1],r),e=[10,0,0],r=i.adjust_column_stats([e])[0],t.deepEqual([10,-1,-1],r),e=[5,4,3],r=i.adjust_column_stats([e])[0],t.deepEqual([7,4,3],r),e=[10,4,3],r=i.adjust_column_stats([e])[0],t.deepEqual([10,7,3],r)}()),await async function(e){let r=n.Uri.joinPath(e,"test","csv_files","lorem_ipsum.txt"),i=await n.workspace.openTextDocument(r);l(`languageId for lorem_ipsum.txt: ${i.languageId}`),t.equal(i.languageId,"plaintext");let o=await n.window.showTextDocument(i);await s(1e3),r=n.Uri.joinPath(e,"test","suite","index.js"),i=await n.workspace.openTextDocument(r),l(`languageId for index.js: ${i.languageId}`),t.equal(i.languageId,"javascript"),o=await n.window.showTextDocument(i),await s(1e3),r=n.Uri.joinPath(e,"test","csv_files","lorem_ipsum"),i=await n.workspace.openTextDocument(r),l(`languageId for lorem_ipsum: ${i.languageId}`),t.equal(i.languageId,"plaintext"),o=await n.window.showTextDocument(i),await s(1e3)}(e),!o){let e=await n.commands.executeCommand("rainbow-csv.InternalTest",{check_initialization_state:!0});t(e.initialized),t(!e.lazy_loaded)}if(await async function(e){let r=n.Uri.joinPath(e,"test","csv_files","university_ranking_semicolon.txt"),i=await n.workspace.openTextDocument(r);await n.window.showTextDocument(i),l(`languageId for university_ranking_semicolon.txt: ${i.languageId}`),t.equal(i.languageId,"csv (semicolon)"),await s(1e3)}(e),await async function(e){let r=n.Uri.joinPath(e,"test","csv_files","small_movies.pipe"),i=await n.workspace.openTextDocument(r);l(`languageId for small_movies.pipe: ${i.languageId}`),t.equal(i.languageId,"plaintext"),await n.window.showTextDocument(i),await s(1e3);for(let e=0;e<6;e++)await n.commands.executeCommand("cursorRight");await n.commands.executeCommand("cursorRightSelect"),await s(1e3),await n.commands.executeCommand("rainbow-csv.RainbowSeparator"),await s(2e3),l(`languageId for small_movies.pipe after RainbowSeparator: ${i.languageId}`),t.equal(i.languageId,"csv (pipe)"),await n.commands.executeCommand("rainbow-csv.RainbowSeparatorOff"),await s(2e3),l(`languageId for small_movies.pipe after RainbowSeparatorOff: ${i.languageId}`),t.equal(i.languageId,"plaintext"),await s(1e3)}(e),!o){let e=await n.commands.executeCommand("rainbow-csv.InternalTest",{check_initialization_state:!0});t(e.initialized),t(!e.lazy_loaded)}if(o?await async function(e){let r=n.Uri.joinPath(e,"test","csv_files","university_ranking.csv"),i=await n.workspace.openTextDocument(r),o=await n.window.showTextDocument(i);await s(1e3);let c={rbql_backend:"js",with_headers:!0,rbql_query:"select top 20 a1, Math.ceil(parseFloat(a.total_score) * 100), a['university_name'], null, 'foo bar' order by a2"};await n.commands.executeCommand("rainbow-csv.RBQL",c),await s(a);let u=await n.commands.executeCommand("rainbow-csv.InternalTest",{check_last_rbql_warnings:!0});t.equal('["null values in output were replaced by empty strings"]',JSON.stringify(u.warnings)),i=n.window.activeTextEditor.document;let p=i.getText().length;l(`Length after first js query: ${p}`),t.equal(846,p),c={rbql_backend:"js",rbql_query:"select a2 * 10, a3, a3.length where NR > 1 order by a3.length limit 10"},await n.commands.executeCommand("rainbow-csv.RBQL",c),await s(a),i=n.window.activeTextEditor.document,p=i.getText().length,l(`Length after second js query: ${p}`),t.equal(267,p),c={rbql_backend:"js",rbql_query:"select nonexistent_function(a1)"},await n.commands.executeCommand("rainbow-csv.RBQL",c),await s(a),u=await n.commands.executeCommand("rainbow-csv.InternalTest",{check_last_rbql_report:!0}),t.equal("query execution",u.error_type),t.equal("At record 1, Details: nonexistent_function is not defined",u.error_msg),l("Starting multiline records test"),r=n.Uri.joinPath(e,"test","csv_files","synthetic_rfc_newline_data.csv"),i=await n.workspace.openTextDocument(r),o=await n.window.showTextDocument(i),await s(1e3),c={rbql_backend:"js",rbql_query:"select '<<<<<', a3, a2, a1, '>>>>> NR: ' + NR",enable_rfc_newlines:!0},await n.commands.executeCommand("rainbow-csv.RBQL",c),await s(a),i=n.window.activeTextEditor.document,p=i.getText().length,l(`Length after js multiline-record query: ${p}`),t.equal(644,p)}(e):await async function(e){let r=n.Uri.joinPath(e,"test","csv_files","university_ranking.csv"),i=await n.workspace.openTextDocument(r),o=await n.window.showTextDocument(i);await s(1e3);let c={rbql_backend:"python",with_headers:!0,rbql_query:"select top 20 a1, math.ceil(float(a.total_score) * 100), a['university_name'], None, 'foo bar' order by a2"};await n.commands.executeCommand("rainbow-csv.RBQL",c),await s(a);let u=await n.commands.executeCommand("rainbow-csv.InternalTest",{check_last_rbql_warnings:!0});t.equal('["None values in output were replaced by empty strings"]',JSON.stringify(u.warnings)),i=n.window.activeTextEditor.document;let p=i.getText().length;l(`Length after python query: ${p}`),t.equal(868,p),c={rbql_backend:"js",rbql_query:"select a2 * 10, a3, a3.length where NR > 1 order by a3.length limit 10"},await n.commands.executeCommand("rainbow-csv.RBQL",c),await s(a),i=n.window.activeTextEditor.document,p=i.getText().length,l(`Length after js query: ${p}`),t.equal(268,p),c={rbql_backend:"python",rbql_query:"select nonexistent_function(a1)"},await n.commands.executeCommand("rainbow-csv.RBQL",c),await s(a),u=await n.commands.executeCommand("rainbow-csv.InternalTest",{check_last_rbql_report:!0}),t.equal("query execution",u.error_type),t.equal("At record 1, Details: name 'nonexistent_function' is not defined",u.error_msg),r=n.Uri.joinPath(e,"test","csv_files","synthetic_rfc_newline_data.csv"),i=await n.workspace.openTextDocument(r),o=await n.window.showTextDocument(i),await s(1e3),c={rbql_backend:"js",rbql_query:"select '<<<<<', a3, a2, a1, '>>>>> NR: ' + NR",enable_rfc_newlines:!0},await n.commands.executeCommand("rainbow-csv.RBQL",c),await s(a),i=n.window.activeTextEditor.document,p=i.getText().length,l(`Length after js multiline-record query: ${p}`),t.equal(645,p),r=n.Uri.joinPath(e,"test","csv_files","university_ranking.csv"),i=await n.workspace.openTextDocument(r),o=await n.window.showTextDocument(i),await s(1e3),c={rbql_backend:"python",with_headers:!0,rbql_query:"select a.university_name, b.Country, b.Population, b['GDP per capita'] JOIN countries.csv on a.country == b.Country order by int(b.Population) desc"},await n.commands.executeCommand("rainbow-csv.RBQL",c),await s(a),u=await n.commands.executeCommand("rainbow-csv.InternalTest",{check_last_rbql_warnings:!0}),t.equal('["The first record in JOIN file countries.csv was also treated as header (and skipped)"]',JSON.stringify(u.warnings)),i=n.window.activeTextEditor.document,p=i.getText().length,l(`Length after join query: ${p}`),t.equal(11592,p),t.equal(202,i.lineCount),r=n.Uri.joinPath(e,"test","csv_files","countries.csv"),i=await n.workspace.openTextDocument(r);let _=i.fileName,f=i.getText().length;o=await n.window.showTextDocument(i),t(-1==i.getText().indexOf("oceania")),t(i.getText().indexOf("OCEANIA")>0),await s(1e3),c={rbql_backend:"python",with_headers:!0,rbql_query:"UPDATE set a.Region = a.Region.lower()"},await n.commands.executeCommand("rainbow-csv.RBQL",c),await s(a),u=await n.commands.executeCommand("rainbow-csv.InternalTest",{check_last_rbql_warnings:!0}),t.equal("[]",JSON.stringify(u.warnings)),i=n.window.activeTextEditor.document,i.fileName,p=i.getText().length,l(`Length after update query: ${p}`),t.equal(f,p-i.lineCount+1),t(-1==i.getText().indexOf("OCEANIA")),t(i.getText().indexOf("oceania")>0),await s(1e3),await n.commands.executeCommand("rainbow-csv.CopyBack"),await s(1e3),i=await n.workspace.openTextDocument(r);let h=i.fileName;t.equal(_,h),t(-1==i.getText().indexOf("OCEANIA")),t(i.getText().indexOf("oceania")>0)}(e),!o){let e=await n.commands.executeCommand("rainbow-csv.InternalTest",{check_initialization_state:!0});t(e.initialized),t(e.lazy_loaded)}await async function(e){let r=n.Uri.joinPath(e,"test","csv_files","university_ranking.csv"),i=await n.workspace.openTextDocument(r),o=(await n.window.showTextDocument(i),i.getText().length);l(`Original length: ${o}`),t.equal(12538,o),await s(2e3),await n.commands.executeCommand("rainbow-csv.Align");let a=i.getText().length;l(`Aligned length: ${a}`),t.equal(25896,a),t(a>o);let c=await n.commands.executeCommand("rainbow-csv.CSVLint");t.equal(c,"OK"),await s(2e3),await n.commands.executeCommand("rainbow-csv.Shrink");let u=i.getText().length;l(`Shrinked length: ${u}`),t.equal(o,u),await s(500);let p="foobar,";await n.commands.executeCommand("default:type",{text:p}),c=await n.commands.executeCommand("rainbow-csv.CSVLint"),t(-1!=c.indexOf("Number of fields is not consistent")),await s(500);for(let e=0;e + * @license MIT + */ diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/dist/web/test/suite/index.js.map b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/dist/web/test/suite/index.js.map new file mode 100644 index 00000000..4eef58d1 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/dist/web/test/suite/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"test/suite/index.js","mappings":";yEAuBA,SAASA,EAAQC,GAAwT,OAAtOD,EAArD,mBAAXE,QAAoD,iBAApBA,OAAOC,SAAmC,SAAiBF,GAAO,cAAcA,GAA2B,SAAiBA,GAAO,OAAOA,GAAyB,mBAAXC,QAAyBD,EAAIG,cAAgBF,QAAUD,IAAQC,OAAOG,UAAY,gBAAkBJ,GAAiBD,EAAQC,GAIxV,IAoBIK,EACAC,EApBAC,EADW,EAAQ,MACOC,MAC1BC,EAAyBF,EAAeE,uBACxCC,EAAuBH,EAAeG,qBACtCC,EAAwBJ,EAAeI,sBACvCC,EAA2BL,EAAeK,yBAC1CC,EAAmBN,EAAeM,iBAElCC,EAAiB,EAAQ,MAGzBC,EADY,EAAQ,MACAA,QAEpBC,EAAiB,cACjBC,EAAYD,EAAeC,UAC3BC,EAAWF,EAAeE,SAE1BC,EAAeC,OAAOC,OAASD,OAAOC,OAAS,eAC/CC,EAAWF,OAAOG,GAAKH,OAAOG,GAAK,EAAQ,KAQ/C,SAASC,IACP,IAAIC,EAAa,EAAQ,MAEzBpB,EAAcoB,EAAWpB,YACzBC,EAAoBmB,EAAWnB,kBAXhB,IAAIoB,IAiBrB,IAOIC,GAAS,EAITC,EAASC,EAAOC,QAAUC,EAC1BC,EAAwB,GAM5B,SAASC,EAAUjC,GACjB,GAAIA,EAAIkC,mBAAmBC,MAAO,MAAMnC,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.js","webpack://rainbow-csv/./node_modules/assert/build/internal/assert/assertion_error.js","webpack://rainbow-csv/./node_modules/assert/build/internal/errors.js","webpack://rainbow-csv/./node_modules/assert/build/internal/util/comparisons.js","webpack://rainbow-csv/./node_modules/call-bind/callBound.js","webpack://rainbow-csv/./node_modules/call-bind/index.js","webpack://rainbow-csv/./node_modules/define-properties/index.js","webpack://rainbow-csv/./node_modules/es6-object-assign/index.js","webpack://rainbow-csv/./node_modules/foreach/index.js","webpack://rainbow-csv/./node_modules/function-bind/implementation.js","webpack://rainbow-csv/./node_modules/function-bind/index.js","webpack://rainbow-csv/./node_modules/get-intrinsic/index.js","webpack://rainbow-csv/./node_modules/has-property-descriptors/index.js","webpack://rainbow-csv/./node_modules/has-symbols/index.js","webpack://rainbow-csv/./node_modules/has-symbols/shams.js","webpack://rainbow-csv/./node_modules/has-tostringtag/shams.js","webpack://rainbow-csv/./node_modules/has/src/index.js","webpack://rainbow-csv/./node_modules/inherits/inherits_browser.js","webpack://rainbow-csv/./node_modules/is-arguments/index.js","webpack://rainbow-csv/./node_modules/is-generator-function/index.js","webpack://rainbow-csv/./node_modules/is-nan/implementation.js","webpack://rainbow-csv/./node_modules/is-nan/index.js","webpack://rainbow-csv/./node_modules/is-nan/polyfill.js","webpack://rainbow-csv/./node_modules/is-nan/shim.js","webpack://rainbow-csv/./node_modules/is-typed-array/index.js","webpack://rainbow-csv/./node_modules/object-is/implementation.js","webpack://rainbow-csv/./node_modules/object-is/index.js","webpack://rainbow-csv/./node_modules/object-is/polyfill.js","webpack://rainbow-csv/./node_modules/object-is/shim.js","webpack://rainbow-csv/./node_modules/object-keys/implementation.js","webpack://rainbow-csv/./node_modules/object-keys/index.js","webpack://rainbow-csv/./node_modules/object-keys/isArguments.js","webpack://rainbow-csv/./node_modules/process/browser.js","webpack://rainbow-csv/./node_modules/util/support/isBufferBrowser.js","webpack://rainbow-csv/./node_modules/util/support/types.js","webpack://rainbow-csv/./node_modules/util/util.js","webpack://rainbow-csv/./node_modules/which-typed-array/index.js","webpack://rainbow-csv/./rainbow_utils.js","webpack://rainbow-csv/./rbql_core/rbql-js/csv_utils.js","webpack://rainbow-csv/./rbql_core/rbql-js/rbql.js","webpack://rainbow-csv/./rbql_core/rbql-js/rbql_csv.js","webpack://rainbow-csv/external commonjs \"vscode\"","webpack://rainbow-csv/./node_modules/available-typed-arrays/index.js","webpack://rainbow-csv/./node_modules/es-abstract/helpers/getOwnPropertyDescriptor.js","webpack://rainbow-csv/webpack/bootstrap","webpack://rainbow-csv/webpack/runtime/global","webpack://rainbow-csv/./test/suite/index.js"],"sourcesContent":["// Currently in sync with Node.js lib/assert.js\n// https://github.com/nodejs/node/commit/2a51ae424a513ec9a6aa3466baa0cc1d55dd4f3b\n// Originally from narwhal.js (http://narwhaljs.org)\n// Copyright (c) 2009 Thomas Robinson <280north.com>\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the 'Software'), to\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n'use strict';\n\nfunction _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nvar _require = require('./internal/errors'),\n _require$codes = _require.codes,\n ERR_AMBIGUOUS_ARGUMENT = _require$codes.ERR_AMBIGUOUS_ARGUMENT,\n ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,\n ERR_INVALID_ARG_VALUE = _require$codes.ERR_INVALID_ARG_VALUE,\n ERR_INVALID_RETURN_VALUE = _require$codes.ERR_INVALID_RETURN_VALUE,\n ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS;\n\nvar AssertionError = require('./internal/assert/assertion_error');\n\nvar _require2 = require('util/'),\n inspect = _require2.inspect;\n\nvar _require$types = require('util/').types,\n isPromise = _require$types.isPromise,\n isRegExp = _require$types.isRegExp;\n\nvar objectAssign = Object.assign ? Object.assign : require('es6-object-assign').assign;\nvar objectIs = Object.is ? Object.is : require('object-is');\nvar errorCache = new Map();\nvar isDeepEqual;\nvar isDeepStrictEqual;\nvar parseExpressionAt;\nvar findNodeAround;\nvar decoder;\n\nfunction lazyLoadComparison() {\n var comparison = require('./internal/util/comparisons');\n\n isDeepEqual = comparison.isDeepEqual;\n isDeepStrictEqual = comparison.isDeepStrictEqual;\n} // Escape control characters but not \\n and \\t to keep the line breaks and\n// indentation intact.\n// eslint-disable-next-line no-control-regex\n\n\nvar escapeSequencesRegExp = /[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f]/g;\nvar meta = [\"\\\\u0000\", \"\\\\u0001\", \"\\\\u0002\", \"\\\\u0003\", \"\\\\u0004\", \"\\\\u0005\", \"\\\\u0006\", \"\\\\u0007\", '\\\\b', '', '', \"\\\\u000b\", '\\\\f', '', \"\\\\u000e\", \"\\\\u000f\", \"\\\\u0010\", \"\\\\u0011\", \"\\\\u0012\", \"\\\\u0013\", \"\\\\u0014\", \"\\\\u0015\", \"\\\\u0016\", \"\\\\u0017\", \"\\\\u0018\", \"\\\\u0019\", \"\\\\u001a\", \"\\\\u001b\", \"\\\\u001c\", \"\\\\u001d\", \"\\\\u001e\", \"\\\\u001f\"];\n\nvar escapeFn = function escapeFn(str) {\n return meta[str.charCodeAt(0)];\n};\n\nvar warned = false; // The assert module provides functions that throw\n// AssertionError's when particular conditions are not met. The\n// assert module must conform to the following interface.\n\nvar assert = module.exports = ok;\nvar NO_EXCEPTION_SENTINEL = {}; // All of the following functions must throw an AssertionError\n// when a corresponding condition is not met, with a message that\n// may be undefined if not provided. All assertion methods provide\n// both the actual and expected values to the assertion error for\n// display purposes.\n\nfunction innerFail(obj) {\n if (obj.message instanceof Error) throw obj.message;\n throw new AssertionError(obj);\n}\n\nfunction fail(actual, expected, message, operator, stackStartFn) {\n var argsLen = arguments.length;\n var internalMessage;\n\n if (argsLen === 0) {\n internalMessage = 'Failed';\n } else if (argsLen === 1) {\n message = actual;\n actual = undefined;\n } else {\n if (warned === false) {\n warned = true;\n var warn = process.emitWarning ? process.emitWarning : console.warn.bind(console);\n warn('assert.fail() with more than one argument is deprecated. ' + 'Please use assert.strictEqual() instead or only pass a message.', 'DeprecationWarning', 'DEP0094');\n }\n\n if (argsLen === 2) operator = '!=';\n }\n\n if (message instanceof Error) throw message;\n var errArgs = {\n actual: actual,\n expected: expected,\n operator: operator === undefined ? 'fail' : operator,\n stackStartFn: stackStartFn || fail\n };\n\n if (message !== undefined) {\n errArgs.message = message;\n }\n\n var err = new AssertionError(errArgs);\n\n if (internalMessage) {\n err.message = internalMessage;\n err.generatedMessage = true;\n }\n\n throw err;\n}\n\nassert.fail = fail; // The AssertionError is defined in internal/error.\n\nassert.AssertionError = AssertionError;\n\nfunction innerOk(fn, argLen, value, message) {\n if (!value) {\n var generatedMessage = false;\n\n if (argLen === 0) {\n generatedMessage = true;\n message = 'No value argument passed to `assert.ok()`';\n } else if (message instanceof Error) {\n throw message;\n }\n\n var err = new AssertionError({\n actual: value,\n expected: true,\n message: message,\n operator: '==',\n stackStartFn: fn\n });\n err.generatedMessage = generatedMessage;\n throw err;\n }\n} // Pure assertion tests whether a value is truthy, as determined\n// by !!value.\n\n\nfunction ok() {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n innerOk.apply(void 0, [ok, args.length].concat(args));\n}\n\nassert.ok = ok; // The equality assertion tests shallow, coercive equality with ==.\n\n/* eslint-disable no-restricted-properties */\n\nassert.equal = function equal(actual, expected, message) {\n if (arguments.length < 2) {\n throw new ERR_MISSING_ARGS('actual', 'expected');\n } // eslint-disable-next-line eqeqeq\n\n\n if (actual != expected) {\n innerFail({\n actual: actual,\n expected: expected,\n message: message,\n operator: '==',\n stackStartFn: equal\n });\n }\n}; // The non-equality assertion tests for whether two objects are not\n// equal with !=.\n\n\nassert.notEqual = function notEqual(actual, expected, message) {\n if (arguments.length < 2) {\n throw new ERR_MISSING_ARGS('actual', 'expected');\n } // eslint-disable-next-line eqeqeq\n\n\n if (actual == expected) {\n innerFail({\n actual: actual,\n expected: expected,\n message: message,\n operator: '!=',\n stackStartFn: notEqual\n });\n }\n}; // The equivalence assertion tests a deep equality relation.\n\n\nassert.deepEqual = function deepEqual(actual, expected, message) {\n if (arguments.length < 2) {\n throw new ERR_MISSING_ARGS('actual', 'expected');\n }\n\n if (isDeepEqual === undefined) lazyLoadComparison();\n\n if (!isDeepEqual(actual, expected)) {\n innerFail({\n actual: actual,\n expected: expected,\n message: message,\n operator: 'deepEqual',\n stackStartFn: deepEqual\n });\n }\n}; // The non-equivalence assertion tests for any deep inequality.\n\n\nassert.notDeepEqual = function notDeepEqual(actual, expected, message) {\n if (arguments.length < 2) {\n throw new ERR_MISSING_ARGS('actual', 'expected');\n }\n\n if (isDeepEqual === undefined) lazyLoadComparison();\n\n if (isDeepEqual(actual, expected)) {\n innerFail({\n actual: actual,\n expected: expected,\n message: message,\n operator: 'notDeepEqual',\n stackStartFn: notDeepEqual\n });\n }\n};\n/* eslint-enable */\n\n\nassert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {\n if (arguments.length < 2) {\n throw new ERR_MISSING_ARGS('actual', 'expected');\n }\n\n if (isDeepEqual === undefined) lazyLoadComparison();\n\n if (!isDeepStrictEqual(actual, expected)) {\n innerFail({\n actual: actual,\n expected: expected,\n message: message,\n operator: 'deepStrictEqual',\n stackStartFn: deepStrictEqual\n });\n }\n};\n\nassert.notDeepStrictEqual = notDeepStrictEqual;\n\nfunction notDeepStrictEqual(actual, expected, message) {\n if (arguments.length < 2) {\n throw new ERR_MISSING_ARGS('actual', 'expected');\n }\n\n if (isDeepEqual === undefined) lazyLoadComparison();\n\n if (isDeepStrictEqual(actual, expected)) {\n innerFail({\n actual: actual,\n expected: expected,\n message: message,\n operator: 'notDeepStrictEqual',\n stackStartFn: notDeepStrictEqual\n });\n }\n}\n\nassert.strictEqual = function strictEqual(actual, expected, message) {\n if (arguments.length < 2) {\n throw new ERR_MISSING_ARGS('actual', 'expected');\n }\n\n if (!objectIs(actual, expected)) {\n innerFail({\n actual: actual,\n expected: expected,\n message: message,\n operator: 'strictEqual',\n stackStartFn: strictEqual\n });\n }\n};\n\nassert.notStrictEqual = function notStrictEqual(actual, expected, message) {\n if (arguments.length < 2) {\n throw new ERR_MISSING_ARGS('actual', 'expected');\n }\n\n if (objectIs(actual, expected)) {\n innerFail({\n actual: actual,\n expected: expected,\n message: message,\n operator: 'notStrictEqual',\n stackStartFn: notStrictEqual\n });\n }\n};\n\nvar Comparison = function Comparison(obj, keys, actual) {\n var _this = this;\n\n _classCallCheck(this, Comparison);\n\n keys.forEach(function (key) {\n if (key in obj) {\n if (actual !== undefined && typeof actual[key] === 'string' && isRegExp(obj[key]) && obj[key].test(actual[key])) {\n _this[key] = actual[key];\n } else {\n _this[key] = obj[key];\n }\n }\n });\n};\n\nfunction compareExceptionKey(actual, expected, key, message, keys, fn) {\n if (!(key in actual) || !isDeepStrictEqual(actual[key], expected[key])) {\n if (!message) {\n // Create placeholder objects to create a nice output.\n var a = new Comparison(actual, keys);\n var b = new Comparison(expected, keys, actual);\n var err = new AssertionError({\n actual: a,\n expected: b,\n operator: 'deepStrictEqual',\n stackStartFn: fn\n });\n err.actual = actual;\n err.expected = expected;\n err.operator = fn.name;\n throw err;\n }\n\n innerFail({\n actual: actual,\n expected: expected,\n message: message,\n operator: fn.name,\n stackStartFn: fn\n });\n }\n}\n\nfunction expectedException(actual, expected, msg, fn) {\n if (typeof expected !== 'function') {\n if (isRegExp(expected)) return expected.test(actual); // assert.doesNotThrow does not accept objects.\n\n if (arguments.length === 2) {\n throw new ERR_INVALID_ARG_TYPE('expected', ['Function', 'RegExp'], expected);\n } // Handle primitives properly.\n\n\n if (_typeof(actual) !== 'object' || actual === null) {\n var err = new AssertionError({\n actual: actual,\n expected: expected,\n message: msg,\n operator: 'deepStrictEqual',\n stackStartFn: fn\n });\n err.operator = fn.name;\n throw err;\n }\n\n var keys = Object.keys(expected); // Special handle errors to make sure the name and the message are compared\n // as well.\n\n if (expected instanceof Error) {\n keys.push('name', 'message');\n } else if (keys.length === 0) {\n throw new ERR_INVALID_ARG_VALUE('error', expected, 'may not be an empty object');\n }\n\n if (isDeepEqual === undefined) lazyLoadComparison();\n keys.forEach(function (key) {\n if (typeof actual[key] === 'string' && isRegExp(expected[key]) && expected[key].test(actual[key])) {\n return;\n }\n\n compareExceptionKey(actual, expected, key, msg, keys, fn);\n });\n return true;\n } // Guard instanceof against arrow functions as they don't have a prototype.\n\n\n if (expected.prototype !== undefined && actual instanceof expected) {\n return true;\n }\n\n if (Error.isPrototypeOf(expected)) {\n return false;\n }\n\n return expected.call({}, actual) === true;\n}\n\nfunction getActual(fn) {\n if (typeof fn !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('fn', 'Function', fn);\n }\n\n try {\n fn();\n } catch (e) {\n return e;\n }\n\n return NO_EXCEPTION_SENTINEL;\n}\n\nfunction checkIsPromise(obj) {\n // Accept native ES6 promises and promises that are implemented in a similar\n // way. Do not accept thenables that use a function as `obj` and that have no\n // `catch` handler.\n // TODO: thenables are checked up until they have the correct methods,\n // but according to documentation, the `then` method should receive\n // the `fulfill` and `reject` arguments as well or it may be never resolved.\n return isPromise(obj) || obj !== null && _typeof(obj) === 'object' && typeof obj.then === 'function' && typeof obj.catch === 'function';\n}\n\nfunction waitForActual(promiseFn) {\n return Promise.resolve().then(function () {\n var resultPromise;\n\n if (typeof promiseFn === 'function') {\n // Return a rejected promise if `promiseFn` throws synchronously.\n resultPromise = promiseFn(); // Fail in case no promise is returned.\n\n if (!checkIsPromise(resultPromise)) {\n throw new ERR_INVALID_RETURN_VALUE('instance of Promise', 'promiseFn', resultPromise);\n }\n } else if (checkIsPromise(promiseFn)) {\n resultPromise = promiseFn;\n } else {\n throw new ERR_INVALID_ARG_TYPE('promiseFn', ['Function', 'Promise'], promiseFn);\n }\n\n return Promise.resolve().then(function () {\n return resultPromise;\n }).then(function () {\n return NO_EXCEPTION_SENTINEL;\n }).catch(function (e) {\n return e;\n });\n });\n}\n\nfunction expectsError(stackStartFn, actual, error, message) {\n if (typeof error === 'string') {\n if (arguments.length === 4) {\n throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error);\n }\n\n if (_typeof(actual) === 'object' && actual !== null) {\n if (actual.message === error) {\n throw new ERR_AMBIGUOUS_ARGUMENT('error/message', \"The error message \\\"\".concat(actual.message, \"\\\" is identical to the message.\"));\n }\n } else if (actual === error) {\n throw new ERR_AMBIGUOUS_ARGUMENT('error/message', \"The error \\\"\".concat(actual, \"\\\" is identical to the message.\"));\n }\n\n message = error;\n error = undefined;\n } else if (error != null && _typeof(error) !== 'object' && typeof error !== 'function') {\n throw new ERR_INVALID_ARG_TYPE('error', ['Object', 'Error', 'Function', 'RegExp'], error);\n }\n\n if (actual === NO_EXCEPTION_SENTINEL) {\n var details = '';\n\n if (error && error.name) {\n details += \" (\".concat(error.name, \")\");\n }\n\n details += message ? \": \".concat(message) : '.';\n var fnType = stackStartFn.name === 'rejects' ? 'rejection' : 'exception';\n innerFail({\n actual: undefined,\n expected: error,\n operator: stackStartFn.name,\n message: \"Missing expected \".concat(fnType).concat(details),\n stackStartFn: stackStartFn\n });\n }\n\n if (error && !expectedException(actual, error, message, stackStartFn)) {\n throw actual;\n }\n}\n\nfunction expectsNoError(stackStartFn, actual, error, message) {\n if (actual === NO_EXCEPTION_SENTINEL) return;\n\n if (typeof error === 'string') {\n message = error;\n error = undefined;\n }\n\n if (!error || expectedException(actual, error)) {\n var details = message ? \": \".concat(message) : '.';\n var fnType = stackStartFn.name === 'doesNotReject' ? 'rejection' : 'exception';\n innerFail({\n actual: actual,\n expected: error,\n operator: stackStartFn.name,\n message: \"Got unwanted \".concat(fnType).concat(details, \"\\n\") + \"Actual message: \\\"\".concat(actual && actual.message, \"\\\"\"),\n stackStartFn: stackStartFn\n });\n }\n\n throw actual;\n}\n\nassert.throws = function throws(promiseFn) {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n\n expectsError.apply(void 0, [throws, getActual(promiseFn)].concat(args));\n};\n\nassert.rejects = function rejects(promiseFn) {\n for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {\n args[_key3 - 1] = arguments[_key3];\n }\n\n return waitForActual(promiseFn).then(function (result) {\n return expectsError.apply(void 0, [rejects, result].concat(args));\n });\n};\n\nassert.doesNotThrow = function doesNotThrow(fn) {\n for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {\n args[_key4 - 1] = arguments[_key4];\n }\n\n expectsNoError.apply(void 0, [doesNotThrow, getActual(fn)].concat(args));\n};\n\nassert.doesNotReject = function doesNotReject(fn) {\n for (var _len5 = arguments.length, args = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {\n args[_key5 - 1] = arguments[_key5];\n }\n\n return waitForActual(fn).then(function (result) {\n return expectsNoError.apply(void 0, [doesNotReject, result].concat(args));\n });\n};\n\nassert.ifError = function ifError(err) {\n if (err !== null && err !== undefined) {\n var message = 'ifError got unwanted exception: ';\n\n if (_typeof(err) === 'object' && typeof err.message === 'string') {\n if (err.message.length === 0 && err.constructor) {\n message += err.constructor.name;\n } else {\n message += err.message;\n }\n } else {\n message += inspect(err);\n }\n\n var newErr = new AssertionError({\n actual: err,\n expected: null,\n operator: 'ifError',\n message: message,\n stackStartFn: ifError\n }); // Make sure we actually have a stack trace!\n\n var origStack = err.stack;\n\n if (typeof origStack === 'string') {\n // This will remove any duplicated frames from the error frames taken\n // from within `ifError` and add the original error frames to the newly\n // created ones.\n var tmp2 = origStack.split('\\n');\n tmp2.shift(); // Filter all frames existing in err.stack.\n\n var tmp1 = newErr.stack.split('\\n');\n\n for (var i = 0; i < tmp2.length; i++) {\n // Find the first occurrence of the frame.\n var pos = tmp1.indexOf(tmp2[i]);\n\n if (pos !== -1) {\n // Only keep new frames.\n tmp1 = tmp1.slice(0, pos);\n break;\n }\n }\n\n newErr.stack = \"\".concat(tmp1.join('\\n'), \"\\n\").concat(tmp2.join('\\n'));\n }\n\n throw newErr;\n }\n}; // Expose a strict only variant of assert\n\n\nfunction strict() {\n for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {\n args[_key6] = arguments[_key6];\n }\n\n innerOk.apply(void 0, [strict, args.length].concat(args));\n}\n\nassert.strict = objectAssign(strict, assert, {\n equal: assert.strictEqual,\n deepEqual: assert.deepStrictEqual,\n notEqual: assert.notStrictEqual,\n notDeepEqual: assert.notDeepStrictEqual\n});\nassert.strict.strict = assert.strict;","// Currently in sync with Node.js lib/internal/assert/assertion_error.js\n// https://github.com/nodejs/node/commit/0817840f775032169ddd70c85ac059f18ffcc81c\n'use strict';\n\nfunction _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }\n\nfunction _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if (\"value\" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }\n\nfunction _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _wrapNativeSuper(Class) { var _cache = typeof Map === \"function\" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== \"function\") { throw new TypeError(\"Super expression must either be null or a function\"); } if (typeof _cache !== \"undefined\") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }\n\nfunction isNativeReflectConstruct() { if (typeof Reflect === \"undefined\" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === \"function\") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }\n\nfunction _construct(Parent, args, Class) { if (isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }\n\nfunction _isNativeFunction(fn) { return Function.toString.call(fn).indexOf(\"[native code]\") !== -1; }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar _require = require('util/'),\n inspect = _require.inspect;\n\nvar _require2 = require('../errors'),\n ERR_INVALID_ARG_TYPE = _require2.codes.ERR_INVALID_ARG_TYPE; // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\n\n\nfunction endsWith(str, search, this_len) {\n if (this_len === undefined || this_len > str.length) {\n this_len = str.length;\n }\n\n return str.substring(this_len - search.length, this_len) === search;\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat\n\n\nfunction repeat(str, count) {\n count = Math.floor(count);\n if (str.length == 0 || count == 0) return '';\n var maxCount = str.length * count;\n count = Math.floor(Math.log(count) / Math.log(2));\n\n while (count) {\n str += str;\n count--;\n }\n\n str += str.substring(0, maxCount - str.length);\n return str;\n}\n\nvar blue = '';\nvar green = '';\nvar red = '';\nvar white = '';\nvar kReadableOperator = {\n deepStrictEqual: 'Expected values to be strictly deep-equal:',\n strictEqual: 'Expected values to be strictly equal:',\n strictEqualObject: 'Expected \"actual\" to be reference-equal to \"expected\":',\n deepEqual: 'Expected values to be loosely deep-equal:',\n equal: 'Expected values to be loosely equal:',\n notDeepStrictEqual: 'Expected \"actual\" not to be strictly deep-equal to:',\n notStrictEqual: 'Expected \"actual\" to be strictly unequal to:',\n notStrictEqualObject: 'Expected \"actual\" not to be reference-equal to \"expected\":',\n notDeepEqual: 'Expected \"actual\" not to be loosely deep-equal to:',\n notEqual: 'Expected \"actual\" to be loosely unequal to:',\n notIdentical: 'Values identical but not reference-equal:'\n}; // Comparing short primitives should just show === / !== instead of using the\n// diff.\n\nvar kMaxShortLength = 10;\n\nfunction copyError(source) {\n var keys = Object.keys(source);\n var target = Object.create(Object.getPrototypeOf(source));\n keys.forEach(function (key) {\n target[key] = source[key];\n });\n Object.defineProperty(target, 'message', {\n value: source.message\n });\n return target;\n}\n\nfunction inspectValue(val) {\n // The util.inspect default values could be changed. This makes sure the\n // error messages contain the necessary information nevertheless.\n return inspect(val, {\n compact: false,\n customInspect: false,\n depth: 1000,\n maxArrayLength: Infinity,\n // Assert compares only enumerable properties (with a few exceptions).\n showHidden: false,\n // Having a long line as error is better than wrapping the line for\n // comparison for now.\n // TODO(BridgeAR): `breakLength` should be limited as soon as soon as we\n // have meta information about the inspected properties (i.e., know where\n // in what line the property starts and ends).\n breakLength: Infinity,\n // Assert does not detect proxies currently.\n showProxy: false,\n sorted: true,\n // Inspect getters as we also check them when comparing entries.\n getters: true\n });\n}\n\nfunction createErrDiff(actual, expected, operator) {\n var other = '';\n var res = '';\n var lastPos = 0;\n var end = '';\n var skipped = false;\n var actualInspected = inspectValue(actual);\n var actualLines = actualInspected.split('\\n');\n var expectedLines = inspectValue(expected).split('\\n');\n var i = 0;\n var indicator = ''; // In case both values are objects explicitly mark them as not reference equal\n // for the `strictEqual` operator.\n\n if (operator === 'strictEqual' && _typeof(actual) === 'object' && _typeof(expected) === 'object' && actual !== null && expected !== null) {\n operator = 'strictEqualObject';\n } // If \"actual\" and \"expected\" fit on a single line and they are not strictly\n // equal, check further special handling.\n\n\n if (actualLines.length === 1 && expectedLines.length === 1 && actualLines[0] !== expectedLines[0]) {\n var inputLength = actualLines[0].length + expectedLines[0].length; // If the character length of \"actual\" and \"expected\" together is less than\n // kMaxShortLength and if neither is an object and at least one of them is\n // not `zero`, use the strict equal comparison to visualize the output.\n\n if (inputLength <= kMaxShortLength) {\n if ((_typeof(actual) !== 'object' || actual === null) && (_typeof(expected) !== 'object' || expected === null) && (actual !== 0 || expected !== 0)) {\n // -0 === +0\n return \"\".concat(kReadableOperator[operator], \"\\n\\n\") + \"\".concat(actualLines[0], \" !== \").concat(expectedLines[0], \"\\n\");\n }\n } else if (operator !== 'strictEqualObject') {\n // If the stderr is a tty and the input length is lower than the current\n // columns per line, add a mismatch indicator below the output. If it is\n // not a tty, use a default value of 80 characters.\n var maxLength = process.stderr && process.stderr.isTTY ? process.stderr.columns : 80;\n\n if (inputLength < maxLength) {\n while (actualLines[0][i] === expectedLines[0][i]) {\n i++;\n } // Ignore the first characters.\n\n\n if (i > 2) {\n // Add position indicator for the first mismatch in case it is a\n // single line and the input length is less than the column length.\n indicator = \"\\n \".concat(repeat(' ', i), \"^\");\n i = 0;\n }\n }\n }\n } // Remove all ending lines that match (this optimizes the output for\n // readability by reducing the number of total changed lines).\n\n\n var a = actualLines[actualLines.length - 1];\n var b = expectedLines[expectedLines.length - 1];\n\n while (a === b) {\n if (i++ < 2) {\n end = \"\\n \".concat(a).concat(end);\n } else {\n other = a;\n }\n\n actualLines.pop();\n expectedLines.pop();\n if (actualLines.length === 0 || expectedLines.length === 0) break;\n a = actualLines[actualLines.length - 1];\n b = expectedLines[expectedLines.length - 1];\n }\n\n var maxLines = Math.max(actualLines.length, expectedLines.length); // Strict equal with identical objects that are not identical by reference.\n // E.g., assert.deepStrictEqual({ a: Symbol() }, { a: Symbol() })\n\n if (maxLines === 0) {\n // We have to get the result again. The lines were all removed before.\n var _actualLines = actualInspected.split('\\n'); // Only remove lines in case it makes sense to collapse those.\n // TODO: Accept env to always show the full error.\n\n\n if (_actualLines.length > 30) {\n _actualLines[26] = \"\".concat(blue, \"...\").concat(white);\n\n while (_actualLines.length > 27) {\n _actualLines.pop();\n }\n }\n\n return \"\".concat(kReadableOperator.notIdentical, \"\\n\\n\").concat(_actualLines.join('\\n'), \"\\n\");\n }\n\n if (i > 3) {\n end = \"\\n\".concat(blue, \"...\").concat(white).concat(end);\n skipped = true;\n }\n\n if (other !== '') {\n end = \"\\n \".concat(other).concat(end);\n other = '';\n }\n\n var printedLines = 0;\n var msg = kReadableOperator[operator] + \"\\n\".concat(green, \"+ actual\").concat(white, \" \").concat(red, \"- expected\").concat(white);\n var skippedMsg = \" \".concat(blue, \"...\").concat(white, \" Lines skipped\");\n\n for (i = 0; i < maxLines; i++) {\n // Only extra expected lines exist\n var cur = i - lastPos;\n\n if (actualLines.length < i + 1) {\n // If the last diverging line is more than one line above and the\n // current line is at least line three, add some of the former lines and\n // also add dots to indicate skipped entries.\n if (cur > 1 && i > 2) {\n if (cur > 4) {\n res += \"\\n\".concat(blue, \"...\").concat(white);\n skipped = true;\n } else if (cur > 3) {\n res += \"\\n \".concat(expectedLines[i - 2]);\n printedLines++;\n }\n\n res += \"\\n \".concat(expectedLines[i - 1]);\n printedLines++;\n } // Mark the current line as the last diverging one.\n\n\n lastPos = i; // Add the expected line to the cache.\n\n other += \"\\n\".concat(red, \"-\").concat(white, \" \").concat(expectedLines[i]);\n printedLines++; // Only extra actual lines exist\n } else if (expectedLines.length < i + 1) {\n // If the last diverging line is more than one line above and the\n // current line is at least line three, add some of the former lines and\n // also add dots to indicate skipped entries.\n if (cur > 1 && i > 2) {\n if (cur > 4) {\n res += \"\\n\".concat(blue, \"...\").concat(white);\n skipped = true;\n } else if (cur > 3) {\n res += \"\\n \".concat(actualLines[i - 2]);\n printedLines++;\n }\n\n res += \"\\n \".concat(actualLines[i - 1]);\n printedLines++;\n } // Mark the current line as the last diverging one.\n\n\n lastPos = i; // Add the actual line to the result.\n\n res += \"\\n\".concat(green, \"+\").concat(white, \" \").concat(actualLines[i]);\n printedLines++; // Lines diverge\n } else {\n var expectedLine = expectedLines[i];\n var actualLine = actualLines[i]; // If the lines diverge, specifically check for lines that only diverge by\n // a trailing comma. In that case it is actually identical and we should\n // mark it as such.\n\n var divergingLines = actualLine !== expectedLine && (!endsWith(actualLine, ',') || actualLine.slice(0, -1) !== expectedLine); // If the expected line has a trailing comma but is otherwise identical,\n // add a comma at the end of the actual line. Otherwise the output could\n // look weird as in:\n //\n // [\n // 1 // No comma at the end!\n // + 2\n // ]\n //\n\n if (divergingLines && endsWith(expectedLine, ',') && expectedLine.slice(0, -1) === actualLine) {\n divergingLines = false;\n actualLine += ',';\n }\n\n if (divergingLines) {\n // If the last diverging line is more than one line above and the\n // current line is at least line three, add some of the former lines and\n // also add dots to indicate skipped entries.\n if (cur > 1 && i > 2) {\n if (cur > 4) {\n res += \"\\n\".concat(blue, \"...\").concat(white);\n skipped = true;\n } else if (cur > 3) {\n res += \"\\n \".concat(actualLines[i - 2]);\n printedLines++;\n }\n\n res += \"\\n \".concat(actualLines[i - 1]);\n printedLines++;\n } // Mark the current line as the last diverging one.\n\n\n lastPos = i; // Add the actual line to the result and cache the expected diverging\n // line so consecutive diverging lines show up as +++--- and not +-+-+-.\n\n res += \"\\n\".concat(green, \"+\").concat(white, \" \").concat(actualLine);\n other += \"\\n\".concat(red, \"-\").concat(white, \" \").concat(expectedLine);\n printedLines += 2; // Lines are identical\n } else {\n // Add all cached information to the result before adding other things\n // and reset the cache.\n res += other;\n other = ''; // If the last diverging line is exactly one line above or if it is the\n // very first line, add the line to the result.\n\n if (cur === 1 || i === 0) {\n res += \"\\n \".concat(actualLine);\n printedLines++;\n }\n }\n } // Inspected object to big (Show ~20 rows max)\n\n\n if (printedLines > 20 && i < maxLines - 2) {\n return \"\".concat(msg).concat(skippedMsg, \"\\n\").concat(res, \"\\n\").concat(blue, \"...\").concat(white).concat(other, \"\\n\") + \"\".concat(blue, \"...\").concat(white);\n }\n }\n\n return \"\".concat(msg).concat(skipped ? skippedMsg : '', \"\\n\").concat(res).concat(other).concat(end).concat(indicator);\n}\n\nvar AssertionError =\n/*#__PURE__*/\nfunction (_Error) {\n _inherits(AssertionError, _Error);\n\n function AssertionError(options) {\n var _this;\n\n _classCallCheck(this, AssertionError);\n\n if (_typeof(options) !== 'object' || options === null) {\n throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);\n }\n\n var message = options.message,\n operator = options.operator,\n stackStartFn = options.stackStartFn;\n var actual = options.actual,\n expected = options.expected;\n var limit = Error.stackTraceLimit;\n Error.stackTraceLimit = 0;\n\n if (message != null) {\n _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, String(message)));\n } else {\n if (process.stderr && process.stderr.isTTY) {\n // Reset on each call to make sure we handle dynamically set environment\n // variables correct.\n if (process.stderr && process.stderr.getColorDepth && process.stderr.getColorDepth() !== 1) {\n blue = \"\\x1B[34m\";\n green = \"\\x1B[32m\";\n white = \"\\x1B[39m\";\n red = \"\\x1B[31m\";\n } else {\n blue = '';\n green = '';\n white = '';\n red = '';\n }\n } // Prevent the error stack from being visible by duplicating the error\n // in a very close way to the original in case both sides are actually\n // instances of Error.\n\n\n if (_typeof(actual) === 'object' && actual !== null && _typeof(expected) === 'object' && expected !== null && 'stack' in actual && actual instanceof Error && 'stack' in expected && expected instanceof Error) {\n actual = copyError(actual);\n expected = copyError(expected);\n }\n\n if (operator === 'deepStrictEqual' || operator === 'strictEqual') {\n _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, createErrDiff(actual, expected, operator)));\n } else if (operator === 'notDeepStrictEqual' || operator === 'notStrictEqual') {\n // In case the objects are equal but the operator requires unequal, show\n // the first object and say A equals B\n var base = kReadableOperator[operator];\n var res = inspectValue(actual).split('\\n'); // In case \"actual\" is an object, it should not be reference equal.\n\n if (operator === 'notStrictEqual' && _typeof(actual) === 'object' && actual !== null) {\n base = kReadableOperator.notStrictEqualObject;\n } // Only remove lines in case it makes sense to collapse those.\n // TODO: Accept env to always show the full error.\n\n\n if (res.length > 30) {\n res[26] = \"\".concat(blue, \"...\").concat(white);\n\n while (res.length > 27) {\n res.pop();\n }\n } // Only print a single input.\n\n\n if (res.length === 1) {\n _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, \"\".concat(base, \" \").concat(res[0])));\n } else {\n _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, \"\".concat(base, \"\\n\\n\").concat(res.join('\\n'), \"\\n\")));\n }\n } else {\n var _res = inspectValue(actual);\n\n var other = '';\n var knownOperators = kReadableOperator[operator];\n\n if (operator === 'notDeepEqual' || operator === 'notEqual') {\n _res = \"\".concat(kReadableOperator[operator], \"\\n\\n\").concat(_res);\n\n if (_res.length > 1024) {\n _res = \"\".concat(_res.slice(0, 1021), \"...\");\n }\n } else {\n other = \"\".concat(inspectValue(expected));\n\n if (_res.length > 512) {\n _res = \"\".concat(_res.slice(0, 509), \"...\");\n }\n\n if (other.length > 512) {\n other = \"\".concat(other.slice(0, 509), \"...\");\n }\n\n if (operator === 'deepEqual' || operator === 'equal') {\n _res = \"\".concat(knownOperators, \"\\n\\n\").concat(_res, \"\\n\\nshould equal\\n\\n\");\n } else {\n other = \" \".concat(operator, \" \").concat(other);\n }\n }\n\n _this = _possibleConstructorReturn(this, _getPrototypeOf(AssertionError).call(this, \"\".concat(_res).concat(other)));\n }\n }\n\n Error.stackTraceLimit = limit;\n _this.generatedMessage = !message;\n Object.defineProperty(_assertThisInitialized(_this), 'name', {\n value: 'AssertionError [ERR_ASSERTION]',\n enumerable: false,\n writable: true,\n configurable: true\n });\n _this.code = 'ERR_ASSERTION';\n _this.actual = actual;\n _this.expected = expected;\n _this.operator = operator;\n\n if (Error.captureStackTrace) {\n // eslint-disable-next-line no-restricted-syntax\n Error.captureStackTrace(_assertThisInitialized(_this), stackStartFn);\n } // Create error message including the error code in the name.\n\n\n _this.stack; // Reset the name.\n\n _this.name = 'AssertionError';\n return _possibleConstructorReturn(_this);\n }\n\n _createClass(AssertionError, [{\n key: \"toString\",\n value: function toString() {\n return \"\".concat(this.name, \" [\").concat(this.code, \"]: \").concat(this.message);\n }\n }, {\n key: inspect.custom,\n value: function value(recurseTimes, ctx) {\n // This limits the `actual` and `expected` property default inspection to\n // the minimum depth. Otherwise those values would be too verbose compared\n // to the actual error message which contains a combined view of these two\n // input values.\n return inspect(this, _objectSpread({}, ctx, {\n customInspect: false,\n depth: 0\n }));\n }\n }]);\n\n return AssertionError;\n}(_wrapNativeSuper(Error));\n\nmodule.exports = AssertionError;","// Currently in sync with Node.js lib/internal/errors.js\n// https://github.com/nodejs/node/commit/3b044962c48fe313905877a96b5d0894a5404f6f\n\n/* eslint node-core/documented-errors: \"error\" */\n\n/* eslint node-core/alphabetize-errors: \"error\" */\n\n/* eslint node-core/prefer-util-format-errors: \"error\" */\n'use strict'; // The whole point behind this internal module is to allow Node.js to no\n// longer be forced to treat every error message change as a semver-major\n// change. The NodeError classes here all expose a `code` property whose\n// value statically and permanently identifies the error. While the error\n// message may change, the code should not.\n\nfunction _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nfunction _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError(\"Cannot call a class as a function\"); } }\n\nfunction _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === \"object\" || typeof call === \"function\")) { return call; } return _assertThisInitialized(self); }\n\nfunction _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\"); } return self; }\n\nfunction _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }\n\nfunction _inherits(subClass, superClass) { if (typeof superClass !== \"function\" && superClass !== null) { throw new TypeError(\"Super expression must either be null or a function\"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }\n\nfunction _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }\n\nvar codes = {}; // Lazy loaded\n\nvar assert;\nvar util;\n\nfunction createErrorType(code, message, Base) {\n if (!Base) {\n Base = Error;\n }\n\n function getMessage(arg1, arg2, arg3) {\n if (typeof message === 'string') {\n return message;\n } else {\n return message(arg1, arg2, arg3);\n }\n }\n\n var NodeError =\n /*#__PURE__*/\n function (_Base) {\n _inherits(NodeError, _Base);\n\n function NodeError(arg1, arg2, arg3) {\n var _this;\n\n _classCallCheck(this, NodeError);\n\n _this = _possibleConstructorReturn(this, _getPrototypeOf(NodeError).call(this, getMessage(arg1, arg2, arg3)));\n _this.code = code;\n return _this;\n }\n\n return NodeError;\n }(Base);\n\n codes[code] = NodeError;\n} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js\n\n\nfunction oneOf(expected, thing) {\n if (Array.isArray(expected)) {\n var len = expected.length;\n expected = expected.map(function (i) {\n return String(i);\n });\n\n if (len > 2) {\n return \"one of \".concat(thing, \" \").concat(expected.slice(0, len - 1).join(', '), \", or \") + expected[len - 1];\n } else if (len === 2) {\n return \"one of \".concat(thing, \" \").concat(expected[0], \" or \").concat(expected[1]);\n } else {\n return \"of \".concat(thing, \" \").concat(expected[0]);\n }\n } else {\n return \"of \".concat(thing, \" \").concat(String(expected));\n }\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith\n\n\nfunction startsWith(str, search, pos) {\n return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith\n\n\nfunction endsWith(str, search, this_len) {\n if (this_len === undefined || this_len > str.length) {\n this_len = str.length;\n }\n\n return str.substring(this_len - search.length, this_len) === search;\n} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes\n\n\nfunction includes(str, search, start) {\n if (typeof start !== 'number') {\n start = 0;\n }\n\n if (start + search.length > str.length) {\n return false;\n } else {\n return str.indexOf(search, start) !== -1;\n }\n}\n\ncreateErrorType('ERR_AMBIGUOUS_ARGUMENT', 'The \"%s\" argument is ambiguous. %s', TypeError);\ncreateErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {\n if (assert === undefined) assert = require('../assert');\n assert(typeof name === 'string', \"'name' must be a string\"); // determiner: 'must be' or 'must not be'\n\n var determiner;\n\n if (typeof expected === 'string' && startsWith(expected, 'not ')) {\n determiner = 'must not be';\n expected = expected.replace(/^not /, '');\n } else {\n determiner = 'must be';\n }\n\n var msg;\n\n if (endsWith(name, ' argument')) {\n // For cases like 'first argument'\n msg = \"The \".concat(name, \" \").concat(determiner, \" \").concat(oneOf(expected, 'type'));\n } else {\n var type = includes(name, '.') ? 'property' : 'argument';\n msg = \"The \\\"\".concat(name, \"\\\" \").concat(type, \" \").concat(determiner, \" \").concat(oneOf(expected, 'type'));\n } // TODO(BridgeAR): Improve the output by showing `null` and similar.\n\n\n msg += \". Received type \".concat(_typeof(actual));\n return msg;\n}, TypeError);\ncreateErrorType('ERR_INVALID_ARG_VALUE', function (name, value) {\n var reason = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'is invalid';\n if (util === undefined) util = require('util/');\n var inspected = util.inspect(value);\n\n if (inspected.length > 128) {\n inspected = \"\".concat(inspected.slice(0, 128), \"...\");\n }\n\n return \"The argument '\".concat(name, \"' \").concat(reason, \". Received \").concat(inspected);\n}, TypeError, RangeError);\ncreateErrorType('ERR_INVALID_RETURN_VALUE', function (input, name, value) {\n var type;\n\n if (value && value.constructor && value.constructor.name) {\n type = \"instance of \".concat(value.constructor.name);\n } else {\n type = \"type \".concat(_typeof(value));\n }\n\n return \"Expected \".concat(input, \" to be returned from the \\\"\").concat(name, \"\\\"\") + \" function but got \".concat(type, \".\");\n}, TypeError);\ncreateErrorType('ERR_MISSING_ARGS', function () {\n for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n if (assert === undefined) assert = require('../assert');\n assert(args.length > 0, 'At least one arg needs to be specified');\n var msg = 'The ';\n var len = args.length;\n args = args.map(function (a) {\n return \"\\\"\".concat(a, \"\\\"\");\n });\n\n switch (len) {\n case 1:\n msg += \"\".concat(args[0], \" argument\");\n break;\n\n case 2:\n msg += \"\".concat(args[0], \" and \").concat(args[1], \" arguments\");\n break;\n\n default:\n msg += args.slice(0, len - 1).join(', ');\n msg += \", and \".concat(args[len - 1], \" arguments\");\n break;\n }\n\n return \"\".concat(msg, \" must be specified\");\n}, TypeError);\nmodule.exports.codes = codes;","// Currently in sync with Node.js lib/internal/util/comparisons.js\n// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9\n'use strict';\n\nfunction _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }\n\nfunction _nonIterableRest() { throw new TypeError(\"Invalid attempt to destructure non-iterable instance\"); }\n\nfunction _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i[\"return\"] != null) _i[\"return\"](); } finally { if (_d) throw _e; } } return _arr; }\n\nfunction _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }\n\nfunction _typeof(obj) { if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\nvar regexFlagsSupported = /a/g.flags !== undefined;\n\nvar arrayFromSet = function arrayFromSet(set) {\n var array = [];\n set.forEach(function (value) {\n return array.push(value);\n });\n return array;\n};\n\nvar arrayFromMap = function arrayFromMap(map) {\n var array = [];\n map.forEach(function (value, key) {\n return array.push([key, value]);\n });\n return array;\n};\n\nvar objectIs = Object.is ? Object.is : require('object-is');\nvar objectGetOwnPropertySymbols = Object.getOwnPropertySymbols ? Object.getOwnPropertySymbols : function () {\n return [];\n};\nvar numberIsNaN = Number.isNaN ? Number.isNaN : require('is-nan');\n\nfunction uncurryThis(f) {\n return f.call.bind(f);\n}\n\nvar hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty);\nvar propertyIsEnumerable = uncurryThis(Object.prototype.propertyIsEnumerable);\nvar objectToString = uncurryThis(Object.prototype.toString);\n\nvar _require$types = require('util/').types,\n isAnyArrayBuffer = _require$types.isAnyArrayBuffer,\n isArrayBufferView = _require$types.isArrayBufferView,\n isDate = _require$types.isDate,\n isMap = _require$types.isMap,\n isRegExp = _require$types.isRegExp,\n isSet = _require$types.isSet,\n isNativeError = _require$types.isNativeError,\n isBoxedPrimitive = _require$types.isBoxedPrimitive,\n isNumberObject = _require$types.isNumberObject,\n isStringObject = _require$types.isStringObject,\n isBooleanObject = _require$types.isBooleanObject,\n isBigIntObject = _require$types.isBigIntObject,\n isSymbolObject = _require$types.isSymbolObject,\n isFloat32Array = _require$types.isFloat32Array,\n isFloat64Array = _require$types.isFloat64Array;\n\nfunction isNonIndex(key) {\n if (key.length === 0 || key.length > 10) return true;\n\n for (var i = 0; i < key.length; i++) {\n var code = key.charCodeAt(i);\n if (code < 48 || code > 57) return true;\n } // The maximum size for an array is 2 ** 32 -1.\n\n\n return key.length === 10 && key >= Math.pow(2, 32);\n}\n\nfunction getOwnNonIndexProperties(value) {\n return Object.keys(value).filter(isNonIndex).concat(objectGetOwnPropertySymbols(value).filter(Object.prototype.propertyIsEnumerable.bind(value)));\n} // Taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js\n// original notice:\n\n/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n\n\nfunction compare(a, b) {\n if (a === b) {\n return 0;\n }\n\n var x = a.length;\n var y = b.length;\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i];\n y = b[i];\n break;\n }\n }\n\n if (x < y) {\n return -1;\n }\n\n if (y < x) {\n return 1;\n }\n\n return 0;\n}\n\nvar ONLY_ENUMERABLE = undefined;\nvar kStrict = true;\nvar kLoose = false;\nvar kNoIterator = 0;\nvar kIsArray = 1;\nvar kIsSet = 2;\nvar kIsMap = 3; // Check if they have the same source and flags\n\nfunction areSimilarRegExps(a, b) {\n return regexFlagsSupported ? a.source === b.source && a.flags === b.flags : RegExp.prototype.toString.call(a) === RegExp.prototype.toString.call(b);\n}\n\nfunction areSimilarFloatArrays(a, b) {\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n\n for (var offset = 0; offset < a.byteLength; offset++) {\n if (a[offset] !== b[offset]) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction areSimilarTypedArrays(a, b) {\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n\n return compare(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)) === 0;\n}\n\nfunction areEqualArrayBuffers(buf1, buf2) {\n return buf1.byteLength === buf2.byteLength && compare(new Uint8Array(buf1), new Uint8Array(buf2)) === 0;\n}\n\nfunction isEqualBoxedPrimitive(val1, val2) {\n if (isNumberObject(val1)) {\n return isNumberObject(val2) && objectIs(Number.prototype.valueOf.call(val1), Number.prototype.valueOf.call(val2));\n }\n\n if (isStringObject(val1)) {\n return isStringObject(val2) && String.prototype.valueOf.call(val1) === String.prototype.valueOf.call(val2);\n }\n\n if (isBooleanObject(val1)) {\n return isBooleanObject(val2) && Boolean.prototype.valueOf.call(val1) === Boolean.prototype.valueOf.call(val2);\n }\n\n if (isBigIntObject(val1)) {\n return isBigIntObject(val2) && BigInt.prototype.valueOf.call(val1) === BigInt.prototype.valueOf.call(val2);\n }\n\n return isSymbolObject(val2) && Symbol.prototype.valueOf.call(val1) === Symbol.prototype.valueOf.call(val2);\n} // Notes: Type tags are historical [[Class]] properties that can be set by\n// FunctionTemplate::SetClassName() in C++ or Symbol.toStringTag in JS\n// and retrieved using Object.prototype.toString.call(obj) in JS\n// See https://tc39.github.io/ecma262/#sec-object.prototype.tostring\n// for a list of tags pre-defined in the spec.\n// There are some unspecified tags in the wild too (e.g. typed array tags).\n// Since tags can be altered, they only serve fast failures\n//\n// Typed arrays and buffers are checked by comparing the content in their\n// underlying ArrayBuffer. This optimization requires that it's\n// reasonable to interpret their underlying memory in the same way,\n// which is checked by comparing their type tags.\n// (e.g. a Uint8Array and a Uint16Array with the same memory content\n// could still be different because they will be interpreted differently).\n//\n// For strict comparison, objects should have\n// a) The same built-in type tags\n// b) The same prototypes.\n\n\nfunction innerDeepEqual(val1, val2, strict, memos) {\n // All identical values are equivalent, as determined by ===.\n if (val1 === val2) {\n if (val1 !== 0) return true;\n return strict ? objectIs(val1, val2) : true;\n } // Check more closely if val1 and val2 are equal.\n\n\n if (strict) {\n if (_typeof(val1) !== 'object') {\n return typeof val1 === 'number' && numberIsNaN(val1) && numberIsNaN(val2);\n }\n\n if (_typeof(val2) !== 'object' || val1 === null || val2 === null) {\n return false;\n }\n\n if (Object.getPrototypeOf(val1) !== Object.getPrototypeOf(val2)) {\n return false;\n }\n } else {\n if (val1 === null || _typeof(val1) !== 'object') {\n if (val2 === null || _typeof(val2) !== 'object') {\n // eslint-disable-next-line eqeqeq\n return val1 == val2;\n }\n\n return false;\n }\n\n if (val2 === null || _typeof(val2) !== 'object') {\n return false;\n }\n }\n\n var val1Tag = objectToString(val1);\n var val2Tag = objectToString(val2);\n\n if (val1Tag !== val2Tag) {\n return false;\n }\n\n if (Array.isArray(val1)) {\n // Check for sparse arrays and general fast path\n if (val1.length !== val2.length) {\n return false;\n }\n\n var keys1 = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE);\n var keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE);\n\n if (keys1.length !== keys2.length) {\n return false;\n }\n\n return keyCheck(val1, val2, strict, memos, kIsArray, keys1);\n } // [browserify] This triggers on certain types in IE (Map/Set) so we don't\n // wan't to early return out of the rest of the checks. However we can check\n // if the second value is one of these values and the first isn't.\n\n\n if (val1Tag === '[object Object]') {\n // return keyCheck(val1, val2, strict, memos, kNoIterator);\n if (!isMap(val1) && isMap(val2) || !isSet(val1) && isSet(val2)) {\n return false;\n }\n }\n\n if (isDate(val1)) {\n if (!isDate(val2) || Date.prototype.getTime.call(val1) !== Date.prototype.getTime.call(val2)) {\n return false;\n }\n } else if (isRegExp(val1)) {\n if (!isRegExp(val2) || !areSimilarRegExps(val1, val2)) {\n return false;\n }\n } else if (isNativeError(val1) || val1 instanceof Error) {\n // Do not compare the stack as it might differ even though the error itself\n // is otherwise identical.\n if (val1.message !== val2.message || val1.name !== val2.name) {\n return false;\n }\n } else if (isArrayBufferView(val1)) {\n if (!strict && (isFloat32Array(val1) || isFloat64Array(val1))) {\n if (!areSimilarFloatArrays(val1, val2)) {\n return false;\n }\n } else if (!areSimilarTypedArrays(val1, val2)) {\n return false;\n } // Buffer.compare returns true, so val1.length === val2.length. If they both\n // only contain numeric keys, we don't need to exam further than checking\n // the symbols.\n\n\n var _keys = getOwnNonIndexProperties(val1, ONLY_ENUMERABLE);\n\n var _keys2 = getOwnNonIndexProperties(val2, ONLY_ENUMERABLE);\n\n if (_keys.length !== _keys2.length) {\n return false;\n }\n\n return keyCheck(val1, val2, strict, memos, kNoIterator, _keys);\n } else if (isSet(val1)) {\n if (!isSet(val2) || val1.size !== val2.size) {\n return false;\n }\n\n return keyCheck(val1, val2, strict, memos, kIsSet);\n } else if (isMap(val1)) {\n if (!isMap(val2) || val1.size !== val2.size) {\n return false;\n }\n\n return keyCheck(val1, val2, strict, memos, kIsMap);\n } else if (isAnyArrayBuffer(val1)) {\n if (!areEqualArrayBuffers(val1, val2)) {\n return false;\n }\n } else if (isBoxedPrimitive(val1) && !isEqualBoxedPrimitive(val1, val2)) {\n return false;\n }\n\n return keyCheck(val1, val2, strict, memos, kNoIterator);\n}\n\nfunction getEnumerables(val, keys) {\n return keys.filter(function (k) {\n return propertyIsEnumerable(val, k);\n });\n}\n\nfunction keyCheck(val1, val2, strict, memos, iterationType, aKeys) {\n // For all remaining Object pairs, including Array, objects and Maps,\n // equivalence is determined by having:\n // a) The same number of owned enumerable properties\n // b) The same set of keys/indexes (although not necessarily the same order)\n // c) Equivalent values for every corresponding key/index\n // d) For Sets and Maps, equal contents\n // Note: this accounts for both named and indexed properties on Arrays.\n if (arguments.length === 5) {\n aKeys = Object.keys(val1);\n var bKeys = Object.keys(val2); // The pair must have the same number of owned properties.\n\n if (aKeys.length !== bKeys.length) {\n return false;\n }\n } // Cheap key test\n\n\n var i = 0;\n\n for (; i < aKeys.length; i++) {\n if (!hasOwnProperty(val2, aKeys[i])) {\n return false;\n }\n }\n\n if (strict && arguments.length === 5) {\n var symbolKeysA = objectGetOwnPropertySymbols(val1);\n\n if (symbolKeysA.length !== 0) {\n var count = 0;\n\n for (i = 0; i < symbolKeysA.length; i++) {\n var key = symbolKeysA[i];\n\n if (propertyIsEnumerable(val1, key)) {\n if (!propertyIsEnumerable(val2, key)) {\n return false;\n }\n\n aKeys.push(key);\n count++;\n } else if (propertyIsEnumerable(val2, key)) {\n return false;\n }\n }\n\n var symbolKeysB = objectGetOwnPropertySymbols(val2);\n\n if (symbolKeysA.length !== symbolKeysB.length && getEnumerables(val2, symbolKeysB).length !== count) {\n return false;\n }\n } else {\n var _symbolKeysB = objectGetOwnPropertySymbols(val2);\n\n if (_symbolKeysB.length !== 0 && getEnumerables(val2, _symbolKeysB).length !== 0) {\n return false;\n }\n }\n }\n\n if (aKeys.length === 0 && (iterationType === kNoIterator || iterationType === kIsArray && val1.length === 0 || val1.size === 0)) {\n return true;\n } // Use memos to handle cycles.\n\n\n if (memos === undefined) {\n memos = {\n val1: new Map(),\n val2: new Map(),\n position: 0\n };\n } else {\n // We prevent up to two map.has(x) calls by directly retrieving the value\n // and checking for undefined. The map can only contain numbers, so it is\n // safe to check for undefined only.\n var val2MemoA = memos.val1.get(val1);\n\n if (val2MemoA !== undefined) {\n var val2MemoB = memos.val2.get(val2);\n\n if (val2MemoB !== undefined) {\n return val2MemoA === val2MemoB;\n }\n }\n\n memos.position++;\n }\n\n memos.val1.set(val1, memos.position);\n memos.val2.set(val2, memos.position);\n var areEq = objEquiv(val1, val2, strict, aKeys, memos, iterationType);\n memos.val1.delete(val1);\n memos.val2.delete(val2);\n return areEq;\n}\n\nfunction setHasEqualElement(set, val1, strict, memo) {\n // Go looking.\n var setValues = arrayFromSet(set);\n\n for (var i = 0; i < setValues.length; i++) {\n var val2 = setValues[i];\n\n if (innerDeepEqual(val1, val2, strict, memo)) {\n // Remove the matching element to make sure we do not check that again.\n set.delete(val2);\n return true;\n }\n }\n\n return false;\n} // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using\n// Sadly it is not possible to detect corresponding values properly in case the\n// type is a string, number, bigint or boolean. The reason is that those values\n// can match lots of different string values (e.g., 1n == '+00001').\n\n\nfunction findLooseMatchingPrimitives(prim) {\n switch (_typeof(prim)) {\n case 'undefined':\n return null;\n\n case 'object':\n // Only pass in null as object!\n return undefined;\n\n case 'symbol':\n return false;\n\n case 'string':\n prim = +prim;\n // Loose equal entries exist only if the string is possible to convert to\n // a regular number and not NaN.\n // Fall through\n\n case 'number':\n if (numberIsNaN(prim)) {\n return false;\n }\n\n }\n\n return true;\n}\n\nfunction setMightHaveLoosePrim(a, b, prim) {\n var altValue = findLooseMatchingPrimitives(prim);\n if (altValue != null) return altValue;\n return b.has(altValue) && !a.has(altValue);\n}\n\nfunction mapMightHaveLoosePrim(a, b, prim, item, memo) {\n var altValue = findLooseMatchingPrimitives(prim);\n\n if (altValue != null) {\n return altValue;\n }\n\n var curB = b.get(altValue);\n\n if (curB === undefined && !b.has(altValue) || !innerDeepEqual(item, curB, false, memo)) {\n return false;\n }\n\n return !a.has(altValue) && innerDeepEqual(item, curB, false, memo);\n}\n\nfunction setEquiv(a, b, strict, memo) {\n // This is a lazily initiated Set of entries which have to be compared\n // pairwise.\n var set = null;\n var aValues = arrayFromSet(a);\n\n for (var i = 0; i < aValues.length; i++) {\n var val = aValues[i]; // Note: Checking for the objects first improves the performance for object\n // heavy sets but it is a minor slow down for primitives. As they are fast\n // to check this improves the worst case scenario instead.\n\n if (_typeof(val) === 'object' && val !== null) {\n if (set === null) {\n set = new Set();\n } // If the specified value doesn't exist in the second set its an not null\n // object (or non strict only: a not matching primitive) we'll need to go\n // hunting for something thats deep-(strict-)equal to it. To make this\n // O(n log n) complexity we have to copy these values in a new set first.\n\n\n set.add(val);\n } else if (!b.has(val)) {\n if (strict) return false; // Fast path to detect missing string, symbol, undefined and null values.\n\n if (!setMightHaveLoosePrim(a, b, val)) {\n return false;\n }\n\n if (set === null) {\n set = new Set();\n }\n\n set.add(val);\n }\n }\n\n if (set !== null) {\n var bValues = arrayFromSet(b);\n\n for (var _i = 0; _i < bValues.length; _i++) {\n var _val = bValues[_i]; // We have to check if a primitive value is already\n // matching and only if it's not, go hunting for it.\n\n if (_typeof(_val) === 'object' && _val !== null) {\n if (!setHasEqualElement(set, _val, strict, memo)) return false;\n } else if (!strict && !a.has(_val) && !setHasEqualElement(set, _val, strict, memo)) {\n return false;\n }\n }\n\n return set.size === 0;\n }\n\n return true;\n}\n\nfunction mapHasEqualEntry(set, map, key1, item1, strict, memo) {\n // To be able to handle cases like:\n // Map([[{}, 'a'], [{}, 'b']]) vs Map([[{}, 'b'], [{}, 'a']])\n // ... we need to consider *all* matching keys, not just the first we find.\n var setValues = arrayFromSet(set);\n\n for (var i = 0; i < setValues.length; i++) {\n var key2 = setValues[i];\n\n if (innerDeepEqual(key1, key2, strict, memo) && innerDeepEqual(item1, map.get(key2), strict, memo)) {\n set.delete(key2);\n return true;\n }\n }\n\n return false;\n}\n\nfunction mapEquiv(a, b, strict, memo) {\n var set = null;\n var aEntries = arrayFromMap(a);\n\n for (var i = 0; i < aEntries.length; i++) {\n var _aEntries$i = _slicedToArray(aEntries[i], 2),\n key = _aEntries$i[0],\n item1 = _aEntries$i[1];\n\n if (_typeof(key) === 'object' && key !== null) {\n if (set === null) {\n set = new Set();\n }\n\n set.add(key);\n } else {\n // By directly retrieving the value we prevent another b.has(key) check in\n // almost all possible cases.\n var item2 = b.get(key);\n\n if (item2 === undefined && !b.has(key) || !innerDeepEqual(item1, item2, strict, memo)) {\n if (strict) return false; // Fast path to detect missing string, symbol, undefined and null\n // keys.\n\n if (!mapMightHaveLoosePrim(a, b, key, item1, memo)) return false;\n\n if (set === null) {\n set = new Set();\n }\n\n set.add(key);\n }\n }\n }\n\n if (set !== null) {\n var bEntries = arrayFromMap(b);\n\n for (var _i2 = 0; _i2 < bEntries.length; _i2++) {\n var _bEntries$_i = _slicedToArray(bEntries[_i2], 2),\n key = _bEntries$_i[0],\n item = _bEntries$_i[1];\n\n if (_typeof(key) === 'object' && key !== null) {\n if (!mapHasEqualEntry(set, a, key, item, strict, memo)) return false;\n } else if (!strict && (!a.has(key) || !innerDeepEqual(a.get(key), item, false, memo)) && !mapHasEqualEntry(set, a, key, item, false, memo)) {\n return false;\n }\n }\n\n return set.size === 0;\n }\n\n return true;\n}\n\nfunction objEquiv(a, b, strict, keys, memos, iterationType) {\n // Sets and maps don't have their entries accessible via normal object\n // properties.\n var i = 0;\n\n if (iterationType === kIsSet) {\n if (!setEquiv(a, b, strict, memos)) {\n return false;\n }\n } else if (iterationType === kIsMap) {\n if (!mapEquiv(a, b, strict, memos)) {\n return false;\n }\n } else if (iterationType === kIsArray) {\n for (; i < a.length; i++) {\n if (hasOwnProperty(a, i)) {\n if (!hasOwnProperty(b, i) || !innerDeepEqual(a[i], b[i], strict, memos)) {\n return false;\n }\n } else if (hasOwnProperty(b, i)) {\n return false;\n } else {\n // Array is sparse.\n var keysA = Object.keys(a);\n\n for (; i < keysA.length; i++) {\n var key = keysA[i];\n\n if (!hasOwnProperty(b, key) || !innerDeepEqual(a[key], b[key], strict, memos)) {\n return false;\n }\n }\n\n if (keysA.length !== Object.keys(b).length) {\n return false;\n }\n\n return true;\n }\n }\n } // The pair must have equivalent values for every corresponding key.\n // Possibly expensive deep test:\n\n\n for (i = 0; i < keys.length; i++) {\n var _key = keys[i];\n\n if (!innerDeepEqual(a[_key], b[_key], strict, memos)) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction isDeepEqual(val1, val2) {\n return innerDeepEqual(val1, val2, kLoose);\n}\n\nfunction isDeepStrictEqual(val1, val2) {\n return innerDeepEqual(val1, val2, kStrict);\n}\n\nmodule.exports = {\n isDeepEqual: isDeepEqual,\n isDeepStrictEqual: isDeepStrictEqual\n};","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar callBind = require('./');\n\nvar $indexOf = callBind(GetIntrinsic('String.prototype.indexOf'));\n\nmodule.exports = function callBoundIntrinsic(name, allowMissing) {\n\tvar intrinsic = GetIntrinsic(name, !!allowMissing);\n\tif (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {\n\t\treturn callBind(intrinsic);\n\t}\n\treturn intrinsic;\n};\n","'use strict';\n\nvar bind = require('function-bind');\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $apply = GetIntrinsic('%Function.prototype.apply%');\nvar $call = GetIntrinsic('%Function.prototype.call%');\nvar $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply);\n\nvar $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);\nvar $defineProperty = GetIntrinsic('%Object.defineProperty%', true);\nvar $max = GetIntrinsic('%Math.max%');\n\nif ($defineProperty) {\n\ttry {\n\t\t$defineProperty({}, 'a', { value: 1 });\n\t} catch (e) {\n\t\t// IE 8 has a broken defineProperty\n\t\t$defineProperty = null;\n\t}\n}\n\nmodule.exports = function callBind(originalFunction) {\n\tvar func = $reflectApply(bind, $call, arguments);\n\tif ($gOPD && $defineProperty) {\n\t\tvar desc = $gOPD(func, 'length');\n\t\tif (desc.configurable) {\n\t\t\t// original length, plus the receiver, minus any additional arguments (after the receiver)\n\t\t\t$defineProperty(\n\t\t\t\tfunc,\n\t\t\t\t'length',\n\t\t\t\t{ value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) }\n\t\t\t);\n\t\t}\n\t}\n\treturn func;\n};\n\nvar applyBind = function applyBind() {\n\treturn $reflectApply(bind, $apply, arguments);\n};\n\nif ($defineProperty) {\n\t$defineProperty(module.exports, 'apply', { value: applyBind });\n} else {\n\tmodule.exports.apply = applyBind;\n}\n","'use strict';\n\nvar keys = require('object-keys');\nvar hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';\n\nvar toStr = Object.prototype.toString;\nvar concat = Array.prototype.concat;\nvar origDefineProperty = Object.defineProperty;\n\nvar isFunction = function (fn) {\n\treturn typeof fn === 'function' && toStr.call(fn) === '[object Function]';\n};\n\nvar hasPropertyDescriptors = require('has-property-descriptors')();\n\nvar supportsDescriptors = origDefineProperty && hasPropertyDescriptors;\n\nvar defineProperty = function (object, name, value, predicate) {\n\tif (name in object && (!isFunction(predicate) || !predicate())) {\n\t\treturn;\n\t}\n\tif (supportsDescriptors) {\n\t\torigDefineProperty(object, name, {\n\t\t\tconfigurable: true,\n\t\t\tenumerable: false,\n\t\t\tvalue: value,\n\t\t\twritable: true\n\t\t});\n\t} else {\n\t\tobject[name] = value; // eslint-disable-line no-param-reassign\n\t}\n};\n\nvar defineProperties = function (object, map) {\n\tvar predicates = arguments.length > 2 ? arguments[2] : {};\n\tvar props = keys(map);\n\tif (hasSymbols) {\n\t\tprops = concat.call(props, Object.getOwnPropertySymbols(map));\n\t}\n\tfor (var i = 0; i < props.length; i += 1) {\n\t\tdefineProperty(object, props[i], map[props[i]], predicates[props[i]]);\n\t}\n};\n\ndefineProperties.supportsDescriptors = !!supportsDescriptors;\n\nmodule.exports = defineProperties;\n","/**\n * Code refactored from Mozilla Developer Network:\n * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\n */\n\n'use strict';\n\nfunction assign(target, firstSource) {\n if (target === undefined || target === null) {\n throw new TypeError('Cannot convert first argument to object');\n }\n\n var to = Object(target);\n for (var i = 1; i < arguments.length; i++) {\n var nextSource = arguments[i];\n if (nextSource === undefined || nextSource === null) {\n continue;\n }\n\n var keysArray = Object.keys(Object(nextSource));\n for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {\n var nextKey = keysArray[nextIndex];\n var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);\n if (desc !== undefined && desc.enumerable) {\n to[nextKey] = nextSource[nextKey];\n }\n }\n }\n return to;\n}\n\nfunction polyfill() {\n if (!Object.assign) {\n Object.defineProperty(Object, 'assign', {\n enumerable: false,\n configurable: true,\n writable: true,\n value: assign\n });\n }\n}\n\nmodule.exports = {\n assign: assign,\n polyfill: polyfill\n};\n","\nvar hasOwn = Object.prototype.hasOwnProperty;\nvar toString = Object.prototype.toString;\n\nmodule.exports = function forEach (obj, fn, ctx) {\n if (toString.call(fn) !== '[object Function]') {\n throw new TypeError('iterator must be a function');\n }\n var l = obj.length;\n if (l === +l) {\n for (var i = 0; i < l; i++) {\n fn.call(ctx, obj[i], i, obj);\n }\n } else {\n for (var k in obj) {\n if (hasOwn.call(obj, k)) {\n fn.call(ctx, obj[k], k, obj);\n }\n }\n }\n};\n\n","'use strict';\n\n/* eslint no-invalid-this: 1 */\n\nvar ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';\nvar slice = Array.prototype.slice;\nvar toStr = Object.prototype.toString;\nvar funcType = '[object Function]';\n\nmodule.exports = function bind(that) {\n var target = this;\n if (typeof target !== 'function' || toStr.call(target) !== funcType) {\n throw new TypeError(ERROR_MESSAGE + target);\n }\n var args = slice.call(arguments, 1);\n\n var bound;\n var binder = function () {\n if (this instanceof bound) {\n var result = target.apply(\n this,\n args.concat(slice.call(arguments))\n );\n if (Object(result) === result) {\n return result;\n }\n return this;\n } else {\n return target.apply(\n that,\n args.concat(slice.call(arguments))\n );\n }\n };\n\n var boundLength = Math.max(0, target.length - args.length);\n var boundArgs = [];\n for (var i = 0; i < boundLength; i++) {\n boundArgs.push('$' + i);\n }\n\n bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);\n\n if (target.prototype) {\n var Empty = function Empty() {};\n Empty.prototype = target.prototype;\n bound.prototype = new Empty();\n Empty.prototype = null;\n }\n\n return bound;\n};\n","'use strict';\n\nvar implementation = require('./implementation');\n\nmodule.exports = Function.prototype.bind || implementation;\n","'use strict';\n\nvar undefined;\n\nvar $SyntaxError = SyntaxError;\nvar $Function = Function;\nvar $TypeError = TypeError;\n\n// eslint-disable-next-line consistent-return\nvar getEvalledConstructor = function (expressionSyntax) {\n\ttry {\n\t\treturn $Function('\"use strict\"; return (' + expressionSyntax + ').constructor;')();\n\t} catch (e) {}\n};\n\nvar $gOPD = Object.getOwnPropertyDescriptor;\nif ($gOPD) {\n\ttry {\n\t\t$gOPD({}, '');\n\t} catch (e) {\n\t\t$gOPD = null; // this is IE 8, which has a broken gOPD\n\t}\n}\n\nvar throwTypeError = function () {\n\tthrow new $TypeError();\n};\nvar ThrowTypeError = $gOPD\n\t? (function () {\n\t\ttry {\n\t\t\t// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties\n\t\t\targuments.callee; // IE 8 does not throw here\n\t\t\treturn throwTypeError;\n\t\t} catch (calleeThrows) {\n\t\t\ttry {\n\t\t\t\t// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')\n\t\t\t\treturn $gOPD(arguments, 'callee').get;\n\t\t\t} catch (gOPDthrows) {\n\t\t\t\treturn throwTypeError;\n\t\t\t}\n\t\t}\n\t}())\n\t: throwTypeError;\n\nvar hasSymbols = require('has-symbols')();\n\nvar getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto\n\nvar needsEval = {};\n\nvar TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);\n\nvar INTRINSICS = {\n\t'%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError,\n\t'%Array%': Array,\n\t'%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,\n\t'%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,\n\t'%AsyncFromSyncIteratorPrototype%': undefined,\n\t'%AsyncFunction%': needsEval,\n\t'%AsyncGenerator%': needsEval,\n\t'%AsyncGeneratorFunction%': needsEval,\n\t'%AsyncIteratorPrototype%': needsEval,\n\t'%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,\n\t'%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt,\n\t'%Boolean%': Boolean,\n\t'%DataView%': typeof DataView === 'undefined' ? undefined : DataView,\n\t'%Date%': Date,\n\t'%decodeURI%': decodeURI,\n\t'%decodeURIComponent%': decodeURIComponent,\n\t'%encodeURI%': encodeURI,\n\t'%encodeURIComponent%': encodeURIComponent,\n\t'%Error%': Error,\n\t'%eval%': eval, // eslint-disable-line no-eval\n\t'%EvalError%': EvalError,\n\t'%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,\n\t'%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,\n\t'%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry,\n\t'%Function%': $Function,\n\t'%GeneratorFunction%': needsEval,\n\t'%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,\n\t'%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,\n\t'%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,\n\t'%isFinite%': isFinite,\n\t'%isNaN%': isNaN,\n\t'%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,\n\t'%JSON%': typeof JSON === 'object' ? JSON : undefined,\n\t'%Map%': typeof Map === 'undefined' ? undefined : Map,\n\t'%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),\n\t'%Math%': Math,\n\t'%Number%': Number,\n\t'%Object%': Object,\n\t'%parseFloat%': parseFloat,\n\t'%parseInt%': parseInt,\n\t'%Promise%': typeof Promise === 'undefined' ? undefined : Promise,\n\t'%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,\n\t'%RangeError%': RangeError,\n\t'%ReferenceError%': ReferenceError,\n\t'%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,\n\t'%RegExp%': RegExp,\n\t'%Set%': typeof Set === 'undefined' ? undefined : Set,\n\t'%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),\n\t'%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,\n\t'%String%': String,\n\t'%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,\n\t'%Symbol%': hasSymbols ? Symbol : undefined,\n\t'%SyntaxError%': $SyntaxError,\n\t'%ThrowTypeError%': ThrowTypeError,\n\t'%TypedArray%': TypedArray,\n\t'%TypeError%': $TypeError,\n\t'%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,\n\t'%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,\n\t'%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,\n\t'%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,\n\t'%URIError%': URIError,\n\t'%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,\n\t'%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef,\n\t'%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet\n};\n\nvar doEval = function doEval(name) {\n\tvar value;\n\tif (name === '%AsyncFunction%') {\n\t\tvalue = getEvalledConstructor('async function () {}');\n\t} else if (name === '%GeneratorFunction%') {\n\t\tvalue = getEvalledConstructor('function* () {}');\n\t} else if (name === '%AsyncGeneratorFunction%') {\n\t\tvalue = getEvalledConstructor('async function* () {}');\n\t} else if (name === '%AsyncGenerator%') {\n\t\tvar fn = doEval('%AsyncGeneratorFunction%');\n\t\tif (fn) {\n\t\t\tvalue = fn.prototype;\n\t\t}\n\t} else if (name === '%AsyncIteratorPrototype%') {\n\t\tvar gen = doEval('%AsyncGenerator%');\n\t\tif (gen) {\n\t\t\tvalue = getProto(gen.prototype);\n\t\t}\n\t}\n\n\tINTRINSICS[name] = value;\n\n\treturn value;\n};\n\nvar LEGACY_ALIASES = {\n\t'%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],\n\t'%ArrayPrototype%': ['Array', 'prototype'],\n\t'%ArrayProto_entries%': ['Array', 'prototype', 'entries'],\n\t'%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],\n\t'%ArrayProto_keys%': ['Array', 'prototype', 'keys'],\n\t'%ArrayProto_values%': ['Array', 'prototype', 'values'],\n\t'%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],\n\t'%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],\n\t'%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],\n\t'%BooleanPrototype%': ['Boolean', 'prototype'],\n\t'%DataViewPrototype%': ['DataView', 'prototype'],\n\t'%DatePrototype%': ['Date', 'prototype'],\n\t'%ErrorPrototype%': ['Error', 'prototype'],\n\t'%EvalErrorPrototype%': ['EvalError', 'prototype'],\n\t'%Float32ArrayPrototype%': ['Float32Array', 'prototype'],\n\t'%Float64ArrayPrototype%': ['Float64Array', 'prototype'],\n\t'%FunctionPrototype%': ['Function', 'prototype'],\n\t'%Generator%': ['GeneratorFunction', 'prototype'],\n\t'%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],\n\t'%Int8ArrayPrototype%': ['Int8Array', 'prototype'],\n\t'%Int16ArrayPrototype%': ['Int16Array', 'prototype'],\n\t'%Int32ArrayPrototype%': ['Int32Array', 'prototype'],\n\t'%JSONParse%': ['JSON', 'parse'],\n\t'%JSONStringify%': ['JSON', 'stringify'],\n\t'%MapPrototype%': ['Map', 'prototype'],\n\t'%NumberPrototype%': ['Number', 'prototype'],\n\t'%ObjectPrototype%': ['Object', 'prototype'],\n\t'%ObjProto_toString%': ['Object', 'prototype', 'toString'],\n\t'%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],\n\t'%PromisePrototype%': ['Promise', 'prototype'],\n\t'%PromiseProto_then%': ['Promise', 'prototype', 'then'],\n\t'%Promise_all%': ['Promise', 'all'],\n\t'%Promise_reject%': ['Promise', 'reject'],\n\t'%Promise_resolve%': ['Promise', 'resolve'],\n\t'%RangeErrorPrototype%': ['RangeError', 'prototype'],\n\t'%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],\n\t'%RegExpPrototype%': ['RegExp', 'prototype'],\n\t'%SetPrototype%': ['Set', 'prototype'],\n\t'%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],\n\t'%StringPrototype%': ['String', 'prototype'],\n\t'%SymbolPrototype%': ['Symbol', 'prototype'],\n\t'%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],\n\t'%TypedArrayPrototype%': ['TypedArray', 'prototype'],\n\t'%TypeErrorPrototype%': ['TypeError', 'prototype'],\n\t'%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],\n\t'%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],\n\t'%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],\n\t'%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],\n\t'%URIErrorPrototype%': ['URIError', 'prototype'],\n\t'%WeakMapPrototype%': ['WeakMap', 'prototype'],\n\t'%WeakSetPrototype%': ['WeakSet', 'prototype']\n};\n\nvar bind = require('function-bind');\nvar hasOwn = require('has');\nvar $concat = bind.call(Function.call, Array.prototype.concat);\nvar $spliceApply = bind.call(Function.apply, Array.prototype.splice);\nvar $replace = bind.call(Function.call, String.prototype.replace);\nvar $strSlice = bind.call(Function.call, String.prototype.slice);\n\n/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */\nvar rePropName = /[^%.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|%$))/g;\nvar reEscapeChar = /\\\\(\\\\)?/g; /** Used to match backslashes in property paths. */\nvar stringToPath = function stringToPath(string) {\n\tvar first = $strSlice(string, 0, 1);\n\tvar last = $strSlice(string, -1);\n\tif (first === '%' && last !== '%') {\n\t\tthrow new $SyntaxError('invalid intrinsic syntax, expected closing `%`');\n\t} else if (last === '%' && first !== '%') {\n\t\tthrow new $SyntaxError('invalid intrinsic syntax, expected opening `%`');\n\t}\n\tvar result = [];\n\t$replace(string, rePropName, function (match, number, quote, subString) {\n\t\tresult[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;\n\t});\n\treturn result;\n};\n/* end adaptation */\n\nvar getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {\n\tvar intrinsicName = name;\n\tvar alias;\n\tif (hasOwn(LEGACY_ALIASES, intrinsicName)) {\n\t\talias = LEGACY_ALIASES[intrinsicName];\n\t\tintrinsicName = '%' + alias[0] + '%';\n\t}\n\n\tif (hasOwn(INTRINSICS, intrinsicName)) {\n\t\tvar value = INTRINSICS[intrinsicName];\n\t\tif (value === needsEval) {\n\t\t\tvalue = doEval(intrinsicName);\n\t\t}\n\t\tif (typeof value === 'undefined' && !allowMissing) {\n\t\t\tthrow new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');\n\t\t}\n\n\t\treturn {\n\t\t\talias: alias,\n\t\t\tname: intrinsicName,\n\t\t\tvalue: value\n\t\t};\n\t}\n\n\tthrow new $SyntaxError('intrinsic ' + name + ' does not exist!');\n};\n\nmodule.exports = function GetIntrinsic(name, allowMissing) {\n\tif (typeof name !== 'string' || name.length === 0) {\n\t\tthrow new $TypeError('intrinsic name must be a non-empty string');\n\t}\n\tif (arguments.length > 1 && typeof allowMissing !== 'boolean') {\n\t\tthrow new $TypeError('\"allowMissing\" argument must be a boolean');\n\t}\n\n\tvar parts = stringToPath(name);\n\tvar intrinsicBaseName = parts.length > 0 ? parts[0] : '';\n\n\tvar intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);\n\tvar intrinsicRealName = intrinsic.name;\n\tvar value = intrinsic.value;\n\tvar skipFurtherCaching = false;\n\n\tvar alias = intrinsic.alias;\n\tif (alias) {\n\t\tintrinsicBaseName = alias[0];\n\t\t$spliceApply(parts, $concat([0, 1], alias));\n\t}\n\n\tfor (var i = 1, isOwn = true; i < parts.length; i += 1) {\n\t\tvar part = parts[i];\n\t\tvar first = $strSlice(part, 0, 1);\n\t\tvar last = $strSlice(part, -1);\n\t\tif (\n\t\t\t(\n\t\t\t\t(first === '\"' || first === \"'\" || first === '`')\n\t\t\t\t|| (last === '\"' || last === \"'\" || last === '`')\n\t\t\t)\n\t\t\t&& first !== last\n\t\t) {\n\t\t\tthrow new $SyntaxError('property names with quotes must have matching quotes');\n\t\t}\n\t\tif (part === 'constructor' || !isOwn) {\n\t\t\tskipFurtherCaching = true;\n\t\t}\n\n\t\tintrinsicBaseName += '.' + part;\n\t\tintrinsicRealName = '%' + intrinsicBaseName + '%';\n\n\t\tif (hasOwn(INTRINSICS, intrinsicRealName)) {\n\t\t\tvalue = INTRINSICS[intrinsicRealName];\n\t\t} else if (value != null) {\n\t\t\tif (!(part in value)) {\n\t\t\t\tif (!allowMissing) {\n\t\t\t\t\tthrow new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');\n\t\t\t\t}\n\t\t\t\treturn void undefined;\n\t\t\t}\n\t\t\tif ($gOPD && (i + 1) >= parts.length) {\n\t\t\t\tvar desc = $gOPD(value, part);\n\t\t\t\tisOwn = !!desc;\n\n\t\t\t\t// By convention, when a data property is converted to an accessor\n\t\t\t\t// property to emulate a data property that does not suffer from\n\t\t\t\t// the override mistake, that accessor's getter is marked with\n\t\t\t\t// an `originalValue` property. Here, when we detect this, we\n\t\t\t\t// uphold the illusion by pretending to see that original data\n\t\t\t\t// property, i.e., returning the value rather than the getter\n\t\t\t\t// itself.\n\t\t\t\tif (isOwn && 'get' in desc && !('originalValue' in desc.get)) {\n\t\t\t\t\tvalue = desc.get;\n\t\t\t\t} else {\n\t\t\t\t\tvalue = value[part];\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tisOwn = hasOwn(value, part);\n\t\t\t\tvalue = value[part];\n\t\t\t}\n\n\t\t\tif (isOwn && !skipFurtherCaching) {\n\t\t\t\tINTRINSICS[intrinsicRealName] = value;\n\t\t\t}\n\t\t}\n\t}\n\treturn value;\n};\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $defineProperty = GetIntrinsic('%Object.defineProperty%', true);\n\nvar hasPropertyDescriptors = function hasPropertyDescriptors() {\n\tif ($defineProperty) {\n\t\ttry {\n\t\t\t$defineProperty({}, 'a', { value: 1 });\n\t\t\treturn true;\n\t\t} catch (e) {\n\t\t\t// IE 8 has a broken defineProperty\n\t\t\treturn false;\n\t\t}\n\t}\n\treturn false;\n};\n\nhasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() {\n\t// node v0.6 has a bug where array lengths can be Set but not Defined\n\tif (!hasPropertyDescriptors()) {\n\t\treturn null;\n\t}\n\ttry {\n\t\treturn $defineProperty([], 'length', { value: 1 }).length !== 1;\n\t} catch (e) {\n\t\t// In Firefox 4-22, defining length on an array throws an exception.\n\t\treturn true;\n\t}\n};\n\nmodule.exports = hasPropertyDescriptors;\n","'use strict';\n\nvar origSymbol = typeof Symbol !== 'undefined' && Symbol;\nvar hasSymbolSham = require('./shams');\n\nmodule.exports = function hasNativeSymbols() {\n\tif (typeof origSymbol !== 'function') { return false; }\n\tif (typeof Symbol !== 'function') { return false; }\n\tif (typeof origSymbol('foo') !== 'symbol') { return false; }\n\tif (typeof Symbol('bar') !== 'symbol') { return false; }\n\n\treturn hasSymbolSham();\n};\n","'use strict';\n\n/* eslint complexity: [2, 18], max-statements: [2, 33] */\nmodule.exports = function hasSymbols() {\n\tif (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }\n\tif (typeof Symbol.iterator === 'symbol') { return true; }\n\n\tvar obj = {};\n\tvar sym = Symbol('test');\n\tvar symObj = Object(sym);\n\tif (typeof sym === 'string') { return false; }\n\n\tif (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }\n\tif (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }\n\n\t// temp disabled per https://github.com/ljharb/object.assign/issues/17\n\t// if (sym instanceof Symbol) { return false; }\n\t// temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4\n\t// if (!(symObj instanceof Symbol)) { return false; }\n\n\t// if (typeof Symbol.prototype.toString !== 'function') { return false; }\n\t// if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }\n\n\tvar symVal = 42;\n\tobj[sym] = symVal;\n\tfor (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop\n\tif (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }\n\n\tif (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }\n\n\tvar syms = Object.getOwnPropertySymbols(obj);\n\tif (syms.length !== 1 || syms[0] !== sym) { return false; }\n\n\tif (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }\n\n\tif (typeof Object.getOwnPropertyDescriptor === 'function') {\n\t\tvar descriptor = Object.getOwnPropertyDescriptor(obj, sym);\n\t\tif (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }\n\t}\n\n\treturn true;\n};\n","'use strict';\n\nvar hasSymbols = require('has-symbols/shams');\n\nmodule.exports = function hasToStringTagShams() {\n\treturn hasSymbols() && !!Symbol.toStringTag;\n};\n","'use strict';\n\nvar bind = require('function-bind');\n\nmodule.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);\n","if (typeof Object.create === 'function') {\n // implementation from standard node.js 'util' module\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n })\n }\n };\n} else {\n // old school shim for old browsers\n module.exports = function inherits(ctor, superCtor) {\n if (superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n }\n}\n","'use strict';\n\nvar hasToStringTag = require('has-tostringtag/shams')();\nvar callBound = require('call-bind/callBound');\n\nvar $toString = callBound('Object.prototype.toString');\n\nvar isStandardArguments = function isArguments(value) {\n\tif (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) {\n\t\treturn false;\n\t}\n\treturn $toString(value) === '[object Arguments]';\n};\n\nvar isLegacyArguments = function isArguments(value) {\n\tif (isStandardArguments(value)) {\n\t\treturn true;\n\t}\n\treturn value !== null &&\n\t\ttypeof value === 'object' &&\n\t\ttypeof value.length === 'number' &&\n\t\tvalue.length >= 0 &&\n\t\t$toString(value) !== '[object Array]' &&\n\t\t$toString(value.callee) === '[object Function]';\n};\n\nvar supportsStandardArguments = (function () {\n\treturn isStandardArguments(arguments);\n}());\n\nisStandardArguments.isLegacyArguments = isLegacyArguments; // for tests\n\nmodule.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments;\n","'use strict';\n\nvar toStr = Object.prototype.toString;\nvar fnToStr = Function.prototype.toString;\nvar isFnRegex = /^\\s*(?:function)?\\*/;\nvar hasToStringTag = require('has-tostringtag/shams')();\nvar getProto = Object.getPrototypeOf;\nvar getGeneratorFunc = function () { // eslint-disable-line consistent-return\n\tif (!hasToStringTag) {\n\t\treturn false;\n\t}\n\ttry {\n\t\treturn Function('return function*() {}')();\n\t} catch (e) {\n\t}\n};\nvar GeneratorFunction;\n\nmodule.exports = function isGeneratorFunction(fn) {\n\tif (typeof fn !== 'function') {\n\t\treturn false;\n\t}\n\tif (isFnRegex.test(fnToStr.call(fn))) {\n\t\treturn true;\n\t}\n\tif (!hasToStringTag) {\n\t\tvar str = toStr.call(fn);\n\t\treturn str === '[object GeneratorFunction]';\n\t}\n\tif (!getProto) {\n\t\treturn false;\n\t}\n\tif (typeof GeneratorFunction === 'undefined') {\n\t\tvar generatorFunc = getGeneratorFunc();\n\t\tGeneratorFunction = generatorFunc ? getProto(generatorFunc) : false;\n\t}\n\treturn getProto(fn) === GeneratorFunction;\n};\n","'use strict';\n\n/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */\n\nmodule.exports = function isNaN(value) {\n\treturn value !== value;\n};\n","'use strict';\n\nvar callBind = require('call-bind');\nvar define = require('define-properties');\n\nvar implementation = require('./implementation');\nvar getPolyfill = require('./polyfill');\nvar shim = require('./shim');\n\nvar polyfill = callBind(getPolyfill(), Number);\n\n/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */\n\ndefine(polyfill, {\n\tgetPolyfill: getPolyfill,\n\timplementation: implementation,\n\tshim: shim\n});\n\nmodule.exports = polyfill;\n","'use strict';\n\nvar implementation = require('./implementation');\n\nmodule.exports = function getPolyfill() {\n\tif (Number.isNaN && Number.isNaN(NaN) && !Number.isNaN('a')) {\n\t\treturn Number.isNaN;\n\t}\n\treturn implementation;\n};\n","'use strict';\n\nvar define = require('define-properties');\nvar getPolyfill = require('./polyfill');\n\n/* http://www.ecma-international.org/ecma-262/6.0/#sec-number.isnan */\n\nmodule.exports = function shimNumberIsNaN() {\n\tvar polyfill = getPolyfill();\n\tdefine(Number, { isNaN: polyfill }, {\n\t\tisNaN: function testIsNaN() {\n\t\t\treturn Number.isNaN !== polyfill;\n\t\t}\n\t});\n\treturn polyfill;\n};\n","'use strict';\n\nvar forEach = require('foreach');\nvar availableTypedArrays = require('available-typed-arrays');\nvar callBound = require('call-bind/callBound');\n\nvar $toString = callBound('Object.prototype.toString');\nvar hasToStringTag = require('has-tostringtag/shams')();\n\nvar g = typeof globalThis === 'undefined' ? global : globalThis;\nvar typedArrays = availableTypedArrays();\n\nvar $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) {\n\tfor (var i = 0; i < array.length; i += 1) {\n\t\tif (array[i] === value) {\n\t\t\treturn i;\n\t\t}\n\t}\n\treturn -1;\n};\nvar $slice = callBound('String.prototype.slice');\nvar toStrTags = {};\nvar gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor');\nvar getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');\nif (hasToStringTag && gOPD && getPrototypeOf) {\n\tforEach(typedArrays, function (typedArray) {\n\t\tvar arr = new g[typedArray]();\n\t\tif (Symbol.toStringTag in arr) {\n\t\t\tvar proto = getPrototypeOf(arr);\n\t\t\tvar descriptor = gOPD(proto, Symbol.toStringTag);\n\t\t\tif (!descriptor) {\n\t\t\t\tvar superProto = getPrototypeOf(proto);\n\t\t\t\tdescriptor = gOPD(superProto, Symbol.toStringTag);\n\t\t\t}\n\t\t\ttoStrTags[typedArray] = descriptor.get;\n\t\t}\n\t});\n}\n\nvar tryTypedArrays = function tryAllTypedArrays(value) {\n\tvar anyTrue = false;\n\tforEach(toStrTags, function (getter, typedArray) {\n\t\tif (!anyTrue) {\n\t\t\ttry {\n\t\t\t\tanyTrue = getter.call(value) === typedArray;\n\t\t\t} catch (e) { /**/ }\n\t\t}\n\t});\n\treturn anyTrue;\n};\n\nmodule.exports = function isTypedArray(value) {\n\tif (!value || typeof value !== 'object') { return false; }\n\tif (!hasToStringTag || !(Symbol.toStringTag in value)) {\n\t\tvar tag = $slice($toString(value), 8, -1);\n\t\treturn $indexOf(typedArrays, tag) > -1;\n\t}\n\tif (!gOPD) { return false; }\n\treturn tryTypedArrays(value);\n};\n","'use strict';\n\nvar numberIsNaN = function (value) {\n\treturn value !== value;\n};\n\nmodule.exports = function is(a, b) {\n\tif (a === 0 && b === 0) {\n\t\treturn 1 / a === 1 / b;\n\t}\n\tif (a === b) {\n\t\treturn true;\n\t}\n\tif (numberIsNaN(a) && numberIsNaN(b)) {\n\t\treturn true;\n\t}\n\treturn false;\n};\n\n","'use strict';\n\nvar define = require('define-properties');\nvar callBind = require('call-bind');\n\nvar implementation = require('./implementation');\nvar getPolyfill = require('./polyfill');\nvar shim = require('./shim');\n\nvar polyfill = callBind(getPolyfill(), Object);\n\ndefine(polyfill, {\n\tgetPolyfill: getPolyfill,\n\timplementation: implementation,\n\tshim: shim\n});\n\nmodule.exports = polyfill;\n","'use strict';\n\nvar implementation = require('./implementation');\n\nmodule.exports = function getPolyfill() {\n\treturn typeof Object.is === 'function' ? Object.is : implementation;\n};\n","'use strict';\n\nvar getPolyfill = require('./polyfill');\nvar define = require('define-properties');\n\nmodule.exports = function shimObjectIs() {\n\tvar polyfill = getPolyfill();\n\tdefine(Object, { is: polyfill }, {\n\t\tis: function testObjectIs() {\n\t\t\treturn Object.is !== polyfill;\n\t\t}\n\t});\n\treturn polyfill;\n};\n","'use strict';\n\nvar keysShim;\nif (!Object.keys) {\n\t// modified from https://github.com/es-shims/es5-shim\n\tvar has = Object.prototype.hasOwnProperty;\n\tvar toStr = Object.prototype.toString;\n\tvar isArgs = require('./isArguments'); // eslint-disable-line global-require\n\tvar isEnumerable = Object.prototype.propertyIsEnumerable;\n\tvar hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');\n\tvar hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');\n\tvar dontEnums = [\n\t\t'toString',\n\t\t'toLocaleString',\n\t\t'valueOf',\n\t\t'hasOwnProperty',\n\t\t'isPrototypeOf',\n\t\t'propertyIsEnumerable',\n\t\t'constructor'\n\t];\n\tvar equalsConstructorPrototype = function (o) {\n\t\tvar ctor = o.constructor;\n\t\treturn ctor && ctor.prototype === o;\n\t};\n\tvar excludedKeys = {\n\t\t$applicationCache: true,\n\t\t$console: true,\n\t\t$external: true,\n\t\t$frame: true,\n\t\t$frameElement: true,\n\t\t$frames: true,\n\t\t$innerHeight: true,\n\t\t$innerWidth: true,\n\t\t$onmozfullscreenchange: true,\n\t\t$onmozfullscreenerror: true,\n\t\t$outerHeight: true,\n\t\t$outerWidth: true,\n\t\t$pageXOffset: true,\n\t\t$pageYOffset: true,\n\t\t$parent: true,\n\t\t$scrollLeft: true,\n\t\t$scrollTop: true,\n\t\t$scrollX: true,\n\t\t$scrollY: true,\n\t\t$self: true,\n\t\t$webkitIndexedDB: true,\n\t\t$webkitStorageInfo: true,\n\t\t$window: true\n\t};\n\tvar hasAutomationEqualityBug = (function () {\n\t\t/* global window */\n\t\tif (typeof window === 'undefined') { return false; }\n\t\tfor (var k in window) {\n\t\t\ttry {\n\t\t\t\tif (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tequalsConstructorPrototype(window[k]);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}());\n\tvar equalsConstructorPrototypeIfNotBuggy = function (o) {\n\t\t/* global window */\n\t\tif (typeof window === 'undefined' || !hasAutomationEqualityBug) {\n\t\t\treturn equalsConstructorPrototype(o);\n\t\t}\n\t\ttry {\n\t\t\treturn equalsConstructorPrototype(o);\n\t\t} catch (e) {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tkeysShim = function keys(object) {\n\t\tvar isObject = object !== null && typeof object === 'object';\n\t\tvar isFunction = toStr.call(object) === '[object Function]';\n\t\tvar isArguments = isArgs(object);\n\t\tvar isString = isObject && toStr.call(object) === '[object String]';\n\t\tvar theKeys = [];\n\n\t\tif (!isObject && !isFunction && !isArguments) {\n\t\t\tthrow new TypeError('Object.keys called on a non-object');\n\t\t}\n\n\t\tvar skipProto = hasProtoEnumBug && isFunction;\n\t\tif (isString && object.length > 0 && !has.call(object, 0)) {\n\t\t\tfor (var i = 0; i < object.length; ++i) {\n\t\t\t\ttheKeys.push(String(i));\n\t\t\t}\n\t\t}\n\n\t\tif (isArguments && object.length > 0) {\n\t\t\tfor (var j = 0; j < object.length; ++j) {\n\t\t\t\ttheKeys.push(String(j));\n\t\t\t}\n\t\t} else {\n\t\t\tfor (var name in object) {\n\t\t\t\tif (!(skipProto && name === 'prototype') && has.call(object, name)) {\n\t\t\t\t\ttheKeys.push(String(name));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (hasDontEnumBug) {\n\t\t\tvar skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);\n\n\t\t\tfor (var k = 0; k < dontEnums.length; ++k) {\n\t\t\t\tif (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {\n\t\t\t\t\ttheKeys.push(dontEnums[k]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn theKeys;\n\t};\n}\nmodule.exports = keysShim;\n","'use strict';\n\nvar slice = Array.prototype.slice;\nvar isArgs = require('./isArguments');\n\nvar origKeys = Object.keys;\nvar keysShim = origKeys ? function keys(o) { return origKeys(o); } : require('./implementation');\n\nvar originalKeys = Object.keys;\n\nkeysShim.shim = function shimObjectKeys() {\n\tif (Object.keys) {\n\t\tvar keysWorksWithArguments = (function () {\n\t\t\t// Safari 5.0 bug\n\t\t\tvar args = Object.keys(arguments);\n\t\t\treturn args && args.length === arguments.length;\n\t\t}(1, 2));\n\t\tif (!keysWorksWithArguments) {\n\t\t\tObject.keys = function keys(object) { // eslint-disable-line func-name-matching\n\t\t\t\tif (isArgs(object)) {\n\t\t\t\t\treturn originalKeys(slice.call(object));\n\t\t\t\t}\n\t\t\t\treturn originalKeys(object);\n\t\t\t};\n\t\t}\n\t} else {\n\t\tObject.keys = keysShim;\n\t}\n\treturn Object.keys || keysShim;\n};\n\nmodule.exports = keysShim;\n","'use strict';\n\nvar toStr = Object.prototype.toString;\n\nmodule.exports = function isArguments(value) {\n\tvar str = toStr.call(value);\n\tvar isArgs = str === '[object Arguments]';\n\tif (!isArgs) {\n\t\tisArgs = str !== '[object Array]' &&\n\t\t\tvalue !== null &&\n\t\t\ttypeof value === 'object' &&\n\t\t\ttypeof value.length === 'number' &&\n\t\t\tvalue.length >= 0 &&\n\t\t\ttoStr.call(value.callee) === '[object Function]';\n\t}\n\treturn isArgs;\n};\n","// shim for using process in browser\nvar process = module.exports = {};\n\n// cached from whatever global is present so that test runners that stub it\n// don't break things. But we need to wrap it in a try catch in case it is\n// wrapped in strict mode code which doesn't define any globals. It's inside a\n// function because try/catches deoptimize in certain engines.\n\nvar cachedSetTimeout;\nvar cachedClearTimeout;\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\n(function () {\n try {\n if (typeof setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n } else {\n cachedSetTimeout = defaultSetTimout;\n }\n } catch (e) {\n cachedSetTimeout = defaultSetTimout;\n }\n try {\n if (typeof clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n } else {\n cachedClearTimeout = defaultClearTimeout;\n }\n } catch (e) {\n cachedClearTimeout = defaultClearTimeout;\n }\n} ())\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\n\nprocess.nextTick = function (fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n};\n\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nprocess.title = 'browser';\nprocess.browser = true;\nprocess.env = {};\nprocess.argv = [];\nprocess.version = ''; // empty string to avoid regexp issues\nprocess.versions = {};\n\nfunction noop() {}\n\nprocess.on = noop;\nprocess.addListener = noop;\nprocess.once = noop;\nprocess.off = noop;\nprocess.removeListener = noop;\nprocess.removeAllListeners = noop;\nprocess.emit = noop;\nprocess.prependListener = noop;\nprocess.prependOnceListener = noop;\n\nprocess.listeners = function (name) { return [] }\n\nprocess.binding = function (name) {\n throw new Error('process.binding is not supported');\n};\n\nprocess.cwd = function () { return '/' };\nprocess.chdir = function (dir) {\n throw new Error('process.chdir is not supported');\n};\nprocess.umask = function() { return 0; };\n","module.exports = function isBuffer(arg) {\n return arg && typeof arg === 'object'\n && typeof arg.copy === 'function'\n && typeof arg.fill === 'function'\n && typeof arg.readUInt8 === 'function';\n}","// Currently in sync with Node.js lib/internal/util/types.js\n// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9\n\n'use strict';\n\nvar isArgumentsObject = require('is-arguments');\nvar isGeneratorFunction = require('is-generator-function');\nvar whichTypedArray = require('which-typed-array');\nvar isTypedArray = require('is-typed-array');\n\nfunction uncurryThis(f) {\n return f.call.bind(f);\n}\n\nvar BigIntSupported = typeof BigInt !== 'undefined';\nvar SymbolSupported = typeof Symbol !== 'undefined';\n\nvar ObjectToString = uncurryThis(Object.prototype.toString);\n\nvar numberValue = uncurryThis(Number.prototype.valueOf);\nvar stringValue = uncurryThis(String.prototype.valueOf);\nvar booleanValue = uncurryThis(Boolean.prototype.valueOf);\n\nif (BigIntSupported) {\n var bigIntValue = uncurryThis(BigInt.prototype.valueOf);\n}\n\nif (SymbolSupported) {\n var symbolValue = uncurryThis(Symbol.prototype.valueOf);\n}\n\nfunction checkBoxedPrimitive(value, prototypeValueOf) {\n if (typeof value !== 'object') {\n return false;\n }\n try {\n prototypeValueOf(value);\n return true;\n } catch(e) {\n return false;\n }\n}\n\nexports.isArgumentsObject = isArgumentsObject;\nexports.isGeneratorFunction = isGeneratorFunction;\nexports.isTypedArray = isTypedArray;\n\n// Taken from here and modified for better browser support\n// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js\nfunction isPromise(input) {\n\treturn (\n\t\t(\n\t\t\ttypeof Promise !== 'undefined' &&\n\t\t\tinput instanceof Promise\n\t\t) ||\n\t\t(\n\t\t\tinput !== null &&\n\t\t\ttypeof input === 'object' &&\n\t\t\ttypeof input.then === 'function' &&\n\t\t\ttypeof input.catch === 'function'\n\t\t)\n\t);\n}\nexports.isPromise = isPromise;\n\nfunction isArrayBufferView(value) {\n if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {\n return ArrayBuffer.isView(value);\n }\n\n return (\n isTypedArray(value) ||\n isDataView(value)\n );\n}\nexports.isArrayBufferView = isArrayBufferView;\n\n\nfunction isUint8Array(value) {\n return whichTypedArray(value) === 'Uint8Array';\n}\nexports.isUint8Array = isUint8Array;\n\nfunction isUint8ClampedArray(value) {\n return whichTypedArray(value) === 'Uint8ClampedArray';\n}\nexports.isUint8ClampedArray = isUint8ClampedArray;\n\nfunction isUint16Array(value) {\n return whichTypedArray(value) === 'Uint16Array';\n}\nexports.isUint16Array = isUint16Array;\n\nfunction isUint32Array(value) {\n return whichTypedArray(value) === 'Uint32Array';\n}\nexports.isUint32Array = isUint32Array;\n\nfunction isInt8Array(value) {\n return whichTypedArray(value) === 'Int8Array';\n}\nexports.isInt8Array = isInt8Array;\n\nfunction isInt16Array(value) {\n return whichTypedArray(value) === 'Int16Array';\n}\nexports.isInt16Array = isInt16Array;\n\nfunction isInt32Array(value) {\n return whichTypedArray(value) === 'Int32Array';\n}\nexports.isInt32Array = isInt32Array;\n\nfunction isFloat32Array(value) {\n return whichTypedArray(value) === 'Float32Array';\n}\nexports.isFloat32Array = isFloat32Array;\n\nfunction isFloat64Array(value) {\n return whichTypedArray(value) === 'Float64Array';\n}\nexports.isFloat64Array = isFloat64Array;\n\nfunction isBigInt64Array(value) {\n return whichTypedArray(value) === 'BigInt64Array';\n}\nexports.isBigInt64Array = isBigInt64Array;\n\nfunction isBigUint64Array(value) {\n return whichTypedArray(value) === 'BigUint64Array';\n}\nexports.isBigUint64Array = isBigUint64Array;\n\nfunction isMapToString(value) {\n return ObjectToString(value) === '[object Map]';\n}\nisMapToString.working = (\n typeof Map !== 'undefined' &&\n isMapToString(new Map())\n);\n\nfunction isMap(value) {\n if (typeof Map === 'undefined') {\n return false;\n }\n\n return isMapToString.working\n ? isMapToString(value)\n : value instanceof Map;\n}\nexports.isMap = isMap;\n\nfunction isSetToString(value) {\n return ObjectToString(value) === '[object Set]';\n}\nisSetToString.working = (\n typeof Set !== 'undefined' &&\n isSetToString(new Set())\n);\nfunction isSet(value) {\n if (typeof Set === 'undefined') {\n return false;\n }\n\n return isSetToString.working\n ? isSetToString(value)\n : value instanceof Set;\n}\nexports.isSet = isSet;\n\nfunction isWeakMapToString(value) {\n return ObjectToString(value) === '[object WeakMap]';\n}\nisWeakMapToString.working = (\n typeof WeakMap !== 'undefined' &&\n isWeakMapToString(new WeakMap())\n);\nfunction isWeakMap(value) {\n if (typeof WeakMap === 'undefined') {\n return false;\n }\n\n return isWeakMapToString.working\n ? isWeakMapToString(value)\n : value instanceof WeakMap;\n}\nexports.isWeakMap = isWeakMap;\n\nfunction isWeakSetToString(value) {\n return ObjectToString(value) === '[object WeakSet]';\n}\nisWeakSetToString.working = (\n typeof WeakSet !== 'undefined' &&\n isWeakSetToString(new WeakSet())\n);\nfunction isWeakSet(value) {\n return isWeakSetToString(value);\n}\nexports.isWeakSet = isWeakSet;\n\nfunction isArrayBufferToString(value) {\n return ObjectToString(value) === '[object ArrayBuffer]';\n}\nisArrayBufferToString.working = (\n typeof ArrayBuffer !== 'undefined' &&\n isArrayBufferToString(new ArrayBuffer())\n);\nfunction isArrayBuffer(value) {\n if (typeof ArrayBuffer === 'undefined') {\n return false;\n }\n\n return isArrayBufferToString.working\n ? isArrayBufferToString(value)\n : value instanceof ArrayBuffer;\n}\nexports.isArrayBuffer = isArrayBuffer;\n\nfunction isDataViewToString(value) {\n return ObjectToString(value) === '[object DataView]';\n}\nisDataViewToString.working = (\n typeof ArrayBuffer !== 'undefined' &&\n typeof DataView !== 'undefined' &&\n isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1))\n);\nfunction isDataView(value) {\n if (typeof DataView === 'undefined') {\n return false;\n }\n\n return isDataViewToString.working\n ? isDataViewToString(value)\n : value instanceof DataView;\n}\nexports.isDataView = isDataView;\n\n// Store a copy of SharedArrayBuffer in case it's deleted elsewhere\nvar SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined;\nfunction isSharedArrayBufferToString(value) {\n return ObjectToString(value) === '[object SharedArrayBuffer]';\n}\nfunction isSharedArrayBuffer(value) {\n if (typeof SharedArrayBufferCopy === 'undefined') {\n return false;\n }\n\n if (typeof isSharedArrayBufferToString.working === 'undefined') {\n isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy());\n }\n\n return isSharedArrayBufferToString.working\n ? isSharedArrayBufferToString(value)\n : value instanceof SharedArrayBufferCopy;\n}\nexports.isSharedArrayBuffer = isSharedArrayBuffer;\n\nfunction isAsyncFunction(value) {\n return ObjectToString(value) === '[object AsyncFunction]';\n}\nexports.isAsyncFunction = isAsyncFunction;\n\nfunction isMapIterator(value) {\n return ObjectToString(value) === '[object Map Iterator]';\n}\nexports.isMapIterator = isMapIterator;\n\nfunction isSetIterator(value) {\n return ObjectToString(value) === '[object Set Iterator]';\n}\nexports.isSetIterator = isSetIterator;\n\nfunction isGeneratorObject(value) {\n return ObjectToString(value) === '[object Generator]';\n}\nexports.isGeneratorObject = isGeneratorObject;\n\nfunction isWebAssemblyCompiledModule(value) {\n return ObjectToString(value) === '[object WebAssembly.Module]';\n}\nexports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule;\n\nfunction isNumberObject(value) {\n return checkBoxedPrimitive(value, numberValue);\n}\nexports.isNumberObject = isNumberObject;\n\nfunction isStringObject(value) {\n return checkBoxedPrimitive(value, stringValue);\n}\nexports.isStringObject = isStringObject;\n\nfunction isBooleanObject(value) {\n return checkBoxedPrimitive(value, booleanValue);\n}\nexports.isBooleanObject = isBooleanObject;\n\nfunction isBigIntObject(value) {\n return BigIntSupported && checkBoxedPrimitive(value, bigIntValue);\n}\nexports.isBigIntObject = isBigIntObject;\n\nfunction isSymbolObject(value) {\n return SymbolSupported && checkBoxedPrimitive(value, symbolValue);\n}\nexports.isSymbolObject = isSymbolObject;\n\nfunction isBoxedPrimitive(value) {\n return (\n isNumberObject(value) ||\n isStringObject(value) ||\n isBooleanObject(value) ||\n isBigIntObject(value) ||\n isSymbolObject(value)\n );\n}\nexports.isBoxedPrimitive = isBoxedPrimitive;\n\nfunction isAnyArrayBuffer(value) {\n return typeof Uint8Array !== 'undefined' && (\n isArrayBuffer(value) ||\n isSharedArrayBuffer(value)\n );\n}\nexports.isAnyArrayBuffer = isAnyArrayBuffer;\n\n['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) {\n Object.defineProperty(exports, method, {\n enumerable: false,\n value: function() {\n throw new Error(method + ' is not supported in userland');\n }\n });\n});\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nvar getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||\n function getOwnPropertyDescriptors(obj) {\n var keys = Object.keys(obj);\n var descriptors = {};\n for (var i = 0; i < keys.length; i++) {\n descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);\n }\n return descriptors;\n };\n\nvar formatRegExp = /%[sdj%]/g;\nexports.format = function(f) {\n if (!isString(f)) {\n var objects = [];\n for (var i = 0; i < arguments.length; i++) {\n objects.push(inspect(arguments[i]));\n }\n return objects.join(' ');\n }\n\n var i = 1;\n var args = arguments;\n var len = args.length;\n var str = String(f).replace(formatRegExp, function(x) {\n if (x === '%%') return '%';\n if (i >= len) return x;\n switch (x) {\n case '%s': return String(args[i++]);\n case '%d': return Number(args[i++]);\n case '%j':\n try {\n return JSON.stringify(args[i++]);\n } catch (_) {\n return '[Circular]';\n }\n default:\n return x;\n }\n });\n for (var x = args[i]; i < len; x = args[++i]) {\n if (isNull(x) || !isObject(x)) {\n str += ' ' + x;\n } else {\n str += ' ' + inspect(x);\n }\n }\n return str;\n};\n\n\n// Mark that a method should not be used.\n// Returns a modified function which warns once by default.\n// If --no-deprecation is set, then it is a no-op.\nexports.deprecate = function(fn, msg) {\n if (typeof process !== 'undefined' && process.noDeprecation === true) {\n return fn;\n }\n\n // Allow for deprecating things in the process of starting up.\n if (typeof process === 'undefined') {\n return function() {\n return exports.deprecate(fn, msg).apply(this, arguments);\n };\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (process.throwDeprecation) {\n throw new Error(msg);\n } else if (process.traceDeprecation) {\n console.trace(msg);\n } else {\n console.error(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n};\n\n\nvar debugs = {};\nvar debugEnvRegex = /^$/;\n\nif (process.env.NODE_DEBUG) {\n var debugEnv = process.env.NODE_DEBUG;\n debugEnv = debugEnv.replace(/[|\\\\{}()[\\]^$+?.]/g, '\\\\$&')\n .replace(/\\*/g, '.*')\n .replace(/,/g, '$|^')\n .toUpperCase();\n debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i');\n}\nexports.debuglog = function(set) {\n set = set.toUpperCase();\n if (!debugs[set]) {\n if (debugEnvRegex.test(set)) {\n var pid = process.pid;\n debugs[set] = function() {\n var msg = exports.format.apply(exports, arguments);\n console.error('%s %d: %s', set, pid, msg);\n };\n } else {\n debugs[set] = function() {};\n }\n }\n return debugs[set];\n};\n\n\n/**\n * Echos the value of a value. Trys to print the value out\n * in the best way possible given the different types.\n *\n * @param {Object} obj The object to print out.\n * @param {Object} opts Optional options object that alters the output.\n */\n/* legacy: obj, showHidden, depth, colors*/\nfunction inspect(obj, opts) {\n // default options\n var ctx = {\n seen: [],\n stylize: stylizeNoColor\n };\n // legacy...\n if (arguments.length >= 3) ctx.depth = arguments[2];\n if (arguments.length >= 4) ctx.colors = arguments[3];\n if (isBoolean(opts)) {\n // legacy...\n ctx.showHidden = opts;\n } else if (opts) {\n // got an \"options\" object\n exports._extend(ctx, opts);\n }\n // set default options\n if (isUndefined(ctx.showHidden)) ctx.showHidden = false;\n if (isUndefined(ctx.depth)) ctx.depth = 2;\n if (isUndefined(ctx.colors)) ctx.colors = false;\n if (isUndefined(ctx.customInspect)) ctx.customInspect = true;\n if (ctx.colors) ctx.stylize = stylizeWithColor;\n return formatValue(ctx, obj, ctx.depth);\n}\nexports.inspect = inspect;\n\n\n// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\ninspect.colors = {\n 'bold' : [1, 22],\n 'italic' : [3, 23],\n 'underline' : [4, 24],\n 'inverse' : [7, 27],\n 'white' : [37, 39],\n 'grey' : [90, 39],\n 'black' : [30, 39],\n 'blue' : [34, 39],\n 'cyan' : [36, 39],\n 'green' : [32, 39],\n 'magenta' : [35, 39],\n 'red' : [31, 39],\n 'yellow' : [33, 39]\n};\n\n// Don't use 'blue' not visible on cmd.exe\ninspect.styles = {\n 'special': 'cyan',\n 'number': 'yellow',\n 'boolean': 'yellow',\n 'undefined': 'grey',\n 'null': 'bold',\n 'string': 'green',\n 'date': 'magenta',\n // \"name\": intentionally not styling\n 'regexp': 'red'\n};\n\n\nfunction stylizeWithColor(str, styleType) {\n var style = inspect.styles[styleType];\n\n if (style) {\n return '\\u001b[' + inspect.colors[style][0] + 'm' + str +\n '\\u001b[' + inspect.colors[style][1] + 'm';\n } else {\n return str;\n }\n}\n\n\nfunction stylizeNoColor(str, styleType) {\n return str;\n}\n\n\nfunction arrayToHash(array) {\n var hash = {};\n\n array.forEach(function(val, idx) {\n hash[val] = true;\n });\n\n return hash;\n}\n\n\nfunction formatValue(ctx, value, recurseTimes) {\n // Provide a hook for user-specified inspect functions.\n // Check that value is an object with an inspect function on it\n if (ctx.customInspect &&\n value &&\n isFunction(value.inspect) &&\n // Filter out the util module, it's inspect function is special\n value.inspect !== exports.inspect &&\n // Also filter out any prototype objects using the circular check.\n !(value.constructor && value.constructor.prototype === value)) {\n var ret = value.inspect(recurseTimes, ctx);\n if (!isString(ret)) {\n ret = formatValue(ctx, ret, recurseTimes);\n }\n return ret;\n }\n\n // Primitive types cannot have properties\n var primitive = formatPrimitive(ctx, value);\n if (primitive) {\n return primitive;\n }\n\n // Look up the keys of the object.\n var keys = Object.keys(value);\n var visibleKeys = arrayToHash(keys);\n\n if (ctx.showHidden) {\n keys = Object.getOwnPropertyNames(value);\n }\n\n // IE doesn't make error fields non-enumerable\n // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx\n if (isError(value)\n && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {\n return formatError(value);\n }\n\n // Some type of object without properties can be shortcutted.\n if (keys.length === 0) {\n if (isFunction(value)) {\n var name = value.name ? ': ' + value.name : '';\n return ctx.stylize('[Function' + name + ']', 'special');\n }\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n }\n if (isDate(value)) {\n return ctx.stylize(Date.prototype.toString.call(value), 'date');\n }\n if (isError(value)) {\n return formatError(value);\n }\n }\n\n var base = '', array = false, braces = ['{', '}'];\n\n // Make Array say that they are Array\n if (isArray(value)) {\n array = true;\n braces = ['[', ']'];\n }\n\n // Make functions say that they are functions\n if (isFunction(value)) {\n var n = value.name ? ': ' + value.name : '';\n base = ' [Function' + n + ']';\n }\n\n // Make RegExps say that they are RegExps\n if (isRegExp(value)) {\n base = ' ' + RegExp.prototype.toString.call(value);\n }\n\n // Make dates with properties first say the date\n if (isDate(value)) {\n base = ' ' + Date.prototype.toUTCString.call(value);\n }\n\n // Make error with message first say the error\n if (isError(value)) {\n base = ' ' + formatError(value);\n }\n\n if (keys.length === 0 && (!array || value.length == 0)) {\n return braces[0] + base + braces[1];\n }\n\n if (recurseTimes < 0) {\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n } else {\n return ctx.stylize('[Object]', 'special');\n }\n }\n\n ctx.seen.push(value);\n\n var output;\n if (array) {\n output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);\n } else {\n output = keys.map(function(key) {\n return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);\n });\n }\n\n ctx.seen.pop();\n\n return reduceToSingleString(output, base, braces);\n}\n\n\nfunction formatPrimitive(ctx, value) {\n if (isUndefined(value))\n return ctx.stylize('undefined', 'undefined');\n if (isString(value)) {\n var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"') + '\\'';\n return ctx.stylize(simple, 'string');\n }\n if (isNumber(value))\n return ctx.stylize('' + value, 'number');\n if (isBoolean(value))\n return ctx.stylize('' + value, 'boolean');\n // For some reason typeof null is \"object\", so special case here.\n if (isNull(value))\n return ctx.stylize('null', 'null');\n}\n\n\nfunction formatError(value) {\n return '[' + Error.prototype.toString.call(value) + ']';\n}\n\n\nfunction formatArray(ctx, value, recurseTimes, visibleKeys, keys) {\n var output = [];\n for (var i = 0, l = value.length; i < l; ++i) {\n if (hasOwnProperty(value, String(i))) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n String(i), true));\n } else {\n output.push('');\n }\n }\n keys.forEach(function(key) {\n if (!key.match(/^\\d+$/)) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n key, true));\n }\n });\n return output;\n}\n\n\nfunction formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {\n var name, str, desc;\n desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };\n if (desc.get) {\n if (desc.set) {\n str = ctx.stylize('[Getter/Setter]', 'special');\n } else {\n str = ctx.stylize('[Getter]', 'special');\n }\n } else {\n if (desc.set) {\n str = ctx.stylize('[Setter]', 'special');\n }\n }\n if (!hasOwnProperty(visibleKeys, key)) {\n name = '[' + key + ']';\n }\n if (!str) {\n if (ctx.seen.indexOf(desc.value) < 0) {\n if (isNull(recurseTimes)) {\n str = formatValue(ctx, desc.value, null);\n } else {\n str = formatValue(ctx, desc.value, recurseTimes - 1);\n }\n if (str.indexOf('\\n') > -1) {\n if (array) {\n str = str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n').substr(2);\n } else {\n str = '\\n' + str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n');\n }\n }\n } else {\n str = ctx.stylize('[Circular]', 'special');\n }\n }\n if (isUndefined(name)) {\n if (array && key.match(/^\\d+$/)) {\n return str;\n }\n name = JSON.stringify('' + key);\n if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n name = name.substr(1, name.length - 2);\n name = ctx.stylize(name, 'name');\n } else {\n name = name.replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"')\n .replace(/(^\"|\"$)/g, \"'\");\n name = ctx.stylize(name, 'string');\n }\n }\n\n return name + ': ' + str;\n}\n\n\nfunction reduceToSingleString(output, base, braces) {\n var numLinesEst = 0;\n var length = output.reduce(function(prev, cur) {\n numLinesEst++;\n if (cur.indexOf('\\n') >= 0) numLinesEst++;\n return prev + cur.replace(/\\u001b\\[\\d\\d?m/g, '').length + 1;\n }, 0);\n\n if (length > 60) {\n return braces[0] +\n (base === '' ? '' : base + '\\n ') +\n ' ' +\n output.join(',\\n ') +\n ' ' +\n braces[1];\n }\n\n return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n}\n\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\nexports.types = require('./support/types');\n\nfunction isArray(ar) {\n return Array.isArray(ar);\n}\nexports.isArray = isArray;\n\nfunction isBoolean(arg) {\n return typeof arg === 'boolean';\n}\nexports.isBoolean = isBoolean;\n\nfunction isNull(arg) {\n return arg === null;\n}\nexports.isNull = isNull;\n\nfunction isNullOrUndefined(arg) {\n return arg == null;\n}\nexports.isNullOrUndefined = isNullOrUndefined;\n\nfunction isNumber(arg) {\n return typeof arg === 'number';\n}\nexports.isNumber = isNumber;\n\nfunction isString(arg) {\n return typeof arg === 'string';\n}\nexports.isString = isString;\n\nfunction isSymbol(arg) {\n return typeof arg === 'symbol';\n}\nexports.isSymbol = isSymbol;\n\nfunction isUndefined(arg) {\n return arg === void 0;\n}\nexports.isUndefined = isUndefined;\n\nfunction isRegExp(re) {\n return isObject(re) && objectToString(re) === '[object RegExp]';\n}\nexports.isRegExp = isRegExp;\nexports.types.isRegExp = isRegExp;\n\nfunction isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\nexports.isObject = isObject;\n\nfunction isDate(d) {\n return isObject(d) && objectToString(d) === '[object Date]';\n}\nexports.isDate = isDate;\nexports.types.isDate = isDate;\n\nfunction isError(e) {\n return isObject(e) &&\n (objectToString(e) === '[object Error]' || e instanceof Error);\n}\nexports.isError = isError;\nexports.types.isNativeError = isError;\n\nfunction isFunction(arg) {\n return typeof arg === 'function';\n}\nexports.isFunction = isFunction;\n\nfunction isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\nexports.isPrimitive = isPrimitive;\n\nexports.isBuffer = require('./support/isBuffer');\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\nfunction pad(n) {\n return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n 'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n var d = new Date();\n var time = [pad(d.getHours()),\n pad(d.getMinutes()),\n pad(d.getSeconds())].join(':');\n return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\n\n// log is just a thin wrapper to console.log that prepends a timestamp\nexports.log = function() {\n console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * The Function.prototype.inherits from lang.js rewritten as a standalone\n * function (not on Function.prototype). NOTE: If this file is to be loaded\n * during bootstrapping this function needs to be rewritten using some native\n * functions as prototype setup using normal JavaScript does not work as\n * expected during bootstrapping (see mirror.js in r114903).\n *\n * @param {function} ctor Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nexports.inherits = require('inherits');\n\nexports._extend = function(origin, add) {\n // Don't do anything if add isn't an object\n if (!add || !isObject(add)) return origin;\n\n var keys = Object.keys(add);\n var i = keys.length;\n while (i--) {\n origin[keys[i]] = add[keys[i]];\n }\n return origin;\n};\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nvar kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;\n\nexports.promisify = function promisify(original) {\n if (typeof original !== 'function')\n throw new TypeError('The \"original\" argument must be of type Function');\n\n if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {\n var fn = original[kCustomPromisifiedSymbol];\n if (typeof fn !== 'function') {\n throw new TypeError('The \"util.promisify.custom\" argument must be of type Function');\n }\n Object.defineProperty(fn, kCustomPromisifiedSymbol, {\n value: fn, enumerable: false, writable: false, configurable: true\n });\n return fn;\n }\n\n function fn() {\n var promiseResolve, promiseReject;\n var promise = new Promise(function (resolve, reject) {\n promiseResolve = resolve;\n promiseReject = reject;\n });\n\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n args.push(function (err, value) {\n if (err) {\n promiseReject(err);\n } else {\n promiseResolve(value);\n }\n });\n\n try {\n original.apply(this, args);\n } catch (err) {\n promiseReject(err);\n }\n\n return promise;\n }\n\n Object.setPrototypeOf(fn, Object.getPrototypeOf(original));\n\n if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {\n value: fn, enumerable: false, writable: false, configurable: true\n });\n return Object.defineProperties(\n fn,\n getOwnPropertyDescriptors(original)\n );\n}\n\nexports.promisify.custom = kCustomPromisifiedSymbol\n\nfunction callbackifyOnRejected(reason, cb) {\n // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).\n // Because `null` is a special error value in callbacks which means \"no error\n // occurred\", we error-wrap so the callback consumer can distinguish between\n // \"the promise rejected with null\" or \"the promise fulfilled with undefined\".\n if (!reason) {\n var newReason = new Error('Promise was rejected with a falsy value');\n newReason.reason = reason;\n reason = newReason;\n }\n return cb(reason);\n}\n\nfunction callbackify(original) {\n if (typeof original !== 'function') {\n throw new TypeError('The \"original\" argument must be of type Function');\n }\n\n // We DO NOT return the promise as it gives the user a false sense that\n // the promise is actually somehow related to the callback's execution\n // and that the callback throwing will reject the promise.\n function callbackified() {\n var args = [];\n for (var i = 0; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n\n var maybeCb = args.pop();\n if (typeof maybeCb !== 'function') {\n throw new TypeError('The last argument must be of type Function');\n }\n var self = this;\n var cb = function() {\n return maybeCb.apply(self, arguments);\n };\n // In true node style we process the callback on `nextTick` with all the\n // implications (stack, `uncaughtException`, `async_hooks`)\n original.apply(this, args)\n .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) },\n function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) });\n }\n\n Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));\n Object.defineProperties(callbackified,\n getOwnPropertyDescriptors(original));\n return callbackified;\n}\nexports.callbackify = callbackify;\n","'use strict';\n\nvar forEach = require('foreach');\nvar availableTypedArrays = require('available-typed-arrays');\nvar callBound = require('call-bind/callBound');\n\nvar $toString = callBound('Object.prototype.toString');\nvar hasToStringTag = require('has-tostringtag/shams')();\n\nvar g = typeof globalThis === 'undefined' ? global : globalThis;\nvar typedArrays = availableTypedArrays();\n\nvar $slice = callBound('String.prototype.slice');\nvar toStrTags = {};\nvar gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor');\nvar getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');\nif (hasToStringTag && gOPD && getPrototypeOf) {\n\tforEach(typedArrays, function (typedArray) {\n\t\tif (typeof g[typedArray] === 'function') {\n\t\t\tvar arr = new g[typedArray]();\n\t\t\tif (Symbol.toStringTag in arr) {\n\t\t\t\tvar proto = getPrototypeOf(arr);\n\t\t\t\tvar descriptor = gOPD(proto, Symbol.toStringTag);\n\t\t\t\tif (!descriptor) {\n\t\t\t\t\tvar superProto = getPrototypeOf(proto);\n\t\t\t\t\tdescriptor = gOPD(superProto, Symbol.toStringTag);\n\t\t\t\t}\n\t\t\t\ttoStrTags[typedArray] = descriptor.get;\n\t\t\t}\n\t\t}\n\t});\n}\n\nvar tryTypedArrays = function tryAllTypedArrays(value) {\n\tvar foundName = false;\n\tforEach(toStrTags, function (getter, typedArray) {\n\t\tif (!foundName) {\n\t\t\ttry {\n\t\t\t\tvar name = getter.call(value);\n\t\t\t\tif (name === typedArray) {\n\t\t\t\t\tfoundName = name;\n\t\t\t\t}\n\t\t\t} catch (e) {}\n\t\t}\n\t});\n\treturn foundName;\n};\n\nvar isTypedArray = require('is-typed-array');\n\nmodule.exports = function whichTypedArray(value) {\n\tif (!isTypedArray(value)) { return false; }\n\tif (!hasToStringTag || !(Symbol.toStringTag in value)) { return $slice($toString(value), 8, -1); }\n\treturn tryTypedArrays(value);\n};\n","const os = require('os');\nconst fs = require('fs');\nconst path = require('path');\n\nconst rbql = require('./rbql_core/rbql-js/rbql.js');\nconst rbql_csv = require('./rbql_core/rbql-js/rbql_csv.js');\nconst csv_utils = require('./rbql_core/rbql-js/csv_utils.js');\n\nconst non_numeric_sentinel = -1;\nconst number_regex = /^([0-9]+)(\\.[0-9]+)?$/;\n\nclass AssertionError extends Error {}\n\nfunction assert(condition, message=null) {\n if (!condition) {\n if (!message) {\n message = 'Assertion error';\n }\n throw new AssertionError(message);\n }\n}\n\n\nfunction get_default_js_udf_content() {\n let default_content = `// This file can be used to store RBQL UDFs. Example:\n //\n // function foo(value) {\n // return 'foo ' + String(value.length);\n // }\n // \n // Functions defined in this file can be used in RBQL queries e.g. \n // SELECT foo(a1), a2 WHERE foo(a3) != 'foo 5' LIMIT 10\n //\n // Don't forget to save this file after editing!\n //\n // Write your own functions bellow this line:\n `.replace(new RegExp(/^ */, 'mg'), '');\n return default_content;\n}\n\n\nfunction get_default_python_udf_content() {\n let default_content = `# This file can be used to store RBQL UDFs. Example:\n #\n # def foo(value):\n # return 'foo ' + str(len(value))\n # \n # \n # Functions defined in this file can be used in RBQL queries e.g. \n # SELECT foo(a1), a2 WHERE foo(a3) != 'foo 5' LIMIT 10\n #\n # Don't forget to save this file after editing!\n #\n # Write your own functions bellow this line:\n `.replace(new RegExp(/^ */, 'mg'), '');\n return default_content;\n}\n\n\nfunction update_subcomponent_stats(field, is_first_line, max_field_components_lens) {\n // Extract overall field length and length of integer and fractional parts of the field if it represents a number.\n // Here `max_field_components_lens` is a tuple: (max_field_length, max_integer_part_length, max_fractional_part_length)\n if (field.length > max_field_components_lens[0]) {\n max_field_components_lens[0] = field.length;\n }\n if (max_field_components_lens[1] == non_numeric_sentinel) {\n // Column is not a number, early return.\n return;\n }\n let match_result = number_regex.exec(field);\n if (match_result === null) {\n if (!is_first_line && field.length) { // Checking field_length here allows numeric columns to have some of the fields empty.\n // We only mark the column as non-header if we know that this is not a header line.\n max_field_components_lens[1] = non_numeric_sentinel;\n max_field_components_lens[2] = non_numeric_sentinel;\n }\n return;\n }\n let cur_integer_part_length = match_result[1].length;\n max_field_components_lens[1] = Math.max(max_field_components_lens[1], cur_integer_part_length);\n let cur_fractional_part_length = match_result[2] === undefined ? 0 : match_result[2].length;\n max_field_components_lens[2] = Math.max(max_field_components_lens[2], cur_fractional_part_length);\n}\n\n\nfunction calc_column_stats(active_doc, delim, policy, comment_prefix) {\n let column_stats = [];\n let num_lines = active_doc.lineCount;\n let is_first_line = true;\n for (let lnum = 0; lnum < num_lines; lnum++) {\n let line_text = active_doc.lineAt(lnum).text;\n if (comment_prefix && line_text.startsWith(comment_prefix))\n continue;\n let [fields, warning] = csv_utils.smart_split(line_text, delim, policy, true);\n if (warning) {\n return [null, lnum + 1];\n }\n for (let fnum = 0; fnum < fields.length; fnum++) {\n let field = fields[fnum].trim();\n if (column_stats.length <= fnum) {\n column_stats.push([0, 0, 0]);\n }\n update_subcomponent_stats(field, is_first_line, column_stats[fnum]);\n }\n is_first_line = false;\n }\n return [column_stats, null];\n}\n\n\nfunction adjust_column_stats(column_stats) {\n // Ensure that numeric components max widths are consistent with non-numeric (header) width.\n let adjusted_stats = [];\n for (let column_stat of column_stats) {\n if (column_stat[1] <= 0) {\n column_stat[1] = -1;\n column_stat[2] = -1;\n }\n if (column_stat[1] > 0) {\n // The sum of integer and float parts can be bigger than the max width, e.g. here:\n // value\n // 0.12\n // 1234\n if (column_stat[1] + column_stat[2] > column_stat[0]) {\n column_stat[0] = column_stat[1] + column_stat[2];\n }\n // This is needed when the header is wider than numeric components and/or their sum.\n if (column_stat[0] - column_stat[2] > column_stat[1]) {\n column_stat[1] = column_stat[0] - column_stat[2];\n }\n // Sanity check.\n if (column_stat[0] != column_stat[1] + column_stat[2]) {\n // Assertion Error, this can never happen.\n return null;\n }\n }\n adjusted_stats.push(column_stat);\n }\n return adjusted_stats;\n}\n\n\nfunction align_field(field, is_first_line, max_field_components_lens, is_last_column) {\n // Align field, use Math.max() to avoid negative delta_length which can happen theorethically due to async doc edit.\n const extra_readability_whitespace_length = 1;\n field = field.trim();\n if (max_field_components_lens[1] == non_numeric_sentinel) {\n let delta_length = Math.max(max_field_components_lens[0] - field.length, 0);\n return is_last_column ? field : field + ' '.repeat(delta_length + extra_readability_whitespace_length);\n }\n if (is_first_line) {\n if (number_regex.exec(field) === null) {\n // The line must be a header - align it using max_width rule.\n let delta_length = Math.max(max_field_components_lens[0] - field.length, 0);\n return is_last_column ? field : field + ' '.repeat(delta_length + extra_readability_whitespace_length);\n }\n }\n let dot_pos = field.indexOf('.');\n let cur_integer_part_length = dot_pos == -1 ? field.length : dot_pos;\n // Here cur_fractional_part_length includes the leading dot too.\n let cur_fractional_part_length = dot_pos == -1 ? 0 : field.length - dot_pos;\n let integer_delta_length = Math.max(max_field_components_lens[1] - cur_integer_part_length, 0);\n let fractional_delta_length = Math.max(max_field_components_lens[2] - cur_fractional_part_length);\n let trailing_spaces = is_last_column ? '' : ' '.repeat(fractional_delta_length + extra_readability_whitespace_length);\n return ' '.repeat(integer_delta_length) + field + trailing_spaces;\n}\n\n\nfunction align_columns(active_doc, delim, policy, comment_prefix, column_stats) {\n let result_lines = [];\n let num_lines = active_doc.lineCount;\n let has_edit = false;\n let is_first_line = true;\n for (let lnum = 0; lnum < num_lines; lnum++) {\n let line_text = active_doc.lineAt(lnum).text;\n if (comment_prefix && line_text.startsWith(comment_prefix)) {\n result_lines.push(line_text);\n continue;\n }\n if (lnum + 1 == num_lines && line_text == '') {\n // Skip the last empty line which corresponds to the trailing newline character.\n result_lines.push(line_text);\n continue;\n }\n let fields = csv_utils.smart_split(line_text, delim, policy, true)[0];\n for (let fnum = 0; fnum < fields.length; fnum++) {\n if (fnum >= column_stats.length) // Safeguard against async doc edit, should never happen.\n break;\n let is_last_column = fnum + 1 == column_stats.length;\n let adjusted = align_field(fields[fnum], is_first_line, column_stats[fnum], is_last_column);\n if (fields[fnum] != adjusted) {\n fields[fnum] = adjusted;\n has_edit = true;\n }\n }\n is_first_line = false;\n result_lines.push(fields.join(delim));\n }\n if (!has_edit)\n return null;\n return result_lines.join('\\n');\n}\n\n\nfunction shrink_columns(active_doc, delim, policy, comment_prefix) {\n let result_lines = [];\n let num_lines = active_doc.lineCount;\n let has_edit = false;\n for (let lnum = 0; lnum < num_lines; lnum++) {\n let line_text = active_doc.lineAt(lnum).text;\n if (comment_prefix && line_text.startsWith(comment_prefix)) {\n result_lines.push(line_text);\n continue;\n }\n let [fields, warning] = csv_utils.smart_split(line_text, delim, policy, true);\n if (warning) {\n return [null, lnum + 1];\n }\n for (let i = 0; i < fields.length; i++) {\n let adjusted = fields[i].trim();\n if (fields[i].length != adjusted.length) {\n fields[i] = adjusted;\n has_edit = true;\n }\n }\n result_lines.push(fields.join(delim));\n }\n if (!has_edit)\n return [null, null];\n return [result_lines.join('\\n'), null];\n}\n\n\nfunction get_last(arr) {\n return arr[arr.length - 1];\n}\n\n\nfunction populate_optimistic_rfc_csv_record_map(document, requested_end_record, dst_record_map, comment_prefix=null) {\n let num_lines = document.lineCount;\n let record_begin = null;\n let start_line_idx = dst_record_map.length ? get_last(dst_record_map)[1] : 0;\n for (let lnum = start_line_idx; lnum < num_lines && dst_record_map.length < requested_end_record; ++lnum) {\n let line_text = document.lineAt(lnum).text;\n if (lnum + 1 >= num_lines && line_text == \"\")\n break; // Skip the last empty line.\n if (comment_prefix && line_text.startsWith(comment_prefix))\n continue;\n let match_list = line_text.match(/\"/g);\n let has_unbalanced_double_quote = match_list && match_list.length % 2 == 1;\n if (record_begin === null && !has_unbalanced_double_quote) {\n dst_record_map.push([lnum, lnum + 1]);\n } else if (record_begin === null && has_unbalanced_double_quote) {\n record_begin = lnum;\n } else if (!has_unbalanced_double_quote) {\n continue;\n } else {\n dst_record_map.push([record_begin, lnum + 1]);\n record_begin = null;\n }\n }\n if (record_begin !== null) {\n dst_record_map.push([record_begin, num_lines]);\n }\n}\n\n\nfunction make_table_name_key(file_path) {\n return 'rbql_table_name:' + file_path;\n}\n\n\nfunction expanduser(filepath) {\n if (filepath.charAt(0) === '~') {\n return path.join(os.homedir(), filepath.slice(1));\n }\n return filepath;\n}\n\n\nfunction find_table_path(vscode_global_state, main_table_dir, table_id) {\n // If table_id is a relative path it could be relative either to the current directory or to the main table dir.\n var candidate_path = expanduser(table_id);\n if (fs.existsSync(candidate_path)) {\n return candidate_path;\n }\n if (main_table_dir && !path.isAbsolute(candidate_path)) {\n candidate_path = path.join(main_table_dir, candidate_path);\n if (fs.existsSync(candidate_path)) {\n return candidate_path;\n }\n }\n let table_path = vscode_global_state ? vscode_global_state.get(make_table_name_key(table_id)) : null;\n if (table_path && fs.existsSync(table_path)) {\n return table_path;\n }\n return null;\n}\n\n\nasync function read_header(table_path, encoding) {\n if (encoding == 'latin-1')\n encoding = 'binary';\n let readline = require('readline');\n let input_reader = readline.createInterface({ input: fs.createReadStream(table_path, {encoding: encoding}) });\n let closed = false;\n let promise_resolve = null;\n let promise_reject = null;\n let output_promise = new Promise(function(resolve, reject) {\n promise_resolve = resolve;\n promise_reject = reject;\n });\n input_reader.on('line', line => {\n if (!closed) {\n closed = true;\n input_reader.close();\n promise_resolve(line);\n }\n });\n input_reader.on('error', error => {\n promise_reject(error);\n });\n return output_promise;\n}\n\n\nfunction get_header_line(document, comment_prefix) {\n const num_lines = document.lineCount;\n for (let lnum = 0; lnum < num_lines; ++lnum) {\n const line_text = document.lineAt(lnum).text;\n if (!comment_prefix || !line_text.startsWith(comment_prefix)) {\n return line_text;\n }\n }\n return null;\n}\n\n\nfunction make_inconsistent_num_fields_warning(table_name, inconsistent_records_info) {\n let keys = Object.keys(inconsistent_records_info);\n let entries = [];\n for (let i = 0; i < keys.length; i++) {\n let key = keys[i];\n let record_id = inconsistent_records_info[key];\n entries.push([record_id, key]);\n }\n entries.sort(function(a, b) { return a[0] - b[0]; });\n assert(entries.length > 1);\n let [record_1, num_fields_1] = entries[0];\n let [record_2, num_fields_2] = entries[1];\n let warn_msg = `Number of fields in \"${table_name}\" table is not consistent: `;\n warn_msg += `e.g. record ${record_1} -> ${num_fields_1} fields, record ${record_2} -> ${num_fields_2} fields`;\n return warn_msg;\n}\n\n\n\nclass RbqlIOHandlingError extends Error {}\n\nclass VSCodeRecordIterator extends rbql.RBQLInputIterator {\n constructor(document, delim, policy, has_header=false, comment_prefix=null, table_name='input', variable_prefix='a') {\n // We could have done a hack here actually: convert the document to stream/buffer and then use the standard reader.\n super();\n this.document = document;\n this.delim = delim;\n this.policy = policy;\n this.has_header = has_header;\n this.comment_prefix = comment_prefix;\n this.table_name = table_name;\n this.variable_prefix = variable_prefix;\n this.NR = 0; // Record number.\n this.NL = 0; // Line number (NL != NR when the CSV file has comments or multiline fields).\n this.fields_info = new Object();\n this.first_defective_line = null;\n this.first_record = this.get_first_record();\n }\n\n stop() {\n }\n\n get_first_record() {\n let header_line = get_header_line(this.document, this.comment_prefix);\n let first_record = csv_utils.smart_split(header_line, this.delim, this.policy, /*preserve_quotes_and_whitespaces=*/false)[0];\n return first_record;\n }\n\n async get_variables_map(query_text) {\n let variable_map = new Object();\n rbql.parse_basic_variables(query_text, this.variable_prefix, variable_map);\n rbql.parse_array_variables(query_text, this.variable_prefix, variable_map);\n let header_line = get_header_line(this.document, this.comment_prefix);\n let first_record = csv_utils.smart_split(header_line, this.delim, this.policy, /*preserve_quotes_and_whitespaces=*/false)[0];\n if (this.has_header) {\n rbql.parse_attribute_variables(query_text, this.variable_prefix, first_record, 'CSV header line', variable_map);\n rbql.parse_dictionary_variables(query_text, this.variable_prefix, first_record, variable_map);\n }\n return variable_map;\n }\n\n async get_header() {\n return this.has_header ? this.first_record : null;\n }\n\n get_line_rfc() {\n let rfc_line_buffer = [];\n const num_lines = this.document.lineCount;\n while (this.NL < num_lines) {\n let line = this.document.lineAt(this.NL).text;\n this.NL += 1;\n if (this.NL == num_lines && line.length == 0)\n return null; // Skip the last line if it is empty - this can happen due to trailing newline.\n let record_line = csv_utils.accumulate_rfc_line_into_record(rfc_line_buffer, line, this.comment_prefix);\n if (record_line !== null)\n return record_line;\n }\n return null;\n }\n\n get_line_simple() {\n const num_lines = this.document.lineCount;\n while (this.NL < num_lines) {\n let line = this.document.lineAt(this.NL).text;\n this.NL += 1;\n if (this.NL == num_lines && line.length == 0)\n return null; // Skip the last line if it is empty - this can happen due to trailing newline.\n if (this.comment_prefix === null || !line.startsWith(this.comment_prefix))\n return line;\n }\n return null;\n }\n\n do_get_record() {\n let line = (this.policy == 'quoted_rfc') ? this.get_line_rfc() : this.get_line_simple();\n if (line === null)\n return null;\n let [record, warning] = csv_utils.smart_split(line, this.delim, this.policy, /*preserve_quotes_and_whitespaces=*/false);\n if (warning) {\n if (this.first_defective_line === null) {\n this.first_defective_line = this.NL;\n if (this.policy == 'quoted_rfc')\n throw new RbqlIOHandlingError(`Inconsistent double quote escaping in ${this.table_name} table at record ${this.NR}, line ${this.NL}`);\n }\n }\n let num_fields = record.length;\n if (!this.fields_info.hasOwnProperty(num_fields))\n this.fields_info[num_fields] = this.NR;\n return record;\n }\n\n async get_record() {\n if (this.NR == 0 && this.has_header) {\n this.do_get_record(); // Skip the header record.\n }\n this.NR += 1;\n let record = this.do_get_record();\n return record;\n }\n\n get_warnings() {\n let result = [];\n if (this.first_defective_line !== null)\n result.push(`Inconsistent double quote escaping in ${this.table_name} table. E.g. at line ${this.first_defective_line}`);\n if (Object.keys(this.fields_info).length > 1)\n result.push(make_inconsistent_num_fields_warning(this.table_name, this.fields_info));\n return result;\n }\n}\n\n\nclass VSCodeWriter extends rbql.RBQLOutputWriter {\n constructor(delim, policy) {\n super();\n this.delim = delim;\n this.policy = policy;\n this.header_len = null;\n this.null_in_output = false;\n this.delim_in_simple_output = false;\n this.output_lines = [];\n\n if (policy == 'simple') {\n this.polymorphic_join = this.simple_join;\n } else if (policy == 'quoted') {\n this.polymorphic_join = this.quoted_join;\n } else if (policy == 'quoted_rfc') {\n this.polymorphic_join = this.quoted_join_rfc;\n } else if (policy == 'monocolumn') {\n this.polymorphic_join = this.mono_join;\n } else if (policy == 'whitespace') {\n this.polymorphic_join = this.simple_join;\n } else {\n throw new RbqlIOHandlingError('Unknown output csv policy');\n }\n }\n\n set_header(header) {\n if (header !== null) {\n this.header_len = header.length;\n this.write(header);\n }\n }\n\n quoted_join(fields) {\n let delim = this.delim;\n var quoted_fields = fields.map(function(v) { return csv_utils.quote_field(String(v), delim); });\n return quoted_fields.join(this.delim);\n };\n\n\n quoted_join_rfc(fields) {\n let delim = this.delim;\n var quoted_fields = fields.map(function(v) { return csv_utils.rfc_quote_field(String(v), delim); });\n return quoted_fields.join(this.delim);\n };\n\n\n mono_join(fields) {\n if (fields.length > 1) {\n throw new RbqlIOHandlingError('Unable to use \"Monocolumn\" output format: some records have more than one field');\n }\n return fields[0];\n };\n\n\n simple_join(fields) {\n var res = fields.join(this.delim);\n if (fields.join('').indexOf(this.delim) != -1) {\n this.delim_in_simple_output = true;\n }\n return res;\n };\n\n\n normalize_fields(out_fields) {\n for (var i = 0; i < out_fields.length; i++) {\n if (out_fields[i] == null) {\n this.null_in_output = true;\n out_fields[i] = '';\n } else if (Array.isArray(out_fields[i])) {\n this.normalize_fields(out_fields[i]);\n out_fields[i] = out_fields[i].join(this.sub_array_delim);\n }\n }\n };\n\n\n write(fields) {\n if (this.header_len !== null && fields.length != this.header_len)\n throw new RbqlIOHandlingError(`Inconsistent number of columns in output header and the current record: ${this.header_len} != ${fields.length}`);\n this.normalize_fields(fields);\n this.output_lines.push(this.polymorphic_join(fields));\n return true;\n };\n\n async finish() {\n }\n\n get_warnings() {\n let result = [];\n if (this.null_in_output)\n result.push('null values in output were replaced by empty strings');\n if (this.delim_in_simple_output)\n result.push('Some output fields contain separator');\n return result;\n };\n}\n\nclass VSCodeTableRegistry {\n constructor(){}\n\n get_iterator_by_table_id(_table_id) {\n throw new RbqlIOHandlingError(\"JOIN queries are currently not supported in vscode.dev web version.\");\n }\n\n get_warnings() {\n return [];\n };\n}\n\nasync function rbql_query_web(query_text, input_document, input_delim, input_policy, output_delim, output_policy, output_warnings, with_headers, comment_prefix=null) {\n let user_init_code = ''; // TODO find a way to have init code.\n let join_tables_registry = new VSCodeTableRegistry(); // TODO find a way to have join registry.\n let input_iterator = new VSCodeRecordIterator(input_document, input_delim, input_policy, with_headers, comment_prefix);\n let output_writer = new VSCodeWriter(output_delim, output_policy);\n await rbql.query(query_text, input_iterator, output_writer, output_warnings, join_tables_registry, user_init_code);\n return output_writer.output_lines;\n}\n\n\nclass VSCodeFileSystemCSVRegistry extends rbql.RBQLTableRegistry {\n constructor(vscode_global_state, input_file_dir, delim, policy, encoding, has_header=false, comment_prefix=null, options=null) {\n super();\n this.vscode_global_state = vscode_global_state;\n this.input_file_dir = input_file_dir;\n this.delim = delim;\n this.policy = policy;\n this.encoding = encoding;\n this.has_header = has_header;\n this.comment_prefix = comment_prefix;\n this.stream = null;\n this.record_iterator = null;\n\n this.options = options;\n this.bulk_input_path = null;\n this.table_path = null;\n }\n\n get_iterator_by_table_id(table_id) {\n this.table_path = find_table_path(this.vscode_global_state, this.input_file_dir, table_id);\n if (this.table_path === null) {\n throw new RbqlIOHandlingError(`Unable to find join table \"${table_id}\"`);\n }\n if (this.options && this.options['bulk_read']) {\n this.bulk_input_path = this.table_path;\n } else {\n this.stream = fs.createReadStream(this.table_path);\n }\n this.record_iterator = new rbql_csv.CSVRecordIterator(this.stream, this.bulk_input_path, this.encoding, this.delim, this.policy, this.has_header, this.comment_prefix, table_id, 'b');\n return this.record_iterator;\n };\n\n get_warnings(output_warnings) {\n if (this.record_iterator && this.has_header) {\n output_warnings.push(`The first record in JOIN file ${path.basename(this.table_path)} was also treated as header (and skipped)`);\n }\n }\n}\n\n\nasync function rbql_query_node(vscode_global_state, query_text, input_path, input_delim, input_policy, output_path, output_delim, output_policy, csv_encoding, output_warnings, with_headers=false, comment_prefix=null, user_init_code='', options=null) {\n let input_stream = null;\n let bulk_input_path = null;\n if (options && options['bulk_read'] && input_path) {\n bulk_input_path = input_path;\n } else {\n input_stream = input_path === null ? process.stdin : fs.createReadStream(input_path);\n }\n let [output_stream, close_output_on_finish] = output_path === null ? [process.stdout, false] : [fs.createWriteStream(output_path), true];\n if (input_delim == '\"' && input_policy == 'quoted')\n throw new RbqlIOHandlingError('Double quote delimiter is incompatible with \"quoted\" policy');\n if (csv_encoding == 'latin-1')\n csv_encoding = 'binary';\n if (!rbql_csv.is_ascii(query_text) && csv_encoding == 'binary')\n throw new RbqlIOHandlingError('To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary');\n if ((!rbql_csv.is_ascii(input_delim) || !rbql_csv.is_ascii(output_delim)) && csv_encoding == 'binary')\n throw new RbqlIOHandlingError('To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary');\n\n let default_init_source_path = path.join(os.homedir(), '.rbql_init_source.js');\n if (user_init_code == '' && fs.existsSync(default_init_source_path)) {\n user_init_code = rbql_csv.read_user_init_code(default_init_source_path);\n }\n let input_file_dir = input_path ? path.dirname(input_path) : null;\n let join_tables_registry = new VSCodeFileSystemCSVRegistry(vscode_global_state, input_file_dir, input_delim, input_policy, csv_encoding, with_headers, comment_prefix, options);\n let input_iterator = new rbql_csv.CSVRecordIterator(input_stream, bulk_input_path, csv_encoding, input_delim, input_policy, with_headers, comment_prefix);\n let output_writer = new rbql_csv.CSVWriter(output_stream, close_output_on_finish, csv_encoding, output_delim, output_policy);\n\n await rbql.query(query_text, input_iterator, output_writer, output_warnings, join_tables_registry, user_init_code);\n join_tables_registry.get_warnings(output_warnings);\n}\n\n\nmodule.exports.make_table_name_key = make_table_name_key;\nmodule.exports.find_table_path = find_table_path;\nmodule.exports.read_header = read_header;\nmodule.exports.rbql_query_web = rbql_query_web;\nmodule.exports.rbql_query_node = rbql_query_node;\nmodule.exports.get_header_line = get_header_line;\nmodule.exports.populate_optimistic_rfc_csv_record_map = populate_optimistic_rfc_csv_record_map;\nmodule.exports.get_default_js_udf_content = get_default_js_udf_content;\nmodule.exports.get_default_python_udf_content = get_default_python_udf_content;\nmodule.exports.align_columns = align_columns;\nmodule.exports.shrink_columns = shrink_columns;\nmodule.exports.calc_column_stats = calc_column_stats;\nmodule.exports.adjust_column_stats = adjust_column_stats;\nmodule.exports.update_subcomponent_stats = update_subcomponent_stats;\nmodule.exports.align_field = align_field;\n","let field_regular_expression = '\"((?:[^\"]*\"\")*[^\"]*)\"';\nlet field_rgx = new RegExp('^' + field_regular_expression);\nlet field_rgx_external_whitespaces = new RegExp('^ *' + field_regular_expression + ' *');\n\n\n// TODO consider making this file (and rbql.js) both node and browser compatible: https://caolan.org/posts/writing_for_node_and_the_browser.html\n\n\nfunction split_lines(text) {\n return text.split(/\\r\\n|\\r|\\n/);\n}\n\n\nfunction extract_next_field(src, dlm, preserve_quotes_and_whitespaces, allow_external_whitespaces, cidx, result) {\n var warning = false;\n let src_cur = src.substring(cidx);\n let rgx = allow_external_whitespaces ? field_rgx_external_whitespaces : field_rgx;\n let match_obj = rgx.exec(src_cur);\n if (match_obj !== null) {\n let match_end = match_obj[0].length;\n if (cidx + match_end == src.length || src[cidx + match_end] == dlm) {\n if (preserve_quotes_and_whitespaces) {\n result.push(match_obj[0]);\n } else {\n result.push(match_obj[1].replace(/\"\"/g, '\"'));\n }\n return [cidx + match_end + 1, false];\n }\n warning = true;\n }\n var uidx = src.indexOf(dlm, cidx);\n if (uidx == -1)\n uidx = src.length;\n var field = src.substring(cidx, uidx);\n warning = warning || field.indexOf('\"') != -1;\n result.push(field);\n return [uidx + 1, warning];\n}\n\n\nfunction split_quoted_str(src, dlm, preserve_quotes_and_whitespaces=false) {\n // This function is newline-agnostic i.e. it can also split records with multiline fields.\n if (src.indexOf('\"') == -1) // Optimization for most common case\n return [src.split(dlm), false];\n var result = [];\n var cidx = 0;\n var warning = false;\n let allow_external_whitespaces = dlm != ' ';\n while (cidx < src.length) {\n var extraction_report = extract_next_field(src, dlm, preserve_quotes_and_whitespaces, allow_external_whitespaces, cidx, result);\n cidx = extraction_report[0];\n warning = warning || extraction_report[1];\n }\n if (src.charAt(src.length - 1) == dlm)\n result.push('');\n return [result, warning];\n}\n\n\nfunction quote_field(src, delim) {\n if (src.indexOf(delim) != -1 || src.indexOf('\"') != -1) {\n var escaped = src.replace(/\"/g, '\"\"');\n return `\"${escaped}\"`;\n }\n return src;\n}\n\n\nfunction rfc_quote_field(src, delim) {\n if (src.indexOf(delim) != -1 || src.indexOf('\"') != -1 || src.indexOf('\\n') != -1 || src.indexOf('\\r') != -1) {\n var escaped = src.replace(/\"/g, '\"\"');\n return `\"${escaped}\"`;\n }\n return src;\n}\n\n\nfunction unquote_field(field) {\n let rgx = new RegExp('^' + ' *' + field_regular_expression + ' *$');\n let match_obj = rgx.exec(field);\n if (match_obj !== null) {\n return match_obj[1].replace(/\"\"/g, '\"');\n }\n return field;\n}\n\n\nfunction unquote_fields(fields) {\n return fields.map(unquote_field);\n}\n\n\nfunction split_whitespace_separated_str(src, preserve_whitespaces=false) {\n var rgxp = preserve_whitespaces ? new RegExp(' *[^ ]+ *', 'g') : new RegExp('[^ ]+', 'g');\n let result = [];\n let match_obj = null;\n while((match_obj = rgxp.exec(src)) !== null) {\n result.push(match_obj[0]);\n }\n if (preserve_whitespaces) {\n for (let i = 0; i < result.length - 1; i++) {\n result[i] = result[i].slice(0, -1);\n }\n }\n return result;\n}\n\n\nfunction smart_split(src, dlm, policy, preserve_quotes_and_whitespaces) {\n if (policy === 'simple')\n return [src.split(dlm), false];\n if (policy === 'whitespace')\n return [split_whitespace_separated_str(src, preserve_quotes_and_whitespaces), false];\n if (policy === 'monocolumn')\n return [[src], false];\n return split_quoted_str(src, dlm, preserve_quotes_and_whitespaces);\n}\n\n\nfunction accumulate_rfc_line_into_record(external_rfc_line_buffer, current_line, comment_prefix=null) {\n // Return null if the current line yields no record.\n // Return a record string if the current line yields the record and cleans the external line buffer.\n if (comment_prefix !== null && external_rfc_line_buffer.length == 0 && current_line.startsWith(comment_prefix))\n return null;\n let match_list = current_line.match(/\"/g);\n let has_unbalanced_double_quote = match_list && match_list.length % 2 == 1;\n if (external_rfc_line_buffer.length == 0 && !has_unbalanced_double_quote) {\n return current_line;\n } else if (external_rfc_line_buffer.length == 0 && has_unbalanced_double_quote) {\n external_rfc_line_buffer.push(current_line);\n } else if (!has_unbalanced_double_quote) {\n external_rfc_line_buffer.push(current_line);\n } else {\n external_rfc_line_buffer.push(current_line);\n let multiline_row = external_rfc_line_buffer.join('\\n');\n external_rfc_line_buffer.splice(0, external_rfc_line_buffer.length); // Cleanup the external buffer.\n return multiline_row;\n }\n return null;\n}\n\n\nmodule.exports.split_quoted_str = split_quoted_str;\nmodule.exports.split_whitespace_separated_str = split_whitespace_separated_str;\nmodule.exports.smart_split = smart_split;\nmodule.exports.quote_field = quote_field;\nmodule.exports.rfc_quote_field = rfc_quote_field;\nmodule.exports.unquote_field = unquote_field;\nmodule.exports.unquote_fields = unquote_fields;\nmodule.exports.split_lines = split_lines;\nmodule.exports.accumulate_rfc_line_into_record = accumulate_rfc_line_into_record;\n","(function(exports){\n// The magic line above is to make the module both browser and Node compatible, see https://stackoverflow.com/questions/3225251/how-can-i-share-code-between-node-js-and-the-browser\n\n// This module works with records only. It is CSV-agnostic.\n// Do not add CSV-related logic or variables/functions/objects like \"delim\", \"separator\" etc\n\n\nclass RbqlParsingError extends Error {}\nclass RbqlRuntimeError extends Error {}\nclass AssertionError extends Error {}\nclass RbqlIOHandlingError extends Error {}\n\n\nclass InternalBadFieldError extends Error {\n constructor(bad_idx, ...params) {\n super(...params);\n this.bad_idx = bad_idx;\n }\n}\n\n\nfunction assert(condition, message=null) {\n if (!condition) {\n if (!message) {\n message = 'Assertion error';\n }\n throw new AssertionError(message);\n }\n}\n\n\nfunction replace_all(src, search, replacement) {\n return src.split(search).join(replacement);\n}\n\n\nclass RBQLContext {\n constructor(query_text, input_iterator, output_writer, user_init_code) {\n this.query_text = query_text;\n this.input_iterator = input_iterator;\n this.writer = output_writer;\n this.user_init_code = user_init_code;\n\n this.unnest_list = null;\n this.top_count = null;\n\n this.like_regex_cache = new Map();\n\n this.sort_key_expression = null;\n\n this.aggregation_stage = 0;\n this.aggregation_key_expression = null;\n this.functional_aggregators = [];\n\n this.join_map_impl = null;\n this.join_map = null;\n this.lhs_join_var_expression = null;\n\n this.where_expression = null;\n\n this.select_expression = null;\n\n this.update_expressions = null;\n\n this.variables_init_code = null;\n }\n}\n\nvar query_context = null; // Needs to be global for MIN(), MAX(), etc functions. TODO find a way to make it local.\n\n\nconst wrong_aggregation_usage_error = 'Usage of RBQL aggregation functions inside JavaScript expressions is not allowed, see the docs';\nconst RBQL_VERSION = '0.25.0';\n\n\nfunction check_if_brackets_match(opening_bracket, closing_bracket) {\n return (opening_bracket == '[' && closing_bracket == ']') || (opening_bracket == '(' && closing_bracket == ')') || (opening_bracket == '{' && closing_bracket == '}');\n}\n\n\nfunction parse_root_bracket_level_text_spans(select_expression) {\n let text_spans = []; // parts of text separated by commas at the root parenthesis level\n let last_pos = 0;\n let bracket_stack = [];\n for (let i = 0; i < select_expression.length; i++) {\n let cur_char = select_expression[i];\n if (cur_char == ',' && bracket_stack.length == 0) {\n text_spans.push(select_expression.substring(last_pos, i));\n last_pos = i + 1;\n } else if (['[', '{', '('].indexOf(cur_char) != -1) {\n bracket_stack.push(cur_char);\n } else if ([']', '}', ')'].indexOf(cur_char) != -1) {\n if (bracket_stack.length && check_if_brackets_match(bracket_stack[bracket_stack.length - 1], cur_char)) {\n bracket_stack.pop();\n } else {\n throw new RbqlParsingError(`Unable to parse column headers in SELECT expression: No matching opening bracket for closing \"${cur_char}\"`);\n }\n }\n }\n if (bracket_stack.length) {\n throw new RbqlParsingError(`Unable to parse column headers in SELECT expression: No matching closing bracket for opening \"${bracket_stack[0]}\"`);\n }\n text_spans.push(select_expression.substring(last_pos, select_expression.length));\n text_spans = text_spans.map(span => span.trim());\n return text_spans;\n}\n\n\nfunction unquote_string(quoted_str) {\n // It's possible to use eval here to unqoute the quoted_column_name, but it would be a little barbaric, let's do it manually instead\n if (!quoted_str || quoted_str.length < 2)\n return null;\n if (quoted_str[0] == \"'\" && quoted_str[quoted_str.length - 1] == \"'\") {\n return quoted_str.substring(1, quoted_str.length - 1).replace(/\\\\'/g, \"'\").replace(/\\\\\\\\/g, \"\\\\\");\n } else if (quoted_str[0] == '\"' && quoted_str[quoted_str.length - 1] == '\"') {\n return quoted_str.substring(1, quoted_str.length - 1).replace(/\\\\\"/g, '\"').replace(/\\\\\\\\/g, \"\\\\\");\n } else {\n return null;\n }\n}\n\n\nfunction column_info_from_text_span(text_span, string_literals) {\n // This function is a rough equivalent of \"column_info_from_node()\" function in python version of RBQL\n text_span = text_span.trim();\n let rbql_star_marker = '__RBQL_INTERNAL_STAR';\n let simple_var_match = /^[_a-zA-Z][_a-zA-Z0-9]*$/.exec(text_span);\n let attribute_match = /^([ab])\\.([_a-zA-Z][_a-zA-Z0-9]*)$/.exec(text_span);\n let subscript_int_match = /^([ab])\\[([0-9]+)\\]$/.exec(text_span);\n let subscript_str_match = /^([ab])\\[___RBQL_STRING_LITERAL([0-9]+)___\\]$/.exec(text_span);\n if (simple_var_match !== null) {\n if (text_span == rbql_star_marker)\n return {table_name: null, column_index: null, column_name: null, is_star: true};\n if (text_span.startsWith('___RBQL_STRING_LITERAL'))\n return null;\n let match = /^([ab])([0-9]+)$/.exec(text_span);\n if (match !== null) {\n return {table_name: match[1], column_index: parseInt(match[2]) - 1, column_name: null, is_star: false};\n }\n // Some examples for this branch: NR, NF\n return {table_name: null, column_index: null, column_name: text_span, is_star: false};\n } else if (attribute_match !== null) {\n let table_name = attribute_match[1];\n let column_name = attribute_match[2];\n if (column_name == rbql_star_marker) {\n return {table_name: table_name, column_index: null, column_name: null, is_star: true};\n }\n return {table_name: null, column_index: null, column_name: column_name, is_star: false};\n } else if (subscript_int_match != null) {\n let table_name = subscript_int_match[1];\n let column_index = parseInt(subscript_int_match[2]) - 1;\n return {table_name: table_name, column_index: column_index, column_name: null, is_star: false};\n } else if (subscript_str_match != null) {\n let table_name = subscript_str_match[1];\n let replaced_string_literal_id = subscript_str_match[2];\n if (replaced_string_literal_id < string_literals.length) {\n let quoted_column_name = string_literals[replaced_string_literal_id];\n let unquoted_column_name = unquote_string(quoted_column_name);\n if (unquoted_column_name !== null && unquoted_column_name !== undefined) {\n return {table_name: null, column_index: null, column_name: unquoted_column_name, is_star: false};\n }\n }\n }\n return null;\n}\n\n\nfunction adhoc_parse_select_expression_to_column_infos(select_expression, string_literals) {\n // It is acceptable for the algorithm to provide null column name when it could be theorethically possible to deduce the name.\n // I.e. this algorithm guarantees precision but doesn't guarantee completeness in all theorethically possible queries.\n // Although the algorithm should be complete in all practical scenarios, i.e. it should be hard to come up with the query that doesn't produce complete set of column names.\n // The null column name just means that the output column will be named as col{i}, so the failure to detect the proper column name can be tolerated.\n // Specifically this function guarantees the following:\n // 1. The number of column_infos is correct and will match the number of fields in each record in the output - otherwise the exception should be thrown\n // 2. If column_info at pos j is not null, it is guaranteed to correctly represent that column name in the output\n let text_spans = parse_root_bracket_level_text_spans(select_expression);\n let column_infos = text_spans.map(ts => column_info_from_text_span(ts, string_literals));\n return column_infos;\n}\n\n\nfunction stable_compare(a, b) {\n for (var i = 0; i < a.length; i++) {\n if (a[i] !== b[i])\n return a[i] < b[i] ? -1 : 1;\n }\n}\n\n\nfunction safe_get(record, idx) {\n return idx < record.length ? record[idx] : null;\n}\n\n\nfunction safe_join_get(record, idx) {\n if (idx < record.length) {\n return record[idx];\n }\n throw new InternalBadFieldError(idx);\n}\n\n\nfunction safe_set(record, idx, value) {\n if (idx < record.length) {\n record[idx] = value;\n } else {\n throw new InternalBadFieldError(idx);\n }\n}\n\n\nfunction regexp_escape(text) {\n // From here: https://stackoverflow.com/a/6969486/2898283\n return text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'); // $& means the whole matched text\n}\n\n\nfunction like_to_regex(pattern) {\n let p = 0;\n let i = 0;\n let converted = '';\n while (i < pattern.length) {\n if (pattern.charAt(i) == '_' || pattern.charAt(i) == '%') {\n converted += regexp_escape(pattern.substring(p, i));\n p = i + 1;\n if (pattern.charAt(i) == '_') {\n converted += '.';\n } else {\n converted += '.*';\n }\n }\n i += 1;\n }\n converted += regexp_escape(pattern.substring(p, i));\n return '^' + converted + '$';\n}\n\n\nfunction like(text, pattern) {\n let matcher = query_context.like_regex_cache.get(pattern);\n if (matcher === undefined) {\n matcher = new RegExp(like_to_regex(pattern));\n query_context.like_regex_cache.set(pattern, matcher);\n }\n return matcher.test(text);\n}\nconst LIKE = like;\n\n\nclass RBQLAggregationToken {\n constructor(marker_id, value) {\n this.marker_id = marker_id;\n this.value = value;\n }\n\n toString() {\n throw new RbqlParsingError(wrong_aggregation_usage_error);\n }\n}\n\n\nclass UnnestMarker {}\n\n\nfunction UNNEST(vals) {\n if (query_context.unnest_list !== null) {\n // Technically we can support multiple UNNEST's but the implementation/algorithm is more complex and just doesn't worth it\n throw new RbqlParsingError('Only one UNNEST is allowed per query');\n }\n query_context.unnest_list = vals;\n return new UnnestMarker();\n}\nconst unnest = UNNEST;\nconst Unnest = UNNEST;\nconst UNFOLD = UNNEST; // \"UNFOLD\" is deprecated, just for backward compatibility\n\n\nfunction parse_number(val) {\n // We can do a more pedantic number test like `/^ *-{0,1}[0-9]+\\.{0,1}[0-9]* *$/.test(val)`, but user will probably use just Number(val) or parseInt/parseFloat\n let result = Number(val);\n if (isNaN(result)) {\n throw new RbqlRuntimeError(`Unable to convert value \"${val}\" to a number. MIN, MAX, SUM, AVG, MEDIAN and VARIANCE aggregate functions convert their string arguments to numeric values`);\n }\n return result;\n}\n\n\nclass MinAggregator {\n constructor() {\n this.stats = new Map();\n }\n\n increment(key, val) {\n val = parse_number(val);\n var cur_aggr = this.stats.get(key);\n if (cur_aggr === undefined) {\n this.stats.set(key, val);\n } else {\n this.stats.set(key, Math.min(cur_aggr, val));\n }\n }\n\n get_final(key) {\n return this.stats.get(key);\n }\n}\n\n\n\nclass MaxAggregator {\n constructor() {\n this.stats = new Map();\n }\n\n increment(key, val) {\n val = parse_number(val);\n var cur_aggr = this.stats.get(key);\n if (cur_aggr === undefined) {\n this.stats.set(key, val);\n } else {\n this.stats.set(key, Math.max(cur_aggr, val));\n }\n }\n\n get_final(key) {\n return this.stats.get(key);\n }\n}\n\n\nclass SumAggregator {\n constructor() {\n this.stats = new Map();\n }\n\n increment(key, val) {\n val = parse_number(val);\n var cur_aggr = this.stats.get(key);\n if (cur_aggr === undefined) {\n this.stats.set(key, val);\n } else {\n this.stats.set(key, cur_aggr + val);\n }\n }\n\n get_final(key) {\n return this.stats.get(key);\n }\n}\n\n\nclass AvgAggregator {\n constructor() {\n this.stats = new Map();\n }\n\n increment(key, val) {\n val = parse_number(val);\n var cur_aggr = this.stats.get(key);\n if (cur_aggr === undefined) {\n this.stats.set(key, [val, 1]);\n } else {\n var cur_sum = cur_aggr[0];\n var cur_cnt = cur_aggr[1];\n this.stats.set(key, [cur_sum + val, cur_cnt + 1]);\n }\n }\n\n get_final(key) {\n var cur_aggr = this.stats.get(key);\n var cur_sum = cur_aggr[0];\n var cur_cnt = cur_aggr[1];\n var avg = cur_sum / cur_cnt;\n return avg;\n }\n}\n\n\nclass VarianceAggregator {\n constructor() {\n this.stats = new Map();\n }\n\n increment(key, val) {\n val = parse_number(val);\n var cur_aggr = this.stats.get(key);\n if (cur_aggr === undefined) {\n this.stats.set(key, [val, val * val, 1]);\n } else {\n var cur_sum = cur_aggr[0];\n var cur_sum_sq = cur_aggr[1];\n var cur_cnt = cur_aggr[2];\n this.stats.set(key, [cur_sum + val, cur_sum_sq + val * val, cur_cnt + 1]);\n }\n }\n\n get_final(key) {\n var cur_aggr = this.stats.get(key);\n var cur_sum = cur_aggr[0];\n var cur_sum_sq = cur_aggr[1];\n var cur_cnt = cur_aggr[2];\n var avg_val = cur_sum / cur_cnt;\n var variance = cur_sum_sq / cur_cnt - avg_val * avg_val;\n return variance;\n }\n}\n\n\nclass MedianAggregator {\n constructor() {\n this.stats = new Map();\n }\n\n increment(key, val) {\n val = parse_number(val);\n var cur_aggr = this.stats.get(key);\n if (cur_aggr === undefined) {\n this.stats.set(key, [val]);\n } else {\n cur_aggr.push(val);\n }\n }\n\n get_final(key) {\n var cur_aggr = this.stats.get(key);\n cur_aggr.sort(function(a, b) { return a - b; });\n var m = Math.floor(cur_aggr.length / 2);\n if (cur_aggr.length % 2) {\n return cur_aggr[m];\n } else {\n return (cur_aggr[m - 1] + cur_aggr[m]) / 2.0;\n }\n }\n}\n\n\nclass CountAggregator {\n constructor() {\n this.stats = new Map();\n }\n\n increment(key, val) {\n var cur_aggr = this.stats.get(key);\n if (cur_aggr === undefined) {\n this.stats.set(key, 1);\n } else {\n this.stats.set(key, cur_aggr + 1);\n }\n }\n\n get_final(key) {\n return this.stats.get(key);\n }\n}\n\n\nclass ArrayAggAggregator {\n constructor(post_proc=null) {\n this.post_proc = post_proc;\n this.stats = new Map();\n }\n\n increment(key, val) {\n let cur_aggr = this.stats.get(key);\n if (cur_aggr === undefined) {\n this.stats.set(key, [val]);\n } else {\n cur_aggr.push(val);\n }\n }\n\n get_final(key) {\n let cur_aggr = this.stats.get(key);\n if (this.post_proc === null)\n return cur_aggr;\n return this.post_proc(cur_aggr);\n }\n}\n\n\nclass ConstGroupVerifier {\n constructor(output_index) {\n this.output_index = output_index;\n this.const_values = new Map();\n }\n\n increment(key, value) {\n var old_value = this.const_values.get(key);\n if (old_value === undefined) {\n this.const_values.set(key, value);\n } else if (old_value != value) {\n throw new RbqlRuntimeError(`Invalid aggregate expression: non-constant values in output column ${this.output_index + 1}. E.g. \"${old_value}\" and \"${value}\"`);\n }\n }\n\n get_final(key) {\n return this.const_values.get(key);\n }\n}\n\n\nfunction init_aggregator(generator_name, val, post_proc=null) {\n query_context.aggregation_stage = 1;\n var res = new RBQLAggregationToken(query_context.functional_aggregators.length, val);\n if (post_proc === null) {\n query_context.functional_aggregators.push(new generator_name());\n } else {\n query_context.functional_aggregators.push(new generator_name(post_proc));\n }\n return res;\n}\n\n\nfunction MIN(val) {\n return query_context.aggregation_stage < 2 ? init_aggregator(MinAggregator, val) : val;\n}\nconst min = MIN;\nconst Min = MIN;\n\n\nfunction MAX(val) {\n return query_context.aggregation_stage < 2 ? init_aggregator(MaxAggregator, val) : val;\n}\nconst max = MAX;\nconst Max = MAX;\n\nfunction COUNT(val) {\n return query_context.aggregation_stage < 2 ? init_aggregator(CountAggregator, 1) : 1;\n}\nconst count = COUNT;\nconst Count = COUNT;\n\nfunction SUM(val) {\n return query_context.aggregation_stage < 2 ? init_aggregator(SumAggregator, val) : val;\n}\nconst sum = SUM;\nconst Sum = SUM;\n\nfunction AVG(val) {\n return query_context.aggregation_stage < 2 ? init_aggregator(AvgAggregator, val) : val;\n}\nconst avg = AVG;\nconst Avg = AVG;\n\nfunction VARIANCE(val) {\n return query_context.aggregation_stage < 2 ? init_aggregator(VarianceAggregator, val) : val;\n}\nconst variance = VARIANCE;\nconst Variance = VARIANCE;\n\nfunction MEDIAN(val) {\n return query_context.aggregation_stage < 2 ? init_aggregator(MedianAggregator, val) : val;\n}\nconst median = MEDIAN;\nconst Median = MEDIAN;\n\nfunction ARRAY_AGG(val, post_proc=null) {\n return query_context.aggregation_stage < 2 ? init_aggregator(ArrayAggAggregator, val, post_proc) : val;\n}\nconst array_agg = ARRAY_AGG;\nconst FOLD = ARRAY_AGG; // \"FOLD\" is deprecated, just for backward compatibility\n\n\nfunction add_to_set(dst_set, value) {\n var len_before = dst_set.size;\n dst_set.add(value);\n return len_before != dst_set.size;\n}\n\n\nclass TopWriter {\n constructor(subwriter, top_count) {\n this.subwriter = subwriter;\n this.NW = 0;\n this.top_count = top_count;\n }\n\n async write(record) {\n if (this.top_count !== null && this.NW >= this.top_count)\n return false;\n await this.subwriter.write(record);\n this.NW += 1;\n return true;\n }\n\n async finish() {\n await this.subwriter.finish();\n }\n}\n\n\nclass UniqWriter {\n constructor(subwriter) {\n this.subwriter = subwriter;\n this.seen = new Set();\n }\n\n async write(record) {\n if (!add_to_set(this.seen, JSON.stringify(record)))\n return true;\n if (!await this.subwriter.write(record))\n return false;\n return true;\n }\n\n async finish() {\n await this.subwriter.finish();\n }\n}\n\n\nclass UniqCountWriter {\n constructor(subwriter) {\n this.subwriter = subwriter;\n this.records = new Map();\n }\n\n async write(record) {\n var key = JSON.stringify(record);\n var old_val = this.records.get(key);\n if (old_val) {\n old_val[0] += 1;\n } else {\n this.records.set(key, [1, record]);\n }\n return true;\n }\n\n async finish() {\n for (var [key, value] of this.records) {\n let [count, record] = value;\n record.unshift(count);\n if (!await this.subwriter.write(record))\n break;\n }\n await this.subwriter.finish();\n }\n}\n\n\nclass SortedWriter {\n constructor(subwriter, reverse_sort) {\n this.subwriter = subwriter;\n this.reverse_sort = reverse_sort;\n this.unsorted_entries = [];\n }\n\n async write(stable_entry) {\n this.unsorted_entries.push(stable_entry);\n return true;\n }\n\n async finish() {\n var unsorted_entries = this.unsorted_entries;\n unsorted_entries.sort(stable_compare);\n if (this.reverse_sort)\n unsorted_entries.reverse();\n for (var i = 0; i < unsorted_entries.length; i++) {\n var entry = unsorted_entries[i];\n if (!await this.subwriter.write(entry[entry.length - 1]))\n break;\n }\n await this.subwriter.finish();\n }\n}\n\n\nclass AggregateWriter {\n constructor(subwriter) {\n this.subwriter = subwriter;\n this.aggregators = [];\n this.aggregation_keys = new Set();\n }\n\n async finish() {\n var all_keys = Array.from(this.aggregation_keys);\n all_keys.sort();\n for (var i = 0; i < all_keys.length; i++) {\n var key = all_keys[i];\n var out_fields = [];\n for (var ag of this.aggregators) {\n out_fields.push(ag.get_final(key));\n }\n if (!await this.subwriter.write(out_fields))\n break;\n }\n await this.subwriter.finish();\n }\n}\n\n\nclass InnerJoiner {\n constructor(join_map) {\n this.join_map = join_map;\n }\n\n get_rhs(lhs_key) {\n return this.join_map.get_join_records(lhs_key);\n }\n}\n\n\nclass LeftJoiner {\n constructor(join_map) {\n this.join_map = join_map;\n this.null_record = [[null, join_map.max_record_len, Array(join_map.max_record_len).fill(null)]];\n }\n\n get_rhs(lhs_key) {\n let result = this.join_map.get_join_records(lhs_key);\n if (result.length == 0) {\n return this.null_record;\n }\n return result;\n }\n}\n\n\nclass StrictLeftJoiner {\n constructor(join_map) {\n this.join_map = join_map;\n }\n\n get_rhs(lhs_key) {\n let result = this.join_map.get_join_records(lhs_key);\n if (result.length != 1) {\n throw new RbqlRuntimeError('In \"STRICT LEFT JOIN\" each key in A must have exactly one match in B. Bad A key: \"' + lhs_key + '\"');\n }\n return result;\n }\n}\n\n\nfunction select_except(src, except_fields) {\n let result = [];\n for (let i = 0; i < src.length; i++) {\n if (except_fields.indexOf(i) == -1)\n result.push(src[i]);\n }\n return result;\n}\n\n\nasync function select_simple(sort_key, NR, out_fields) {\n if (query_context.sort_key_expression !== null) {\n var sort_entry = sort_key.concat([NR, out_fields]);\n if (!await query_context.writer.write(sort_entry))\n return false;\n } else {\n if (!await query_context.writer.write(out_fields))\n return false;\n }\n return true;\n}\n\n\nfunction select_aggregated(key, transparent_values) {\n if (key !== null) {\n key = JSON.stringify(key);\n }\n if (query_context.aggregation_stage === 1) {\n if (!(query_context.writer instanceof TopWriter)) {\n throw new RbqlParsingError('\"ORDER BY\", \"UPDATE\" and \"DISTINCT\" keywords are not allowed in aggregate queries');\n }\n query_context.writer = new AggregateWriter(query_context.writer);\n let num_aggregators_found = 0;\n for (var i = 0; i < transparent_values.length; i++) {\n var trans_value = transparent_values[i];\n if (trans_value instanceof RBQLAggregationToken) {\n query_context.writer.aggregators.push(query_context.functional_aggregators[trans_value.marker_id]);\n query_context.writer.aggregators[query_context.writer.aggregators.length - 1].increment(key, trans_value.value);\n num_aggregators_found += 1;\n } else {\n query_context.writer.aggregators.push(new ConstGroupVerifier(query_context.writer.aggregators.length));\n query_context.writer.aggregators[query_context.writer.aggregators.length - 1].increment(key, trans_value);\n }\n }\n if (num_aggregators_found != query_context.functional_aggregators.length) {\n throw new RbqlParsingError(wrong_aggregation_usage_error);\n }\n query_context.aggregation_stage = 2;\n } else {\n for (var i = 0; i < transparent_values.length; i++) {\n var trans_value = transparent_values[i];\n query_context.writer.aggregators[i].increment(key, trans_value);\n }\n }\n query_context.writer.aggregation_keys.add(key);\n}\n\n\nasync function select_unnested(sort_key, NR, folded_fields) {\n let out_fields = folded_fields.slice();\n let unnest_pos = folded_fields.findIndex(val => val instanceof UnnestMarker);\n for (var i = 0; i < query_context.unnest_list.length; i++) {\n out_fields[unnest_pos] = query_context.unnest_list[i];\n if (!await select_simple(sort_key, NR, out_fields.slice()))\n return false;\n }\n return true;\n}\n\n\nconst PROCESS_SELECT_COMMON = `\n__RBQLMP__variables_init_code\nif (__RBQLMP__where_expression) {\n let out_fields = __RBQLMP__select_expression;\n if (query_context.aggregation_stage > 0) {\n let key = __RBQLMP__aggregation_key_expression;\n select_aggregated(key, out_fields);\n } else {\n let sort_key = [__RBQLMP__sort_key_expression];\n if (query_context.unnest_list !== null) {\n if (!await select_unnested(sort_key, NR, out_fields))\n stop_flag = true;\n } else {\n if (!await select_simple(sort_key, NR, out_fields))\n stop_flag = true;\n }\n }\n}\n`;\n\n\nconst PROCESS_SELECT_SIMPLE = `\nlet star_fields = record_a;\n__CODE__\n`;\n\n\nconst PROCESS_SELECT_JOIN = `\nlet join_matches = query_context.join_map.get_rhs(__RBQLMP__lhs_join_var_expression);\nfor (let join_match of join_matches) {\n let [bNR, bNF, record_b] = join_match;\n let star_fields = record_a.concat(record_b);\n __CODE__\n if (stop_flag)\n break;\n}\n`;\n\n\nconst PROCESS_UPDATE_JOIN = `\nlet join_matches = query_context.join_map.get_rhs(__RBQLMP__lhs_join_var_expression);\nif (join_matches.length > 1)\n throw new RbqlRuntimeError('More than one record in UPDATE query matched a key from the input table in the join table');\nlet record_b = null;\nlet bNR = null;\nlet bNF = null;\nif (join_matches.length == 1)\n [bNR, bNF, record_b] = join_matches[0];\nlet up_fields = record_a;\n__RBQLMP__variables_init_code\nif (join_matches.length == 1 && (__RBQLMP__where_expression)) {\n NU += 1;\n __RBQLMP__update_expressions\n}\nif (!await query_context.writer.write(up_fields))\n stop_flag = true;\n`;\n\n\nconst PROCESS_UPDATE_SIMPLE = `\nlet up_fields = record_a;\n__RBQLMP__variables_init_code\nif (__RBQLMP__where_expression) {\n NU += 1;\n __RBQLMP__update_expressions\n}\nif (!await query_context.writer.write(up_fields))\n stop_flag = true;\n`;\n\n\nconst MAIN_LOOP_BODY = `\n__USER_INIT_CODE__\n\nlet NU = 0;\nlet NR = 0;\n\nlet stop_flag = false;\nwhile (!stop_flag) {\n let record_a = await query_context.input_iterator.get_record();\n if (record_a === null)\n break;\n NR += 1;\n let NF = record_a.length;\n query_context.unnest_list = null; // TODO optimize, don't need to set this every iteration\n try {\n __CODE__\n } catch (e) {\n if (e.constructor.name === 'InternalBadFieldError') {\n throw new RbqlRuntimeError(\\`No \"a\\${e.bad_idx + 1}\" field at record \\${NR}\\`);\n } else if (e.constructor.name === 'RbqlParsingError') {\n throw(e);\n } else {\n throw new RbqlRuntimeError(\\`At record \\${NR}, Details: \\${e.message}\\`);\n }\n }\n}\n`;\n\n\nfunction embed_expression(parent_code, child_placeholder, child_expression) {\n return replace_all(parent_code, child_placeholder, child_expression);\n}\n\n\nfunction embed_code(parent_code, child_placeholder, child_code) {\n let parent_lines = parent_code.split('\\n');\n let child_lines = child_code.split('\\n');\n for (let i = 0; i < parent_lines.length; i++) {\n let pos = parent_lines[i].indexOf(child_placeholder);\n if (pos == -1)\n continue;\n assert(pos % 4 == 0);\n let placeholder_indentation = parent_lines[i].substring(0, pos);\n child_lines = child_lines.map(l => placeholder_indentation + l);\n let result_lines = parent_lines.slice(0, i).concat(child_lines).concat(parent_lines.slice(i + 1));\n return result_lines.join('\\n') + '\\n';\n }\n assert(false);\n}\n\n\nfunction generate_main_loop_code(query_context) {\n let is_select_query = query_context.select_expression !== null;\n let is_join_query = query_context.join_map !== null;\n let where_expression = query_context.where_expression === null ? 'true' : query_context.where_expression;\n let aggregation_key_expression = query_context.aggregation_key_expression === null ? 'null' : query_context.aggregation_key_expression;\n let sort_key_expression = query_context.sort_key_expression === null ? 'null' : query_context.sort_key_expression;\n let js_code = embed_code(MAIN_LOOP_BODY, '__USER_INIT_CODE__', query_context.user_init_code);\n if (is_select_query) {\n if (is_join_query) {\n js_code = embed_code(embed_code(js_code, '__CODE__', PROCESS_SELECT_JOIN), '__CODE__', PROCESS_SELECT_COMMON);\n js_code = embed_expression(js_code, '__RBQLMP__lhs_join_var_expression', query_context.lhs_join_var_expression);\n } else {\n js_code = embed_code(embed_code(js_code, '__CODE__', PROCESS_SELECT_SIMPLE), '__CODE__', PROCESS_SELECT_COMMON);\n }\n js_code = embed_code(js_code, '__RBQLMP__variables_init_code', query_context.variables_init_code);\n js_code = embed_expression(js_code, '__RBQLMP__select_expression', query_context.select_expression);\n js_code = embed_expression(js_code, '__RBQLMP__where_expression', where_expression);\n js_code = embed_expression(js_code, '__RBQLMP__aggregation_key_expression', aggregation_key_expression);\n js_code = embed_expression(js_code, '__RBQLMP__sort_key_expression', sort_key_expression);\n } else {\n if (is_join_query) {\n js_code = embed_code(js_code, '__CODE__', PROCESS_UPDATE_JOIN);\n js_code = embed_expression(js_code, '__RBQLMP__lhs_join_var_expression', query_context.lhs_join_var_expression);\n } else {\n js_code = embed_code(js_code, '__CODE__', PROCESS_UPDATE_SIMPLE);\n }\n js_code = embed_code(js_code, '__RBQLMP__variables_init_code', query_context.variables_init_code);\n js_code = embed_code(js_code, '__RBQLMP__update_expressions', query_context.update_expressions);\n js_code = embed_expression(js_code, '__RBQLMP__where_expression', where_expression);\n }\n return \"(async () => {\" + js_code + \"})()\";\n}\n\n\nasync function compile_and_run(query_context) {\n let main_loop_body = generate_main_loop_code(query_context);\n try {\n let main_loop_promise = eval(main_loop_body);\n await main_loop_promise;\n } catch (e) {\n if (e instanceof SyntaxError) {\n // SyntaxError's from eval() function do not contain detailed explanation of what has caused the syntax error, so to guess what was wrong we can only use the original query\n // v8 issue to fix eval: https://bugs.chromium.org/p/v8/issues/detail?id=2589\n let lower_case_query = query_context.query_text.toLowerCase();\n if (lower_case_query.indexOf(' having ') != -1)\n throw new SyntaxError(e.message + \"\\nRBQL doesn't support \\\"HAVING\\\" keyword\");\n if (lower_case_query.indexOf(' like ') != -1)\n throw new SyntaxError(e.message + \"\\nRBQL doesn't support \\\"LIKE\\\" operator, use like() function instead e.g. ... WHERE like(a1, 'foo%bar') ... \"); // UT JSON\n if (lower_case_query.indexOf(' from ') != -1)\n throw new SyntaxError(e.message + \"\\nTip: If input table is defined by the environment, RBQL query should not have \\\"FROM\\\" keyword\"); // UT JSON\n if (e && e.message && String(e.message).toLowerCase().indexOf('unexpected identifier') != -1) {\n if (lower_case_query.indexOf(' and ') != -1)\n throw new SyntaxError(e.message + \"\\nDid you use 'and' keyword in your query?\\nJavaScript backend doesn't support 'and' keyword, use '&&' operator instead!\");\n if (lower_case_query.indexOf(' or ') != -1)\n throw new SyntaxError(e.message + \"\\nDid you use 'or' keyword in your query?\\nJavaScript backend doesn't support 'or' keyword, use '||' operator instead!\");\n }\n }\n if (e && e.message && e.message.indexOf('Received an instance of RBQLAggregationToken') != -1)\n throw new RbqlParsingError(wrong_aggregation_usage_error);\n throw e;\n }\n}\n\n\nconst GROUP_BY = 'GROUP BY';\nconst UPDATE = 'UPDATE';\nconst SELECT = 'SELECT';\nconst JOIN = 'JOIN';\nconst INNER_JOIN = 'INNER JOIN';\nconst LEFT_JOIN = 'LEFT JOIN';\nconst LEFT_OUTER_JOIN = 'LEFT OUTER JOIN';\nconst STRICT_LEFT_JOIN = 'STRICT LEFT JOIN';\nconst ORDER_BY = 'ORDER BY';\nconst WHERE = 'WHERE';\nconst LIMIT = 'LIMIT';\nconst EXCEPT = 'EXCEPT';\nconst WITH = 'WITH';\n\n\nfunction get_ambiguous_error_msg(variable_name) {\n return `Ambiguous variable name: \"${variable_name}\" is present both in input and in join tables`;\n}\n\n\nfunction get_all_matches(regexp, text) {\n var result = [];\n let match_obj = null;\n while((match_obj = regexp.exec(text)) !== null) {\n result.push(match_obj);\n }\n return result;\n}\n\n\nfunction str_strip(src) {\n return src.replace(/^ +| +$/g, '');\n}\n\n\nfunction strip_comments(cline) {\n cline = cline.trim();\n if (cline.startsWith('//'))\n return '';\n return cline;\n}\n\n\nfunction combine_string_literals(backend_expression, string_literals) {\n for (var i = 0; i < string_literals.length; i++) {\n backend_expression = replace_all(backend_expression, `___RBQL_STRING_LITERAL${i}___`, string_literals[i]);\n }\n return backend_expression;\n}\n\n\nfunction parse_basic_variables(query_text, prefix, dst_variables_map) {\n assert(prefix == 'a' || prefix == 'b');\n let rgx = new RegExp(`(?:^|[^_a-zA-Z0-9])${prefix}([1-9][0-9]*)(?:$|(?=[^_a-zA-Z0-9]))`, 'g');\n let matches = get_all_matches(rgx, query_text);\n for (let i = 0; i < matches.length; i++) {\n let field_num = parseInt(matches[i][1]);\n dst_variables_map[prefix + String(field_num)] = {initialize: true, index: field_num - 1};\n }\n}\n\n\nfunction parse_array_variables(query_text, prefix, dst_variables_map) {\n assert(prefix == 'a' || prefix == 'b');\n let rgx = new RegExp(`(?:^|[^_a-zA-Z0-9])${prefix}\\\\[([1-9][0-9]*)\\\\]`, 'g');\n let matches = get_all_matches(rgx, query_text);\n for (let i = 0; i < matches.length; i++) {\n let field_num = parseInt(matches[i][1]);\n dst_variables_map[`${prefix}[${field_num}]`] = {initialize: true, index: field_num - 1};\n }\n}\n\n\nfunction js_string_escape_column_name(column_name, quote_char) {\n column_name = column_name.replace(/\\\\/g, '\\\\\\\\');\n column_name = column_name.replace(/\\n/g, '\\\\n');\n column_name = column_name.replace(/\\r/g, '\\\\r');\n column_name = column_name.replace(/\\t/g, '\\\\t');\n if (quote_char === \"'\")\n return column_name.replace(/'/g, \"\\\\'\");\n if (quote_char === '\"')\n return column_name.replace(/\"/g, '\\\\\"');\n assert(quote_char === \"`\");\n return column_name.replace(/`/g, \"\\\\`\");\n}\n\n\nfunction query_probably_has_dictionary_variable(query_text, column_name) {\n let rgx = new RegExp('[-a-zA-Z0-9_:;+=!.,()%^#@&* ]+', 'g');\n let continuous_name_segments = get_all_matches(rgx, column_name);\n for (let continuous_segment of continuous_name_segments) {\n if (query_text.indexOf(continuous_segment) == -1)\n return false;\n }\n return true;\n}\n\n\nfunction parse_dictionary_variables(query_text, prefix, column_names, dst_variables_map) {\n // The purpose of this algorithm is to minimize number of variables in varibale_map to improve performance, ideally it should be only variables from the query\n\n // FIXME to prevent typos in attribute names either use query-based variable parsing which can properly handle back-tick strings or wrap \"a\" and \"b\" variables with ES6 Proxies https://stackoverflow.com/a/25658975/2898283\n assert(prefix === 'a' || prefix === 'b');\n let dict_test_rgx = new RegExp(`(?:^|[^_a-zA-Z0-9])${prefix}\\\\[`);\n if (query_text.search(dict_test_rgx) == -1)\n return;\n for (let i = 0; i < column_names.length; i++) {\n let column_name = column_names[i];\n if (query_probably_has_dictionary_variable(query_text, column_name)) {\n let escaped_column_name = js_string_escape_column_name(column_name, '\"');\n dst_variables_map[`${prefix}[\"${escaped_column_name}\"]`] = {initialize: true, index: i};\n escaped_column_name = js_string_escape_column_name(column_name, \"'\");\n dst_variables_map[`${prefix}['${escaped_column_name}']`] = {initialize: false, index: i};\n escaped_column_name = js_string_escape_column_name(column_name, \"`\");\n dst_variables_map[`${prefix}[\\`${escaped_column_name}\\`]`] = {initialize: false, index: i};\n }\n }\n}\n\n\nfunction parse_attribute_variables(query_text, prefix, column_names, column_names_source, dst_variables_map) {\n // The purpose of this algorithm is to minimize number of variables in varibale_map to improve performance, ideally it should be only variables from the query\n\n assert(prefix === 'a' || prefix === 'b');\n let rgx = new RegExp(`(?:^|[^_a-zA-Z0-9])${prefix}\\\\.([_a-zA-Z][_a-zA-Z0-9]*)`, 'g');\n let matches = get_all_matches(rgx, query_text);\n let column_names_from_query = matches.map(v => v[1]);\n for (let column_name of column_names_from_query) {\n let zero_based_idx = column_names.indexOf(column_name);\n if (zero_based_idx != -1) {\n dst_variables_map[`${prefix}.${column_name}`] = {initialize: true, index: zero_based_idx};\n } else {\n throw new RbqlParsingError(`Unable to find column \"${column_name}\" in ${prefix == 'a' ? 'input' : 'join'} ${column_names_source}`);\n }\n }\n}\n\n\nfunction map_variables_directly(query_text, column_names, dst_variables_map) {\n for (let i = 0; i < column_names.length; i++) {\n let column_name = column_names[i];\n if ( /^[_a-zA-Z][_a-zA-Z0-9]*$/.exec(column_name) === null)\n throw new RbqlIOHandlingError(`Unable to use column name \"${column_name}\" as RBQL/JS variable`);\n if (query_text.indexOf(column_name) != -1)\n dst_variables_map[column_name] = {initialize: true, index: i};\n }\n}\n\n\nfunction ensure_no_ambiguous_variables(query_text, input_column_names, join_column_names) {\n let join_column_names_set = new Set(join_column_names);\n for (let column_name of input_column_names) {\n if (join_column_names_set.has(column_name) && query_text.indexOf(column_name) != -1) // False positive is tolerable here\n throw new RbqlParsingError(get_ambiguous_error_msg(column_name));\n }\n}\n\n\nfunction parse_join_expression(src) {\n src = str_strip(src);\n const invalid_join_syntax_error = 'Invalid join syntax. Valid syntax: /path/to/B/table on a... == b... [and a... == b... [and ... ]]';\n let rgx = /^ *([^ ]+) +on +/i;\n let match = rgx.exec(src);\n if (match === null)\n throw new RbqlParsingError(invalid_join_syntax_error);\n let table_id = match[1];\n src = src.substr(match[0].length);\n\n let variable_pairs = [];\n var pair_rgx = /^([^ =]+) *==? *([^ =]+)/;\n var and_rgx = /^ +(and|&&) +/i;\n while (true) {\n match = pair_rgx.exec(src);\n if (match === null)\n throw new RbqlParsingError(invalid_join_syntax_error);\n variable_pairs.push([match[1], match[2]]);\n src = src.substr(match[0].length);\n if (!src.length)\n break;\n match = and_rgx.exec(src);\n if (match === null)\n throw new RbqlParsingError(invalid_join_syntax_error);\n src = src.substr(match[0].length);\n }\n return [table_id, variable_pairs];\n}\n\n\nfunction resolve_join_variables(input_variables_map, join_variables_map, variable_pairs, string_literals) {\n let lhs_variables = [];\n let rhs_indices = [];\n const valid_join_syntax_msg = 'Valid JOIN syntax: /path/to/B/table on a... == b... [and a... == b... [and ... ]]';\n for (let variable_pair of variable_pairs) {\n let [join_var_1, join_var_2] = variable_pair;\n join_var_1 = combine_string_literals(join_var_1, string_literals);\n join_var_2 = combine_string_literals(join_var_2, string_literals);\n if (input_variables_map.hasOwnProperty(join_var_1) && join_variables_map.hasOwnProperty(join_var_1))\n throw new RbqlParsingError(get_ambiguous_error_msg(join_var_1));\n if (input_variables_map.hasOwnProperty(join_var_2) && join_variables_map.hasOwnProperty(join_var_2))\n throw new RbqlParsingError(get_ambiguous_error_msg(join_var_2));\n if (input_variables_map.hasOwnProperty(join_var_2))\n [join_var_1, join_var_2] = [join_var_2, join_var_1];\n\n let [lhs_key_index, rhs_key_index] = [null, null];\n if (['NR', 'a.NR', 'aNR'].indexOf(join_var_1) != -1) {\n lhs_key_index = -1;\n } else if (input_variables_map.hasOwnProperty(join_var_1)) {\n lhs_key_index = input_variables_map[join_var_1].index;\n } else {\n throw new RbqlParsingError(`Unable to parse JOIN expression: Input table does not have field \"${join_var_1}\"\\n${valid_join_syntax_msg}`);\n }\n\n if (['b.NR', 'bNR'].indexOf(join_var_2) != -1) {\n rhs_key_index = -1;\n } else if (join_variables_map.hasOwnProperty(join_var_2)) {\n rhs_key_index = join_variables_map[join_var_2].index;\n } else {\n throw new RbqlParsingError(`Unable to parse JOIN expression: Join table does not have field \"${join_var_2}\"\\n${valid_join_syntax_msg}`);\n }\n\n let lhs_join_var_expression = lhs_key_index == -1 ? 'NR' : `safe_join_get(record_a, ${lhs_key_index})`;\n rhs_indices.push(rhs_key_index);\n lhs_variables.push(lhs_join_var_expression);\n }\n return [lhs_variables, rhs_indices];\n}\n\n\nfunction generate_common_init_code(query_text, variable_prefix) {\n assert(variable_prefix == 'a' || variable_prefix == 'b');\n let result = [];\n result.push(`${variable_prefix} = new Object();`);\n let base_var = variable_prefix == 'a' ? 'NR' : 'bNR';\n let attr_var = `${variable_prefix}.NR`;\n if (query_text.indexOf(attr_var) != -1)\n result.push(`${attr_var} = ${base_var};`);\n if (variable_prefix == 'a' && query_text.indexOf('aNR') != -1)\n result.push('aNR = NR;');\n return result;\n}\n\n\nfunction generate_init_statements(query_text, variables_map, join_variables_map, indent) {\n let code_lines = generate_common_init_code(query_text, 'a');\n let simple_var_name_rgx = /^[_0-9a-zA-Z]+$/;\n for (const [variable_name, var_info] of Object.entries(variables_map)) {\n if (var_info.initialize) {\n let variable_declaration_keyword = simple_var_name_rgx.exec(variable_name) ? 'var ' : '';\n code_lines.push(`${variable_declaration_keyword}${variable_name} = safe_get(record_a, ${var_info.index});`);\n }\n }\n if (join_variables_map) {\n code_lines = code_lines.concat(generate_common_init_code(query_text, 'b'));\n for (const [variable_name, var_info] of Object.entries(join_variables_map)) {\n if (var_info.initialize) {\n let variable_declaration_keyword = simple_var_name_rgx.exec(variable_name) ? 'var ' : '';\n code_lines.push(`${variable_declaration_keyword}${variable_name} = record_b === null ? null : safe_get(record_b, ${var_info.index});`);\n }\n }\n }\n for (let i = 1; i < code_lines.length; i++) {\n code_lines[i] = indent + code_lines[i];\n }\n return code_lines.join('\\n');\n}\n\n\nfunction replace_star_count(aggregate_expression) {\n var rgx = /(^|,) *COUNT\\( *\\* *\\) *(?:$|(?=,))/ig;\n var result = aggregate_expression.replace(rgx, '$1 COUNT(1)');\n return str_strip(result);\n}\n\n\nfunction replace_star_vars(rbql_expression) {\n let star_rgx = /(?:^|,) *(\\*|a\\.\\*|b\\.\\*) *(?=$|,)/g;\n let matches = get_all_matches(star_rgx, rbql_expression);\n let last_pos = 0;\n let result = '';\n for (let match of matches) {\n let star_expression = match[1];\n let replacement_expression = ']).concat(' + {'*': 'star_fields', 'a.*': 'record_a', 'b.*': 'record_b'}[star_expression] + ').concat([';\n if (last_pos < match.index)\n result += rbql_expression.substring(last_pos, match.index);\n result += replacement_expression;\n last_pos = match.index + match[0].length + 1; // Adding one to skip the lookahead comma\n }\n result += rbql_expression.substring(last_pos);\n return result;\n}\n\n\nfunction replace_star_vars_for_header_parsing(rbql_expression) {\n let star_rgx = /(?:(?<=^)|(?<=,)) *(\\*|a\\.\\*|b\\.\\*) *(?=$|,)/g;\n let matches = get_all_matches(star_rgx, rbql_expression);\n let last_pos = 0;\n let result = '';\n for (let match of matches) {\n let star_expression = match[1];\n let replacement_expression = {'*': '__RBQL_INTERNAL_STAR', 'a.*': 'a.__RBQL_INTERNAL_STAR', 'b.*': 'b.__RBQL_INTERNAL_STAR'}[star_expression];\n if (last_pos < match.index)\n result += rbql_expression.substring(last_pos, match.index);\n result += replacement_expression;\n last_pos = match.index + match[0].length;\n }\n result += rbql_expression.substring(last_pos);\n return result;\n}\n\n\nfunction translate_update_expression(update_expression, input_variables_map, string_literals, indent) {\n let first_assignment = str_strip(update_expression.split('=')[0]);\n let first_assignment_error = `Unable to parse \"UPDATE\" expression: the expression must start with assignment, but \"${first_assignment}\" does not look like an assignable field name`;\n\n let assignment_looking_rgx = /(?:^|,) *(a[.#a-zA-Z0-9\\[\\]_]*) *=(?=[^=])/g;\n let update_expressions = [];\n let pos = 0;\n while (true) {\n let match = assignment_looking_rgx.exec(update_expression);\n if (update_expressions.length == 0 && (match === null || match.index != 0)) {\n throw new RbqlParsingError(first_assignment_error);\n }\n if (match === null) {\n update_expressions[update_expressions.length - 1] += str_strip(update_expression.substr(pos)) + ');';\n break;\n }\n if (update_expressions.length)\n update_expressions[update_expressions.length - 1] += str_strip(update_expression.substring(pos, match.index)) + ');';\n let dst_var_name = combine_string_literals(str_strip(match[1]), string_literals);\n if (!input_variables_map.hasOwnProperty(dst_var_name))\n throw new RbqlParsingError(`Unable to parse \"UPDATE\" expression: Unknown field name: \"${dst_var_name}\"`);\n let var_index = input_variables_map[dst_var_name].index;\n let current_indent = update_expressions.length ? indent : '';\n update_expressions.push(`${current_indent}safe_set(up_fields, ${var_index}, `);\n pos = match.index + match[0].length;\n }\n return combine_string_literals(update_expressions.join('\\n'), string_literals);\n}\n\n\nfunction translate_select_expression(select_expression) {\n let expression_without_stars = replace_star_count(select_expression);\n let translated = str_strip(replace_star_vars(expression_without_stars));\n let translated_for_header = str_strip(replace_star_vars_for_header_parsing(expression_without_stars));\n if (!translated.length)\n throw new RbqlParsingError('\"SELECT\" expression is empty');\n return [`[].concat([${translated}])`, translated_for_header];\n}\n\n\nfunction separate_string_literals(rbql_expression) {\n // The regex consists of 3 almost identicall parts, the only difference is quote type\n var rgx = /('(\\\\(\\\\\\\\)*'|[^'])*')|(\"(\\\\(\\\\\\\\)*\"|[^\"])*\")|(`(\\\\(\\\\\\\\)*`|[^`])*`)/g;\n var match_obj = null;\n var format_parts = [];\n var string_literals = [];\n var idx_before = 0;\n while((match_obj = rgx.exec(rbql_expression)) !== null) {\n var literal_id = string_literals.length;\n var string_literal = match_obj[0];\n string_literals.push(string_literal);\n var start_index = match_obj.index;\n format_parts.push(rbql_expression.substring(idx_before, start_index));\n format_parts.push(`___RBQL_STRING_LITERAL${literal_id}___`);\n idx_before = rgx.lastIndex;\n }\n format_parts.push(rbql_expression.substring(idx_before));\n var format_expression = format_parts.join('');\n format_expression = format_expression.replace(/\\t/g, ' ');\n return [format_expression, string_literals];\n}\n\n\nfunction locate_statements(rbql_expression) {\n let statement_groups = [];\n statement_groups.push([STRICT_LEFT_JOIN, LEFT_OUTER_JOIN, LEFT_JOIN, INNER_JOIN, JOIN]);\n statement_groups.push([SELECT]);\n statement_groups.push([ORDER_BY]);\n statement_groups.push([WHERE]);\n statement_groups.push([UPDATE]);\n statement_groups.push([GROUP_BY]);\n statement_groups.push([LIMIT]);\n statement_groups.push([EXCEPT]);\n var result = [];\n for (var ig = 0; ig < statement_groups.length; ig++) {\n for (var is = 0; is < statement_groups[ig].length; is++) {\n var statement = statement_groups[ig][is];\n var rgxp = new RegExp('(?:^| )' + replace_all(statement, ' ', ' *') + '(?= )', 'ig');\n var matches = get_all_matches(rgxp, rbql_expression);\n if (!matches.length)\n continue;\n if (matches.length > 1)\n throw new RbqlParsingError(`More than one \"${statement}\" statements found`);\n assert(matches.length == 1);\n var match = matches[0];\n var match_str = match[0];\n result.push([match.index, match.index + match_str.length, statement]);\n break; // Break to avoid matching a sub-statement from the same group e.g. \"INNER JOIN\" -> \"JOIN\"\n }\n }\n result.sort(function(a, b) { return a[0] - b[0]; });\n return result;\n}\n\n\nfunction separate_actions(rbql_expression) {\n rbql_expression = str_strip(rbql_expression);\n var result = {};\n let with_match = /^(.*) *[Ww][Ii][Tt][Hh] *\\(([a-z]{4,20})\\) *$/.exec(rbql_expression);\n if (with_match !== null) {\n rbql_expression = with_match[1];\n result[WITH] = with_match[2];\n }\n var ordered_statements = locate_statements(rbql_expression);\n for (var i = 0; i < ordered_statements.length; i++) {\n var statement_start = ordered_statements[i][0];\n var span_start = ordered_statements[i][1];\n var statement = ordered_statements[i][2];\n var span_end = i + 1 < ordered_statements.length ? ordered_statements[i + 1][0] : rbql_expression.length;\n assert(statement_start < span_start);\n assert(span_start <= span_end);\n var span = rbql_expression.substring(span_start, span_end);\n var statement_params = {};\n if ([STRICT_LEFT_JOIN, LEFT_OUTER_JOIN, LEFT_JOIN, INNER_JOIN, JOIN].indexOf(statement) != -1) {\n statement_params['join_subtype'] = statement;\n statement = JOIN;\n }\n\n if (statement == UPDATE) {\n if (statement_start != 0)\n throw new RbqlParsingError('UPDATE keyword must be at the beginning of the query');\n span = span.replace(/^ *SET/i, '');\n }\n\n if (statement == ORDER_BY) {\n span = span.replace(/ ASC *$/i, '');\n var new_span = span.replace(/ DESC *$/i, '');\n if (new_span != span) {\n span = new_span;\n statement_params['reverse'] = true;\n } else {\n statement_params['reverse'] = false;\n }\n }\n\n if (statement == SELECT) {\n if (statement_start != 0)\n throw new RbqlParsingError('SELECT keyword must be at the beginning of the query');\n let match = /^ *TOP *([0-9]+) /i.exec(span);\n if (match !== null) {\n statement_params['top'] = parseInt(match[1]);\n span = span.substr(match.index + match[0].length);\n }\n match = /^ *DISTINCT *(COUNT)? /i.exec(span);\n if (match !== null) {\n statement_params['distinct'] = true;\n if (match[1]) {\n statement_params['distinct_count'] = true;\n }\n span = span.substr(match.index + match[0].length);\n }\n }\n statement_params['text'] = str_strip(span);\n result[statement] = statement_params;\n }\n if (!result.hasOwnProperty(SELECT) && !result.hasOwnProperty(UPDATE)) {\n throw new RbqlParsingError('Query must contain either SELECT or UPDATE statement');\n }\n assert(result.hasOwnProperty(SELECT) != result.hasOwnProperty(UPDATE));\n return result;\n}\n\n\nfunction find_top(rb_actions) {\n if (rb_actions.hasOwnProperty(LIMIT)) {\n var rgx = /^[0-9]+$/;\n if (rgx.exec(rb_actions[LIMIT]['text']) === null) {\n throw new RbqlParsingError('LIMIT keyword must be followed by an integer');\n }\n var result = parseInt(rb_actions[LIMIT]['text']);\n return result;\n }\n var select_action = rb_actions[SELECT];\n if (select_action && select_action.hasOwnProperty('top')) {\n return select_action['top'];\n }\n return null;\n}\n\n\nfunction translate_except_expression(except_expression, input_variables_map, string_literals, input_header) {\n let skip_vars = except_expression.split(',');\n skip_vars = skip_vars.map(str_strip);\n let skip_indices = [];\n for (let var_name of skip_vars) {\n var_name = combine_string_literals(var_name, string_literals);\n if (!input_variables_map.hasOwnProperty(var_name))\n throw new RbqlParsingError(`Unknown field in EXCEPT expression: \"${var_name}\"`);\n skip_indices.push(input_variables_map[var_name].index);\n }\n skip_indices = skip_indices.sort((a, b) => a - b);\n let output_header = input_header === null ? null : select_except(input_header, skip_indices);\n let indices_str = skip_indices.join(',');\n return [output_header, `select_except(record_a, [${indices_str}])`];\n}\n\n\nclass HashJoinMap {\n constructor(record_iterator, key_indices) {\n this.max_record_len = 0;\n this.hash_map = new Map();\n this.record_iterator = record_iterator;\n this.nr = 0;\n if (key_indices.length == 1) {\n this.key_index = key_indices[0];\n this.key_indices = null;\n this.polymorphic_get_key = this.get_single_key;\n } else {\n this.key_index = null;\n this.key_indices = key_indices;\n this.polymorphic_get_key = this.get_multi_key;\n }\n }\n\n get_single_key(nr, fields) {\n if (this.key_index >= fields.length)\n throw new RbqlRuntimeError(`No field with index ${this.key_index + 1} at record ${this.nr} in \"B\" table`);\n return this.key_index === -1 ? this.nr : fields[this.key_index];\n };\n\n get_multi_key(nr, fields) {\n let result = [];\n for (let ki of this.key_indices) {\n if (ki >= fields.length)\n throw new RbqlRuntimeError(`No field with index ${ki + 1} at record ${this.nr} in \"B\" table`);\n result.push(ki === -1 ? this.nr : fields[ki]);\n }\n return JSON.stringify(result);\n };\n\n async build() {\n while (true) {\n let fields = await this.record_iterator.get_record();\n if (fields === null)\n break;\n this.nr += 1;\n let nf = fields.length;\n this.max_record_len = Math.max(this.max_record_len, nf);\n let key = this.polymorphic_get_key(this.nr, fields);\n let key_records = this.hash_map.get(key);\n if (key_records === undefined) {\n this.hash_map.set(key, [[this.nr, nf, fields]]);\n } else {\n key_records.push([this.nr, nf, fields]);\n }\n }\n };\n\n get_join_records(key) {\n let result = this.hash_map.get(key);\n if (result === undefined)\n return [];\n return result;\n };\n\n get_warnings() {\n return this.record_iterator.get_warnings();\n };\n}\n\n\nfunction cleanup_query(query_text) {\n return query_text.split('\\n').map(strip_comments).filter(line => line.length).join(' ').replace(/;+$/g, '');\n}\n\n\nfunction remove_redundant_table_name(query_text) {\n query_text = str_strip(query_text.replace(/ +from +a(?: +|$)/gi, ' '));\n query_text = str_strip(query_text.replace(/^ *update +a +set /gi, 'update '));\n return query_text;\n}\n\n\nfunction select_output_header(input_header, join_header, query_column_infos) {\n if (input_header === null && join_header === null)\n return null;\n if (input_header === null)\n input_header = [];\n if (join_header === null)\n join_header = [];\n let output_header = [];\n for (let qci of query_column_infos) {\n // TODO refactor this and python version: extract this code into a function instead to always return something\n if (qci === null) {\n output_header.push('col' + (output_header.length + 1));\n } else if (qci.is_star) {\n if (qci.table_name === null) {\n output_header = output_header.concat(input_header).concat(join_header);\n } else if (qci.table_name === 'a') {\n output_header = output_header.concat(input_header);\n } else if (qci.table_name === 'b') {\n output_header = output_header.concat(join_header);\n }\n } else if (qci.column_name !== null) {\n output_header.push(qci.column_name);\n } else if (qci.column_index !== null) {\n if (qci.table_name == 'a' && qci.column_index < input_header.length) {\n output_header.push(input_header[qci.column_index]);\n } else if (qci.table_name == 'b' && qci.column_index < join_header.length) {\n output_header.push(join_header[qci.column_index]);\n } else {\n output_header.push('col' + (output_header.length + 1));\n }\n } else { // Should never happen\n output_header.push('col' + (output_header.length + 1));\n }\n }\n return output_header;\n}\n\n\nfunction make_inconsistent_num_fields_warning(table_name, inconsistent_records_info) {\n let keys = Object.keys(inconsistent_records_info);\n let entries = [];\n for (let i = 0; i < keys.length; i++) {\n let key = keys[i];\n let record_id = inconsistent_records_info[key];\n entries.push([record_id, key]);\n }\n entries.sort(function(a, b) { return a[0] - b[0]; });\n assert(entries.length > 1);\n let [record_1, num_fields_1] = entries[0];\n let [record_2, num_fields_2] = entries[1];\n let warn_msg = `Number of fields in \"${table_name}\" table is not consistent: `;\n warn_msg += `e.g. record ${record_1} -> ${num_fields_1} fields, record ${record_2} -> ${num_fields_2} fields`;\n return warn_msg;\n}\n\n\nclass RBQLInputIterator {\n constructor(){}\n stop() {\n throw new Error(\"Unable to call the interface method\");\n }\n async get_variables_map(query_text) {\n throw new Error(\"Unable to call the interface method\");\n }\n async get_record() {\n throw new Error(\"Unable to call the interface method\");\n }\n handle_query_modifier() {\n return; // Reimplement if you need to handle a boolean query modifier that can be used like this: `SELECT * WITH (modifiername)`\n }\n get_warnings() {\n return []; // Reimplement if your class can produce warnings\n }\n async get_header() {\n return null; // Reimplement if your class can provide input header\n }\n}\n\n\nclass RBQLOutputWriter {\n constructor(){}\n\n async write(fields) {\n throw new Error(\"Unable to call the interface method\");\n }\n\n async finish() {\n // Reimplement if your class needs to do something on finish e.g. cleanup\n };\n\n get_warnings() {\n return []; // Reimplement if your class can produce warnings\n };\n\n set_header() {\n return; // Reimplement if your class can handle output headers in a meaningful way\n }\n}\n\n\nclass RBQLTableRegistry {\n constructor(){}\n\n get_iterator_by_table_id(table_id) {\n throw new Error(\"Unable to call the interface method\");\n }\n\n get_warnings() {\n return []; // Reimplement if your class can produce warnings\n };\n}\n\n\nclass TableIterator extends RBQLInputIterator {\n constructor(table, column_names=null, normalize_column_names=true, variable_prefix='a') {\n super();\n this.table = table;\n this.column_names = column_names;\n this.normalize_column_names = normalize_column_names;\n this.variable_prefix = variable_prefix;\n this.nr = 0;\n this.fields_info = new Object();\n this.stopped = false;\n }\n\n\n stop() {\n this.stopped = true;\n };\n\n\n async get_variables_map(query_text) {\n let variable_map = new Object();\n parse_basic_variables(query_text, this.variable_prefix, variable_map);\n parse_array_variables(query_text, this.variable_prefix, variable_map);\n if (this.column_names !== null) {\n if (this.table.length && this.column_names.length != this.table[0].length)\n throw new RbqlIOHandlingError('List of column names and table records have different lengths');\n if (this.normalize_column_names) {\n parse_dictionary_variables(query_text, this.variable_prefix, this.column_names, variable_map);\n parse_attribute_variables(query_text, this.variable_prefix, this.column_names, 'column names list', variable_map);\n } else {\n map_variables_directly(query_text, this.column_names, variable_map);\n }\n }\n return variable_map;\n };\n\n\n async get_record() {\n if (this.stopped)\n return null;\n if (this.nr >= this.table.length)\n return null;\n let record = this.table[this.nr];\n this.nr += 1;\n let num_fields = record.length;\n if (!this.fields_info.hasOwnProperty(num_fields))\n this.fields_info[num_fields] = this.nr;\n return record;\n };\n\n get_warnings() {\n if (Object.keys(this.fields_info).length > 1)\n return [make_inconsistent_num_fields_warning('input', this.fields_info)];\n return [];\n };\n\n async get_header() {\n return this.column_names;\n }\n}\n\n\nclass TableWriter extends RBQLOutputWriter {\n constructor(external_table) {\n super();\n this.table = external_table;\n this.header = null;\n }\n\n async write(fields) {\n this.table.push(fields);\n return true;\n };\n\n set_header(header) {\n this.header = header;\n }\n}\n\n\nclass SingleTableRegistry extends RBQLTableRegistry {\n constructor(table, column_names=null, normalize_column_names=true, table_id='b') {\n super();\n this.table = table;\n this.table_id = table_id;\n this.column_names = column_names;\n this.normalize_column_names = normalize_column_names;\n }\n\n get_iterator_by_table_id(table_id) {\n if (table_id.toLowerCase() !== this.table_id)\n throw new RbqlIOHandlingError(`Unable to find join table: \"${table_id}\"`);\n return new TableIterator(this.table, this.column_names, this.normalize_column_names, 'b');\n };\n}\n\n\nasync function shallow_parse_input_query(query_text, input_iterator, join_tables_registry, query_context) {\n query_text = cleanup_query(query_text);\n var [format_expression, string_literals] = separate_string_literals(query_text);\n format_expression = remove_redundant_table_name(format_expression);\n\n var rb_actions = separate_actions(format_expression);\n if (rb_actions.hasOwnProperty(WITH)) {\n input_iterator.handle_query_modifier(rb_actions[WITH]);\n }\n var input_variables_map = await input_iterator.get_variables_map(query_text);\n\n if (rb_actions.hasOwnProperty(ORDER_BY) && rb_actions.hasOwnProperty(UPDATE))\n throw new RbqlParsingError('\"ORDER BY\" is not allowed in \"UPDATE\" queries');\n\n if (rb_actions.hasOwnProperty(GROUP_BY)) {\n if (rb_actions.hasOwnProperty(ORDER_BY) || rb_actions.hasOwnProperty(UPDATE))\n throw new RbqlParsingError('\"ORDER BY\", \"UPDATE\" and \"DISTINCT\" keywords are not allowed in aggregate queries');\n query_context.aggregation_key_expression = '[' + combine_string_literals(rb_actions[GROUP_BY]['text'], string_literals) + ']';\n }\n\n let join_variables_map = null;\n let join_header = null;\n if (rb_actions.hasOwnProperty(JOIN)) {\n var [rhs_table_id, variable_pairs] = parse_join_expression(rb_actions[JOIN]['text']);\n if (join_tables_registry === null)\n throw new RbqlParsingError('JOIN operations are not supported by the application');\n let join_record_iterator = join_tables_registry.get_iterator_by_table_id(rhs_table_id);\n if (!join_record_iterator)\n throw new RbqlParsingError(`Unable to find join table: \"${rhs_table_id}\"`);\n if (rb_actions.hasOwnProperty(WITH)) {\n join_record_iterator.handle_query_modifier(rb_actions[WITH]);\n }\n join_variables_map = await join_record_iterator.get_variables_map(query_text);\n join_header = await join_record_iterator.get_header();\n let [lhs_variables, rhs_indices] = resolve_join_variables(input_variables_map, join_variables_map, variable_pairs, string_literals);\n let sql_join_type = {'JOIN': InnerJoiner, 'INNER JOIN': InnerJoiner, 'LEFT JOIN': LeftJoiner, 'LEFT OUTER JOIN': LeftJoiner, 'STRICT LEFT JOIN': StrictLeftJoiner}[rb_actions[JOIN]['join_subtype']];\n query_context.lhs_join_var_expression = lhs_variables.length == 1 ? lhs_variables[0] : 'JSON.stringify([' + lhs_variables.join(',') + '])';\n query_context.join_map_impl = new HashJoinMap(join_record_iterator, rhs_indices);\n await query_context.join_map_impl.build();\n query_context.join_map = new sql_join_type(query_context.join_map_impl);\n }\n\n query_context.variables_init_code = combine_string_literals(generate_init_statements(format_expression, input_variables_map, join_variables_map, ' '.repeat(4)), string_literals);\n\n if (rb_actions.hasOwnProperty(WHERE)) {\n var where_expression = rb_actions[WHERE]['text'];\n if (/[^>= 3 && line.charCodeAt(0) === 0xEF && line.charCodeAt(1) === 0xBB && line.charCodeAt(2) === 0xBF) {\n return line.substring(3);\n }\n if (assumed_source_encoding == 'utf-8' && line.length >= 1 && line.charCodeAt(0) === 0xFEFF) {\n return line.substring(1);\n }\n return line;\n}\n\n\nfunction make_inconsistent_num_fields_warning(table_name, inconsistent_records_info) {\n let keys = Object.keys(inconsistent_records_info);\n let entries = [];\n for (let i = 0; i < keys.length; i++) {\n let key = keys[i];\n let record_id = inconsistent_records_info[key];\n entries.push([record_id, key]);\n }\n entries.sort(function(a, b) { return a[0] - b[0]; });\n assert(entries.length > 1);\n let [record_1, num_fields_1] = entries[0];\n let [record_2, num_fields_2] = entries[1];\n let warn_msg = `Number of fields in \"${table_name}\" table is not consistent: `;\n warn_msg += `e.g. record ${record_1} -> ${num_fields_1} fields, record ${record_2} -> ${num_fields_2} fields`;\n return warn_msg;\n}\n\n\nfunction expanduser(filepath) {\n if (filepath.charAt(0) === '~') {\n return path.join(os.homedir(), filepath.slice(1));\n }\n return filepath;\n}\n\n\nfunction try_read_index(index_path) {\n var content = null;\n try {\n content = fs.readFileSync(index_path, 'utf-8');\n } catch (e) {\n return [];\n }\n var lines = content.split('\\n');\n var records = [];\n for (var i = 0; i < lines.length; i++) {\n if (!lines[i])\n continue;\n var record = lines[i].split('\\t');\n records.push(record);\n }\n return records;\n}\n\n\nfunction get_index_record(index_path, key) {\n var records = try_read_index(index_path);\n for (var i = 0; i < records.length; i++) {\n if (records[i].length && records[i][0] == key) {\n return records[i];\n }\n }\n return null;\n}\n\n\nfunction find_table_path(main_table_dir, table_id) {\n // If table_id is a relative path it could be relative either to the current directory or to the main table dir.\n var candidate_path = expanduser(table_id);\n if (fs.existsSync(candidate_path)) {\n return candidate_path;\n }\n if (main_table_dir && !path.isAbsolute(candidate_path)) {\n candidate_path = path.join(main_table_dir, candidate_path);\n if (fs.existsSync(candidate_path)) {\n return candidate_path;\n }\n }\n let table_names_settings_path = path.join(os.homedir(), '.rbql_table_names');\n var name_record = get_index_record(table_names_settings_path, table_id);\n if (name_record && name_record.length > 1 && fs.existsSync(name_record[1])) {\n return name_record[1];\n }\n return null;\n}\n\n\nclass RecordQueue {\n // TODO compare performance with a linked list\n constructor() {\n this.push_stack = [];\n this.pull_stack = [];\n }\n\n enqueue(record) {\n this.push_stack.push(record);\n }\n\n dequeue() {\n if (!this.pull_stack.length) {\n if (!this.push_stack.length)\n return null;\n this.pull_stack = this.push_stack;\n this.pull_stack.reverse();\n this.push_stack = [];\n }\n return this.pull_stack.pop();\n }\n}\n\n\nclass CSVRecordIterator extends rbql.RBQLInputIterator {\n // CSVRecordIterator implements a typical async producer-consumer model with an internal buffer:\n // get_record() - consumer\n // stream.on('data') - producer\n constructor(stream, csv_path, encoding, delim, policy, has_header=false, comment_prefix=null, table_name='input', variable_prefix='a') {\n super();\n this.stream = stream;\n this.csv_path = csv_path;\n assert((this.stream === null) != (this.csv_path === null));\n this.encoding = encoding;\n this.delim = delim;\n this.policy = policy;\n\n this.has_header = has_header;\n this.first_record = null;\n this.first_record_should_be_emitted = !has_header;\n this.header_preread_complete = false;\n\n this.table_name = table_name;\n this.variable_prefix = variable_prefix;\n this.comment_prefix = (comment_prefix !== null && comment_prefix.length) ? comment_prefix : null;\n\n this.decoder = null;\n if (encoding == 'utf-8' && this.csv_path === null) {\n // Unfortunately util.TextDecoder has serious flaws:\n // 1. It doesn't work in Node without ICU: https://nodejs.org/api/util.html#util_new_textdecoder_encoding_options\n // 2. It is broken in Electron: https://github.com/electron/electron/issues/18733\n\n // Technically we can implement our own custom streaming text decoder, using the 3 following technologies:\n // 1. decode-encode validation method from https://stackoverflow.com/a/32279283/2898283\n // 2. Scanning buffer chunks for non-continuation utf-8 bytes from the end of the buffer:\n // src_buffer -> (buffer_before, buffer_after) where buffer_after is very small(a couple of bytes) and buffer_before is large and ends with a non-continuation bytes\n // 3. Internal buffer to store small tail part from the previous buffer\n this.decoder = new util.TextDecoder(encoding, {fatal: true, stream: true});\n }\n\n this.input_exhausted = false;\n this.started = false;\n\n this.utf8_bom_removed = false; // BOM doesn't get automatically removed by the decoder when utf-8 file is treated as latin-1\n this.first_defective_line = null;\n\n this.fields_info = new Object();\n this.NR = 0; // Record number\n this.NL = 0; // Line number (NL != NR when the CSV file has comments or multiline fields)\n\n this.rfc_line_buffer = [];\n\n this.partially_decoded_line = '';\n this.partially_decoded_line_ends_with_cr = false;\n\n // Holds an external \"resolve\" function which is called when everything is fine.\n this.resolve_current_record = null;\n // Holds an external \"reject\" function which is called when error has occured.\n this.reject_current_record = null;\n // Holds last exception if we don't have any reject callbacks from clients yet.\n this.current_exception = null;\n\n this.produced_records_queue = new RecordQueue();\n\n this.process_line_polymorphic = policy == 'quoted_rfc' ? this.process_partial_rfc_record_line : this.process_record_line;\n }\n\n\n handle_query_modifier(modifier) {\n // For `... WITH (header) ...` syntax\n if (['header', 'headers'].indexOf(modifier) != -1) {\n this.has_header = true;\n this.first_record_should_be_emitted = false;\n }\n if (['noheader', 'noheaders'].indexOf(modifier) != -1) {\n this.has_header = false;\n this.first_record_should_be_emitted = true;\n }\n }\n\n\n reset_external_callbacks() {\n // Drop external callbacks simultaneously since promises can only resolve once, see: https://stackoverflow.com/a/18218542/2898283\n this.reject_current_record = null;\n this.resolve_current_record = null;\n }\n\n try_propagate_exception() {\n if (this.current_exception && this.reject_current_record) {\n let reject = this.reject_current_record;\n let exception = this.current_exception;\n this.reset_external_callbacks();\n this.current_exception = null;\n reject(exception);\n }\n }\n\n\n store_or_propagate_exception(exception) {\n if (this.current_exception === null)\n // Ignore subsequent exceptions if we already have an unreported error. This way we prioritize earlier errors over the more recent ones.\n this.current_exception = exception;\n this.try_propagate_exception();\n }\n\n\n async preread_first_record() {\n if (this.header_preread_complete)\n return;\n this.first_record = await this.get_record();\n this.header_preread_complete = true; // We must set header_preread_complete to true after calling get_record(), because get_record() uses it internally.\n if (this.first_record === null) {\n return;\n }\n if (this.stream)\n this.stream.pause();\n this.first_record = this.first_record.slice();\n };\n\n\n async get_variables_map(query_text) {\n let variable_map = new Object();\n rbql.parse_basic_variables(query_text, this.variable_prefix, variable_map);\n rbql.parse_array_variables(query_text, this.variable_prefix, variable_map);\n\n await this.preread_first_record();\n if (this.has_header && this.first_record) {\n rbql.parse_attribute_variables(query_text, this.variable_prefix, this.first_record, 'CSV header line', variable_map);\n rbql.parse_dictionary_variables(query_text, this.variable_prefix, this.first_record, variable_map);\n }\n return variable_map;\n };\n\n async get_header() {\n await this.preread_first_record();\n return this.has_header ? this.first_record : null;\n }\n\n\n try_resolve_next_record() {\n this.try_propagate_exception();\n if (this.resolve_current_record === null)\n return;\n\n let record = null;\n if (this.first_record_should_be_emitted && this.header_preread_complete) {\n this.first_record_should_be_emitted = false;\n record = this.first_record;\n } else {\n record = this.produced_records_queue.dequeue();\n }\n\n if (record === null && !this.input_exhausted)\n return;\n let resolve = this.resolve_current_record;\n this.reset_external_callbacks();\n resolve(record);\n };\n\n\n async get_record() {\n if (!this.started)\n await this.start();\n if (this.stream && this.stream.isPaused())\n this.stream.resume();\n\n let parent_iterator = this;\n let current_record_promise = new Promise(function(resolve, reject) {\n parent_iterator.resolve_current_record = resolve;\n parent_iterator.reject_current_record = reject;\n });\n this.try_resolve_next_record();\n return current_record_promise;\n };\n\n\n async get_all_records(num_records=null) {\n let records = [];\n while (true) {\n let record = await this.get_record();\n if (record === null)\n break;\n records.push(record);\n if (num_records && records.length >= num_records) {\n this.stop();\n break;\n }\n }\n return records;\n };\n\n\n process_record_line(line) {\n if (this.comment_prefix !== null && line.startsWith(this.comment_prefix))\n return; // Just skip the line\n this.NR += 1;\n var [record, warning] = csv_utils.smart_split(line, this.delim, this.policy, false);\n if (warning) {\n if (this.first_defective_line === null) {\n this.first_defective_line = this.NL;\n if (this.policy == 'quoted_rfc')\n this.store_or_propagate_exception(new RbqlIOHandlingError(`Inconsistent double quote escaping in ${this.table_name} table at record ${this.NR}, line ${this.NL}`));\n }\n }\n let num_fields = record.length;\n if (!this.fields_info.hasOwnProperty(num_fields))\n this.fields_info[num_fields] = this.NR;\n this.produced_records_queue.enqueue(record);\n this.try_resolve_next_record();\n };\n\n\n process_partial_rfc_record_line(line) {\n let record_line = csv_utils.accumulate_rfc_line_into_record(this.rfc_line_buffer, line, this.comment_prefix);\n if (record_line !== null)\n this.process_record_line(record_line);\n };\n\n\n process_line(line) {\n this.NL += 1;\n if (this.NL === 1) {\n var clean_line = remove_utf8_bom(line, this.encoding);\n if (clean_line != line) {\n line = clean_line;\n this.utf8_bom_removed = true;\n }\n }\n this.process_line_polymorphic(line);\n };\n\n\n process_data_stream_chunk(data_chunk) {\n let decoded_string = null;\n if (this.decoder) {\n try {\n decoded_string = this.decoder.decode(data_chunk);\n } catch (e) {\n if (e instanceof TypeError) {\n this.store_or_propagate_exception(new RbqlIOHandlingError(utf_decoding_error));\n } else {\n this.store_or_propagate_exception(e);\n }\n return;\n }\n } else {\n decoded_string = data_chunk.toString(this.encoding);\n }\n let line_starts_with_lf = decoded_string.length && decoded_string[0] == '\\n';\n let first_line_index = line_starts_with_lf && this.partially_decoded_line_ends_with_cr ? 1 : 0;\n this.partially_decoded_line_ends_with_cr = decoded_string.length && decoded_string[decoded_string.length - 1] == '\\r';\n let lines = csv_utils.split_lines(decoded_string);\n lines[0] = this.partially_decoded_line + lines[0];\n assert(first_line_index == 0 || lines[0].length == 0);\n this.partially_decoded_line = lines.pop();\n for (let i = first_line_index; i < lines.length; i++) {\n this.process_line(lines[i]);\n }\n };\n\n\n process_data_bulk(data_chunk) {\n let decoded_string = data_chunk.toString(this.encoding);\n if (this.encoding == 'utf-8') {\n // Using hacky comparison method from here: https://stackoverflow.com/a/32279283/2898283\n // TODO get rid of this once TextDecoder is really fixed or when alternative method of reliable decoding appears\n let control_buffer = Buffer.from(decoded_string, 'utf-8');\n if (Buffer.compare(data_chunk, control_buffer) != 0) {\n this.store_or_propagate_exception(new RbqlIOHandlingError(utf_decoding_error));\n return;\n }\n }\n let lines = csv_utils.split_lines(decoded_string);\n if (lines.length && lines[lines.length - 1].length == 0)\n lines.pop();\n for (let i = 0; i < lines.length; i++) {\n this.process_line(lines[i]);\n }\n if (this.rfc_line_buffer.length > 0) {\n this.process_record_line(this.rfc_line_buffer.join('\\n'));\n }\n this.input_exhausted = true;\n this.try_resolve_next_record(); // Should be a NOOP here?\n }\n\n\n process_data_stream_end() {\n this.input_exhausted = true;\n if (this.partially_decoded_line.length) {\n let last_line = this.partially_decoded_line;\n this.partially_decoded_line = '';\n this.process_line(last_line);\n }\n if (this.rfc_line_buffer.length > 0) {\n this.process_record_line(this.rfc_line_buffer.join('\\n'));\n }\n this.try_resolve_next_record();\n };\n\n\n stop() {\n if (this.stream)\n this.stream.destroy(); // TODO consider using pause() instead\n };\n\n\n async start() {\n if (this.started)\n return;\n this.started = true;\n if (this.stream) {\n this.stream.on('data', (data_chunk) => { this.process_data_stream_chunk(data_chunk); });\n this.stream.on('end', () => { this.process_data_stream_end(); });\n } else {\n let parent_iterator = this;\n return new Promise(function(resolve, reject) {\n fs.readFile(parent_iterator.csv_path, (err, data_chunk) => {\n if (err) {\n reject(err);\n } else {\n parent_iterator.process_data_bulk(data_chunk);\n resolve();\n }\n });\n });\n }\n };\n\n\n get_warnings() {\n let result = [];\n if (this.first_defective_line !== null)\n result.push(`Inconsistent double quote escaping in ${this.table_name} table. E.g. at line ${this.first_defective_line}`);\n if (this.utf8_bom_removed)\n result.push(`UTF-8 Byte Order Mark (BOM) was found and skipped in ${this.table_name} table`);\n if (Object.keys(this.fields_info).length > 1)\n result.push(make_inconsistent_num_fields_warning(this.table_name, this.fields_info));\n return result;\n };\n}\n\n\nclass CSVWriter extends rbql.RBQLOutputWriter {\n constructor(stream, close_stream_on_finish, encoding, delim, policy, line_separator='\\n') {\n super();\n this.stream = stream;\n this.encoding = encoding;\n if (encoding)\n this.stream.setDefaultEncoding(encoding);\n this.stream.on('error', (error_obj) => { this.store_first_error(error_obj); })\n this.delim = delim;\n this.policy = policy;\n this.line_separator = line_separator;\n this.sub_array_delim = delim == '|' ? ';' : '|';\n\n this.close_stream_on_finish = close_stream_on_finish;\n\n this.null_in_output = false;\n this.delim_in_simple_output = false;\n this.header_len = null;\n this.first_error = null;\n\n if (policy == 'simple') {\n this.polymorphic_join = this.simple_join;\n } else if (policy == 'quoted') {\n this.polymorphic_join = this.quoted_join;\n } else if (policy == 'quoted_rfc') {\n this.polymorphic_join = this.quoted_join_rfc;\n } else if (policy == 'monocolumn') {\n this.polymorphic_join = this.mono_join;\n } else if (policy == 'whitespace') {\n this.polymorphic_join = this.simple_join;\n } else {\n throw new RbqlIOHandlingError('Unknown output csv policy');\n }\n }\n\n\n store_first_error(error_obj) {\n // Store only first error because it is typically more important than the subsequent ones.\n if (this.first_error === null)\n this.first_error = error_obj;\n }\n\n set_header(header) {\n if (header !== null) {\n this.header_len = header.length;\n this.write(header);\n }\n }\n\n\n quoted_join(fields) {\n let delim = this.delim;\n var quoted_fields = fields.map(function(v) { return csv_utils.quote_field(String(v), delim); });\n return quoted_fields.join(this.delim);\n };\n\n\n quoted_join_rfc(fields) {\n let delim = this.delim;\n var quoted_fields = fields.map(function(v) { return csv_utils.rfc_quote_field(String(v), delim); });\n return quoted_fields.join(this.delim);\n };\n\n\n mono_join(fields) {\n if (fields.length > 1) {\n throw new RbqlIOHandlingError('Unable to use \"Monocolumn\" output format: some records have more than one field');\n }\n return fields[0];\n };\n\n\n simple_join(fields) {\n var res = fields.join(this.delim);\n if (fields.join('').indexOf(this.delim) != -1) {\n this.delim_in_simple_output = true;\n }\n return res;\n };\n\n\n normalize_fields(out_fields) {\n for (var i = 0; i < out_fields.length; i++) {\n if (out_fields[i] == null) {\n this.null_in_output = true;\n out_fields[i] = '';\n } else if (Array.isArray(out_fields[i])) {\n this.normalize_fields(out_fields[i]);\n out_fields[i] = out_fields[i].join(this.sub_array_delim);\n }\n }\n };\n\n\n async write(fields) {\n if (this.header_len !== null && fields.length != this.header_len)\n throw new RbqlIOHandlingError(`Inconsistent number of columns in output header and the current record: ${this.header_len} != ${fields.length}`);\n this.normalize_fields(fields);\n this.stream.write(this.polymorphic_join(fields));\n this.stream.write(this.line_separator);\n let writer_error = this.first_error;\n return new Promise(function(resolve, reject) {\n if (writer_error !== null) {\n reject(writer_error);\n } else {\n resolve(true);\n }\n });\n };\n\n\n _write_all(table) {\n for (let i = 0; i < table.length; i++) {\n this.write(table[i]);\n }\n };\n\n\n async finish() {\n let close_stream_on_finish = this.close_stream_on_finish;\n let output_stream = this.stream;\n let output_encoding = this.encoding;\n let writer_error = this.first_error;\n let finish_promise = new Promise(function(resolve, reject) {\n if (writer_error !== null) {\n reject(writer_error);\n }\n if (close_stream_on_finish) {\n output_stream.end('', output_encoding, () => { resolve(); });\n } else {\n setTimeout(() => { resolve(); }, 0);\n }\n });\n return finish_promise;\n };\n\n\n get_warnings() {\n let result = [];\n if (this.null_in_output)\n result.push('null values in output were replaced by empty strings');\n if (this.delim_in_simple_output)\n result.push('Some output fields contain separator');\n return result;\n };\n\n}\n\n\nclass FileSystemCSVRegistry extends rbql.RBQLTableRegistry {\n constructor(input_file_dir, delim, policy, encoding, has_header=false, comment_prefix=null, options=null) {\n super();\n this.input_file_dir = input_file_dir;\n this.delim = delim;\n this.policy = policy;\n this.encoding = encoding;\n this.has_header = has_header;\n this.comment_prefix = comment_prefix;\n this.stream = null;\n this.record_iterator = null;\n\n this.options = options;\n this.bulk_input_path = null;\n this.table_path = null;\n }\n\n get_iterator_by_table_id(table_id) {\n this.table_path = find_table_path(this.input_file_dir, table_id);\n if (this.table_path === null) {\n throw new RbqlIOHandlingError(`Unable to find join table \"${table_id}\"`);\n }\n if (this.options && this.options['bulk_read']) {\n this.bulk_input_path = this.table_path;\n } else {\n this.stream = fs.createReadStream(this.table_path);\n }\n this.record_iterator = new CSVRecordIterator(this.stream, this.bulk_input_path, this.encoding, this.delim, this.policy, this.has_header, this.comment_prefix, table_id, 'b');\n return this.record_iterator;\n };\n\n get_warnings(output_warnings) {\n if (this.record_iterator && this.has_header) {\n output_warnings.push(`The first record in JOIN file ${path.basename(this.table_path)} was also treated as header (and skipped)`);\n }\n }\n}\n\n\nasync function query_csv(query_text, input_path, input_delim, input_policy, output_path, output_delim, output_policy, csv_encoding, output_warnings, with_headers=false, comment_prefix=null, user_init_code='', options=null) {\n let input_stream = null;\n let bulk_input_path = null;\n if (options && options['bulk_read'] && input_path) {\n bulk_input_path = input_path;\n } else {\n input_stream = input_path === null ? process.stdin : fs.createReadStream(input_path);\n }\n let [output_stream, close_output_on_finish] = output_path === null ? [process.stdout, false] : [fs.createWriteStream(output_path), true];\n if (input_delim == '\"' && input_policy == 'quoted')\n throw new RbqlIOHandlingError('Double quote delimiter is incompatible with \"quoted\" policy');\n if (csv_encoding == 'latin-1')\n csv_encoding = 'binary';\n if (!is_ascii(query_text) && csv_encoding == 'binary')\n throw new RbqlIOHandlingError('To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary');\n if ((!is_ascii(input_delim) || !is_ascii(output_delim)) && csv_encoding == 'binary')\n throw new RbqlIOHandlingError('To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary');\n\n let default_init_source_path = path.join(os.homedir(), '.rbql_init_source.js');\n if (user_init_code == '' && fs.existsSync(default_init_source_path)) {\n user_init_code = read_user_init_code(default_init_source_path);\n }\n let input_file_dir = input_path ? path.dirname(input_path) : null;\n let join_tables_registry = new FileSystemCSVRegistry(input_file_dir, input_delim, input_policy, csv_encoding, with_headers, comment_prefix, options);\n let input_iterator = new CSVRecordIterator(input_stream, bulk_input_path, csv_encoding, input_delim, input_policy, with_headers, comment_prefix);\n let output_writer = new CSVWriter(output_stream, close_output_on_finish, csv_encoding, output_delim, output_policy);\n\n await rbql.query(query_text, input_iterator, output_writer, output_warnings, join_tables_registry, user_init_code);\n join_tables_registry.get_warnings(output_warnings);\n}\n\n\nmodule.exports.is_ascii = is_ascii;\nmodule.exports.CSVRecordIterator = CSVRecordIterator;\nmodule.exports.CSVWriter = CSVWriter;\nmodule.exports.FileSystemCSVRegistry = FileSystemCSVRegistry;\nmodule.exports.interpret_named_csv_format = interpret_named_csv_format;\nmodule.exports.read_user_init_code = read_user_init_code;\nmodule.exports.query_csv = query_csv;\nmodule.exports.RecordQueue = RecordQueue;\nmodule.exports.exception_to_error_info = rbql.exception_to_error_info;\n","module.exports = require(\"vscode\");","'use strict';\n\nvar possibleNames = [\n\t'BigInt64Array',\n\t'BigUint64Array',\n\t'Float32Array',\n\t'Float64Array',\n\t'Int16Array',\n\t'Int32Array',\n\t'Int8Array',\n\t'Uint16Array',\n\t'Uint32Array',\n\t'Uint8Array',\n\t'Uint8ClampedArray'\n];\n\nvar g = typeof globalThis === 'undefined' ? global : globalThis;\n\nmodule.exports = function availableTypedArrays() {\n\tvar out = [];\n\tfor (var i = 0; i < possibleNames.length; i++) {\n\t\tif (typeof g[possibleNames[i]] === 'function') {\n\t\t\tout[out.length] = possibleNames[i];\n\t\t}\n\t}\n\treturn out;\n};\n","'use strict';\n\nvar GetIntrinsic = require('get-intrinsic');\n\nvar $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true);\nif ($gOPD) {\n\ttry {\n\t\t$gOPD([], 'length');\n\t} catch (e) {\n\t\t// IE 8 has a broken gOPD\n\t\t$gOPD = null;\n\t}\n}\n\nmodule.exports = $gOPD;\n","// The module cache\nvar __webpack_module_cache__ = {};\n\n// The require function\nfunction __webpack_require__(moduleId) {\n\t// Check if module is in cache\n\tvar cachedModule = __webpack_module_cache__[moduleId];\n\tif (cachedModule !== undefined) {\n\t\treturn cachedModule.exports;\n\t}\n\t// Create a new module (and put it into the cache)\n\tvar module = __webpack_module_cache__[moduleId] = {\n\t\t// no module.id needed\n\t\t// no module.loaded needed\n\t\texports: {}\n\t};\n\n\t// Execute the module function\n\t__webpack_modules__[moduleId](module, module.exports, __webpack_require__);\n\n\t// Return the exports of the module\n\treturn module.exports;\n}\n\n","__webpack_require__.g = (function() {\n\tif (typeof globalThis === 'object') return globalThis;\n\ttry {\n\t\treturn this || new Function('return this')();\n\t} catch (e) {\n\t\tif (typeof window === 'object') return window;\n\t}\n})();","const assert = require('assert');\nconst os = require('os');\n\nconst vscode = require('vscode');\n\nconst rainbow_utils = require('../../rainbow_utils.js');\n\nconst is_web_ext = (os.homedir === undefined); // Runs as web extension in browser.\n\n\n// TODO make RBQL command wait for the result to reduce the timeout.\nconst poor_rbql_async_design_workaround_timeout = 6000;\n\n\nfunction sleep(ms) {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n\nfunction log_message(msg) {\n console.log('###RAINBOW_CSV_UNIT_TEST_MESSAGE### ' + msg);\n}\n\n\nasync function test_rbql_node(workspace_folder_uri) {\n let uri = vscode.Uri.joinPath(workspace_folder_uri, 'test', 'csv_files', 'university_ranking.csv');\n let active_doc = await vscode.workspace.openTextDocument(uri);\n let editor = await vscode.window.showTextDocument(active_doc);\n await sleep(1000);\n\n // Test Python query.\n let test_task = {rbql_backend: \"python\", with_headers: true, rbql_query: \"select top 20 a1, math.ceil(float(a.total_score) * 100), a['university_name'], None, 'foo bar' order by a2\"};\n await vscode.commands.executeCommand('rainbow-csv.RBQL', test_task);\n await sleep(poor_rbql_async_design_workaround_timeout);\n // Indirectly check reported warnings.\n let state_report = await vscode.commands.executeCommand('rainbow-csv.InternalTest', {check_last_rbql_warnings: true});\n assert.equal('[\"None values in output were replaced by empty strings\"]', JSON.stringify(state_report.warnings));\n active_doc = vscode.window.activeTextEditor.document;\n let length_after_query = active_doc.getText().length;\n log_message(`Length after python query: ${length_after_query}`);\n assert.equal(868, length_after_query); // wc -c gives smaller value. Probably VSCode uses '\\r\\n' as line ends.\n\n // Test JS query.\n test_task = {rbql_backend: \"js\", rbql_query: \"select a2 * 10, a3, a3.length where NR > 1 order by a3.length limit 10\"};\n await vscode.commands.executeCommand('rainbow-csv.RBQL', test_task);\n await sleep(poor_rbql_async_design_workaround_timeout);\n active_doc = vscode.window.activeTextEditor.document;\n length_after_query = active_doc.getText().length;\n log_message(`Length after js query: ${length_after_query}`);\n assert.equal(268, length_after_query);\n\n // Test RBQL query error reporting.\n test_task = {rbql_backend: \"python\", rbql_query: \"select nonexistent_function(a1)\"};\n await vscode.commands.executeCommand('rainbow-csv.RBQL', test_task);\n await sleep(poor_rbql_async_design_workaround_timeout);\n state_report = await vscode.commands.executeCommand('rainbow-csv.InternalTest', {check_last_rbql_report: true});\n assert.equal('query execution', state_report.error_type);\n assert.equal(\"At record 1, Details: name 'nonexistent_function' is not defined\", state_report.error_msg);\n\n // Test with multiline records.\n uri = vscode.Uri.joinPath(workspace_folder_uri, 'test', 'csv_files', 'synthetic_rfc_newline_data.csv');\n active_doc = await vscode.workspace.openTextDocument(uri);\n editor = await vscode.window.showTextDocument(active_doc);\n await sleep(1000);\n\n test_task = {rbql_backend: \"js\", rbql_query: \"select '<<<<<', a3, a2, a1, '>>>>> NR: ' + NR\", enable_rfc_newlines: true};\n await vscode.commands.executeCommand('rainbow-csv.RBQL', test_task);\n await sleep(poor_rbql_async_design_workaround_timeout);\n active_doc = vscode.window.activeTextEditor.document;\n length_after_query = active_doc.getText().length;\n log_message(`Length after js multiline-record query: ${length_after_query}`);\n assert.equal(645, length_after_query);\n\n // Test RBQL JOIN query.\n uri = vscode.Uri.joinPath(workspace_folder_uri, 'test', 'csv_files', 'university_ranking.csv');\n active_doc = await vscode.workspace.openTextDocument(uri);\n editor = await vscode.window.showTextDocument(active_doc);\n await sleep(1000);\n test_task = {rbql_backend: \"python\", with_headers: true, rbql_query: \"select a.university_name, b.Country, b.Population, b['GDP per capita'] JOIN countries.csv on a.country == b.Country order by int(b.Population) desc\"};\n await vscode.commands.executeCommand('rainbow-csv.RBQL', test_task);\n await sleep(poor_rbql_async_design_workaround_timeout);\n state_report = await vscode.commands.executeCommand('rainbow-csv.InternalTest', {check_last_rbql_warnings: true});\n assert.equal('[\"The first record in JOIN file countries.csv was also treated as header (and skipped)\"]', JSON.stringify(state_report.warnings));\n active_doc = vscode.window.activeTextEditor.document;\n length_after_query = active_doc.getText().length;\n log_message(`Length after join query: ${length_after_query}`);\n // Not sure why it is 11592 and not 11610, when saving the file `wc -c` gives 11610.\n assert.equal(11592, length_after_query);\n // We have 202 not 201 because the trailing '\\n' maps to a trailing empty line in VSCode.\n assert.equal(202, active_doc.lineCount);\n\n // Test UPDATE, no warnings and copy back.\n uri = vscode.Uri.joinPath(workspace_folder_uri, 'test', 'csv_files', 'countries.csv');\n active_doc = await vscode.workspace.openTextDocument(uri);\n let filename_before = active_doc.fileName;\n let length_before_query = active_doc.getText().length;\n editor = await vscode.window.showTextDocument(active_doc);\n assert(active_doc.getText().indexOf('oceania') == -1);\n assert(active_doc.getText().indexOf('OCEANIA') > 0);\n await sleep(1000);\n\n test_task = {rbql_backend: \"python\", with_headers: true, rbql_query: \"UPDATE set a.Region = a.Region.lower()\"};\n await vscode.commands.executeCommand('rainbow-csv.RBQL', test_task);\n await sleep(poor_rbql_async_design_workaround_timeout);\n state_report = await vscode.commands.executeCommand('rainbow-csv.InternalTest', {check_last_rbql_warnings: true});\n assert.equal('[]', JSON.stringify(state_report.warnings));\n active_doc = vscode.window.activeTextEditor.document;\n let filename_after = active_doc.fileName;\n length_after_query = active_doc.getText().length;\n log_message(`Length after update query: ${length_after_query}`);\n // Changing column to lowercase should not affect the doc length if we account for the '\\r\\n' line endings.\n assert.equal(length_before_query, length_after_query - active_doc.lineCount + 1);\n assert(active_doc.getText().indexOf('OCEANIA') == -1);\n assert(active_doc.getText().indexOf('oceania') > 0);\n\n await sleep(1000);\n await vscode.commands.executeCommand('rainbow-csv.CopyBack');\n await sleep(1000);\n active_doc = await vscode.workspace.openTextDocument(uri);\n let filename_after_copy_back = active_doc.fileName;\n // Make sure that the name stays the same as the original doc but the content has changed.\n assert.equal(filename_before, filename_after_copy_back);\n assert(active_doc.getText().indexOf('OCEANIA') == -1);\n assert(active_doc.getText().indexOf('oceania') > 0);\n}\n\n\nasync function test_rbql_web(workspace_folder_uri) {\n let uri = vscode.Uri.joinPath(workspace_folder_uri, 'test', 'csv_files', 'university_ranking.csv');\n let active_doc = await vscode.workspace.openTextDocument(uri);\n let editor = await vscode.window.showTextDocument(active_doc);\n await sleep(1000);\n\n let test_task = {rbql_backend: \"js\", with_headers: true, rbql_query: \"select top 20 a1, Math.ceil(parseFloat(a.total_score) * 100), a['university_name'], null, 'foo bar' order by a2\"};\n await vscode.commands.executeCommand('rainbow-csv.RBQL', test_task);\n await sleep(poor_rbql_async_design_workaround_timeout);\n // Indirectly check reported warnings.\n let state_report = await vscode.commands.executeCommand('rainbow-csv.InternalTest', {check_last_rbql_warnings: true});\n assert.equal('[\"null values in output were replaced by empty strings\"]', JSON.stringify(state_report.warnings));\n active_doc = vscode.window.activeTextEditor.document;\n let length_after_query = active_doc.getText().length;\n log_message(`Length after first js query: ${length_after_query}`);\n assert.equal(846, length_after_query);\n\n test_task = {rbql_backend: \"js\", rbql_query: \"select a2 * 10, a3, a3.length where NR > 1 order by a3.length limit 10\"};\n await vscode.commands.executeCommand('rainbow-csv.RBQL', test_task);\n await sleep(poor_rbql_async_design_workaround_timeout);\n active_doc = vscode.window.activeTextEditor.document;\n length_after_query = active_doc.getText().length;\n log_message(`Length after second js query: ${length_after_query}`);\n // 267 instead of 268 because no trailing '\\n' at the end of file.\n assert.equal(267, length_after_query);\n\n // Test RBQL query error reporting.\n test_task = {rbql_backend: \"js\", rbql_query: \"select nonexistent_function(a1)\"};\n await vscode.commands.executeCommand('rainbow-csv.RBQL', test_task);\n await sleep(poor_rbql_async_design_workaround_timeout);\n state_report = await vscode.commands.executeCommand('rainbow-csv.InternalTest', {check_last_rbql_report: true});\n assert.equal('query execution', state_report.error_type);\n assert.equal(\"At record 1, Details: nonexistent_function is not defined\", state_report.error_msg);\n\n // Test with multiline records.\n log_message('Starting multiline records test');\n uri = vscode.Uri.joinPath(workspace_folder_uri, 'test', 'csv_files', 'synthetic_rfc_newline_data.csv');\n active_doc = await vscode.workspace.openTextDocument(uri);\n editor = await vscode.window.showTextDocument(active_doc);\n await sleep(1000);\n\n test_task = {rbql_backend: \"js\", rbql_query: \"select '<<<<<', a3, a2, a1, '>>>>> NR: ' + NR\", enable_rfc_newlines: true};\n await vscode.commands.executeCommand('rainbow-csv.RBQL', test_task);\n await sleep(poor_rbql_async_design_workaround_timeout);\n active_doc = vscode.window.activeTextEditor.document;\n length_after_query = active_doc.getText().length;\n log_message(`Length after js multiline-record query: ${length_after_query}`);\n // 644 instead of 645 because no trailing '\\n' at the end of file.\n assert.equal(644, length_after_query);\n}\n\n\nasync function test_align_shrink_lint(workspace_folder_uri) {\n let uri = vscode.Uri.joinPath(workspace_folder_uri, 'test', 'csv_files', 'university_ranking.csv');\n let active_doc = await vscode.workspace.openTextDocument(uri);\n let editor = await vscode.window.showTextDocument(active_doc);\n let length_original = active_doc.getText().length;\n log_message(`Original length: ${length_original}`)\n assert.equal(12538, length_original);\n await sleep(2000);\n\n await vscode.commands.executeCommand('rainbow-csv.Align');\n let length_aligned = active_doc.getText().length;\n log_message(`Aligned length: ${length_aligned}`)\n assert.equal(25896, length_aligned);\n assert(length_aligned > length_original);\n let lint_report = await vscode.commands.executeCommand('rainbow-csv.CSVLint');\n assert.equal(lint_report, 'OK');\n await sleep(2000);\n\n await vscode.commands.executeCommand('rainbow-csv.Shrink');\n let length_shrinked = active_doc.getText().length;\n log_message(`Shrinked length: ${length_shrinked}`)\n // This is to ensure that after original -> align -> shrink sequence we get back to original doc.\n assert.equal(length_original, length_shrinked);\n await sleep(500);\n\n let text_with_comma = 'foobar,';\n await vscode.commands.executeCommand('default:type', { text: text_with_comma });\n lint_report = await vscode.commands.executeCommand('rainbow-csv.CSVLint');\n assert(lint_report.indexOf('Number of fields is not consistent') != -1);\n await sleep(500);\n\n for (let i = 0; i < text_with_comma.length; i++) {\n await vscode.commands.executeCommand(\"deleteLeft\");\n }\n await sleep(500);\n}\n\n\nasync function test_column_edit(workspace_folder_uri) {\n let uri = vscode.Uri.joinPath(workspace_folder_uri, 'test', 'csv_files', 'movies.txt');\n let active_doc = await vscode.workspace.openTextDocument(uri);\n let editor = await vscode.window.showTextDocument(active_doc);\n let length_original = active_doc.getText().length;\n assert.equal(9986, length_original);\n for (let i = 0; i < 10; i++) {\n await vscode.commands.executeCommand(\"cursorRight\");\n }\n await sleep(1000);\n await vscode.commands.executeCommand(\"rainbow-csv.ColumnEditAfter\");\n await sleep(1000);\n let text_with_comma = 'foobar,';\n await vscode.commands.executeCommand('default:type', { text: text_with_comma });\n let length_after_column_edit = active_doc.getText().length;\n assert.equal(length_original + active_doc.lineCount * text_with_comma.length, length_after_column_edit);\n await sleep(1000);\n for (let i = 0; i < text_with_comma.length; i++) {\n await vscode.commands.executeCommand(\"deleteLeft\");\n }\n await sleep(1000);\n let length_after_delete = active_doc.getText().length;\n // Ensure that after multicursor deletion of the added `text_with_comma` text we get back to the original doc.\n assert.equal(length_original, length_after_delete);\n}\n\n\nasync function test_no_autodetection(workspace_folder_uri) {\n let uri = vscode.Uri.joinPath(workspace_folder_uri, 'test', 'csv_files', 'lorem_ipsum.txt');\n let active_doc = await vscode.workspace.openTextDocument(uri);\n log_message(`languageId for lorem_ipsum.txt: ${active_doc.languageId}`)\n assert.equal(active_doc.languageId, 'plaintext');\n let editor = await vscode.window.showTextDocument(active_doc);\n await sleep(1000);\n\n uri = vscode.Uri.joinPath(workspace_folder_uri, 'test', 'suite', 'index.js');\n active_doc = await vscode.workspace.openTextDocument(uri);\n log_message(`languageId for index.js: ${active_doc.languageId}`)\n assert.equal(active_doc.languageId, 'javascript');\n editor = await vscode.window.showTextDocument(active_doc);\n await sleep(1000);\n\n uri = vscode.Uri.joinPath(workspace_folder_uri, 'test', 'csv_files', 'lorem_ipsum');\n active_doc = await vscode.workspace.openTextDocument(uri);\n log_message(`languageId for lorem_ipsum: ${active_doc.languageId}`)\n assert.equal(active_doc.languageId, 'plaintext');\n editor = await vscode.window.showTextDocument(active_doc);\n await sleep(1000);\n}\n\n\nasync function test_autodetection(workspace_folder_uri) {\n let uri = vscode.Uri.joinPath(workspace_folder_uri, 'test', 'csv_files', 'university_ranking_semicolon.txt');\n let active_doc = await vscode.workspace.openTextDocument(uri);\n let editor = await vscode.window.showTextDocument(active_doc);\n log_message(`languageId for university_ranking_semicolon.txt: ${active_doc.languageId}`)\n assert.equal(active_doc.languageId, 'csv (semicolon)');\n await sleep(1000);\n}\n\n\nasync function test_manual_enable_disable(workspace_folder_uri) {\n let uri = vscode.Uri.joinPath(workspace_folder_uri, 'test', 'csv_files', 'small_movies.pipe');\n let active_doc = await vscode.workspace.openTextDocument(uri);\n log_message(`languageId for small_movies.pipe: ${active_doc.languageId}`)\n assert.equal(active_doc.languageId, 'plaintext');\n let editor = await vscode.window.showTextDocument(active_doc);\n await sleep(1000);\n for (let i = 0; i < 6; i++) {\n await vscode.commands.executeCommand(\"cursorRight\");\n }\n await vscode.commands.executeCommand(\"cursorRightSelect\");\n await sleep(1000);\n await vscode.commands.executeCommand('rainbow-csv.RainbowSeparator');\n await sleep(2000);\n log_message(`languageId for small_movies.pipe after RainbowSeparator: ${active_doc.languageId}`)\n assert.equal(active_doc.languageId, 'csv (pipe)');\n await vscode.commands.executeCommand('rainbow-csv.RainbowSeparatorOff');\n await sleep(2000);\n log_message(`languageId for small_movies.pipe after RainbowSeparatorOff: ${active_doc.languageId}`)\n assert.equal(active_doc.languageId, 'plaintext');\n await sleep(1000);\n}\n\n\nfunction test_align_stats() {\n // Previous fields are numbers but the current one is not - mark the column as non-numeric.\n let field = 'foobar';\n let is_first_line = 0;\n let field_components = [5, 2, 3];\n rainbow_utils.update_subcomponent_stats(field, is_first_line, field_components);\n assert.deepEqual(field_components, [6, -1, -1]);\n\n // The field is non-numeric but it is at the first line so could be a header - do not mark the column as non-numeric just yet.\n field = 'foobar';\n is_first_line = 1;\n field_components = [0, 0, 0];\n rainbow_utils.update_subcomponent_stats(field, is_first_line, field_components);\n assert.deepEqual(field_components, [6, 0, 0]);\n\n // The field is a number but the column is already marked as non-numeric so we just update the max string width.\n field = '100000';\n is_first_line = 0;\n field_components = [2, -1, -1];\n rainbow_utils.update_subcomponent_stats(field, is_first_line, field_components);\n assert.deepEqual(field_components, [6, -1, -1]);\n\n // Empty field should not mark a potentially numeric column as non-numeric.\n field = '';\n is_first_line = 0;\n field_components = [5, 2, 3];\n rainbow_utils.update_subcomponent_stats(field, is_first_line, field_components);\n assert.deepEqual(field_components, [5, 2, 3]);\n\n // The field doesn't change stats because all of 3 components are smaller than the current maximums.\n field = '100.3';\n is_first_line = 0;\n field_components = [7, 4, 3];\n rainbow_utils.update_subcomponent_stats(field, is_first_line, field_components);\n assert.deepEqual(field_components, [7, 4, 3]);\n\n // Integer update example.\n field = '100000';\n is_first_line = 0;\n field_components = [5, 2, 3];\n rainbow_utils.update_subcomponent_stats(field, is_first_line, field_components);\n assert.deepEqual(field_components, [6, 6, 3]);\n\n // Float update example.\n field = '1000.23';\n is_first_line = 0;\n field_components = [3, 3, 0];\n rainbow_utils.update_subcomponent_stats(field, is_first_line, field_components);\n assert.deepEqual(field_components, [7, 4, 3]);\n}\n\n\nfunction test_field_align() {\n // Align field in non-numeric non-last column.\n let field = 'foobar';\n let is_first_line = 0;\n let max_components_lens = [10, -1, -1];\n max_components_lens = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n let is_last_column = 0;\n let aligned_field = rainbow_utils.align_field(field, is_first_line, max_components_lens, is_last_column);\n assert.deepEqual('foobar ', aligned_field);\n\n // Align field in non-numeric last column.\n field = 'foobar';\n is_first_line = 0;\n max_components_lens = [10, -1, -1];\n max_components_lens = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n is_last_column = 1;\n aligned_field = rainbow_utils.align_field(field, is_first_line, max_components_lens, is_last_column);\n assert.deepEqual('foobar', aligned_field);\n\n // Align non-numeric first line (potentially header) field in numeric column.\n field = 'foobar';\n is_first_line = 1;\n max_components_lens = [10, 4, 6];\n max_components_lens = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n is_last_column = 0;\n aligned_field = rainbow_utils.align_field(field, is_first_line, max_components_lens, is_last_column);\n assert.deepEqual('foobar ', aligned_field);\n\n // Align numeric first line (potentially header) field in numeric column.\n field = '10.1';\n is_first_line = 1;\n max_components_lens = [10, 4, 6];\n max_components_lens = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n is_last_column = 0;\n aligned_field = rainbow_utils.align_field(field, is_first_line, max_components_lens, is_last_column);\n assert.deepEqual(' 10.1 ', aligned_field);\n\n // Align numeric field in non-numeric column (first line).\n field = '10.1';\n is_first_line = 1;\n max_components_lens = [10, -1, -1];\n max_components_lens = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n is_last_column = 0;\n aligned_field = rainbow_utils.align_field(field, is_first_line, max_components_lens, is_last_column);\n assert.deepEqual('10.1 ', aligned_field);\n\n // Align numeric field in non-numeric column (not first line).\n field = '10.1';\n is_first_line = 0;\n max_components_lens = [10, -1, -1];\n max_components_lens = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n is_last_column = 0;\n aligned_field = rainbow_utils.align_field(field, is_first_line, max_components_lens, is_last_column);\n assert.deepEqual('10.1 ', aligned_field);\n\n // Align numeric float in numeric non-last column.\n field = '10.1';\n is_first_line = 0;\n max_components_lens = [10, 4, 6];\n max_components_lens = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n is_last_column = 0;\n aligned_field = rainbow_utils.align_field(field, is_first_line, max_components_lens, is_last_column);\n assert.deepEqual(' 10.1 ', aligned_field);\n\n // Align numeric float in numeric last column.\n field = '10.1';\n is_first_line = 0;\n max_components_lens = [10, 4, 6];\n max_components_lens = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n is_last_column = 1;\n aligned_field = rainbow_utils.align_field(field, is_first_line, max_components_lens, is_last_column);\n assert.deepEqual(' 10.1', aligned_field);\n\n // Align numeric integer in numeric non-last column.\n field = '1000';\n is_first_line = 0;\n max_components_lens = [10, 4, 6];\n max_components_lens = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n is_last_column = 0;\n aligned_field = rainbow_utils.align_field(field, is_first_line, max_components_lens, is_last_column);\n assert.deepEqual('1000 ', aligned_field);\n\n // Align numeric integer in numeric last column.\n field = '1000';\n is_first_line = 0;\n max_components_lens = [10, 4, 6];\n max_components_lens = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n is_last_column = 1;\n aligned_field = rainbow_utils.align_field(field, is_first_line, max_components_lens, is_last_column);\n assert.deepEqual('1000', aligned_field);\n\n // Align numeric integer in numeric (integer) column.\n field = '1000';\n is_first_line = 0;\n max_components_lens = [4, 4, 0];\n max_components_lens = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n is_last_column = 0;\n aligned_field = rainbow_utils.align_field(field, is_first_line, max_components_lens, is_last_column);\n assert.deepEqual('1000 ', aligned_field);\n\n // Align numeric integer in numeric (integer) column dominated by header width.\n field = '1000';\n is_first_line = 0;\n max_components_lens = [6, 4, 0];\n max_components_lens = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n is_last_column = 0;\n aligned_field = rainbow_utils.align_field(field, is_first_line, max_components_lens, is_last_column);\n assert.deepEqual(' 1000 ', aligned_field);\n\n // Align numeric float in numeric column dominated by header width.\n field = '10.1';\n is_first_line = 0;\n max_components_lens = [12, 4, 6];\n max_components_lens = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n is_last_column = 0;\n aligned_field = rainbow_utils.align_field(field, is_first_line, max_components_lens, is_last_column);\n assert.deepEqual(' 10.1 ', aligned_field);\n}\n\n\nfunction test_adjust_column_stats() {\n // Not a numeric column, adjustment is NOOP.\n let max_components_lens = [10, -1, -1];\n let adjusted_components = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n assert.deepEqual([10, -1, -1], adjusted_components);\n\n // This is possisble with a single-line file.\n max_components_lens = [10, 0, 0];\n adjusted_components = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n assert.deepEqual([10, -1, -1], adjusted_components);\n\n // Header is smaller than the sum of the numeric components.\n // value\n // 0.12\n // 1234\n max_components_lens = [5, 4, 3];\n adjusted_components = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n assert.deepEqual([7, 4, 3], adjusted_components);\n\n // Header is bigger than the sum of the numeric components.\n max_components_lens = [10, 4, 3];\n adjusted_components = rainbow_utils.adjust_column_stats([max_components_lens])[0];\n assert.deepEqual([10, 7, 3], adjusted_components);\n}\n\n\nfunction unit_test_align_logic() {\n test_align_stats();\n test_field_align();\n test_adjust_column_stats();\n}\n\n\nasync function run() {\n try {\n log_message('Starting tests');\n\n assert.equal(-1, [1, 2, 3].indexOf(0));\n\n assert(vscode.workspace.workspaceFolders);\n assert.equal(1, vscode.workspace.workspaceFolders.length);\n let workspace_folder_uri = vscode.workspace.workspaceFolders[0].uri;\n\n await unit_test_align_logic();\n\n await test_no_autodetection(workspace_folder_uri);\n if (!is_web_ext) {\n // Ensure that opening non-csv files doesn't cause rainbow csv to import relatively heavy lazy-loaded code.\n // There is no point to check this in web since all of the files are bundled into a single script anyway.\n let state_report = await vscode.commands.executeCommand('rainbow-csv.InternalTest', {check_initialization_state: true});\n assert(state_report.initialized);\n assert(!state_report.lazy_loaded);\n }\n\n await test_autodetection(workspace_folder_uri);\n await test_manual_enable_disable(workspace_folder_uri);\n\n if (!is_web_ext) {\n // Ensure that basic operations don't cause rainbow csv to lazy load unnecessary code.\n let state_report = await vscode.commands.executeCommand('rainbow-csv.InternalTest', {check_initialization_state: true});\n assert(state_report.initialized);\n assert(!state_report.lazy_loaded);\n }\n\n if (is_web_ext) {\n await test_rbql_web(workspace_folder_uri);\n } else {\n await test_rbql_node(workspace_folder_uri);\n }\n\n if (!is_web_ext) {\n // Sanity check that after using advanced functionality such as RBQL, the non-basic code is lazy loaded.\n let state_report = await vscode.commands.executeCommand('rainbow-csv.InternalTest', {check_initialization_state: true});\n assert(state_report.initialized);\n assert(state_report.lazy_loaded);\n }\n\n await test_align_shrink_lint(workspace_folder_uri);\n await test_column_edit(workspace_folder_uri);\n\n log_message('Finishing tests');\n } catch (e) {\n log_message('Error: tests have failed. Exception:');\n log_message(String(e));\n log_message(String(e.stack));\n }\n}\n\nexports.run = run;\n"],"names":["_typeof","obj","Symbol","iterator","constructor","prototype","isDeepEqual","isDeepStrictEqual","_require$codes","codes","ERR_AMBIGUOUS_ARGUMENT","ERR_INVALID_ARG_TYPE","ERR_INVALID_ARG_VALUE","ERR_INVALID_RETURN_VALUE","ERR_MISSING_ARGS","AssertionError","inspect","_require$types","isPromise","isRegExp","objectAssign","Object","assign","objectIs","is","lazyLoadComparison","comparison","Map","warned","assert","module","exports","ok","NO_EXCEPTION_SENTINEL","innerFail","message","Error","innerOk","fn","argLen","value","generatedMessage","err","actual","expected","operator","stackStartFn","_len","arguments","length","args","Array","_key","apply","concat","fail","internalMessage","argsLen","undefined","warn","process","emitWarning","console","bind","errArgs","equal","notEqual","deepEqual","notDeepEqual","deepStrictEqual","notDeepStrictEqual","strictEqual","notStrictEqual","Comparison","keys","_this","this","instance","Constructor","TypeError","_classCallCheck","forEach","key","test","compareExceptionKey","a","b","name","expectedException","msg","push","isPrototypeOf","call","getActual","e","checkIsPromise","then","catch","waitForActual","promiseFn","Promise","resolve","resultPromise","expectsError","error","details","fnType","expectsNoError","strict","_len6","_key6","throws","_len2","_key2","rejects","_len3","_key3","result","doesNotThrow","_len4","_key4","doesNotReject","_len5","_key5","ifError","newErr","origStack","stack","tmp2","split","shift","tmp1","i","pos","indexOf","slice","join","_defineProperty","defineProperty","enumerable","configurable","writable","_defineProperties","target","props","descriptor","_possibleConstructorReturn","self","_assertThisInitialized","ReferenceError","_wrapNativeSuper","Class","_cache","Function","toString","has","get","set","Wrapper","_construct","_getPrototypeOf","create","_setPrototypeOf","isNativeReflectConstruct","Reflect","construct","sham","Proxy","Date","Parent","o","p","setPrototypeOf","__proto__","getPrototypeOf","endsWith","str","search","this_len","substring","blue","green","red","white","kReadableOperator","strictEqualObject","notStrictEqualObject","notIdentical","copyError","source","inspectValue","val","compact","customInspect","depth","maxArrayLength","Infinity","showHidden","breakLength","showProxy","sorted","getters","_Error","options","limit","stackTraceLimit","String","stderr","isTTY","getColorDepth","other","res","lastPos","end","skipped","actualInspected","actualLines","expectedLines","indicator","inputLength","columns","count","Math","floor","maxCount","log","repeat","pop","maxLines","max","_actualLines","printedLines","skippedMsg","cur","expectedLine","actualLine","divergingLines","createErrDiff","base","_res","knownOperators","code","captureStackTrace","protoProps","subClass","superClass","_inherits","custom","recurseTimes","ctx","ownKeys","getOwnPropertySymbols","filter","sym","getOwnPropertyDescriptor","_objectSpread","util","createErrorType","Base","NodeError","_Base","arg1","arg2","arg3","getMessage","oneOf","thing","isArray","len","map","determiner","start","substr","replace","type","reason","inspected","RangeError","input","_slicedToArray","arr","_arrayWithHoles","_arr","_n","_d","_e","_s","_i","next","done","_iterableToArrayLimit","_nonIterableRest","regexFlagsSupported","flags","arrayFromSet","array","arrayFromMap","objectGetOwnPropertySymbols","numberIsNaN","Number","isNaN","uncurryThis","f","hasOwnProperty","propertyIsEnumerable","objectToString","isAnyArrayBuffer","isArrayBufferView","isDate","isMap","isSet","isNativeError","isBoxedPrimitive","isNumberObject","isStringObject","isBooleanObject","isBigIntObject","isSymbolObject","isFloat32Array","isFloat64Array","isNonIndex","charCodeAt","pow","getOwnNonIndexProperties","compare","x","y","min","innerDeepEqual","val1","val2","memos","buf1","buf2","val1Tag","keys1","keys2","keyCheck","getTime","RegExp","byteLength","Uint8Array","buffer","byteOffset","areSimilarTypedArrays","offset","areSimilarFloatArrays","_keys","_keys2","size","valueOf","Boolean","BigInt","isEqualBoxedPrimitive","getEnumerables","k","iterationType","aKeys","bKeys","symbolKeysA","symbolKeysB","_symbolKeysB","position","val2MemoA","val2MemoB","areEq","objEquiv","delete","setHasEqualElement","memo","setValues","findLooseMatchingPrimitives","prim","setMightHaveLoosePrim","altValue","mapMightHaveLoosePrim","item","curB","mapHasEqualEntry","key1","item1","key2","aValues","Set","add","bValues","_val","setEquiv","aEntries","_aEntries$i","item2","bEntries","_i2","_bEntries$_i","mapEquiv","keysA","GetIntrinsic","callBind","$indexOf","allowMissing","intrinsic","$apply","$call","$reflectApply","$gOPD","$defineProperty","$max","originalFunction","func","desc","applyBind","hasSymbols","toStr","origDefineProperty","hasPropertyDescriptors","supportsDescriptors","object","predicate","defineProperties","predicates","firstSource","to","nextSource","keysArray","nextIndex","nextKey","polyfill","hasOwn","l","ERROR_MESSAGE","funcType","that","bound","binder","boundLength","boundArgs","Empty","implementation","$SyntaxError","SyntaxError","$Function","$TypeError","getEvalledConstructor","expressionSyntax","throwTypeError","ThrowTypeError","calleeThrows","gOPDthrows","getProto","needsEval","TypedArray","INTRINSICS","AggregateError","ArrayBuffer","Atomics","DataView","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","eval","EvalError","Float32Array","Float64Array","FinalizationRegistry","Int8Array","Int16Array","Int32Array","isFinite","JSON","parseFloat","parseInt","SharedArrayBuffer","Uint8ClampedArray","Uint16Array","Uint32Array","URIError","WeakMap","WeakRef","WeakSet","doEval","gen","LEGACY_ALIASES","$concat","$spliceApply","splice","$replace","$strSlice","rePropName","reEscapeChar","stringToPath","string","first","last","match","number","quote","subString","getBaseIntrinsic","alias","intrinsicName","parts","intrinsicBaseName","intrinsicRealName","skipFurtherCaching","isOwn","part","hasArrayLengthDefineBug","origSymbol","hasSymbolSham","symObj","getOwnPropertyNames","syms","toStringTag","ctor","superCtor","super_","TempCtor","hasToStringTag","$toString","callBound","isStandardArguments","isLegacyArguments","callee","supportsStandardArguments","GeneratorFunction","fnToStr","isFnRegex","generatorFunc","getGeneratorFunc","define","getPolyfill","shim","NaN","availableTypedArrays","g","globalThis","typedArrays","$slice","toStrTags","gOPD","typedArray","proto","superProto","tag","anyTrue","getter","tryTypedArrays","keysShim","isArgs","isEnumerable","hasDontEnumBug","hasProtoEnumBug","dontEnums","equalsConstructorPrototype","excludedKeys","$applicationCache","$console","$external","$frame","$frameElement","$frames","$innerHeight","$innerWidth","$onmozfullscreenchange","$onmozfullscreenerror","$outerHeight","$outerWidth","$pageXOffset","$pageYOffset","$parent","$scrollLeft","$scrollTop","$scrollX","$scrollY","$self","$webkitIndexedDB","$webkitStorageInfo","$window","hasAutomationEqualityBug","window","isObject","isFunction","isArguments","isString","theKeys","skipProto","j","skipConstructor","equalsConstructorPrototypeIfNotBuggy","origKeys","originalKeys","keysWorksWithArguments","cachedSetTimeout","cachedClearTimeout","defaultSetTimout","defaultClearTimeout","runTimeout","fun","setTimeout","clearTimeout","currentQueue","queue","draining","queueIndex","cleanUpNextTick","drainQueue","timeout","run","marker","runClearTimeout","Item","noop","nextTick","title","browser","env","argv","version","versions","on","addListener","once","off","removeListener","removeAllListeners","emit","prependListener","prependOnceListener","listeners","binding","cwd","chdir","dir","umask","arg","copy","fill","readUInt8","isArgumentsObject","isGeneratorFunction","whichTypedArray","isTypedArray","BigIntSupported","SymbolSupported","ObjectToString","numberValue","stringValue","booleanValue","bigIntValue","symbolValue","checkBoxedPrimitive","prototypeValueOf","isMapToString","isSetToString","isWeakMapToString","isWeakSetToString","isArrayBufferToString","isArrayBuffer","working","isDataViewToString","isDataView","isView","isUint8Array","isUint8ClampedArray","isUint16Array","isUint32Array","isInt8Array","isInt16Array","isInt32Array","isBigInt64Array","isBigUint64Array","isWeakMap","isWeakSet","SharedArrayBufferCopy","isSharedArrayBufferToString","isSharedArrayBuffer","isAsyncFunction","isMapIterator","isSetIterator","isGeneratorObject","isWebAssemblyCompiledModule","method","getOwnPropertyDescriptors","descriptors","formatRegExp","format","objects","stringify","_","isNull","deprecate","noDeprecation","throwDeprecation","traceDeprecation","trace","debugs","debugEnvRegex","NODE_DEBUG","debugEnv","toUpperCase","opts","seen","stylize","stylizeNoColor","colors","isBoolean","_extend","isUndefined","stylizeWithColor","formatValue","styleType","style","styles","ret","primitive","simple","isNumber","formatPrimitive","visibleKeys","hash","idx","arrayToHash","isError","formatError","output","braces","toUTCString","formatProperty","formatArray","reduce","prev","reduceToSingleString","line","ar","re","d","pad","n","debuglog","pid","types","isNullOrUndefined","isSymbol","isPrimitive","isBuffer","months","timestamp","time","getHours","getMinutes","getSeconds","getDate","getMonth","prop","inherits","origin","kCustomPromisifiedSymbol","callbackifyOnRejected","cb","newReason","promisify","original","promiseResolve","promiseReject","promise","reject","callbackify","callbackified","maybeCb","rej","foundName","os","fs","path","rbql","rbql_csv","csv_utils","number_regex","update_subcomponent_stats","field","is_first_line","max_field_components_lens","match_result","exec","cur_integer_part_length","cur_fractional_part_length","align_field","is_last_column","trim","delta_length","dot_pos","integer_delta_length","fractional_delta_length","trailing_spaces","make_table_name_key","file_path","find_table_path","vscode_global_state","main_table_dir","table_id","filepath","candidate_path","charAt","homedir","existsSync","isAbsolute","table_path","get_header_line","document","comment_prefix","num_lines","lineCount","lnum","line_text","lineAt","text","startsWith","RbqlIOHandlingError","VSCodeRecordIterator","RBQLInputIterator","delim","policy","has_header","table_name","variable_prefix","super","NR","NL","fields_info","first_defective_line","first_record","get_first_record","stop","header_line","smart_split","async","query_text","variable_map","parse_basic_variables","parse_array_variables","parse_attribute_variables","parse_dictionary_variables","get_line_rfc","rfc_line_buffer","record_line","accumulate_rfc_line_into_record","get_line_simple","do_get_record","record","warning","num_fields","get_warnings","inconsistent_records_info","entries","record_id","sort","condition","record_1","num_fields_1","record_2","num_fields_2","warn_msg","make_inconsistent_num_fields_warning","VSCodeWriter","RBQLOutputWriter","header_len","null_in_output","delim_in_simple_output","output_lines","polymorphic_join","simple_join","quoted_join","quoted_join_rfc","mono_join","set_header","header","write","fields","v","quote_field","rfc_quote_field","normalize_fields","out_fields","sub_array_delim","VSCodeTableRegistry","get_iterator_by_table_id","_table_id","VSCodeFileSystemCSVRegistry","RBQLTableRegistry","input_file_dir","encoding","stream","record_iterator","bulk_input_path","createReadStream","CSVRecordIterator","output_warnings","basename","read_header","input_reader","createInterface","closed","promise_resolve","promise_reject","output_promise","close","rbql_query_web","input_document","input_delim","input_policy","output_delim","output_policy","with_headers","join_tables_registry","input_iterator","output_writer","query","rbql_query_node","input_path","output_path","csv_encoding","user_init_code","input_stream","stdin","output_stream","close_output_on_finish","stdout","createWriteStream","is_ascii","default_init_source_path","read_user_init_code","dirname","CSVWriter","populate_optimistic_rfc_csv_record_map","requested_end_record","dst_record_map","record_begin","match_list","has_unbalanced_double_quote","get_default_js_udf_content","get_default_python_udf_content","align_columns","active_doc","column_stats","result_lines","has_edit","fnum","adjusted","shrink_columns","calc_column_stats","adjust_column_stats","adjusted_stats","column_stat","field_rgx","field_rgx_external_whitespaces","extract_next_field","src","dlm","preserve_quotes_and_whitespaces","allow_external_whitespaces","cidx","src_cur","match_obj","match_end","uidx","split_quoted_str","extraction_report","unquote_field","split_whitespace_separated_str","preserve_whitespaces","rgxp","unquote_fields","split_lines","external_rfc_line_buffer","current_line","multiline_row","RbqlParsingError","RbqlRuntimeError","InternalBadFieldError","bad_idx","params","replace_all","replacement","RBQLContext","writer","unnest_list","top_count","like_regex_cache","sort_key_expression","aggregation_stage","aggregation_key_expression","functional_aggregators","join_map_impl","join_map","lhs_join_var_expression","where_expression","select_expression","update_expressions","variables_init_code","query_context","wrong_aggregation_usage_error","RBQL_VERSION","check_if_brackets_match","opening_bracket","closing_bracket","parse_root_bracket_level_text_spans","text_spans","last_pos","bracket_stack","cur_char","span","unquote_string","quoted_str","column_info_from_text_span","text_span","string_literals","rbql_star_marker","simple_var_match","attribute_match","subscript_int_match","subscript_str_match","column_index","column_name","is_star","replaced_string_literal_id","unquoted_column_name","adhoc_parse_select_expression_to_column_infos","ts","stable_compare","safe_get","safe_join_get","safe_set","regexp_escape","like_to_regex","pattern","converted","like","matcher","LIKE","RBQLAggregationToken","marker_id","UnnestMarker","UNNEST","vals","unnest","Unnest","UNFOLD","parse_number","MinAggregator","stats","increment","cur_aggr","get_final","MaxAggregator","SumAggregator","AvgAggregator","cur_sum","cur_cnt","VarianceAggregator","cur_sum_sq","avg_val","MedianAggregator","m","CountAggregator","ArrayAggAggregator","post_proc","ConstGroupVerifier","output_index","const_values","old_value","init_aggregator","generator_name","MIN","Min","MAX","Max","COUNT","Count","SUM","sum","Sum","AVG","avg","Avg","VARIANCE","variance","Variance","MEDIAN","median","Median","ARRAY_AGG","array_agg","FOLD","add_to_set","dst_set","len_before","TopWriter","subwriter","NW","finish","UniqWriter","UniqCountWriter","records","old_val","unshift","SortedWriter","reverse_sort","unsorted_entries","stable_entry","reverse","entry","AggregateWriter","aggregators","aggregation_keys","all_keys","from","ag","InnerJoiner","get_rhs","lhs_key","get_join_records","LeftJoiner","null_record","max_record_len","StrictLeftJoiner","select_except","except_fields","select_simple","sort_key","sort_entry","select_aggregated","transparent_values","num_aggregators_found","trans_value","select_unnested","folded_fields","unnest_pos","findIndex","PROCESS_SELECT_COMMON","PROCESS_SELECT_SIMPLE","PROCESS_SELECT_JOIN","PROCESS_UPDATE_JOIN","PROCESS_UPDATE_SIMPLE","MAIN_LOOP_BODY","embed_expression","parent_code","child_placeholder","child_expression","embed_code","child_code","parent_lines","child_lines","placeholder_indentation","generate_main_loop_code","is_select_query","is_join_query","js_code","compile_and_run","main_loop_body","main_loop_promise","lower_case_query","toLowerCase","GROUP_BY","UPDATE","SELECT","JOIN","INNER_JOIN","LEFT_JOIN","LEFT_OUTER_JOIN","STRICT_LEFT_JOIN","ORDER_BY","WHERE","LIMIT","EXCEPT","WITH","get_ambiguous_error_msg","variable_name","get_all_matches","regexp","str_strip","strip_comments","cline","combine_string_literals","backend_expression","prefix","dst_variables_map","matches","field_num","initialize","index","js_string_escape_column_name","quote_char","query_probably_has_dictionary_variable","continuous_name_segments","continuous_segment","column_names","dict_test_rgx","escaped_column_name","column_names_source","column_names_from_query","zero_based_idx","map_variables_directly","ensure_no_ambiguous_variables","input_column_names","join_column_names","join_column_names_set","parse_join_expression","invalid_join_syntax_error","variable_pairs","pair_rgx","and_rgx","resolve_join_variables","input_variables_map","join_variables_map","lhs_variables","rhs_indices","valid_join_syntax_msg","variable_pair","join_var_1","join_var_2","lhs_key_index","rhs_key_index","generate_common_init_code","base_var","attr_var","generate_init_statements","variables_map","indent","code_lines","simple_var_name_rgx","var_info","variable_declaration_keyword","replace_star_count","aggregate_expression","replace_star_vars","rbql_expression","replacement_expression","replace_star_vars_for_header_parsing","translate_update_expression","update_expression","first_assignment_error","assignment_looking_rgx","dst_var_name","var_index","current_indent","translate_select_expression","expression_without_stars","translated","translated_for_header","separate_string_literals","rgx","format_parts","idx_before","literal_id","string_literal","start_index","lastIndex","format_expression","locate_statements","statement_groups","ig","statement","match_str","separate_actions","with_match","ordered_statements","statement_start","span_start","span_end","statement_params","new_span","find_top","rb_actions","select_action","translate_except_expression","except_expression","input_header","skip_vars","skip_indices","var_name","HashJoinMap","key_indices","hash_map","nr","key_index","polymorphic_get_key","get_single_key","get_multi_key","ki","get_record","nf","key_records","cleanup_query","remove_redundant_table_name","select_output_header","join_header","query_column_infos","output_header","qci","handle_query_modifier","TableIterator","table","normalize_column_names","stopped","TableWriter","external_table","SingleTableRegistry","shallow_parse_input_query","get_variables_map","rhs_table_id","join_record_iterator","get_header","sql_join_type","build","select_expression_for_ast","query_table","input_table","output_table","join_table","output_column_names","exception_to_error_info","exceptions_type_map","error_type","utf_decoding_error","rbql_init_source_path","readFileSync","name_record","index_path","content","lines","try_read_index","get_index_record","RecordQueue","push_stack","pull_stack","enqueue","dequeue","csv_path","first_record_should_be_emitted","header_preread_complete","decoder","TextDecoder","fatal","input_exhausted","started","utf8_bom_removed","partially_decoded_line","partially_decoded_line_ends_with_cr","resolve_current_record","reject_current_record","current_exception","produced_records_queue","process_line_polymorphic","process_partial_rfc_record_line","process_record_line","modifier","reset_external_callbacks","try_propagate_exception","exception","store_or_propagate_exception","pause","preread_first_record","try_resolve_next_record","isPaused","resume","parent_iterator","current_record_promise","num_records","process_line","clean_line","assumed_source_encoding","remove_utf8_bom","process_data_stream_chunk","data_chunk","decoded_string","decode","first_line_index","process_data_bulk","control_buffer","Buffer","process_data_stream_end","last_line","destroy","readFile","close_stream_on_finish","line_separator","setDefaultEncoding","error_obj","store_first_error","first_error","writer_error","_write_all","output_encoding","FileSystemCSVRegistry","interpret_named_csv_format","format_name","query_csv","require","possibleNames","out","__webpack_module_cache__","__webpack_require__","moduleId","cachedModule","__webpack_modules__","vscode","rainbow_utils","is_web_ext","poor_rbql_async_design_workaround_timeout","sleep","ms","log_message","workspace","workspaceFolders","workspace_folder_uri","uri","field_components","test_align_stats","max_components_lens","aligned_field","test_field_align","adjusted_components","test_adjust_column_stats","Uri","joinPath","openTextDocument","languageId","editor","showTextDocument","test_no_autodetection","state_report","commands","executeCommand","check_initialization_state","initialized","lazy_loaded","test_autodetection","test_manual_enable_disable","test_task","rbql_backend","rbql_query","check_last_rbql_warnings","warnings","activeTextEditor","length_after_query","getText","check_last_rbql_report","error_msg","enable_rfc_newlines","test_rbql_web","filename_before","fileName","length_before_query","filename_after_copy_back","test_rbql_node","length_original","length_aligned","lint_report","length_shrinked","text_with_comma","test_align_shrink_lint","length_after_column_edit","length_after_delete","test_column_edit"],"sourceRoot":""} \ No newline at end of file diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/extension.js b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/extension.js new file mode 100644 index 00000000..1ec0cf53 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/extension.js @@ -0,0 +1,1586 @@ +const vscode = require('vscode'); + +const path = require('path'); +const fs = require('fs'); +const os = require('os'); +const child_process = require('child_process'); + +// Please see DEV_README.md file for additional info. + +const csv_utils = require('./rbql_core/rbql-js/csv_utils.js'); + +var rbql_csv = null; // Using lazy load to improve startup performance. +function ll_rbql_csv() { + if (rbql_csv === null) + rbql_csv = require('./rbql_core/rbql-js/rbql_csv.js'); + return rbql_csv; +} + + +var rainbow_utils = null; // Using lazy load to improve startup performance. +function ll_rainbow_utils() { + if (rainbow_utils === null) + rainbow_utils = require('./rainbow_utils.js'); + return rainbow_utils; +} + + +const is_web_ext = (os.homedir === undefined); // Runs as web extension in browser. +const preview_window_size = 100; +const max_preview_field_length = 250; +const scratch_buf_marker = 'vscode_rbql_scratch'; + +let client_html_template_web = null; + +var lint_results = new Map(); +var aligned_files = new Set(); +var autodetection_stoplist = new Set(); +var original_language_ids = new Map(); +var result_set_parent_map = new Map(); + +var lint_status_bar_button = null; +var rbql_status_bar_button = null; +var align_shrink_button = null; +var rainbow_off_status_bar_button = null; +var copy_back_button = null; + +let last_statusbar_doc = null; + +var rbql_context = null; + +var last_rbql_queries = new Map(); // Query history does not replace this structure, it is also used to store partially entered queries for preview window switch. + +var client_html_template = null; + +var global_state = null; + +var preview_panel = null; + +var doc_edit_subscription = null; + +var _unit_test_last_rbql_report = null; // For unit tests only. +var _unit_test_last_warnings = null; // For unit tests only. + +const dialect_map = { + 'csv': [',', 'quoted'], + 'tsv': ['\t', 'simple'], + 'csv (semicolon)': [';', 'quoted'], + 'csv (pipe)': ['|', 'simple'], + 'csv (tilde)': ['~', 'simple'], + 'csv (caret)': ['^', 'simple'], + 'csv (colon)': [':', 'simple'], + 'csv (double quote)': ['"', 'simple'], + 'csv (equals)': ['=', 'simple'], + 'csv (dot)': ['.', 'simple'], + 'csv (whitespace)': [' ', 'whitespace'], + 'csv (hyphen)': ['-', 'simple'] +}; + + +// This structure will get properly initialized during the startup. +let absolute_path_map = { + 'rbql_client.js': null, + 'contrib/textarea-caret-position/index.js': null, + 'rbql_suggest.js': null, + 'rbql_logo.svg': null, + 'rbql_client.html': null, + 'rbql mock/rbql_mock.py': null, + 'rbql_core/vscode_rbql.py': null +}; + + +function show_single_line_error(error_msg) { + var active_window = vscode.window; + if (!active_window) + return; + // Do not "await" error messages because the promise gets resolved only on error dismissal. + active_window.showErrorMessage(error_msg); +} + + +function sleep(ms) { + return new Promise(resolve => setTimeout(resolve, ms)); +} + + +async function push_current_stack_to_js_callback_queue_to_allow_ui_update() { + await sleep(0); +} + + +function map_separator_to_language_id(separator) { + for (let language_id in dialect_map) { + if (!dialect_map.hasOwnProperty(language_id)) + continue; + if (dialect_map[language_id][0] == separator) + return language_id; + } + return null; +} + + +function get_from_global_state(key, default_value) { + if (global_state) { + var value = global_state.get(key); + if (value !== null && value !== undefined) + return value; + } + return default_value; +} + + +async function save_to_global_state(key, value) { + if (global_state && key) { + await global_state.update(key, value); + return true; + } + return false; +} + + +function get_rfc_record_text(document, record_start, record_end) { + let result = []; + for (let i = record_start; i < record_end && i < document.lineCount; i++) { + result.push(document.lineAt(i).text); + } + return result.join('\n'); +} + + +async function replace_doc_content(active_editor, active_doc, new_content) { + let invalid_range = new vscode.Range(0, 0, active_doc.lineCount /* Intentionally missing the '-1' */, 0); + let full_range = active_doc.validateRange(invalid_range); + await active_editor.edit(edit => edit.replace(full_range, new_content)); +} + + +function sample_preview_records_from_context(rbql_context, dst_message) { + let document = rbql_context.input_document; + let delim = rbql_context.delim; + let policy = rbql_context.policy; + + rbql_context.requested_start_record = Math.max(rbql_context.requested_start_record, 0); + + let preview_records = []; + if (rbql_context.enable_rfc_newlines) { + let requested_end_record = rbql_context.requested_start_record + preview_window_size; + ll_rainbow_utils().populate_optimistic_rfc_csv_record_map(document, requested_end_record, rbql_context.rfc_record_map); + rbql_context.requested_start_record = Math.max(0, Math.min(rbql_context.requested_start_record, rbql_context.rfc_record_map.length - preview_window_size)); + for (let nr = rbql_context.requested_start_record; nr < rbql_context.rfc_record_map.length && preview_records.length < preview_window_size; nr++) { + let [record_start, record_end] = rbql_context.rfc_record_map[nr]; + let record_text = get_rfc_record_text(document, record_start, record_end); + let [cur_record, warning] = csv_utils.smart_split(record_text, delim, policy, false); + if (warning) { + dst_message.preview_sampling_error = `Double quotes are not consistent in record ${nr + 1} which starts at line ${record_start + 1}`; + return; + } + preview_records.push(cur_record); + } + } else { + let num_records = document.lineCount; + if (document.lineAt(Math.max(num_records - 1, 0)).text == '') + num_records -= 1; + rbql_context.requested_start_record = Math.max(0, Math.min(rbql_context.requested_start_record, num_records - preview_window_size)); + for (let nr = rbql_context.requested_start_record; nr < num_records && preview_records.length < preview_window_size; nr++) { + let line_text = document.lineAt(nr).text; + let cur_record = csv_utils.smart_split(line_text, delim, policy, false)[0]; + preview_records.push(cur_record); + } + } + + for (let r = 0; r < preview_records.length; r++) { + let cur_record = preview_records[r]; + for (let c = 0; c < cur_record.length; c++) { + if (cur_record[c].length > max_preview_field_length) { + cur_record[c] = cur_record[c].substr(0, max_preview_field_length) + '###UI_STRING_TRIM_MARKER###'; + } + } + } + dst_message.preview_records = preview_records; + dst_message.start_record_zero_based = rbql_context.requested_start_record; +} + + +function make_header_key(file_path) { + return 'rbql_header:' + file_path; +} + + +function make_rfc_policy_key(file_path) { + return 'enable_rfc_newlines:' + file_path; +} + + +function make_with_headers_key(file_path) { + return 'rbql_with_headers:' + file_path; +} + + +function get_from_config(param_name, default_value) { + const config = vscode.workspace.getConfiguration('rainbow_csv'); + return config ? config.get(param_name) : default_value; +} + + +function get_header_from_document(document, delim, policy) { + let comment_prefix = get_from_config('comment_prefix', ''); + let header_line = ll_rainbow_utils().get_header_line(document, comment_prefix); + return csv_utils.smart_split(header_line, delim, policy, /*preserve_quotes_and_whitespaces=*/false)[0]; +} + + +function get_header(document, delim, policy) { + var file_path = document.fileName; + if (file_path) { + let raw_header = get_from_global_state(make_header_key(file_path), null); + if (raw_header) { + return JSON.parse(raw_header); + } + } + return get_header_from_document(document, delim, policy); +} + + +function get_field_by_line_position(fields, query_pos) { + if (!fields.length) + return null; + var col_num = 0; + var cpos = fields[col_num].length + 1; + while (query_pos > cpos && col_num + 1 < fields.length) { + col_num += 1; + cpos = cpos + fields[col_num].length + 1; + } + return col_num; +} + + +function make_hover_text(document, position, language_id, enable_tooltip_column_names, enable_tooltip_warnings) { + let [delim, policy] = dialect_map[language_id]; + var lnum = position.line; + var cnum = position.character; + var line = document.lineAt(lnum).text; + + let comment_prefix = get_from_config('comment_prefix', ''); + if (comment_prefix && line.startsWith(comment_prefix)) + return 'Comment'; + + var report = csv_utils.smart_split(line, delim, policy, true); + + var entries = report[0]; + var warning = report[1]; + var col_num = get_field_by_line_position(entries, cnum + 1); + + if (col_num == null) + return null; + var result = 'Col #' + (col_num + 1); + + var header = get_header(document, delim, policy); + if (enable_tooltip_column_names && col_num < header.length) { + const max_label_len = 50; + let column_label = header[col_num].trim(); + var short_column_label = column_label.substr(0, max_label_len); + if (short_column_label != column_label) + short_column_label = short_column_label + '...'; + result += ', Header: "' + short_column_label + '"'; + } + if (enable_tooltip_warnings) { + if (warning) { + result += '; ERR: Inconsistent double quotes in line'; + } else if (header.length != entries.length) { + result += `; WARN: Inconsistent num of fields, header: ${header.length}, this line: ${entries.length}`; + } + } + return result; +} + + +function make_hover(document, position, language_id, cancellation_token) { + if (last_statusbar_doc != document) { + refresh_status_bar_buttons(document); // Being paranoid and making sure that the buttons are visible. + } + if (!get_from_config('enable_tooltip', false)) { + return; + } + let enable_tooltip_column_names = get_from_config('enable_tooltip_column_names', false); + let enable_tooltip_warnings = get_from_config('enable_tooltip_warnings', false); + var hover_text = make_hover_text(document, position, language_id, enable_tooltip_column_names, enable_tooltip_warnings); + if (hover_text && !cancellation_token.isCancellationRequested) { + let mds = null; + try { + mds = new vscode.MarkdownString(); + mds.appendCodeblock(hover_text, 'rainbow hover markup'); + } catch (e) { + mds = hover_text; // Older VSCode versions may not have MarkdownString/appendCodeblock functionality. + } + return new vscode.Hover(mds); + } else { + return null; + } +} + + +function produce_lint_report(active_doc, delim, policy) { + let comment_prefix = get_from_config('comment_prefix', ''); + let detect_trailing_spaces = get_from_config('csv_lint_detect_trailing_spaces', false); + let first_trailing_space_line = null; + var num_lines = active_doc.lineCount; + var num_fields = null; + for (var lnum = 0; lnum < num_lines; lnum++) { + var line_text = active_doc.lineAt(lnum).text; + if (lnum + 1 == num_lines && !line_text) + break; + if (comment_prefix && line_text.startsWith(comment_prefix)) + continue; + var split_result = csv_utils.smart_split(line_text, delim, policy, true); + if (split_result[1]) { + return 'Error. Line ' + (lnum + 1) + ' has formatting error: double quote chars are not consistent'; + } + if (detect_trailing_spaces && first_trailing_space_line === null) { + let fields = split_result[0]; + for (let i = 0; i < fields.length; i++) { + if (fields[i].length && (fields[i].charAt(0) == ' ' || fields[i].slice(-1) == ' ')) { + first_trailing_space_line = lnum; + } + } + } + if (!num_fields) { + num_fields = split_result[0].length; + } + if (num_fields != split_result[0].length) { + return 'Error. Number of fields is not consistent: e.g. line 1 has ' + num_fields + ' fields, and line ' + (lnum + 1) + ' has ' + split_result[0].length + ' fields.'; + } + } + if (first_trailing_space_line !== null) { + return 'Leading/Trailing spaces detected: e.g. at line ' + (first_trailing_space_line + 1) + '. Run "Shrink" command to remove them.'; + } + return 'OK'; +} + + +function get_active_editor() { + var active_window = vscode.window; + if (!active_window) + return null; + var active_editor = active_window.activeTextEditor; + if (!active_editor) + return null; + return active_editor; +} + + +function get_active_doc(active_editor=null) { + if (!active_editor) + active_editor = get_active_editor(); + if (!active_editor) + return null; + var active_doc = active_editor.document; + if (!active_doc) + return null; + return active_doc; +} + + +function show_lint_status_bar_button(file_path, language_id) { + let lint_cache_key = `${file_path}.${language_id}`; + if (!lint_results.has(lint_cache_key)) + return; + var lint_report = lint_results.get(lint_cache_key); + if (!lint_status_bar_button) + lint_status_bar_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left); + lint_status_bar_button.text = 'CSVLint'; + if (lint_report === 'OK') { + lint_status_bar_button.color = '#62f442'; + } else if (lint_report == 'Processing...') { + lint_status_bar_button.color = '#A0A0A0'; + } else if (lint_report.indexOf('spaces detected') != -1) { + lint_status_bar_button.color = '#ffff28'; + } else { + lint_status_bar_button.color = '#f44242'; + } + lint_status_bar_button.tooltip = lint_report + '\nClick to recheck'; + lint_status_bar_button.command = 'rainbow-csv.CSVLint'; + lint_status_bar_button.show(); +} + + +function show_align_shrink_button(file_path) { + if (!align_shrink_button) + align_shrink_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left); + if (aligned_files.has(file_path)) { + align_shrink_button.text = 'Shrink'; + align_shrink_button.tooltip = 'Click to shrink table (Then you can click again to align)'; + align_shrink_button.command = 'rainbow-csv.Shrink'; + } else { + align_shrink_button.text = 'Align'; + align_shrink_button.tooltip = 'Click to align table (Then you can click again to shrink)'; + align_shrink_button.command = 'rainbow-csv.Align'; + } + align_shrink_button.show(); +} + + +function show_rainbow_off_status_bar_button() { + if (!rainbow_off_status_bar_button) + rainbow_off_status_bar_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left); + rainbow_off_status_bar_button.text = 'Rainbow OFF'; + rainbow_off_status_bar_button.tooltip = 'Click to restore original file type and syntax'; + rainbow_off_status_bar_button.command = 'rainbow-csv.RainbowSeparatorOff'; + rainbow_off_status_bar_button.show(); +} + + +function show_rbql_status_bar_button() { + if (!rbql_status_bar_button) + rbql_status_bar_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left); + rbql_status_bar_button.text = 'Query'; + rbql_status_bar_button.tooltip = 'Click to run SQL-like RBQL query'; + rbql_status_bar_button.command = 'rainbow-csv.RBQL'; + rbql_status_bar_button.show(); +} + + +function hide_status_bar_buttons() { + let all_buttons = [lint_status_bar_button, rbql_status_bar_button, rainbow_off_status_bar_button, copy_back_button, align_shrink_button]; + for (let i = 0; i < all_buttons.length; i++) { + if (all_buttons[i]) + all_buttons[i].hide(); + } +} + + +function show_rbql_copy_to_source_button(file_path) { + let parent_table_path = result_set_parent_map.get(file_path.toLowerCase()); + if (!parent_table_path || parent_table_path.indexOf(scratch_buf_marker) != -1) + return; + let parent_basename = path.basename(parent_table_path); + if (!copy_back_button) + copy_back_button = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left); + copy_back_button.text = 'Copy Back'; + copy_back_button.tooltip = `Copy to parent table: ${parent_basename}`; + copy_back_button.command = 'rainbow-csv.CopyBack'; + copy_back_button.show(); +} + + +function refresh_status_bar_buttons(active_doc=null) { + if (!active_doc) + active_doc = get_active_doc(); + last_statusbar_doc = active_doc; + var file_path = active_doc ? active_doc.fileName : null; + if (!active_doc || !file_path) { + hide_status_bar_buttons(); + return; + } + if (file_path.endsWith('.git')) { + return; // Sometimes for git-controlled dirs VSCode opens mysterious .git files. Skip them, don't hide buttons. + } + hide_status_bar_buttons(); + var language_id = active_doc.languageId; + if (!dialect_map.hasOwnProperty(language_id)) + return; + show_lint_status_bar_button(file_path, language_id); + show_rbql_status_bar_button(); + show_align_shrink_button(file_path); + show_rainbow_off_status_bar_button(); + show_rbql_copy_to_source_button(file_path); +} + + +function csv_lint(active_doc, is_manual_op) { + if (!active_doc) + active_doc = get_active_doc(); + if (!active_doc) + return null; + var file_path = active_doc.fileName; // For new unitled scratch documents this would be "Untitled-1", "Untitled-2", etc... + if (!file_path) + return null; + var language_id = active_doc.languageId; + if (!dialect_map.hasOwnProperty(language_id)) + return null; + let lint_cache_key = `${file_path}.${language_id}`; + if (!is_manual_op) { + if (lint_results.has(lint_cache_key)) + return null; + if (!get_from_config('enable_auto_csv_lint', false)) + return null; + } + lint_results.set(lint_cache_key, 'Processing...'); + refresh_status_bar_buttons(active_doc); // Visual feedback. + let [delim, policy] = dialect_map[language_id]; + var lint_report = produce_lint_report(active_doc, delim, policy); + lint_results.set(lint_cache_key, lint_report); + return lint_report; +} + + +async function csv_lint_cmd() { + // TODO re-run on each file save with content change. + let lint_report = csv_lint(null, true); + // Need timeout here to give user enough time to notice green -> yellow -> green switch, this is a sort of visual feedback. + await sleep(500); + refresh_status_bar_buttons(); + return lint_report; +} + + +async function run_internal_test_cmd(integration_test_options) { + if (integration_test_options && integration_test_options.check_initialization_state) { + // This mode is to ensure that the most basic operations do not cause rainbow csv to load extra (potentially heavy) code. + // Vim uses the same approach with its plugin/autoload folder layout design. + return {initialized: global_state !== null, lazy_loaded: rainbow_utils !== null}; + } + if (integration_test_options && integration_test_options.check_last_rbql_report) { + return _unit_test_last_rbql_report; + } + if (integration_test_options && integration_test_options.check_last_rbql_warnings) { + return {'warnings': _unit_test_last_warnings}; + } + return null; +} + + +async function show_warnings(warnings) { + _unit_test_last_warnings = []; + if (!warnings || !warnings.length) + return; + var active_window = vscode.window; + if (!active_window) + return null; + for (var i = 0; i < warnings.length; i++) { + // Do not "await" warning messages because the promise gets resolved only on warning dismissal. + active_window.showWarningMessage('RBQL warning: ' + warnings[i]); + } + _unit_test_last_warnings = warnings; +} + + +async function handle_rbql_result_file(text_doc, warnings) { + var out_delim = rbql_context.output_delim; + let language_id = map_separator_to_language_id(out_delim); + var active_window = vscode.window; + if (!active_window) + return; + try { + await active_window.showTextDocument(text_doc); + } catch (error) { + show_single_line_error('Unable to open RBQL result document'); + return; + } + if (language_id && text_doc.language_id != language_id) { + console.log('changing RBQL result language ' + text_doc.language_id + ' -> ' + language_id); + await vscode.languages.setTextDocumentLanguage(text_doc, language_id); + } + await show_warnings(warnings); +} + + +function run_command(cmd, args, close_and_error_guard, callback_func) { + var command = child_process.spawn(cmd, args, {'windowsHide': true}); + var stdout = ''; + var stderr = ''; + command.stdout.on('data', function(data) { + stdout += data.toString(); + }); + command.stderr.on('data', function(data) { + stderr += data.toString(); + }); + command.on('close', function(code) { + if (!close_and_error_guard['process_reported']) { + close_and_error_guard['process_reported'] = true; + callback_func(code, stdout, stderr); + } + }); + command.on('error', function(error) { + var error_msg = error ? error.name + ': ' + error.message : ''; + if (!close_and_error_guard['process_reported']) { + close_and_error_guard['process_reported'] = true; + callback_func(1, '', 'Something went wrong. Make sure you have python installed and added to PATH variable in your OS. Or you can use it with JavaScript instead - it should work out of the box\nDetails:\n' + error_msg); + } + }); +} + + +async function handle_command_result(src_table_path, dst_table_path, error_code, stdout, stderr, webview_report_handler) { + let json_report = stdout; + let error_type = null; + let error_msg = null; + let warnings = []; + if (error_code || !json_report || stderr) { + error_type = 'Integration'; + error_msg = stderr ? stderr : 'empty error'; + } else { + try { + let report = JSON.parse(json_report); + if (report.hasOwnProperty('error_type')) + error_type = report['error_type']; + if (report.hasOwnProperty('error_msg')) + error_msg = report['error_msg']; + if (report.hasOwnProperty('warnings')) + warnings = report['warnings']; + } catch (e) { + error_type = 'Integration'; + error_msg = 'Unable to parse JSON report'; + } + } + webview_report_handler(error_type, error_msg); + if (error_type || error_msg) { + return; // Just exit: error would be shown in the preview window. + } + // No need to close the RBQL console here, better to leave it open so it can be used to quickly adjust the query if needed. + autodetection_stoplist.add(dst_table_path); + result_set_parent_map.set(dst_table_path.toLowerCase(), src_table_path); + let doc = await vscode.workspace.openTextDocument(dst_table_path); + await handle_rbql_result_file(doc, warnings); +} + + +function get_dst_table_name(input_path, output_delim) { + var table_name = path.basename(input_path); + var orig_extension = path.extname(table_name); + var delim_ext_map = {'\t': '.tsv', ',': '.csv'}; + var dst_extension = '.txt'; + if (delim_ext_map.hasOwnProperty(output_delim)) { + dst_extension = delim_ext_map[output_delim]; + } else if (orig_extension.length > 1) { + dst_extension = orig_extension; + } + let result_table_name = table_name + dst_extension; + if (result_table_name == table_name) { // Just being paranoid to avoid overwriting input table accidentally when output dir configured to be the same as input. + result_table_name += '.txt'; + } + return result_table_name; +} + + +function file_path_to_query_key(file_path) { + return (file_path && file_path.indexOf(scratch_buf_marker) != -1) ? scratch_buf_marker : file_path; +} + +function get_dst_table_dir(input_table_path) { + let rbql_output_dir = get_from_config('rbql_output_dir', 'TMP') + if (rbql_output_dir == 'TMP') { + return os.tmpdir(); + } else if (rbql_output_dir == 'INPUT') { + return path.dirname(input_table_path); + } else { + // Return custom directory. If the directory does not exist or isn't writable RBQL itself will report more or less clear error. + return rbql_output_dir; + } +} + + +async function run_rbql_query(input_path, csv_encoding, backend_language, rbql_query, output_dialect, enable_rfc_newlines, with_headers, webview_report_handler) { + last_rbql_queries.set(file_path_to_query_key(input_path), rbql_query); + var cmd = 'python'; + const test_marker = 'test '; + let close_and_error_guard = {'process_reported': false}; + + let [input_delim, input_policy] = [rbql_context.delim, rbql_context.policy]; + if (input_policy == 'quoted' && enable_rfc_newlines) + input_policy = 'quoted_rfc'; + let [output_delim, output_policy] = [input_delim, input_policy]; + if (output_dialect == 'csv') + [output_delim, output_policy] = [',', 'quoted']; // XXX should it be "quoted_rfc" instead? + if (output_dialect == 'tsv') + [output_delim, output_policy] = ['\t', 'simple']; + rbql_context.output_delim = output_delim; + + let output_path = is_web_ext ? null : path.join(get_dst_table_dir(input_path), get_dst_table_name(input_path, output_delim)); + + if (rbql_query.startsWith(test_marker)) { + if (rbql_query.indexOf('nopython') != -1) { + cmd = 'nopython'; + } + let args = [absolute_path_map['rbql mock/rbql_mock.py'], rbql_query]; + run_command(cmd, args, close_and_error_guard, function(error_code, stdout, stderr) { handle_command_result(input_path, output_path, error_code, stdout, stderr, webview_report_handler); }); + return; + } + if (backend_language == 'js') { + let warnings = []; + let result_doc = null; + try { + if (is_web_ext) { + let result_lines = await ll_rainbow_utils().rbql_query_web(rbql_query, rbql_context.input_document, input_delim, input_policy, output_delim, output_policy, warnings, with_headers, null); + let output_doc_cfg = {content: result_lines.join('\n'), language: map_separator_to_language_id(output_delim)}; + result_doc = await vscode.workspace.openTextDocument(output_doc_cfg); + } else { + let csv_options = {'bulk_read': true}; + await ll_rainbow_utils().rbql_query_node(global_state, rbql_query, input_path, input_delim, input_policy, output_path, output_delim, output_policy, csv_encoding, warnings, with_headers, null, '', csv_options); + result_set_parent_map.set(output_path.toLowerCase(), input_path); + autodetection_stoplist.add(output_path); + result_doc = await vscode.workspace.openTextDocument(output_path); + } + } catch (e) { + let [error_type, error_msg] = ll_rbql_csv().exception_to_error_info(e); + webview_report_handler(error_type, error_msg); + return; + } + webview_report_handler(null, null); + await handle_rbql_result_file(result_doc, warnings); + } else { + if (is_web_ext) { + webview_report_handler('Input error', 'Python backend for RBQL is not supported in web version, please use JavaScript backend.'); + return; + } + let cmd_safe_query = Buffer.from(rbql_query, "utf-8").toString("base64"); + let args = [absolute_path_map['rbql_core/vscode_rbql.py'], cmd_safe_query, input_path, input_delim, input_policy, output_path, output_delim, output_policy, csv_encoding]; + if (with_headers) + args.push('--with_headers'); + run_command(cmd, args, close_and_error_guard, function(error_code, stdout, stderr) { handle_command_result(input_path, output_path, error_code, stdout, stderr, webview_report_handler); }); + } +} + + +function get_dialect(document) { + var language_id = document.languageId; + if (!dialect_map.hasOwnProperty(language_id)) + return ['monocolumn', 'monocolumn']; + return dialect_map[language_id]; +} + + +async function set_header_line() { + let active_editor = get_active_editor(); + if (!active_editor) + return; + var active_doc = get_active_doc(active_editor); + if (!active_doc) + return; + + var dialect = get_dialect(active_doc); + var delim = dialect[0]; + var policy = dialect[1]; + if (policy == 'monocolumn') { + show_single_line_error('Unable to set header line: no separator specified'); + return; + } + let file_path = active_doc.fileName; + if (!file_path) { + show_single_line_error('Unable to set header line for non-file documents'); + return; + } + let selection = active_editor.selection; + let raw_header = active_doc.lineAt(selection.start.line).text; + + let header = csv_utils.smart_split(raw_header, delim, policy, false)[0]; + await save_to_global_state(make_header_key(file_path), JSON.stringify(header)); +} + + +async function set_rainbow_separator() { + let active_editor = get_active_editor(); + if (!active_editor) + return; + var active_doc = get_active_doc(active_editor); + if (!active_doc) + return; + let original_language_id = active_doc.languageId; + let selection = active_editor.selection; + if (!selection) { + show_single_line_error("Selection is empty"); + return; + } + if (selection.start.line != selection.end.line || selection.start.character + 1 != selection.end.character) { + show_single_line_error("Selection must contain exactly one separator character"); + return; + } + let separator = active_doc.lineAt(selection.start.line).text.charAt(selection.start.character); + let language_id = map_separator_to_language_id(separator); + if (!language_id) { + show_single_line_error("Selected separator is not supported"); + return; + } + + let doc = await vscode.languages.setTextDocumentLanguage(active_doc, language_id); + original_language_ids.set(doc.fileName, original_language_id); + csv_lint(doc, false); + refresh_status_bar_buttons(doc); +} + + +async function restore_original_language() { + var active_doc = get_active_doc(); + if (!active_doc) + return; + let file_path = active_doc.fileName; + autodetection_stoplist.add(file_path); + let original_language_id = 'plaintext'; + if (original_language_ids.has(file_path)) { + original_language_id = original_language_ids.get(file_path); + } + if (!original_language_id || original_language_id == active_doc.languageId) { + show_single_line_error("Unable to restore original language"); + return; + } + + let doc = await vscode.languages.setTextDocumentLanguage(active_doc, original_language_id); + original_language_ids.delete(file_path); + refresh_status_bar_buttons(doc); +} + + +async function set_join_table_name() { + if (is_web_ext) { + show_single_line_error('This command is currently unavailable in web mode.'); + return; + } + var active_doc = get_active_doc(); + if (!active_doc) + return; + let file_path = active_doc.fileName; + if (!file_path) { + show_single_line_error('Unable to use this document as join table'); + return; + } + var title = "Input table name to use in RBQL JOIN expressions instead of table path"; + var input_box_props = {"prompt": title, "value": 'b'}; + let table_name = await vscode.window.showInputBox(input_box_props); + if (!table_name) + return; // User pressed Esc and closed the input box. + save_to_global_state(ll_rainbow_utils().make_table_name_key(table_name), file_path); +} + + +async function set_virtual_header() { + var active_doc = get_active_doc(); + var dialect = get_dialect(active_doc); + var delim = dialect[0]; + var policy = dialect[1]; + var file_path = active_doc.fileName; + if (!file_path) { + show_single_line_error('Unable to edit column names for non-file documents'); + return; + } + if (policy == 'monocolumn') { + show_single_line_error('Unable to set virtual header: no separator specified'); + return; + } + var old_header = get_header(active_doc, delim, policy); + var title = "Adjust column names displayed in hover tooltips. Actual header line and file content won't be affected."; + var old_header_str = quoted_join(old_header, delim); + var input_box_props = {"prompt": title, "value": old_header_str}; + let raw_new_header = await vscode.window.showInputBox(input_box_props); + if (!raw_new_header) + return; // User pressed Esc and closed the input box. + let new_header = csv_utils.smart_split(raw_new_header, delim, policy, false)[0]; + await save_to_global_state(make_header_key(file_path), JSON.stringify(new_header)); +} + + +async function column_edit(edit_mode) { + let active_editor = get_active_editor(); + if (!active_editor || !active_editor.selection) + return; + let active_doc = active_editor.document; + if (!active_doc) + return; + let dialect = get_dialect(active_doc); + let delim = dialect[0]; + let policy = dialect[1]; + let comment_prefix = get_from_config('comment_prefix', ''); + + let position = active_editor.selection.active; + let lnum = position.line; + let cnum = position.character; + let line = active_doc.lineAt(lnum).text; + + let report = csv_utils.smart_split(line, delim, policy, true); + + let entries = report[0]; + let quoting_warning = report[1]; + let col_num = get_field_by_line_position(entries, cnum + 1); + + let selections = []; + let num_lines = active_doc.lineCount; + if (num_lines >= 10000) { + show_single_line_error('Multicursor column edit works only for files smaller than 10000 lines.'); + return; + } + for (let lnum = 0; lnum < num_lines; lnum++) { + let line_text = active_doc.lineAt(lnum).text; + if (lnum + 1 == num_lines && !line_text) + break; + if (comment_prefix && line_text.startsWith(comment_prefix)) + continue; + let report = csv_utils.smart_split(line_text, delim, policy, true); + let entries = report[0]; + quoting_warning = quoting_warning || report[1]; + if (col_num >= entries.length) { + show_single_line_error(`Line ${lnum + 1} doesn't have field number ${col_num + 1}`); + return; + } + let char_pos_before = entries.slice(0, col_num).join('').length + col_num; + let char_pos_after = entries.slice(0, col_num + 1).join('').length + col_num; + if (edit_mode == 'ce_before' && policy == 'quoted' && line_text.substring(char_pos_before - 2, char_pos_before + 2).indexOf('"') != -1) { + show_single_line_error(`Accidental data corruption prevention: Cursor at line ${lnum + 1} will not be set: a double quote is in proximity.`); + return; + } + if (edit_mode == 'ce_after' && policy == 'quoted' && line_text.substring(char_pos_after - 2, char_pos_after + 2).indexOf('"') != -1) { + show_single_line_error(`Accidental data corruption prevention: Cursor at line ${lnum + 1} will not be set: a double quote is in proximity.`); + return; + } + if (edit_mode == 'ce_select' && char_pos_before == char_pos_after) { + show_single_line_error(`Accidental data corruption prevention: The column can not be selected: field ${col_num + 1} at line ${lnum + 1} is empty.`); + return; + } + let position_before = new vscode.Position(lnum, char_pos_before); + let position_after = new vscode.Position(lnum, char_pos_after); + if (edit_mode == 'ce_before') { + selections.push(new vscode.Selection(position_before, position_before)); + } + if (edit_mode == 'ce_after') { + selections.push(new vscode.Selection(position_after, position_after)); + } + if (edit_mode == 'ce_select') { + selections.push(new vscode.Selection(position_before, position_after)); + } + } + active_editor.selections = selections; + if (quoting_warning) { + vscode.window.showWarningMessage('Some lines have quoting issues: cursors positioning may be incorrect.'); + } + // Call showTextDocument so that the editor will gain focus and the cursors will become active and blinking. This is a critical step here! + await vscode.window.showTextDocument(active_doc); +} + + +async function shrink_table() { + let active_editor = get_active_editor(); + let active_doc = get_active_doc(active_editor); + if (!active_doc) + return; + let language_id = active_doc.languageId; + if (!dialect_map.hasOwnProperty(language_id)) + return; + let [delim, policy] = dialect_map[language_id]; + let comment_prefix = get_from_config('comment_prefix', ''); + let progress_options = {location: vscode.ProgressLocation.Window, title: 'Rainbow CSV'}; + await vscode.window.withProgress(progress_options, async (progress) => { + progress.report({message: 'Preparing'}); + await push_current_stack_to_js_callback_queue_to_allow_ui_update(); + let [shrinked_doc_text, first_failed_line] = ll_rainbow_utils().shrink_columns(active_doc, delim, policy, comment_prefix); + if (first_failed_line) { + show_single_line_error(`Unable to shrink: Inconsistent double quotes at line ${first_failed_line}`); + return; + } + aligned_files.delete(active_doc.fileName); + refresh_status_bar_buttons(active_doc); + if (shrinked_doc_text === null) { + vscode.window.showWarningMessage('No trailing whitespaces found, skipping'); + return; + } + progress.report({message: 'Shrinking columns'}); + await push_current_stack_to_js_callback_queue_to_allow_ui_update(); + await replace_doc_content(active_editor, active_doc, shrinked_doc_text); + }); +} + + +async function align_table() { + let active_editor = get_active_editor(); + let active_doc = get_active_doc(active_editor); + if (!active_doc) + return; + let language_id = active_doc.languageId; + if (!dialect_map.hasOwnProperty(language_id)) + return; + let [delim, policy] = dialect_map[language_id]; + let comment_prefix = get_from_config('comment_prefix', ''); + let progress_options = {location: vscode.ProgressLocation.Window, title: 'Rainbow CSV'}; + await vscode.window.withProgress(progress_options, async (progress) => { + progress.report({message: 'Calculating column statistics'}); + await push_current_stack_to_js_callback_queue_to_allow_ui_update(); + let [column_stats, first_failed_line] = ll_rainbow_utils().calc_column_stats(active_doc, delim, policy, comment_prefix); + if (first_failed_line) { + show_single_line_error(`Unable to align: Inconsistent double quotes at line ${first_failed_line}`); + return; + } + column_stats = ll_rainbow_utils().adjust_column_stats(column_stats); + if (column_stats === null) { + show_single_line_error('Unable to allign: Internal Rainbow CSV Error'); + return; + } + progress.report({message: 'Preparing final alignment'}); + await push_current_stack_to_js_callback_queue_to_allow_ui_update(); + aligned_doc_text = ll_rainbow_utils().align_columns(active_doc, delim, policy, comment_prefix, column_stats); + aligned_files.add(active_doc.fileName); + refresh_status_bar_buttons(active_doc); + if (aligned_doc_text === null) { + vscode.window.showWarningMessage('Table is already aligned, skipping'); + return; + } + // The last stage of actually applying the edits takes almost 80% of the whole alignment runtime. + progress.report({message: 'Aligning columns'}); + await push_current_stack_to_js_callback_queue_to_allow_ui_update(); + await replace_doc_content(active_editor, active_doc, aligned_doc_text); + }); +} + + +async function do_copy_back(query_result_doc, active_editor) { + let data = query_result_doc.getText(); + let active_doc = get_active_doc(active_editor); + if (!active_doc) + return; + await replace_doc_content(active_editor, active_doc, data); +} + + +async function copy_back() { + if (is_web_ext) { + show_single_line_error('This command is currently unavailable in web mode.'); + return; + } + let result_doc = get_active_doc(); + if (!result_doc) + return; + let file_path = result_doc.fileName; + let parent_table_path = result_set_parent_map.get(file_path.toLowerCase()); + if (!parent_table_path) + return; + let parent_doc = await vscode.workspace.openTextDocument(parent_table_path); + let parent_editor = await vscode.window.showTextDocument(parent_doc); + await do_copy_back(result_doc, parent_editor); +} + + +async function update_query_history(query) { + let history_list = get_from_global_state('rbql_query_history', []); + let old_index = history_list.indexOf(query); + if (old_index != -1) { + history_list.splice(old_index, 1); + } else if (history_list.length >= 20) { + history_list.splice(0, 1); + } + history_list.push(query); + await save_to_global_state('rbql_query_history', history_list); +} + + +async function handle_rbql_client_message(webview, message, integration_test_options=null) { + let message_type = message['msg_type']; + + let webview_report_handler = async function(error_type, error_msg) { + let report_msg = {'msg_type': 'rbql_report'}; + if (error_type) + report_msg["error_type"] = error_type; + if (error_msg) + report_msg["error_msg"] = error_msg; + _unit_test_last_rbql_report = report_msg; + await webview.postMessage(report_msg); + }; + + if (message_type == 'handshake') { + var backend_language = get_from_global_state('rbql_backend_language', 'js'); + var encoding = get_from_global_state('rbql_encoding', 'utf-8'); + var init_msg = {'msg_type': 'handshake', 'backend_language': backend_language, 'encoding': encoding}; + sample_preview_records_from_context(rbql_context, init_msg); + let path_key = file_path_to_query_key(rbql_context.input_document_path); + if (last_rbql_queries.has(path_key)) + init_msg['last_query'] = last_rbql_queries.get(path_key); + let history_list = get_from_global_state('rbql_query_history', []); + init_msg['query_history'] = history_list; + init_msg['policy'] = rbql_context.policy; + init_msg['enable_rfc_newlines'] = rbql_context.enable_rfc_newlines; + init_msg['with_headers'] = rbql_context.with_headers; + init_msg['header'] = rbql_context.header; + init_msg['is_web_ext'] = is_web_ext; + if (integration_test_options) { + init_msg['integration_test_language'] = integration_test_options.rbql_backend; + init_msg['integration_test_query'] = integration_test_options.rbql_query; + init_msg['integration_test_with_headers'] = integration_test_options.with_headers || false; + init_msg['integration_test_enable_rfc_newlines'] = integration_test_options.enable_rfc_newlines || false; + } + await webview.postMessage(init_msg); + } + + if (message_type == 'fetch_table_header') { + try { + let table_id = message['table_id']; + let encoding = message['encoding']; + + let input_table_dir = rbql_context.input_document_path ? path.dirname(rbql_context.input_document_path) : null; + let table_path = ll_rainbow_utils().find_table_path(global_state, input_table_dir, table_id); + if (!table_path) + return; + let header_line = await ll_rainbow_utils().read_header(table_path, encoding); + let [fields, warning] = csv_utils.smart_split(header_line, rbql_context.delim, rbql_context.policy, false); + if (!warning) { + webview.postMessage({'msg_type': 'fetch_table_header_response', 'header': fields}); + } + } catch (e) { + console.error('Unable to get join table header: ' + String(e)); + } + } + + if (message_type == 'update_query') { + let rbql_query = message['query']; + if (!rbql_query) + return; + if (rbql_context.input_document_path) + last_rbql_queries.set(file_path_to_query_key(rbql_context.input_document_path), rbql_query); + } + + if (message_type == 'newlines_policy_change') { + rbql_context.enable_rfc_newlines = message['enable_rfc_newlines']; + if (rbql_context.input_document_path) + await save_to_global_state(make_rfc_policy_key(rbql_context.input_document_path), rbql_context.enable_rfc_newlines); + let protocol_message = {'msg_type': 'resample'}; + sample_preview_records_from_context(rbql_context, protocol_message); + await webview.postMessage(protocol_message); + } + + if (message_type == 'with_headers_change') { + rbql_context.with_headers = message['with_headers']; + if (rbql_context.input_document_path) + await save_to_global_state(make_with_headers_key(rbql_context.input_document_path), rbql_context.with_headers); + } + + if (message_type == 'navigate') { + var navig_direction = message['direction']; + if (navig_direction == 'backward') { + rbql_context.requested_start_record -= preview_window_size; + } else if (navig_direction == 'forward') { + rbql_context.requested_start_record += preview_window_size; + } else if (navig_direction == 'begin') { + rbql_context.requested_start_record = 0; + } else if (navig_direction == 'end') { + rbql_context.requested_start_record = rbql_context.input_document.lineCount; // This is just max possible value which is incorrect and will be adjusted later. + } + let protocol_message = {'msg_type': 'navigate'}; + sample_preview_records_from_context(rbql_context, protocol_message); + await webview.postMessage(protocol_message); + } + + if (message_type == 'run') { + let rbql_query = message['query']; + let backend_language = message['backend_language']; + let encoding = message['encoding']; + let output_dialect = message['output_dialect']; + let enable_rfc_newlines = message['enable_rfc_newlines']; + let with_headers = message['with_headers']; + await update_query_history(rbql_query); + await run_rbql_query(rbql_context.input_document_path, encoding, backend_language, rbql_query, output_dialect, enable_rfc_newlines, with_headers, webview_report_handler); + } + + if (message_type == 'edit_udf') { + if (is_web_ext) { + webview_report_handler('Input error', 'UDFs are currently not supported in web version'); + return; + } + let backend_language = message['backend_language']; + let udf_file_path = null; + let default_content = ''; + if (backend_language == 'js') { + udf_file_path = path.join(os.homedir(), '.rbql_init_source.js'); + default_content = ll_rainbow_utils().get_default_js_udf_content(); + } else { + udf_file_path = path.join(os.homedir(), '.rbql_init_source.py'); + default_content = ll_rainbow_utils().get_default_python_udf_content(); + } + if (!fs.existsSync(udf_file_path)) { + fs.writeFileSync(udf_file_path, default_content); + } + let udf_doc = await vscode.workspace.openTextDocument(udf_file_path); + await vscode.window.showTextDocument(udf_doc); + } + + if (message_type == 'global_param_change') { + await save_to_global_state(message['key'], message['value']); + } +} + + +function adjust_webview_paths(paths_list, client_html) { + for (const local_path of paths_list) { + let adjusted_webview_url = null; + if (is_web_ext) { + adjusted_webview_url = absolute_path_map[local_path]; + } else { + adjusted_webview_url = preview_panel.webview.asWebviewUri(vscode.Uri.file(absolute_path_map[local_path])); + } + client_html = client_html.replace(`src="${local_path}"`, `src="${adjusted_webview_url}"`); + } + return client_html; +} + + +async function edit_rbql(integration_test_options=null) { + let active_window = vscode.window; + if (!active_window) + return; + let active_editor = active_window.activeTextEditor; + if (!active_editor) + return; + let active_doc = active_editor.document; + if (!active_doc) + return; + let orig_uri = active_doc.uri; + if (!orig_uri) + return; + // For web orig_uri.scheme can have other valid values e.g. `vscode-test-web` when testing the browser integration. + if (orig_uri.scheme != 'file' && orig_uri.scheme != 'untitled' && !is_web_ext) + return; + if (orig_uri.scheme == 'file' && active_doc.isDirty && !is_web_ext) { + show_single_line_error("Unable to run RBQL: file has unsaved changes"); + return; + } + let input_path = null; + if (orig_uri.scheme == 'untitled' && !is_web_ext) { + // Scheme 'untitled' means that the document is a scratch buffer that hasn't been saved yet, see https://code.visualstudio.com/api/references/document-selector + let data = active_doc.getText(); + let rnd_suffix = String(Math.floor(Math.random() * 1000000)); + input_path = path.join(os.tmpdir(), `${scratch_buf_marker}_${rnd_suffix}.txt`); + // TODO consider adding username to the input_path and using chmod 600 on it. + fs.writeFileSync(input_path, data); + } else { + input_path = active_doc.fileName; + } + + if (!input_path) { + show_single_line_error("Unable to run RBQL for this file"); + return; + } + let language_id = active_doc.languageId; + let delim = 'monocolumn'; + let policy = 'monocolumn'; + if (dialect_map.hasOwnProperty(language_id)) { + [delim, policy] = dialect_map[language_id]; + } + let enable_rfc_newlines = get_from_global_state(make_rfc_policy_key(input_path), false); + let with_headers_by_default = get_from_config('rbql_with_headers_by_default', false); + let with_headers = get_from_global_state(make_with_headers_key(input_path), with_headers_by_default); + let header = get_header_from_document(active_doc, delim, policy); + rbql_context = { + "input_document": active_doc, + "input_document_path": input_path, + "requested_start_record": 0, + "delim": delim, + "policy": policy, + "rfc_record_map": [], + "enable_rfc_newlines": enable_rfc_newlines, + "with_headers": with_headers, + "header": header + }; + + preview_panel = vscode.window.createWebviewPanel('rbql-console', 'RBQL Console', vscode.ViewColumn.Active, {enableScripts: true}); + if (!client_html_template) { + if (is_web_ext) { + client_html_template = client_html_template_web; + } else { + client_html_template = fs.readFileSync(absolute_path_map['rbql_client.html'], "utf8"); + } + } + let client_html = client_html_template; + client_html = adjust_webview_paths(['contrib/textarea-caret-position/index.js', 'rbql_suggest.js', 'rbql_client.js', 'rbql_logo.svg'], client_html); + preview_panel.webview.html = client_html; + preview_panel.webview.onDidReceiveMessage(function(message) { handle_rbql_client_message(preview_panel.webview, message, integration_test_options); }); +} + + +function get_num_columns_if_delimited(active_doc, delim, policy, min_num_columns, min_num_lines) { + var num_lines = active_doc.lineCount; + let num_fields = 0; + let num_lines_checked = 0; + let comment_prefix_for_autodetection = get_from_config('comment_prefix', ''); + if (!comment_prefix_for_autodetection) + comment_prefix_for_autodetection = '#'; + for (var lnum = 0; lnum < num_lines; lnum++) { + var line_text = active_doc.lineAt(lnum).text; + if (lnum + 1 == num_lines && !line_text) + break; + if (line_text.startsWith(comment_prefix_for_autodetection)) + continue; + let [fields, warning] = csv_utils.smart_split(line_text, delim, policy, true); + if (warning) + return 0; // TODO don't fail on warnings? + if (!num_fields) + num_fields = fields.length; + if (num_fields < min_num_columns || num_fields != fields.length) + return 0; + num_lines_checked += 1; + } + return num_lines_checked >= min_num_lines ? num_fields : 0; +} + + +function autodetect_dialect(active_doc, candidate_separators) { + let min_num_lines = get_from_config('autodetection_min_line_count', 10); + if (active_doc.lineCount < min_num_lines) + return null; + + let best_dialect = null; + let best_dialect_num_columns = 1; + for (let i = 0; i < candidate_separators.length; i++) { + let dialect_id = map_separator_to_language_id(candidate_separators[i]); + if (!dialect_id) + continue; + let [delim, policy] = dialect_map[dialect_id]; + let cur_dialect_num_columns = get_num_columns_if_delimited(active_doc, delim, policy, best_dialect_num_columns + 1, min_num_lines); + if (cur_dialect_num_columns > best_dialect_num_columns) { + best_dialect_num_columns = cur_dialect_num_columns; + best_dialect = dialect_id; + } + } + return best_dialect; +} + + +function autodetect_dialect_frequency_based(active_doc, candidate_separators) { + let best_dialect = 'csv'; + let best_dialect_frequency = 0; + let data = active_doc.getText(); + if (!data) + return best_dialect; + for (let i = 0; i < candidate_separators.length; i++) { + if (candidate_separators[i] == ' ' || candidate_separators[i] == '.') + continue; // Whitespace and dot have advantage over other separators in this algorithm, so we just skip them. + let dialect_id = map_separator_to_language_id(candidate_separators[i]); + let frequency = 0; + for (let j = 0; j < 10000 && j < data.length; j++) { + if (data[j] == candidate_separators[i]) + frequency += 1; + } + if (frequency > best_dialect_frequency) { + best_dialect = dialect_id; + best_dialect_frequency = frequency; + } + } + return best_dialect; +} + + +async function autoenable_rainbow_csv(active_doc) { + if (!active_doc) + return; + if (!get_from_config('enable_separator_autodetection', false)) + return; + let candidate_separators = get_from_config('autodetect_separators', []); + var original_language_id = active_doc.languageId; + var file_path = active_doc.fileName; + if (!file_path || autodetection_stoplist.has(file_path)) { + return; + } + let is_default_csv = file_path.endsWith('.csv') && original_language_id == 'csv'; + if (original_language_id != 'plaintext' && !is_default_csv) + return; + let rainbow_csv_language_id = autodetect_dialect(active_doc, candidate_separators); + if (!rainbow_csv_language_id && is_default_csv) { + // Smart autodetection method has failed, but we need to choose a separator because this is a csv file. Let's just find the most popular one. + rainbow_csv_language_id = autodetect_dialect_frequency_based(active_doc, candidate_separators); + } + if (!rainbow_csv_language_id || rainbow_csv_language_id == original_language_id) + return; + + let doc = await vscode.languages.setTextDocumentLanguage(active_doc, rainbow_csv_language_id); + original_language_ids.set(file_path, original_language_id); + csv_lint(doc, false); + refresh_status_bar_buttons(doc); +} + + +async function handle_doc_edit(change_event) { + if (!change_event) + return; + if (doc_edit_subscription) { + doc_edit_subscription.dispose(); + doc_edit_subscription = null; + } + let active_doc = change_event.document; + if (!active_doc) + return; + let candidate_separators = get_from_config('autodetect_separators', []); + let rainbow_csv_language_id = autodetect_dialect(active_doc, candidate_separators); + if (!rainbow_csv_language_id) + return; + let doc = await vscode.languages.setTextDocumentLanguage(active_doc, rainbow_csv_language_id); + csv_lint(doc, false); + refresh_status_bar_buttons(doc); +} + + +function register_csv_copy_paste(active_doc) { + if (!get_from_config('enable_separator_autodetection', false)) + return; + if (!active_doc || doc_edit_subscription) + return; + if (!active_doc.isUntitled && active_doc.lineCount != 0) + return; + doc_edit_subscription = vscode.workspace.onDidChangeTextDocument(handle_doc_edit); + return; +} + + +function handle_editor_switch(editor) { + let active_doc = get_active_doc(editor); + csv_lint(active_doc, false); + refresh_status_bar_buttons(active_doc); +} + + +async function handle_doc_open(active_doc) { + await autoenable_rainbow_csv(active_doc); + register_csv_copy_paste(active_doc); + csv_lint(active_doc, false); + refresh_status_bar_buttons(active_doc); +} + + +function quote_field(field, delim) { + if (field.indexOf('"') != -1 || field.indexOf(delim) != -1) { + return '"' + field.replace(/"/g, '""') + '"'; + } + return field; +} + + +function quoted_join(fields, delim) { + var quoted_fields = fields.map(function(val) { return quote_field(val, delim); }); + return quoted_fields.join(delim); +} + + +async function make_preview(uri, preview_mode) { + if (is_web_ext) { + show_single_line_error('This command is currently unavailable in web mode.'); + return; + } + var file_path = uri.fsPath; + if (!file_path || !fs.existsSync(file_path)) { + vscode.window.showErrorMessage('Invalid file'); + return; + } + + var size_limit = 1024000; // ~1MB + var file_size_in_bytes = fs.statSync(file_path)['size']; + if (file_size_in_bytes <= size_limit) { + vscode.window.showWarningMessage('Rainbow CSV: The file is not big enough, showing the full file instead. Use this preview for files larger than 1MB'); + let full_orig_doc = await vscode.workspace.openTextDocument(file_path); + await vscode.window.showTextDocument(full_orig_doc); + return; + } + + let file_basename = path.basename(file_path); + const out_path = path.join(os.tmpdir(), `.rb_csv_preview.${preview_mode}.${file_basename}`); + + fs.open(file_path, 'r', (err, fd) => { + if (err) { + console.log(err.message); + vscode.window.showErrorMessage('Unable to preview file'); + return; + } + + var buffer = Buffer.alloc(size_limit); + let read_begin_pos = preview_mode == 'head' ? 0 : Math.max(file_size_in_bytes - size_limit, 0); + fs.read(fd, buffer, 0, size_limit, read_begin_pos, function(err, _num) { + if (err) { + console.log(err.message); + vscode.window.showErrorMessage('Unable to preview file'); + return; + } + + const buffer_str = buffer.toString(); + // TODO handle old mac '\r' line endings - still used by Mac version of Excel. + let content = null; + if (preview_mode == 'head') { + content = buffer_str.substr(0, buffer_str.lastIndexOf(buffer_str.includes('\r\n') ? '\r\n' : '\n')); + } else { + content = buffer_str.substr(buffer_str.indexOf('\n') + 1); + } + fs.writeFileSync(out_path, content); + vscode.workspace.openTextDocument(out_path).then(doc => vscode.window.showTextDocument(doc)); + }); + }); +} + + +function register_csv_hover_info_provider(language_id, context) { + let hover_provider = vscode.languages.registerHoverProvider(language_id, { + provideHover(document, position, token) { + return make_hover(document, position, language_id, token); + } + }); + context.subscriptions.push(hover_provider); +} + + +async function activate(context) { + global_state = context.globalState; + + if (is_web_ext) { + let rbql_client_uri = vscode.Uri.joinPath(context.extensionUri, 'rbql_client.html'); + let bytes = await vscode.workspace.fs.readFile(rbql_client_uri); + // Using TextDecoder because it should work fine in web extension. + client_html_template_web = new TextDecoder().decode(bytes); + } + + for (let local_path in absolute_path_map) { + if (absolute_path_map.hasOwnProperty(local_path)) { + if (is_web_ext) { + absolute_path_map[local_path] = vscode.Uri.joinPath(context.extensionUri, local_path); + } else { + absolute_path_map[local_path] = context.asAbsolutePath(local_path); + } + } + } + + for (let language_id in dialect_map) { + if (dialect_map.hasOwnProperty(language_id)) { + register_csv_hover_info_provider(language_id, context); + } + } + + var lint_cmd = vscode.commands.registerCommand('rainbow-csv.CSVLint', csv_lint_cmd); + var rbql_cmd = vscode.commands.registerCommand('rainbow-csv.RBQL', edit_rbql); + var set_header_line_cmd = vscode.commands.registerCommand('rainbow-csv.SetHeaderLine', set_header_line); + var edit_column_names_cmd = vscode.commands.registerCommand('rainbow-csv.SetVirtualHeader', set_virtual_header); + var set_join_table_name_cmd = vscode.commands.registerCommand('rainbow-csv.SetJoinTableName', set_join_table_name); // WEB_DISABLED + var column_edit_before_cmd = vscode.commands.registerCommand('rainbow-csv.ColumnEditBefore', async function() { await column_edit('ce_before'); }); + var column_edit_after_cmd = vscode.commands.registerCommand('rainbow-csv.ColumnEditAfter', async function() { await column_edit('ce_after'); }); + var column_edit_select_cmd = vscode.commands.registerCommand('rainbow-csv.ColumnEditSelect', async function() { await column_edit('ce_select'); }); + var set_separator_cmd = vscode.commands.registerCommand('rainbow-csv.RainbowSeparator', set_rainbow_separator); + var rainbow_off_cmd = vscode.commands.registerCommand('rainbow-csv.RainbowSeparatorOff', restore_original_language); + var sample_head_cmd = vscode.commands.registerCommand('rainbow-csv.SampleHead', async function(uri) { await make_preview(uri, 'head'); }); // WEB_DISABLED + var sample_tail_cmd = vscode.commands.registerCommand('rainbow-csv.SampleTail', async function(uri) { await make_preview(uri, 'tail'); }); // WEB_DISABLED + var align_cmd = vscode.commands.registerCommand('rainbow-csv.Align', align_table); + var shrink_cmd = vscode.commands.registerCommand('rainbow-csv.Shrink', shrink_table); + var copy_back_cmd = vscode.commands.registerCommand('rainbow-csv.CopyBack', copy_back); // WEB_DISABLED + var internal_test_cmd = vscode.commands.registerCommand('rainbow-csv.InternalTest', run_internal_test_cmd); + + var doc_open_event = vscode.workspace.onDidOpenTextDocument(handle_doc_open); + var switch_event = vscode.window.onDidChangeActiveTextEditor(handle_editor_switch); + + context.subscriptions.push(lint_cmd); + context.subscriptions.push(rbql_cmd); + context.subscriptions.push(edit_column_names_cmd); + context.subscriptions.push(column_edit_before_cmd); + context.subscriptions.push(column_edit_after_cmd); + context.subscriptions.push(column_edit_select_cmd); + context.subscriptions.push(doc_open_event); + context.subscriptions.push(switch_event); + context.subscriptions.push(set_separator_cmd); + context.subscriptions.push(rainbow_off_cmd); + context.subscriptions.push(sample_head_cmd); + context.subscriptions.push(sample_tail_cmd); + context.subscriptions.push(set_join_table_name_cmd); + context.subscriptions.push(align_cmd); + context.subscriptions.push(shrink_cmd); + context.subscriptions.push(copy_back_cmd); + context.subscriptions.push(set_header_line_cmd); + context.subscriptions.push(internal_test_cmd); + + // Need this because "onDidOpenTextDocument()" doesn't get called for the first open document. + // Another issue is when dev debug logging mode is enabled, the first document would be "Log" because it is printing something and gets VSCode focus. + await sleep(1000); + let active_doc = get_active_doc(); + handle_doc_open(active_doc); +} + + +function deactivate() { + // This method is called when extension is deactivated. +} + + +exports.activate = activate; +exports.deactivate = deactivate; diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/package.json b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/package.json new file mode 100644 index 00000000..43e2f899 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/package.json @@ -0,0 +1,433 @@ +{ + "name": "rainbow-csv", + "displayName": "Rainbow CSV", + "description": "Highlight CSV and TSV files, Run SQL-like queries", + "version": "2.3.0", + "publisher": "mechatroner", + "license": "MIT", + "icon": "rainbow_csv_logo.png", + "engines": { + "vscode": "^1.62.0" + }, + "keywords": [ + "csv", + "tsv", + "highlight" + ], + "categories": [ + "Data Science", + "Other", + "Programming Languages" + ], + "activationEvents": [ + "onLanguage:csv", + "onLanguage:tsv", + "onLanguage:csv (semicolon)", + "onLanguage:csv (pipe)", + "onLanguage:csv (tilde)", + "onLanguage:csv (whitespace)", + "onLanguage:csv (caret)", + "onLanguage:csv (colon)", + "onLanguage:csv (double quote)", + "onLanguage:csv (equals)", + "onLanguage:csv (dot)", + "onLanguage:csv (hyphen)", + "onLanguage:plaintext", + "onCommand:rainbow-csv.RBQL", + "onCommand:rainbow-csv.RainbowSeparator", + "onCommand:rainbow-csv.SampleHead", + "onCommand:rainbow-csv.SampleTail" + ], + "main": "./extension", + "browser": "./dist/web/extension.js", + "contributes": { + "configuration": { + "type": "object", + "title": "Rainbow CSV", + "properties": { + "rainbow_csv.enable_separator_autodetection": { + "type": "boolean", + "default": true, + "description": "Enable automatic content based separator autodetection" + }, + "rainbow_csv.autodetection_min_line_count": { + "type": "number", + "default": 10, + "description": "Minimum number of non-comment lines in file for content-based autodetection" + }, + "rainbow_csv.autodetect_separators": { + "type": "array", + "default": [ + "\t", + ",", + ";", + "|" + ], + "description": "Enable automatic content-based separator autodetection for the specified list of separators", + "items": { + "type": "string", + "description": "Separator" + } + }, + "rainbow_csv.enable_tooltip": { + "type": "boolean", + "default": true, + "description": "Enable column-info tooltip on hover" + }, + "rainbow_csv.enable_tooltip_column_names": { + "type": "boolean", + "default": true, + "description": "Show column names in tooltip" + }, + "rainbow_csv.rbql_with_headers_by_default": { + "type": "boolean", + "default": false, + "description": "RBQL treats the first line as header by default" + }, + "rainbow_csv.rbql_output_dir": { + "type": "string", + "default": "TMP", + "description": "Output directory for RBQL result sets, can be `TMP`, `INPUT` or a custom absolute path. `TMP` - output in system tmp dir(default), `INPUT` - output in the same dir as input file, otherwise use provided path as the output directory e.g. `/path/to/custom/dir`" + }, + "rainbow_csv.enable_tooltip_warnings": { + "type": "boolean", + "default": true, + "description": "Show warnings in tooltip" + }, + "rainbow_csv.enable_auto_csv_lint": { + "type": "boolean", + "default": true, + "description": "Enable automatic linting/checking of opened csv files" + }, + "rainbow_csv.csv_lint_detect_trailing_spaces": { + "type": "boolean", + "default": false, + "description": "CSV Lint: detect leading and trailing whitespaces in fields and show warning" + }, + "rainbow_csv.comment_prefix": { + "type": "string", + "default": "", + "description": "Comment lines prefix, e.g. \"#\". Set to empty string to disable" + }, + "rainbow_csv.enable_context_menu_head": { + "type": "boolean", + "default": true, + "description": "Enable \"Preview CSV head\" option in File Explorer context menu" + }, + "rainbow_csv.enable_context_menu_tail": { + "type": "boolean", + "default": false, + "description": "Enable \"Preview CSV tail\" option in File Explorer context menu" + } + } + }, + "menus": { + "editor/context": [ + { + "when": "editorHasSelection && editorLangId == plaintext", + "command": "rainbow-csv.RainbowSeparator", + "group": "rainbow_csv" + }, + { + "when": "editorTextFocus && editorLangId =~ /^[ct]sv/", + "command": "rainbow-csv.SetHeaderLine", + "group": "rainbow_csv" + } + ], + "explorer/context": [ + { + "command": "rainbow-csv.SampleHead", + "when": "config.rainbow_csv.enable_context_menu_head", + "group": "rainbow_csv" + }, + { + "command": "rainbow-csv.SampleTail", + "when": "config.rainbow_csv.enable_context_menu_tail", + "group": "rainbow_csv" + } + ] + }, + "languages": [ + { + "id": "csv", + "aliases": [ + "CSV", + "csv" + ], + "extensions": [ + ".csv" + ] + }, + { + "id": "tsv", + "aliases": [ + "TSV", + "tsv" + ], + "extensions": [ + ".tsv", + ".tab" + ] + }, + { + "id": "csv (pipe)", + "aliases": [ + "CSV (pipe)", + "csv (pipe)" + ], + "extensions": [] + }, + { + "id": "csv (tilde)", + "aliases": [ + "CSV (tilde)", + "csv (tilde)" + ], + "extensions": [] + }, + { + "id": "csv (whitespace)", + "aliases": [ + "CSV (whitespace)", + "csv (whitespace)" + ], + "extensions": [] + }, + { + "id": "csv (caret)", + "aliases": [ + "CSV (caret)", + "csv (caret)" + ], + "extensions": [] + }, + { + "id": "csv (colon)", + "aliases": [ + "CSV (colon)", + "csv (colon)" + ], + "extensions": [] + }, + { + "id": "csv (double quote)", + "aliases": [ + "CSV (double quote)", + "csv (double quote)" + ], + "extensions": [] + }, + { + "id": "csv (equals)", + "aliases": [ + "CSV (equals)", + "csv (equals)" + ], + "extensions": [] + }, + { + "id": "csv (dot)", + "aliases": [ + "CSV (dot)", + "csv (dot)" + ], + "extensions": [] + }, + { + "id": "csv (hyphen)", + "aliases": [ + "CSV (hyphen)", + "csv (hyphen)" + ], + "extensions": [] + }, + { + "id": "csv (semicolon)", + "aliases": [ + "CSV (semicolon)", + "csv (semicolon)" + ], + "extensions": [] + }, + { + "id": "rainbow hover markup", + "extensions": [] + } + ], + "commands": [ + { + "command": "rainbow-csv.CSVLint", + "title": "CSV Lint" + }, + { + "command": "rainbow-csv.SetVirtualHeader", + "category": "Rainbow CSV", + "title": "Set virtual header" + }, + { + "command": "rainbow-csv.SetHeaderLine", + "category": "Rainbow CSV", + "title": "Set header line" + }, + { + "command": "rainbow-csv.RBQL", + "category": "Rainbow CSV", + "title": "RBQL" + }, + { + "command": "rainbow-csv.SetJoinTableName", + "category": "Rainbow CSV", + "title": "Set join table name for RBQL" + }, + { + "command": "rainbow-csv.ColumnEditBefore", + "category": "Rainbow CSV", + "title": "Column edit before" + }, + { + "command": "rainbow-csv.ColumnEditAfter", + "category": "Rainbow CSV", + "title": "Column edit after" + }, + { + "command": "rainbow-csv.ColumnEditSelect", + "category": "Rainbow CSV", + "title": "Column edit select" + }, + { + "command": "rainbow-csv.RainbowSeparator", + "title": "Set as Rainbow separator" + }, + { + "command": "rainbow-csv.RainbowSeparatorOff", + "title": "RainbowSeparatorOff" + }, + { + "command": "rainbow-csv.Align", + "category": "Rainbow CSV", + "title": "Align CSV Columns" + }, + { + "command": "rainbow-csv.Shrink", + "category": "Rainbow CSV", + "title": "Shrink CSV table: Remove leading and trailing whitespaces from all fields" + }, + { + "command": "rainbow-csv.CopyBack", + "title": "CopyBack" + }, + { + "command": "rainbow-csv.SampleHead", + "title": "Preview big CSV: head" + }, + { + "command": "rainbow-csv.SampleTail", + "title": "Preview big CSV: tail" + } + ], + "grammars": [ + { + "language": "csv", + "scopeName": "text.csv", + "path": "./syntaxes/csv.tmLanguage.json" + }, + { + "language": "tsv", + "scopeName": "text.tsv", + "path": "./syntaxes/tsv.tmLanguage.json" + }, + { + "language": "csv (pipe)", + "scopeName": "text.psv", + "path": "./syntaxes/pipe_simple.tmLanguage.json" + }, + { + "language": "csv (tilde)", + "scopeName": "text.tldsv", + "path": "./syntaxes/tldsv.tmLanguage.json" + }, + { + "language": "csv (whitespace)", + "scopeName": "text.wspcsv", + "path": "./syntaxes/wspcsv.tmLanguage.json" + }, + { + "language": "csv (caret)", + "scopeName": "text.crtsv", + "path": "./syntaxes/crtsv.tmLanguage.json" + }, + { + "language": "csv (colon)", + "scopeName": "text.clnsv", + "path": "./syntaxes/clnsv.tmLanguage.json" + }, + { + "language": "csv (double quote)", + "scopeName": "text.dbqsv", + "path": "./syntaxes/dbqsv.tmLanguage.json" + }, + { + "language": "csv (equals)", + "scopeName": "text.eqlsv", + "path": "./syntaxes/eqlsv.tmLanguage.json" + }, + { + "language": "csv (dot)", + "scopeName": "text.dotsv", + "path": "./syntaxes/dotsv.tmLanguage.json" + }, + { + "language": "csv (hyphen)", + "scopeName": "text.hypsv", + "path": "./syntaxes/hypsv.tmLanguage.json" + }, + { + "language": "csv (semicolon)", + "scopeName": "text.scsv", + "path": "./syntaxes/scsv.tmLanguage.json" + }, + { + "language": "rainbow hover markup", + "scopeName": "text.rbhover", + "path": "./syntaxes/rb_hover.tmLanguage.json" + } + ] + }, + "capabilities": { + "hoverProvider": "true" + }, + "scripts": { + "vscode:prepublish": "npm run package-web", + "compile-web": "webpack", + "lint": "eslint rainbow_utils.js extension.js test/runTest.js && eslint -c .eslintrc_browser.json rainbow_utils.js rbql_client.js", + "watch-web": "webpack --watch", + "package-web": "webpack --mode production --devtool hidden-source-map", + "start-web-server": "vscode-test-web --version stable --browser=none --extensionDevelopmentPath=. .", + "test-in-browser": "vscode-test-web --version stable --browser=chromium --extensionDevelopmentPath=. --extensionTestsPath=dist/web/test/suite/index.js .", + "test": "node ./test/runTest.js" + }, + "devDependencies": { + "@types/vscode": "^1.62.0", + "@vscode/test-web": "^0.0.22", + "@vscode/test-electron": "^1.6.1", + "webpack": "^5.64.0", + "webpack-cli": "^4.9.1", + "assert": "^2.0.0", + "process": "^0.11.10", + "eslint": "^7.21.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/mechatroner/vscode_rainbow_csv" + }, + "__metadata": { + "id": "3792588c-3d35-442d-91ea-fe6a755e8155", + "publisherId": "0d5438b6-325a-4f88-aa28-6192aa2cf2a6", + "publisherDisplayName": "mechatroner", + "targetPlatform": "undefined", + "updated": true, + "isPreReleaseVersion": false, + "preRelease": false, + "installedTimestamp": 1651406513766 + } +} \ No newline at end of file diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rainbow_csv_logo.png b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rainbow_csv_logo.png new file mode 100644 index 0000000000000000000000000000000000000000..85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7b{ z6?o#xg%xvwNIo#tV+{NSbewrD3CpNBd^}(}CbxerxUZ*JernfwiINiLflEr*xI_CB z5e9v9U!I{U)oh^}gL~sO?iRYc|9ap!ByRiyJ8fn3$+>JhlW&ww1&$VLC7kzMTDjtX eLH}X@F(lo&zA|r4_V*wE9AIH)P52A%5&wT%`I=Aw literal 0 HcmV?d00001 diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rainbow_utils.js b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rainbow_utils.js new file mode 100644 index 00000000..6645c851 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rainbow_utils.js @@ -0,0 +1,675 @@ +const os = require('os'); +const fs = require('fs'); +const path = require('path'); + +const rbql = require('./rbql_core/rbql-js/rbql.js'); +const rbql_csv = require('./rbql_core/rbql-js/rbql_csv.js'); +const csv_utils = require('./rbql_core/rbql-js/csv_utils.js'); + +const non_numeric_sentinel = -1; +const number_regex = /^([0-9]+)(\.[0-9]+)?$/; + +class AssertionError extends Error {} + +function assert(condition, message=null) { + if (!condition) { + if (!message) { + message = 'Assertion error'; + } + throw new AssertionError(message); + } +} + + +function get_default_js_udf_content() { + let default_content = `// This file can be used to store RBQL UDFs. Example: + // + // function foo(value) { + // return 'foo ' + String(value.length); + // } + // + // Functions defined in this file can be used in RBQL queries e.g. + // SELECT foo(a1), a2 WHERE foo(a3) != 'foo 5' LIMIT 10 + // + // Don't forget to save this file after editing! + // + // Write your own functions bellow this line: + `.replace(new RegExp(/^ */, 'mg'), ''); + return default_content; +} + + +function get_default_python_udf_content() { + let default_content = `# This file can be used to store RBQL UDFs. Example: + # + # def foo(value): + # return 'foo ' + str(len(value)) + # + # + # Functions defined in this file can be used in RBQL queries e.g. + # SELECT foo(a1), a2 WHERE foo(a3) != 'foo 5' LIMIT 10 + # + # Don't forget to save this file after editing! + # + # Write your own functions bellow this line: + `.replace(new RegExp(/^ */, 'mg'), ''); + return default_content; +} + + +function update_subcomponent_stats(field, is_first_line, max_field_components_lens) { + // Extract overall field length and length of integer and fractional parts of the field if it represents a number. + // Here `max_field_components_lens` is a tuple: (max_field_length, max_integer_part_length, max_fractional_part_length) + if (field.length > max_field_components_lens[0]) { + max_field_components_lens[0] = field.length; + } + if (max_field_components_lens[1] == non_numeric_sentinel) { + // Column is not a number, early return. + return; + } + let match_result = number_regex.exec(field); + if (match_result === null) { + if (!is_first_line && field.length) { // Checking field_length here allows numeric columns to have some of the fields empty. + // We only mark the column as non-header if we know that this is not a header line. + max_field_components_lens[1] = non_numeric_sentinel; + max_field_components_lens[2] = non_numeric_sentinel; + } + return; + } + let cur_integer_part_length = match_result[1].length; + max_field_components_lens[1] = Math.max(max_field_components_lens[1], cur_integer_part_length); + let cur_fractional_part_length = match_result[2] === undefined ? 0 : match_result[2].length; + max_field_components_lens[2] = Math.max(max_field_components_lens[2], cur_fractional_part_length); +} + + +function calc_column_stats(active_doc, delim, policy, comment_prefix) { + let column_stats = []; + let num_lines = active_doc.lineCount; + let is_first_line = true; + for (let lnum = 0; lnum < num_lines; lnum++) { + let line_text = active_doc.lineAt(lnum).text; + if (comment_prefix && line_text.startsWith(comment_prefix)) + continue; + let [fields, warning] = csv_utils.smart_split(line_text, delim, policy, true); + if (warning) { + return [null, lnum + 1]; + } + for (let fnum = 0; fnum < fields.length; fnum++) { + let field = fields[fnum].trim(); + if (column_stats.length <= fnum) { + column_stats.push([0, 0, 0]); + } + update_subcomponent_stats(field, is_first_line, column_stats[fnum]); + } + is_first_line = false; + } + return [column_stats, null]; +} + + +function adjust_column_stats(column_stats) { + // Ensure that numeric components max widths are consistent with non-numeric (header) width. + let adjusted_stats = []; + for (let column_stat of column_stats) { + if (column_stat[1] <= 0) { + column_stat[1] = -1; + column_stat[2] = -1; + } + if (column_stat[1] > 0) { + // The sum of integer and float parts can be bigger than the max width, e.g. here: + // value + // 0.12 + // 1234 + if (column_stat[1] + column_stat[2] > column_stat[0]) { + column_stat[0] = column_stat[1] + column_stat[2]; + } + // This is needed when the header is wider than numeric components and/or their sum. + if (column_stat[0] - column_stat[2] > column_stat[1]) { + column_stat[1] = column_stat[0] - column_stat[2]; + } + // Sanity check. + if (column_stat[0] != column_stat[1] + column_stat[2]) { + // Assertion Error, this can never happen. + return null; + } + } + adjusted_stats.push(column_stat); + } + return adjusted_stats; +} + + +function align_field(field, is_first_line, max_field_components_lens, is_last_column) { + // Align field, use Math.max() to avoid negative delta_length which can happen theorethically due to async doc edit. + const extra_readability_whitespace_length = 1; + field = field.trim(); + if (max_field_components_lens[1] == non_numeric_sentinel) { + let delta_length = Math.max(max_field_components_lens[0] - field.length, 0); + return is_last_column ? field : field + ' '.repeat(delta_length + extra_readability_whitespace_length); + } + if (is_first_line) { + if (number_regex.exec(field) === null) { + // The line must be a header - align it using max_width rule. + let delta_length = Math.max(max_field_components_lens[0] - field.length, 0); + return is_last_column ? field : field + ' '.repeat(delta_length + extra_readability_whitespace_length); + } + } + let dot_pos = field.indexOf('.'); + let cur_integer_part_length = dot_pos == -1 ? field.length : dot_pos; + // Here cur_fractional_part_length includes the leading dot too. + let cur_fractional_part_length = dot_pos == -1 ? 0 : field.length - dot_pos; + let integer_delta_length = Math.max(max_field_components_lens[1] - cur_integer_part_length, 0); + let fractional_delta_length = Math.max(max_field_components_lens[2] - cur_fractional_part_length); + let trailing_spaces = is_last_column ? '' : ' '.repeat(fractional_delta_length + extra_readability_whitespace_length); + return ' '.repeat(integer_delta_length) + field + trailing_spaces; +} + + +function align_columns(active_doc, delim, policy, comment_prefix, column_stats) { + let result_lines = []; + let num_lines = active_doc.lineCount; + let has_edit = false; + let is_first_line = true; + for (let lnum = 0; lnum < num_lines; lnum++) { + let line_text = active_doc.lineAt(lnum).text; + if (comment_prefix && line_text.startsWith(comment_prefix)) { + result_lines.push(line_text); + continue; + } + if (lnum + 1 == num_lines && line_text == '') { + // Skip the last empty line which corresponds to the trailing newline character. + result_lines.push(line_text); + continue; + } + let fields = csv_utils.smart_split(line_text, delim, policy, true)[0]; + for (let fnum = 0; fnum < fields.length; fnum++) { + if (fnum >= column_stats.length) // Safeguard against async doc edit, should never happen. + break; + let is_last_column = fnum + 1 == column_stats.length; + let adjusted = align_field(fields[fnum], is_first_line, column_stats[fnum], is_last_column); + if (fields[fnum] != adjusted) { + fields[fnum] = adjusted; + has_edit = true; + } + } + is_first_line = false; + result_lines.push(fields.join(delim)); + } + if (!has_edit) + return null; + return result_lines.join('\n'); +} + + +function shrink_columns(active_doc, delim, policy, comment_prefix) { + let result_lines = []; + let num_lines = active_doc.lineCount; + let has_edit = false; + for (let lnum = 0; lnum < num_lines; lnum++) { + let line_text = active_doc.lineAt(lnum).text; + if (comment_prefix && line_text.startsWith(comment_prefix)) { + result_lines.push(line_text); + continue; + } + let [fields, warning] = csv_utils.smart_split(line_text, delim, policy, true); + if (warning) { + return [null, lnum + 1]; + } + for (let i = 0; i < fields.length; i++) { + let adjusted = fields[i].trim(); + if (fields[i].length != adjusted.length) { + fields[i] = adjusted; + has_edit = true; + } + } + result_lines.push(fields.join(delim)); + } + if (!has_edit) + return [null, null]; + return [result_lines.join('\n'), null]; +} + + +function get_last(arr) { + return arr[arr.length - 1]; +} + + +function populate_optimistic_rfc_csv_record_map(document, requested_end_record, dst_record_map, comment_prefix=null) { + let num_lines = document.lineCount; + let record_begin = null; + let start_line_idx = dst_record_map.length ? get_last(dst_record_map)[1] : 0; + for (let lnum = start_line_idx; lnum < num_lines && dst_record_map.length < requested_end_record; ++lnum) { + let line_text = document.lineAt(lnum).text; + if (lnum + 1 >= num_lines && line_text == "") + break; // Skip the last empty line. + if (comment_prefix && line_text.startsWith(comment_prefix)) + continue; + let match_list = line_text.match(/"/g); + let has_unbalanced_double_quote = match_list && match_list.length % 2 == 1; + if (record_begin === null && !has_unbalanced_double_quote) { + dst_record_map.push([lnum, lnum + 1]); + } else if (record_begin === null && has_unbalanced_double_quote) { + record_begin = lnum; + } else if (!has_unbalanced_double_quote) { + continue; + } else { + dst_record_map.push([record_begin, lnum + 1]); + record_begin = null; + } + } + if (record_begin !== null) { + dst_record_map.push([record_begin, num_lines]); + } +} + + +function make_table_name_key(file_path) { + return 'rbql_table_name:' + file_path; +} + + +function expanduser(filepath) { + if (filepath.charAt(0) === '~') { + return path.join(os.homedir(), filepath.slice(1)); + } + return filepath; +} + + +function find_table_path(vscode_global_state, main_table_dir, table_id) { + // If table_id is a relative path it could be relative either to the current directory or to the main table dir. + var candidate_path = expanduser(table_id); + if (fs.existsSync(candidate_path)) { + return candidate_path; + } + if (main_table_dir && !path.isAbsolute(candidate_path)) { + candidate_path = path.join(main_table_dir, candidate_path); + if (fs.existsSync(candidate_path)) { + return candidate_path; + } + } + let table_path = vscode_global_state ? vscode_global_state.get(make_table_name_key(table_id)) : null; + if (table_path && fs.existsSync(table_path)) { + return table_path; + } + return null; +} + + +async function read_header(table_path, encoding) { + if (encoding == 'latin-1') + encoding = 'binary'; + let readline = require('readline'); + let input_reader = readline.createInterface({ input: fs.createReadStream(table_path, {encoding: encoding}) }); + let closed = false; + let promise_resolve = null; + let promise_reject = null; + let output_promise = new Promise(function(resolve, reject) { + promise_resolve = resolve; + promise_reject = reject; + }); + input_reader.on('line', line => { + if (!closed) { + closed = true; + input_reader.close(); + promise_resolve(line); + } + }); + input_reader.on('error', error => { + promise_reject(error); + }); + return output_promise; +} + + +function get_header_line(document, comment_prefix) { + const num_lines = document.lineCount; + for (let lnum = 0; lnum < num_lines; ++lnum) { + const line_text = document.lineAt(lnum).text; + if (!comment_prefix || !line_text.startsWith(comment_prefix)) { + return line_text; + } + } + return null; +} + + +function make_inconsistent_num_fields_warning(table_name, inconsistent_records_info) { + let keys = Object.keys(inconsistent_records_info); + let entries = []; + for (let i = 0; i < keys.length; i++) { + let key = keys[i]; + let record_id = inconsistent_records_info[key]; + entries.push([record_id, key]); + } + entries.sort(function(a, b) { return a[0] - b[0]; }); + assert(entries.length > 1); + let [record_1, num_fields_1] = entries[0]; + let [record_2, num_fields_2] = entries[1]; + let warn_msg = `Number of fields in "${table_name}" table is not consistent: `; + warn_msg += `e.g. record ${record_1} -> ${num_fields_1} fields, record ${record_2} -> ${num_fields_2} fields`; + return warn_msg; +} + + + +class RbqlIOHandlingError extends Error {} + +class VSCodeRecordIterator extends rbql.RBQLInputIterator { + constructor(document, delim, policy, has_header=false, comment_prefix=null, table_name='input', variable_prefix='a') { + // We could have done a hack here actually: convert the document to stream/buffer and then use the standard reader. + super(); + this.document = document; + this.delim = delim; + this.policy = policy; + this.has_header = has_header; + this.comment_prefix = comment_prefix; + this.table_name = table_name; + this.variable_prefix = variable_prefix; + this.NR = 0; // Record number. + this.NL = 0; // Line number (NL != NR when the CSV file has comments or multiline fields). + this.fields_info = new Object(); + this.first_defective_line = null; + this.first_record = this.get_first_record(); + } + + stop() { + } + + get_first_record() { + let header_line = get_header_line(this.document, this.comment_prefix); + let first_record = csv_utils.smart_split(header_line, this.delim, this.policy, /*preserve_quotes_and_whitespaces=*/false)[0]; + return first_record; + } + + async get_variables_map(query_text) { + let variable_map = new Object(); + rbql.parse_basic_variables(query_text, this.variable_prefix, variable_map); + rbql.parse_array_variables(query_text, this.variable_prefix, variable_map); + let header_line = get_header_line(this.document, this.comment_prefix); + let first_record = csv_utils.smart_split(header_line, this.delim, this.policy, /*preserve_quotes_and_whitespaces=*/false)[0]; + if (this.has_header) { + rbql.parse_attribute_variables(query_text, this.variable_prefix, first_record, 'CSV header line', variable_map); + rbql.parse_dictionary_variables(query_text, this.variable_prefix, first_record, variable_map); + } + return variable_map; + } + + async get_header() { + return this.has_header ? this.first_record : null; + } + + get_line_rfc() { + let rfc_line_buffer = []; + const num_lines = this.document.lineCount; + while (this.NL < num_lines) { + let line = this.document.lineAt(this.NL).text; + this.NL += 1; + if (this.NL == num_lines && line.length == 0) + return null; // Skip the last line if it is empty - this can happen due to trailing newline. + let record_line = csv_utils.accumulate_rfc_line_into_record(rfc_line_buffer, line, this.comment_prefix); + if (record_line !== null) + return record_line; + } + return null; + } + + get_line_simple() { + const num_lines = this.document.lineCount; + while (this.NL < num_lines) { + let line = this.document.lineAt(this.NL).text; + this.NL += 1; + if (this.NL == num_lines && line.length == 0) + return null; // Skip the last line if it is empty - this can happen due to trailing newline. + if (this.comment_prefix === null || !line.startsWith(this.comment_prefix)) + return line; + } + return null; + } + + do_get_record() { + let line = (this.policy == 'quoted_rfc') ? this.get_line_rfc() : this.get_line_simple(); + if (line === null) + return null; + let [record, warning] = csv_utils.smart_split(line, this.delim, this.policy, /*preserve_quotes_and_whitespaces=*/false); + if (warning) { + if (this.first_defective_line === null) { + this.first_defective_line = this.NL; + if (this.policy == 'quoted_rfc') + throw new RbqlIOHandlingError(`Inconsistent double quote escaping in ${this.table_name} table at record ${this.NR}, line ${this.NL}`); + } + } + let num_fields = record.length; + if (!this.fields_info.hasOwnProperty(num_fields)) + this.fields_info[num_fields] = this.NR; + return record; + } + + async get_record() { + if (this.NR == 0 && this.has_header) { + this.do_get_record(); // Skip the header record. + } + this.NR += 1; + let record = this.do_get_record(); + return record; + } + + get_warnings() { + let result = []; + if (this.first_defective_line !== null) + result.push(`Inconsistent double quote escaping in ${this.table_name} table. E.g. at line ${this.first_defective_line}`); + if (Object.keys(this.fields_info).length > 1) + result.push(make_inconsistent_num_fields_warning(this.table_name, this.fields_info)); + return result; + } +} + + +class VSCodeWriter extends rbql.RBQLOutputWriter { + constructor(delim, policy) { + super(); + this.delim = delim; + this.policy = policy; + this.header_len = null; + this.null_in_output = false; + this.delim_in_simple_output = false; + this.output_lines = []; + + if (policy == 'simple') { + this.polymorphic_join = this.simple_join; + } else if (policy == 'quoted') { + this.polymorphic_join = this.quoted_join; + } else if (policy == 'quoted_rfc') { + this.polymorphic_join = this.quoted_join_rfc; + } else if (policy == 'monocolumn') { + this.polymorphic_join = this.mono_join; + } else if (policy == 'whitespace') { + this.polymorphic_join = this.simple_join; + } else { + throw new RbqlIOHandlingError('Unknown output csv policy'); + } + } + + set_header(header) { + if (header !== null) { + this.header_len = header.length; + this.write(header); + } + } + + quoted_join(fields) { + let delim = this.delim; + var quoted_fields = fields.map(function(v) { return csv_utils.quote_field(String(v), delim); }); + return quoted_fields.join(this.delim); + }; + + + quoted_join_rfc(fields) { + let delim = this.delim; + var quoted_fields = fields.map(function(v) { return csv_utils.rfc_quote_field(String(v), delim); }); + return quoted_fields.join(this.delim); + }; + + + mono_join(fields) { + if (fields.length > 1) { + throw new RbqlIOHandlingError('Unable to use "Monocolumn" output format: some records have more than one field'); + } + return fields[0]; + }; + + + simple_join(fields) { + var res = fields.join(this.delim); + if (fields.join('').indexOf(this.delim) != -1) { + this.delim_in_simple_output = true; + } + return res; + }; + + + normalize_fields(out_fields) { + for (var i = 0; i < out_fields.length; i++) { + if (out_fields[i] == null) { + this.null_in_output = true; + out_fields[i] = ''; + } else if (Array.isArray(out_fields[i])) { + this.normalize_fields(out_fields[i]); + out_fields[i] = out_fields[i].join(this.sub_array_delim); + } + } + }; + + + write(fields) { + if (this.header_len !== null && fields.length != this.header_len) + throw new RbqlIOHandlingError(`Inconsistent number of columns in output header and the current record: ${this.header_len} != ${fields.length}`); + this.normalize_fields(fields); + this.output_lines.push(this.polymorphic_join(fields)); + return true; + }; + + async finish() { + } + + get_warnings() { + let result = []; + if (this.null_in_output) + result.push('null values in output were replaced by empty strings'); + if (this.delim_in_simple_output) + result.push('Some output fields contain separator'); + return result; + }; +} + +class VSCodeTableRegistry { + constructor(){} + + get_iterator_by_table_id(_table_id) { + throw new RbqlIOHandlingError("JOIN queries are currently not supported in vscode.dev web version."); + } + + get_warnings() { + return []; + }; +} + +async function rbql_query_web(query_text, input_document, input_delim, input_policy, output_delim, output_policy, output_warnings, with_headers, comment_prefix=null) { + let user_init_code = ''; // TODO find a way to have init code. + let join_tables_registry = new VSCodeTableRegistry(); // TODO find a way to have join registry. + let input_iterator = new VSCodeRecordIterator(input_document, input_delim, input_policy, with_headers, comment_prefix); + let output_writer = new VSCodeWriter(output_delim, output_policy); + await rbql.query(query_text, input_iterator, output_writer, output_warnings, join_tables_registry, user_init_code); + return output_writer.output_lines; +} + + +class VSCodeFileSystemCSVRegistry extends rbql.RBQLTableRegistry { + constructor(vscode_global_state, input_file_dir, delim, policy, encoding, has_header=false, comment_prefix=null, options=null) { + super(); + this.vscode_global_state = vscode_global_state; + this.input_file_dir = input_file_dir; + this.delim = delim; + this.policy = policy; + this.encoding = encoding; + this.has_header = has_header; + this.comment_prefix = comment_prefix; + this.stream = null; + this.record_iterator = null; + + this.options = options; + this.bulk_input_path = null; + this.table_path = null; + } + + get_iterator_by_table_id(table_id) { + this.table_path = find_table_path(this.vscode_global_state, this.input_file_dir, table_id); + if (this.table_path === null) { + throw new RbqlIOHandlingError(`Unable to find join table "${table_id}"`); + } + if (this.options && this.options['bulk_read']) { + this.bulk_input_path = this.table_path; + } else { + this.stream = fs.createReadStream(this.table_path); + } + this.record_iterator = new rbql_csv.CSVRecordIterator(this.stream, this.bulk_input_path, this.encoding, this.delim, this.policy, this.has_header, this.comment_prefix, table_id, 'b'); + return this.record_iterator; + }; + + get_warnings(output_warnings) { + if (this.record_iterator && this.has_header) { + output_warnings.push(`The first record in JOIN file ${path.basename(this.table_path)} was also treated as header (and skipped)`); + } + } +} + + +async function rbql_query_node(vscode_global_state, query_text, input_path, input_delim, input_policy, output_path, output_delim, output_policy, csv_encoding, output_warnings, with_headers=false, comment_prefix=null, user_init_code='', options=null) { + let input_stream = null; + let bulk_input_path = null; + if (options && options['bulk_read'] && input_path) { + bulk_input_path = input_path; + } else { + input_stream = input_path === null ? process.stdin : fs.createReadStream(input_path); + } + let [output_stream, close_output_on_finish] = output_path === null ? [process.stdout, false] : [fs.createWriteStream(output_path), true]; + if (input_delim == '"' && input_policy == 'quoted') + throw new RbqlIOHandlingError('Double quote delimiter is incompatible with "quoted" policy'); + if (csv_encoding == 'latin-1') + csv_encoding = 'binary'; + if (!rbql_csv.is_ascii(query_text) && csv_encoding == 'binary') + throw new RbqlIOHandlingError('To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary'); + if ((!rbql_csv.is_ascii(input_delim) || !rbql_csv.is_ascii(output_delim)) && csv_encoding == 'binary') + throw new RbqlIOHandlingError('To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary'); + + let default_init_source_path = path.join(os.homedir(), '.rbql_init_source.js'); + if (user_init_code == '' && fs.existsSync(default_init_source_path)) { + user_init_code = rbql_csv.read_user_init_code(default_init_source_path); + } + let input_file_dir = input_path ? path.dirname(input_path) : null; + let join_tables_registry = new VSCodeFileSystemCSVRegistry(vscode_global_state, input_file_dir, input_delim, input_policy, csv_encoding, with_headers, comment_prefix, options); + let input_iterator = new rbql_csv.CSVRecordIterator(input_stream, bulk_input_path, csv_encoding, input_delim, input_policy, with_headers, comment_prefix); + let output_writer = new rbql_csv.CSVWriter(output_stream, close_output_on_finish, csv_encoding, output_delim, output_policy); + + await rbql.query(query_text, input_iterator, output_writer, output_warnings, join_tables_registry, user_init_code); + join_tables_registry.get_warnings(output_warnings); +} + + +module.exports.make_table_name_key = make_table_name_key; +module.exports.find_table_path = find_table_path; +module.exports.read_header = read_header; +module.exports.rbql_query_web = rbql_query_web; +module.exports.rbql_query_node = rbql_query_node; +module.exports.get_header_line = get_header_line; +module.exports.populate_optimistic_rfc_csv_record_map = populate_optimistic_rfc_csv_record_map; +module.exports.get_default_js_udf_content = get_default_js_udf_content; +module.exports.get_default_python_udf_content = get_default_python_udf_content; +module.exports.align_columns = align_columns; +module.exports.shrink_columns = shrink_columns; +module.exports.calc_column_stats = calc_column_stats; +module.exports.adjust_column_stats = adjust_column_stats; +module.exports.update_subcomponent_stats = update_subcomponent_stats; +module.exports.align_field = align_field; diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql mock/rbql_mock.py b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql mock/rbql_mock.py new file mode 100644 index 00000000..44e5430c --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql mock/rbql_mock.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python + +import sys +import os +import argparse +import random +import tempfile +import json +import time + + +def parse_params(param_string): + test_marker = 'test ' + assert param_string.startswith(test_marker) + param_string = param_string[len(test_marker):] + result = dict() + kv_pairs = param_string.split(',') + for p in kv_pairs: + if p.find(':') == -1: + continue + key, value = p.split(':') + result[key] = value + return result + + +class MockException(RuntimeError): + pass + + +def main(): + param_string = sys.argv[1] + params = parse_params(param_string) + output = ' '.join(sys.argv) + tmp_dir = tempfile.gettempdir() + tmp_file = os.path.join(tmp_dir, 'rnd_mock.{}.txt'.format(random.randint(0, 1000 * 1000 * 1000))) + with open(tmp_file, 'w') as f: + for i in range(10): + f.write(param_string + '\n') + report = {'result_path': tmp_file} + + + if 'sleep' in params: + sleep_time = float(params['sleep']) + time.sleep(sleep_time) + + if 'error' in params: + report['error_type'] = 'Mock Error' + report['error_details'] = params['error'] + + if 'warning' in params: + report['warnings'] = params['warning'].split(';') + + if 'unhandled_exception' in params: + raise MockException('Unhandled Mock Exception') + + if 'handled_exception' in params: + try: + raise MockException('Handled Mock Exception') + except Exception as e: + report['error_type'] = 'Exception' + report['error_details'] = str(e) + + if 'stderr' in params: + sys.stderr.write(params['stderr']) + + if 'stdout' in params: + sys.stdout.write(params['stdout']) + else: + sys.stdout.write(json.dumps(report)) + + if 'return_code' in params: + return_code = int(params['return_code']) + sys.exit(return_code) + + +if __name__ == '__main__': + main() diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_client.html b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_client.html new file mode 100644 index 00000000..08fc321d --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_client.html @@ -0,0 +1,620 @@ + + + + + + + + + + + + + + + + + + + +
+
+
+ +
+
+ +
+
+ + +
+

⚙ Query settings

+
+
+ +
+
+ +
+
+
+ Output format +
+ +
+
+
+ Encoding +
+ +
+
+
+ Backend language for RBQL +
+ +
+
+ +
+
+
+ + +
+
+ Query history + +
+
+
+
+ + +
+
+ + +
+
+ ⚠ Error while executing RBQL query! +
+
+
+ +
+
+
+ Details: +
+
+
+
+ +
+
+ + + +
+ RBQL +

Read RBQL documentation on github

+
+

RBQL: Rainbow Query Language

+

RBQL is an eval-based SQL-like query engine for (not only) CSV file processing. It provides SQL-like language that supports SELECT queries with Python or JavaScript expressions.
+ RBQL is best suited for data transformation, data cleaning, and analytical queries.
+ RBQL is distributed with CLI apps, text editor plugins, Python and JS libraries.

+

Main Features

+
    +
  • Use Python or JavaScript expressions inside SELECT, UPDATE, WHERE and ORDER BY statements
  • +
  • Supports multiple input formats
  • +
  • Result set of any query immediately becomes a first-class table on its own
  • +
  • No need to provide FROM statement in the query - input table is defined by the current context
  • +
  • Supports all main SQL keywords
  • +
  • Supports aggregate functions and GROUP BY queries
  • +
  • Supports user-defined functions (UDF)
  • +
  • Provides some new useful query modes which traditional SQL engines do not have
  • +
  • Lightweight, dependency-free, works out of the box
  • +
+

Limitations:

+
    +
  • RBQL doesn't support nested queries, but they can be emulated with consecutive queries
  • +
  • Number of tables in all JOIN queries is always 2 (input table and join table), use consecutive queries to join 3 or more tables
  • +
+

Supported SQL Keywords (Keywords are case insensitive)

+
    +
  • SELECT
  • +
  • UPDATE
  • +
  • WHERE
  • +
  • ORDER BY … [ DESC | ASC ]
  • +
  • [ LEFT | INNER ] JOIN
  • +
  • DISTINCT
  • +
  • GROUP BY
  • +
  • TOP N
  • +
  • LIMIT N
  • +
+

All keywords have the same meaning as in SQL queries. You can check them online

+

RBQL variables

+

RBQL for CSV files provides the following variables which you can use in your queries:

+
    +
  • a1, a2,…, a{N}
    + Variable type: string
    + Description: value of i-th field in the current record in input table
  • +
  • b1, b2,…, b{N}
    + Variable type: string
    + Description: value of i-th field in the current record in join table B
  • +
  • NR
    + Variable type: integer
    + Description: Record number (1-based)
  • +
  • NF
    + Variable type: integer
    + Description: Number of fields in the current record
  • +
  • a.name, b.Person_age, … a.{Good_alphanumeric_column_name}
    + Variable type: string
    + Description: Value of the field referenced by it's "name". You can use this notation if the field in the header has a "good" alphanumeric name
  • +
  • a["object id"], a['9.12341234'], b["%$ !! 10 20"]a["Arbitrary column name!"]
    + Variable type: string
    + Description: Value of the field referenced by it's "name". You can use this notation to reference fields by arbitrary values in the header
  • +
+

UPDATE statement

+

UPDATE query produces a new table where original values are replaced according to the UPDATE expression, so it can also be considered a special type of SELECT query. This prevents accidental data loss from poorly written queries.
+ UPDATE SET is synonym to UPDATE, because in RBQL there is no need to specify the source table.

+

Aggregate functions and queries

+

RBQL supports the following aggregate functions, which can also be used with GROUP BY keyword:
+ COUNT, ARRAY_AGG, MIN, MAX, SUM, AVG, VARIANCE, MEDIAN

+

Limitation: aggregate functions inside Python (or JS) expressions are not supported. Although you can use expressions inside aggregate functions.
+ E.g. MAX(float(a1) / 1000) - valid; MAX(a1) / 1000 - invalid.
+ There is a workaround for the limitation above for ARRAY_AGG function which supports an optional parameter - a callback function that can do something with the aggregated array. Example:
+ select a2, ARRAY_AGG(a1, lambda v: sorted(v)[:5]) group by a2 - Python; select a2, ARRAY_AGG(a1, v => v.sort().slice(0, 5)) group by a2 - JS

+

JOIN statements

+

Join table B can be referenced either by its file path or by its name - an arbitrary string which the user should provide before executing the JOIN query.
+ RBQL supports STRICT LEFT JOIN which is like LEFT JOIN, but generates an error if any key in the left table "A" doesn't have exactly one matching key in the right table "B".
+ Limitation: JOIN statements can't contain Python/JS expressions and must have the following form: (/path/to/table.tsv | table_name ) ON a… == b… [AND a… == b… [AND … ]]

+

SELECT EXCEPT statement

+

SELECT EXCEPT can be used to select everything except specific columns. E.g. to select everything but columns 2 and 4, run: SELECT * EXCEPT a2, a4
+ Traditional SQL engines do not support this query mode.

+

UNNEST() operator

+

UNNEST(list) takes a list/array as an argument and repeats the output record multiple times - one time for each value from the list argument.
+ Example: SELECT a1, UNNEST(a2.split(';'))

+

LIKE() function

+

RBQL does not support LIKE operator, instead it provides "like()" function which can be used like this:
+ SELECT * where like(a1, 'foo%bar')

+

WITH (header) and WITH (noheader) statements

+

You can set whether the input (and join) CSV file has a header or not using the environment configuration parameters which could be --with_headers CLI flag or GUI checkbox or something else.
+ But it is also possible to override this selection directly in the query by adding either WITH (header) or WITH (noheader) statement at the end of the query.
+ Example: select top 5 NR, * with (header)

+

User Defined Functions (UDF)

+

RBQL supports User Defined Functions
+ You can define custom functions and/or import libraries in two special files:

+
    +
  • ~/.rbql_init_source.py - for Python
  • +
  • ~/.rbql_init_source.js - for JavaScript
  • +
+

Examples of RBQL queries

+

With Python expressions

+
    +
  • select top 100 a1, int(a2) * 10, len(a4) where a1 == "Buy" order by int(a2) desc
  • +
  • select * order by random.random() - random sort
  • +
  • select len(a.vehicle_price) / 10, a2 where int(a.vehicle_price) < 500 and a['Vehicle type'] in ["car", "plane", "boat"] limit 20 - referencing columns by names from header and using Python's "in" to emulate SQL's "in"
  • +
  • update set a3 = 'NPC' where a3.find('Non-playable character') != -1
  • +
  • select NR, * - enumerate records, NR is 1-based
  • +
  • select * where re.match(".*ab.*", a1) is not None - select entries where first column has "ab" pattern
  • +
  • select a1, b1, b2 inner join ./countries.txt on a2 == b1 order by a1, a3 - example of join query
  • +
  • select MAX(a1), MIN(a1) where a.Name != 'John' group by a2, a3 - example of aggregate query
  • +
  • select *a1.split(':') - Using Python3 unpack operator to split one column into many. Do not try this with other SQL engines!
  • +
+

With JavaScript expressions

+
    +
  • select top 100 a1, a2 * 10, a4.length where a1 == "Buy" order by parseInt(a2) desc
  • +
  • select * order by Math.random() - random sort
  • +
  • select top 20 a.vehicle_price.length / 10, a2 where parseInt(a.vehicle_price) < 500 && ["car", "plane", "boat"].indexOf(a['Vehicle type']) > -1 limit 20 - referencing columns by names from header
  • +
  • update set a3 = 'NPC' where a3.indexOf('Non-playable character') != -1
  • +
  • select NR, * - enumerate records, NR is 1-based
  • +
  • select a1, b1, b2 inner join ./countries.txt on a2 == b1 order by a1, a3 - example of join query
  • +
  • select MAX(a1), MIN(a1) where a.Name != 'John' group by a2, a3 - example of aggregate query
  • +
  • select ...a1.split(':') - Using JS "destructuring assignment" syntax to split one column into many. Do not try this with other SQL engines!
  • +
+
+
+ + + + + diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_client.js b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_client.js new file mode 100644 index 00000000..bce84748 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_client.js @@ -0,0 +1,437 @@ +var rbql_running = false; + +var handshake_completed = false; + +var query_history = []; + +const vscode = acquireVsCodeApi(); + +var global_css_style = null; + +var last_preview_message = null; + +var adjust_join_table_header_callback = null; + +var global_header = null; + +var is_web_ext = null; + +function report_backend_language_change() { + let backend_language = document.getElementById('select_backend_language').value; + vscode.postMessage({'msg_type': 'global_param_change', 'key': 'rbql_backend_language', 'value': backend_language}); + assign_backend_lang_selection_title(); +} + + +function report_encoding_change() { + let encoding = document.getElementById('select_encoding').value; + vscode.postMessage({'msg_type': 'global_param_change', 'key': 'rbql_encoding', 'value': encoding}); +} + + +function report_rfc_fields_policy_change() { + let enable_rfc_newlines = document.getElementById('enable_rfc_newlines').checked; + vscode.postMessage({'msg_type': 'newlines_policy_change', 'enable_rfc_newlines': enable_rfc_newlines}); +} + + +function remove_children(root_node) { + while (root_node.firstChild) { + root_node.removeChild(root_node.firstChild); + } +} + + +function get_max_num_columns(records, with_headers) { + let max_num_columns = 0; + for (let r = 0; r < records.length; r++) { + max_num_columns = Math.max(max_num_columns, records[r].length); + } + if (with_headers && global_header && global_header.length) + max_num_columns = Math.max(max_num_columns, global_header.length); + return max_num_columns; +} + + +function add_header_cell_with_text(cell_text, dst_row_elem) { + let cell = document.createElement('th'); + cell.textContent = cell_text; + dst_row_elem.appendChild(cell); +} + + +function add_header_row(max_num_columns, with_headers, table) { + let row_elem = document.createElement('tr'); + add_header_cell_with_text('NR', row_elem); + let named_header_vars = []; + if (with_headers && global_header && global_header.length) { + named_header_vars = rbql_suggest.convert_header_to_rbql_variables(global_header, 'a'); + } + for (let i = 0; i < max_num_columns; i++) { + let cell_text = `a${i + 1}`; + if (i < named_header_vars.length) { + let var_column = named_header_vars[i].dot_var ? named_header_vars[i].dot_var : named_header_vars[i].single_q_var; + cell_text += '\r\n' + var_column; + } + add_header_cell_with_text(cell_text, row_elem); + } + table.appendChild(row_elem); +} + + +function make_data_cell(cell_text) { + let cell = document.createElement('td'); + const trim_marker = '###UI_STRING_TRIM_MARKER###'; + let add_ellipsis = false; + if (cell_text.endsWith(trim_marker)) { + cell_text = cell_text.substr(0, cell_text.length - trim_marker.length); + add_ellipsis = true; + } + let field_rfc_lines = cell_text.split('\n'); + for (let i = 0; i < field_rfc_lines.length; i++) { + let span = document.createElement('span'); + span.textContent = field_rfc_lines[i]; + cell.appendChild(span); + if (i + 1 < field_rfc_lines.length) { + let newline_span = document.createElement('span'); + newline_span.textContent = '\\n'; + newline_span.style.color = global_css_style.getPropertyValue('--vscode-editorWarning-foreground'); + newline_span.title = 'new line'; + cell.appendChild(newline_span); + } + } + if (add_ellipsis) { + let ellipsis_span = document.createElement('span'); + ellipsis_span.style.color = global_css_style.getPropertyValue('--vscode-editorWarning-foreground'); + ellipsis_span.textContent = ' ...'; + ellipsis_span.title = 'value too long to display'; + cell.appendChild(ellipsis_span); + } + return cell; +} + + +function make_nr_cell(cell_text) { + let nr_cell = document.createElement('td'); + nr_cell.textContent = cell_text; + return nr_cell; +} + + +function make_preview_table() { + if (!last_preview_message) + return; + let records = last_preview_message.preview_records; + let start_record_zero_based = last_preview_message.start_record_zero_based; + let preview_error = last_preview_message.preview_sampling_error; + + var table = document.getElementById('preview_table'); + remove_children(table); + if (preview_error) { + let row = document.createElement('tr'); + table.appendChild(row); + let span = document.createElement('span'); + span.style.color = global_css_style.getPropertyValue('--vscode-inputValidation-errorForeground'); + span.textContent = 'Unable to display preview table and run RBQL query:'; + row.appendChild(span); + row.appendChild(document.createElement('br')); + span = document.createElement('span'); + span.style.color = global_css_style.getPropertyValue('--vscode-inputValidation-errorForeground'); + span.textContent = preview_error; + row.appendChild(span); + return; + } + + let with_headers = document.getElementById('with_headers').checked; + let max_num_columns = get_max_num_columns(records, with_headers); + add_header_row(max_num_columns, with_headers, table); + for (var r = 0; r < records.length; r++) { + let row = document.createElement('tr'); + let NR = r + start_record_zero_based + 1; + if (with_headers) { + NR -= 1; + if (NR == 0) + continue; + } + row.appendChild(make_nr_cell(String(NR))); + for (var nf = 0; nf < records[r].length; nf++) { + row.appendChild(make_data_cell(records[r][nf])); + } + table.appendChild(row); + } +} + + +function navigate_preview(direction) { + vscode.postMessage({'msg_type': 'navigate', 'direction': direction}); +} + + +function preview_backward() { + navigate_preview('backward'); +} + + +function preview_forward() { + navigate_preview('forward'); +} + + +function preview_begin() { + navigate_preview('begin'); +} + + +function preview_end() { + navigate_preview('end'); +} + + +function apply_suggest_callback(query) { + vscode.postMessage({'msg_type': 'update_query', 'query': query}); +} + + +function fetch_join_header_callback(join_table_id, adjust_join_table_headers) { + adjust_join_table_header_callback = adjust_join_table_headers; + let encoding = document.getElementById('select_encoding').value; + vscode.postMessage({'msg_type': 'fetch_table_header', 'table_id': join_table_id, 'encoding': encoding}); +} + + +function process_with_headers_change() { + let with_headers = document.getElementById('with_headers').checked; + vscode.postMessage({'msg_type': 'with_headers_change', 'with_headers': with_headers}); // We need to send it to remember preview state + let header = with_headers ? global_header : null; + rbql_suggest.initialize_suggest('rbql_input', 'query_suggest', 'history_button', apply_suggest_callback, header, fetch_join_header_callback); + make_preview_table(); +} + + +function show_error(error_type, error_msg) { + error_msg = error_msg.replace('\r?\n', '\r\n'); + document.getElementById('error_message_header').textContent = 'Error type: "' + error_type + '"'; + document.getElementById('error_message_details').textContent = error_msg; + document.getElementById('rbql_error_message').style.display = 'block'; + document.getElementById('ack_error').focus(); +} + + +function hide_error_msg() { + document.getElementById('rbql_error_message').style.display = 'none'; + document.getElementById("rbql_input").focus(); +} + + +function toggle_help_msg() { + let document_bg_color = global_css_style.getPropertyValue('--vscode-notifications-background'); + let rbql_help_element = document.getElementById('rbql_help'); + var style_before = rbql_help_element.style.display; + var new_style = style_before == 'block' ? 'none' : 'block'; + if (new_style == 'block') + rbql_help_element.style.backgroundColor = document_bg_color; + rbql_help_element.style.display = new_style; + document.getElementById('close_help').style.display = new_style; +} + + +function register_history_callback(button_element, query) { + button_element.addEventListener("click", () => { document.getElementById('rbql_input').value = query; }); +} + + +function toggle_history() { + let query_history_block = document.getElementById('query_history'); + var style_before = query_history_block.style.display; + var new_style = style_before == 'block' ? 'none' : 'block'; + if (new_style == 'block') { + document.getElementById('toggle_history_btn').textContent = '\u25BC'; + } else { + document.getElementById('toggle_history_btn').textContent = '\u25B2'; + } + let history_entries_block = document.getElementById('history_entries'); + remove_children(history_entries_block); + for (let nr = 0; nr < query_history.length; nr++) { + let entry_button = document.createElement('button'); + entry_button.className = 'history_button'; + entry_button.textContent = query_history[nr]; + register_history_callback(entry_button, query_history[nr]); + history_entries_block.appendChild(entry_button); + } + query_history_block.style.display = new_style; + let calculated_height = query_history_block.offsetHeight; + let text_input_coordinates = document.getElementById('rbql_input').getBoundingClientRect(); + query_history_block.style.left = text_input_coordinates.left + 'px'; + query_history_block.style.top = (text_input_coordinates.top - calculated_height) + 'px'; +} + + +function clear_history() { + query_history = []; + toggle_history(); + vscode.postMessage({'msg_type': 'global_param_change', 'key': 'rbql_query_history', 'value': []}); +} + + +function start_rbql() { + var rbql_text = document.getElementById('rbql_input').value; + if (!rbql_text || rbql_running) + return; + rbql_running = true; + document.getElementById('rbql_run_btn').textContent = "\u231B"; + let backend_language = document.getElementById('select_backend_language').value; + let output_format = document.getElementById('select_output_format').value; + let encoding = document.getElementById('select_encoding').value; + let enable_rfc_newlines = document.getElementById('enable_rfc_newlines').checked; + let with_headers = document.getElementById('with_headers').checked; + vscode.postMessage({'msg_type': 'run', 'query': rbql_text, 'backend_language': backend_language, 'output_dialect': output_format, 'encoding': encoding, 'enable_rfc_newlines': enable_rfc_newlines, 'with_headers': with_headers}); +} + + +function handle_message(msg_event) { + var message = msg_event.data; + console.log('message received at client: ' + JSON.stringify(msg_event)); + let message_type = message['msg_type']; + + if (message_type == 'handshake') { + if (handshake_completed) + return; + handshake_completed = true; + if (message.hasOwnProperty('last_query')) { + document.getElementById('rbql_input').value = message['last_query']; + } + if (message.hasOwnProperty('query_history')) { + query_history = message['query_history']; + } + global_header = message['header']; + is_web_ext = message['is_web_ext']; + let with_headers = message['with_headers']; + let header = with_headers ? global_header : null; + rbql_suggest.initialize_suggest('rbql_input', 'query_suggest', 'history_button', apply_suggest_callback, header, fetch_join_header_callback); + let enable_rfc_newlines = message['enable_rfc_newlines']; + last_preview_message = message; + document.getElementById("select_backend_language").value = message['backend_language']; + assign_backend_lang_selection_title(); + document.getElementById("select_encoding").value = message['encoding']; + document.getElementById("enable_rfc_newlines").checked = enable_rfc_newlines; + document.getElementById("with_headers").checked = with_headers; + if (message['policy'] == 'quoted') { + document.getElementById('enable_rfc_newlines_section').style.display = 'block'; + } + make_preview_table(); + + let integration_test_query = message['integration_test_query']; + let integration_test_language = message['integration_test_language']; + if (integration_test_query && integration_test_language) { + if (message['integration_test_enable_rfc_newlines']) { + document.getElementById("enable_rfc_newlines").checked = true; + report_rfc_fields_policy_change(); + } + if (message['integration_test_with_headers']) { + document.getElementById("with_headers").checked = true; + process_with_headers_change(); + } + document.getElementById("select_backend_language").value = integration_test_language; + assign_backend_lang_selection_title(); + document.getElementById('rbql_input').value = integration_test_query; + setTimeout(function() { + start_rbql(); + }, 2000); + } + } + + if (message_type == 'fetch_table_header_response') { + if (adjust_join_table_header_callback && message['header']) { + adjust_join_table_header_callback(message['header']); + } + } + + if (message_type == 'navigate' || message_type == 'resample') { + last_preview_message = message; + make_preview_table(); + } + + if (message_type == 'rbql_report') { + rbql_running = false; + if (message.hasOwnProperty('error_type') || message.hasOwnProperty('error_msg')) { + let error_type = message.hasOwnProperty('error_type') ? message['error_type'] : 'Unexpected'; + let error_msg = message.hasOwnProperty('error_msg') ? message['error_msg'] : 'Unknown Error'; + show_error(error_type, error_msg); + } + document.getElementById('rbql_run_btn').textContent = "Run"; + } +} + + +function is_printable_key_code(keycode) { + // Taken from here: https://stackoverflow.com/a/12467610/2898283 + return (keycode > 47 && keycode < 58) || keycode == 32 || (keycode > 64 && keycode < 91) || (keycode > 185 && keycode < 193) || (keycode > 218 && keycode < 223); +} + + +function handle_input_keyup(event) { + rbql_suggest.handle_input_keyup(event); + if (is_printable_key_code(event.keyCode) || event.keyCode == 8 /* Bakspace */) { + let current_query = document.getElementById('rbql_input').value; + vscode.postMessage({'msg_type': 'update_query', 'query': current_query}); + } +} + + +function handle_input_keydown(event) { + if (event.keyCode == 13 && rbql_suggest.active_suggest_idx === null) { + start_rbql(); + } else { + rbql_suggest.handle_input_keydown(event); + } +} + + +function assign_backend_lang_selection_title() { + let select_backend_element = document.getElementById('select_backend_language'); + let backend_language = select_backend_element.value; + if (backend_language == 'js') { + select_backend_element.title = 'Allows to use JS expressions such as: `Math.sqrt(a1)`, `a2.substring(1, 5)`, `a3.toUpperCase()`, etc'; + } else { + select_backend_element.title = 'Allows to use Python expressions such as: `math.sqrt(float(a1))`, `a2[1:5]`, `a3.upper()`, etc'; + } +} + + +function handle_udf_edit() { + let backend_language = document.getElementById('select_backend_language').value; + vscode.postMessage({'msg_type': 'edit_udf', 'backend_language': backend_language}); +} + + +function main() { + global_css_style = getComputedStyle(document.body); + assign_backend_lang_selection_title(); + + window.addEventListener('message', handle_message); + vscode.postMessage({'msg_type': 'handshake'}); + + document.getElementById("rbql_run_btn").addEventListener("click", start_rbql); + document.getElementById("select_backend_language").addEventListener("change", report_backend_language_change); + document.getElementById("select_encoding").addEventListener("change", report_encoding_change); + document.getElementById("enable_rfc_newlines").addEventListener("click", report_rfc_fields_policy_change); + document.getElementById("with_headers").addEventListener("click", process_with_headers_change); + document.getElementById("ack_error").addEventListener("click", hide_error_msg); + document.getElementById("help_btn").addEventListener("click", toggle_help_msg); + document.getElementById("close_help").addEventListener("click", toggle_help_msg); + document.getElementById("toggle_history_btn").addEventListener("click", toggle_history); + document.getElementById("clear_history_btn").addEventListener("click", clear_history); + document.getElementById("go_begin").addEventListener("click", preview_begin); + document.getElementById("go_backward").addEventListener("click", preview_backward); + document.getElementById("go_forward").addEventListener("click", preview_forward); + document.getElementById("go_end").addEventListener("click", preview_end); + document.getElementById("rbql_input").addEventListener("keyup", handle_input_keyup); + document.getElementById("rbql_input").addEventListener("keydown", handle_input_keydown); + document.getElementById("udf_button").addEventListener("click", handle_udf_edit); + document.getElementById("rbql_input").focus(); +} + + +document.addEventListener("DOMContentLoaded", function(_event) { + main(); +}); diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/LICENSE b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/LICENSE new file mode 100644 index 00000000..6a82aa1c --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Dmitry Ignatovich + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/README.md b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/README.md new file mode 100644 index 00000000..24e0016b --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/README.md @@ -0,0 +1,200 @@ +![RBQL logo](rbql_logo.png) + +# RBQL: Rainbow Query Language + +RBQL is an eval-based SQL-like query engine for (not only) CSV file processing. It provides SQL-like language that supports SELECT queries with Python or JavaScript expressions. +RBQL is best suited for data transformation, data cleaning, and analytical queries. +RBQL is distributed with CLI apps, text editor plugins, IPython/Jupyter magic command, Python and JS libraries. + +[Official Site](https://rbql.org/) + +#### Supported formats + +Matrix of data formats that RBQL supports out of the box. R=Read, W=Write + +|Data Format | Python | JS | +|-----------------------|----------|---------| +|CSV, TSV, etc | **RW** | **RW** | +|Native 2D arrays/lists | **RW** | **RW** | +|Pandas dataframe | **RW** | | +|Sqlite databases | **R** | | + +If you use RBQL as a library you can write implementation for a couple of classes to support additional formats. + +### Main Features + +* Use Python or JavaScript expressions inside _SELECT_, _UPDATE_, _WHERE_ and _ORDER BY_ statements +* Supports multiple input formats +* Result set of any query immediately becomes a first-class table on its own +* No need to provide FROM statement in the query when the input table is defined by the current context. +* Supports all main SQL keywords +* Supports aggregate functions and GROUP BY queries +* Supports user-defined functions (UDF) +* Provides some new useful query modes which traditional SQL engines do not have +* Lightweight, dependency-free, works out of the box + +#### Limitations: + +* RBQL doesn't support nested queries, but they can be emulated with consecutive queries +* Number of tables in all JOIN queries is always 2 (input table and join table), use consecutive queries to join 3 or more tables + +### Supported SQL Keywords (Keywords are case insensitive) + +* SELECT +* UPDATE +* WHERE +* ORDER BY ... [ DESC | ASC ] +* [ LEFT | INNER ] JOIN +* DISTINCT +* GROUP BY +* TOP _N_ +* LIMIT _N_ + +All keywords have the same meaning as in SQL queries. You can check them [online](https://www.w3schools.com/sql/default.asp) + + +### RBQL variables +RBQL for CSV files provides the following variables which you can use in your queries: + +* _a1_, _a2_,..., _a{N}_ + Variable type: **string** + Description: value of i-th field in the current record in input table +* _b1_, _b2_,..., _b{N}_ + Variable type: **string** + Description: value of i-th field in the current record in join table B +* _NR_ + Variable type: **integer** + Description: Record number (1-based) +* _NF_ + Variable type: **integer** + Description: Number of fields in the current record +* _a.name_, _b.Person_age_, ... _a.{Good_alphanumeric_column_name}_ + Variable type: **string** + Description: Value of the field referenced by it's "name". You can use this notation if the field in the header has a "good" alphanumeric name +* _a["object id"]_, _a['9.12341234']_, _b["%$ !! 10 20"]_ ... _a["Arbitrary column name!"]_ + Variable type: **string** + Description: Value of the field referenced by it's "name". You can use this notation to reference fields by arbitrary values in the header + + +### UPDATE statement + +_UPDATE_ query produces a new table where original values are replaced according to the UPDATE expression, so it can also be considered a special type of SELECT query. + +### Aggregate functions and queries + +RBQL supports the following aggregate functions, which can also be used with _GROUP BY_ keyword: +_COUNT_, _ARRAY_AGG_, _MIN_, _MAX_, _SUM_, _AVG_, _VARIANCE_, _MEDIAN_ + +Limitation: aggregate functions inside Python (or JS) expressions are not supported. Although you can use expressions inside aggregate functions. +E.g. `MAX(float(a1) / 1000)` - valid; `MAX(a1) / 1000` - invalid. +There is a workaround for the limitation above for _ARRAY_AGG_ function which supports an optional parameter - a callback function that can do something with the aggregated array. Example: +`select a2, ARRAY_AGG(a1, lambda v: sorted(v)[:5]) group by a2` - Python; `select a2, ARRAY_AGG(a1, v => v.sort().slice(0, 5)) group by a2` - JS + + +### JOIN statements + +Join table B can be referenced either by its file path or by its name - an arbitrary string which the user should provide before executing the JOIN query. +RBQL supports _STRICT LEFT JOIN_ which is like _LEFT JOIN_, but generates an error if any key in the left table "A" doesn't have exactly one matching key in the right table "B". +Table B path can be either relative to the working dir, relative to the main table or absolute. +Limitation: _JOIN_ statements can't contain Python/JS expressions and must have the following form: _ (/path/to/table.tsv | table_name ) ON a... == b... [AND a... == b... [AND ... ]]_ + +### SELECT EXCEPT statement + +SELECT EXCEPT can be used to select everything except specific columns. E.g. to select everything but columns 2 and 4, run: `SELECT * EXCEPT a2, a4` +Traditional SQL engines do not support this query mode. + + +### UNNEST() operator +UNNEST(list) takes a list/array as an argument and repeats the output record multiple times - one time for each value from the list argument. +Example: `SELECT a1, UNNEST(a2.split(';'))` + + +### LIKE() function +RBQL does not support LIKE operator, instead it provides "like()" function which can be used like this: +`SELECT * where like(a1, 'foo%bar')` + + +### WITH (header) and WITH (noheader) statements +You can set whether the input (and join) CSV file has a header or not using the environment configuration parameters which could be `--with_headers` CLI flag or GUI checkbox or something else. +But it is also possible to override this selection directly in the query by adding either `WITH (header)` or `WITH (noheader)` statement at the end of the query. +Example: `select top 5 NR, * with (header)` + + +### User Defined Functions (UDF) + +RBQL supports User Defined Functions +You can define custom functions and/or import libraries in two special files: +* `~/.rbql_init_source.py` - for Python +* `~/.rbql_init_source.js` - for JavaScript + + +## Examples of RBQL queries + +#### With Python expressions + +* `select top 100 a1, int(a2) * 10, len(a4) where a1 == "Buy" order by int(a2) desc` +* `select * order by random.random()` - random sort +* `select len(a.vehicle_price) / 10, a2 where int(a.vehicle_price) < 500 and a['Vehicle type'] in ["car", "plane", "boat"] limit 20` - referencing columns by names from header and using Python's "in" to emulate SQL's "in" +* `update set a3 = 'NPC' where a3.find('Non-playable character') != -1` +* `select NR, *` - enumerate records, NR is 1-based +* `select * where re.match(".*ab.*", a1) is not None` - select entries where first column has "ab" pattern +* `select a1, b1, b2 inner join ./countries.txt on a2 == b1 order by a1, a3` - example of join query +* `select MAX(a1), MIN(a1) where a.Name != 'John' group by a2, a3` - example of aggregate query +* `select *a1.split(':')` - Using Python3 unpack operator to split one column into many. Do not try this with other SQL engines! + +#### With JavaScript expressions + +* `select top 100 a1, a2 * 10, a4.length where a1 == "Buy" order by parseInt(a2) desc` +* `select * order by Math.random()` - random sort +* `select top 20 a.vehicle_price.length / 10, a2 where parseInt(a.vehicle_price) < 500 && ["car", "plane", "boat"].indexOf(a['Vehicle type']) > -1 limit 20` - referencing columns by names from header +* `update set a3 = 'NPC' where a3.indexOf('Non-playable character') != -1` +* `select NR, *` - enumerate records, NR is 1-based +* `select a1, b1, b2 inner join ./countries.txt on a2 == b1 order by a1, a3` - example of join query +* `select MAX(a1), MIN(a1) where a.Name != 'John' group by a2, a3` - example of aggregate query +* `select ...a1.split(':')` - Using JS "destructuring assignment" syntax to split one column into many. Do not try this with other SQL engines! + + +## RBQL design principles and architecture +RBQL core idea is based on dynamic code generation and execution with [exec](https://docs.python.org/3/library/functions.html#exec) and [eval](https://www.w3schools.com/jsref/jsref_eval.asp) functions. +Here are the main steps that RBQL engine performs when processing a query: +1. Shallow parsing: split the query into logical expressions such as "SELECT", "WHERE", "ORDER BY", etc. +2. Embed the expression segments into the main loop template code +3. Execute the hydrated loop code + +Here you can find a very basic working script (only 15 lines of Python code) which implements this idea: [mini_rbql.py](https://github.com/mechatroner/mini-rbql/blob/master/mini_rbql.py) + +The diagram below gives an overview of the main RBQL components and data flow: +![RBQL Diagram](https://i.imgur.com/KDQHoVM.png) + + +### Advantages of RBQL over traditional SQL engines +* Provides power and flexibility of general purpose Python and JS languages in relational expressions (including regexp, math, file system, json, xml, random and many other libraries that these languages provide) +* Can work with different data sources including CSV files, sqlite tables, native 2D arrays/lists (traditional SQL engines are usually tightly coupled with their databases) +* Result set of any query immediately becomes a first-class table on its own +* Supports both TOP and LIMIT keywords +* Provides additional NR (record number) variable which is especially useful for input sources where record order is well defined (such as CSV files) +* Supports input tables with inconsistent number of fields per record +* Allows to generate result sets with variable number of fields per record e.g. by using split() function and unpack operator (Python) / destructuring assignment (JS) +* UPDATE is a special case of SELECT query - this prevents accidental data loss +* No need to use FROM statement when the table name is defined by the context. This improves query typing speed and allows immediate autocomplete for variables inside SELECT statement (in traditional SQL engines autocomplete will not work until you write FROM statement, which goes after SELECT statement) +* SELECT, WHERE, ORDER BY, and other statements can be rearranged in any way you like +* Supports EXCEPT statement +* Provides a fully-functional client-side browser demo application +* Almost nonexistent entry barrier both for SQL users and JS/Python users +* Integration with popular text editors (VSCode, Vim, Sublime Text, Atom) +* Small, maintainable, dependency-free, eco-friendly and hackable code base: RBQL engine fits into a single file with less than 2000 LOC + +### Disadvantages of RBQL compared to traditional SQL engines +* Not suitable for transactional workload +* RBQL doesn't support nested queries, but they can be emulated with consecutive queries +* Number of tables in all JOIN queries is always 2 (input table and join table), use consecutive queries to join 3 or more tables +* Does not support HAVING statement + + +### References + +* [RBQL: Official Site](https://rbql.org/) +* RBQL is integrated with Rainbow CSV extensions in [Vim](https://github.com/mechatroner/rainbow_csv), [VSCode](https://marketplace.visualstudio.com/items?itemName=mechatroner.rainbow-csv), [Sublime Text](https://packagecontrol.io/packages/rainbow_csv) and [Atom](https://atom.io/packages/rainbow-csv) editors. +* [Demo Google Colab notebook](https://colab.research.google.com/drive/1_cFPtnQUxILP0RE2_DBlqIfXaEzT-oZ6?usp=sharing) +* [RBQL in npm](https://www.npmjs.com/package/rbql): `$ npm install -g rbql` +* [RBQL in PyPI](https://pypi.org/project/rbql/): `$ pip install rbql` - the module also provides `%rbql` magic command for IPython/Jupyter. diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/.eslintrc.json b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/.eslintrc.json new file mode 100644 index 00000000..1abe7eef --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/.eslintrc.json @@ -0,0 +1,26 @@ +{ + "env": { + "browser": false, + "commonjs": true, + "es6": true, + "node": true + }, + "parserOptions": { + "ecmaFeatures": { + "jsx": true + }, + "sourceType": "module", + "ecmaVersion": 2018 + }, + "rules": { + "no-const-assign": "warn", + "no-this-before-super": "warn", + "no-undef": "warn", + "semi": [2, "always"], + "no-unreachable": "warn", + "no-unused-vars": "warn", + "constructor-super": "warn", + "no-trailing-spaces": "error", + "valid-typeof": "warn" + } +} diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/cli_parser.js b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/cli_parser.js new file mode 100644 index 00000000..92203d78 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/cli_parser.js @@ -0,0 +1,74 @@ +function die(error_msg) { + console.error('Error: ' + error_msg); + process.exit(1); +} + + +function normalize_cli_key(cli_key) { + return cli_key.replace(/^-*/, ''); +} + + +function show_help(scheme, description, epilog) { + if (description) + console.log(description); + console.log('Options:'); + for (var k in scheme) { + if (scheme[k].hasOwnProperty('hidden')) { + continue; + } + let metavar = ''; + if (scheme[k].hasOwnProperty('metavar')) + metavar = ' ' + scheme[k]['metavar']; + console.log(' ' + k + metavar); + if (scheme[k].hasOwnProperty('default')) { + console.log(' Default: "' + scheme[k]['default'] + '"'); + } + console.log(' ' + scheme[k]['help']); + console.log(); + } + if (epilog) + console.log(epilog); +} + + +function parse_cmd_args(cmd_args, scheme, description=null, epilog=null) { + var result = {}; + for (var arg_key in scheme) { + var arg_info = scheme[arg_key]; + if (arg_info.hasOwnProperty('default')) + result[normalize_cli_key(arg_key)] = arg_info['default']; + if (arg_info.hasOwnProperty('boolean')) + result[normalize_cli_key(arg_key)] = false; + } + cmd_args = cmd_args.slice(2); + var i = 0; + while(i < cmd_args.length) { + var arg_key = cmd_args[i]; + if (arg_key == '--help' || arg_key == '-h') { + show_help(scheme, description, epilog); + process.exit(0); + } + i += 1; + if (!scheme.hasOwnProperty(arg_key)) { + die(`unknown argument: ${arg_key}`); + } + var arg_info = scheme[arg_key]; + var normalized_key = normalize_cli_key(arg_key); + if (arg_info['boolean']) { + result[normalized_key] = true; + continue; + } + if (i >= cmd_args.length) { + die(`no CLI value for key: ${arg_key}`); + } + var arg_value = cmd_args[i]; + i += 1; + result[normalized_key] = arg_value; + } + return result; +} + + + +module.exports.parse_cmd_args = parse_cmd_args; diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/cli_rbql.js b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/cli_rbql.js new file mode 100644 index 00000000..3a7a4c26 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/cli_rbql.js @@ -0,0 +1,387 @@ +#!/usr/bin/env node + +const fs = require('fs'); +const readline = require('readline'); + +const rbql = require('./rbql.js'); +const rbql_csv = require('./rbql_csv.js'); +const csv_utils = require('./csv_utils.js'); +const cli_parser = require('./cli_parser.js'); + +let out_format_names = ['csv', 'tsv', 'monocolumn', 'input']; + +var error_format = 'hr'; +var interactive_mode = false; + + +// TODO implement colored output like in Python version +// TODO implement query history like in Python version. "readline" modules allows to do that, see "completer" parameter. + +// FIXME test readline on Win: disable interactive mode? + +// FIXME handle broken pipe error and add tests. See Python version. + + +class RbqlParsingError extends Error {} +class GenericError extends Error {} + + +function show_error_plain_text(error_type, error_msg) { + if (interactive_mode) { + console.log(`\x1b[31;1mError [${error_type}]:\x1b[0m ${error_msg}`); + } else { + console.error(`Error [${error_type}]: ${error_msg}`); + } +} + + +function report_error_json(error_type, error_msg) { + let report = new Object(); + report.error_type = error_type; + report.error = error_msg; + process.stderr.write(JSON.stringify(report)); +} + + +function show_exception(e) { + let [error_type, error_msg] = rbql.exception_to_error_info(e); + if (error_format == 'hr') { + show_error_plain_text(error_type, error_msg); + } else { + report_error_json(error_type, error_msg); + } +} + + +function show_warning(msg) { + if (interactive_mode) { + console.log('\x1b[33;1mWarning:\x1b[0m ' + msg); + } else { + console.error('Warning: ' + msg); + } +} + + +function normalize_delim(delim) { + if (delim == 'TAB') + return '\t'; + if (delim == '\\t') + return '\t'; + return delim; +} + + +function get_default(src, key, default_val) { + return src.hasOwnProperty(key) ? src[key] : default_val; +} + + +async function read_user_query(user_input_reader) { + let finish_promise = new Promise(function(resolve, reject) { + user_input_reader.question('Input SQL-like RBQL query and press Enter:\n> ', (query) => { + resolve(query); + }); + }); + let query = await finish_promise; + return query; +} + + +function get_default_policy(delim) { + if ([';', ','].indexOf(delim) != -1) { + return 'quoted'; + } else if (delim == ' ') { + return 'whitespace'; + } else { + return 'simple'; + } +} + + +function is_delimited_table(sampled_lines, delim, policy) { + if (sampled_lines.length < 10) + return false; + let num_fields = null; + for (var i = 0; i < sampled_lines.length; i++) { + let [fields, warning] = csv_utils.smart_split(sampled_lines[i], delim, policy, true); + if (warning) + return false; + if (num_fields === null) + num_fields = fields.length; + if (num_fields < 2 || num_fields != fields.length) + return false; + } + return true; +} + + +async function sample_lines(table_path) { + let finish_promise = new Promise(function(resolve, reject) { + let input_reader = readline.createInterface({ input: fs.createReadStream(table_path) }); + let sampled_lines = []; + input_reader.on('line', line => { + if (sampled_lines.length < 10) { + sampled_lines.push(line); + } else { + input_reader.close(); + } + }); + input_reader.on('close', () => { resolve(sampled_lines); }); + }); + let sampled_lines = await finish_promise; + return sampled_lines; +} + + +async function sample_records(table_path, encoding, delim, policy) { + let table_stream = fs.createReadStream(table_path); + let sampling_iterator = new rbql_csv.CSVRecordIterator(table_stream, null, encoding, delim, policy); + let sampled_records = await sampling_iterator.get_all_records(10); + let warnings = sampling_iterator.get_warnings(); + return [sampled_records, warnings]; +} + + +async function autodetect_delim_policy(table_path) { + let sampled_lines = await sample_lines(table_path); + let autodetection_dialects = [['\t', 'simple'], [',', 'quoted'], [';', 'quoted'], ['|', 'simple']]; + for (var i = 0; i < autodetection_dialects.length; i++) { + let [delim, policy] = autodetection_dialects[i]; + if (is_delimited_table(sampled_lines, delim, policy)) + return [delim, policy]; + } + if (table_path.endsWith('.csv')) + return [',', 'quoted']; + if (table_path.endsWith('.tsv')) + return ['\t', 'simple']; + return [null, null]; +} + + +function print_colorized(records, delim, show_column_names, with_headers) { + let reset_color_code = '\x1b[0m'; + let color_codes = ['\x1b[0m', '\x1b[31m', '\x1b[32m', '\x1b[33m', '\x1b[34m', '\x1b[35m', '\x1b[36m', '\x1b[31;1m', '\x1b[32;1m', '\x1b[33;1m']; + for (let r = 0; r < records.length; r++) { + let out_fields = []; + for (let c = 0; c < records[r].length; c++) { + let color_code = color_codes[c % color_codes.length]; + let field = records[r][c]; + let colored_field = (!show_column_names || (with_headers && r == 0)) ? color_code + field : `${color_code}a${c + 1}:${field}`; + out_fields.push(colored_field); + } + let out_line = out_fields.join(delim) + reset_color_code; + console.log(out_line); + } +} + + +async function handle_query_success(warnings, output_path, encoding, delim, policy) { + if (error_format == 'hr') { + if (warnings !== null) { + for (let i = 0; i < warnings.length; i++) { + show_warning(warnings[i]); + } + } + if (interactive_mode) { + let [records, _warnings] = await sample_records(output_path, encoding, delim, policy); + console.log('\nOutput table preview:'); + console.log('===================================='); + print_colorized(records, delim, false, false); + console.log('===================================='); + console.log('Success! Result table was saved to: ' + output_path); + } + } else { + if (warnings !== null && warnings.length) { + var warnings_report = JSON.stringify({'warnings': warnings}); + process.stderr.write(warnings_report); + } + } +} + + +async function run_with_js(args) { + var delim = normalize_delim(args['delim']); + var policy = args['policy'] ? args['policy'] : get_default_policy(delim); + var query = args['query']; + if (!query) + throw new RbqlParsingError('RBQL query is empty'); + var input_path = get_default(args, 'input', null); + var output_path = get_default(args, 'output', null); + var csv_encoding = args['encoding']; + var with_headers = args['with-headers']; + var comment_prefix = args['comment-prefix']; + var output_delim = get_default(args, 'out-delim', null); + var output_policy = get_default(args, 'out-policy', null); + let init_source_file = get_default(args, 'init-source-file', null); + let output_format = args['out-format']; + if (output_delim === null) { + [output_delim, output_policy] = output_format == 'input' ? [delim, policy] : rbql_csv.interpret_named_csv_format(output_format); + } + + let user_init_code = ''; + if (init_source_file !== null) + user_init_code = rbql_csv.read_user_init_code(init_source_file); + try { + let warnings = []; + // Do not use bulk_read mode here because: + // * Bulk read can't handle large file since node unable to read the whole file into a string, see https://github.com/mechatroner/rainbow_csv/issues/19 + // * In case of stdin read we would have to use the util.TextDecoder anyway + // * binary/latin-1 do not require the decoder anyway + // * This is CLI so no way we are in the Electron environment which can't use the TextDecoder + // * Streaming mode works a little faster (since we don't need to do the manual validation) + // TODO check if the current node installation doesn't have ICU enabled (which is typicaly provided by Node.js by default, see https://nodejs.org/api/intl.html) and report a user-friendly error with an option to use latin-1 encoding or switch the interpreter + await rbql_csv.query_csv(query, input_path, delim, policy, output_path, output_delim, output_policy, csv_encoding, warnings, with_headers, comment_prefix, user_init_code/*, {'bulk_read': true}*/); + await handle_query_success(warnings, output_path, csv_encoding, output_delim, output_policy); + return true; + } catch (e) { + if (!interactive_mode) + throw e; + show_exception(e); + return false; + } +} + + +function get_default_output_path(input_path, delim) { + let well_known_extensions = {',': '.csv', '\t': '.tsv'}; + if (well_known_extensions.hasOwnProperty(delim)) + return input_path + well_known_extensions[delim]; + return input_path + '.txt'; +} + + +async function show_preview(input_path, encoding, delim, policy, with_headers) { + let [records, warnings] = await sample_records(input_path, encoding, delim, policy); + console.log('Input table preview:'); + console.log('===================================='); + print_colorized(records, delim, true, with_headers); + console.log('====================================\n'); + for (let warning of warnings) { + show_warning(warning); + } +} + + +async function run_interactive_loop(args) { + let input_path = get_default(args, 'input', null); + if (!input_path) + throw new GenericError('Input file must be provided in interactive mode. You can use stdin input only in non-interactive mode'); + if (error_format != 'hr') + throw new GenericError('Only default "hr" error format is supported in interactive mode'); + + + let delim = get_default(args, 'delim', null); + let policy = null; + if (delim !== null) { + delim = normalize_delim(delim); + policy = args['policy'] ? args['policy'] : get_default_policy(delim); + } else { + [delim, policy] = await autodetect_delim_policy(input_path); + if (!delim) + throw new GenericError('Unable to autodetect table delimiter. Provide column separator explicitly with "--delim" option'); + } + await show_preview(input_path, args['encoding'], delim, policy, args['with-headers']); + args.delim = delim; + args.policy = policy; + if (!args.output) { + args.output = get_default_output_path(input_path, delim); + show_warning('Output path was not provided. Result set will be saved as: ' + args.output); + } + + let user_input_reader = readline.createInterface({ input: process.stdin, output: process.stdout }); + try { + while (true) { + let query = await read_user_query(user_input_reader); + args.query = query; + let success = await run_with_js(args); + if (success) + break; + } + } finally { + user_input_reader.close(); + } +} + + +let tool_description = `rbql-js + +Run RBQL queries against CSV files and data streams + +rbql-js supports two modes: non-interactive (with "--query" option) and interactive (without "--query" option) +Interactive mode shows source table preview which makes query editing much easier. Usage example: + $ rbql-js --input input.csv +Non-interactive mode supports source tables in stdin. Usage example: + $ rbql-js --query "select a1, a2 order by a1" --delim , < input.csv +`; + +let epilog = ` +Description of the available CSV split policies: + * "simple" - RBQL uses simple split() function and doesn't perform special handling of double quote characters + * "quoted" - Separator can be escaped inside double-quoted fields. Double quotes inside double-quoted fields must be doubled + * "quoted_rfc" - Same as "quoted", but also allows newlines inside double-quoted fields, see RFC-4180: https://tools.ietf.org/html/rfc4180 + * "whitespace" - Works only with whitespace separator, multiple consecutive whitespaces are treated as a single whitespace + * "monocolumn" - RBQL doesn't perform any split at all, each line is a single-element record, i.e. only "a1" and "NR" are available +`; + + +async function do_main(args) { + + if (args['version']) { + console.log(rbql.version); + process.exit(0); + } + + if (args.hasOwnProperty('policy') && args['policy'] === 'monocolumn') + args['delim'] = ''; + + if (args.hasOwnProperty('policy') && !args.hasOwnProperty('delim')) + throw new GenericError('Using "--policy" without "--delim" is not allowed'); + + if (args.encoding == 'latin-1') + args.encoding = 'binary'; + + error_format = args['error-format']; + + if (args.hasOwnProperty('query')) { + interactive_mode = false; + if (!args.hasOwnProperty('delim')) { + throw new GenericError('Separator must be provided with "--delim" option in non-interactive mode'); + } + await run_with_js(args); + } else { + interactive_mode = true; + if (error_format == 'json') { + throw new GenericError('json error format is not compatible with interactive mode'); + } + await run_interactive_loop(args); + } +} + + +function main() { + var scheme = { + '--input': {'help': 'Read csv table from FILE instead of stdin. Required in interactive mode', 'metavar': 'FILE'}, + '--query': {'help': 'Query string in rbql. Run in interactive mode if empty', 'metavar': 'QUERY'}, + '--output': {'help': 'Write output table to FILE instead of stdout', 'metavar': 'FILE'}, + '--delim': {'help': 'Delimiter character or multicharacter string, e.g. "," or "###". Can be autodetected in interactive mode', 'metavar': 'DELIM'}, + '--policy': {'help': 'Split policy, see the explanation below. Supported values: "simple", "quoted", "quoted_rfc", "whitespace", "monocolumn". Can be autodetected in interactive mode', 'metavar': 'POLICY'}, + '--with-headers': {'boolean': true, 'help': 'Indicates that input (and join) table has header'}, + '--comment-prefix': {'help': 'Ignore lines in input and join tables that start with the comment PREFIX, e.g. "#" or ">>"', 'metavar': 'PREFIX'}, + '--encoding': {'default': 'utf-8', 'help': 'Manually set csv encoding', 'metavar': 'ENCODING'}, + '--out-format': {'default': 'input', 'help': 'Output format. Supported values: ' + out_format_names.map(v => `"${v}"`).join(', '), 'metavar': 'FORMAT'}, + '--out-delim': {'help': 'Output delim. Use with "out-policy". Overrides out-format', 'metavar': 'DELIM'}, + '--out-policy': {'help': 'Output policy. Use with "out-delim". Overrides out-format', 'metavar': 'POLICY'}, + '--error-format': {'default': 'hr', 'help': 'Errors and warnings format. [hr|json]', 'hidden': true}, + '--version': {'boolean': true, 'help': 'Print RBQL version and exit'}, + '--init-source-file': {'help': 'Path to init source file to use instead of ~/.rbql_init_source.js', 'hidden': true} + }; + let args = cli_parser.parse_cmd_args(process.argv, scheme, tool_description, epilog); + do_main(args).then(() => {}).catch(error_info => { show_exception(error_info); process.exit(1); }); +} + + +if (require.main === module) { + main(); +} + + diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/csv_utils.js b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/csv_utils.js new file mode 100644 index 00000000..e64c21d7 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/csv_utils.js @@ -0,0 +1,151 @@ +let field_regular_expression = '"((?:[^"]*"")*[^"]*)"'; +let field_rgx = new RegExp('^' + field_regular_expression); +let field_rgx_external_whitespaces = new RegExp('^ *' + field_regular_expression + ' *'); + + +// TODO consider making this file (and rbql.js) both node and browser compatible: https://caolan.org/posts/writing_for_node_and_the_browser.html + + +function split_lines(text) { + return text.split(/\r\n|\r|\n/); +} + + +function extract_next_field(src, dlm, preserve_quotes_and_whitespaces, allow_external_whitespaces, cidx, result) { + var warning = false; + let src_cur = src.substring(cidx); + let rgx = allow_external_whitespaces ? field_rgx_external_whitespaces : field_rgx; + let match_obj = rgx.exec(src_cur); + if (match_obj !== null) { + let match_end = match_obj[0].length; + if (cidx + match_end == src.length || src[cidx + match_end] == dlm) { + if (preserve_quotes_and_whitespaces) { + result.push(match_obj[0]); + } else { + result.push(match_obj[1].replace(/""/g, '"')); + } + return [cidx + match_end + 1, false]; + } + warning = true; + } + var uidx = src.indexOf(dlm, cidx); + if (uidx == -1) + uidx = src.length; + var field = src.substring(cidx, uidx); + warning = warning || field.indexOf('"') != -1; + result.push(field); + return [uidx + 1, warning]; +} + + +function split_quoted_str(src, dlm, preserve_quotes_and_whitespaces=false) { + // This function is newline-agnostic i.e. it can also split records with multiline fields. + if (src.indexOf('"') == -1) // Optimization for most common case + return [src.split(dlm), false]; + var result = []; + var cidx = 0; + var warning = false; + let allow_external_whitespaces = dlm != ' '; + while (cidx < src.length) { + var extraction_report = extract_next_field(src, dlm, preserve_quotes_and_whitespaces, allow_external_whitespaces, cidx, result); + cidx = extraction_report[0]; + warning = warning || extraction_report[1]; + } + if (src.charAt(src.length - 1) == dlm) + result.push(''); + return [result, warning]; +} + + +function quote_field(src, delim) { + if (src.indexOf(delim) != -1 || src.indexOf('"') != -1) { + var escaped = src.replace(/"/g, '""'); + return `"${escaped}"`; + } + return src; +} + + +function rfc_quote_field(src, delim) { + if (src.indexOf(delim) != -1 || src.indexOf('"') != -1 || src.indexOf('\n') != -1 || src.indexOf('\r') != -1) { + var escaped = src.replace(/"/g, '""'); + return `"${escaped}"`; + } + return src; +} + + +function unquote_field(field) { + let rgx = new RegExp('^' + ' *' + field_regular_expression + ' *$'); + let match_obj = rgx.exec(field); + if (match_obj !== null) { + return match_obj[1].replace(/""/g, '"'); + } + return field; +} + + +function unquote_fields(fields) { + return fields.map(unquote_field); +} + + +function split_whitespace_separated_str(src, preserve_whitespaces=false) { + var rgxp = preserve_whitespaces ? new RegExp(' *[^ ]+ *', 'g') : new RegExp('[^ ]+', 'g'); + let result = []; + let match_obj = null; + while((match_obj = rgxp.exec(src)) !== null) { + result.push(match_obj[0]); + } + if (preserve_whitespaces) { + for (let i = 0; i < result.length - 1; i++) { + result[i] = result[i].slice(0, -1); + } + } + return result; +} + + +function smart_split(src, dlm, policy, preserve_quotes_and_whitespaces) { + if (policy === 'simple') + return [src.split(dlm), false]; + if (policy === 'whitespace') + return [split_whitespace_separated_str(src, preserve_quotes_and_whitespaces), false]; + if (policy === 'monocolumn') + return [[src], false]; + return split_quoted_str(src, dlm, preserve_quotes_and_whitespaces); +} + + +function accumulate_rfc_line_into_record(external_rfc_line_buffer, current_line, comment_prefix=null) { + // Return null if the current line yields no record. + // Return a record string if the current line yields the record and cleans the external line buffer. + if (comment_prefix !== null && external_rfc_line_buffer.length == 0 && current_line.startsWith(comment_prefix)) + return null; + let match_list = current_line.match(/"/g); + let has_unbalanced_double_quote = match_list && match_list.length % 2 == 1; + if (external_rfc_line_buffer.length == 0 && !has_unbalanced_double_quote) { + return current_line; + } else if (external_rfc_line_buffer.length == 0 && has_unbalanced_double_quote) { + external_rfc_line_buffer.push(current_line); + } else if (!has_unbalanced_double_quote) { + external_rfc_line_buffer.push(current_line); + } else { + external_rfc_line_buffer.push(current_line); + let multiline_row = external_rfc_line_buffer.join('\n'); + external_rfc_line_buffer.splice(0, external_rfc_line_buffer.length); // Cleanup the external buffer. + return multiline_row; + } + return null; +} + + +module.exports.split_quoted_str = split_quoted_str; +module.exports.split_whitespace_separated_str = split_whitespace_separated_str; +module.exports.smart_split = smart_split; +module.exports.quote_field = quote_field; +module.exports.rfc_quote_field = rfc_quote_field; +module.exports.unquote_field = unquote_field; +module.exports.unquote_fields = unquote_fields; +module.exports.split_lines = split_lines; +module.exports.accumulate_rfc_line_into_record = accumulate_rfc_line_into_record; diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/rbql.js b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/rbql.js new file mode 100644 index 00000000..18726efd --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql-js/rbql.js @@ -0,0 +1,1951 @@ +(function(exports){ +// The magic line above is to make the module both browser and Node compatible, see https://stackoverflow.com/questions/3225251/how-can-i-share-code-between-node-js-and-the-browser + +// This module works with records only. It is CSV-agnostic. +// Do not add CSV-related logic or variables/functions/objects like "delim", "separator" etc + + +class RbqlParsingError extends Error {} +class RbqlRuntimeError extends Error {} +class AssertionError extends Error {} +class RbqlIOHandlingError extends Error {} + + +class InternalBadFieldError extends Error { + constructor(bad_idx, ...params) { + super(...params); + this.bad_idx = bad_idx; + } +} + + +function assert(condition, message=null) { + if (!condition) { + if (!message) { + message = 'Assertion error'; + } + throw new AssertionError(message); + } +} + + +function replace_all(src, search, replacement) { + return src.split(search).join(replacement); +} + + +class RBQLContext { + constructor(query_text, input_iterator, output_writer, user_init_code) { + this.query_text = query_text; + this.input_iterator = input_iterator; + this.writer = output_writer; + this.user_init_code = user_init_code; + + this.unnest_list = null; + this.top_count = null; + + this.like_regex_cache = new Map(); + + this.sort_key_expression = null; + + this.aggregation_stage = 0; + this.aggregation_key_expression = null; + this.functional_aggregators = []; + + this.join_map_impl = null; + this.join_map = null; + this.lhs_join_var_expression = null; + + this.where_expression = null; + + this.select_expression = null; + + this.update_expressions = null; + + this.variables_init_code = null; + } +} + +var query_context = null; // Needs to be global for MIN(), MAX(), etc functions. TODO find a way to make it local. + + +const wrong_aggregation_usage_error = 'Usage of RBQL aggregation functions inside JavaScript expressions is not allowed, see the docs'; +const RBQL_VERSION = '0.25.0'; + + +function check_if_brackets_match(opening_bracket, closing_bracket) { + return (opening_bracket == '[' && closing_bracket == ']') || (opening_bracket == '(' && closing_bracket == ')') || (opening_bracket == '{' && closing_bracket == '}'); +} + + +function parse_root_bracket_level_text_spans(select_expression) { + let text_spans = []; // parts of text separated by commas at the root parenthesis level + let last_pos = 0; + let bracket_stack = []; + for (let i = 0; i < select_expression.length; i++) { + let cur_char = select_expression[i]; + if (cur_char == ',' && bracket_stack.length == 0) { + text_spans.push(select_expression.substring(last_pos, i)); + last_pos = i + 1; + } else if (['[', '{', '('].indexOf(cur_char) != -1) { + bracket_stack.push(cur_char); + } else if ([']', '}', ')'].indexOf(cur_char) != -1) { + if (bracket_stack.length && check_if_brackets_match(bracket_stack[bracket_stack.length - 1], cur_char)) { + bracket_stack.pop(); + } else { + throw new RbqlParsingError(`Unable to parse column headers in SELECT expression: No matching opening bracket for closing "${cur_char}"`); + } + } + } + if (bracket_stack.length) { + throw new RbqlParsingError(`Unable to parse column headers in SELECT expression: No matching closing bracket for opening "${bracket_stack[0]}"`); + } + text_spans.push(select_expression.substring(last_pos, select_expression.length)); + text_spans = text_spans.map(span => span.trim()); + return text_spans; +} + + +function unquote_string(quoted_str) { + // It's possible to use eval here to unqoute the quoted_column_name, but it would be a little barbaric, let's do it manually instead + if (!quoted_str || quoted_str.length < 2) + return null; + if (quoted_str[0] == "'" && quoted_str[quoted_str.length - 1] == "'") { + return quoted_str.substring(1, quoted_str.length - 1).replace(/\\'/g, "'").replace(/\\\\/g, "\\"); + } else if (quoted_str[0] == '"' && quoted_str[quoted_str.length - 1] == '"') { + return quoted_str.substring(1, quoted_str.length - 1).replace(/\\"/g, '"').replace(/\\\\/g, "\\"); + } else { + return null; + } +} + + +function column_info_from_text_span(text_span, string_literals) { + // This function is a rough equivalent of "column_info_from_node()" function in python version of RBQL + text_span = text_span.trim(); + let rbql_star_marker = '__RBQL_INTERNAL_STAR'; + let simple_var_match = /^[_a-zA-Z][_a-zA-Z0-9]*$/.exec(text_span); + let attribute_match = /^([ab])\.([_a-zA-Z][_a-zA-Z0-9]*)$/.exec(text_span); + let subscript_int_match = /^([ab])\[([0-9]+)\]$/.exec(text_span); + let subscript_str_match = /^([ab])\[___RBQL_STRING_LITERAL([0-9]+)___\]$/.exec(text_span); + if (simple_var_match !== null) { + if (text_span == rbql_star_marker) + return {table_name: null, column_index: null, column_name: null, is_star: true}; + if (text_span.startsWith('___RBQL_STRING_LITERAL')) + return null; + let match = /^([ab])([0-9]+)$/.exec(text_span); + if (match !== null) { + return {table_name: match[1], column_index: parseInt(match[2]) - 1, column_name: null, is_star: false}; + } + // Some examples for this branch: NR, NF + return {table_name: null, column_index: null, column_name: text_span, is_star: false}; + } else if (attribute_match !== null) { + let table_name = attribute_match[1]; + let column_name = attribute_match[2]; + if (column_name == rbql_star_marker) { + return {table_name: table_name, column_index: null, column_name: null, is_star: true}; + } + return {table_name: null, column_index: null, column_name: column_name, is_star: false}; + } else if (subscript_int_match != null) { + let table_name = subscript_int_match[1]; + let column_index = parseInt(subscript_int_match[2]) - 1; + return {table_name: table_name, column_index: column_index, column_name: null, is_star: false}; + } else if (subscript_str_match != null) { + let table_name = subscript_str_match[1]; + let replaced_string_literal_id = subscript_str_match[2]; + if (replaced_string_literal_id < string_literals.length) { + let quoted_column_name = string_literals[replaced_string_literal_id]; + let unquoted_column_name = unquote_string(quoted_column_name); + if (unquoted_column_name !== null && unquoted_column_name !== undefined) { + return {table_name: null, column_index: null, column_name: unquoted_column_name, is_star: false}; + } + } + } + return null; +} + + +function adhoc_parse_select_expression_to_column_infos(select_expression, string_literals) { + // It is acceptable for the algorithm to provide null column name when it could be theorethically possible to deduce the name. + // I.e. this algorithm guarantees precision but doesn't guarantee completeness in all theorethically possible queries. + // Although the algorithm should be complete in all practical scenarios, i.e. it should be hard to come up with the query that doesn't produce complete set of column names. + // The null column name just means that the output column will be named as col{i}, so the failure to detect the proper column name can be tolerated. + // Specifically this function guarantees the following: + // 1. The number of column_infos is correct and will match the number of fields in each record in the output - otherwise the exception should be thrown + // 2. If column_info at pos j is not null, it is guaranteed to correctly represent that column name in the output + let text_spans = parse_root_bracket_level_text_spans(select_expression); + let column_infos = text_spans.map(ts => column_info_from_text_span(ts, string_literals)); + return column_infos; +} + + +function stable_compare(a, b) { + for (var i = 0; i < a.length; i++) { + if (a[i] !== b[i]) + return a[i] < b[i] ? -1 : 1; + } +} + + +function safe_get(record, idx) { + return idx < record.length ? record[idx] : null; +} + + +function safe_join_get(record, idx) { + if (idx < record.length) { + return record[idx]; + } + throw new InternalBadFieldError(idx); +} + + +function safe_set(record, idx, value) { + if (idx < record.length) { + record[idx] = value; + } else { + throw new InternalBadFieldError(idx); + } +} + + +function regexp_escape(text) { + // From here: https://stackoverflow.com/a/6969486/2898283 + return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched text +} + + +function like_to_regex(pattern) { + let p = 0; + let i = 0; + let converted = ''; + while (i < pattern.length) { + if (pattern.charAt(i) == '_' || pattern.charAt(i) == '%') { + converted += regexp_escape(pattern.substring(p, i)); + p = i + 1; + if (pattern.charAt(i) == '_') { + converted += '.'; + } else { + converted += '.*'; + } + } + i += 1; + } + converted += regexp_escape(pattern.substring(p, i)); + return '^' + converted + '$'; +} + + +function like(text, pattern) { + let matcher = query_context.like_regex_cache.get(pattern); + if (matcher === undefined) { + matcher = new RegExp(like_to_regex(pattern)); + query_context.like_regex_cache.set(pattern, matcher); + } + return matcher.test(text); +} +const LIKE = like; + + +class RBQLAggregationToken { + constructor(marker_id, value) { + this.marker_id = marker_id; + this.value = value; + } + + toString() { + throw new RbqlParsingError(wrong_aggregation_usage_error); + } +} + + +class UnnestMarker {} + + +function UNNEST(vals) { + if (query_context.unnest_list !== null) { + // Technically we can support multiple UNNEST's but the implementation/algorithm is more complex and just doesn't worth it + throw new RbqlParsingError('Only one UNNEST is allowed per query'); + } + query_context.unnest_list = vals; + return new UnnestMarker(); +} +const unnest = UNNEST; +const Unnest = UNNEST; +const UNFOLD = UNNEST; // "UNFOLD" is deprecated, just for backward compatibility + + +function parse_number(val) { + // We can do a more pedantic number test like `/^ *-{0,1}[0-9]+\.{0,1}[0-9]* *$/.test(val)`, but user will probably use just Number(val) or parseInt/parseFloat + let result = Number(val); + if (isNaN(result)) { + throw new RbqlRuntimeError(`Unable to convert value "${val}" to a number. MIN, MAX, SUM, AVG, MEDIAN and VARIANCE aggregate functions convert their string arguments to numeric values`); + } + return result; +} + + +class MinAggregator { + constructor() { + this.stats = new Map(); + } + + increment(key, val) { + val = parse_number(val); + var cur_aggr = this.stats.get(key); + if (cur_aggr === undefined) { + this.stats.set(key, val); + } else { + this.stats.set(key, Math.min(cur_aggr, val)); + } + } + + get_final(key) { + return this.stats.get(key); + } +} + + + +class MaxAggregator { + constructor() { + this.stats = new Map(); + } + + increment(key, val) { + val = parse_number(val); + var cur_aggr = this.stats.get(key); + if (cur_aggr === undefined) { + this.stats.set(key, val); + } else { + this.stats.set(key, Math.max(cur_aggr, val)); + } + } + + get_final(key) { + return this.stats.get(key); + } +} + + +class SumAggregator { + constructor() { + this.stats = new Map(); + } + + increment(key, val) { + val = parse_number(val); + var cur_aggr = this.stats.get(key); + if (cur_aggr === undefined) { + this.stats.set(key, val); + } else { + this.stats.set(key, cur_aggr + val); + } + } + + get_final(key) { + return this.stats.get(key); + } +} + + +class AvgAggregator { + constructor() { + this.stats = new Map(); + } + + increment(key, val) { + val = parse_number(val); + var cur_aggr = this.stats.get(key); + if (cur_aggr === undefined) { + this.stats.set(key, [val, 1]); + } else { + var cur_sum = cur_aggr[0]; + var cur_cnt = cur_aggr[1]; + this.stats.set(key, [cur_sum + val, cur_cnt + 1]); + } + } + + get_final(key) { + var cur_aggr = this.stats.get(key); + var cur_sum = cur_aggr[0]; + var cur_cnt = cur_aggr[1]; + var avg = cur_sum / cur_cnt; + return avg; + } +} + + +class VarianceAggregator { + constructor() { + this.stats = new Map(); + } + + increment(key, val) { + val = parse_number(val); + var cur_aggr = this.stats.get(key); + if (cur_aggr === undefined) { + this.stats.set(key, [val, val * val, 1]); + } else { + var cur_sum = cur_aggr[0]; + var cur_sum_sq = cur_aggr[1]; + var cur_cnt = cur_aggr[2]; + this.stats.set(key, [cur_sum + val, cur_sum_sq + val * val, cur_cnt + 1]); + } + } + + get_final(key) { + var cur_aggr = this.stats.get(key); + var cur_sum = cur_aggr[0]; + var cur_sum_sq = cur_aggr[1]; + var cur_cnt = cur_aggr[2]; + var avg_val = cur_sum / cur_cnt; + var variance = cur_sum_sq / cur_cnt - avg_val * avg_val; + return variance; + } +} + + +class MedianAggregator { + constructor() { + this.stats = new Map(); + } + + increment(key, val) { + val = parse_number(val); + var cur_aggr = this.stats.get(key); + if (cur_aggr === undefined) { + this.stats.set(key, [val]); + } else { + cur_aggr.push(val); + } + } + + get_final(key) { + var cur_aggr = this.stats.get(key); + cur_aggr.sort(function(a, b) { return a - b; }); + var m = Math.floor(cur_aggr.length / 2); + if (cur_aggr.length % 2) { + return cur_aggr[m]; + } else { + return (cur_aggr[m - 1] + cur_aggr[m]) / 2.0; + } + } +} + + +class CountAggregator { + constructor() { + this.stats = new Map(); + } + + increment(key, val) { + var cur_aggr = this.stats.get(key); + if (cur_aggr === undefined) { + this.stats.set(key, 1); + } else { + this.stats.set(key, cur_aggr + 1); + } + } + + get_final(key) { + return this.stats.get(key); + } +} + + +class ArrayAggAggregator { + constructor(post_proc=null) { + this.post_proc = post_proc; + this.stats = new Map(); + } + + increment(key, val) { + let cur_aggr = this.stats.get(key); + if (cur_aggr === undefined) { + this.stats.set(key, [val]); + } else { + cur_aggr.push(val); + } + } + + get_final(key) { + let cur_aggr = this.stats.get(key); + if (this.post_proc === null) + return cur_aggr; + return this.post_proc(cur_aggr); + } +} + + +class ConstGroupVerifier { + constructor(output_index) { + this.output_index = output_index; + this.const_values = new Map(); + } + + increment(key, value) { + var old_value = this.const_values.get(key); + if (old_value === undefined) { + this.const_values.set(key, value); + } else if (old_value != value) { + throw new RbqlRuntimeError(`Invalid aggregate expression: non-constant values in output column ${this.output_index + 1}. E.g. "${old_value}" and "${value}"`); + } + } + + get_final(key) { + return this.const_values.get(key); + } +} + + +function init_aggregator(generator_name, val, post_proc=null) { + query_context.aggregation_stage = 1; + var res = new RBQLAggregationToken(query_context.functional_aggregators.length, val); + if (post_proc === null) { + query_context.functional_aggregators.push(new generator_name()); + } else { + query_context.functional_aggregators.push(new generator_name(post_proc)); + } + return res; +} + + +function MIN(val) { + return query_context.aggregation_stage < 2 ? init_aggregator(MinAggregator, val) : val; +} +const min = MIN; +const Min = MIN; + + +function MAX(val) { + return query_context.aggregation_stage < 2 ? init_aggregator(MaxAggregator, val) : val; +} +const max = MAX; +const Max = MAX; + +function COUNT(val) { + return query_context.aggregation_stage < 2 ? init_aggregator(CountAggregator, 1) : 1; +} +const count = COUNT; +const Count = COUNT; + +function SUM(val) { + return query_context.aggregation_stage < 2 ? init_aggregator(SumAggregator, val) : val; +} +const sum = SUM; +const Sum = SUM; + +function AVG(val) { + return query_context.aggregation_stage < 2 ? init_aggregator(AvgAggregator, val) : val; +} +const avg = AVG; +const Avg = AVG; + +function VARIANCE(val) { + return query_context.aggregation_stage < 2 ? init_aggregator(VarianceAggregator, val) : val; +} +const variance = VARIANCE; +const Variance = VARIANCE; + +function MEDIAN(val) { + return query_context.aggregation_stage < 2 ? init_aggregator(MedianAggregator, val) : val; +} +const median = MEDIAN; +const Median = MEDIAN; + +function ARRAY_AGG(val, post_proc=null) { + return query_context.aggregation_stage < 2 ? init_aggregator(ArrayAggAggregator, val, post_proc) : val; +} +const array_agg = ARRAY_AGG; +const FOLD = ARRAY_AGG; // "FOLD" is deprecated, just for backward compatibility + + +function add_to_set(dst_set, value) { + var len_before = dst_set.size; + dst_set.add(value); + return len_before != dst_set.size; +} + + +class TopWriter { + constructor(subwriter, top_count) { + this.subwriter = subwriter; + this.NW = 0; + this.top_count = top_count; + } + + async write(record) { + if (this.top_count !== null && this.NW >= this.top_count) + return false; + await this.subwriter.write(record); + this.NW += 1; + return true; + } + + async finish() { + await this.subwriter.finish(); + } +} + + +class UniqWriter { + constructor(subwriter) { + this.subwriter = subwriter; + this.seen = new Set(); + } + + async write(record) { + if (!add_to_set(this.seen, JSON.stringify(record))) + return true; + if (!await this.subwriter.write(record)) + return false; + return true; + } + + async finish() { + await this.subwriter.finish(); + } +} + + +class UniqCountWriter { + constructor(subwriter) { + this.subwriter = subwriter; + this.records = new Map(); + } + + async write(record) { + var key = JSON.stringify(record); + var old_val = this.records.get(key); + if (old_val) { + old_val[0] += 1; + } else { + this.records.set(key, [1, record]); + } + return true; + } + + async finish() { + for (var [key, value] of this.records) { + let [count, record] = value; + record.unshift(count); + if (!await this.subwriter.write(record)) + break; + } + await this.subwriter.finish(); + } +} + + +class SortedWriter { + constructor(subwriter, reverse_sort) { + this.subwriter = subwriter; + this.reverse_sort = reverse_sort; + this.unsorted_entries = []; + } + + async write(stable_entry) { + this.unsorted_entries.push(stable_entry); + return true; + } + + async finish() { + var unsorted_entries = this.unsorted_entries; + unsorted_entries.sort(stable_compare); + if (this.reverse_sort) + unsorted_entries.reverse(); + for (var i = 0; i < unsorted_entries.length; i++) { + var entry = unsorted_entries[i]; + if (!await this.subwriter.write(entry[entry.length - 1])) + break; + } + await this.subwriter.finish(); + } +} + + +class AggregateWriter { + constructor(subwriter) { + this.subwriter = subwriter; + this.aggregators = []; + this.aggregation_keys = new Set(); + } + + async finish() { + var all_keys = Array.from(this.aggregation_keys); + all_keys.sort(); + for (var i = 0; i < all_keys.length; i++) { + var key = all_keys[i]; + var out_fields = []; + for (var ag of this.aggregators) { + out_fields.push(ag.get_final(key)); + } + if (!await this.subwriter.write(out_fields)) + break; + } + await this.subwriter.finish(); + } +} + + +class InnerJoiner { + constructor(join_map) { + this.join_map = join_map; + } + + get_rhs(lhs_key) { + return this.join_map.get_join_records(lhs_key); + } +} + + +class LeftJoiner { + constructor(join_map) { + this.join_map = join_map; + this.null_record = [[null, join_map.max_record_len, Array(join_map.max_record_len).fill(null)]]; + } + + get_rhs(lhs_key) { + let result = this.join_map.get_join_records(lhs_key); + if (result.length == 0) { + return this.null_record; + } + return result; + } +} + + +class StrictLeftJoiner { + constructor(join_map) { + this.join_map = join_map; + } + + get_rhs(lhs_key) { + let result = this.join_map.get_join_records(lhs_key); + if (result.length != 1) { + throw new RbqlRuntimeError('In "STRICT LEFT JOIN" each key in A must have exactly one match in B. Bad A key: "' + lhs_key + '"'); + } + return result; + } +} + + +function select_except(src, except_fields) { + let result = []; + for (let i = 0; i < src.length; i++) { + if (except_fields.indexOf(i) == -1) + result.push(src[i]); + } + return result; +} + + +async function select_simple(sort_key, NR, out_fields) { + if (query_context.sort_key_expression !== null) { + var sort_entry = sort_key.concat([NR, out_fields]); + if (!await query_context.writer.write(sort_entry)) + return false; + } else { + if (!await query_context.writer.write(out_fields)) + return false; + } + return true; +} + + +function select_aggregated(key, transparent_values) { + if (key !== null) { + key = JSON.stringify(key); + } + if (query_context.aggregation_stage === 1) { + if (!(query_context.writer instanceof TopWriter)) { + throw new RbqlParsingError('"ORDER BY", "UPDATE" and "DISTINCT" keywords are not allowed in aggregate queries'); + } + query_context.writer = new AggregateWriter(query_context.writer); + let num_aggregators_found = 0; + for (var i = 0; i < transparent_values.length; i++) { + var trans_value = transparent_values[i]; + if (trans_value instanceof RBQLAggregationToken) { + query_context.writer.aggregators.push(query_context.functional_aggregators[trans_value.marker_id]); + query_context.writer.aggregators[query_context.writer.aggregators.length - 1].increment(key, trans_value.value); + num_aggregators_found += 1; + } else { + query_context.writer.aggregators.push(new ConstGroupVerifier(query_context.writer.aggregators.length)); + query_context.writer.aggregators[query_context.writer.aggregators.length - 1].increment(key, trans_value); + } + } + if (num_aggregators_found != query_context.functional_aggregators.length) { + throw new RbqlParsingError(wrong_aggregation_usage_error); + } + query_context.aggregation_stage = 2; + } else { + for (var i = 0; i < transparent_values.length; i++) { + var trans_value = transparent_values[i]; + query_context.writer.aggregators[i].increment(key, trans_value); + } + } + query_context.writer.aggregation_keys.add(key); +} + + +async function select_unnested(sort_key, NR, folded_fields) { + let out_fields = folded_fields.slice(); + let unnest_pos = folded_fields.findIndex(val => val instanceof UnnestMarker); + for (var i = 0; i < query_context.unnest_list.length; i++) { + out_fields[unnest_pos] = query_context.unnest_list[i]; + if (!await select_simple(sort_key, NR, out_fields.slice())) + return false; + } + return true; +} + + +const PROCESS_SELECT_COMMON = ` +__RBQLMP__variables_init_code +if (__RBQLMP__where_expression) { + let out_fields = __RBQLMP__select_expression; + if (query_context.aggregation_stage > 0) { + let key = __RBQLMP__aggregation_key_expression; + select_aggregated(key, out_fields); + } else { + let sort_key = [__RBQLMP__sort_key_expression]; + if (query_context.unnest_list !== null) { + if (!await select_unnested(sort_key, NR, out_fields)) + stop_flag = true; + } else { + if (!await select_simple(sort_key, NR, out_fields)) + stop_flag = true; + } + } +} +`; + + +const PROCESS_SELECT_SIMPLE = ` +let star_fields = record_a; +__CODE__ +`; + + +const PROCESS_SELECT_JOIN = ` +let join_matches = query_context.join_map.get_rhs(__RBQLMP__lhs_join_var_expression); +for (let join_match of join_matches) { + let [bNR, bNF, record_b] = join_match; + let star_fields = record_a.concat(record_b); + __CODE__ + if (stop_flag) + break; +} +`; + + +const PROCESS_UPDATE_JOIN = ` +let join_matches = query_context.join_map.get_rhs(__RBQLMP__lhs_join_var_expression); +if (join_matches.length > 1) + throw new RbqlRuntimeError('More than one record in UPDATE query matched a key from the input table in the join table'); +let record_b = null; +let bNR = null; +let bNF = null; +if (join_matches.length == 1) + [bNR, bNF, record_b] = join_matches[0]; +let up_fields = record_a; +__RBQLMP__variables_init_code +if (join_matches.length == 1 && (__RBQLMP__where_expression)) { + NU += 1; + __RBQLMP__update_expressions +} +if (!await query_context.writer.write(up_fields)) + stop_flag = true; +`; + + +const PROCESS_UPDATE_SIMPLE = ` +let up_fields = record_a; +__RBQLMP__variables_init_code +if (__RBQLMP__where_expression) { + NU += 1; + __RBQLMP__update_expressions +} +if (!await query_context.writer.write(up_fields)) + stop_flag = true; +`; + + +const MAIN_LOOP_BODY = ` +__USER_INIT_CODE__ + +let NU = 0; +let NR = 0; + +let stop_flag = false; +while (!stop_flag) { + let record_a = await query_context.input_iterator.get_record(); + if (record_a === null) + break; + NR += 1; + let NF = record_a.length; + query_context.unnest_list = null; // TODO optimize, don't need to set this every iteration + try { + __CODE__ + } catch (e) { + if (e.constructor.name === 'InternalBadFieldError') { + throw new RbqlRuntimeError(\`No "a\${e.bad_idx + 1}" field at record \${NR}\`); + } else if (e.constructor.name === 'RbqlParsingError') { + throw(e); + } else { + throw new RbqlRuntimeError(\`At record \${NR}, Details: \${e.message}\`); + } + } +} +`; + + +function embed_expression(parent_code, child_placeholder, child_expression) { + return replace_all(parent_code, child_placeholder, child_expression); +} + + +function embed_code(parent_code, child_placeholder, child_code) { + let parent_lines = parent_code.split('\n'); + let child_lines = child_code.split('\n'); + for (let i = 0; i < parent_lines.length; i++) { + let pos = parent_lines[i].indexOf(child_placeholder); + if (pos == -1) + continue; + assert(pos % 4 == 0); + let placeholder_indentation = parent_lines[i].substring(0, pos); + child_lines = child_lines.map(l => placeholder_indentation + l); + let result_lines = parent_lines.slice(0, i).concat(child_lines).concat(parent_lines.slice(i + 1)); + return result_lines.join('\n') + '\n'; + } + assert(false); +} + + +function generate_main_loop_code(query_context) { + let is_select_query = query_context.select_expression !== null; + let is_join_query = query_context.join_map !== null; + let where_expression = query_context.where_expression === null ? 'true' : query_context.where_expression; + let aggregation_key_expression = query_context.aggregation_key_expression === null ? 'null' : query_context.aggregation_key_expression; + let sort_key_expression = query_context.sort_key_expression === null ? 'null' : query_context.sort_key_expression; + let js_code = embed_code(MAIN_LOOP_BODY, '__USER_INIT_CODE__', query_context.user_init_code); + if (is_select_query) { + if (is_join_query) { + js_code = embed_code(embed_code(js_code, '__CODE__', PROCESS_SELECT_JOIN), '__CODE__', PROCESS_SELECT_COMMON); + js_code = embed_expression(js_code, '__RBQLMP__lhs_join_var_expression', query_context.lhs_join_var_expression); + } else { + js_code = embed_code(embed_code(js_code, '__CODE__', PROCESS_SELECT_SIMPLE), '__CODE__', PROCESS_SELECT_COMMON); + } + js_code = embed_code(js_code, '__RBQLMP__variables_init_code', query_context.variables_init_code); + js_code = embed_expression(js_code, '__RBQLMP__select_expression', query_context.select_expression); + js_code = embed_expression(js_code, '__RBQLMP__where_expression', where_expression); + js_code = embed_expression(js_code, '__RBQLMP__aggregation_key_expression', aggregation_key_expression); + js_code = embed_expression(js_code, '__RBQLMP__sort_key_expression', sort_key_expression); + } else { + if (is_join_query) { + js_code = embed_code(js_code, '__CODE__', PROCESS_UPDATE_JOIN); + js_code = embed_expression(js_code, '__RBQLMP__lhs_join_var_expression', query_context.lhs_join_var_expression); + } else { + js_code = embed_code(js_code, '__CODE__', PROCESS_UPDATE_SIMPLE); + } + js_code = embed_code(js_code, '__RBQLMP__variables_init_code', query_context.variables_init_code); + js_code = embed_code(js_code, '__RBQLMP__update_expressions', query_context.update_expressions); + js_code = embed_expression(js_code, '__RBQLMP__where_expression', where_expression); + } + return "(async () => {" + js_code + "})()"; +} + + +async function compile_and_run(query_context) { + let main_loop_body = generate_main_loop_code(query_context); + try { + let main_loop_promise = eval(main_loop_body); + await main_loop_promise; + } catch (e) { + if (e instanceof SyntaxError) { + // SyntaxError's from eval() function do not contain detailed explanation of what has caused the syntax error, so to guess what was wrong we can only use the original query + // v8 issue to fix eval: https://bugs.chromium.org/p/v8/issues/detail?id=2589 + let lower_case_query = query_context.query_text.toLowerCase(); + if (lower_case_query.indexOf(' having ') != -1) + throw new SyntaxError(e.message + "\nRBQL doesn't support \"HAVING\" keyword"); + if (lower_case_query.indexOf(' like ') != -1) + throw new SyntaxError(e.message + "\nRBQL doesn't support \"LIKE\" operator, use like() function instead e.g. ... WHERE like(a1, 'foo%bar') ... "); // UT JSON + if (lower_case_query.indexOf(' from ') != -1) + throw new SyntaxError(e.message + "\nTip: If input table is defined by the environment, RBQL query should not have \"FROM\" keyword"); // UT JSON + if (e && e.message && String(e.message).toLowerCase().indexOf('unexpected identifier') != -1) { + if (lower_case_query.indexOf(' and ') != -1) + throw new SyntaxError(e.message + "\nDid you use 'and' keyword in your query?\nJavaScript backend doesn't support 'and' keyword, use '&&' operator instead!"); + if (lower_case_query.indexOf(' or ') != -1) + throw new SyntaxError(e.message + "\nDid you use 'or' keyword in your query?\nJavaScript backend doesn't support 'or' keyword, use '||' operator instead!"); + } + } + if (e && e.message && e.message.indexOf('Received an instance of RBQLAggregationToken') != -1) + throw new RbqlParsingError(wrong_aggregation_usage_error); + throw e; + } +} + + +const GROUP_BY = 'GROUP BY'; +const UPDATE = 'UPDATE'; +const SELECT = 'SELECT'; +const JOIN = 'JOIN'; +const INNER_JOIN = 'INNER JOIN'; +const LEFT_JOIN = 'LEFT JOIN'; +const LEFT_OUTER_JOIN = 'LEFT OUTER JOIN'; +const STRICT_LEFT_JOIN = 'STRICT LEFT JOIN'; +const ORDER_BY = 'ORDER BY'; +const WHERE = 'WHERE'; +const LIMIT = 'LIMIT'; +const EXCEPT = 'EXCEPT'; +const WITH = 'WITH'; + + +function get_ambiguous_error_msg(variable_name) { + return `Ambiguous variable name: "${variable_name}" is present both in input and in join tables`; +} + + +function get_all_matches(regexp, text) { + var result = []; + let match_obj = null; + while((match_obj = regexp.exec(text)) !== null) { + result.push(match_obj); + } + return result; +} + + +function str_strip(src) { + return src.replace(/^ +| +$/g, ''); +} + + +function strip_comments(cline) { + cline = cline.trim(); + if (cline.startsWith('//')) + return ''; + return cline; +} + + +function combine_string_literals(backend_expression, string_literals) { + for (var i = 0; i < string_literals.length; i++) { + backend_expression = replace_all(backend_expression, `___RBQL_STRING_LITERAL${i}___`, string_literals[i]); + } + return backend_expression; +} + + +function parse_basic_variables(query_text, prefix, dst_variables_map) { + assert(prefix == 'a' || prefix == 'b'); + let rgx = new RegExp(`(?:^|[^_a-zA-Z0-9])${prefix}([1-9][0-9]*)(?:$|(?=[^_a-zA-Z0-9]))`, 'g'); + let matches = get_all_matches(rgx, query_text); + for (let i = 0; i < matches.length; i++) { + let field_num = parseInt(matches[i][1]); + dst_variables_map[prefix + String(field_num)] = {initialize: true, index: field_num - 1}; + } +} + + +function parse_array_variables(query_text, prefix, dst_variables_map) { + assert(prefix == 'a' || prefix == 'b'); + let rgx = new RegExp(`(?:^|[^_a-zA-Z0-9])${prefix}\\[([1-9][0-9]*)\\]`, 'g'); + let matches = get_all_matches(rgx, query_text); + for (let i = 0; i < matches.length; i++) { + let field_num = parseInt(matches[i][1]); + dst_variables_map[`${prefix}[${field_num}]`] = {initialize: true, index: field_num - 1}; + } +} + + +function js_string_escape_column_name(column_name, quote_char) { + column_name = column_name.replace(/\\/g, '\\\\'); + column_name = column_name.replace(/\n/g, '\\n'); + column_name = column_name.replace(/\r/g, '\\r'); + column_name = column_name.replace(/\t/g, '\\t'); + if (quote_char === "'") + return column_name.replace(/'/g, "\\'"); + if (quote_char === '"') + return column_name.replace(/"/g, '\\"'); + assert(quote_char === "`"); + return column_name.replace(/`/g, "\\`"); +} + + +function query_probably_has_dictionary_variable(query_text, column_name) { + let rgx = new RegExp('[-a-zA-Z0-9_:;+=!.,()%^#@&* ]+', 'g'); + let continuous_name_segments = get_all_matches(rgx, column_name); + for (let continuous_segment of continuous_name_segments) { + if (query_text.indexOf(continuous_segment) == -1) + return false; + } + return true; +} + + +function parse_dictionary_variables(query_text, prefix, column_names, dst_variables_map) { + // The purpose of this algorithm is to minimize number of variables in varibale_map to improve performance, ideally it should be only variables from the query + + // FIXME to prevent typos in attribute names either use query-based variable parsing which can properly handle back-tick strings or wrap "a" and "b" variables with ES6 Proxies https://stackoverflow.com/a/25658975/2898283 + assert(prefix === 'a' || prefix === 'b'); + let dict_test_rgx = new RegExp(`(?:^|[^_a-zA-Z0-9])${prefix}\\[`); + if (query_text.search(dict_test_rgx) == -1) + return; + for (let i = 0; i < column_names.length; i++) { + let column_name = column_names[i]; + if (query_probably_has_dictionary_variable(query_text, column_name)) { + let escaped_column_name = js_string_escape_column_name(column_name, '"'); + dst_variables_map[`${prefix}["${escaped_column_name}"]`] = {initialize: true, index: i}; + escaped_column_name = js_string_escape_column_name(column_name, "'"); + dst_variables_map[`${prefix}['${escaped_column_name}']`] = {initialize: false, index: i}; + escaped_column_name = js_string_escape_column_name(column_name, "`"); + dst_variables_map[`${prefix}[\`${escaped_column_name}\`]`] = {initialize: false, index: i}; + } + } +} + + +function parse_attribute_variables(query_text, prefix, column_names, column_names_source, dst_variables_map) { + // The purpose of this algorithm is to minimize number of variables in varibale_map to improve performance, ideally it should be only variables from the query + + assert(prefix === 'a' || prefix === 'b'); + let rgx = new RegExp(`(?:^|[^_a-zA-Z0-9])${prefix}\\.([_a-zA-Z][_a-zA-Z0-9]*)`, 'g'); + let matches = get_all_matches(rgx, query_text); + let column_names_from_query = matches.map(v => v[1]); + for (let column_name of column_names_from_query) { + let zero_based_idx = column_names.indexOf(column_name); + if (zero_based_idx != -1) { + dst_variables_map[`${prefix}.${column_name}`] = {initialize: true, index: zero_based_idx}; + } else { + throw new RbqlParsingError(`Unable to find column "${column_name}" in ${prefix == 'a' ? 'input' : 'join'} ${column_names_source}`); + } + } +} + + +function map_variables_directly(query_text, column_names, dst_variables_map) { + for (let i = 0; i < column_names.length; i++) { + let column_name = column_names[i]; + if ( /^[_a-zA-Z][_a-zA-Z0-9]*$/.exec(column_name) === null) + throw new RbqlIOHandlingError(`Unable to use column name "${column_name}" as RBQL/JS variable`); + if (query_text.indexOf(column_name) != -1) + dst_variables_map[column_name] = {initialize: true, index: i}; + } +} + + +function ensure_no_ambiguous_variables(query_text, input_column_names, join_column_names) { + let join_column_names_set = new Set(join_column_names); + for (let column_name of input_column_names) { + if (join_column_names_set.has(column_name) && query_text.indexOf(column_name) != -1) // False positive is tolerable here + throw new RbqlParsingError(get_ambiguous_error_msg(column_name)); + } +} + + +function parse_join_expression(src) { + src = str_strip(src); + const invalid_join_syntax_error = 'Invalid join syntax. Valid syntax: /path/to/B/table on a... == b... [and a... == b... [and ... ]]'; + let rgx = /^ *([^ ]+) +on +/i; + let match = rgx.exec(src); + if (match === null) + throw new RbqlParsingError(invalid_join_syntax_error); + let table_id = match[1]; + src = src.substr(match[0].length); + + let variable_pairs = []; + var pair_rgx = /^([^ =]+) *==? *([^ =]+)/; + var and_rgx = /^ +(and|&&) +/i; + while (true) { + match = pair_rgx.exec(src); + if (match === null) + throw new RbqlParsingError(invalid_join_syntax_error); + variable_pairs.push([match[1], match[2]]); + src = src.substr(match[0].length); + if (!src.length) + break; + match = and_rgx.exec(src); + if (match === null) + throw new RbqlParsingError(invalid_join_syntax_error); + src = src.substr(match[0].length); + } + return [table_id, variable_pairs]; +} + + +function resolve_join_variables(input_variables_map, join_variables_map, variable_pairs, string_literals) { + let lhs_variables = []; + let rhs_indices = []; + const valid_join_syntax_msg = 'Valid JOIN syntax: /path/to/B/table on a... == b... [and a... == b... [and ... ]]'; + for (let variable_pair of variable_pairs) { + let [join_var_1, join_var_2] = variable_pair; + join_var_1 = combine_string_literals(join_var_1, string_literals); + join_var_2 = combine_string_literals(join_var_2, string_literals); + if (input_variables_map.hasOwnProperty(join_var_1) && join_variables_map.hasOwnProperty(join_var_1)) + throw new RbqlParsingError(get_ambiguous_error_msg(join_var_1)); + if (input_variables_map.hasOwnProperty(join_var_2) && join_variables_map.hasOwnProperty(join_var_2)) + throw new RbqlParsingError(get_ambiguous_error_msg(join_var_2)); + if (input_variables_map.hasOwnProperty(join_var_2)) + [join_var_1, join_var_2] = [join_var_2, join_var_1]; + + let [lhs_key_index, rhs_key_index] = [null, null]; + if (['NR', 'a.NR', 'aNR'].indexOf(join_var_1) != -1) { + lhs_key_index = -1; + } else if (input_variables_map.hasOwnProperty(join_var_1)) { + lhs_key_index = input_variables_map[join_var_1].index; + } else { + throw new RbqlParsingError(`Unable to parse JOIN expression: Input table does not have field "${join_var_1}"\n${valid_join_syntax_msg}`); + } + + if (['b.NR', 'bNR'].indexOf(join_var_2) != -1) { + rhs_key_index = -1; + } else if (join_variables_map.hasOwnProperty(join_var_2)) { + rhs_key_index = join_variables_map[join_var_2].index; + } else { + throw new RbqlParsingError(`Unable to parse JOIN expression: Join table does not have field "${join_var_2}"\n${valid_join_syntax_msg}`); + } + + let lhs_join_var_expression = lhs_key_index == -1 ? 'NR' : `safe_join_get(record_a, ${lhs_key_index})`; + rhs_indices.push(rhs_key_index); + lhs_variables.push(lhs_join_var_expression); + } + return [lhs_variables, rhs_indices]; +} + + +function generate_common_init_code(query_text, variable_prefix) { + assert(variable_prefix == 'a' || variable_prefix == 'b'); + let result = []; + result.push(`${variable_prefix} = new Object();`); + let base_var = variable_prefix == 'a' ? 'NR' : 'bNR'; + let attr_var = `${variable_prefix}.NR`; + if (query_text.indexOf(attr_var) != -1) + result.push(`${attr_var} = ${base_var};`); + if (variable_prefix == 'a' && query_text.indexOf('aNR') != -1) + result.push('aNR = NR;'); + return result; +} + + +function generate_init_statements(query_text, variables_map, join_variables_map, indent) { + let code_lines = generate_common_init_code(query_text, 'a'); + let simple_var_name_rgx = /^[_0-9a-zA-Z]+$/; + for (const [variable_name, var_info] of Object.entries(variables_map)) { + if (var_info.initialize) { + let variable_declaration_keyword = simple_var_name_rgx.exec(variable_name) ? 'var ' : ''; + code_lines.push(`${variable_declaration_keyword}${variable_name} = safe_get(record_a, ${var_info.index});`); + } + } + if (join_variables_map) { + code_lines = code_lines.concat(generate_common_init_code(query_text, 'b')); + for (const [variable_name, var_info] of Object.entries(join_variables_map)) { + if (var_info.initialize) { + let variable_declaration_keyword = simple_var_name_rgx.exec(variable_name) ? 'var ' : ''; + code_lines.push(`${variable_declaration_keyword}${variable_name} = record_b === null ? null : safe_get(record_b, ${var_info.index});`); + } + } + } + for (let i = 1; i < code_lines.length; i++) { + code_lines[i] = indent + code_lines[i]; + } + return code_lines.join('\n'); +} + + +function replace_star_count(aggregate_expression) { + var rgx = /(^|,) *COUNT\( *\* *\) *(?:$|(?=,))/ig; + var result = aggregate_expression.replace(rgx, '$1 COUNT(1)'); + return str_strip(result); +} + + +function replace_star_vars(rbql_expression) { + let star_rgx = /(?:^|,) *(\*|a\.\*|b\.\*) *(?=$|,)/g; + let matches = get_all_matches(star_rgx, rbql_expression); + let last_pos = 0; + let result = ''; + for (let match of matches) { + let star_expression = match[1]; + let replacement_expression = ']).concat(' + {'*': 'star_fields', 'a.*': 'record_a', 'b.*': 'record_b'}[star_expression] + ').concat(['; + if (last_pos < match.index) + result += rbql_expression.substring(last_pos, match.index); + result += replacement_expression; + last_pos = match.index + match[0].length + 1; // Adding one to skip the lookahead comma + } + result += rbql_expression.substring(last_pos); + return result; +} + + +function replace_star_vars_for_header_parsing(rbql_expression) { + let star_rgx = /(?:(?<=^)|(?<=,)) *(\*|a\.\*|b\.\*) *(?=$|,)/g; + let matches = get_all_matches(star_rgx, rbql_expression); + let last_pos = 0; + let result = ''; + for (let match of matches) { + let star_expression = match[1]; + let replacement_expression = {'*': '__RBQL_INTERNAL_STAR', 'a.*': 'a.__RBQL_INTERNAL_STAR', 'b.*': 'b.__RBQL_INTERNAL_STAR'}[star_expression]; + if (last_pos < match.index) + result += rbql_expression.substring(last_pos, match.index); + result += replacement_expression; + last_pos = match.index + match[0].length; + } + result += rbql_expression.substring(last_pos); + return result; +} + + +function translate_update_expression(update_expression, input_variables_map, string_literals, indent) { + let first_assignment = str_strip(update_expression.split('=')[0]); + let first_assignment_error = `Unable to parse "UPDATE" expression: the expression must start with assignment, but "${first_assignment}" does not look like an assignable field name`; + + let assignment_looking_rgx = /(?:^|,) *(a[.#a-zA-Z0-9\[\]_]*) *=(?=[^=])/g; + let update_expressions = []; + let pos = 0; + while (true) { + let match = assignment_looking_rgx.exec(update_expression); + if (update_expressions.length == 0 && (match === null || match.index != 0)) { + throw new RbqlParsingError(first_assignment_error); + } + if (match === null) { + update_expressions[update_expressions.length - 1] += str_strip(update_expression.substr(pos)) + ');'; + break; + } + if (update_expressions.length) + update_expressions[update_expressions.length - 1] += str_strip(update_expression.substring(pos, match.index)) + ');'; + let dst_var_name = combine_string_literals(str_strip(match[1]), string_literals); + if (!input_variables_map.hasOwnProperty(dst_var_name)) + throw new RbqlParsingError(`Unable to parse "UPDATE" expression: Unknown field name: "${dst_var_name}"`); + let var_index = input_variables_map[dst_var_name].index; + let current_indent = update_expressions.length ? indent : ''; + update_expressions.push(`${current_indent}safe_set(up_fields, ${var_index}, `); + pos = match.index + match[0].length; + } + return combine_string_literals(update_expressions.join('\n'), string_literals); +} + + +function translate_select_expression(select_expression) { + let expression_without_stars = replace_star_count(select_expression); + let translated = str_strip(replace_star_vars(expression_without_stars)); + let translated_for_header = str_strip(replace_star_vars_for_header_parsing(expression_without_stars)); + if (!translated.length) + throw new RbqlParsingError('"SELECT" expression is empty'); + return [`[].concat([${translated}])`, translated_for_header]; +} + + +function separate_string_literals(rbql_expression) { + // The regex consists of 3 almost identicall parts, the only difference is quote type + var rgx = /('(\\(\\\\)*'|[^'])*')|("(\\(\\\\)*"|[^"])*")|(`(\\(\\\\)*`|[^`])*`)/g; + var match_obj = null; + var format_parts = []; + var string_literals = []; + var idx_before = 0; + while((match_obj = rgx.exec(rbql_expression)) !== null) { + var literal_id = string_literals.length; + var string_literal = match_obj[0]; + string_literals.push(string_literal); + var start_index = match_obj.index; + format_parts.push(rbql_expression.substring(idx_before, start_index)); + format_parts.push(`___RBQL_STRING_LITERAL${literal_id}___`); + idx_before = rgx.lastIndex; + } + format_parts.push(rbql_expression.substring(idx_before)); + var format_expression = format_parts.join(''); + format_expression = format_expression.replace(/\t/g, ' '); + return [format_expression, string_literals]; +} + + +function locate_statements(rbql_expression) { + let statement_groups = []; + statement_groups.push([STRICT_LEFT_JOIN, LEFT_OUTER_JOIN, LEFT_JOIN, INNER_JOIN, JOIN]); + statement_groups.push([SELECT]); + statement_groups.push([ORDER_BY]); + statement_groups.push([WHERE]); + statement_groups.push([UPDATE]); + statement_groups.push([GROUP_BY]); + statement_groups.push([LIMIT]); + statement_groups.push([EXCEPT]); + var result = []; + for (var ig = 0; ig < statement_groups.length; ig++) { + for (var is = 0; is < statement_groups[ig].length; is++) { + var statement = statement_groups[ig][is]; + var rgxp = new RegExp('(?:^| )' + replace_all(statement, ' ', ' *') + '(?= )', 'ig'); + var matches = get_all_matches(rgxp, rbql_expression); + if (!matches.length) + continue; + if (matches.length > 1) + throw new RbqlParsingError(`More than one "${statement}" statements found`); + assert(matches.length == 1); + var match = matches[0]; + var match_str = match[0]; + result.push([match.index, match.index + match_str.length, statement]); + break; // Break to avoid matching a sub-statement from the same group e.g. "INNER JOIN" -> "JOIN" + } + } + result.sort(function(a, b) { return a[0] - b[0]; }); + return result; +} + + +function separate_actions(rbql_expression) { + rbql_expression = str_strip(rbql_expression); + var result = {}; + let with_match = /^(.*) *[Ww][Ii][Tt][Hh] *\(([a-z]{4,20})\) *$/.exec(rbql_expression); + if (with_match !== null) { + rbql_expression = with_match[1]; + result[WITH] = with_match[2]; + } + var ordered_statements = locate_statements(rbql_expression); + for (var i = 0; i < ordered_statements.length; i++) { + var statement_start = ordered_statements[i][0]; + var span_start = ordered_statements[i][1]; + var statement = ordered_statements[i][2]; + var span_end = i + 1 < ordered_statements.length ? ordered_statements[i + 1][0] : rbql_expression.length; + assert(statement_start < span_start); + assert(span_start <= span_end); + var span = rbql_expression.substring(span_start, span_end); + var statement_params = {}; + if ([STRICT_LEFT_JOIN, LEFT_OUTER_JOIN, LEFT_JOIN, INNER_JOIN, JOIN].indexOf(statement) != -1) { + statement_params['join_subtype'] = statement; + statement = JOIN; + } + + if (statement == UPDATE) { + if (statement_start != 0) + throw new RbqlParsingError('UPDATE keyword must be at the beginning of the query'); + span = span.replace(/^ *SET/i, ''); + } + + if (statement == ORDER_BY) { + span = span.replace(/ ASC *$/i, ''); + var new_span = span.replace(/ DESC *$/i, ''); + if (new_span != span) { + span = new_span; + statement_params['reverse'] = true; + } else { + statement_params['reverse'] = false; + } + } + + if (statement == SELECT) { + if (statement_start != 0) + throw new RbqlParsingError('SELECT keyword must be at the beginning of the query'); + let match = /^ *TOP *([0-9]+) /i.exec(span); + if (match !== null) { + statement_params['top'] = parseInt(match[1]); + span = span.substr(match.index + match[0].length); + } + match = /^ *DISTINCT *(COUNT)? /i.exec(span); + if (match !== null) { + statement_params['distinct'] = true; + if (match[1]) { + statement_params['distinct_count'] = true; + } + span = span.substr(match.index + match[0].length); + } + } + statement_params['text'] = str_strip(span); + result[statement] = statement_params; + } + if (!result.hasOwnProperty(SELECT) && !result.hasOwnProperty(UPDATE)) { + throw new RbqlParsingError('Query must contain either SELECT or UPDATE statement'); + } + assert(result.hasOwnProperty(SELECT) != result.hasOwnProperty(UPDATE)); + return result; +} + + +function find_top(rb_actions) { + if (rb_actions.hasOwnProperty(LIMIT)) { + var rgx = /^[0-9]+$/; + if (rgx.exec(rb_actions[LIMIT]['text']) === null) { + throw new RbqlParsingError('LIMIT keyword must be followed by an integer'); + } + var result = parseInt(rb_actions[LIMIT]['text']); + return result; + } + var select_action = rb_actions[SELECT]; + if (select_action && select_action.hasOwnProperty('top')) { + return select_action['top']; + } + return null; +} + + +function translate_except_expression(except_expression, input_variables_map, string_literals, input_header) { + let skip_vars = except_expression.split(','); + skip_vars = skip_vars.map(str_strip); + let skip_indices = []; + for (let var_name of skip_vars) { + var_name = combine_string_literals(var_name, string_literals); + if (!input_variables_map.hasOwnProperty(var_name)) + throw new RbqlParsingError(`Unknown field in EXCEPT expression: "${var_name}"`); + skip_indices.push(input_variables_map[var_name].index); + } + skip_indices = skip_indices.sort((a, b) => a - b); + let output_header = input_header === null ? null : select_except(input_header, skip_indices); + let indices_str = skip_indices.join(','); + return [output_header, `select_except(record_a, [${indices_str}])`]; +} + + +class HashJoinMap { + constructor(record_iterator, key_indices) { + this.max_record_len = 0; + this.hash_map = new Map(); + this.record_iterator = record_iterator; + this.nr = 0; + if (key_indices.length == 1) { + this.key_index = key_indices[0]; + this.key_indices = null; + this.polymorphic_get_key = this.get_single_key; + } else { + this.key_index = null; + this.key_indices = key_indices; + this.polymorphic_get_key = this.get_multi_key; + } + } + + get_single_key(nr, fields) { + if (this.key_index >= fields.length) + throw new RbqlRuntimeError(`No field with index ${this.key_index + 1} at record ${this.nr} in "B" table`); + return this.key_index === -1 ? this.nr : fields[this.key_index]; + }; + + get_multi_key(nr, fields) { + let result = []; + for (let ki of this.key_indices) { + if (ki >= fields.length) + throw new RbqlRuntimeError(`No field with index ${ki + 1} at record ${this.nr} in "B" table`); + result.push(ki === -1 ? this.nr : fields[ki]); + } + return JSON.stringify(result); + }; + + async build() { + while (true) { + let fields = await this.record_iterator.get_record(); + if (fields === null) + break; + this.nr += 1; + let nf = fields.length; + this.max_record_len = Math.max(this.max_record_len, nf); + let key = this.polymorphic_get_key(this.nr, fields); + let key_records = this.hash_map.get(key); + if (key_records === undefined) { + this.hash_map.set(key, [[this.nr, nf, fields]]); + } else { + key_records.push([this.nr, nf, fields]); + } + } + }; + + get_join_records(key) { + let result = this.hash_map.get(key); + if (result === undefined) + return []; + return result; + }; + + get_warnings() { + return this.record_iterator.get_warnings(); + }; +} + + +function cleanup_query(query_text) { + return query_text.split('\n').map(strip_comments).filter(line => line.length).join(' ').replace(/;+$/g, ''); +} + + +function remove_redundant_table_name(query_text) { + query_text = str_strip(query_text.replace(/ +from +a(?: +|$)/gi, ' ')); + query_text = str_strip(query_text.replace(/^ *update +a +set /gi, 'update ')); + return query_text; +} + + +function select_output_header(input_header, join_header, query_column_infos) { + if (input_header === null && join_header === null) + return null; + if (input_header === null) + input_header = []; + if (join_header === null) + join_header = []; + let output_header = []; + for (let qci of query_column_infos) { + // TODO refactor this and python version: extract this code into a function instead to always return something + if (qci === null) { + output_header.push('col' + (output_header.length + 1)); + } else if (qci.is_star) { + if (qci.table_name === null) { + output_header = output_header.concat(input_header).concat(join_header); + } else if (qci.table_name === 'a') { + output_header = output_header.concat(input_header); + } else if (qci.table_name === 'b') { + output_header = output_header.concat(join_header); + } + } else if (qci.column_name !== null) { + output_header.push(qci.column_name); + } else if (qci.column_index !== null) { + if (qci.table_name == 'a' && qci.column_index < input_header.length) { + output_header.push(input_header[qci.column_index]); + } else if (qci.table_name == 'b' && qci.column_index < join_header.length) { + output_header.push(join_header[qci.column_index]); + } else { + output_header.push('col' + (output_header.length + 1)); + } + } else { // Should never happen + output_header.push('col' + (output_header.length + 1)); + } + } + return output_header; +} + + +function make_inconsistent_num_fields_warning(table_name, inconsistent_records_info) { + let keys = Object.keys(inconsistent_records_info); + let entries = []; + for (let i = 0; i < keys.length; i++) { + let key = keys[i]; + let record_id = inconsistent_records_info[key]; + entries.push([record_id, key]); + } + entries.sort(function(a, b) { return a[0] - b[0]; }); + assert(entries.length > 1); + let [record_1, num_fields_1] = entries[0]; + let [record_2, num_fields_2] = entries[1]; + let warn_msg = `Number of fields in "${table_name}" table is not consistent: `; + warn_msg += `e.g. record ${record_1} -> ${num_fields_1} fields, record ${record_2} -> ${num_fields_2} fields`; + return warn_msg; +} + + +class RBQLInputIterator { + constructor(){} + stop() { + throw new Error("Unable to call the interface method"); + } + async get_variables_map(query_text) { + throw new Error("Unable to call the interface method"); + } + async get_record() { + throw new Error("Unable to call the interface method"); + } + handle_query_modifier() { + return; // Reimplement if you need to handle a boolean query modifier that can be used like this: `SELECT * WITH (modifiername)` + } + get_warnings() { + return []; // Reimplement if your class can produce warnings + } + async get_header() { + return null; // Reimplement if your class can provide input header + } +} + + +class RBQLOutputWriter { + constructor(){} + + async write(fields) { + throw new Error("Unable to call the interface method"); + } + + async finish() { + // Reimplement if your class needs to do something on finish e.g. cleanup + }; + + get_warnings() { + return []; // Reimplement if your class can produce warnings + }; + + set_header() { + return; // Reimplement if your class can handle output headers in a meaningful way + } +} + + +class RBQLTableRegistry { + constructor(){} + + get_iterator_by_table_id(table_id) { + throw new Error("Unable to call the interface method"); + } + + get_warnings() { + return []; // Reimplement if your class can produce warnings + }; +} + + +class TableIterator extends RBQLInputIterator { + constructor(table, column_names=null, normalize_column_names=true, variable_prefix='a') { + super(); + this.table = table; + this.column_names = column_names; + this.normalize_column_names = normalize_column_names; + this.variable_prefix = variable_prefix; + this.nr = 0; + this.fields_info = new Object(); + this.stopped = false; + } + + + stop() { + this.stopped = true; + }; + + + async get_variables_map(query_text) { + let variable_map = new Object(); + parse_basic_variables(query_text, this.variable_prefix, variable_map); + parse_array_variables(query_text, this.variable_prefix, variable_map); + if (this.column_names !== null) { + if (this.table.length && this.column_names.length != this.table[0].length) + throw new RbqlIOHandlingError('List of column names and table records have different lengths'); + if (this.normalize_column_names) { + parse_dictionary_variables(query_text, this.variable_prefix, this.column_names, variable_map); + parse_attribute_variables(query_text, this.variable_prefix, this.column_names, 'column names list', variable_map); + } else { + map_variables_directly(query_text, this.column_names, variable_map); + } + } + return variable_map; + }; + + + async get_record() { + if (this.stopped) + return null; + if (this.nr >= this.table.length) + return null; + let record = this.table[this.nr]; + this.nr += 1; + let num_fields = record.length; + if (!this.fields_info.hasOwnProperty(num_fields)) + this.fields_info[num_fields] = this.nr; + return record; + }; + + get_warnings() { + if (Object.keys(this.fields_info).length > 1) + return [make_inconsistent_num_fields_warning('input', this.fields_info)]; + return []; + }; + + async get_header() { + return this.column_names; + } +} + + +class TableWriter extends RBQLOutputWriter { + constructor(external_table) { + super(); + this.table = external_table; + this.header = null; + } + + async write(fields) { + this.table.push(fields); + return true; + }; + + set_header(header) { + this.header = header; + } +} + + +class SingleTableRegistry extends RBQLTableRegistry { + constructor(table, column_names=null, normalize_column_names=true, table_id='b') { + super(); + this.table = table; + this.table_id = table_id; + this.column_names = column_names; + this.normalize_column_names = normalize_column_names; + } + + get_iterator_by_table_id(table_id) { + if (table_id.toLowerCase() !== this.table_id) + throw new RbqlIOHandlingError(`Unable to find join table: "${table_id}"`); + return new TableIterator(this.table, this.column_names, this.normalize_column_names, 'b'); + }; +} + + +async function shallow_parse_input_query(query_text, input_iterator, join_tables_registry, query_context) { + query_text = cleanup_query(query_text); + var [format_expression, string_literals] = separate_string_literals(query_text); + format_expression = remove_redundant_table_name(format_expression); + + var rb_actions = separate_actions(format_expression); + if (rb_actions.hasOwnProperty(WITH)) { + input_iterator.handle_query_modifier(rb_actions[WITH]); + } + var input_variables_map = await input_iterator.get_variables_map(query_text); + + if (rb_actions.hasOwnProperty(ORDER_BY) && rb_actions.hasOwnProperty(UPDATE)) + throw new RbqlParsingError('"ORDER BY" is not allowed in "UPDATE" queries'); + + if (rb_actions.hasOwnProperty(GROUP_BY)) { + if (rb_actions.hasOwnProperty(ORDER_BY) || rb_actions.hasOwnProperty(UPDATE)) + throw new RbqlParsingError('"ORDER BY", "UPDATE" and "DISTINCT" keywords are not allowed in aggregate queries'); + query_context.aggregation_key_expression = '[' + combine_string_literals(rb_actions[GROUP_BY]['text'], string_literals) + ']'; + } + + let join_variables_map = null; + let join_header = null; + if (rb_actions.hasOwnProperty(JOIN)) { + var [rhs_table_id, variable_pairs] = parse_join_expression(rb_actions[JOIN]['text']); + if (join_tables_registry === null) + throw new RbqlParsingError('JOIN operations are not supported by the application'); + let join_record_iterator = join_tables_registry.get_iterator_by_table_id(rhs_table_id); + if (!join_record_iterator) + throw new RbqlParsingError(`Unable to find join table: "${rhs_table_id}"`); + if (rb_actions.hasOwnProperty(WITH)) { + join_record_iterator.handle_query_modifier(rb_actions[WITH]); + } + join_variables_map = await join_record_iterator.get_variables_map(query_text); + join_header = await join_record_iterator.get_header(); + let [lhs_variables, rhs_indices] = resolve_join_variables(input_variables_map, join_variables_map, variable_pairs, string_literals); + let sql_join_type = {'JOIN': InnerJoiner, 'INNER JOIN': InnerJoiner, 'LEFT JOIN': LeftJoiner, 'LEFT OUTER JOIN': LeftJoiner, 'STRICT LEFT JOIN': StrictLeftJoiner}[rb_actions[JOIN]['join_subtype']]; + query_context.lhs_join_var_expression = lhs_variables.length == 1 ? lhs_variables[0] : 'JSON.stringify([' + lhs_variables.join(',') + '])'; + query_context.join_map_impl = new HashJoinMap(join_record_iterator, rhs_indices); + await query_context.join_map_impl.build(); + query_context.join_map = new sql_join_type(query_context.join_map_impl); + } + + query_context.variables_init_code = combine_string_literals(generate_init_statements(format_expression, input_variables_map, join_variables_map, ' '.repeat(4)), string_literals); + + if (rb_actions.hasOwnProperty(WHERE)) { + var where_expression = rb_actions[WHERE]['text']; + if (/[^>= 3 && line.charCodeAt(0) === 0xEF && line.charCodeAt(1) === 0xBB && line.charCodeAt(2) === 0xBF) { + return line.substring(3); + } + if (assumed_source_encoding == 'utf-8' && line.length >= 1 && line.charCodeAt(0) === 0xFEFF) { + return line.substring(1); + } + return line; +} + + +function make_inconsistent_num_fields_warning(table_name, inconsistent_records_info) { + let keys = Object.keys(inconsistent_records_info); + let entries = []; + for (let i = 0; i < keys.length; i++) { + let key = keys[i]; + let record_id = inconsistent_records_info[key]; + entries.push([record_id, key]); + } + entries.sort(function(a, b) { return a[0] - b[0]; }); + assert(entries.length > 1); + let [record_1, num_fields_1] = entries[0]; + let [record_2, num_fields_2] = entries[1]; + let warn_msg = `Number of fields in "${table_name}" table is not consistent: `; + warn_msg += `e.g. record ${record_1} -> ${num_fields_1} fields, record ${record_2} -> ${num_fields_2} fields`; + return warn_msg; +} + + +function expanduser(filepath) { + if (filepath.charAt(0) === '~') { + return path.join(os.homedir(), filepath.slice(1)); + } + return filepath; +} + + +function try_read_index(index_path) { + var content = null; + try { + content = fs.readFileSync(index_path, 'utf-8'); + } catch (e) { + return []; + } + var lines = content.split('\n'); + var records = []; + for (var i = 0; i < lines.length; i++) { + if (!lines[i]) + continue; + var record = lines[i].split('\t'); + records.push(record); + } + return records; +} + + +function get_index_record(index_path, key) { + var records = try_read_index(index_path); + for (var i = 0; i < records.length; i++) { + if (records[i].length && records[i][0] == key) { + return records[i]; + } + } + return null; +} + + +function find_table_path(main_table_dir, table_id) { + // If table_id is a relative path it could be relative either to the current directory or to the main table dir. + var candidate_path = expanduser(table_id); + if (fs.existsSync(candidate_path)) { + return candidate_path; + } + if (main_table_dir && !path.isAbsolute(candidate_path)) { + candidate_path = path.join(main_table_dir, candidate_path); + if (fs.existsSync(candidate_path)) { + return candidate_path; + } + } + let table_names_settings_path = path.join(os.homedir(), '.rbql_table_names'); + var name_record = get_index_record(table_names_settings_path, table_id); + if (name_record && name_record.length > 1 && fs.existsSync(name_record[1])) { + return name_record[1]; + } + return null; +} + + +class RecordQueue { + // TODO compare performance with a linked list + constructor() { + this.push_stack = []; + this.pull_stack = []; + } + + enqueue(record) { + this.push_stack.push(record); + } + + dequeue() { + if (!this.pull_stack.length) { + if (!this.push_stack.length) + return null; + this.pull_stack = this.push_stack; + this.pull_stack.reverse(); + this.push_stack = []; + } + return this.pull_stack.pop(); + } +} + + +class CSVRecordIterator extends rbql.RBQLInputIterator { + // CSVRecordIterator implements a typical async producer-consumer model with an internal buffer: + // get_record() - consumer + // stream.on('data') - producer + constructor(stream, csv_path, encoding, delim, policy, has_header=false, comment_prefix=null, table_name='input', variable_prefix='a') { + super(); + this.stream = stream; + this.csv_path = csv_path; + assert((this.stream === null) != (this.csv_path === null)); + this.encoding = encoding; + this.delim = delim; + this.policy = policy; + + this.has_header = has_header; + this.first_record = null; + this.first_record_should_be_emitted = !has_header; + this.header_preread_complete = false; + + this.table_name = table_name; + this.variable_prefix = variable_prefix; + this.comment_prefix = (comment_prefix !== null && comment_prefix.length) ? comment_prefix : null; + + this.decoder = null; + if (encoding == 'utf-8' && this.csv_path === null) { + // Unfortunately util.TextDecoder has serious flaws: + // 1. It doesn't work in Node without ICU: https://nodejs.org/api/util.html#util_new_textdecoder_encoding_options + // 2. It is broken in Electron: https://github.com/electron/electron/issues/18733 + + // Technically we can implement our own custom streaming text decoder, using the 3 following technologies: + // 1. decode-encode validation method from https://stackoverflow.com/a/32279283/2898283 + // 2. Scanning buffer chunks for non-continuation utf-8 bytes from the end of the buffer: + // src_buffer -> (buffer_before, buffer_after) where buffer_after is very small(a couple of bytes) and buffer_before is large and ends with a non-continuation bytes + // 3. Internal buffer to store small tail part from the previous buffer + this.decoder = new util.TextDecoder(encoding, {fatal: true, stream: true}); + } + + this.input_exhausted = false; + this.started = false; + + this.utf8_bom_removed = false; // BOM doesn't get automatically removed by the decoder when utf-8 file is treated as latin-1 + this.first_defective_line = null; + + this.fields_info = new Object(); + this.NR = 0; // Record number + this.NL = 0; // Line number (NL != NR when the CSV file has comments or multiline fields) + + this.rfc_line_buffer = []; + + this.partially_decoded_line = ''; + this.partially_decoded_line_ends_with_cr = false; + + // Holds an external "resolve" function which is called when everything is fine. + this.resolve_current_record = null; + // Holds an external "reject" function which is called when error has occured. + this.reject_current_record = null; + // Holds last exception if we don't have any reject callbacks from clients yet. + this.current_exception = null; + + this.produced_records_queue = new RecordQueue(); + + this.process_line_polymorphic = policy == 'quoted_rfc' ? this.process_partial_rfc_record_line : this.process_record_line; + } + + + handle_query_modifier(modifier) { + // For `... WITH (header) ...` syntax + if (['header', 'headers'].indexOf(modifier) != -1) { + this.has_header = true; + this.first_record_should_be_emitted = false; + } + if (['noheader', 'noheaders'].indexOf(modifier) != -1) { + this.has_header = false; + this.first_record_should_be_emitted = true; + } + } + + + reset_external_callbacks() { + // Drop external callbacks simultaneously since promises can only resolve once, see: https://stackoverflow.com/a/18218542/2898283 + this.reject_current_record = null; + this.resolve_current_record = null; + } + + try_propagate_exception() { + if (this.current_exception && this.reject_current_record) { + let reject = this.reject_current_record; + let exception = this.current_exception; + this.reset_external_callbacks(); + this.current_exception = null; + reject(exception); + } + } + + + store_or_propagate_exception(exception) { + if (this.current_exception === null) + // Ignore subsequent exceptions if we already have an unreported error. This way we prioritize earlier errors over the more recent ones. + this.current_exception = exception; + this.try_propagate_exception(); + } + + + async preread_first_record() { + if (this.header_preread_complete) + return; + this.first_record = await this.get_record(); + this.header_preread_complete = true; // We must set header_preread_complete to true after calling get_record(), because get_record() uses it internally. + if (this.first_record === null) { + return; + } + if (this.stream) + this.stream.pause(); + this.first_record = this.first_record.slice(); + }; + + + async get_variables_map(query_text) { + let variable_map = new Object(); + rbql.parse_basic_variables(query_text, this.variable_prefix, variable_map); + rbql.parse_array_variables(query_text, this.variable_prefix, variable_map); + + await this.preread_first_record(); + if (this.has_header && this.first_record) { + rbql.parse_attribute_variables(query_text, this.variable_prefix, this.first_record, 'CSV header line', variable_map); + rbql.parse_dictionary_variables(query_text, this.variable_prefix, this.first_record, variable_map); + } + return variable_map; + }; + + async get_header() { + await this.preread_first_record(); + return this.has_header ? this.first_record : null; + } + + + try_resolve_next_record() { + this.try_propagate_exception(); + if (this.resolve_current_record === null) + return; + + let record = null; + if (this.first_record_should_be_emitted && this.header_preread_complete) { + this.first_record_should_be_emitted = false; + record = this.first_record; + } else { + record = this.produced_records_queue.dequeue(); + } + + if (record === null && !this.input_exhausted) + return; + let resolve = this.resolve_current_record; + this.reset_external_callbacks(); + resolve(record); + }; + + + async get_record() { + if (!this.started) + await this.start(); + if (this.stream && this.stream.isPaused()) + this.stream.resume(); + + let parent_iterator = this; + let current_record_promise = new Promise(function(resolve, reject) { + parent_iterator.resolve_current_record = resolve; + parent_iterator.reject_current_record = reject; + }); + this.try_resolve_next_record(); + return current_record_promise; + }; + + + async get_all_records(num_records=null) { + let records = []; + while (true) { + let record = await this.get_record(); + if (record === null) + break; + records.push(record); + if (num_records && records.length >= num_records) { + this.stop(); + break; + } + } + return records; + }; + + + process_record_line(line) { + if (this.comment_prefix !== null && line.startsWith(this.comment_prefix)) + return; // Just skip the line + this.NR += 1; + var [record, warning] = csv_utils.smart_split(line, this.delim, this.policy, false); + if (warning) { + if (this.first_defective_line === null) { + this.first_defective_line = this.NL; + if (this.policy == 'quoted_rfc') + this.store_or_propagate_exception(new RbqlIOHandlingError(`Inconsistent double quote escaping in ${this.table_name} table at record ${this.NR}, line ${this.NL}`)); + } + } + let num_fields = record.length; + if (!this.fields_info.hasOwnProperty(num_fields)) + this.fields_info[num_fields] = this.NR; + this.produced_records_queue.enqueue(record); + this.try_resolve_next_record(); + }; + + + process_partial_rfc_record_line(line) { + let record_line = csv_utils.accumulate_rfc_line_into_record(this.rfc_line_buffer, line, this.comment_prefix); + if (record_line !== null) + this.process_record_line(record_line); + }; + + + process_line(line) { + this.NL += 1; + if (this.NL === 1) { + var clean_line = remove_utf8_bom(line, this.encoding); + if (clean_line != line) { + line = clean_line; + this.utf8_bom_removed = true; + } + } + this.process_line_polymorphic(line); + }; + + + process_data_stream_chunk(data_chunk) { + let decoded_string = null; + if (this.decoder) { + try { + decoded_string = this.decoder.decode(data_chunk); + } catch (e) { + if (e instanceof TypeError) { + this.store_or_propagate_exception(new RbqlIOHandlingError(utf_decoding_error)); + } else { + this.store_or_propagate_exception(e); + } + return; + } + } else { + decoded_string = data_chunk.toString(this.encoding); + } + let line_starts_with_lf = decoded_string.length && decoded_string[0] == '\n'; + let first_line_index = line_starts_with_lf && this.partially_decoded_line_ends_with_cr ? 1 : 0; + this.partially_decoded_line_ends_with_cr = decoded_string.length && decoded_string[decoded_string.length - 1] == '\r'; + let lines = csv_utils.split_lines(decoded_string); + lines[0] = this.partially_decoded_line + lines[0]; + assert(first_line_index == 0 || lines[0].length == 0); + this.partially_decoded_line = lines.pop(); + for (let i = first_line_index; i < lines.length; i++) { + this.process_line(lines[i]); + } + }; + + + process_data_bulk(data_chunk) { + let decoded_string = data_chunk.toString(this.encoding); + if (this.encoding == 'utf-8') { + // Using hacky comparison method from here: https://stackoverflow.com/a/32279283/2898283 + // TODO get rid of this once TextDecoder is really fixed or when alternative method of reliable decoding appears + let control_buffer = Buffer.from(decoded_string, 'utf-8'); + if (Buffer.compare(data_chunk, control_buffer) != 0) { + this.store_or_propagate_exception(new RbqlIOHandlingError(utf_decoding_error)); + return; + } + } + let lines = csv_utils.split_lines(decoded_string); + if (lines.length && lines[lines.length - 1].length == 0) + lines.pop(); + for (let i = 0; i < lines.length; i++) { + this.process_line(lines[i]); + } + if (this.rfc_line_buffer.length > 0) { + this.process_record_line(this.rfc_line_buffer.join('\n')); + } + this.input_exhausted = true; + this.try_resolve_next_record(); // Should be a NOOP here? + } + + + process_data_stream_end() { + this.input_exhausted = true; + if (this.partially_decoded_line.length) { + let last_line = this.partially_decoded_line; + this.partially_decoded_line = ''; + this.process_line(last_line); + } + if (this.rfc_line_buffer.length > 0) { + this.process_record_line(this.rfc_line_buffer.join('\n')); + } + this.try_resolve_next_record(); + }; + + + stop() { + if (this.stream) + this.stream.destroy(); // TODO consider using pause() instead + }; + + + async start() { + if (this.started) + return; + this.started = true; + if (this.stream) { + this.stream.on('data', (data_chunk) => { this.process_data_stream_chunk(data_chunk); }); + this.stream.on('end', () => { this.process_data_stream_end(); }); + } else { + let parent_iterator = this; + return new Promise(function(resolve, reject) { + fs.readFile(parent_iterator.csv_path, (err, data_chunk) => { + if (err) { + reject(err); + } else { + parent_iterator.process_data_bulk(data_chunk); + resolve(); + } + }); + }); + } + }; + + + get_warnings() { + let result = []; + if (this.first_defective_line !== null) + result.push(`Inconsistent double quote escaping in ${this.table_name} table. E.g. at line ${this.first_defective_line}`); + if (this.utf8_bom_removed) + result.push(`UTF-8 Byte Order Mark (BOM) was found and skipped in ${this.table_name} table`); + if (Object.keys(this.fields_info).length > 1) + result.push(make_inconsistent_num_fields_warning(this.table_name, this.fields_info)); + return result; + }; +} + + +class CSVWriter extends rbql.RBQLOutputWriter { + constructor(stream, close_stream_on_finish, encoding, delim, policy, line_separator='\n') { + super(); + this.stream = stream; + this.encoding = encoding; + if (encoding) + this.stream.setDefaultEncoding(encoding); + this.stream.on('error', (error_obj) => { this.store_first_error(error_obj); }) + this.delim = delim; + this.policy = policy; + this.line_separator = line_separator; + this.sub_array_delim = delim == '|' ? ';' : '|'; + + this.close_stream_on_finish = close_stream_on_finish; + + this.null_in_output = false; + this.delim_in_simple_output = false; + this.header_len = null; + this.first_error = null; + + if (policy == 'simple') { + this.polymorphic_join = this.simple_join; + } else if (policy == 'quoted') { + this.polymorphic_join = this.quoted_join; + } else if (policy == 'quoted_rfc') { + this.polymorphic_join = this.quoted_join_rfc; + } else if (policy == 'monocolumn') { + this.polymorphic_join = this.mono_join; + } else if (policy == 'whitespace') { + this.polymorphic_join = this.simple_join; + } else { + throw new RbqlIOHandlingError('Unknown output csv policy'); + } + } + + + store_first_error(error_obj) { + // Store only first error because it is typically more important than the subsequent ones. + if (this.first_error === null) + this.first_error = error_obj; + } + + set_header(header) { + if (header !== null) { + this.header_len = header.length; + this.write(header); + } + } + + + quoted_join(fields) { + let delim = this.delim; + var quoted_fields = fields.map(function(v) { return csv_utils.quote_field(String(v), delim); }); + return quoted_fields.join(this.delim); + }; + + + quoted_join_rfc(fields) { + let delim = this.delim; + var quoted_fields = fields.map(function(v) { return csv_utils.rfc_quote_field(String(v), delim); }); + return quoted_fields.join(this.delim); + }; + + + mono_join(fields) { + if (fields.length > 1) { + throw new RbqlIOHandlingError('Unable to use "Monocolumn" output format: some records have more than one field'); + } + return fields[0]; + }; + + + simple_join(fields) { + var res = fields.join(this.delim); + if (fields.join('').indexOf(this.delim) != -1) { + this.delim_in_simple_output = true; + } + return res; + }; + + + normalize_fields(out_fields) { + for (var i = 0; i < out_fields.length; i++) { + if (out_fields[i] == null) { + this.null_in_output = true; + out_fields[i] = ''; + } else if (Array.isArray(out_fields[i])) { + this.normalize_fields(out_fields[i]); + out_fields[i] = out_fields[i].join(this.sub_array_delim); + } + } + }; + + + async write(fields) { + if (this.header_len !== null && fields.length != this.header_len) + throw new RbqlIOHandlingError(`Inconsistent number of columns in output header and the current record: ${this.header_len} != ${fields.length}`); + this.normalize_fields(fields); + this.stream.write(this.polymorphic_join(fields)); + this.stream.write(this.line_separator); + let writer_error = this.first_error; + return new Promise(function(resolve, reject) { + if (writer_error !== null) { + reject(writer_error); + } else { + resolve(true); + } + }); + }; + + + _write_all(table) { + for (let i = 0; i < table.length; i++) { + this.write(table[i]); + } + }; + + + async finish() { + let close_stream_on_finish = this.close_stream_on_finish; + let output_stream = this.stream; + let output_encoding = this.encoding; + let writer_error = this.first_error; + let finish_promise = new Promise(function(resolve, reject) { + if (writer_error !== null) { + reject(writer_error); + } + if (close_stream_on_finish) { + output_stream.end('', output_encoding, () => { resolve(); }); + } else { + setTimeout(() => { resolve(); }, 0); + } + }); + return finish_promise; + }; + + + get_warnings() { + let result = []; + if (this.null_in_output) + result.push('null values in output were replaced by empty strings'); + if (this.delim_in_simple_output) + result.push('Some output fields contain separator'); + return result; + }; + +} + + +class FileSystemCSVRegistry extends rbql.RBQLTableRegistry { + constructor(input_file_dir, delim, policy, encoding, has_header=false, comment_prefix=null, options=null) { + super(); + this.input_file_dir = input_file_dir; + this.delim = delim; + this.policy = policy; + this.encoding = encoding; + this.has_header = has_header; + this.comment_prefix = comment_prefix; + this.stream = null; + this.record_iterator = null; + + this.options = options; + this.bulk_input_path = null; + this.table_path = null; + } + + get_iterator_by_table_id(table_id) { + this.table_path = find_table_path(this.input_file_dir, table_id); + if (this.table_path === null) { + throw new RbqlIOHandlingError(`Unable to find join table "${table_id}"`); + } + if (this.options && this.options['bulk_read']) { + this.bulk_input_path = this.table_path; + } else { + this.stream = fs.createReadStream(this.table_path); + } + this.record_iterator = new CSVRecordIterator(this.stream, this.bulk_input_path, this.encoding, this.delim, this.policy, this.has_header, this.comment_prefix, table_id, 'b'); + return this.record_iterator; + }; + + get_warnings(output_warnings) { + if (this.record_iterator && this.has_header) { + output_warnings.push(`The first record in JOIN file ${path.basename(this.table_path)} was also treated as header (and skipped)`); + } + } +} + + +async function query_csv(query_text, input_path, input_delim, input_policy, output_path, output_delim, output_policy, csv_encoding, output_warnings, with_headers=false, comment_prefix=null, user_init_code='', options=null) { + let input_stream = null; + let bulk_input_path = null; + if (options && options['bulk_read'] && input_path) { + bulk_input_path = input_path; + } else { + input_stream = input_path === null ? process.stdin : fs.createReadStream(input_path); + } + let [output_stream, close_output_on_finish] = output_path === null ? [process.stdout, false] : [fs.createWriteStream(output_path), true]; + if (input_delim == '"' && input_policy == 'quoted') + throw new RbqlIOHandlingError('Double quote delimiter is incompatible with "quoted" policy'); + if (csv_encoding == 'latin-1') + csv_encoding = 'binary'; + if (!is_ascii(query_text) && csv_encoding == 'binary') + throw new RbqlIOHandlingError('To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary'); + if ((!is_ascii(input_delim) || !is_ascii(output_delim)) && csv_encoding == 'binary') + throw new RbqlIOHandlingError('To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary'); + + let default_init_source_path = path.join(os.homedir(), '.rbql_init_source.js'); + if (user_init_code == '' && fs.existsSync(default_init_source_path)) { + user_init_code = read_user_init_code(default_init_source_path); + } + let input_file_dir = input_path ? path.dirname(input_path) : null; + let join_tables_registry = new FileSystemCSVRegistry(input_file_dir, input_delim, input_policy, csv_encoding, with_headers, comment_prefix, options); + let input_iterator = new CSVRecordIterator(input_stream, bulk_input_path, csv_encoding, input_delim, input_policy, with_headers, comment_prefix); + let output_writer = new CSVWriter(output_stream, close_output_on_finish, csv_encoding, output_delim, output_policy); + + await rbql.query(query_text, input_iterator, output_writer, output_warnings, join_tables_registry, user_init_code); + join_tables_registry.get_warnings(output_warnings); +} + + +module.exports.is_ascii = is_ascii; +module.exports.CSVRecordIterator = CSVRecordIterator; +module.exports.CSVWriter = CSVWriter; +module.exports.FileSystemCSVRegistry = FileSystemCSVRegistry; +module.exports.interpret_named_csv_format = interpret_named_csv_format; +module.exports.read_user_init_code = read_user_init_code; +module.exports.query_csv = query_csv; +module.exports.RecordQueue = RecordQueue; +module.exports.exception_to_error_info = rbql.exception_to_error_info; diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/__init__.py b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/__init__.py new file mode 100644 index 00000000..0bc59a72 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/__init__.py @@ -0,0 +1,11 @@ +from .rbql_engine import query +from .rbql_engine import query_table +from .rbql_engine import exception_to_error_info + +from ._version import __version__ + +from .rbql_csv import query_csv + +from .rbql_pandas import query_dataframe as query_pandas_dataframe + +from .rbql_ipython import load_ipython_extension diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/__main__.py b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/__main__.py new file mode 100644 index 00000000..1defb94b --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/__main__.py @@ -0,0 +1,2 @@ +from .rbql_main import main +main() diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/_version.py b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/_version.py new file mode 100644 index 00000000..4fbcd0c1 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/_version.py @@ -0,0 +1,3 @@ +# Explanation of this file purpose: https://stackoverflow.com/a/16084844/2898283 +__version__ = '0.25.0' + diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/csv_utils.py b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/csv_utils.py new file mode 100644 index 00000000..c0e102ad --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/csv_utils.py @@ -0,0 +1,114 @@ +from __future__ import unicode_literals +from __future__ import print_function +import re + + +newline_rgx = re.compile('(?:\r\n)|\r|\n') + +field_regular_expression = '"((?:[^"]*"")*[^"]*)"' +field_rgx = re.compile(field_regular_expression) +field_rgx_external_whitespaces = re.compile(' *' + field_regular_expression + ' *') + + +def extract_next_field(src, dlm, preserve_quotes_and_whitespaces, allow_external_whitespaces, cidx, result): + warning = False + rgx = field_rgx_external_whitespaces if allow_external_whitespaces else field_rgx + match_obj = rgx.match(src, cidx) + if match_obj is not None: + match_end = match_obj.span()[1] + if match_end == len(src) or src[match_end] == dlm: + if preserve_quotes_and_whitespaces: + result.append(match_obj.group(0)) + else: + result.append(match_obj.group(1).replace('""', '"')) + return (match_end + 1, False) + warning = True + uidx = src.find(dlm, cidx) + if uidx == -1: + uidx = len(src) + field = src[cidx:uidx] + warning = warning or field.find('"') != -1 + result.append(field) + return (uidx + 1, warning) + + + +def split_quoted_str(src, dlm, preserve_quotes_and_whitespaces=False): + # This function is newline-agnostic i.e. it can also split records with multiline fields. + assert dlm != '"' + if src.find('"') == -1: # Optimization for most common case + return (src.split(dlm), False) + result = list() + cidx = 0 + warning = False + allow_external_whitespaces = dlm != ' ' + while cidx < len(src): + extraction_report = extract_next_field(src, dlm, preserve_quotes_and_whitespaces, allow_external_whitespaces, cidx, result) + cidx = extraction_report[0] + warning = warning or extraction_report[1] + + if src[-1] == dlm: + result.append('') + return (result, warning) + + +def split_whitespace_separated_str(src, preserve_whitespaces=False): + rgxp = re.compile(" *[^ ]+ *") if preserve_whitespaces else re.compile("[^ ]+") + result = [] + for m in rgxp.finditer(src): + result.append(m.group()) + if preserve_whitespaces and len(result) > 1: + for i in range(len(result) - 1): + result[i] = result[i][:-1] + return result + + +def smart_split(src, dlm, policy, preserve_quotes_and_whitespaces): + if policy == 'simple': + return (src.split(dlm), False) + if policy == 'whitespace': + return (split_whitespace_separated_str(src, preserve_quotes_and_whitespaces), False) + if policy == 'monocolumn': + return ([src], False) + return split_quoted_str(src, dlm, preserve_quotes_and_whitespaces) + + +def extract_line_from_data(data): + mobj = newline_rgx.search(data) + if mobj is None: + return (None, None, data) + pos_start, pos_end = mobj.span() + str_before = data[:pos_start] + str_after = data[pos_end:] + return (str_before, mobj.group(0), str_after) + + +def quote_field(src, delim): + if src.find('"') != -1: + return '"{}"'.format(src.replace('"', '""')) + if src.find(delim) != -1: + return '"{}"'.format(src) + return src + + +def rfc_quote_field(src, delim): + # A single regexp can be used to find all 4 characters simultaneously, but this approach doesn't significantly improve performance according to my tests. + if src.find('"') != -1: + return '"{}"'.format(src.replace('"', '""')) + if src.find(delim) != -1 or src.find('\n') != -1 or src.find('\r') != -1: + return '"{}"'.format(src) + return src + + +def unquote_field(field): + field_rgx_external_whitespaces_full = re.compile('^ *'+ field_regular_expression + ' *$') + match_obj = field_rgx_external_whitespaces_full.match(field) + if match_obj is not None: + return match_obj.group(1).replace('""', '"') + return field + + +def unquote_fields(fields): + return [unquote_field(f) for f in fields] + + diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_csv.py b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_csv.py new file mode 100644 index 00000000..307e7f4a --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_csv.py @@ -0,0 +1,584 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals +from __future__ import print_function + +import sys +import os +import codecs +import io +from errno import EPIPE + +from . import rbql_engine +from . import csv_utils + + +PY3 = sys.version_info[0] == 3 +polymorphic_xrange = range if PY3 else xrange + +default_csv_encoding = 'utf-8' +ansi_reset_color_code = '\u001b[0m' + +debug_mode = False + +try: + broken_pipe_exception = BrokenPipeError +except NameError: # Python 2 + broken_pipe_exception = IOError + + +def is_ascii(s): + return all(ord(c) < 128 for c in s) + + +def read_user_init_code(rbql_init_source_path): + with open(rbql_init_source_path) as src: + return src.read() + + +def normalize_delim(delim): + if delim == 'TAB': + return '\t' + if delim == r'\t': + return '\t' + return delim + + +def interpret_named_csv_format(format_name): + format_name = format_name.lower() + if format_name == 'monocolumn': + return ('', 'monocolumn') + if format_name == 'csv': + return (',', 'quoted') + if format_name == 'tsv': + return ('\t', 'simple') + raise RuntimeError('Unknown format name: "{}"'.format(format_name)) + + + +def encode_input_stream(stream, encoding): + if encoding is None: + return stream + if PY3: + # Reference: https://stackoverflow.com/a/16549381/2898283 + # typical stream (e.g. sys.stdin) in Python 3 is actually a io.TextIOWrapper but with some unknown encoding + try: + return io.TextIOWrapper(stream.buffer, encoding=encoding) + except AttributeError: + # BytesIO doesn't have "buffer" + return io.TextIOWrapper(stream, encoding=encoding) + else: + # Reference: https://stackoverflow.com/a/27425797/2898283 + # Python 2 streams don't have stream.buffer and therefore we can't use io.TextIOWrapper. Instead we use codecs + return codecs.getreader(encoding)(stream) + + +def encode_output_stream(stream, encoding): + if encoding is None: + return stream + if PY3: + try: + return io.TextIOWrapper(stream.buffer, encoding=encoding) + except AttributeError: + # BytesIO doesn't have "buffer" + return io.TextIOWrapper(stream, encoding=encoding) + else: + return codecs.getwriter(encoding)(stream) + + +def remove_utf8_bom(line, assumed_source_encoding): + if assumed_source_encoding == 'latin-1' and len(line) >= 3 and line[:3] == '\xef\xbb\xbf': + return line[3:] + # TODO consider replacing "utf-8" with "utf-8-sig" to automatically remove BOM, see https://stackoverflow.com/a/44573867/2898283 + if assumed_source_encoding == 'utf-8' and len(line) >= 1 and line[0] == u'\ufeff': + return line[1:] + return line + + +def try_read_index(index_path): + lines = [] + try: + with open(index_path) as f: + lines = f.readlines() + except Exception: + return [] + result = list() + for line in lines: + line = line.rstrip('\r\n') + record = line.split('\t') + result.append(record) + return result + + +def get_index_record(index_path, key): + records = try_read_index(index_path) + for record in records: + if len(record) and record[0] == key: + return record + return None + + +def find_table_path(main_table_dir, table_id): + # If table_id is a relative path it could be relative either to the current directory or to the main table dir. + candidate_path = os.path.expanduser(table_id) + if os.path.exists(candidate_path): + return candidate_path + if main_table_dir and not os.path.isabs(candidate_path): + candidate_path = os.path.join(main_table_dir, candidate_path) + if os.path.exists(candidate_path): + return candidate_path + user_home_dir = os.path.expanduser('~') + table_names_settings_path = os.path.join(user_home_dir, '.rbql_table_names') + name_record = get_index_record(table_names_settings_path, table_id) + if name_record is not None and len(name_record) > 1 and os.path.exists(name_record[1]): + return name_record[1] + return None + + +def make_inconsistent_num_fields_warning(table_name, inconsistent_records_info): + assert len(inconsistent_records_info) > 1 + inconsistent_records_info = inconsistent_records_info.items() + inconsistent_records_info = sorted(inconsistent_records_info, key=lambda v: v[1]) + num_fields_1, record_num_1 = inconsistent_records_info[0] + num_fields_2, record_num_2 = inconsistent_records_info[1] + warn_msg = 'Number of fields in "{}" table is not consistent: '.format(table_name) + warn_msg += 'e.g. record {} -> {} fields, record {} -> {} fields'.format(record_num_1, num_fields_1, record_num_2, num_fields_2) + return warn_msg + + +def init_ansi_terminal_colors(): + result = [ansi_reset_color_code] + foreground_codes = list(range(31, 37 + 1)) + background_codes = list(range(41, 47 + 1)) + for fc in foreground_codes: + result.append('\u001b[{}m'.format(fc)) + for fc in foreground_codes: + for bc in background_codes: + if fc % 10 == bc % 10: + continue + if fc % 10 in [2, 6] and bc % 10 in [2, 6]: # Skipping green - cyan pair cause they might have low contrast + continue + result.append('\u001b[{};{}m'.format(fc, bc)) + return result + + + +class CSVWriter(rbql_engine.RBQLOutputWriter): + def __init__(self, stream, close_stream_on_finish, encoding, delim, policy, line_separator='\n', colorize_output=False): + assert encoding in ['utf-8', 'latin-1', None] + self.stream = encode_output_stream(stream, encoding) + self.line_separator = line_separator + self.delim = delim + self.sub_array_delim = '|' if delim != '|' else ';' + self.broken_pipe = False + self.close_stream_on_finish = close_stream_on_finish + self.polymorphic_preprocess = None + self.polymorphic_join = self.join_by_delim + self.check_separators_after_join = False + self.colors = None + if policy == 'simple' or policy == 'whitespace': + if colorize_output: + self.polymorphic_preprocess = self.check_separators_in_fields_before_join + else: + self.check_separators_after_join = True + elif policy == 'quoted': + self.polymorphic_preprocess = self.quote_fields + elif policy == 'quoted_rfc': + self.polymorphic_preprocess = self.quote_fields_rfc + elif policy == 'monocolumn': + colorize_output = False + self.polymorphic_preprocess = self.ensure_single_field + self.polymorphic_join = self.monocolumn_join + else: + raise RuntimeError('unknown output csv policy') + + if colorize_output: + self.colors = init_ansi_terminal_colors() + + self.none_in_output = False + self.delim_in_simple_output = False + self.header_len = None + + + def set_header(self, header): + if header is not None: + self.header_len = len(header) + self.write(header) + + + def monocolumn_join(self, fields): + return fields[0] + + + def check_separators_in_fields_before_join(self, fields): + if ''.join(fields).find(self.delim) != -1: + self.delim_in_simple_output = True + + + def check_separator_in_fields_after_join(self, output_line, num_fields_expected): + num_fields_calculated = output_line.count(self.delim) + 1 + if num_fields_calculated != num_fields_expected: + self.delim_in_simple_output = True + + + def join_by_delim(self, fields): + return self.delim.join(fields) + + + def write(self, fields): + if self.header_len is not None and len(fields) != self.header_len: + raise rbql_engine.RbqlIOHandlingError('Inconsistent number of columns in output header and the current record: {} != {}'.format(self.header_len, len(fields))) + self.normalize_fields(fields) + + if self.polymorphic_preprocess is not None: + self.polymorphic_preprocess(fields) + + if self.colors is not None: + self.colorize_fields(fields) + + out_line = self.polymorphic_join(fields) + + if self.check_separators_after_join: + self.check_separator_in_fields_after_join(out_line, len(fields)) + + try: + self.stream.write(out_line) + if self.colors is not None: + self.stream.write(ansi_reset_color_code) + self.stream.write(self.line_separator) + return True + except broken_pipe_exception as exc: + if broken_pipe_exception == IOError: + if exc.errno != EPIPE: + raise + self.broken_pipe = True + return False + + + def colorize_fields(self, fields): + for i in polymorphic_xrange(len(fields)): + fields[i] = self.colors[i % len(self.colors)] + fields[i] + + + def quote_fields(self, fields): + for i in polymorphic_xrange(len(fields)): + fields[i] = csv_utils.quote_field(fields[i], self.delim) + + + def quote_fields_rfc(self, fields): + for i in polymorphic_xrange(len(fields)): + fields[i] = csv_utils.rfc_quote_field(fields[i], self.delim) + + + def ensure_single_field(self, fields): + if len(fields) > 1: + raise rbql_engine.RbqlIOHandlingError('Unable to use "Monocolumn" output format: some records have more than one field') + + + def normalize_fields(self, fields): + for i in polymorphic_xrange(len(fields)): + if PY3 and isinstance(fields[i], str): + continue + elif not PY3 and isinstance(fields[i], basestring): + continue + elif fields[i] is None: + fields[i] = '' + self.none_in_output = True + elif isinstance(fields[i], list): + self.normalize_fields(fields[i]) + fields[i] = self.sub_array_delim.join(fields[i]) + else: + fields[i] = str(fields[i]) + + + def _write_all(self, table): + for record in table: + self.write(record[:]) + self.finish() + + + def finish(self): + if self.broken_pipe: + return + if self.close_stream_on_finish: + self.stream.close() + else: + try: + self.stream.flush() # This flush still can throw if all flushes before were sucessfull! And the exceptions would be printed anyway, even if it was explicitly catched just couple of lines after. + # Basically this fails if output is small and this is the first flush after the pipe was broken e.g. second flush if piped to head -n 1 + # Here head -n 1 finished after the first flush, and the final explict flush here just killing it + except broken_pipe_exception as exc: + if broken_pipe_exception == IOError: + if exc.errno != EPIPE: + raise + # In order to avoid BrokenPipeError from being printed as a warning to stderr, we need to perform this magic below. See: + # Explanation 1: https://stackoverflow.com/a/35761190/2898283 + # Explanation 2: https://bugs.python.org/issue11380 + try: + sys.stdout.close() + except Exception: + pass + + + def get_warnings(self): + result = list() + if self.none_in_output: + result.append('None values in output were replaced by empty strings') + if self.delim_in_simple_output: + result.append('Some output fields contain separator') + return result + + +class CSVRecordIterator(rbql_engine.RBQLInputIterator): + def __init__(self, stream, encoding, delim, policy, has_header=False, comment_prefix=None, table_name='input', variable_prefix='a', chunk_size=1024, line_mode=False): + assert encoding in ['utf-8', 'latin-1', None] + self.encoding = encoding + self.stream = encode_input_stream(stream, encoding) + self.delim = delim + self.policy = policy + self.table_name = table_name + self.variable_prefix = variable_prefix + self.comment_prefix = comment_prefix if (comment_prefix is not None and len(comment_prefix)) else None + + self.buffer = '' + self.detected_line_separator = '\n' + self.exhausted = False + self.NR = 0 # Record number + self.NL = 0 # Line number (NL != NR when the CSV file has comments or multiline fields) + self.chunk_size = chunk_size + self.fields_info = dict() + + self.utf8_bom_removed = False + self.first_defective_line = None + self.polymorphic_get_row = self.get_row_rfc if policy == 'quoted_rfc' else self.get_row_simple + self.has_header = has_header + self.first_record_should_be_emitted = False + + if not line_mode: + self.first_record = None + self.first_record = self.get_record() + self.first_record_should_be_emitted = not has_header + + + def handle_query_modifier(self, modifier): + # For `... WITH (header) ...` syntax + if modifier in ['header', 'headers']: + self.has_header = True + self.first_record_should_be_emitted = False + if modifier in ['noheader', 'noheaders']: + self.has_header = False + self.first_record_should_be_emitted = True + + + def get_variables_map(self, query_text): + variable_map = dict() + rbql_engine.parse_basic_variables(query_text, self.variable_prefix, variable_map) + rbql_engine.parse_array_variables(query_text, self.variable_prefix, variable_map) + if self.has_header and self.first_record is not None: + rbql_engine.parse_attribute_variables(query_text, self.variable_prefix, self.first_record, 'CSV header line', variable_map) + rbql_engine.parse_dictionary_variables(query_text, self.variable_prefix, self.first_record, variable_map) + return variable_map + + def get_header(self): + return self.first_record if self.has_header else None + + def _get_row_from_buffer(self): + str_before, separator, str_after = csv_utils.extract_line_from_data(self.buffer) + if separator is None: + return None + if separator == '\r' and str_after == '': + one_more = self.stream.read(1) + if one_more == '\n': + separator = '\r\n' + else: + str_after = one_more + self.detected_line_separator = separator + self.buffer = str_after + return str_before + + + def _read_until_found(self): + if self.exhausted: + return + chunks = [] + while True: + chunk = self.stream.read(self.chunk_size) + if not chunk: + self.exhausted = True + break + chunks.append(chunk) + if csv_utils.newline_rgx.search(chunk) is not None: + break + self.buffer += ''.join(chunks) + + + def get_row_simple(self): + try: + row = self._get_row_from_buffer() + if row is None: + self._read_until_found() + row = self._get_row_from_buffer() + if row is None: + assert self.exhausted + if not len(self.buffer): + return None + row = self.buffer + self.buffer = '' + self.NL += 1 + if self.NL == 1: + clean_line = remove_utf8_bom(row, self.encoding) + if clean_line != row: + row = clean_line + self.utf8_bom_removed = True + return row + except UnicodeDecodeError: + raise rbql_engine.RbqlIOHandlingError('Unable to decode input table as UTF-8. Use binary (latin-1) encoding instead') + + + def get_row_rfc(self): + first_row = self.get_row_simple() + if first_row is None: + return None + if self.comment_prefix is not None and first_row.startswith(self.comment_prefix): + return first_row + if first_row.count('"') % 2 == 0: + return first_row + rows_buffer = [first_row] + while True: + row = self.get_row_simple() + if row is None: + return '\n'.join(rows_buffer) + rows_buffer.append(row) + if row.count('"') % 2 == 1: + return '\n'.join(rows_buffer) + + + def get_record(self): + if self.first_record_should_be_emitted: + self.first_record_should_be_emitted = False + return self.first_record + while True: + line = self.polymorphic_get_row() + if line is None: + return None + if self.comment_prefix is None or not line.startswith(self.comment_prefix): + break + self.NR += 1 + record, warning = csv_utils.smart_split(line, self.delim, self.policy, preserve_quotes_and_whitespaces=False) + if warning: + if self.first_defective_line is None: + self.first_defective_line = self.NL + if self.policy == 'quoted_rfc': + raise rbql_engine.RbqlIOHandlingError('Inconsistent double quote escaping in {} table at record {}, line {}'.format(self.table_name, self.NR, self.NL)) + num_fields = len(record) + if num_fields not in self.fields_info: + self.fields_info[num_fields] = self.NR + return record + + + def _get_all_rows(self): + result = [] + while True: + row = self.polymorphic_get_row() + if row is None: + break + result.append(row) + return result + + + def get_all_records(self, num_rows=None): + result = [] + while True: + record = self.get_record() + if record is None: + break + result.append(record) + if num_rows is not None and len(result) >= num_rows: + break + return result + + + def get_warnings(self): + result = list() + if self.utf8_bom_removed: + result.append('UTF-8 Byte Order Mark (BOM) was found and skipped in {} table'.format(self.table_name)) + if self.first_defective_line is not None: + result.append('Inconsistent double quote escaping in {} table. E.g. at line {}'.format(self.table_name, self.first_defective_line)) + if len(self.fields_info) > 1: + result.append(make_inconsistent_num_fields_warning(self.table_name, self.fields_info)) + return result + + +class FileSystemCSVRegistry(rbql_engine.RBQLTableRegistry): + def __init__(self, input_file_dir, delim, policy, encoding, has_header, comment_prefix): + self.input_file_dir = input_file_dir + self.delim = delim + self.policy = policy + self.encoding = encoding + self.record_iterator = None + self.input_stream = None + self.has_header = has_header + self.comment_prefix = comment_prefix + self.table_path = None + + def get_iterator_by_table_id(self, table_id, single_char_alias): + self.table_path = find_table_path(self.input_file_dir, table_id) + if self.table_path is None: + raise rbql_engine.RbqlIOHandlingError('Unable to find join table "{}"'.format(table_id)) + self.input_stream = open(self.table_path, 'rb') + self.record_iterator = CSVRecordIterator(self.input_stream, self.encoding, self.delim, self.policy, self.has_header, comment_prefix=self.comment_prefix, table_name=table_id, variable_prefix=single_char_alias) + return self.record_iterator + + def finish(self): + if self.input_stream is not None: + self.input_stream.close() + + def get_warnings(self): + result = [] + if self.record_iterator is not None and self.has_header: + result.append('The first record in JOIN file {} was also treated as header (and skipped)'.format(os.path.basename(self.table_path))) # UT JSON CSV + return result + + +def query_csv(query_text, input_path, input_delim, input_policy, output_path, output_delim, output_policy, csv_encoding, output_warnings, with_headers, comment_prefix=None, user_init_code='', colorize_output=False): + output_stream, close_output_on_finish = (None, False) + input_stream, close_input_on_finish = (None, False) + join_tables_registry = None + try: + output_stream, close_output_on_finish = (sys.stdout, False) if output_path is None else (open(output_path, 'wb'), True) + input_stream, close_input_on_finish = (sys.stdin, False) if input_path is None else (open(input_path, 'rb'), True) + + if input_delim == '"' and input_policy == 'quoted': + raise rbql_engine.RbqlIOHandlingError('Double quote delimiter is incompatible with "quoted" policy') + if input_delim != ' ' and input_policy == 'whitespace': + raise rbql_engine.RbqlIOHandlingError('Only whitespace " " delim is supported with "whitespace" policy') + + if not is_ascii(query_text) and csv_encoding == 'latin-1': + raise rbql_engine.RbqlIOHandlingError('To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary') + + if (not is_ascii(input_delim) or not is_ascii(output_delim)) and csv_encoding == 'latin-1': + raise rbql_engine.RbqlIOHandlingError('To use non-ascii separators enable UTF-8 encoding instead of latin-1/binary') + + default_init_source_path = os.path.join(os.path.expanduser('~'), '.rbql_init_source.py') + if user_init_code == '' and os.path.exists(default_init_source_path): + user_init_code = read_user_init_code(default_init_source_path) + + input_file_dir = None if not input_path else os.path.dirname(input_path) + join_tables_registry = FileSystemCSVRegistry(input_file_dir, input_delim, input_policy, csv_encoding, with_headers, comment_prefix) + input_iterator = CSVRecordIterator(input_stream, csv_encoding, input_delim, input_policy, with_headers, comment_prefix=comment_prefix) + output_writer = CSVWriter(output_stream, close_output_on_finish, csv_encoding, output_delim, output_policy, colorize_output=colorize_output) + if debug_mode: + rbql_engine.set_debug_mode() + rbql_engine.query(query_text, input_iterator, output_writer, output_warnings, join_tables_registry, user_init_code) + finally: + if close_input_on_finish: + input_stream.close() + if close_output_on_finish: + output_stream.close() + if join_tables_registry: + join_tables_registry.finish() + output_warnings += join_tables_registry.get_warnings() + + +def set_debug_mode(): + global debug_mode + debug_mode = True diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_engine.py b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_engine.py new file mode 100644 index 00000000..f51ceed0 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_engine.py @@ -0,0 +1,1662 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals +from __future__ import print_function + +import sys +import re +import ast +from collections import OrderedDict, defaultdict, namedtuple + +import random # For usage inside user queries only. +import datetime # For usage inside user queries only. +import os # For usage inside user queries only. +import math # For usage inside user queries only. +import time # For usage inside user queries only. + +from ._version import __version__ + +# This module must be both python2 and python3 compatible. +# This module works with records only. It is CSV-agnostic. +# Do not add CSV-related logic or variables/functions/objects like "delim", "separator" etc. +# See DEV_README.md for additional info. + +# UT JSON - means json Unit Test exists for this case. +# UT JSON CSV - means json csv Unit Test exists for this case. + +GROUP_BY = 'GROUP BY' +UPDATE = 'UPDATE' +SELECT = 'SELECT' +JOIN = 'JOIN' +INNER_JOIN = 'INNER JOIN' +LEFT_JOIN = 'LEFT JOIN' +LEFT_OUTER_JOIN = 'LEFT OUTER JOIN' +STRICT_LEFT_JOIN = 'STRICT LEFT JOIN' +ORDER_BY = 'ORDER BY' +WHERE = 'WHERE' +LIMIT = 'LIMIT' +EXCEPT = 'EXCEPT' +WITH = 'WITH' +FROM = 'FROM' + +default_statement_groups = [[STRICT_LEFT_JOIN, LEFT_OUTER_JOIN, LEFT_JOIN, INNER_JOIN, JOIN], [SELECT], [ORDER_BY], [WHERE], [UPDATE], [GROUP_BY], [LIMIT], [EXCEPT], [FROM]] + +ambiguous_error_msg = 'Ambiguous variable name: "{}" is present both in input and in join tables' +invalid_keyword_in_aggregate_query_error_msg = '"ORDER BY", "UPDATE" and "DISTINCT" keywords are not allowed in aggregate queries' +wrong_aggregation_usage_error = 'Usage of RBQL aggregation functions inside Python expressions is not allowed, see the docs' +numeric_conversion_error = 'Unable to convert value "{}" to int or float. MIN, MAX, SUM, AVG, MEDIAN and VARIANCE aggregate functions convert their string arguments to numeric values' + +PY3 = sys.version_info[0] == 3 + +RBQL_VERSION = __version__ + +debug_mode = False + +class RbqlRuntimeError(Exception): + pass + +class RbqlParsingError(Exception): + pass + +class RbqlIOHandlingError(Exception): + pass + + +class InternalBadFieldError(Exception): + def __init__(self, bad_idx): + self.bad_idx = bad_idx + + +class InternalBadKeyError(Exception): + def __init__(self, bad_key): + self.bad_key = bad_key + + +VariableInfo = namedtuple('VariableInfo', ['initialize', 'index']) + + +class RBQLContext: + def __init__(self, input_iterator, output_writer, user_init_code): + self.input_iterator = input_iterator + self.writer = output_writer + self.user_init_code = user_init_code + + self.unnest_list = None + self.top_count = None + + self.like_regex_cache = dict() + + self.sort_key_expression = None + + self.aggregation_stage = 0 + self.aggregation_key_expression = None + self.functional_aggregators = [] + + self.join_map_impl = None + self.join_map = None + self.lhs_join_var_expression = None + + self.where_expression = None + + self.select_expression = None + + self.update_expressions = None + + self.variables_init_code = None + + +def is_str6(val): + return (PY3 and isinstance(val, str)) or (not PY3 and isinstance(val, basestring)) + + +QueryColumnInfo = namedtuple('QueryColumnInfo', ['table_name', 'column_index', 'column_name', 'is_star']) + + +def get_field(root, field_name): + for f in ast.iter_fields(root): + if len(f) == 2 and f[0] == field_name: + return f[1] + return None + + +def column_info_from_node(root): + rbql_star_marker = '__RBQL_INTERNAL_STAR' + if isinstance(root, ast.Name): + var_name = get_field(root, 'id') + if var_name is None: + return None + if var_name == rbql_star_marker: + return QueryColumnInfo(table_name=None, column_index=None, column_name=None, is_star=True) + good_column_name_rgx = '^([ab])([0-9][0-9]*)$' + match_obj = re.match(good_column_name_rgx, var_name) + if match_obj is not None: + table_name = match_obj.group(1) + column_index = int(match_obj.group(2)) - 1 + return QueryColumnInfo(table_name=table_name, column_index=column_index, column_name=None, is_star=False) + # Some examples for this branch: NR, NF + return QueryColumnInfo(table_name=None, column_index=None, column_name=var_name, is_star=False) + if isinstance(root, ast.Attribute): + column_name = get_field(root, 'attr') + if not column_name: + return None + if not is_str6(column_name): + return None + var_root = get_field(root, 'value') + if not isinstance(var_root, ast.Name): + return None + table_name = get_field(var_root, 'id') + if table_name is None or table_name not in ['a', 'b']: + return None + if column_name == rbql_star_marker: + return QueryColumnInfo(table_name=table_name, column_index=None, column_name=None, is_star=True) + return QueryColumnInfo(table_name=None, column_index=None, column_name=column_name, is_star=False) + if isinstance(root, ast.Subscript): + var_root = get_field(root, 'value') + if not isinstance(var_root, ast.Name): + return None + table_name = get_field(var_root, 'id') + if table_name is None or table_name not in ['a', 'b']: + return None + slice_root = get_field(root, 'slice') + if slice_root is None or not isinstance(slice_root, ast.Index): + return None + slice_val_root = get_field(slice_root, 'value') + column_index = None + column_name = None + if isinstance(slice_val_root, ast.Str): + column_name = get_field(slice_val_root, 's') + table_name = None # We don't need table name for named fields + elif isinstance(slice_val_root, ast.Num): + column_index = get_field(slice_val_root, 'n') - 1 + else: + return None + if not PY3 and isinstance(column_name, str): + column_name = column_name.decode('utf-8') + return QueryColumnInfo(table_name=table_name, column_index=column_index, column_name=column_name, is_star=False) + return None + + +def ast_parse_select_expression_to_column_infos(select_expression): + root = ast.parse(select_expression) + children = list(ast.iter_child_nodes(root)) + if 'body' not in root._fields: + raise RbqlParsingError('Unable to parse SELECT expression (error code #117)') # Should never happen + if len(children) != 1: + raise RbqlParsingError('Unable to parse SELECT expression (error code #118)') # Should never happen + root = children[0] + children = list(ast.iter_child_nodes(root)) + if len(children) != 1: + raise RbqlParsingError('Unable to parse SELECT expression (error code #119): "{}"'.format(select_expression)) # This can be triggered with `SELECT a = 100` + root = children[0] + if isinstance(root, ast.Tuple): + column_expression_trees = root.elts + column_infos = [column_info_from_node(ct) for ct in column_expression_trees] + else: + column_infos = [column_info_from_node(root)] + return column_infos + + +def iteritems6(x): + if PY3: + return x.items() + return x.iteritems() + + +class RBQLRecord: + def __init__(self): + self.storage = dict() + + def __getitem__(self, key): + try: + return self.storage[key] + except KeyError: + raise InternalBadKeyError(key) + + def __setitem__(self, key, value): + self.storage[key] = value + + +def safe_get(record, idx): + return record[idx] if idx < len(record) else None + + +def safe_join_get(record, idx): + try: + return record[idx] + except IndexError: + raise InternalBadFieldError(idx) + + +def safe_set(record, idx, value): + try: + record[idx] = value + except IndexError: + raise InternalBadFieldError(idx) + + +def like_to_regex(pattern): + p = 0 + i = 0 + converted = '' + while i < len(pattern): + if pattern[i] in ['_', '%']: + converted += re.escape(pattern[p:i]) + p = i + 1 + if pattern[i] == '_': + converted += '.' + else: + converted += '.*' + i += 1 + converted += re.escape(pattern[p:i]) + return '^' + converted + '$' + + +class RBQLAggregationToken(object): + def __init__(self, marker_id, value): + self.marker_id = marker_id + self.value = value + + def __str__(self): + raise TypeError('RBQLAggregationToken') + + +class NumHandler: + def __init__(self, start_with_int): + self.is_int = start_with_int + self.string_detection_done = False + self.is_str = False + + def parse(self, val): + if not self.string_detection_done: + self.string_detection_done = True + if is_str6(val): + self.is_str = True + if not self.is_str: + return val + if self.is_int: + try: + return int(val) + except ValueError: + self.is_int = False + try: + return float(val) + except ValueError: + raise RbqlRuntimeError(numeric_conversion_error.format(val)) # UT JSON + + +class MinAggregator: + def __init__(self): + self.stats = dict() + self.num_handler = NumHandler(True) + + def increment(self, key, val): + val = self.num_handler.parse(val) + cur_aggr = self.stats.get(key) + if cur_aggr is None: + self.stats[key] = val + else: + self.stats[key] = min(cur_aggr, val) + + def get_final(self, key): + return self.stats[key] + + +class MaxAggregator: + def __init__(self): + self.stats = dict() + self.num_handler = NumHandler(True) + + def increment(self, key, val): + val = self.num_handler.parse(val) + cur_aggr = self.stats.get(key) + if cur_aggr is None: + self.stats[key] = val + else: + self.stats[key] = max(cur_aggr, val) + + def get_final(self, key): + return self.stats[key] + + +class SumAggregator: + def __init__(self): + self.stats = defaultdict(int) + self.num_handler = NumHandler(True) + + def increment(self, key, val): + val = self.num_handler.parse(val) + self.stats[key] += val + + def get_final(self, key): + return self.stats[key] + + +class AvgAggregator: + def __init__(self): + self.stats = dict() + self.num_handler = NumHandler(False) + + def increment(self, key, val): + val = self.num_handler.parse(val) + cur_aggr = self.stats.get(key) + if cur_aggr is None: + self.stats[key] = (val, 1) + else: + cur_sum, cur_cnt = cur_aggr + self.stats[key] = (cur_sum + val, cur_cnt + 1) + + def get_final(self, key): + final_sum, final_cnt = self.stats[key] + return float(final_sum) / final_cnt + + +class VarianceAggregator: + def __init__(self): + self.stats = dict() + self.num_handler = NumHandler(False) + + def increment(self, key, val): + val = self.num_handler.parse(val) + cur_aggr = self.stats.get(key) + if cur_aggr is None: + self.stats[key] = (val, val ** 2, 1) + else: + cur_sum, cur_sum_of_squares, cur_cnt = cur_aggr + self.stats[key] = (cur_sum + val, cur_sum_of_squares + val ** 2, cur_cnt + 1) + + def get_final(self, key): + final_sum, final_sum_of_squares, final_cnt = self.stats[key] + return float(final_sum_of_squares) / final_cnt - (float(final_sum) / final_cnt) ** 2 + + +class MedianAggregator: + def __init__(self): + self.stats = defaultdict(list) + self.num_handler = NumHandler(True) + + def increment(self, key, val): + val = self.num_handler.parse(val) + self.stats[key].append(val) + + def get_final(self, key): + sorted_vals = sorted(self.stats[key]) + assert len(sorted_vals) + m = int(len(sorted_vals) / 2) + if len(sorted_vals) % 2: + return sorted_vals[m] + else: + a = sorted_vals[m - 1] + b = sorted_vals[m] + return a if a == b else (a + b) / 2.0 + + +class CountAggregator: + def __init__(self): + self.stats = defaultdict(int) + + def increment(self, key, _val): + self.stats[key] += 1 + + def get_final(self, key): + return self.stats[key] + + +class ArrayAggAggregator: + def __init__(self, post_proc=None): + self.stats = defaultdict(list) + self.post_proc = post_proc + + def increment(self, key, val): + self.stats[key].append(val) + + def get_final(self, key): + res = self.stats[key] + if self.post_proc is not None: + return self.post_proc(res) + return res + + +class ConstGroupVerifier: + def __init__(self, output_index): + self.const_values = dict() + self.output_index = output_index + + def increment(self, key, value): + old_value = self.const_values.get(key) + if old_value is None: + self.const_values[key] = value + elif old_value != value: + raise RbqlRuntimeError('Invalid aggregate expression: non-constant values in output column {}. E.g. "{}" and "{}"'.format(self.output_index + 1, old_value, value)) # UT JSON + + def get_final(self, key): + return self.const_values[key] + + +def add_to_set(dst_set, value): + len_before = len(dst_set) + dst_set.add(value) + return len_before != len(dst_set) + + +class TopWriter(object): + def __init__(self, subwriter, top_count): + self.subwriter = subwriter + self.NW = 0 + self.top_count = top_count + + def write(self, record): + if self.NW >= self.top_count: + return False + success = self.subwriter.write(record) + if success: + self.NW += 1 + return success + + def finish(self): + self.subwriter.finish() + + +class UniqWriter(object): + def __init__(self, subwriter): + self.subwriter = subwriter + self.seen = set() + + def write(self, record): + immutable_record = tuple(record) + if not add_to_set(self.seen, immutable_record): + return True + if not self.subwriter.write(record): + return False + return True + + def finish(self): + self.subwriter.finish() + + +class UniqCountWriter(object): + def __init__(self, subwriter): + self.subwriter = subwriter + self.records = OrderedDict() + + def write(self, record): + record = tuple(record) + if record in self.records: + self.records[record] += 1 + else: + self.records[record] = 1 + return True + + def finish(self): + for record, cnt in iteritems6(self.records): + mutable_record = list(record) + mutable_record.insert(0, cnt) + if not self.subwriter.write(mutable_record): + break + self.subwriter.finish() + + +class SortedWriter(object): + def __init__(self, subwriter, reverse_sort): + self.subwriter = subwriter + self.reverse_sort = reverse_sort + self.unsorted_entries = list() + + def write(self, sort_key_value, record): + self.unsorted_entries.append((sort_key_value, record)) + return True + + def finish(self): + sorted_entries = sorted(self.unsorted_entries, key=lambda x: x[0]) + if self.reverse_sort: + sorted_entries.reverse() + for e in sorted_entries: + if not self.subwriter.write(e[1]): + break + self.subwriter.finish() + + +class AggregateWriter(object): + def __init__(self, subwriter): + self.subwriter = subwriter + self.aggregators = [] + self.aggregation_keys = set() + + def finish(self): + all_keys = sorted(list(self.aggregation_keys)) + for key in all_keys: + out_fields = [ag.get_final(key) for ag in self.aggregators] + if not self.subwriter.write(out_fields): + break + self.subwriter.finish() + + +class InnerJoiner(object): + def __init__(self, join_map): + self.join_map = join_map + + def get_rhs(self, lhs_key): + return self.join_map.get_join_records(lhs_key) + + +class LeftJoiner(object): + def __init__(self, join_map): + self.join_map = join_map + self.null_record = [(None, join_map.max_record_len, [None] * join_map.max_record_len)] + + def get_rhs(self, lhs_key): + result = self.join_map.get_join_records(lhs_key) + if len(result) == 0: + return self.null_record + return result + + +class StrictLeftJoiner(object): + def __init__(self, join_map): + self.join_map = join_map + + def get_rhs(self, lhs_key): + result = self.join_map.get_join_records(lhs_key) + if len(result) != 1: + raise RbqlRuntimeError('In "{}" each key in A must have exactly one match in B. Bad A key: "{}"'.format(STRICT_LEFT_JOIN, lhs_key)) # UT JSON + return result + + +def select_except(src, except_fields): + result = list() + for i, v in enumerate(src): + if i not in except_fields: + result.append(v) + return result + + +def select_simple(query_context, sort_key, out_fields): + if query_context.sort_key_expression is not None: + if not query_context.writer.write(sort_key, out_fields): + return False + else: + if not query_context.writer.write(out_fields): + return False + return True + + +def select_aggregated(query_context, key, transparent_values): + if query_context.aggregation_stage == 1: + if type(query_context.writer) is SortedWriter or type(query_context.writer) is UniqWriter or type(query_context.writer) is UniqCountWriter: + raise RbqlParsingError(invalid_keyword_in_aggregate_query_error_msg) # UT JSON + query_context.writer = AggregateWriter(query_context.writer) + num_aggregators_found = 0 + for i, trans_value in enumerate(transparent_values): + if isinstance(trans_value, RBQLAggregationToken): + num_aggregators_found += 1 + query_context.writer.aggregators.append(query_context.functional_aggregators[trans_value.marker_id]) + query_context.writer.aggregators[-1].increment(key, trans_value.value) + else: + query_context.writer.aggregators.append(ConstGroupVerifier(len(query_context.writer.aggregators))) + query_context.writer.aggregators[-1].increment(key, trans_value) + if num_aggregators_found != len(query_context.functional_aggregators): + raise RbqlParsingError(wrong_aggregation_usage_error) # UT JSON + query_context.aggregation_stage = 2 + else: + for i, trans_value in enumerate(transparent_values): + query_context.writer.aggregators[i].increment(key, trans_value) + query_context.writer.aggregation_keys.add(key) + + +PROCESS_SELECT_COMMON = ''' +__RBQLMP__variables_init_code +if __RBQLMP__where_expression: + out_fields = __RBQLMP__select_expression + if query_context.aggregation_stage > 0: + key = __RBQLMP__aggregation_key_expression + select_aggregated(query_context, key, out_fields) + else: + sort_key = __RBQLMP__sort_key_expression + if query_context.unnest_list is not None: + if not select_unnested(sort_key, out_fields): + stop_flag = True + else: + if not select_simple(query_context, sort_key, out_fields): + stop_flag = True +''' + + +PROCESS_SELECT_SIMPLE = ''' +star_fields = record_a +__CODE__ +''' + + +PROCESS_SELECT_JOIN = ''' +join_matches = query_context.join_map.get_rhs(__RBQLMP__lhs_join_var_expression) +for join_match in join_matches: + bNR, bNF, record_b = join_match + star_fields = record_a + record_b + __CODE__ + if stop_flag: + break +''' + + +PROCESS_UPDATE_JOIN = ''' +join_matches = query_context.join_map.get_rhs(__RBQLMP__lhs_join_var_expression) +if len(join_matches) > 1: + raise RbqlRuntimeError('More than one record in UPDATE query matched a key from the input table in the join table') # UT JSON # TODO output the failed key +if len(join_matches) == 1: + bNR, bNF, record_b = join_matches[0] +else: + bNR, bNF, record_b = None, None, None +up_fields = record_a[:] +__RBQLMP__variables_init_code +if len(join_matches) == 1 and (__RBQLMP__where_expression): + NU += 1 + __RBQLMP__update_expressions +if not query_context.writer.write(up_fields): + stop_flag = True +''' + + +PROCESS_UPDATE_SIMPLE = ''' +up_fields = record_a[:] +__RBQLMP__variables_init_code +if __RBQLMP__where_expression: + NU += 1 + __RBQLMP__update_expressions +if not query_context.writer.write(up_fields): + stop_flag = True +''' + +# We need dummy_wrapper_for_exec function because otherwise "import" statements won't work as expected if used inside user-defined functions, see: https://github.com/mechatroner/sublime_rainbow_csv/issues/22 +MAIN_LOOP_BODY = ''' +def dummy_wrapper_for_exec(query_context, user_namespace, LIKE, UNNEST, MIN, MAX, COUNT, SUM, AVG, VARIANCE, MEDIAN, ARRAY_AGG, mad_max, mad_min, mad_sum, select_unnested): + + try: + pass + __USER_INIT_CODE__ + except Exception as e: + raise RuntimeError('Exception while executing user-provided init code: {}'.format(e)) + + like = LIKE + unnest = UNNEST + Unnest = UNNEST + Min = MIN + Max = MAX + count = COUNT + Count = COUNT + Sum = SUM + avg = AVG + Avg = AVG + variance = VARIANCE + Variance = VARIANCE + median = MEDIAN + Median = MEDIAN + array_agg = ARRAY_AGG + max = mad_max + min = mad_min + sum = mad_sum + + udf = user_namespace + + NR = 0 + NU = 0 + stop_flag = False + + while not stop_flag: + record_a = query_context.input_iterator.get_record() + if record_a is None: + break + NR += 1 + NF = len(record_a) + query_context.unnest_list = None # TODO optimize, don't need to set this every iteration + try: + __CODE__ + except InternalBadKeyError as e: + raise RbqlRuntimeError('No "{}" field at record {}'.format(e.bad_key, NR)) # UT JSON + except InternalBadFieldError as e: + raise RbqlRuntimeError('No "a{}" field at record {}'.format(e.bad_idx + 1, NR)) # UT JSON + except RbqlParsingError: + raise + except Exception as e: + if debug_mode: + raise + if str(e).find('RBQLAggregationToken') != -1: + raise RbqlParsingError(wrong_aggregation_usage_error) # UT JSON + raise RbqlRuntimeError('At record ' + str(NR) + ', Details: ' + str(e)) # UT JSON + +dummy_wrapper_for_exec(query_context, user_namespace, LIKE, UNNEST, MIN, MAX, COUNT, SUM, AVG, VARIANCE, MEDIAN, ARRAY_AGG, mad_max, mad_min, mad_sum, select_unnested) +''' + + +def embed_expression(parent_code, child_placeholder, child_expression): + assert parent_code.count(child_placeholder) == 1 + assert child_expression.find('\n') == -1 + return parent_code.strip().replace(child_placeholder, child_expression) + '\n' + + +def embed_code(parent_code, child_placeholder, child_code): + assert parent_code.count(child_placeholder) == 1 + parent_lines = parent_code.strip().split('\n') + child_lines = child_code.strip().split('\n') + for i in range(len(parent_lines)): + pos = parent_lines[i].find(child_placeholder) + if pos == -1: + continue + assert pos % 4 == 0 + placeholder_indentation = parent_lines[i][:pos] + assert placeholder_indentation == ' ' * pos + child_lines = [placeholder_indentation + cl for cl in child_lines] + result_lines = parent_lines[:i] + child_lines + parent_lines[i + 1:] + return '\n'.join(result_lines) + '\n' + assert False + + +def generate_main_loop_code(query_context): + is_select_query = query_context.select_expression is not None + is_join_query = query_context.join_map is not None + where_expression = 'True' if query_context.where_expression is None else query_context.where_expression + aggregation_key_expression = 'None' if query_context.aggregation_key_expression is None else query_context.aggregation_key_expression + sort_key_expression = 'None' if query_context.sort_key_expression is None else query_context.sort_key_expression + python_code = embed_code(MAIN_LOOP_BODY, '__USER_INIT_CODE__', query_context.user_init_code) + if is_select_query: + if is_join_query: + python_code = embed_code(embed_code(python_code, '__CODE__', PROCESS_SELECT_JOIN), '__CODE__', PROCESS_SELECT_COMMON) + python_code = embed_expression(python_code, '__RBQLMP__lhs_join_var_expression', query_context.lhs_join_var_expression) + else: + python_code = embed_code(embed_code(python_code, '__CODE__', PROCESS_SELECT_SIMPLE), '__CODE__', PROCESS_SELECT_COMMON) + python_code = embed_code(python_code, '__RBQLMP__variables_init_code', query_context.variables_init_code) + python_code = embed_expression(python_code, '__RBQLMP__select_expression', query_context.select_expression) + python_code = embed_expression(python_code, '__RBQLMP__where_expression', where_expression) + python_code = embed_expression(python_code, '__RBQLMP__aggregation_key_expression', aggregation_key_expression) + python_code = embed_expression(python_code, '__RBQLMP__sort_key_expression', sort_key_expression) + else: + if is_join_query: + python_code = embed_code(python_code, '__CODE__', PROCESS_UPDATE_JOIN) + python_code = embed_expression(python_code, '__RBQLMP__lhs_join_var_expression', query_context.lhs_join_var_expression) + else: + python_code = embed_code(python_code, '__CODE__', PROCESS_UPDATE_SIMPLE) + python_code = embed_code(python_code, '__RBQLMP__variables_init_code', query_context.variables_init_code) + python_code = embed_code(python_code, '__RBQLMP__update_expressions', query_context.update_expressions) + python_code = embed_expression(python_code, '__RBQLMP__where_expression', where_expression) + return python_code + + +builtin_max = max +builtin_min = min +builtin_sum = sum + + +def compile_and_run(query_context, user_namespace, unit_test_mode=False): + def LIKE(text, pattern): + matcher = query_context.like_regex_cache.get(pattern, None) + if matcher is None: + matcher = re.compile(like_to_regex(pattern)) + query_context.like_regex_cache[pattern] = matcher + return matcher.match(text) is not None + + class UNNEST: + def __init__(self, vals): + if query_context.unnest_list is not None: + # Technically we can support multiple UNNEST's but the implementation/algorithm is more complex and just doesn't worth it + raise RbqlParsingError('Only one UNNEST is allowed per query') # UT JSON + query_context.unnest_list = vals + + def __str__(self): + raise TypeError('UNNEST') + + def select_unnested(sort_key, folded_fields): + unnest_pos = None + for i, trans_value in enumerate(folded_fields): + if isinstance(trans_value, UNNEST): + unnest_pos = i + break + assert unnest_pos is not None + for v in query_context.unnest_list: + out_fields = folded_fields[:] + out_fields[unnest_pos] = v + if not select_simple(query_context, sort_key, out_fields): + return False + return True + + def init_aggregator(generator_name, val, post_proc=None): + query_context.aggregation_stage = 1 + res = RBQLAggregationToken(len(query_context.functional_aggregators), val) + if post_proc is not None: + query_context.functional_aggregators.append(generator_name(post_proc)) + else: + query_context.functional_aggregators.append(generator_name()) + return res + + + def MIN(val): + return init_aggregator(MinAggregator, val) if query_context.aggregation_stage < 2 else val + + + + def MAX(val): + return init_aggregator(MaxAggregator, val) if query_context.aggregation_stage < 2 else val + + + def COUNT(_val): + return init_aggregator(CountAggregator, 1) if query_context.aggregation_stage < 2 else 1 + + def SUM(val): + return init_aggregator(SumAggregator, val) if query_context.aggregation_stage < 2 else val + + def AVG(val): + return init_aggregator(AvgAggregator, val) if query_context.aggregation_stage < 2 else val + + def VARIANCE(val): + return init_aggregator(VarianceAggregator, val) if query_context.aggregation_stage < 2 else val + + def MEDIAN(val): + return init_aggregator(MedianAggregator, val) if query_context.aggregation_stage < 2 else val + + def ARRAY_AGG(val, post_proc=None): + # TODO consider passing array to output writer + return init_aggregator(ArrayAggAggregator, val, post_proc) if query_context.aggregation_stage < 2 else val + + + # We use `mad_` prefix with the function names to avoid ovewriting global min/max/sum just yet - this might interfere with logic inside user-defined functions in the init code. + def mad_max(*args, **kwargs): + single_arg = len(args) == 1 and not kwargs + if single_arg: + if PY3 and isinstance(args[0], str): + return MAX(args[0]) + if not PY3 and isinstance(args[0], basestring): + return MAX(args[0]) + if isinstance(args[0], int) or isinstance(args[0], float): + return MAX(args[0]) + try: + return max(*args, **kwargs) + except TypeError: + if single_arg: + return MAX(args[0]) + raise + + + def mad_min(*args, **kwargs): + single_arg = len(args) == 1 and not kwargs + if single_arg: + if PY3 and isinstance(args[0], str): + return MIN(args[0]) + if not PY3 and isinstance(args[0], basestring): + return MIN(args[0]) + if isinstance(args[0], int) or isinstance(args[0], float): + return MIN(args[0]) + try: + return min(*args, **kwargs) + except TypeError: + if single_arg: + return MIN(args[0]) + raise + + + def mad_sum(*args): + try: + return sum(*args) + except TypeError: + if len(args) == 1: + return SUM(args[0]) + raise + + if unit_test_mode: + # Return these 3 functions to be able to unit test them from outside + return (mad_max, mad_min, mad_sum) + + main_loop_body = generate_main_loop_code(query_context) + compiled_main_loop = compile(main_loop_body, '
', 'exec') + exec(compiled_main_loop, globals(), locals()) + + +def exception_to_error_info(e): + exceptions_type_map = { + 'RbqlRuntimeError': 'query execution', + 'RbqlParsingError': 'query parsing', + 'RbqlIOHandlingError': 'IO handling' + } + if isinstance(e, SyntaxError): + import traceback + etype, evalue, _etb = sys.exc_info() + error_strings = traceback.format_exception_only(etype, evalue) + if len(error_strings) and re.search('File.*line', error_strings[0]) is not None: + error_strings[0] = '\n' + error_msg = ''.join(error_strings).rstrip() + if re.search(' having ', error_msg, flags=re.IGNORECASE) is not None: + error_msg += "\nRBQL doesn't support \"HAVING\" keyword" + if re.search(' like[ (]', error_msg, flags=re.IGNORECASE) is not None: + error_msg += "\nRBQL doesn't support \"LIKE\" operator, use like() function instead e.g. ... WHERE like(a1, 'foo%bar') ... " # UT JSON + if error_msg.lower().find(' from ') != -1: + error_msg += "\nTip: If input table is defined by the environment, RBQL query should not have \"FROM\" keyword" # UT JSON + return ('syntax error', error_msg) + error_type = 'unexpected' + error_msg = str(e) + for k, v in exceptions_type_map.items(): + if type(e).__name__.find(k) != -1: + error_type = v + return (error_type, error_msg) + + +def strip_comments(cline): + cline = cline.strip() + if cline.startswith('#'): + return '' + return cline + + +def combine_string_literals(backend_expression, string_literals): + for i in range(len(string_literals)): + backend_expression = backend_expression.replace('___RBQL_STRING_LITERAL{}___'.format(i), string_literals[i]) + return backend_expression + + +def parse_join_expression(src): + src = src.strip() + invalid_join_syntax_error = 'Invalid join syntax. Valid syntax: /path/to/B/table on a... == b... [and a... == b... [and ... ]]' + match = re.search(r'^([^ ]+) +on +', src, re.IGNORECASE) + if match is None: + raise RbqlParsingError(invalid_join_syntax_error) + table_id = match.group(1) + src = src[match.end():] + variable_pairs = [] + while True: + match = re.search('^([^ =]+) *==? *([^ =]+)', src) + if match is None: + raise RbqlParsingError(invalid_join_syntax_error) + variable_pair = (match.group(1), match.group(2)) + variable_pairs.append(variable_pair) + src = src[match.end():] + if not len(src): + break + match = re.search('^ +and +', src, re.IGNORECASE) + if match is None: + raise RbqlParsingError(invalid_join_syntax_error) + src = src[match.end():] + return (table_id, variable_pairs) + + +def resolve_join_variables(input_variables_map, join_variables_map, variable_pairs, string_literals): + lhs_variables = [] + rhs_indices = [] + valid_join_syntax_msg = 'Valid JOIN syntax: /path/to/B/table on a... == b... [and a... == b... [and ... ]]' + for join_var_1, join_var_2 in variable_pairs: + join_var_1 = combine_string_literals(join_var_1, string_literals) + join_var_2 = combine_string_literals(join_var_2, string_literals) + if join_var_1 in input_variables_map and join_var_1 in join_variables_map: + raise RbqlParsingError(ambiguous_error_msg.format(join_var_1)) + if join_var_2 in input_variables_map and join_var_2 in join_variables_map: + raise RbqlParsingError(ambiguous_error_msg.format(join_var_2)) + if join_var_2 in input_variables_map: + join_var_1, join_var_2 = join_var_2, join_var_1 + if join_var_1 in ['NR', 'a.NR', 'aNR']: + lhs_key_index = -1 + elif join_var_1 in input_variables_map: + lhs_key_index = input_variables_map.get(join_var_1).index + else: + raise RbqlParsingError('Unable to parse JOIN expression: Input table does not have field "{}"\n{}'.format(join_var_1, valid_join_syntax_msg)) # UT JSON + if join_var_2 in ['bNR', 'b.NR']: + rhs_key_index = -1 + elif join_var_2 in join_variables_map: + rhs_key_index = join_variables_map.get(join_var_2).index + else: + raise RbqlParsingError('Unable to parse JOIN expression: Join table does not have field "{}"\n{}'.format(join_var_2, valid_join_syntax_msg)) # UT JSON + lhs_join_var_expression = 'NR' if lhs_key_index == -1 else 'safe_join_get(record_a, {})'.format(lhs_key_index) + rhs_indices.append(rhs_key_index) + lhs_variables.append(lhs_join_var_expression) + return (lhs_variables, rhs_indices) + + +def parse_basic_variables(query_text, prefix, dst_variables_map): + assert prefix in ['a', 'b'] + rgx = '(?:^|[^_a-zA-Z0-9]){}([1-9][0-9]*)(?:$|(?=[^_a-zA-Z0-9]))'.format(prefix) + matches = list(re.finditer(rgx, query_text)) + field_nums = list(set([int(m.group(1)) for m in matches])) + for field_num in field_nums: + dst_variables_map[prefix + str(field_num)] = VariableInfo(initialize=True, index=field_num - 1) + + +def parse_array_variables(query_text, prefix, dst_variables_map): + assert prefix in ['a', 'b'] + rgx = r'(?:^|[^_a-zA-Z0-9]){}\[([1-9][0-9]*)\]'.format(prefix) + matches = list(re.finditer(rgx, query_text)) + field_nums = list(set([int(m.group(1)) for m in matches])) + for field_num in field_nums: + dst_variables_map['{}[{}]'.format(prefix, field_num)] = VariableInfo(initialize=True, index=field_num - 1) + + +def python_string_escape_column_name(column_name, quote_char): + assert quote_char in ['"', "'"] + column_name = column_name.replace('\\', '\\\\') + column_name = column_name.replace('\n', '\\n') + column_name = column_name.replace('\r', '\\r') + column_name = column_name.replace('\t', '\\t') + if quote_char == '"': + return column_name.replace('"', '\\"') + return column_name.replace("'", "\\'") + + +def query_probably_has_dictionary_variable(query_text, column_name): + # It is OK to return false positive - in the worst case we woud just waste some performance on unused variable initialization + continuous_name_segments = re.findall('[-a-zA-Z0-9_:;+=!.,()%^#@&* ]+', column_name) + for continuous_segment in continuous_name_segments: + if query_text.find(continuous_segment) == -1: + return False + return True + + +def parse_dictionary_variables(query_text, prefix, column_names, dst_variables_map): + # The purpose of this algorithm is to minimize number of variables in varibale_map to improve performance, ideally it should be only variables from the query + # TODO implement algorithm for honest python f-string parsing + assert prefix in ['a', 'b'] + if re.search(r'(?:^|[^_a-zA-Z0-9]){}\['.format(prefix), query_text) is None: + return + for i in range(len(column_names)): + column_name = column_names[i] + if query_probably_has_dictionary_variable(query_text, column_name): + dst_variables_map['{}["{}"]'.format(prefix, python_string_escape_column_name(column_name, '"'))] = VariableInfo(initialize=True, index=i) + dst_variables_map["{}['{}']".format(prefix, python_string_escape_column_name(column_name, "'"))] = VariableInfo(initialize=False, index=i) + + +def parse_attribute_variables(query_text, prefix, column_names, column_names_source, dst_variables_map): + # The purpose of this algorithm is to minimize number of variables in varibale_map to improve performance, ideally it should be only variables from the query + + # TODO ideally we should either: + # * not search inside string literals (excluding brackets in f-strings) OR + # * check if column_name is not among reserved python keywords like "None", "if", "else", etc + assert prefix in ['a', 'b'] + column_names = {v: i for i, v in enumerate(column_names)} + rgx = r'(?:^|[^_a-zA-Z0-9]){}\.([_a-zA-Z][_a-zA-Z0-9]*)'.format(prefix) + matches = list(re.finditer(rgx, query_text)) + column_names_from_query = list(set([m.group(1) for m in matches])) + for column_name in column_names_from_query: + zero_based_idx = column_names.get(column_name) + if zero_based_idx is not None: + dst_variables_map['{}.{}'.format(prefix, column_name)] = VariableInfo(initialize=True, index=zero_based_idx) + else: + raise RbqlParsingError('Unable to find column "{}" in {} {}'.format(column_name, {'a': 'input', 'b': 'join'}[prefix], column_names_source)) + + +def map_variables_directly(query_text, column_names, dst_variables_map): + for idx, column_name in enumerate(column_names): + if re.match(r'^[_a-zA-Z][_a-zA-Z0-9]*$', column_name) is None: + raise RbqlIOHandlingError('Unable to use column name "{}" as RBQL/Python variable'.format(column_name)) + if query_text.find(column_name) != -1: + dst_variables_map[column_name] = VariableInfo(initialize=True, index=idx) + + +def ensure_no_ambiguous_variables(query_text, input_column_names, join_column_names): + join_column_names_set = set(join_column_names) + for column_name in input_column_names: + if column_name in join_column_names_set and query_text.find(column_name) != -1: # False positive is tolerable here + raise RbqlParsingError(ambiguous_error_msg.format(column_name)) + + + +def generate_common_init_code(query_text, variable_prefix): + assert variable_prefix in ['a', 'b'] + result = list() + # TODO [PERFORMANCE] do not initialize RBQLRecord if we don't have `a.` or `a[` prefix in the query + result.append('{} = RBQLRecord()'.format(variable_prefix)) + base_var = 'NR' if variable_prefix == 'a' else 'bNR' + attr_var = '{}.NR'.format(variable_prefix) + if query_text.find(attr_var) != -1: + result.append('{} = {}'.format(attr_var, base_var)) + if variable_prefix == 'a' and query_text.find('aNR') != -1: + result.append('aNR = NR') + return result + + +def generate_init_statements(query_text, variables_map, join_variables_map): + code_lines = generate_common_init_code(query_text, 'a') + for var_name, var_info in variables_map.items(): + if var_info.initialize: + code_lines.append('{} = safe_get(record_a, {})'.format(var_name, var_info.index)) + if join_variables_map: + code_lines += generate_common_init_code(query_text, 'b') + for var_name, var_info in join_variables_map.items(): + if var_info.initialize: + code_lines.append('{} = safe_get(record_b, {}) if record_b is not None else None'.format(var_name, var_info.index)) + return '\n'.join(code_lines) + + +def replace_star_count(aggregate_expression): + return re.sub(r'(^|(?<=,)) *COUNT\( *\* *\) *($|(?=,))', ' COUNT(1)', aggregate_expression, flags=re.IGNORECASE).lstrip(' ') + + +def replace_star_vars(rbql_expression): + star_matches = list(re.finditer(r'(?:^|,) *(\*|a\.\*|b\.\*) *(?=$|,)', rbql_expression)) + last_pos = 0 + result = '' + for match in star_matches: + star_expression = match.group(1) + replacement_expression = '] + ' + {'*': 'star_fields', 'a.*': 'record_a', 'b.*': 'record_b'}[star_expression] + ' + [' + if last_pos < match.start(): + result += rbql_expression[last_pos:match.start()] + result += replacement_expression + last_pos = match.end() + 1 # Adding one to skip the lookahead comma + result += rbql_expression[last_pos:] + return result + + +def replace_star_vars_for_ast(rbql_expression): + star_matches = list(re.finditer(r'(?:(?<=^)|(?<=,)) *(\*|a\.\*|b\.\*) *(?=$|,)', rbql_expression)) + last_pos = 0 + result = '' + for match in star_matches: + star_expression = match.group(1) + replacement_expression = {'*': '__RBQL_INTERNAL_STAR', 'a.*': 'a.__RBQL_INTERNAL_STAR', 'b.*': 'b.__RBQL_INTERNAL_STAR'}[star_expression] + if last_pos < match.start(): + result += rbql_expression[last_pos:match.start()] + result += replacement_expression + last_pos = match.end() + result += rbql_expression[last_pos:] + return result + + +def translate_update_expression(update_expression, input_variables_map, string_literals): + assignment_looking_rgx = re.compile(r'(?:^|,) *(a[.#a-zA-Z0-9\[\]_]*) *=(?=[^=])') + update_expressions = [] + pos = 0 + first_assignment_error = 'Unable to parse "UPDATE" expression: the expression must start with assignment, but "{}" does not look like an assignable field name'.format(update_expression.split('=')[0].strip()) + while True: + match = assignment_looking_rgx.search(update_expression, pos) + if not len(update_expressions) and (match is None or match.start() != 0): + raise RbqlParsingError(first_assignment_error) # UT JSON + if match is None: + update_expressions[-1] += update_expression[pos:].strip() + ')' + break + if len(update_expressions): + update_expressions[-1] += update_expression[pos:match.start()].strip() + ')' + dst_var_name = combine_string_literals(match.group(1).strip(), string_literals) + var_info = input_variables_map.get(dst_var_name) + if var_info is None: + raise RbqlParsingError('Unable to parse "UPDATE" expression: Unknown field name: "{}"'.format(dst_var_name)) # UT JSON + update_expressions.append('safe_set(up_fields, {}, '.format(var_info.index)) + pos = match.end() + return combine_string_literals('\n'.join(update_expressions), string_literals) + + +def translate_select_expression(select_expression): + expression_without_stars = replace_star_count(select_expression) + translated = replace_star_vars(expression_without_stars).strip() + translated_for_ast = replace_star_vars_for_ast(expression_without_stars).strip() + if not len(translated): + raise RbqlParsingError('"SELECT" expression is empty') # UT JSON + return ('[{}]'.format(translated), translated_for_ast) + + +def separate_string_literals(rbql_expression): + # The regex is improved expression from here: https://stackoverflow.com/a/14366904/2898283 + string_literals_regex = r'''(\"\"\"|\'\'\'|\"|\')((? 1: + raise RbqlParsingError('More than one "{}" statements found'.format(statement)) # UT JSON + assert len(matches) == 1 + match = matches[0] + result.append((match.start(), match.end(), statement)) + break # Break to avoid matching a sub-statement from the same group e.g. "INNER JOIN" -> "JOIN" + return sorted(result) + + +def separate_actions(statement_groups, rbql_expression): + # TODO add more checks: + # make sure all rbql_expression was separated and SELECT or UPDATE is at the beginning + rbql_expression = rbql_expression.strip(' ') + result = dict() + # For now support no more than one query modifier per query + mobj = re.match('^(.*) *[Ww][Ii][Tt][Hh] *\(([a-z]{4,20})\) *$', rbql_expression) + if mobj is not None: + rbql_expression = mobj.group(1) + result[WITH] = mobj.group(2) + ordered_statements = locate_statements(statement_groups, rbql_expression) + for i in range(len(ordered_statements)): + statement_start = ordered_statements[i][0] + span_start = ordered_statements[i][1] + statement = ordered_statements[i][2] + span_end = ordered_statements[i + 1][0] if i + 1 < len(ordered_statements) else len(rbql_expression) + assert statement_start < span_start + assert span_start <= span_end + span = rbql_expression[span_start:span_end] + + statement_params = dict() + + if statement in [STRICT_LEFT_JOIN, LEFT_OUTER_JOIN, LEFT_JOIN, INNER_JOIN, JOIN]: + statement_params['join_subtype'] = statement + statement = JOIN + + if statement == UPDATE: + if statement_start != 0: + raise RbqlParsingError('UPDATE keyword must be at the beginning of the query') # UT JSON + span = re.sub('(?i)^ *SET ', '', span) + + if statement == ORDER_BY: + span = re.sub('(?i) ASC *$', '', span) + new_span = re.sub('(?i) DESC *$', '', span) + if new_span != span: + span = new_span + statement_params['reverse'] = True + else: + statement_params['reverse'] = False + + if statement == SELECT: + if statement_start != 0: + raise RbqlParsingError('SELECT keyword must be at the beginning of the query') # UT JSON + match = re.match('(?i)^ *TOP *([0-9]+) ', span) + if match is not None: + statement_params['top'] = int(match.group(1)) + span = span[match.end():] + match = re.match('(?i)^ *DISTINCT *(COUNT)? ', span) + if match is not None: + statement_params['distinct'] = True + if match.group(1) is not None: + statement_params['distinct_count'] = True + span = span[match.end():] + + statement_params['text'] = span.strip() + result[statement] = statement_params + if SELECT not in result and UPDATE not in result: + raise RbqlParsingError('Query must contain either SELECT or UPDATE statement') # UT JSON + if SELECT in result and UPDATE in result: + raise RbqlParsingError('Query can not contain both SELECT and UPDATE statements') + return result + + +def find_top(rb_actions): + if LIMIT in rb_actions: + try: + return int(rb_actions[LIMIT]['text']) + except ValueError: + raise RbqlParsingError('LIMIT keyword must be followed by an integer') # UT JSON + return rb_actions[SELECT].get('top', None) + + +def translate_except_expression(except_expression, input_variables_map, string_literals, input_header): + skip_vars = except_expression.split(',') + skip_vars = [v.strip() for v in skip_vars] + skip_indices = list() + for var_name in skip_vars: + var_name = combine_string_literals(var_name, string_literals) + var_info = input_variables_map.get(var_name) + if var_info is None: + raise RbqlParsingError('Unknown field in EXCEPT expression: "{}"'.format(var_name)) # UT JSON + skip_indices.append(var_info.index) + skip_indices = sorted(skip_indices) + output_header = None if input_header is None else select_except(input_header, skip_indices) + skip_indices = [str(v) for v in skip_indices] + return (output_header, 'select_except(record_a, [{}])'.format(','.join(skip_indices))) + + +class HashJoinMap: + # Other possible flavors: BinarySearchJoinMap, MergeJoinMap + def __init__(self, record_iterator, key_indices): + self.max_record_len = 0 + self.hash_map = defaultdict(list) + self.record_iterator = record_iterator + self.key_indices = None + self.key_index = None + if len(key_indices) == 1: + self.key_index = key_indices[0] + self.polymorphic_get_key = self.get_single_key + else: + self.key_indices = key_indices + self.polymorphic_get_key = self.get_multi_key + + + def get_single_key(self, nr, fields): + if self.key_index >= len(fields): + raise RbqlRuntimeError('No field with index {} at record {} in "B" table'.format(self.key_index + 1, nr)) + return nr if self.key_index == -1 else fields[self.key_index] + + + def get_multi_key(self, nr, fields): + result = [] + for ki in self.key_indices: + if ki >= len(fields): + raise RbqlRuntimeError('No field with index {} at record {} in "B" table'.format(ki + 1, nr)) + result.append(nr if ki == -1 else fields[ki]) + return tuple(result) + + + def build(self): + nr = 0 + while True: + fields = self.record_iterator.get_record() + if fields is None: + break + nr += 1 + nf = len(fields) + self.max_record_len = max(self.max_record_len, nf) + key = self.polymorphic_get_key(nr, fields) + self.hash_map[key].append((nr, nf, fields)) + + + def get_join_records(self, key): + return self.hash_map[key] + + + def get_warnings(self): + return self.record_iterator.get_warnings() + + +def cleanup_query(query_text): + rbql_lines = query_text.split('\n') + rbql_lines = [strip_comments(l) for l in rbql_lines] + rbql_lines = [l for l in rbql_lines if len(l)] + return ' '.join(rbql_lines).rstrip(';') + + +def remove_redundant_input_table_name(query_text): + query_text = re.sub(' +from +a(?: +|$)', ' ', query_text, flags=re.IGNORECASE).strip() + query_text = re.sub('^ *update +a +set ', 'update ', query_text, flags=re.IGNORECASE).strip() + return query_text + + +def select_output_header(input_header, join_header, query_column_infos): + if input_header is None and join_header is None: + return None + if input_header is None: + input_header = [] + if join_header is None: + join_header = [] + output_header = [] + for qci in query_column_infos: + if qci is None: + output_header.append('col{}'.format(len(output_header) + 1)) + elif qci.is_star: + if qci.table_name is None: + output_header += input_header + join_header + elif qci.table_name == 'a': + output_header += input_header + elif qci.table_name == 'b': + output_header += join_header + elif qci.column_name is not None: + output_header.append(qci.column_name) + elif qci.column_index is not None: + if qci.table_name == 'a' and qci.column_index < len(input_header): + output_header.append(input_header[qci.column_index]) + elif qci.table_name == 'b' and qci.column_index < len(join_header): + output_header.append(join_header[qci.column_index]) + else: + output_header.append('col{}'.format(len(output_header) + 1)) + else: # Should never happen + output_header.append('col{}'.format(len(output_header) + 1)) + return output_header + + +def shallow_parse_input_query(query_text, input_iterator, tables_registry, query_context): + query_text = cleanup_query(query_text) + format_expression, string_literals = separate_string_literals(query_text) + statement_groups = default_statement_groups[:] + if input_iterator is not None: + # In case if input_iterator i.e. input table is already fixed RBQL assumes that the only valid table name is "A" or "a". + format_expression = remove_redundant_input_table_name(format_expression) + statement_groups.remove([FROM]) + else: + assert tables_registry is not None + rb_actions = separate_actions(statement_groups, format_expression) + + if FROM in rb_actions: + assert input_iterator is None + input_table_id = rb_actions[FROM]['text'] + input_iterator = tables_registry.get_iterator_by_table_id(input_table_id, 'a') + if input_iterator is None: + raise RbqlParsingError('Unable to find input table: "{}"'.format(input_table_id)) + query_context.input_iterator = input_iterator + + if input_iterator is None: + raise RbqlParsingError('Queries without context-based input table must contain "FROM" statement') + + if WITH in rb_actions: + input_iterator.handle_query_modifier(rb_actions[WITH]) + input_variables_map = input_iterator.get_variables_map(query_text) + + if ORDER_BY in rb_actions and UPDATE in rb_actions: + raise RbqlParsingError('"ORDER BY" is not allowed in "UPDATE" queries') # UT JSON + + if GROUP_BY in rb_actions: + if ORDER_BY in rb_actions or UPDATE in rb_actions: + raise RbqlParsingError(invalid_keyword_in_aggregate_query_error_msg) # UT JSON + query_context.aggregation_key_expression = '({},)'.format(combine_string_literals(rb_actions[GROUP_BY]['text'], string_literals)) + + + join_variables_map = None + join_header = None + if JOIN in rb_actions: + rhs_table_id, variable_pairs = parse_join_expression(rb_actions[JOIN]['text']) + if tables_registry is None: + raise RbqlParsingError('JOIN operations are not supported by the application') # UT JSON + join_record_iterator = tables_registry.get_iterator_by_table_id(rhs_table_id, 'b') + if join_record_iterator is None: + raise RbqlParsingError('Unable to find join table: "{}"'.format(rhs_table_id)) # UT JSON CSV + if WITH in rb_actions: + join_record_iterator.handle_query_modifier(rb_actions[WITH]) + join_variables_map = join_record_iterator.get_variables_map(query_text) + join_header = join_record_iterator.get_header() + # TODO check ambiguous column names here instead of external check. + + lhs_variables, rhs_indices = resolve_join_variables(input_variables_map, join_variables_map, variable_pairs, string_literals) + joiner_type = {JOIN: InnerJoiner, INNER_JOIN: InnerJoiner, LEFT_OUTER_JOIN: LeftJoiner, LEFT_JOIN: LeftJoiner, STRICT_LEFT_JOIN: StrictLeftJoiner}[rb_actions[JOIN]['join_subtype']] + query_context.lhs_join_var_expression = lhs_variables[0] if len(lhs_variables) == 1 else '({})'.format(', '.join(lhs_variables)) + query_context.join_map_impl = HashJoinMap(join_record_iterator, rhs_indices) + query_context.join_map_impl.build() + query_context.join_map = joiner_type(query_context.join_map_impl) + + query_context.variables_init_code = combine_string_literals(generate_init_statements(format_expression, input_variables_map, join_variables_map), string_literals) + + + if WHERE in rb_actions: + where_expression = rb_actions[WHERE]['text'] + if re.search(r'[^> 1 + inconsistent_records_info = inconsistent_records_info.items() + inconsistent_records_info = sorted(inconsistent_records_info, key=lambda v: v[1]) + num_fields_1, record_num_1 = inconsistent_records_info[0] + num_fields_2, record_num_2 = inconsistent_records_info[1] + warn_msg = 'Number of fields in "{}" table is not consistent: '.format(table_name) + warn_msg += 'e.g. record {} -> {} fields, record {} -> {} fields'.format(record_num_1, num_fields_1, record_num_2, num_fields_2) + return warn_msg + + +def query(query_text, input_iterator, output_writer, output_warnings, join_tables_registry=None, user_init_code='', user_namespace=None): + query_context = RBQLContext(input_iterator, output_writer, user_init_code) + shallow_parse_input_query(query_text, input_iterator, join_tables_registry, query_context) + compile_and_run(query_context, user_namespace) + query_context.writer.finish() + output_warnings.extend(query_context.input_iterator.get_warnings()) + if query_context.join_map_impl is not None: + output_warnings.extend(query_context.join_map_impl.get_warnings()) + output_warnings.extend(output_writer.get_warnings()) + + +class RBQLInputIterator: + def get_variables_map(self, query_text): + raise NotImplementedError('Unable to call the interface method') + + def get_record(self): + raise NotImplementedError('Unable to call the interface method') + + def handle_query_modifier(self, modifier_name): + # Reimplement if you need to handle a boolean query modifier that can be used like this: `SELECT * WITH (modifiername)` + pass + + def get_warnings(self): + return [] # Reimplement if your class can produce warnings + + def get_header(self): + return None # Reimplement if your class can provide input header + + +class RBQLOutputWriter: + def write(self, fields): + raise NotImplementedError('Unable to call the interface method') + + def finish(self): + pass # Reimplement if your class needs to do something on finish e.g. cleanup + + def get_warnings(self): + return [] # Reimplement if your class can produce warnings + + def set_header(self, header): + pass # Reimplement if your class can handle output headers in a meaningful way + + +class RBQLTableRegistry: + # table_id - external table identifier like filename for csv files or variable name for pandas dataframes. + # single_char_alias - either `a` (for input table) or `b` (for join table) + def get_iterator_by_table_id(self, table_id, single_char_alias): + raise NotImplementedError('Unable to call the interface method') + + def finish(self): + pass # Reimplement if your class needs to do something on finish e.g. cleanup + + def get_warnings(self): + return [] # Reimplement if your class can produce warnings + + +class TableIterator(RBQLInputIterator): + def __init__(self, table, column_names=None, normalize_column_names=True, variable_prefix='a'): + self.table = table + self.column_names = column_names + self.normalize_column_names = normalize_column_names + self.variable_prefix = variable_prefix + self.NR = 0 + self.fields_info = dict() + + def get_variables_map(self, query_text): + variable_map = dict() + parse_basic_variables(query_text, self.variable_prefix, variable_map) + parse_array_variables(query_text, self.variable_prefix, variable_map) + if self.column_names is not None: + if len(self.table) and len(self.column_names) != len(self.table[0]): + raise RbqlIOHandlingError('List of column names and table records have different lengths') + if self.normalize_column_names: + parse_dictionary_variables(query_text, self.variable_prefix, self.column_names, variable_map) + parse_attribute_variables(query_text, self.variable_prefix, self.column_names, 'column names list', variable_map) + else: + map_variables_directly(query_text, self.column_names, variable_map) + return variable_map + + def get_record(self): + if self.NR >= len(self.table): + return None + record = self.table[self.NR] + self.NR += 1 + num_fields = len(record) + if num_fields not in self.fields_info: + self.fields_info[num_fields] = self.NR + return record + + def get_warnings(self): + if len(self.fields_info) > 1: + return [make_inconsistent_num_fields_warning('input', self.fields_info)] + return [] + + def get_header(self): + return self.column_names + + +class TableWriter(RBQLOutputWriter): + def __init__(self, external_table): + self.table = external_table + self.header = None + + def write(self, fields): + self.table.append(fields) + return True + + def set_header(self, header): + self.header = header + + +ListTableInfo = namedtuple('ListTableInfo', ['table_id', 'table', 'column_names']) + + +class ListTableRegistry(RBQLTableRegistry): + # Here table_infos is a list of ListTableInfo + def __init__(self, table_infos, normalize_column_names=True): + self.table_infos = table_infos + self.normalize_column_names = normalize_column_names + + def get_iterator_by_table_id(self, table_id, single_char_alias): + for table_info in self.table_infos: + if table_info.table_id == table_id: + return TableIterator(table_info.table, table_info.column_names, self.normalize_column_names, single_char_alias) + return None + + +def query_table(query_text, input_table, output_table, output_warnings, join_table=None, input_column_names=None, join_column_names=None, output_column_names=None, normalize_column_names=True, user_init_code=''): + if not normalize_column_names and input_column_names is not None and join_column_names is not None: + ensure_no_ambiguous_variables(query_text, input_column_names, join_column_names) + input_iterator = TableIterator(input_table, input_column_names, normalize_column_names) + output_writer = TableWriter(output_table) + join_tables_registry = None if join_table is None else ListTableRegistry([ListTableInfo('b', join_table, join_column_names), ListTableInfo('B', join_table, join_column_names)], normalize_column_names) + query(query_text, input_iterator, output_writer, output_warnings, join_tables_registry, user_init_code=user_init_code) + if output_column_names is not None: + assert len(output_column_names) == 0, '`output_column_names` param must be an empty list or None' + if output_writer.header is not None: + for column_name in output_writer.header: + output_column_names.append(column_name) + + +def set_debug_mode(new_value=True): + global debug_mode + debug_mode = new_value + diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_ipython.py b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_ipython.py new file mode 100644 index 00000000..e58bc77b --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_ipython.py @@ -0,0 +1,117 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals +from __future__ import print_function + +from . import rbql_engine +from . import rbql_pandas + +# TODO figure out how to implement at least basic autocomplete for the magic command. + +import re +from_autocomplete_matcher = re.compile(r'(?:^| )from +([_a-zA-Z0-9]+)(?:$| )', flags=re.IGNORECASE) +join_autocomplete_matcher = re.compile(r'(?:^| )join +([_a-zA-Z0-9]+)(?:$| )', flags=re.IGNORECASE) + + +class IPythonDataframeRegistry(rbql_engine.RBQLTableRegistry): + # TODO consider making this class nested under load_ipython_extension to avoid redundant `import pandas`. + def __init__(self, all_ns_refs): + self.all_ns_refs = all_ns_refs + + def get_iterator_by_table_id(self, table_id, single_char_alias): + import pandas + # It seems to be the first namespace is "user" namespace, at least according to this code: + # https://github.com/google/picatrix/blob/a2f39766ad4b007b125dc8f84916e18fb3dc5478/picatrix/lib/utils.py + for ns in self.all_ns_refs: + if table_id in ns and isinstance(ns[table_id], pandas.DataFrame): + return rbql_pandas.DataframeIterator(ns[table_id], normalize_column_names=True, variable_prefix=single_char_alias) + return None + + +def eprint(*args, **kwargs): + import sys + print(*args, file=sys.stderr, **kwargs) + + +class AttrDict(dict): + # Helper class to convert dict keys to attributes. See explanation here: https://stackoverflow.com/a/14620633/2898283 + def __init__(self, *args, **kwargs): + super(AttrDict, self).__init__(*args, **kwargs) + self.__dict__ = self + + +def load_ipython_extension(ipython): + from IPython.core.magic import register_line_magic + from IPython.core.getipython import get_ipython + import pandas + + ipython = ipython or get_ipython() # The pattern taken from here: https://github.com/pydoit/doit/blob/9efe141a5dc96d4912143561695af7fc4a076490/doit/tools.py + # ipython is interactiveshell. Docs: https://ipython.readthedocs.io/en/stable/api/generated/IPython.core.interactiveshell.html + + + def get_table_column_names(table_id): + user_namespace = ipython.all_ns_refs[0] if len(ipython.all_ns_refs) else dict() + if table_id not in user_namespace or not isinstance(user_namespace[table_id], pandas.DataFrame): + return [] + input_df = user_namespace[table_id] + if isinstance(input_df.columns, pandas.RangeIndex) or not len(input_df.columns): + return [] + return [str(v) for v in list(input_df.columns)] + + + def rbql_completers(self, event): + # This should return a list of strings with possible completions. + # Note that all the included strings that don't start with event.symbol + # are removed, in order to not confuse readline. + + # eg Typing %%rbql foo then hitting tab would yield an event like so: namespace(command='%%rbql', line='%%rbql foo', symbol='foo', text_until_cursor='%%rbql foo') + # https://stackoverflow.com/questions/36479197/ipython-custom-tab-completion-for-user-magic-function + # https://github.com/ipython/ipython/issues/11878 + + simple_sql_keys_lower_case = ['update', 'select', 'where', 'limit', 'from', 'group by', 'order by'] + simple_sql_keys_upper_case = [sk.upper() for sk in simple_sql_keys_lower_case] + autocomplete_suggestions = simple_sql_keys_lower_case + simple_sql_keys_upper_case + + if event.symbol and event.symbol.startswith('a.'): + from_match = from_autocomplete_matcher.search(event.line) + if from_match is not None: + table_id = from_match.group(1) + table_column_names = get_table_column_names(table_id) + autocomplete_suggestions += ['a.' + cn for cn in table_column_names] + + if event.symbol and event.symbol.startswith('b.'): + from_match = join_autocomplete_matcher.search(event.line) + if from_match is not None: + table_id = from_match.group(1) + table_column_names = get_table_column_names(table_id) + autocomplete_suggestions += ['b.' + cn for cn in table_column_names] + + return autocomplete_suggestions + + ipython.set_hook('complete_command', rbql_completers, str_key='%rbql') + + + # The difference between line and cell magic is described here: https://jakevdp.github.io/PythonDataScienceHandbook/01.03-magic-commands.html. + # In short: line magic only accepts one line of input whereas cell magic supports multiline input as magic command argument. + # Both line and cell magic would make sense for RBQL queries but for MVP it should be enough to implement just the cell magic. + @register_line_magic("rbql") + def run_rbql_query(query_text): + # Unfortunately globals() and locals() called from here won't contain user variables defined in the notebook. + + tables_registry = IPythonDataframeRegistry(ipython.all_ns_refs) + output_writer = rbql_pandas.DataframeWriter() + # Ignore warnings because pandas dataframes can't cause them. + output_warnings = [] + # TODO make it possible to specify user_init_code in code cells. + error_type, error_msg = None, None + user_namespace = None + if len(ipython.all_ns_refs) > 0: + user_namespace = AttrDict(ipython.all_ns_refs[0]) + try: + rbql_engine.query(query_text, input_iterator=None, output_writer=output_writer, output_warnings=output_warnings, join_tables_registry=tables_registry, user_init_code='', user_namespace=user_namespace) + except Exception as e: + error_type, error_msg = rbql_engine.exception_to_error_info(e) + if error_type is None: + return output_writer.result + else: + # TODO use IPython.display to print error in red color, see https://stackoverflow.com/questions/16816013/is-it-possible-to-print-using-different-colors-in-ipythons-notebook + eprint('Error [{}]: {}'.format(error_type, error_msg)) diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_main.py b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_main.py new file mode 100644 index 00000000..6123493b --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_main.py @@ -0,0 +1,519 @@ +#!/usr/bin/env python +from __future__ import unicode_literals +from __future__ import print_function + +import sys +import os +import argparse + +from . import csv_utils +from . import rbql_csv +from . import rbql_sqlite +from . import rbql_engine +from . import _version + +# TODO support sqlite input join on both sqlite and csv tables - pass 2 join registries +# TODO add demo gif to python package README.md for pypi website + +# TODO add --output_header param +# TODO add option to write to other sqlite dbs + +# TODO add an option to align columns for content preview. This would be especially useful for Windows which doesn't support terminal colors + + +PY3 = sys.version_info[0] == 3 + + +history_path = os.path.join(os.path.expanduser("~"), ".rbql_py_query_history") + +polymorphic_input = input if PY3 else raw_input + + +def eprint(*args, **kwargs): + print(*args, file=sys.stderr, **kwargs) + + +policy_names = ['quoted', 'simple', 'whitespace', 'quoted_rfc', 'monocolumn'] +out_format_names = ['csv', 'tsv', 'input'] + + +polymorphic_xrange = range if PY3 else xrange + + +def get_default_policy(delim): + if delim in [';', ',']: + return 'quoted' + elif delim == ' ': + return 'whitespace' + else: + return 'simple' + + +def show_error(error_type, error_msg, is_interactive): + if is_interactive: + if os.name == 'nt': # Windows does not support terminal colors + print('Error [{}]: {}'.format(error_type, error_msg)) + else: + print('{}Error [{}]:{} {}'.format('\u001b[31;1m', error_type, '\u001b[0m', error_msg)) + else: + eprint('Error [{}]: {}'.format(error_type, error_msg)) + + +def show_warning(msg, is_interactive): + if is_interactive: + if os.name == 'nt': # Windows does not support terminal colors + print('Warning: ' + msg) + else: + print('{}Warning:{} {}'.format('\u001b[33;1m', '\u001b[0m', msg)) + else: + eprint('Warning: ' + msg) + + +def run_with_python_csv(args, is_interactive): + if args.debug_mode: + rbql_csv.set_debug_mode() + delim = rbql_csv.normalize_delim(args.delim) + policy = args.policy if args.policy is not None else get_default_policy(delim) + query = args.query + with_headers = args.with_headers + input_path = args.input + output_path = args.output + csv_encoding = args.encoding + args.output_delim, args.output_policy = (delim, policy) if args.out_format == 'input' else rbql_csv.interpret_named_csv_format(args.out_format) + out_delim, out_policy = args.output_delim, args.output_policy + + user_init_code = rbql_csv.read_user_init_code(args.init_source_file) if args.init_source_file is not None else '' + + warnings = [] + error_type, error_msg = None, None + try: + rbql_csv.query_csv(query, input_path, delim, policy, output_path, out_delim, out_policy, csv_encoding, warnings, with_headers, args.comment_prefix, user_init_code, args.color) + except Exception as e: + if args.debug_mode: + raise + error_type, error_msg = rbql_engine.exception_to_error_info(e) + + if error_type is None: + success = True + for warning in warnings: + show_warning(warning, is_interactive) + else: + success = False + show_error(error_type, error_msg, is_interactive) + + return success + + +def run_with_python_sqlite(args, is_interactive): + import sqlite3 + user_init_code = rbql_csv.read_user_init_code(args.init_source_file) if args.init_source_file is not None else '' + + warnings = [] + error_type, error_msg = None, None + try: + # TODO open in readonly mode + db_connection = sqlite3.connect(args.database) + if args.debug_mode: + rbql_engine.set_debug_mode() + rbql_sqlite.query_sqlite_to_csv(args.query, db_connection, args.input, args.output, args.output_delim, args.output_policy, args.encoding, warnings, user_init_code, args.color) + except Exception as e: + if args.debug_mode: + raise + error_type, error_msg = rbql_engine.exception_to_error_info(e) + finally: + db_connection.close() + + if error_type is None: + success = True + for warning in warnings: + show_warning(warning, is_interactive) + else: + success = False + show_error(error_type, error_msg, is_interactive) + + return success + + +def is_delimited_table(sampled_lines, delim, policy): + if len(sampled_lines) < 2: + return False + num_fields = None + for sl in sampled_lines: + fields, warning = csv_utils.smart_split(sl, delim, policy, True) + if warning or len(fields) < 2: + return False + if num_fields is None: + num_fields = len(fields) + if num_fields != len(fields): + return False + return True + + +def sample_lines(src_path, encoding, delim, policy, comment_prefix=None): + # TODO this should be a dependency-free function, remove sample line functionality from CSVRecordIterator + result = [] + with open(src_path, 'rb') as source: + line_iterator = rbql_csv.CSVRecordIterator(source, encoding, delim=delim, policy=policy, line_mode=True, comment_prefix=comment_prefix) + for _i in polymorphic_xrange(10): + line = line_iterator.polymorphic_get_row() + if line is None: + break + result.append(line) + return result + + +def autodetect_delim_policy(input_path, encoding, comment_prefix=None): + sampled_lines = sample_lines(input_path, encoding, None, None, comment_prefix) + autodetection_dialects = [('\t', 'simple'), (',', 'quoted'), (';', 'quoted'), ('|', 'simple')] + for delim, policy in autodetection_dialects: + if is_delimited_table(sampled_lines, delim, policy): + return (delim, policy) + if input_path.endswith('.csv'): + return (',', 'quoted') + if input_path.endswith('.tsv'): + return ('\t', 'simple') + return (None, None) + + +def sample_records(input_path, delim, policy, encoding, comment_prefix=None): + with open(input_path, 'rb') as source: + record_iterator = rbql_csv.CSVRecordIterator(source, encoding, delim=delim, policy=policy, comment_prefix=comment_prefix) + sampled_records = record_iterator.get_all_records(num_rows=10); + warnings = record_iterator.get_warnings() + return (sampled_records, warnings) + + +def print_colorized(records, delim, encoding, show_column_names, with_headers): + # TODO consider colorizing a1,a2,... in different default color + if os.name == 'nt': # Windows does not support terminal colors + reset_color_code = '' + color_codes = [''] + else: + reset_color_code = '\u001b[0m' + color_codes = ['\u001b[0m', '\u001b[31m', '\u001b[32m', '\u001b[33m', '\u001b[34m', '\u001b[35m', '\u001b[36m', '\u001b[31;1m', '\u001b[32;1m', '\u001b[33;1m'] + for rnum, record in enumerate(records): + out_fields = [] + for i, field in enumerate(record): + color_code = color_codes[i % len(color_codes)] + if not show_column_names or (with_headers and rnum == 0): + colored_field = '{}{}'.format(color_code, field) + else: + colored_field = '{}a{}:{}'.format(color_code, i + 1, field) + out_fields.append(colored_field) + out_line = delim.join(out_fields) + reset_color_code + if PY3: + sys.stdout.buffer.write(out_line.encode(encoding)) + else: + sys.stdout.write(out_line.encode(encoding)) + sys.stdout.write('\n') + sys.stdout.flush() + + +def get_default_output_path(input_path, delim): + well_known_extensions = {',': '.csv', '\t': '.tsv'} + if delim in well_known_extensions: + return input_path + well_known_extensions[delim] + return input_path + '.txt' + + +def run_interactive_loop(mode, args): + assert mode in ['csv', 'sqlite'] + try: + import readline # Module readline is not available on Windows + if os.path.exists(history_path): + readline.read_history_file(history_path) + readline.set_history_length(100) + except Exception: + pass + while True: + try: + query = polymorphic_input('Input SQL-like RBQL query and press Enter:\n> ') + query = query.strip() + except EOFError: + print() + break # Ctrl-D + if not len(query): + break + try: + readline.write_history_file(history_path) # This can fail sometimes for no valid reason + except Exception: + pass + args.query = query + if mode == 'csv': + success = run_with_python_csv(args, is_interactive=True) + else: + success = run_with_python_sqlite(args, is_interactive=True) + if success: + print('\nOutput table preview:') + print('====================================') + records, _warnings = sample_records(args.output, args.output_delim, args.output_policy, args.encoding, comment_prefix=None) + print_colorized(records, args.output_delim, args.encoding, show_column_names=False, with_headers=False) + print('====================================') + print('Success! Result table was saved to: ' + args.output) + break + + +def sample_records_sqlite(db_connection, table_name): + import sqlite3 + record_iterator = rbql_sqlite.SqliteRecordIterator(db_connection, table_name) + records = [] + records.append(record_iterator.get_column_names()) + records += record_iterator.get_all_records(num_rows=10) + return records + + +def read_table_names(db_connection): + cursor = db_connection.cursor() + cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") + table_names = [r[0] for r in cursor.fetchall()] + return table_names + + +def select_table_name_by_user_choice(db_connection): + table_names = read_table_names(db_connection) + max_to_show = 20 + if len(table_names) > max_to_show: + print('Database has {} tables, showing top {}:'.format(len(table_names), max_to_show)) + else: + print('Showing database tables:') + print(', '.join(table_names[:max_to_show])) + table_name = polymorphic_input('No input table was provided as a CLI argument, please type in the table name to use:\n> ') + table_name = table_name.strip() + while table_name not in table_names: + table_name = polymorphic_input('"{}" is not a valid table name. Please enter a valid table name:\n> '.format(table_name)) + table_name = table_name.strip() + return table_name + + +def start_preview_mode_sqlite(args): + import sqlite3 + db_path = args.database + db_connection = sqlite3.connect(db_path) + if not args.input: + args.input = select_table_name_by_user_choice(db_connection) + try: + records = sample_records_sqlite(db_connection, table_name=args.input) + except Exception as e: + if args.debug_mode: + raise + error_type, error_msg = rbql_engine.exception_to_error_info(e) + show_error(error_type, 'Unable to sample preview records: {}'.format(error_msg), is_interactive=True) + sys.exit(1) + db_connection.close() + + print('Input table preview:') + print('====================================') + print_colorized(records, '|', args.encoding, show_column_names=True, with_headers=False) + print('====================================\n') + if args.output is None: + args.output = get_default_output_path('rbql_sqlite_rs', args.output_delim) + show_warning('Output path was not provided. Result set will be saved as: ' + args.output, is_interactive=True) + try: + run_interactive_loop('sqlite', args) + except KeyboardInterrupt: + print() + + +def start_preview_mode_csv(args): + input_path = args.input + if not input_path: + show_error('generic', 'Input file must be provided in interactive mode. You can use stdin input only in non-interactive mode', is_interactive=True) + return + if not os.path.exists(input_path): + show_error('generic', 'Input file {} does not exist'.format(input_path), is_interactive=True) + return + if args.delim is not None: + delim = rbql_csv.normalize_delim(args.delim) + policy = args.policy if args.policy is not None else get_default_policy(delim) + else: + delim, policy = autodetect_delim_policy(input_path, args.encoding, args.comment_prefix) + if delim is None: + show_error('generic', 'Unable to autodetect table delimiter. Provide column separator explicitly with "--delim" option', is_interactive=True) + return + args.delim = delim + args.policy = policy + records, warnings = sample_records(input_path, delim, policy, args.encoding, args.comment_prefix) + print('Input table preview:') + print('====================================') + print_colorized(records, delim, args.encoding, show_column_names=True, with_headers=args.with_headers) + print('====================================\n') + for warning in warnings: + show_warning(warning, is_interactive=True) + if args.output is None: + args.output = get_default_output_path(input_path, delim) + show_warning('Output path was not provided. Result set will be saved as: ' + args.output, is_interactive=True) + try: + run_interactive_loop('csv', args) + except KeyboardInterrupt: + print() + + +csv_tool_description = ''' +Run RBQL queries against CSV files, sqlite databases + +rbql supports two modes: non-interactive (with "--query" option) and interactive (without "--query" option) + +Interactive mode shows source table preview which makes query editing much easier. Usage example: + $ rbql --input input.csv + +Non-interactive mode supports reading input tables from stdin and writing output to stdout. Usage example: + $ rbql --query "select a1, a2 order by a1" --delim , < input.csv + +By default rbql works with CSV input files. +To learn how to use rbql to query an sqlite database, run this command: + + $ rbql sqlite --help + +''' + +csv_epilog = ''' +Description of the available CSV split policies: + * "simple" - RBQL uses simple split() function and doesn't perform special handling of double quote characters + * "quoted" - Separator can be escaped inside double-quoted fields. Double quotes inside double-quoted fields must be doubled + * "quoted_rfc" - Same as "quoted", but also allows newlines inside double-quoted fields, see RFC-4180: https://tools.ietf.org/html/rfc4180 + * "whitespace" - Works only with whitespace separator, multiple consecutive whitespaces are treated as a single whitespace + * "monocolumn" - RBQL doesn't perform any split at all, each line is a single-element record, i.e. only "a1" and "NR" column variables are available +''' + + +def csv_main(): + parser = argparse.ArgumentParser(prog='rbql [csv]', formatter_class=argparse.RawDescriptionHelpFormatter, description=csv_tool_description, epilog=csv_epilog) + parser.add_argument('--input', metavar='FILE', help='read csv table from FILE instead of stdin. Required in interactive mode') + parser.add_argument('--delim', help='delimiter character or multicharacter string, e.g. "," or "###". Can be autodetected in interactive mode') + parser.add_argument('--policy', help='CSV split policy, see the explanation below. Can be autodetected in interactive mode', choices=policy_names) + parser.add_argument('--with-headers', action='store_true', help='indicates that input (and join) table has header') + parser.add_argument('--comment-prefix', metavar='PREFIX', help='ignore lines in input and join tables that start with the comment PREFIX, e.g. "#" or ">>"') + parser.add_argument('--query', help='query string in rbql. Run in interactive mode if empty') + parser.add_argument('--out-format', help='output format', default='input', choices=out_format_names) + parser.add_argument('--encoding', help='manually set csv encoding', default=rbql_csv.default_csv_encoding, choices=['latin-1', 'utf-8']) + parser.add_argument('--output', metavar='FILE', help='write output table to FILE instead of stdout') + parser.add_argument('--color', action='store_true', help='colorize columns in output in non-interactive mode') + parser.add_argument('--version', action='store_true', help='print RBQL version and exit') + parser.add_argument('--init-source-file', metavar='FILE', help=argparse.SUPPRESS) # Path to init source file to use instead of ~/.rbql_init_source.py + parser.add_argument('--debug-mode', action='store_true', help=argparse.SUPPRESS) # Run in debug mode + args = parser.parse_args() + + if args.version: + print(_version.__version__) + return + + if args.color and os.name == 'nt': + show_error('generic', '--color option is not supported for Windows terminals', is_interactive=False) + sys.exit(1) + + if args.output is not None and args.color: + show_error('generic', '"--output" is not compatible with "--color" option', is_interactive=False) + sys.exit(1) + + if args.policy == 'monocolumn': + args.delim = '' + + if args.delim is None and args.policy is not None: + show_error('generic', 'Using "--policy" without "--delim" is not allowed', is_interactive=False) + sys.exit(1) + + if args.encoding != 'latin-1' and not PY3: + if args.delim is not None: + args.delim = args.delim.decode(args.encoding) + if args.query is not None: + args.query = args.query.decode(args.encoding) + + is_interactive_mode = args.query is None + if is_interactive_mode: + if args.color: + show_error('generic', '"--color" option is not compatible with interactive mode. Output and Input files preview would be colorized anyway', is_interactive=False) + sys.exit(1) + start_preview_mode_csv(args) + else: + if args.delim is None: + show_error('generic', 'Separator must be provided with "--delim" option in non-interactive mode', is_interactive=False) + sys.exit(1) + if not run_with_python_csv(args, is_interactive=False): + sys.exit(1) + + +sqlite_tool_description = ''' +Run RBQL queries against sqlite databases +Although sqlite database can serve as an input data source, the query engine which will be used is RBQL (not sqlite). +Result set will be written to a csv file. This is also true for UPDATE queries because in RBQL UPDATE is just a special case of SELECT. + +rbql sqlite supports two modes: non-interactive (with "--query" option) and interactive (without "--query" option) + +Interactive mode shows source table preview which makes query editing much easier. + $ rbql sqlite path/to/database.sqlite + +Non-interactive mode supports reading input tables from stdin and writing output to stdout. Usage example: + $ rbql sqlite path/to/database.sqlite --input Employee --query "select top 20 a1, random.random(), a.salary // 1000 order by a.emp_id" + +''' + + +def sqlite_main(): + parser = argparse.ArgumentParser(prog='rbql sqlite', formatter_class=argparse.RawDescriptionHelpFormatter, description=sqlite_tool_description) + parser.add_argument('database', metavar='PATH', help='PATH to sqlite db') + parser.add_argument('--input', metavar='NAME', help='NAME of the table in sqlite database') + parser.add_argument('--query', help='query string in rbql. Run in interactive mode if empty') + parser.add_argument('--out-format', help='output format', default='csv', choices=['csv', 'tsv']) + parser.add_argument('--output', metavar='FILE', help='write output table to FILE instead of stdout') + parser.add_argument('--color', action='store_true', help='colorize columns in output in non-interactive mode. Do NOT use if redirecting output to a file') + parser.add_argument('--version', action='store_true', help='print RBQL version and exit') + parser.add_argument('--init-source-file', metavar='FILE', help=argparse.SUPPRESS) # Path to init source file to use instead of ~/.rbql_init_source.py + parser.add_argument('--debug-mode', action='store_true', help=argparse.SUPPRESS) # Run in debug mode + args = parser.parse_args() + + if args.version: + print(_version.__version__) + return + + if not os.path.isfile(args.database): + show_error('generic', 'The database does not exist: {}'.format(args.database), is_interactive=False) + sys.exit(1) + + is_interactive_mode = args.query is None + + import sqlite3 + if not args.input: + db_connection = sqlite3.connect(args.database) + table_names = read_table_names(db_connection) + db_connection.close() + if len(table_names) == 1: + args.input = table_names[0] + # TODO Consider showing a warning here + elif not is_interactive_mode: + show_error('generic', 'Please provide input table name with --input parameter: source database has more than one table', is_interactive=False) + sys.exit(1) + + if args.output is not None and args.color: + show_error('generic', '"--output" is not compatible with "--color" option', is_interactive=False) + sys.exit(1) + + args.encoding = 'utf-8' + args.output_delim, args.output_policy = (',', 'quoted_rfc') if args.out_format == 'csv' else rbql_csv.interpret_named_csv_format(args.out_format) + + if is_interactive_mode: + if args.color: + show_error('generic', '"--color" option is not compatible with interactive mode. Output and Input files preview would be colorized anyway', is_interactive=False) + sys.exit(1) + start_preview_mode_sqlite(args) + else: + if not run_with_python_sqlite(args, is_interactive=False): + sys.exit(1) + + +def main(): + if len(sys.argv) > 1: + if sys.argv[1] == 'sqlite': + del sys.argv[1] + sqlite_main() + elif sys.argv[1] == 'csv': + del sys.argv[1] + csv_main() + else: + # TODO Consider showing "uknown mode" error if the first argument doesn't start with '--' + csv_main() + else: + csv_main() + + +if __name__ == '__main__': + main() diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_pandas.py b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_pandas.py new file mode 100644 index 00000000..0abd0d16 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_pandas.py @@ -0,0 +1,96 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals +from __future__ import print_function + +from . import rbql_engine + + +def get_dataframe_column_names_for_rbql(dataframe): + import pandas + if isinstance(dataframe.columns, pandas.RangeIndex) or not len(dataframe.columns): + return None + return [str(v) for v in list(dataframe.columns)] + + +class DataframeIterator(rbql_engine.RBQLInputIterator): + def __init__(self, table, normalize_column_names=True, variable_prefix='a'): + self.table = table + self.normalize_column_names = normalize_column_names + self.variable_prefix = variable_prefix + self.NR = 0 + # TODO include `Index` into the list of addressable variable names. + self.column_names = get_dataframe_column_names_for_rbql(table) + self.table_itertuples = self.table.itertuples(index=False) + + def get_variables_map(self, query_text): + variable_map = dict() + rbql_engine.parse_basic_variables(query_text, self.variable_prefix, variable_map) + rbql_engine.parse_array_variables(query_text, self.variable_prefix, variable_map) + if self.column_names is not None: + if self.normalize_column_names: + rbql_engine.parse_dictionary_variables(query_text, self.variable_prefix, self.column_names, variable_map) + rbql_engine.parse_attribute_variables(query_text, self.variable_prefix, self.column_names, 'column names list', variable_map) + else: + rbql_engine.map_variables_directly(query_text, self.column_names, variable_map) + return variable_map + + def get_record(self): + try: + record = next(self.table_itertuples) + except StopIteration: + return None + self.NR += 1 + # Convert to list because `record` has `Pandas` type. + return list(record) + + def get_warnings(self): + return [] + + def get_header(self): + return self.column_names + + +class DataframeWriter(rbql_engine.RBQLOutputWriter): + def __init__(self): + self.header = None + self.output_rows = [] + self.result = None + + def write(self, fields): + self.output_rows.append(fields) + return True + + def set_header(self, header): + self.header = header + + def finish(self): + import pandas as pd + self.result = pd.DataFrame(self.output_rows, columns=self.header) + + +class SingleDataframeRegistry(rbql_engine.RBQLTableRegistry): + def __init__(self, table, table_name, normalize_column_names=True): + self.table = table + self.normalize_column_names = normalize_column_names + self.table_name = table_name + + def get_iterator_by_table_id(self, table_id, single_char_alias): + if table_id.lower() != self.table_name: + raise rbql_engine.RbqlParsingError('Unable to find join table: "{}"'.format(table_id)) + return DataframeIterator(self.table, self.normalize_column_names, single_char_alias) + + +def query_dataframe(query_text, input_dataframe, output_warnings=None, join_dataframe=None, normalize_column_names=True, user_init_code=''): + if output_warnings is None: + # Ignore output warnings if the output_warnings container hasn't been provided. + output_warnings = [] + if not normalize_column_names and join_dataframe is not None: + input_columns = get_dataframe_column_names_for_rbql(input_dataframe) + join_columns = get_dataframe_column_names_for_rbql(join_dataframe) + if input_columns is not None and join_columns is not None: + rbql_engine.ensure_no_ambiguous_variables(query_text, input_columns, join_columns) + input_iterator = DataframeIterator(input_dataframe, normalize_column_names) + output_writer = DataframeWriter() + join_tables_registry = None if join_dataframe is None else SingleDataframeRegistry(join_dataframe, 'b', normalize_column_names) + rbql_engine.query(query_text, input_iterator, output_writer, output_warnings, join_tables_registry, user_init_code=user_init_code) + return output_writer.result diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_sqlite.py b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_sqlite.py new file mode 100644 index 00000000..3ad0feb9 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql/rbql_sqlite.py @@ -0,0 +1,105 @@ +# -*- coding: utf-8 -*- + +# This module allows to query sqlite databases using RBQL + +from __future__ import unicode_literals +from __future__ import print_function + + +# TODO consider to support table names in "FROM" section of the query, making table_name param of SqliteRecordIterator optional +# TODO consider adding support for multiple variable_prefixes i.e. "a" and or "b" and to alias input and join tables + + +import re +import os +import sys + +from . import rbql_engine +from . import rbql_csv + + +class SqliteRecordIterator(rbql_engine.RBQLInputIterator): + def __init__(self, db_connection, table_name, variable_prefix='a'): + self.db_connection = db_connection + self.table_name = table_name + self.variable_prefix = variable_prefix + self.cursor = self.db_connection.cursor() + import sqlite3 + if re.match('^[a-zA-Z0-9_]*$', table_name) is None: + raise rbql_engine.RbqlIOHandlingError('Unable to use "{}": input table name can contain only alphanumeric characters and underscore'.format(table_name)) + try: + self.cursor.execute('SELECT * FROM {};'.format(table_name)) + except sqlite3.OperationalError as e: + if str(e).find('no such table') != -1: + raise rbql_engine.RbqlIOHandlingError('no such table "{}"'.format(table_name)) + raise + + def get_header(self): + column_names = [description[0] for description in self.cursor.description] + return column_names + + def get_variables_map(self, query_text): + variable_map = dict() + rbql_engine.parse_basic_variables(query_text, self.variable_prefix, variable_map) + rbql_engine.parse_array_variables(query_text, self.variable_prefix, variable_map) + rbql_engine.parse_dictionary_variables(query_text, self.variable_prefix, self.get_header(), variable_map) + rbql_engine.parse_attribute_variables(query_text, self.variable_prefix, self.get_header(), 'table column names', variable_map) + return variable_map + + def get_record(self): + record_tuple = self.cursor.fetchone() + if record_tuple is None: + return None + # We need to convert tuple to list here because otherwise we won't be able to concatinate lists in expressions with star `*` operator + return list(record_tuple) + + def get_all_records(self, num_rows=None): + # TODO consider to use TOP in the sqlite query when num_rows is not None + if num_rows is None: + return self.cursor.fetchall() + result = [] + for i in range(num_rows): + row = self.cursor.fetchone() + if row is None: + break + result.append(row) + return result + + def get_warnings(self): + return [] + + +class SqliteDbRegistry(rbql_engine.RBQLTableRegistry): + def __init__(self, db_connection): + self.db_connection = db_connection + + def get_iterator_by_table_id(self, table_id, single_char_alias): + self.record_iterator = SqliteRecordIterator(self.db_connection, table_id, single_char_alias) + return self.record_iterator + + +def query_sqlite_to_csv(query_text, db_connection, input_table_name, output_path, output_delim, output_policy, output_csv_encoding, output_warnings, user_init_code='', colorize_output=False): + output_stream, close_output_on_finish = (None, False) + join_tables_registry = None + try: + output_stream, close_output_on_finish = (sys.stdout, False) if output_path is None else (open(output_path, 'wb'), True) + + if not rbql_csv.is_ascii(query_text) and output_csv_encoding == 'latin-1': + raise rbql_engine.RbqlIOHandlingError('To use non-ascii characters in query enable UTF-8 encoding instead of latin-1/binary') + + if not rbql_csv.is_ascii(output_delim) and output_csv_encoding == 'latin-1': + raise rbql_engine.RbqlIOHandlingError('To use non-ascii separators enable UTF-8 encoding instead of latin-1/binary') + + default_init_source_path = os.path.join(os.path.expanduser('~'), '.rbql_init_source.py') + if user_init_code == '' and os.path.exists(default_init_source_path): + user_init_code = rbql_csv.read_user_init_code(default_init_source_path) + + join_tables_registry = SqliteDbRegistry(db_connection) + input_iterator = SqliteRecordIterator(db_connection, input_table_name) + output_writer = rbql_csv.CSVWriter(output_stream, close_output_on_finish, output_csv_encoding, output_delim, output_policy, colorize_output=colorize_output) + rbql_engine.query(query_text, input_iterator, output_writer, output_warnings, join_tables_registry, user_init_code) + finally: + if close_output_on_finish: + output_stream.close() + + diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql_logo.png b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/rbql_logo.png new file mode 100644 index 0000000000000000000000000000000000000000..553a33f141834a30472e5f962cacf78c7481b901 GIT binary patch literal 113463 zcmeEtWmuG57w$7dN_Ur_h=6oA(nz<`jndsPgdj*rNjHLYcY}0yH%NEqobmnY{l4@6 z{5ls8Gw{sJ-m}+Uaj$!=9ipTlg^ogk0ssKIjI_8403g8r1VfM!VNadsQ<<BoF}ZV7DMU0N~650DA@iz?T33gmx(n$^x(#5RKkR zi389-KN-z=F|a$&?4;j20)VX6pI^{c(MK`ZO(Z87c?qQ7ATm5^rgv{9_F*FeGUB3Y zZu1AJt|>3o6I)x4d7V|a)5sEuiP-#+yVc$*D6)Ri3VjZ`)4 zqZC^HI>^XE21m!Bp~)Q_?d~petEXOHOHJkTIg91(CZ_G)3wZ^#)OO^nIyc&`c-*1? z8blMt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1*R8GjX@p?1 z1d@Tj`|BN`n|D6+y8mr}VA+pvN?t)Rqa0}Mdh68g$C?*L9$#vTrJ29bZB#iqmvxn0 zILgy@_<8Klu1%m%eRA|k9u8v{2w}7MszSIC59_+RE{0kYYe&DQYJ_%eT3U}krER9k zrj4<|mL2&&?Zk3*2L%G|aW>f?$XdO`7FWj|4x0)C6ucUt<#>o7mmI>H_s$8Mn}T&U zpHAvu+<=5zJkp!F&o=Z~I+plV783z{e6r-{$4 z?pu%F>s#+K+|A{Xh?(`JN*m>l!8F+;5cYk`-UA8etW58(eHi6V$)OAWV4$CB>m?vA zFS}2=ocy~-Bwo_Fd6u*9Z)*GuO$mT?x{{Tghjz)fU*9KLPW#>Lsz53LZ%r|V@s;H1 z;fD|3ObJgjWXks(%wrBF-q-&9fhJast(@-HIe#qHkj;03?-$@4y1R$@cm0L-Pgxvt zEC~2NFH+AeE9Y4#JDuz^gD}Yhn=tLx_3=@8z{qpoJN=OqZG+Qs z$1@FAF#W+nFWz>hh4}+gO9K-F z9G5XK9D)k$!Pf(h>)H@5_=$)njKKUmB>c~LToCwhAcfap>VxA}=Kl{TA9_8}@Ujmr zVRQhG%;~FQ=Idnd>n!c);|zWvQDIS00bvmVQAs0FVd=lFOJ5fk5Ehdb7Um2g%Kqa7 zPcJ7om!SXm2}WG?+~5Q{%pGoex%dXy`#3`Z0Re(;cRcPn+Iu?-dil6!Z^G$8BS=F< LSGh*fF7kf>wt2Oz literal 0 HcmV?d00001 diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/vscode_rbql.py b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/vscode_rbql.py new file mode 100644 index 00000000..dcf52829 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_core/vscode_rbql.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python +from __future__ import unicode_literals +from __future__ import print_function + +import os +import sys +import codecs +import time +import tempfile +import subprocess +import argparse +import json +import base64 + +import rbql + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('query', help='Query string') + parser.add_argument('input_table_path', metavar='FILE', help='input path') + parser.add_argument('delim', help='Delimiter') + parser.add_argument('policy', help='csv split policy') + parser.add_argument('output_table_path', metavar='FILE', help='output path') + parser.add_argument('output_delim', help='Out Delimiter') + parser.add_argument('output_policy', help='Out csv policy') + parser.add_argument('encoding', help='encoding') + parser.add_argument('--with_headers', action='store_true', help='use headers') + args = parser.parse_args() + + delim = args.delim + policy = args.policy + output_delim = args.output_delim + output_policy = args.output_policy + query = base64.standard_b64decode(args.query).decode("utf-8") + input_path = args.input_table_path + csv_encoding = args.encoding + output_path = args.output_table_path + with_headers = args.with_headers + + try: + warnings = [] + rbql.query_csv(query, input_path, delim, policy, output_path, output_delim, output_policy, csv_encoding, warnings, with_headers) + sys.stdout.write(json.dumps({'warnings': warnings})) + except Exception as e: + error_type, error_msg = rbql.exception_to_error_info(e) + sys.stdout.write(json.dumps({'error_type': error_type, 'error_msg': error_msg})) + + +if __name__ == '__main__': + main() diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_logo.svg b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_logo.svg new file mode 100644 index 00000000..8b5967b5 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_suggest.js b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_suggest.js new file mode 100644 index 00000000..1a21c3a8 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/rbql_suggest.js @@ -0,0 +1,286 @@ +let rbql_suggest = {}; + +( function() { + +rbql_suggest.active_suggest_idx = null; +rbql_suggest.suggest_list = [] +rbql_suggest.apply_suggest_callback = null; +rbql_suggest.autosuggest_header_vars = []; +rbql_suggest.input_id = null; +rbql_suggest.suggest_list_id = null; +rbql_suggest.suggest_entry_class = null; +rbql_suggest.current_join_table_id = null; +rbql_suggest.fetch_join_header_callback = null; + + + +function js_string_escape_column_name(column_name, quote_char) { + column_name = column_name.replace(/\\/g, '\\\\'); + column_name = column_name.replace(/\n/g, '\\n'); + column_name = column_name.replace(/\r/g, '\\r'); + column_name = column_name.replace(/\t/g, '\\t'); + if (quote_char === "'") + return column_name.replace(/'/g, "\\'"); + if (quote_char === '"') + return column_name.replace(/"/g, '\\"'); + return column_name.replace(/`/g, "\\`"); +} + + +function convert_header_to_rbql_variables(header, table_var_prefix) { + let max_suggest_len = 100; // Suggest UI could become unresponsive if there are too many suggest options to consider + let result = []; + for (let h of header) { + let column_var_options = {orig_column_name: h, table_var_prefix: table_var_prefix}; + if (h.match('^[_a-zA-Z][_a-zA-Z0-9]*$') !== null) { + column_var_options.dot_var = `${table_var_prefix}.${h}`; + } else { + column_var_options.dot_var = null; + } + let escaped_column_name = js_string_escape_column_name(h, '"'); + column_var_options.double_q_var = `${table_var_prefix}["${escaped_column_name}"]`; + escaped_column_name = js_string_escape_column_name(h, "'"); + column_var_options.single_q_var = `${table_var_prefix}['${escaped_column_name}']`; + result.push(column_var_options); + if (result.length > max_suggest_len) + break; + } + return result; +} + + +function initialize_suggest(input_id, suggest_list_id, suggest_entry_class, apply_suggest_callback, header, fetch_join_header_callback=null) { + if (!header) + header = []; + rbql_suggest.autosuggest_header_vars = convert_header_to_rbql_variables(header, 'a'); + rbql_suggest.active_suggest_idx = null; + rbql_suggest.suggest_list = [] + rbql_suggest.input_id = input_id; + rbql_suggest.suggest_list_id = suggest_list_id; + rbql_suggest.suggest_entry_class = suggest_entry_class; + rbql_suggest.apply_suggest_callback = apply_suggest_callback; + rbql_suggest.fetch_join_header_callback = fetch_join_header_callback; +} + + +function hide_suggest(suggest_div) { + if (rbql_suggest.active_suggest_idx !== null) { + suggest_div.style.display = 'none'; + rbql_suggest.active_suggest_idx = null; + rbql_suggest.suggest_list = []; + } +} + + +function apply_suggest(suggest_index) { + try { + let rbql_input = document.getElementById(rbql_suggest.input_id); + rbql_input.value = rbql_suggest.suggest_list[suggest_index][0]; + rbql_input.selectionStart = rbql_suggest.suggest_list[suggest_index][1]; + rbql_input.selectionEnd = rbql_suggest.suggest_list[suggest_index][1]; + rbql_input.focus(); + if (rbql_suggest.apply_suggest_callback) { + rbql_suggest.apply_suggest_callback(rbql_suggest.suggest_list[suggest_index][0]); + } + hide_suggest(document.getElementById(rbql_suggest.suggest_list_id)); + } catch (e) { + console.error(`Autocomplete error: ${e}`); + } +} + + +function register_suggest_callback(button_element, suggest_index) { + button_element.addEventListener("click", () => { + apply_suggest(suggest_index); + }); +} + + +function highlight_active_suggest_entry(do_highlight) { + let entry_button = document.getElementById(`rbql_suggest_var_${rbql_suggest.active_suggest_idx}`); + if (!entry_button) + return; + if (do_highlight) { + let active_entry_class = rbql_suggest.suggest_entry_class + '_active'; + entry_button.className = [rbql_suggest.suggest_entry_class, active_entry_class].join(' '); + entry_button.scrollIntoView(); + } else { + entry_button.className = rbql_suggest.suggest_entry_class; + } +} + + +function remove_children(root_node) { + while (root_node.firstChild) { + root_node.removeChild(root_node.firstChild); + } +} + + +function show_suggest(suggest_div, query_before_var, relevant_suggest_list, query_after_cursor) { + let rbql_input = document.getElementById(rbql_suggest.input_id); + let caret_left_shift = 0; + try { + let caret_coordinates = getCaretCoordinates(rbql_input, rbql_input.selectionStart); + caret_left_shift = caret_coordinates.left ? caret_coordinates.left : 0; + } catch (e) { + caret_left_shift = 0; + } + remove_children(suggest_div); + rbql_suggest.active_suggest_idx = 0; + rbql_suggest.suggest_list = []; + for (let i = 0; i < relevant_suggest_list.length; i++) { + let suggest_text = relevant_suggest_list[i]; + let entry_button = document.createElement('button'); + entry_button.className = rbql_suggest.suggest_entry_class; + entry_button.textContent = suggest_text; + entry_button.setAttribute('id', `rbql_suggest_var_${i}`); + register_suggest_callback(entry_button, i); + suggest_div.appendChild(entry_button); + rbql_suggest.suggest_list.push([query_before_var + suggest_text + query_after_cursor, (query_before_var + suggest_text).length]); + } + highlight_active_suggest_entry(true); + suggest_div.style.display = 'block'; + let calculated_height = suggest_div.offsetHeight; + let calculated_width = suggest_div.offsetWidth; + let box = rbql_input.getBoundingClientRect(); + suggest_div.style.left = Math.max(0, Math.min(box.left + caret_left_shift, box.right - calculated_width)) + 'px'; + suggest_div.style.top = (box.top - calculated_height) + 'px'; +} + + +function switch_active_suggest(direction) { + if (rbql_suggest.active_suggest_idx === null) + return false; + highlight_active_suggest_entry(false); + if (direction == 'up') { + rbql_suggest.active_suggest_idx = (rbql_suggest.active_suggest_idx + rbql_suggest.suggest_list.length - 1) % rbql_suggest.suggest_list.length; + } else { + rbql_suggest.active_suggest_idx = (rbql_suggest.active_suggest_idx + 1) % rbql_suggest.suggest_list.length; + } + highlight_active_suggest_entry(true); + return true; +} + + +function is_printable_key_code(keycode) { + // Taken from here: https://stackoverflow.com/a/12467610/2898283 + return (keycode > 47 && keycode < 58) || keycode == 32 || (keycode > 64 && keycode < 91) || (keycode > 185 && keycode < 193) || (keycode > 218 && keycode < 223); +} + + +function handle_input_keydown(event) { + // We need this logic to prevent the caret from going to the start of the input field with the default arrow-up keydown handler + try { + if (event.keyCode == 38) { + if (switch_active_suggest('up')) + event.preventDefault(); + } else if (event.keyCode == 40) { + if (switch_active_suggest('down')) + event.preventDefault(); + } else if (event.keyCode == 39) { + if (rbql_suggest.active_suggest_idx !== null) { + apply_suggest(rbql_suggest.active_suggest_idx); + event.preventDefault(); + } + } + } catch (e) { + console.error(`Autocomplete error: ${e}`); + } +} + + +function variable_has_prefix(full_variable, cursor_var_prefix) { + return full_variable && full_variable.toLowerCase().startsWith(cursor_var_prefix.toLowerCase()) && full_variable != cursor_var_prefix; +} + + +function get_best_matching_variable(cursor_var_prefix, column_var_options) { + if (cursor_var_prefix.startsWith(column_var_options.table_var_prefix + '.')) { + if (variable_has_prefix(column_var_options.dot_var, cursor_var_prefix)) + return column_var_options.dot_var; + if (variable_has_prefix(column_var_options.table_var_prefix + '.' + column_var_options.orig_column_name, cursor_var_prefix)) + return column_var_options.single_q_var; + } + if (variable_has_prefix(column_var_options.single_q_var, cursor_var_prefix)) + return column_var_options.single_q_var; + if (variable_has_prefix(column_var_options.double_q_var, cursor_var_prefix)) + return column_var_options.double_q_var; + return null; +} + + +function get_join_table_id(query) { + let match = query.match(/ join +([^ ]+)(?: *$| +o$| +on)/i); + if (!match) + return null; + return match[1]; +} + + +function adjust_join_table_header_callback(join_header) { + if (!join_header || !join_header.length) { + rbql_suggest.autosuggest_header_vars = rbql_suggest.autosuggest_header_vars.filter(v => v.table_var_prefix != 'b'); + } else { + let join_header_vars = convert_header_to_rbql_variables(join_header, 'b'); + rbql_suggest.autosuggest_header_vars = rbql_suggest.autosuggest_header_vars.concat(join_header_vars); + } +} + + +function handle_input_keyup(event) { + try { + if (event.keyCode == 13) { + if (rbql_suggest.active_suggest_idx !== null) + apply_suggest(rbql_suggest.active_suggest_idx); + return; + } + if (is_printable_key_code(event.keyCode) || event.keyCode == 8 /* Bakspace */) { + // We can't move this into the keydown handler because the characters appear in the input box only after keyUp event. + // Or alternatively we could scan the event.keyCode to find out the next char, but this is additional logic + let rbql_input = document.getElementById(rbql_suggest.input_id); + let current_query = rbql_input.value; + if (rbql_suggest.fetch_join_header_callback !== null) { + let join_table_id = get_join_table_id(current_query); + if (rbql_suggest.current_join_table_id != join_table_id) { + rbql_suggest.current_join_table_id = join_table_id; + if (join_table_id === null) { + adjust_join_table_header_callback([]); + } else { + rbql_suggest.fetch_join_header_callback(join_table_id, adjust_join_table_header_callback) + } + } + } + let suggest_div = document.getElementById(rbql_suggest.suggest_list_id); + hide_suggest(suggest_div); + let cursor_pos = rbql_input.selectionStart; + let query_before_cursor = current_query.substr(0, cursor_pos); + let query_after_cursor = current_query.substr(cursor_pos); + // TODO improve the match - just find last var-looking expression. The problem with this one - it won't match extended suggest like a.arbitrary-var -> a['arbitrary-var'] + let last_var_prefix_match = query_before_cursor.match(/(?:[^_a-zA-Z0-9])([ab](?:\.[_a-zA-Z0-9]*|\[[^\]]*))$/); + if (last_var_prefix_match) { + let relevant_suggest_list = []; + let cursor_var_prefix = last_var_prefix_match[1]; + let query_before_var = query_before_cursor.substr(0, last_var_prefix_match.index + 1); + for (let column_var_options of rbql_suggest.autosuggest_header_vars) { + let suggested_var = get_best_matching_variable(cursor_var_prefix, column_var_options); + if (suggested_var) + relevant_suggest_list.push(suggested_var); + } + if (relevant_suggest_list.length) { + show_suggest(suggest_div, query_before_var, relevant_suggest_list, query_after_cursor); + } + } + } + } catch (e) { + console.error(`Autocomplete error: ${e}`); + } +} + + +rbql_suggest.initialize_suggest = initialize_suggest; +rbql_suggest.handle_input_keydown = handle_input_keydown; +rbql_suggest.handle_input_keyup = handle_input_keyup; +rbql_suggest.convert_header_to_rbql_variables = convert_header_to_rbql_variables; + +} )(); diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/clnsv.tmLanguage.json b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/clnsv.tmLanguage.json new file mode 100644 index 00000000..13f853e4 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/clnsv.tmLanguage.json @@ -0,0 +1,23 @@ +{ "name": "clnsv syntax", + "scopeName": "text.clnsv", + "fileTypes": [], + "patterns": [ + { "match": "([^:]*:?)([^:]*:?)([^:]*:?)([^:]*:?)([^:]*:?)([^:]*:?)([^:]*:?)([^:]*:?)([^:]*:?)([^:]*:?)", + "name": "rainbowgroup", + "captures": { + "1": {"name": "rainbow1"}, + "2": {"name": "keyword.rainbow2"}, + "3": {"name": "entity.name.function.rainbow3"}, + "4": {"name": "comment.rainbow4"}, + "5": {"name": "string.rainbow5"}, + "6": {"name": "variable.parameter.rainbow6"}, + "7": {"name": "constant.numeric.rainbow7"}, + "8": {"name": "entity.name.type.rainbow8"}, + "9": {"name": "markup.bold.rainbow9"}, + "10": {"name": "invalid.rainbow10"} + } + } + + ], + "uuid": "ca03e352-04ef-4340-9a6b-9b99aae1c058" +} diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/crtsv.tmLanguage.json b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/crtsv.tmLanguage.json new file mode 100644 index 00000000..44cd560a --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/crtsv.tmLanguage.json @@ -0,0 +1,23 @@ +{ "name": "crtsv syntax", + "scopeName": "text.crtsv", + "fileTypes": [], + "patterns": [ + { "match": "([^^]*\\^?)([^^]*\\^?)([^^]*\\^?)([^^]*\\^?)([^^]*\\^?)([^^]*\\^?)([^^]*\\^?)([^^]*\\^?)([^^]*\\^?)([^^]*\\^?)", + "name": "rainbowgroup", + "captures": { + "1": {"name": "rainbow1"}, + "2": {"name": "keyword.rainbow2"}, + "3": {"name": "entity.name.function.rainbow3"}, + "4": {"name": "comment.rainbow4"}, + "5": {"name": "string.rainbow5"}, + "6": {"name": "variable.parameter.rainbow6"}, + "7": {"name": "constant.numeric.rainbow7"}, + "8": {"name": "entity.name.type.rainbow8"}, + "9": {"name": "markup.bold.rainbow9"}, + "10": {"name": "invalid.rainbow10"} + } + } + + ], + "uuid": "ca03e352-04ef-4340-9a6b-9b99aae1c094" +} diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/csv.tmLanguage.json b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/csv.tmLanguage.json new file mode 100644 index 00000000..ad92873d --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/csv.tmLanguage.json @@ -0,0 +1,23 @@ +{ "name": "csv syntax", + "scopeName": "text.csv", + "fileTypes": ["csv"], + "patterns": [ + { "match": "((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:,|$))|(?:[^,]*(?:,|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:,|$))|(?:[^,]*(?:,|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:,|$))|(?:[^,]*(?:,|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:,|$))|(?:[^,]*(?:,|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:,|$))|(?:[^,]*(?:,|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:,|$))|(?:[^,]*(?:,|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:,|$))|(?:[^,]*(?:,|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:,|$))|(?:[^,]*(?:,|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:,|$))|(?:[^,]*(?:,|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:,|$))|(?:[^,]*(?:,|$)))?", + "name": "rainbowgroup", + "captures": { + "1": {"name": "rainbow1"}, + "2": {"name": "keyword.rainbow2"}, + "3": {"name": "entity.name.function.rainbow3"}, + "4": {"name": "comment.rainbow4"}, + "5": {"name": "string.rainbow5"}, + "6": {"name": "variable.parameter.rainbow6"}, + "7": {"name": "constant.numeric.rainbow7"}, + "8": {"name": "entity.name.type.rainbow8"}, + "9": {"name": "markup.bold.rainbow9"}, + "10": {"name": "invalid.rainbow10"} + } + } + + ], + "uuid": "ca03e352-04ef-4340-9a6b-9b99aae1c418" +} diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/dbqsv.tmLanguage.json b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/dbqsv.tmLanguage.json new file mode 100644 index 00000000..9d86810f --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/dbqsv.tmLanguage.json @@ -0,0 +1,23 @@ +{ "name": "dbqsv syntax", + "scopeName": "text.dbqsv", + "fileTypes": [], + "patterns": [ + { "match": "([^\"]*\"?)([^\"]*\"?)([^\"]*\"?)([^\"]*\"?)([^\"]*\"?)([^\"]*\"?)([^\"]*\"?)([^\"]*\"?)([^\"]*\"?)([^\"]*\"?)", + "name": "rainbowgroup", + "captures": { + "1": {"name": "rainbow1"}, + "2": {"name": "keyword.rainbow2"}, + "3": {"name": "entity.name.function.rainbow3"}, + "4": {"name": "comment.rainbow4"}, + "5": {"name": "string.rainbow5"}, + "6": {"name": "variable.parameter.rainbow6"}, + "7": {"name": "constant.numeric.rainbow7"}, + "8": {"name": "entity.name.type.rainbow8"}, + "9": {"name": "markup.bold.rainbow9"}, + "10": {"name": "invalid.rainbow10"} + } + } + + ], + "uuid": "ca03e352-04ef-4340-9a6b-9b99aae1c034" +} diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/dotsv.tmLanguage.json b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/dotsv.tmLanguage.json new file mode 100644 index 00000000..37d18779 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/dotsv.tmLanguage.json @@ -0,0 +1,23 @@ +{ "name": "dotsv syntax", + "scopeName": "text.dotsv", + "fileTypes": [], + "patterns": [ + { "match": "([^.]*\\.?)([^.]*\\.?)([^.]*\\.?)([^.]*\\.?)([^.]*\\.?)([^.]*\\.?)([^.]*\\.?)([^.]*\\.?)([^.]*\\.?)([^.]*\\.?)", + "name": "rainbowgroup", + "captures": { + "1": {"name": "rainbow1"}, + "2": {"name": "keyword.rainbow2"}, + "3": {"name": "entity.name.function.rainbow3"}, + "4": {"name": "comment.rainbow4"}, + "5": {"name": "string.rainbow5"}, + "6": {"name": "variable.parameter.rainbow6"}, + "7": {"name": "constant.numeric.rainbow7"}, + "8": {"name": "entity.name.type.rainbow8"}, + "9": {"name": "markup.bold.rainbow9"}, + "10": {"name": "invalid.rainbow10"} + } + } + + ], + "uuid": "ca03e352-04ef-4340-9a6b-9b99aae1c046" +} diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/eqlsv.tmLanguage.json b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/eqlsv.tmLanguage.json new file mode 100644 index 00000000..44e0026a --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/eqlsv.tmLanguage.json @@ -0,0 +1,23 @@ +{ "name": "eqlsv syntax", + "scopeName": "text.eqlsv", + "fileTypes": [], + "patterns": [ + { "match": "([^=]*=?)([^=]*=?)([^=]*=?)([^=]*=?)([^=]*=?)([^=]*=?)([^=]*=?)([^=]*=?)([^=]*=?)([^=]*=?)", + "name": "rainbowgroup", + "captures": { + "1": {"name": "rainbow1"}, + "2": {"name": "keyword.rainbow2"}, + "3": {"name": "entity.name.function.rainbow3"}, + "4": {"name": "comment.rainbow4"}, + "5": {"name": "string.rainbow5"}, + "6": {"name": "variable.parameter.rainbow6"}, + "7": {"name": "constant.numeric.rainbow7"}, + "8": {"name": "entity.name.type.rainbow8"}, + "9": {"name": "markup.bold.rainbow9"}, + "10": {"name": "invalid.rainbow10"} + } + } + + ], + "uuid": "ca03e352-04ef-4340-9a6b-9b99aae1c061" +} diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/hypsv.tmLanguage.json b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/hypsv.tmLanguage.json new file mode 100644 index 00000000..1135b246 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/hypsv.tmLanguage.json @@ -0,0 +1,23 @@ +{ "name": "hypsv syntax", + "scopeName": "text.hypsv", + "fileTypes": [], + "patterns": [ + { "match": "([^\\-]*-?)([^\\-]*-?)([^\\-]*-?)([^\\-]*-?)([^\\-]*-?)([^\\-]*-?)([^\\-]*-?)([^\\-]*-?)([^\\-]*-?)([^\\-]*-?)", + "name": "rainbowgroup", + "captures": { + "1": {"name": "rainbow1"}, + "2": {"name": "keyword.rainbow2"}, + "3": {"name": "entity.name.function.rainbow3"}, + "4": {"name": "comment.rainbow4"}, + "5": {"name": "string.rainbow5"}, + "6": {"name": "variable.parameter.rainbow6"}, + "7": {"name": "constant.numeric.rainbow7"}, + "8": {"name": "entity.name.type.rainbow8"}, + "9": {"name": "markup.bold.rainbow9"}, + "10": {"name": "invalid.rainbow10"} + } + } + + ], + "uuid": "ca03e352-04ef-4340-9a6b-9b99aae1c045" +} diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/pipe_simple.tmLanguage.json b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/pipe_simple.tmLanguage.json new file mode 100644 index 00000000..78fd7d49 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/pipe_simple.tmLanguage.json @@ -0,0 +1,23 @@ +{ "name": "pipe syntax", + "scopeName": "text.psv", + "fileTypes": [], + "patterns": [ + { "match": "([^|]*\\|?)([^|]*\\|?)([^|]*\\|?)([^|]*\\|?)([^|]*\\|?)([^|]*\\|?)([^|]*\\|?)([^|]*\\|?)([^|]*\\|?)([^|]*\\|?)", + "name": "rainbowgroup", + "captures": { + "1": {"name": "rainbow1"}, + "2": {"name": "keyword.rainbow2"}, + "3": {"name": "entity.name.function.rainbow3"}, + "4": {"name": "comment.rainbow4"}, + "5": {"name": "string.rainbow5"}, + "6": {"name": "variable.parameter.rainbow6"}, + "7": {"name": "constant.numeric.rainbow7"}, + "8": {"name": "entity.name.type.rainbow8"}, + "9": {"name": "markup.bold.rainbow9"}, + "10": {"name": "invalid.rainbow10"} + } + } + + ], + "uuid": "ca13e332-04ef-1340-9a6b-9b99aae1c418" +} diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/rb_hover.tmLanguage.json b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/rb_hover.tmLanguage.json new file mode 100644 index 00000000..15446eac --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/rb_hover.tmLanguage.json @@ -0,0 +1,91 @@ +{ "name": "rbhover syntax", + "scopeName": "text.rbhover", + "fileTypes": ["rbhover"], + "patterns": [ + { + "match": "^Col #[0-9]*1(?:[^0-9].*?)?( WARN: Inconsistent num of fields, header: [0-9]*, this line: [0-9]*)?( ERR: Inconsistent double quotes in line)?$", + "name": "rainbow1", + "captures": { + "1": {"name": "entity.name.function"}, + "2": {"name": "invalid"} + } + }, + { + "match": "^Col #[0-9]*2(?:[^0-9].*?)?( WARN: Inconsistent num of fields, header: [0-9]*, this line: [0-9]*)?( ERR: Inconsistent double quotes in line)?$", + "name": "keyword.rainbow2", + "captures": { + "1": {"name": "entity.name.function"}, + "2": {"name": "invalid"} + } + }, + { + "match": "^Col #[0-9]*3(?:[^0-9].*?)?( WARN: Inconsistent num of fields, header: [0-9]*, this line: [0-9]*)?( ERR: Inconsistent double quotes in line)?$", + "name": "entity.name.function.rainbow3", + "captures": { + "1": {"name": "entity.name.function"}, + "2": {"name": "invalid"} + } + }, + { + "match": "^Col #[0-9]*4(?:[^0-9].*?)?( WARN: Inconsistent num of fields, header: [0-9]*, this line: [0-9]*)?( ERR: Inconsistent double quotes in line)?$", + "name": "comment.rainbow4", + "captures": { + "1": {"name": "entity.name.function"}, + "2": {"name": "invalid"} + } + }, + { + "match": "^Col #[0-9]*5(?:[^0-9].*?)?( WARN: Inconsistent num of fields, header: [0-9]*, this line: [0-9]*)?( ERR: Inconsistent double quotes in line)?$", + "name": "string.rainbow5", + "captures": { + "1": {"name": "entity.name.function"}, + "2": {"name": "invalid"} + } + }, + { + "match": "^Col #[0-9]*6(?:[^0-9].*?)?( WARN: Inconsistent num of fields, header: [0-9]*, this line: [0-9]*)?( ERR: Inconsistent double quotes in line)?$", + "name": "variable.parameter.rainbow6", + "captures": { + "1": {"name": "entity.name.function"}, + "2": {"name": "invalid"} + } + }, + { + "match": "^Col #[0-9]*7(?:[^0-9].*?)?( WARN: Inconsistent num of fields, header: [0-9]*, this line: [0-9]*)?( ERR: Inconsistent double quotes in line)?$", + "name": "constant.numeric.rainbow7", + "captures": { + "1": {"name": "entity.name.function"}, + "2": {"name": "invalid"} + } + }, + { + "match": "^Col #[0-9]*8(?:[^0-9].*?)?( WARN: Inconsistent num of fields, header: [0-9]*, this line: [0-9]*)?( ERR: Inconsistent double quotes in line)?$", + "name": "entity.name.type.rainbow8", + "captures": { + "1": {"name": "entity.name.function"}, + "2": {"name": "invalid"} + } + }, + { + "match": "^Col #[0-9]*9(?:[^0-9].*?)?( WARN: Inconsistent num of fields, header: [0-9]*, this line: [0-9]*)?( ERR: Inconsistent double quotes in line)?$", + "name": "markup.bold.rainbow9", + "captures": { + "1": {"name": "entity.name.function"}, + "2": {"name": "invalid"} + } + }, + { + "match": "^Col #[0-9]*0(?:[^0-9].*?)?( WARN: Inconsistent num of fields, header: [0-9]*, this line: [0-9]*)?( ERR: Inconsistent double quotes in line)?$", + "name": "invalid.rainbow10", + "captures": { + "1": {"name": "entity.name.function"}, + "2": {"name": "invalid"} + } + }, + { + "match": "^Comment *$", + "name": "comment" + } + ], + "uuid": "cb14e353-04bf-4319-9a2b-9b99aae1c419" +} diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/scsv.tmLanguage.json b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/scsv.tmLanguage.json new file mode 100644 index 00000000..220c0075 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/scsv.tmLanguage.json @@ -0,0 +1,23 @@ +{ "name": "scsv syntax", + "scopeName": "text.scsv", + "fileTypes": ["scsv"], + "patterns": [ + { "match": "((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:;|$))|(?:[^;]*(?:;|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:;|$))|(?:[^;]*(?:;|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:;|$))|(?:[^;]*(?:;|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:;|$))|(?:[^;]*(?:;|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:;|$))|(?:[^;]*(?:;|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:;|$))|(?:[^;]*(?:;|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:;|$))|(?:[^;]*(?:;|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:;|$))|(?:[^;]*(?:;|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:;|$))|(?:[^;]*(?:;|$)))?((?: *\"(?:[^\"]*\"\")*[^\"]*\" *(?:;|$))|(?:[^;]*(?:;|$)))?", + "name": "rainbowgroup", + "captures": { + "1": {"name": "rainbow1"}, + "2": {"name": "keyword.rainbow2"}, + "3": {"name": "entity.name.function.rainbow3"}, + "4": {"name": "comment.rainbow4"}, + "5": {"name": "string.rainbow5"}, + "6": {"name": "variable.parameter.rainbow6"}, + "7": {"name": "constant.numeric.rainbow7"}, + "8": {"name": "entity.name.type.rainbow8"}, + "9": {"name": "markup.bold.rainbow9"}, + "10": {"name": "invalid.rainbow10"} + } + } + + ], + "uuid": "cb13e352-03bf-4340-9a6b-9b99aae1c418" +} diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/tldsv.tmLanguage.json b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/tldsv.tmLanguage.json new file mode 100644 index 00000000..2d404eef --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/tldsv.tmLanguage.json @@ -0,0 +1,23 @@ +{ "name": "tldsv syntax", + "scopeName": "text.tldsv", + "fileTypes": [], + "patterns": [ + { "match": "([^~]*~?)([^~]*~?)([^~]*~?)([^~]*~?)([^~]*~?)([^~]*~?)([^~]*~?)([^~]*~?)([^~]*~?)([^~]*~?)", + "name": "rainbowgroup", + "captures": { + "1": {"name": "rainbow1"}, + "2": {"name": "keyword.rainbow2"}, + "3": {"name": "entity.name.function.rainbow3"}, + "4": {"name": "comment.rainbow4"}, + "5": {"name": "string.rainbow5"}, + "6": {"name": "variable.parameter.rainbow6"}, + "7": {"name": "constant.numeric.rainbow7"}, + "8": {"name": "entity.name.type.rainbow8"}, + "9": {"name": "markup.bold.rainbow9"}, + "10": {"name": "invalid.rainbow10"} + } + } + + ], + "uuid": "ca03e352-04ef-4340-9a6b-9b99aae1c126" +} diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/tsv.tmLanguage.json b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/tsv.tmLanguage.json new file mode 100644 index 00000000..8346ff47 --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/tsv.tmLanguage.json @@ -0,0 +1,23 @@ +{ "name": "tsv syntax", + "scopeName": "text.tsv", + "fileTypes": ["tsv", "tab"], + "patterns": [ + { "match": "([^\\t]*\\t?)([^\\t]*\\t?)([^\\t]*\\t?)([^\\t]*\\t?)([^\\t]*\\t?)([^\\t]*\\t?)([^\\t]*\\t?)([^\\t]*\\t?)([^\\t]*\\t?)([^\\t]*\\t?)", + "name": "rainbowgroup", + "captures": { + "1": {"name": "rainbow1"}, + "2": {"name": "keyword.rainbow2"}, + "3": {"name": "entity.name.function.rainbow3"}, + "4": {"name": "comment.rainbow4"}, + "5": {"name": "string.rainbow5"}, + "6": {"name": "variable.parameter.rainbow6"}, + "7": {"name": "constant.numeric.rainbow7"}, + "8": {"name": "entity.name.type.rainbow8"}, + "9": {"name": "markup.bold.rainbow9"}, + "10": {"name": "invalid.rainbow10"} + } + } + + ], + "uuid": "ca13e332-04ef-1340-9a6b-9b99aae1c418" +} diff --git a/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/wspcsv.tmLanguage.json b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/wspcsv.tmLanguage.json new file mode 100644 index 00000000..216e066d --- /dev/null +++ b/vscodium/extensions/mechatroner.rainbow-csv-2.3.0/syntaxes/wspcsv.tmLanguage.json @@ -0,0 +1,23 @@ +{ "name": "wspcsv syntax", + "scopeName": "text.wspcsv", + "fileTypes": [], + "patterns": [ + { "match": "( *[^ ]* *)([^ ]* *)([^ ]* *)([^ ]* *)([^ ]* *)([^ ]* *)([^ ]* *)([^ ]* *)([^ ]* *)([^ ]* *)", + "name": "rainbowgroup", + "captures": { + "1": {"name": "rainbow1"}, + "2": {"name": "keyword.rainbow2"}, + "3": {"name": "entity.name.function.rainbow3"}, + "4": {"name": "comment.rainbow4"}, + "5": {"name": "string.rainbow5"}, + "6": {"name": "variable.parameter.rainbow6"}, + "7": {"name": "constant.numeric.rainbow7"}, + "8": {"name": "entity.name.type.rainbow8"}, + "9": {"name": "markup.bold.rainbow9"}, + "10": {"name": "invalid.rainbow10"} + } + } + + ], + "uuid": "ca02e451-04ef-4040-9a6b-9b99aae1c058" +} diff --git a/vscodium/extensions/visualstudioexptteam.vscodeintellicode-1.2.20/cache/models.json b/vscodium/extensions/visualstudioexptteam.vscodeintellicode-1.2.20/cache/models.json index 2a9f91eb..e470f608 100644 --- a/vscodium/extensions/visualstudioexptteam.vscodeintellicode-1.2.20/cache/models.json +++ b/vscodium/extensions/visualstudioexptteam.vscodeintellicode-1.2.20/cache/models.json @@ -1 +1 @@ -[{"analyzerName":"intellisense-members-lstm-pylance","languageName":"python","identity":{"modelId":"E61945A9A512ED5E1A3EE3F1A2365B88F8FE","outputId":"E4E9EADA96734F01970E616FAB2FAC19","modifiedTimeUtc":"2020-08-11T14:06:50.811Z"},"filePath":"/home/kristofers/.vscode/extensions/visualstudioexptteam.vscodeintellicode-1.2.20/cache/E61945A9A512ED5E1A3EE3F1A2365B88F8FE_E4E9EADA96734F01970E616FAB2FAC19","lastAccessTimeUtc":"2022-04-28T20:51:11.821Z"}] \ No newline at end of file +[{"analyzerName":"intellisense-members-lstm-pylance","languageName":"python","identity":{"modelId":"E61945A9A512ED5E1A3EE3F1A2365B88F8FE","outputId":"E4E9EADA96734F01970E616FAB2FAC19","modifiedTimeUtc":"2020-08-11T14:06:50.811Z"},"filePath":"/home/kristofers/.vscode/extensions/visualstudioexptteam.vscodeintellicode-1.2.20/cache/E61945A9A512ED5E1A3EE3F1A2365B88F8FE_E4E9EADA96734F01970E616FAB2FAC19","lastAccessTimeUtc":"2022-05-01T12:19:01.804Z"}] \ No newline at end of file diff --git a/vscodium/settings.json b/vscodium/settings.json index abb0aedd..73ab011b 100644 --- a/vscodium/settings.json +++ b/vscodium/settings.json @@ -18,7 +18,7 @@ "[python]": { "editor.defaultFormatter": "ms-python.python", "editor.insertSpaces": false, - "editor.formatOnSave": true, + "editor.formatOnSave": true }, "editor.insertSpaces": false, "python.terminal.executeInFileDir": true, @@ -57,10 +57,7 @@ "suppressLineUncommittedWarning": true }, "vsicons.dontShowNewVersionMessage": true, - "indentRainbow.excludedLanguages": [ - "plaintext", - "django-txt" - ], + "indentRainbow.excludedLanguages": ["plaintext", "django-txt"], "[markdown]": { "editor.defaultFormatter": "yzhang.markdown-all-in-one" }, @@ -114,4 +111,4 @@ ] }, "workbench.colorTheme": "Sweet Dracula" -} \ No newline at end of file +} diff --git a/zsh/.zshrc b/zsh/.zshrc index 55910599..1f81dc77 100644 --- a/zsh/.zshrc +++ b/zsh/.zshrc @@ -45,7 +45,7 @@ WORDCHARS=${WORDCHARS//\/[&.;]} # Don't consider certain part of the word source /usr/share/zsh/plugins/zsh-autosuggestions/zsh-autosuggestions.zsh 2>/dev/null source /usr/share/zsh/plugins/zsh-history-substring-search/zsh-history-substring-search.zsh 2>/dev/null zmodload zsh/terminfo - +eval "$(lua ~/.config/zsh/z.lua --init zsh)" # Keybindings bindkey -e From 5b8e9b63bb70162a826e63eac9d3447ace3af0c9 Mon Sep 17 00:00:00 2001 From: Kristofers Solo Date: Wed, 4 May 2022 23:35:30 +0300 Subject: [PATCH 4/4] Changed picom --- picom/picom.conf | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/picom/picom.conf b/picom/picom.conf index dd48c39d..f66b3de1 100644 --- a/picom/picom.conf +++ b/picom/picom.conf @@ -436,7 +436,8 @@ opacity-rule = [ "95:class_g = 'code'", "95:class_g = 'code-oss'", "95:class_g = 'vscodium'", - "95:class_g = 'VSCodium'" + "95:class_g = 'VSCodium'", + "90:name = 'Spotify'" ]