Compare commits
79 Commits
macosintel
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0900492ccb | ||
|
|
5db8c6b591 | ||
|
|
9e8bad0084 | ||
|
|
eb8812b26e | ||
|
|
3f56166655 | ||
|
|
69e7e0adf1 | ||
|
|
74378f74bf | ||
|
|
2f31bc7b06 | ||
|
|
4e06d543b3 | ||
|
|
a536c6970f | ||
|
|
e17744faf0 | ||
|
|
a05a600071 | ||
|
|
8b6067f83f | ||
|
|
98e8dc0a67 | ||
|
|
6b8f6aae81 | ||
|
|
dc5c87376b | ||
|
|
db090f3696 | ||
|
|
aee24cdaa1 | ||
|
|
be0ab9b125 | ||
|
|
50ba00b0af | ||
|
|
29e1069bf2 | ||
|
|
c7e57b8913 | ||
|
|
4cea6b26ec | ||
|
|
c2f4b68786 | ||
|
|
e8add5ec08 | ||
|
|
55c23e9d4c | ||
|
|
d77c3cbbe2 | ||
|
|
f89c2322b0 | ||
|
|
ded55a66d6 | ||
|
|
6fbc81675f | ||
|
|
48d97afdf6 | ||
|
|
109fc01c9a | ||
|
|
b185255a0a | ||
|
|
c2d3cddc47 | ||
|
|
8526d2510b | ||
|
|
11e566d0e5 | ||
|
|
ae0165f1fe | ||
|
|
a6505587bf | ||
|
|
b16e13678c | ||
|
|
abe03cef3f | ||
|
|
dd7239b8c1 | ||
|
|
851917e049 | ||
|
|
8d7a7eb434 | ||
|
|
0239b52385 | ||
|
|
19ea8dbc5b | ||
|
|
70959ccada | ||
|
|
5d365f65fa | ||
|
|
cca397c8c7 | ||
|
|
1430d5215a | ||
|
|
c09c5ffa47 | ||
|
|
ed7e69c07e | ||
|
|
f286f92b1f | ||
|
|
e7031a3ae4 | ||
|
|
2f828735a8 | ||
|
|
78c62cfc95 | ||
|
|
ed93614ca3 | ||
|
|
fac26a6ca0 | ||
|
|
48761f62a2 | ||
|
|
dc03bff324 | ||
|
|
e9a52859f6 | ||
|
|
1a10cf2e5f | ||
|
|
1c2d82dc9b | ||
|
|
6ecfa9b954 | ||
|
|
c138f74460 | ||
|
|
8becc7dbc4 | ||
|
|
b29cd7b5f7 | ||
|
|
f21ef9250a | ||
|
|
fa2a92bf89 | ||
|
|
8341411be4 | ||
|
|
22d6c7991e | ||
|
|
795b7f0321 | ||
|
|
9e34e64449 | ||
|
|
ce4cfdd169 | ||
|
|
12b1f183f7 | ||
|
|
4212c7b9e0 | ||
|
|
7794846185 | ||
|
|
150e067039 | ||
|
|
f347fde0c8 | ||
|
|
ff3d5c4841 |
12
.github/actions/install-imagemagick/action.yml
vendored
Normal file
12
.github/actions/install-imagemagick/action.yml
vendored
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
inputs:
|
||||||
|
project-root:
|
||||||
|
required: false
|
||||||
|
default: '.'
|
||||||
|
runs:
|
||||||
|
using: composite
|
||||||
|
steps:
|
||||||
|
-
|
||||||
|
name: Install ImageMagick
|
||||||
|
shell: bash
|
||||||
|
run: ./.github/actions/install-imagemagick/install-imagemagick.sh
|
||||||
|
working-directory: ${{ inputs.project-root }}
|
||||||
56
.github/actions/install-imagemagick/install-imagemagick.sh
vendored
Executable file
56
.github/actions/install-imagemagick/install-imagemagick.sh
vendored
Executable file
@@ -0,0 +1,56 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
main() {
|
||||||
|
local install_command
|
||||||
|
if ! install_command=$(get_install_command); then
|
||||||
|
fatal_error 'Could not find available command to install'
|
||||||
|
fi
|
||||||
|
if ! eval "$install_command"; then
|
||||||
|
echo "Failed to install ImageMagick. Command: ${install_command}"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
echo 'ImageMagick installation completed successfully'
|
||||||
|
}
|
||||||
|
|
||||||
|
get_install_command() {
|
||||||
|
case "$OSTYPE" in
|
||||||
|
darwin*)
|
||||||
|
ensure_command_exists 'brew'
|
||||||
|
echo 'brew install imagemagick'
|
||||||
|
;;
|
||||||
|
linux-gnu*)
|
||||||
|
if is_ubuntu; then
|
||||||
|
ensure_command_exists 'apt'
|
||||||
|
echo 'sudo apt install -y imagemagick'
|
||||||
|
else
|
||||||
|
fatal_error 'Unsupported Linux distribution'
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
msys*|cygwin*)
|
||||||
|
ensure_command_exists 'choco'
|
||||||
|
echo 'choco install -y imagemagick'
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
fatal_error "Unsupported operating system: $OSTYPE"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
ensure_command_exists() {
|
||||||
|
local -r command="$1"
|
||||||
|
if ! command -v "$command" >/dev/null 2>&1; then
|
||||||
|
fatal_error "Command missing: $command"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
fatal_error() {
|
||||||
|
local -r error_message="$1"
|
||||||
|
>&2 echo "❌ $error_message"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
is_ubuntu() {
|
||||||
|
[ -f /etc/os-release ] && grep -qi 'ubuntu' /etc/os-release
|
||||||
|
}
|
||||||
|
|
||||||
|
main
|
||||||
15
.github/actions/upload-artifact/action.yaml
vendored
Normal file
15
.github/actions/upload-artifact/action.yaml
vendored
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
inputs:
|
||||||
|
name:
|
||||||
|
required: true
|
||||||
|
path:
|
||||||
|
required: true
|
||||||
|
|
||||||
|
runs:
|
||||||
|
using: composite
|
||||||
|
steps:
|
||||||
|
-
|
||||||
|
name: Upload artifact
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: ${{ inputs.name }}
|
||||||
|
path: ${{ inputs.path }}
|
||||||
14
.github/workflows/checks.build.yaml
vendored
14
.github/workflows/checks.build.yaml
vendored
@@ -86,21 +86,9 @@ jobs:
|
|||||||
name: Install Docker on macOS
|
name: Install Docker on macOS
|
||||||
if: contains(matrix.os, 'macos') # macOS runner is missing Docker
|
if: contains(matrix.os, 'macos') # macOS runner is missing Docker
|
||||||
run: |-
|
run: |-
|
||||||
# Verify Intel-based macOS
|
|
||||||
arch=$(uname -m)
|
|
||||||
case "$arch" in
|
|
||||||
i386|x86_64)
|
|
||||||
echo "Supported architecture: $arch"
|
|
||||||
;;
|
|
||||||
*)
|
|
||||||
>&2 echo 'The macOS is not running on a supported Intel architecture. Virtualization is not supported.'
|
|
||||||
exit 1
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
# Install Docker
|
# Install Docker
|
||||||
brew install docker
|
brew install docker
|
||||||
# Docker on macOS does not include the Docker daemon due to licensing issues.
|
# Docker on macOS misses daemon due to licensing, so install colima as runtime
|
||||||
# Install Colima to use as the Docker runtime.
|
|
||||||
brew install colima
|
brew install colima
|
||||||
# Start the daemon
|
# Start the daemon
|
||||||
colima start
|
colima start
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ jobs:
|
|||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
os:
|
os:
|
||||||
- macos-latest # Latest Apple silicon (ARM64)
|
- macos-latest # Apple silicon (ARM64)
|
||||||
- macos-12 # Latest Intel-based (x86-64)
|
- macos-13 # Intel-based (x86-64)
|
||||||
- ubuntu-latest
|
- ubuntu-latest
|
||||||
- windows-latest
|
- windows-latest
|
||||||
fail-fast: false # Allows to see results from other combinations
|
fail-fast: false # Allows to see results from other combinations
|
||||||
@@ -26,9 +26,12 @@ jobs:
|
|||||||
-
|
-
|
||||||
name: Install dependencies
|
name: Install dependencies
|
||||||
uses: ./.github/actions/npm-install-dependencies
|
uses: ./.github/actions/npm-install-dependencies
|
||||||
|
-
|
||||||
|
name: Install ImageMagick # For screenshots
|
||||||
|
uses: ./.github/actions/install-imagemagick
|
||||||
-
|
-
|
||||||
name: Configure Ubuntu
|
name: Configure Ubuntu
|
||||||
if: contains(matrix.os, 'ubuntu') # macOS runner is missing Docker
|
if: contains(matrix.os, 'ubuntu')
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |-
|
run: |-
|
||||||
sudo apt update
|
sudo apt update
|
||||||
@@ -56,11 +59,20 @@ jobs:
|
|||||||
sudo Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
|
sudo Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 &
|
||||||
echo "DISPLAY=:99" >> $GITHUB_ENV
|
echo "DISPLAY=:99" >> $GITHUB_ENV
|
||||||
|
|
||||||
# Install ImageMagick for screenshots
|
|
||||||
sudo apt install -y imagemagick
|
|
||||||
|
|
||||||
# Install xdotool and xprop (from x11-utils) for window title capturing
|
# Install xdotool and xprop (from x11-utils) for window title capturing
|
||||||
sudo apt install -y xdotool x11-utils
|
sudo apt install -y xdotool x11-utils
|
||||||
|
|
||||||
|
# Workaround for Electron AppImage apps failing to initialize on Ubuntu 24.04 due to AppArmor restrictions
|
||||||
|
# Disables unprivileged user namespaces restriction to allow Electron apps to run
|
||||||
|
# Reference: https://github.com/electron/electron/issues/42510
|
||||||
|
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
|
||||||
|
|
||||||
|
# Workaround for Mesa driver issues on Ubuntu 24.04
|
||||||
|
# Installs latest Mesa drivers from Kisak PPA
|
||||||
|
# Reference: https://askubuntu.com/q/1516040
|
||||||
|
sudo add-apt-repository ppa:kisak/kisak-mesa
|
||||||
|
sudo apt update
|
||||||
|
sudo apt upgrade
|
||||||
-
|
-
|
||||||
name: Test
|
name: Test
|
||||||
shell: bash
|
shell: bash
|
||||||
@@ -70,7 +82,7 @@ jobs:
|
|||||||
-
|
-
|
||||||
name: Upload screenshot
|
name: Upload screenshot
|
||||||
if: always() # Run even if previous step fails
|
if: always() # Run even if previous step fails
|
||||||
uses: actions/upload-artifact@v3
|
uses: ./.github/actions/upload-artifact
|
||||||
with:
|
with:
|
||||||
name: screenshot-${{ matrix.os }}
|
name: screenshot-${{ matrix.os }}
|
||||||
path: screenshot.png
|
path: screenshot.png
|
||||||
|
|||||||
28
.github/workflows/checks.quality.yaml
vendored
28
.github/workflows/checks.quality.yaml
vendored
@@ -11,8 +11,9 @@ jobs:
|
|||||||
- npm run lint:eslint
|
- npm run lint:eslint
|
||||||
- npm run lint:yaml
|
- npm run lint:yaml
|
||||||
- npm run lint:md
|
- npm run lint:md
|
||||||
- npm run lint:md:relative-urls
|
|
||||||
- npm run lint:md:consistency
|
- npm run lint:md:consistency
|
||||||
|
- npm run lint:md:relative-urls
|
||||||
|
- npm run lint:md:external-urls
|
||||||
os: [ macos, ubuntu, windows ]
|
os: [ macos, ubuntu, windows ]
|
||||||
fail-fast: false # Still interested to see results from other combinations
|
fail-fast: false # Still interested to see results from other combinations
|
||||||
steps:
|
steps:
|
||||||
@@ -74,3 +75,28 @@ jobs:
|
|||||||
-
|
-
|
||||||
name: Analyzing the code with pylint
|
name: Analyzing the code with pylint
|
||||||
run: npm run lint:pylint
|
run: npm run lint:pylint
|
||||||
|
|
||||||
|
validate-collection-files:
|
||||||
|
runs-on: ${{ matrix.os }}-latest
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
os: [ macos, ubuntu, windows ]
|
||||||
|
fail-fast: false # Still interested to see results from other combinations
|
||||||
|
steps:
|
||||||
|
-
|
||||||
|
name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
-
|
||||||
|
name: Setup node
|
||||||
|
uses: ./.github/actions/setup-node
|
||||||
|
-
|
||||||
|
name: Set up Python
|
||||||
|
uses: actions/setup-python@v5
|
||||||
|
with:
|
||||||
|
python-version: '3.x'
|
||||||
|
-
|
||||||
|
name: Install dependencies
|
||||||
|
run: python3 -m pip install -r ./scripts/validate-collections-yaml/requirements.txt
|
||||||
|
-
|
||||||
|
name: Validate
|
||||||
|
run: python3 ./scripts/validate-collections-yaml
|
||||||
|
|||||||
7
.github/workflows/checks.scripts.yaml
vendored
7
.github/workflows/checks.scripts.yaml
vendored
@@ -9,16 +9,15 @@ jobs:
|
|||||||
runs-on: ${{ matrix.os }}-latest
|
runs-on: ${{ matrix.os }}-latest
|
||||||
strategy:
|
strategy:
|
||||||
matrix:
|
matrix:
|
||||||
os: [ macos, ubuntu, windows ]
|
os: [macos, ubuntu, windows]
|
||||||
fail-fast: false # Still interested to see results from other combinations
|
fail-fast: false # Still interested to see results from other combinations
|
||||||
steps:
|
steps:
|
||||||
-
|
-
|
||||||
name: Checkout
|
name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
-
|
-
|
||||||
name: Install ImageMagick on macOS
|
name: Install ImageMagick
|
||||||
if: matrix.os == 'macos'
|
uses: ./.github/actions/install-imagemagick
|
||||||
run: brew install imagemagick
|
|
||||||
-
|
-
|
||||||
name: Setup node
|
name: Setup node
|
||||||
uses: ./.github/actions/setup-node
|
uses: ./.github/actions/setup-node
|
||||||
|
|||||||
4
.github/workflows/tests.e2e.yaml
vendored
4
.github/workflows/tests.e2e.yaml
vendored
@@ -51,14 +51,14 @@ jobs:
|
|||||||
-
|
-
|
||||||
name: Upload screenshots
|
name: Upload screenshots
|
||||||
if: failure() # Run only if previous steps fail because screenshots will be generated only if E2E test failed
|
if: failure() # Run only if previous steps fail because screenshots will be generated only if E2E test failed
|
||||||
uses: actions/upload-artifact@v3
|
uses: ./.github/actions/upload-artifact
|
||||||
with:
|
with:
|
||||||
name: e2e-screenshots-${{ matrix.os }}
|
name: e2e-screenshots-${{ matrix.os }}
|
||||||
path: ${{ steps.artifacts.outputs.SCREENSHOTS_DIR }}
|
path: ${{ steps.artifacts.outputs.SCREENSHOTS_DIR }}
|
||||||
-
|
-
|
||||||
name: Upload videos
|
name: Upload videos
|
||||||
if: always() # Run even if previous steps fail because test run video is always captured
|
if: always() # Run even if previous steps fail because test run video is always captured
|
||||||
uses: actions/upload-artifact@v3
|
uses: ./.github/actions/upload-artifact
|
||||||
with:
|
with:
|
||||||
name: e2e-videos-${{ matrix.os }}
|
name: e2e-videos-${{ matrix.os }}
|
||||||
path: ${{ steps.artifacts.outputs.VIDEOS_DIR }}
|
path: ${{ steps.artifacts.outputs.VIDEOS_DIR }}
|
||||||
|
|||||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -14,3 +14,7 @@ node_modules
|
|||||||
|
|
||||||
# macOS
|
# macOS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
||||||
|
# Python
|
||||||
|
__pycache__
|
||||||
|
.venv
|
||||||
4
.vscode/extensions.json
vendored
4
.vscode/extensions.json
vendored
@@ -5,8 +5,10 @@
|
|||||||
"wengerk.highlight-bad-chars", // Highlights bad chars.
|
"wengerk.highlight-bad-chars", // Highlights bad chars.
|
||||||
"wayou.vscode-todo-highlight", // Highlights TODO.
|
"wayou.vscode-todo-highlight", // Highlights TODO.
|
||||||
"wix.vscode-import-cost", // Shows in KB how much a require include in code.
|
"wix.vscode-import-cost", // Shows in KB how much a require include in code.
|
||||||
// Documentation
|
// Markdown
|
||||||
"davidanson.vscode-markdownlint", // Lints markdown.
|
"davidanson.vscode-markdownlint", // Lints markdown.
|
||||||
|
// YAML
|
||||||
|
"redhat.vscode-yaml", // Lints YAML files, validates against schema.
|
||||||
// TypeScript / JavaScript
|
// TypeScript / JavaScript
|
||||||
"dbaeumer.vscode-eslint", // Lints JavaScript/TypeScript.
|
"dbaeumer.vscode-eslint", // Lints JavaScript/TypeScript.
|
||||||
"pmneo.tsimporter", // Provides better auto-complete for TypeScripts imports.
|
"pmneo.tsimporter", // Provides better auto-complete for TypeScripts imports.
|
||||||
|
|||||||
82
CHANGELOG.md
82
CHANGELOG.md
@@ -1,5 +1,87 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 0.13.6 (2024-08-13)
|
||||||
|
|
||||||
|
* win: improve service disabling as TrustedInstaller | [5d365f6](https://github.com/undergroundwires/privacy.sexy/commit/5d365f65fa0e34925b16b2eac2af53c31e34e99a)
|
||||||
|
* Fix documentation button spacing on small screens | [70959cc](https://github.com/undergroundwires/privacy.sexy/commit/70959ccadafac5abcfa83e90cdb0537890b05f14)
|
||||||
|
* Fix close button overlap by scrollbar | [19ea8db](https://github.com/undergroundwires/privacy.sexy/commit/19ea8dbc5bc2dc436200cd40bf2a84c3fc3c6471)
|
||||||
|
* win: refactor version-specific actions | [0239b52](https://github.com/undergroundwires/privacy.sexy/commit/0239b523859d5c2b80033cc03f0248a9af35f28f)
|
||||||
|
* win: support Microsoft Store Firefox installations | [8d7a7eb](https://github.com/undergroundwires/privacy.sexy/commit/8d7a7eb434b2d83e32fa758db7e6798849bad41c)
|
||||||
|
* Refactor text utilities and expand their usage | [851917e](https://github.com/undergroundwires/privacy.sexy/commit/851917e049c41c679644ddbe8ad4b6e45e5c8f35)
|
||||||
|
* Bump dependencies to latest | [dd7239b](https://github.com/undergroundwires/privacy.sexy/commit/dd7239b8c14027274926279a4c8c7e5845b55558)
|
||||||
|
* Refactor styles to match new CSS nesting behavior | [abe03ce](https://github.com/undergroundwires/privacy.sexy/commit/abe03cef3f691f6e56faee991cd2da9c45244279)
|
||||||
|
* Improve compiler error display for latest Chromium | [b16e136](https://github.com/undergroundwires/privacy.sexy/commit/b16e13678ce1b8a6871eba8196e82bb321410067)
|
||||||
|
* Fix intermittent `ModalDialog` unit test failures | [a650558](https://github.com/undergroundwires/privacy.sexy/commit/a6505587bf4a448f5f3de930004a95ee203416b8)
|
||||||
|
* Ensure tests do not log warning or errors | [ae0165f](https://github.com/undergroundwires/privacy.sexy/commit/ae0165f1fe7dba9dd8ddaa1afa722a939772d3b6)
|
||||||
|
* win: improve disabling SmartScreen #385 | [11e566d](https://github.com/undergroundwires/privacy.sexy/commit/11e566d0e5177214a2600f3fd2097aea62373b24)
|
||||||
|
* win: unify registry setting as TrustedInstaller | [8526d25](https://github.com/undergroundwires/privacy.sexy/commit/8526d2510b34cbd7e79342f79d444419f601b186)
|
||||||
|
* win: improve, fix, restructure CEIP disabling | [c2d3cdd](https://github.com/undergroundwires/privacy.sexy/commit/c2d3cddc47d8d4b34bff63d959612919fa971012)
|
||||||
|
* win: centralize, improve Defender data collection | [b185255](https://github.com/undergroundwires/privacy.sexy/commit/b185255a0a72d5bfa96d6cf60f868ecc67149d68)
|
||||||
|
* win: fix and document VStudio license removal | [109fc01](https://github.com/undergroundwires/privacy.sexy/commit/109fc01c9a047002c4309e7f8a2ca4647c494a8a)
|
||||||
|
* win: improve registry/recent cleaning | [48d97af](https://github.com/undergroundwires/privacy.sexy/commit/48d97afdf6c2964cab7951208e1b0a02c3fd4c9b)
|
||||||
|
* Relax linting to allow null recommendation | [6fbc816](https://github.com/undergroundwires/privacy.sexy/commit/6fbc81675f7f063c4ee2502b8d9f169aacb39ae4)
|
||||||
|
* Refactor executable IDs to use strings #262 | [ded55a6](https://github.com/undergroundwires/privacy.sexy/commit/ded55a66d6044a03d4e18330e146b69d159509a3)
|
||||||
|
* win: fix, improve and unify Windows version logic | [f89c232](https://github.com/undergroundwires/privacy.sexy/commit/f89c2322b05d19b82914b20416ecefd7bc7e3702)
|
||||||
|
* Fix PowerShell code block inlining in compiler | [d77c3cb](https://github.com/undergroundwires/privacy.sexy/commit/d77c3cbbe212d9929e083181cc331b45d01e2883)
|
||||||
|
* win: improve registry value deletion #381 | [55c23e9](https://github.com/undergroundwires/privacy.sexy/commit/55c23e9d4cee3b7f74c26a4ac8516535048d67f2)
|
||||||
|
* win: improve folder hiding in "This PC" #16 | [e8add5e](https://github.com/undergroundwires/privacy.sexy/commit/e8add5ec08d2e8b7636cc9c8f0f9a33e4b004265)
|
||||||
|
* win: improve Microsoft Edge associations removal | [c2f4b68](https://github.com/undergroundwires/privacy.sexy/commit/c2f4b6878635e97f9c4be7bf2ee194a2deebb38a)
|
||||||
|
* win: unify registry data setting, fix #380 | [4cea6b2](https://github.com/undergroundwires/privacy.sexy/commit/4cea6b26ec2717c792c2471cc587f370274f90c4)
|
||||||
|
* win: improve disabling NCSI #189, #216, #279 | [c7e57b8](https://github.com/undergroundwires/privacy.sexy/commit/c7e57b8913f409a1c149ba598dc2f8786df0f9a9)
|
||||||
|
* win, mac: fix minor typos, formatting, dead URLs | [29e1069](https://github.com/undergroundwires/privacy.sexy/commit/29e1069bf2bc317e3c255b38c1ba0ab078b42d98)
|
||||||
|
* win: fix, constrain and document WNS #227 #314 | [50ba00b](https://github.com/undergroundwires/privacy.sexy/commit/50ba00b0af6232fc9187532635b04c4d9d9a68af)
|
||||||
|
|
||||||
|
[compare](https://github.com/undergroundwires/privacy.sexy/compare/0.13.5...0.13.6)
|
||||||
|
|
||||||
|
## 0.13.5 (2024-06-26)
|
||||||
|
|
||||||
|
* ci/cd: centralize and bump artifact uploads | [22d6c79](https://github.com/undergroundwires/privacy.sexy/commit/22d6c7991eb2c138578a7d41950f301906dbf703)
|
||||||
|
* win: document and improve Firefox telemetry #259 | [8341411](https://github.com/undergroundwires/privacy.sexy/commit/8341411be434c6d145e942b1792020ccf02f58c8)
|
||||||
|
* Add image to `README.md` to thank supporters | [fa2a92b](https://github.com/undergroundwires/privacy.sexy/commit/fa2a92bf893933bf5cd04512a712b7aa1b921277)
|
||||||
|
* win: improve executable blocking, Chrome reporting | [f21ef92](https://github.com/undergroundwires/privacy.sexy/commit/f21ef9250a2f459dbd4f789d857c78298fc202e6)
|
||||||
|
* mac: discourage and document captive portal script | [b29cd7b](https://github.com/undergroundwires/privacy.sexy/commit/b29cd7b5f74accf92c9700c3171670f82c8cb3b3)
|
||||||
|
* win: fix revert scripts for removing shortcuts | [8becc7d](https://github.com/undergroundwires/privacy.sexy/commit/8becc7dbc46af4441900e9841a716a53735bc82e)
|
||||||
|
* Refactor to unify scripts/categories as Executable | [c138f74](https://github.com/undergroundwires/privacy.sexy/commit/c138f74460bafaba3da55a65f3942bb6f95b1d99)
|
||||||
|
* Add object property validation in parser #369 | [6ecfa9b](https://github.com/undergroundwires/privacy.sexy/commit/6ecfa9b954edc10401acaf5c735eec0fc9f991cd)
|
||||||
|
* win: fix missing app access recommendations #369 | [1c2d82d](https://github.com/undergroundwires/privacy.sexy/commit/1c2d82dc9bd412ea601ab2550ba0b4f7d144f8e8)
|
||||||
|
* win: fix text and handwriting script omission #369 | [1a10cf2](https://github.com/undergroundwires/privacy.sexy/commit/1a10cf2e5f87cd8eb421ef77f6ce764b5482515e)
|
||||||
|
* mac: document, improve, encourage clearing logs | [e9a5285](https://github.com/undergroundwires/privacy.sexy/commit/e9a52859f63609c3f56def0b3e4d1ac6e5661536)
|
||||||
|
* Add schema validation for collection files #369 | [dc03bff](https://github.com/undergroundwires/privacy.sexy/commit/dc03bff324d673101002bb16f14e0429e8170fbb)
|
||||||
|
* win: fix incomplete VSCEIP, location scripts | [48761f6](https://github.com/undergroundwires/privacy.sexy/commit/48761f62a242f0910307994271cbe6730fb30f7e)
|
||||||
|
* Add type validation for parameters and fix types | [fac26a6](https://github.com/undergroundwires/privacy.sexy/commit/fac26a6ca07479c84fe62c5ea2a572dad1898ef8)
|
||||||
|
* Bump Electron to latest | [ed93614](https://github.com/undergroundwires/privacy.sexy/commit/ed93614ca34b1ab166e645cc5bedd497b0caeaac)
|
||||||
|
* Trim compiler error output for better readability | [78c62cf](https://github.com/undergroundwires/privacy.sexy/commit/78c62cfc953dbba543d8bdc42828a4ef4b13a7c7)
|
||||||
|
* win: fix errors due to missing Edge uninstaller | [2f82873](https://github.com/undergroundwires/privacy.sexy/commit/2f828735a87f98ba87b4fc826823d1482d4f2db2)
|
||||||
|
* win: fix latest Edge removal on Windows 10 #309 | [e7031a3](https://github.com/undergroundwires/privacy.sexy/commit/e7031a3ae4e57b6522c6ca67fc30e8a8718506b2)
|
||||||
|
* win: categorize, rename, doc Chrome & Edge scripts | [f286f92](https://github.com/undergroundwires/privacy.sexy/commit/f286f92b1fec49e89eea8982dffbc3d6ef1defde)
|
||||||
|
* win: add disabling Edge/WebView2 auto-updates #309 | [ed7e69c](https://github.com/undergroundwires/privacy.sexy/commit/ed7e69c07efe83fdb7f4af13aa220ff991fbbe59)
|
||||||
|
* win, linux, mac: fix typos #373 | [c09c5ff](https://github.com/undergroundwires/privacy.sexy/commit/c09c5ffa47865f7c76910644558b6783ed44f1e4)
|
||||||
|
* win: add more Edge scripts including AI & ads | [1430d52](https://github.com/undergroundwires/privacy.sexy/commit/1430d5215ab094d8201710761d631dc2bd740918)
|
||||||
|
|
||||||
|
[compare](https://github.com/undergroundwires/privacy.sexy/compare/0.13.4...0.13.5)
|
||||||
|
|
||||||
|
## 0.13.4 (2024-05-27)
|
||||||
|
|
||||||
|
* Add specific empty function name compiler error | [870120b](https://github.com/undergroundwires/privacy.sexy/commit/870120bc13909a3681e0f0a2351806849476342f)
|
||||||
|
* ci/cd: fix recent Docker build failures on macOS | [a1922c5](https://github.com/undergroundwires/privacy.sexy/commit/a1922c50c12b3b7806e9e681ace842194a178bda)
|
||||||
|
* win: standardize registry edit + delete on revert | [cec0b4b](https://github.com/undergroundwires/privacy.sexy/commit/cec0b4b4f63c3563a0e7923ce6324a38d71a3955)
|
||||||
|
* Fix e2e test failing on Windows | [4a7efa2](https://github.com/undergroundwires/privacy.sexy/commit/4a7efa27c8df73ef9b7960afed29f216b066cba2)
|
||||||
|
* Add support for macOS universal binary #348, #362 | [d25c4e8](https://github.com/undergroundwires/privacy.sexy/commit/d25c4e8c812b8d012010ba38070a2931dcd28908)
|
||||||
|
* Migrate to GitHub issue forms | [9ab3ff7](https://github.com/undergroundwires/privacy.sexy/commit/9ab3ff75b0a69ac2ba27dd02e82db9b5bd76ea0f)
|
||||||
|
* ci/cd: fix quality checks not running on all OSes | [2390530](https://github.com/undergroundwires/privacy.sexy/commit/2390530d929fb92c266558c52376569a0ecb90c1)
|
||||||
|
* Bump Vue to latest and fix universal selector CSS | [aae5434](https://github.com/undergroundwires/privacy.sexy/commit/aae54344511ec51d17ad0420a92cb5a064e0e7bb)
|
||||||
|
* Centralize and optimize `ResizeObserver` usage | [2923621](https://github.com/undergroundwires/privacy.sexy/commit/292362135db0519ec1050bab80ed373aad115731)
|
||||||
|
* win: improve app access disabling and docs #138 | [ff3d5c4](https://github.com/undergroundwires/privacy.sexy/commit/ff3d5c48419f663379f5aba8936636c22f2c5de8)
|
||||||
|
* win: document and discourage RSA key script #363 | [f347fde](https://github.com/undergroundwires/privacy.sexy/commit/f347fde0c85f8b51b0060fdea0a2724b042aaeed)
|
||||||
|
* win: improve printing removal /w Print Queue #279 | [150e067](https://github.com/undergroundwires/privacy.sexy/commit/150e0670392bb62348c20ec644a4ed8a6bbffe74)
|
||||||
|
* win: discourage blocking app access #121 #339 #350 | [7794846](https://github.com/undergroundwires/privacy.sexy/commit/77948461856e6837ddfbcbbef72a1bf9fc706b4e)
|
||||||
|
* Improve context for errors thrown by compiler | [4212c7b](https://github.com/undergroundwires/privacy.sexy/commit/4212c7b9e0b1500378a1e4e88efc2d59f39f3d29)
|
||||||
|
* win: document disabling firewall #115 #152 #364 | [12b1f18](https://github.com/undergroundwires/privacy.sexy/commit/12b1f183f7ce966d6ce090d98aeea7ec491f8c7c)
|
||||||
|
* win: add script to disable Recall feature | [ce4cfdd](https://github.com/undergroundwires/privacy.sexy/commit/ce4cfdd169b7da0edc3da61143c988ed5f3c976e)
|
||||||
|
* win, mac, linux: fix typos and dead URLs #367 | [9e34e64](https://github.com/undergroundwires/privacy.sexy/commit/9e34e644493674ca709b64a47206763d5d4bd60c)
|
||||||
|
|
||||||
|
[compare](https://github.com/undergroundwires/privacy.sexy/compare/0.13.3...0.13.4)
|
||||||
|
|
||||||
## 0.13.3 (2024-05-11)
|
## 0.13.3 (2024-05-11)
|
||||||
|
|
||||||
* win: organize and document network disablement | [2eed6f4](https://github.com/undergroundwires/privacy.sexy/commit/2eed6f4afb6cf85fdc1d6acb808f82405a35cafd)
|
* win: organize and document network disablement | [2eed6f4](https://github.com/undergroundwires/privacy.sexy/commit/2eed6f4afb6cf85fdc1d6acb808f82405a35cafd)
|
||||||
|
|||||||
@@ -122,7 +122,7 @@
|
|||||||
## Get started
|
## Get started
|
||||||
|
|
||||||
- 🌍️ **Online**: [https://privacy.sexy](https://privacy.sexy).
|
- 🌍️ **Online**: [https://privacy.sexy](https://privacy.sexy).
|
||||||
- 🖥️ **Offline**: Download directly for: [Windows](https://github.com/undergroundwires/privacy.sexy/releases/download/0.13.3/privacy.sexy-Setup-0.13.3.exe), [macOS](https://github.com/undergroundwires/privacy.sexy/releases/download/0.13.3/privacy.sexy-0.13.3.dmg), [Linux](https://github.com/undergroundwires/privacy.sexy/releases/download/0.13.3/privacy.sexy-0.13.3.AppImage). For more options, see [here](#additional-install-options).
|
- 🖥️ **Offline**: Download directly for: [Windows](https://github.com/undergroundwires/privacy.sexy/releases/download/0.13.6/privacy.sexy-Setup-0.13.6.exe), [macOS](https://github.com/undergroundwires/privacy.sexy/releases/download/0.13.6/privacy.sexy-0.13.6.dmg), [Linux](https://github.com/undergroundwires/privacy.sexy/releases/download/0.13.6/privacy.sexy-0.13.6.AppImage). For more options, see [here](#additional-install-options).
|
||||||
|
|
||||||
See also:
|
See also:
|
||||||
|
|
||||||
@@ -186,3 +186,7 @@ Check [architecture.md](./docs/architecture.md) for an overview of design and ho
|
|||||||
Security is a top priority at privacy.sexy.
|
Security is a top priority at privacy.sexy.
|
||||||
An extensive commitment to security verification ensures this priority.
|
An extensive commitment to security verification ensures this priority.
|
||||||
For any security concerns or vulnerabilities, please consult the [Security Policy](./SECURITY.md).
|
For any security concerns or vulnerabilities, please consult the [Security Policy](./SECURITY.md).
|
||||||
|
|
||||||
|
## Supporters
|
||||||
|
|
||||||
|
[](https://undergroundwires.dev/supporters)
|
||||||
|
|||||||
@@ -41,5 +41,5 @@ Application layer compiles templating syntax during parsing to create the end sc
|
|||||||
|
|
||||||
The steps to extend the templating syntax:
|
The steps to extend the templating syntax:
|
||||||
|
|
||||||
1. Add a new parser under [SyntaxParsers](./../src/application/Parser/Script/Compiler/Expressions/SyntaxParsers) where you can look at other parsers to understand more.
|
1. Add a new parser under [SyntaxParsers](./../src/application/Parser/Executable/Script/Compiler/Expressions/SyntaxParsers) where you can look at other parsers to understand more.
|
||||||
2. Register your in [CompositeExpressionParser](./../src/application/Parser/Script/Compiler/Expressions/Parser/CompositeExpressionParser.ts).
|
2. Register your in [CompositeExpressionParser](./../src/application/Parser/Executable/Script/Compiler/Expressions/Parser/CompositeExpressionParser.ts).
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
# Collection files
|
# Collection files
|
||||||
|
|
||||||
privacy.sexy is a data-driven application that reads YAML files.
|
privacy.sexy is a data-driven application that reads YAML files.
|
||||||
This document details the structure and syntax of the YAML files located in [`application/collections`](./../src/application/collections/), which form the backbone of the application's data model.
|
This document details the structure and syntax of the YAML files located in [`application/collections`](./../src/application/collections/), which form the backbone of the application's data model. The YAML schema [`.schema.yaml`](./../src/application/collections/.schema.yaml) is provided to provide better IDE support and be used in automated validations.
|
||||||
|
|
||||||
Related documentation:
|
Related documentation:
|
||||||
|
|
||||||
- 📖 [`collection.yaml.d.ts`](./../src/application/collections/collection.yaml.d.ts) outlines code types.
|
- 📖 [`Collections README`](./../src/application/collections/README.md) includes references to code as documentation.
|
||||||
- 📖 [Script Guidelines](./script-guidelines.md) provide guidance on script creation including best-practices.
|
- 📖 [Script Guidelines](./script-guidelines.md) provide guidance on script creation including best-practices.
|
||||||
|
|
||||||
## Objects
|
## Objects
|
||||||
@@ -28,11 +28,22 @@ Related documentation:
|
|||||||
- `scripting:` ***[`ScriptingDefinition`](#scriptingdefinition)*** **(required)**
|
- `scripting:` ***[`ScriptingDefinition`](#scriptingdefinition)*** **(required)**
|
||||||
- Sets the scripting language for all inline code used within the collection.
|
- Sets the scripting language for all inline code used within the collection.
|
||||||
|
|
||||||
### `Category`
|
### Executables
|
||||||
|
|
||||||
|
They represent independently executable actions with documentation and reversibility.
|
||||||
|
|
||||||
|
An Executable is a logical entity that can
|
||||||
|
|
||||||
|
- execute once compiled,
|
||||||
|
- include a `docs` property for documentation.
|
||||||
|
|
||||||
|
It's either [Category](#category) or a [Script](#script).
|
||||||
|
|
||||||
|
#### `Category`
|
||||||
|
|
||||||
Represents a logical group of scripts and subcategories.
|
Represents a logical group of scripts and subcategories.
|
||||||
|
|
||||||
#### `Category` syntax
|
##### `Category` syntax
|
||||||
|
|
||||||
- `category:` *`string`* **(required)**
|
- `category:` *`string`* **(required)**
|
||||||
- Name of the category.
|
- Name of the category.
|
||||||
@@ -43,7 +54,7 @@ Represents a logical group of scripts and subcategories.
|
|||||||
- `docs`: *`string`* | `[`*`string`*`, ... ]`
|
- `docs`: *`string`* | `[`*`string`*`, ... ]`
|
||||||
- Markdown-formatted documentation related to the category.
|
- Markdown-formatted documentation related to the category.
|
||||||
|
|
||||||
### `Script`
|
#### `Script`
|
||||||
|
|
||||||
Represents an individual tweak.
|
Represents an individual tweak.
|
||||||
|
|
||||||
@@ -58,7 +69,7 @@ Types (like [functions](#function)):
|
|||||||
|
|
||||||
📖 For detailed guidelines, see [Script Guidelines](./script-guidelines.md).
|
📖 For detailed guidelines, see [Script Guidelines](./script-guidelines.md).
|
||||||
|
|
||||||
#### `Script` syntax
|
##### `Script` syntax
|
||||||
|
|
||||||
- `name`: *`string`* **(required)**
|
- `name`: *`string`* **(required)**
|
||||||
- Script name.
|
- Script name.
|
||||||
|
|||||||
@@ -34,8 +34,10 @@ The desktop version ensures secure delivery through cryptographic signatures and
|
|||||||
|
|
||||||
[Security is a top priority](./../../SECURITY.md#update-security-and-integrity) at privacy.sexy.
|
[Security is a top priority](./../../SECURITY.md#update-security-and-integrity) at privacy.sexy.
|
||||||
|
|
||||||
> **Note for macOS users:** On macOS, the desktop version's auto-update process involves manual steps due to Apple's code signing costs.
|
> **Note for macOS users:**
|
||||||
|
> On macOS, the desktop version's auto-update process involves manual steps due to Apple's code signing costs.
|
||||||
> Users get notified about updates but might need to complete the installation manually.
|
> Users get notified about updates but might need to complete the installation manually.
|
||||||
|
> Updater stores update installation files temporarily at `$HOME/Library/Application Support/privacy.sexy/updates`.
|
||||||
> Consider [donating](https://github.com/sponsors/undergroundwires) to help improve this process ❤️.
|
> Consider [donating](https://github.com/sponsors/undergroundwires) to help improve this process ❤️.
|
||||||
|
|
||||||
### Logging
|
### Logging
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ See [ci-cd.md](./ci-cd.md) for more information.
|
|||||||
- Markdown: `npm run lint:md`
|
- Markdown: `npm run lint:md`
|
||||||
- Markdown consistency `npm run lint:md:consistency`
|
- Markdown consistency `npm run lint:md:consistency`
|
||||||
- Markdown relative URLs: `npm run lint:md:relative-urls`
|
- Markdown relative URLs: `npm run lint:md:relative-urls`
|
||||||
|
- Markdown external URLs: `npm run lint:md:external-urls`
|
||||||
- JavaScript/TypeScript: `npm run lint:eslint`
|
- JavaScript/TypeScript: `npm run lint:eslint`
|
||||||
- Yaml: `npm run lint:yaml`
|
- Yaml: `npm run lint:yaml`
|
||||||
|
|
||||||
@@ -80,8 +81,10 @@ See [ci-cd.md](./ci-cd.md) for more information.
|
|||||||
- [**`npm run install-deps [-- <options>]`**](../scripts/npm-install.js):
|
- [**`npm run install-deps [-- <options>]`**](../scripts/npm-install.js):
|
||||||
- Manages NPM dependency installation, it offers capabilities like doing a fresh install, retries on network errors, and other features.
|
- Manages NPM dependency installation, it offers capabilities like doing a fresh install, retries on network errors, and other features.
|
||||||
- For example, you can run `npm run install-deps -- --fresh` to do clean installation of dependencies.
|
- For example, you can run `npm run install-deps -- --fresh` to do clean installation of dependencies.
|
||||||
- [**`python ./scripts/configure_vscode.py`**](../scripts/configure_vscode.py):
|
- [**`python3 ./scripts/configure_vscode.py`**](../scripts/configure_vscode.py):
|
||||||
- Optimizes Visual Studio Code settings and installs essential extensions, enhancing the development environment.
|
- Optimizes Visual Studio Code settings and installs essential extensions, enhancing the development environment.
|
||||||
|
- [**`python3 ./scripts/validate-collections-yaml`**](../scripts/validate-collections-yaml/README.md):
|
||||||
|
- Validates the syntax and structure of collection YAML files.
|
||||||
|
|
||||||
#### Automation scripts
|
#### Automation scripts
|
||||||
|
|
||||||
|
|||||||
10074
package-lock.json
generated
10074
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
63
package.json
63
package.json
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "privacy.sexy",
|
"name": "privacy.sexy",
|
||||||
"version": "0.13.3",
|
"version": "0.13.6",
|
||||||
"private": true,
|
"private": true,
|
||||||
"slogan": "Privacy is sexy",
|
"slogan": "Privacy is sexy",
|
||||||
"description": "Enforce privacy & security best-practices on Windows, macOS and Linux, because privacy is sexy.",
|
"description": "Enforce privacy & security best-practices on Windows, macOS and Linux, because privacy is sexy.",
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
"test:integration": "vitest run --dir tests/integration",
|
"test:integration": "vitest run --dir tests/integration",
|
||||||
"test:cy:run": "start-server-and-test \"vite build && vite preview --port 7070\" http://localhost:7070 \"cypress run --config baseUrl=http://localhost:7070\"",
|
"test:cy:run": "start-server-and-test \"vite build && vite preview --port 7070\" http://localhost:7070 \"cypress run --config baseUrl=http://localhost:7070\"",
|
||||||
"test:cy:open": "start-server-and-test \"vite --port 7070 --mode production\" http://localhost:7070 \"cypress open --config baseUrl=http://localhost:7070\"",
|
"test:cy:open": "start-server-and-test \"vite --port 7070 --mode production\" http://localhost:7070 \"cypress open --config baseUrl=http://localhost:7070\"",
|
||||||
"lint": "npm run lint:md && npm run lint:md:consistency && npm run lint:md:relative-urls && npm run lint:eslint && npm run lint:yaml && npm run lint:pylint",
|
"lint": "npm run lint:md && npm run lint:md:consistency && npm run lint:md:relative-urls && npm run lint:md:external-urls && npm run lint:eslint && npm run lint:yaml && npm run lint:pylint",
|
||||||
"install-deps": "node scripts/npm-install.js",
|
"install-deps": "node scripts/npm-install.js",
|
||||||
"icons:build": "node scripts/logo-update.js",
|
"icons:build": "node scripts/logo-update.js",
|
||||||
"check:desktop": "vitest run --dir tests/checks/desktop-runtime-errors --environment node",
|
"check:desktop": "vitest run --dir tests/checks/desktop-runtime-errors --environment node",
|
||||||
@@ -28,60 +28,61 @@
|
|||||||
"lint:md": "markdownlint **/*.md --ignore node_modules",
|
"lint:md": "markdownlint **/*.md --ignore node_modules",
|
||||||
"lint:md:consistency": "remark . --frail --use remark-preset-lint-consistent",
|
"lint:md:consistency": "remark . --frail --use remark-preset-lint-consistent",
|
||||||
"lint:md:relative-urls": "remark . --frail --use remark-validate-links",
|
"lint:md:relative-urls": "remark . --frail --use remark-validate-links",
|
||||||
|
"lint:md:external-urls": "remark . --frail --use remark-lint-no-dead-urls",
|
||||||
"lint:yaml": "yamllint **/*.yaml --ignore=node_modules/**/*.yaml",
|
"lint:yaml": "yamllint **/*.yaml --ignore=node_modules/**/*.yaml",
|
||||||
"lint:pylint": "pylint **/*.py",
|
"lint:pylint": "pylint **/*.py",
|
||||||
"postinstall": "electron-builder install-app-deps",
|
"postinstall": "electron-builder install-app-deps",
|
||||||
"postuninstall": "electron-builder install-app-deps"
|
"postuninstall": "electron-builder install-app-deps"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@floating-ui/vue": "^1.0.6",
|
"@floating-ui/vue": "^1.1.1",
|
||||||
"@juggle/resize-observer": "^3.4.0",
|
"@juggle/resize-observer": "^3.4.0",
|
||||||
"ace-builds": "^1.33.0",
|
"ace-builds": "^1.35.3",
|
||||||
"electron-log": "^5.1.2",
|
"electron-log": "^5.1.6",
|
||||||
"electron-progressbar": "^2.2.1",
|
"electron-progressbar": "^2.2.1",
|
||||||
"electron-updater": "^6.1.9",
|
"electron-updater": "^6.2.1",
|
||||||
"file-saver": "^2.0.5",
|
"file-saver": "^2.0.5",
|
||||||
"markdown-it": "^14.1.0",
|
"markdown-it": "^14.1.0",
|
||||||
"vue": "^3.4.27"
|
"vue": "^3.4.32"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@modyfi/vite-plugin-yaml": "^1.1.0",
|
"@modyfi/vite-plugin-yaml": "^1.1.0",
|
||||||
"@rushstack/eslint-patch": "^1.10.2",
|
"@rushstack/eslint-patch": "^1.10.3",
|
||||||
"@types/ace": "^0.0.52",
|
"@types/ace": "^0.0.52",
|
||||||
"@types/file-saver": "^2.0.7",
|
"@types/file-saver": "^2.0.7",
|
||||||
"@types/markdown-it": "^14.0.1",
|
"@types/markdown-it": "^14.1.1",
|
||||||
"@typescript-eslint/eslint-plugin": "6.21.0",
|
"@typescript-eslint/eslint-plugin": "6.21.0",
|
||||||
"@typescript-eslint/parser": "6.21.0",
|
"@typescript-eslint/parser": "6.21.0",
|
||||||
"@vitejs/plugin-legacy": "^5.3.2",
|
"@vitejs/plugin-legacy": "^5.4.1",
|
||||||
"@vitejs/plugin-vue": "^5.0.4",
|
"@vitejs/plugin-vue": "^5.0.5",
|
||||||
"@vue/eslint-config-airbnb-with-typescript": "^8.0.0",
|
"@vue/eslint-config-airbnb-with-typescript": "^8.0.0",
|
||||||
"@vue/eslint-config-typescript": "12.0.0",
|
"@vue/eslint-config-typescript": "12.0.0",
|
||||||
"@vue/test-utils": "^2.4.5",
|
"@vue/test-utils": "^2.4.6",
|
||||||
"autoprefixer": "^10.4.19",
|
"autoprefixer": "^10.4.19",
|
||||||
"cypress": "^13.7.3",
|
"cypress": "^13.13.1",
|
||||||
"electron": "^29.3.0",
|
"electron": "^31.2.1",
|
||||||
"electron-builder": "^24.13.3",
|
"electron-builder": "^24.13.3",
|
||||||
"electron-devtools-installer": "^3.2.0",
|
"electron-devtools-installer": "^3.2.0",
|
||||||
"electron-vite": "^2.1.0",
|
"electron-vite": "^2.3.0",
|
||||||
"eslint": "8.57.0",
|
"eslint": "8.57.0",
|
||||||
"eslint-plugin-cypress": "^2.15.1",
|
"eslint-plugin-cypress": "^3.3.0",
|
||||||
"eslint-plugin-vue": "^9.25.0",
|
"eslint-plugin-vue": "^9.27.0",
|
||||||
"eslint-plugin-vuejs-accessibility": "^2.2.1",
|
"eslint-plugin-vuejs-accessibility": "^2.4.0",
|
||||||
"jsdom": "^24.0.0",
|
"jsdom": "^24.1.0",
|
||||||
"markdownlint-cli": "^0.39.0",
|
"markdownlint-cli": "^0.41.0",
|
||||||
"postcss": "^8.4.38",
|
"postcss": "^8.4.39",
|
||||||
"remark-cli": "^12.0.0",
|
"remark-cli": "^12.0.1",
|
||||||
"remark-lint-no-dead-urls": "^1.1.0",
|
"remark-lint-no-dead-urls": "^2.0.0",
|
||||||
"remark-preset-lint-consistent": "^6.0.0",
|
"remark-preset-lint-consistent": "^6.0.0",
|
||||||
"remark-validate-links": "^13.0.1",
|
"remark-validate-links": "^13.0.1",
|
||||||
"sass": "^1.75.0",
|
"sass": "~1.79.4",
|
||||||
"start-server-and-test": "^2.0.3",
|
"start-server-and-test": "^2.0.4",
|
||||||
"terser": "^5.30.3",
|
"terser": "^5.31.3",
|
||||||
"tslib": "^2.6.2",
|
"tslib": "^2.6.3",
|
||||||
"typescript": "^5.4.5",
|
"typescript": "~5.5.4",
|
||||||
"vite": "^5.2.8",
|
"vite": "^5.4.8",
|
||||||
"vitest": "^1.5.0",
|
"vitest": "^2.0.3",
|
||||||
"vue-tsc": "^2.0.13",
|
"vue-tsc": "^2.0.26",
|
||||||
"yaml-lint": "^1.7.0"
|
"yaml-lint": "^1.7.0"
|
||||||
},
|
},
|
||||||
"//devDependencies": {
|
"//devDependencies": {
|
||||||
|
|||||||
@@ -58,6 +58,10 @@ def add_or_update_settings() -> None:
|
|||||||
# Details: # pylint: disable-next=line-too-long
|
# Details: # pylint: disable-next=line-too-long
|
||||||
# - https://archive.ph/2024.01.06-003914/https://github.com/microsoft/vscode/issues/179274, https://web.archive.org/web/20240106003915/https://github.com/microsoft/vscode/issues/179274
|
# - https://archive.ph/2024.01.06-003914/https://github.com/microsoft/vscode/issues/179274, https://web.archive.org/web/20240106003915/https://github.com/microsoft/vscode/issues/179274
|
||||||
|
|
||||||
|
# Disable telemetry
|
||||||
|
configure_setting_key('redhat.telemetry.enabled', False)
|
||||||
|
configure_setting_key('gitlens.telemetry.enabled', False)
|
||||||
|
|
||||||
def configure_setting_key(configuration_key: str, desired_value: Any) -> None:
|
def configure_setting_key(configuration_key: str, desired_value: Any) -> None:
|
||||||
try:
|
try:
|
||||||
with open(VSCODE_SETTINGS_JSON_FILE, 'r+', encoding='utf-8') as file:
|
with open(VSCODE_SETTINGS_JSON_FILE, 'r+', encoding='utf-8') as file:
|
||||||
|
|||||||
51
scripts/validate-collections-yaml/README.md
Normal file
51
scripts/validate-collections-yaml/README.md
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
# validate-collections-yaml
|
||||||
|
|
||||||
|
This script validates YAML collection files against a predefined schema to ensure their integrity.
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- Python 3.x installed on your system.
|
||||||
|
|
||||||
|
## Running in a Virtual Environment (Recommended)
|
||||||
|
|
||||||
|
Using a virtual environment isolates dependencies and prevents conflicts.
|
||||||
|
|
||||||
|
1. **Create a virtual environment:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -m venv ./scripts/validate-collections-yaml/.venv
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Activate the virtual environment:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
source ./scripts/validate-collections-yaml/.venv/bin/activate
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Install dependencies:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -m pip install -r ./scripts/validate-collections-yaml/requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Run the script:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 ./scripts/validate-collections-yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
## Running Globally
|
||||||
|
|
||||||
|
Running the script globally is less recommended due to potential dependency conflicts.
|
||||||
|
|
||||||
|
1. **Install dependencies:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -m pip install -r ./scripts/validate-collections-yaml/requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Run the script:**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 ./scripts/validate-collections-yaml
|
||||||
|
```
|
||||||
62
scripts/validate-collections-yaml/__main__.py
Normal file
62
scripts/validate-collections-yaml/__main__.py
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
"""
|
||||||
|
Description:
|
||||||
|
This script validates collection YAML files against the expected schema.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python3 ./scripts/validate-collections-yaml
|
||||||
|
|
||||||
|
Notes:
|
||||||
|
This script requires the `jsonschema` and `pyyaml` packages (see requirements.txt).
|
||||||
|
"""
|
||||||
|
# pylint: disable=missing-function-docstring
|
||||||
|
from os import path
|
||||||
|
import sys
|
||||||
|
from glob import glob
|
||||||
|
from typing import List
|
||||||
|
from jsonschema import exceptions, validate # pylint: disable=import-error
|
||||||
|
import yaml # pylint: disable=import-error
|
||||||
|
|
||||||
|
SCHEMA_FILE_PATH = './src/application/collections/.schema.yaml'
|
||||||
|
COLLECTIONS_GLOB_PATTERN = './src/application/collections/*.yaml'
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
schema_yaml = read_file(SCHEMA_FILE_PATH)
|
||||||
|
schema_json = convert_yaml_to_json(schema_yaml)
|
||||||
|
collection_file_paths = find_collection_files(COLLECTIONS_GLOB_PATTERN)
|
||||||
|
print(f'Found {len(collection_file_paths)} YAML files to validate.')
|
||||||
|
|
||||||
|
total_invalid_files = 0
|
||||||
|
for collection_file_path in collection_file_paths:
|
||||||
|
file_name = path.basename(collection_file_path)
|
||||||
|
print(f'Validating {file_name}...')
|
||||||
|
collection_yaml = read_file(collection_file_path)
|
||||||
|
collection_json = convert_yaml_to_json(collection_yaml)
|
||||||
|
try:
|
||||||
|
validate(instance=collection_json, schema=schema_json)
|
||||||
|
print(f'Success: {file_name} is valid.')
|
||||||
|
except exceptions.ValidationError as err:
|
||||||
|
print(f'Error: Validation failed for {file_name}.', file=sys.stderr)
|
||||||
|
print(str(err), file=sys.stderr)
|
||||||
|
total_invalid_files += 1
|
||||||
|
|
||||||
|
if total_invalid_files > 0:
|
||||||
|
print(f'Validation complete with {total_invalid_files} invalid files.', file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
else:
|
||||||
|
print('Validation complete. All files are valid.')
|
||||||
|
sys.exit(0)
|
||||||
|
|
||||||
|
def read_file(file_path: str) -> str:
|
||||||
|
with open(file_path, 'r', encoding='utf-8') as file:
|
||||||
|
return file.read()
|
||||||
|
|
||||||
|
def find_collection_files(glob_pattern: str) -> List[str]:
|
||||||
|
files = glob(glob_pattern)
|
||||||
|
filtered_files = [f for f in files if not path.basename(f).startswith('.')]
|
||||||
|
return filtered_files
|
||||||
|
|
||||||
|
def convert_yaml_to_json(yaml_content: str) -> dict:
|
||||||
|
return yaml.safe_load(yaml_content)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
6
scripts/validate-collections-yaml/requirements.txt
Normal file
6
scripts/validate-collections-yaml/requirements.txt
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
attrs==23.2.0
|
||||||
|
jsonschema==4.22.0
|
||||||
|
jsonschema-specifications==2023.12.1
|
||||||
|
PyYAML==6.0.1
|
||||||
|
referencing==0.35.1
|
||||||
|
rpds-py==0.18.1
|
||||||
@@ -91,7 +91,7 @@ async function verifyFilesExist(directoryPath, filePatterns) {
|
|||||||
if (!match) {
|
if (!match) {
|
||||||
die(
|
die(
|
||||||
`No file matches the pattern ${pattern.source} in directory \`${directoryPath}\``,
|
`No file matches the pattern ${pattern.source} in directory \`${directoryPath}\``,
|
||||||
`\nFiles in directory:\n${files.map((file) => `\t- ${file}`).join('\n')}`,
|
`\nFiles in directory:\n${files.map((file) => `- ${file}`).join('\n')}`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { isFunction } from '@/TypeHelpers';
|
import { isFunction, type ConstructorArguments } from '@/TypeHelpers';
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Provides a unified and resilient way to extend errors across platforms.
|
Provides a unified and resilient way to extend errors across platforms.
|
||||||
@@ -12,8 +12,8 @@ import { isFunction } from '@/TypeHelpers';
|
|||||||
> https://web.archive.org/web/20230810014143/https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
|
> https://web.archive.org/web/20230810014143/https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
|
||||||
*/
|
*/
|
||||||
export abstract class CustomError extends Error {
|
export abstract class CustomError extends Error {
|
||||||
constructor(message?: string, options?: ErrorOptions) {
|
constructor(...args: ConstructorArguments<typeof Error>) {
|
||||||
super(message, options);
|
super(...args);
|
||||||
|
|
||||||
fixPrototype(this, new.target.prototype);
|
fixPrototype(this, new.target.prototype);
|
||||||
ensureStackTrace(this);
|
ensureStackTrace(this);
|
||||||
|
|||||||
@@ -5,13 +5,13 @@ export type EnumType = number | string;
|
|||||||
export type EnumVariable<T extends EnumType, TEnumValue extends EnumType>
|
export type EnumVariable<T extends EnumType, TEnumValue extends EnumType>
|
||||||
= { [key in T]: TEnumValue };
|
= { [key in T]: TEnumValue };
|
||||||
|
|
||||||
export interface IEnumParser<TEnum> {
|
export interface EnumParser<TEnum> {
|
||||||
parseEnum(value: string, propertyName: string): TEnum;
|
parseEnum(value: string, propertyName: string): TEnum;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createEnumParser<T extends EnumType, TEnumValue extends EnumType>(
|
export function createEnumParser<T extends EnumType, TEnumValue extends EnumType>(
|
||||||
enumVariable: EnumVariable<T, TEnumValue>,
|
enumVariable: EnumVariable<T, TEnumValue>,
|
||||||
): IEnumParser<TEnumValue> {
|
): EnumParser<TEnumValue> {
|
||||||
return {
|
return {
|
||||||
parseEnum: (value, propertyName) => parseEnumValue(value, propertyName, enumVariable),
|
parseEnum: (value, propertyName) => parseEnumValue(value, propertyName, enumVariable),
|
||||||
};
|
};
|
||||||
@@ -33,23 +33,25 @@ function parseEnumValue<T extends EnumType, TEnumValue extends EnumType>(
|
|||||||
if (!casedValue) {
|
if (!casedValue) {
|
||||||
throw new Error(`unknown ${enumName}: "${value}"`);
|
throw new Error(`unknown ${enumName}: "${value}"`);
|
||||||
}
|
}
|
||||||
return enumVariable[casedValue as keyof typeof enumVariable];
|
return enumVariable[casedValue as keyof EnumVariable<T, TEnumValue>];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getEnumNames
|
export function getEnumNames
|
||||||
<T extends EnumType, TEnumValue extends EnumType>(
|
<T extends EnumType, TEnumValue extends EnumType>(
|
||||||
enumVariable: EnumVariable<T, TEnumValue>,
|
enumVariable: EnumVariable<T, TEnumValue>,
|
||||||
): string[] {
|
): (string & keyof EnumVariable<T, TEnumValue>)[] {
|
||||||
return Object
|
return Object
|
||||||
.values(enumVariable)
|
.values(enumVariable)
|
||||||
.filter((enumMember): enumMember is string => isString(enumMember));
|
.filter((
|
||||||
|
enumMember,
|
||||||
|
): enumMember is string & (keyof EnumVariable<T, TEnumValue>) => isString(enumMember));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getEnumValues<T extends EnumType, TEnumValue extends EnumType>(
|
export function getEnumValues<T extends EnumType, TEnumValue extends EnumType>(
|
||||||
enumVariable: EnumVariable<T, TEnumValue>,
|
enumVariable: EnumVariable<T, TEnumValue>,
|
||||||
): TEnumValue[] {
|
): TEnumValue[] {
|
||||||
return getEnumNames(enumVariable)
|
return getEnumNames(enumVariable)
|
||||||
.map((level) => enumVariable[level]) as TEnumValue[];
|
.map((name) => enumVariable[name]) as TEnumValue[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export function assertInRange<T extends EnumType, TEnumValue extends EnumType>(
|
export function assertInRange<T extends EnumType, TEnumValue extends EnumType>(
|
||||||
|
|||||||
25
src/application/Common/Text/FilterEmptyStrings.ts
Normal file
25
src/application/Common/Text/FilterEmptyStrings.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { isArray } from '@/TypeHelpers';
|
||||||
|
|
||||||
|
export type OptionalString = string | undefined | null;
|
||||||
|
|
||||||
|
export function filterEmptyStrings(
|
||||||
|
texts: readonly OptionalString[],
|
||||||
|
isArrayType: typeof isArray = isArray,
|
||||||
|
): string[] {
|
||||||
|
if (!isArrayType(texts)) {
|
||||||
|
throw new Error(`Invalid input: Expected an array, but received type ${typeof texts}.`);
|
||||||
|
}
|
||||||
|
assertArrayItemsAreStringLike(texts);
|
||||||
|
return texts
|
||||||
|
.filter((title): title is string => Boolean(title));
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertArrayItemsAreStringLike(
|
||||||
|
texts: readonly unknown[],
|
||||||
|
): asserts texts is readonly OptionalString[] {
|
||||||
|
const invalidItems = texts.filter((item) => !(typeof item === 'string' || item === undefined || item === null));
|
||||||
|
if (invalidItems.length > 0) {
|
||||||
|
const invalidTypes = invalidItems.map((item) => typeof item).join(', ');
|
||||||
|
throw new Error(`Invalid array items: Expected items as string, undefined, or null. Received invalid types: ${invalidTypes}.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
29
src/application/Common/Text/IndentText.ts
Normal file
29
src/application/Common/Text/IndentText.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import { isString } from '@/TypeHelpers';
|
||||||
|
import { splitTextIntoLines } from './SplitTextIntoLines';
|
||||||
|
|
||||||
|
export function indentText(
|
||||||
|
text: string,
|
||||||
|
indentLevel = 1,
|
||||||
|
utilities: TextIndentationUtilities = DefaultUtilities,
|
||||||
|
): string {
|
||||||
|
if (!utilities.isStringType(text)) {
|
||||||
|
throw new Error(`Indentation error: The input must be a string. Received type: ${typeof text}.`);
|
||||||
|
}
|
||||||
|
if (indentLevel <= 0) {
|
||||||
|
throw new Error(`Indentation error: The indent level must be a positive integer. Received: ${indentLevel}.`);
|
||||||
|
}
|
||||||
|
const indentation = '\t'.repeat(indentLevel);
|
||||||
|
return utilities.splitIntoLines(text)
|
||||||
|
.map((line) => (line ? `${indentation}${line}` : line))
|
||||||
|
.join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TextIndentationUtilities {
|
||||||
|
readonly splitIntoLines: typeof splitTextIntoLines;
|
||||||
|
readonly isStringType: typeof isString;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DefaultUtilities: TextIndentationUtilities = {
|
||||||
|
splitIntoLines: splitTextIntoLines,
|
||||||
|
isStringType: isString,
|
||||||
|
};
|
||||||
11
src/application/Common/Text/SplitTextIntoLines.ts
Normal file
11
src/application/Common/Text/SplitTextIntoLines.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
import { isString } from '@/TypeHelpers';
|
||||||
|
|
||||||
|
export function splitTextIntoLines(
|
||||||
|
text: string,
|
||||||
|
isStringType = isString,
|
||||||
|
): string[] {
|
||||||
|
if (!isStringType(text)) {
|
||||||
|
throw new Error(`Line splitting error: Expected a string but received type '${typeof text}'.`);
|
||||||
|
}
|
||||||
|
return text.split(/\r\n|\r|\n/);
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import type { IApplication } from '@/domain/IApplication';
|
import type { IApplication } from '@/domain/IApplication';
|
||||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||||
import type { ICategoryCollection } from '@/domain/ICategoryCollection';
|
import type { ICategoryCollection } from '@/domain/Collection/ICategoryCollection';
|
||||||
import { EventSource } from '@/infrastructure/Events/EventSource';
|
import { EventSource } from '@/infrastructure/Events/EventSource';
|
||||||
import { assertInRange } from '@/application/Common/Enum';
|
import { assertInRange } from '@/application/Common/Enum';
|
||||||
import { CategoryCollectionState } from './State/CategoryCollectionState';
|
import { CategoryCollectionState } from './State/CategoryCollectionState';
|
||||||
@@ -17,7 +17,7 @@ export class ApplicationContext implements IApplicationContext {
|
|||||||
public currentOs: OperatingSystem;
|
public currentOs: OperatingSystem;
|
||||||
|
|
||||||
public get state(): ICategoryCollectionState {
|
public get state(): ICategoryCollectionState {
|
||||||
return this.states[this.collection.os];
|
return this.getState(this.collection.os);
|
||||||
}
|
}
|
||||||
|
|
||||||
private readonly states: StateMachine;
|
private readonly states: StateMachine;
|
||||||
@@ -26,30 +26,51 @@ export class ApplicationContext implements IApplicationContext {
|
|||||||
public readonly app: IApplication,
|
public readonly app: IApplication,
|
||||||
initialContext: OperatingSystem,
|
initialContext: OperatingSystem,
|
||||||
) {
|
) {
|
||||||
|
this.setContext(initialContext);
|
||||||
this.states = initializeStates(app);
|
this.states = initializeStates(app);
|
||||||
this.changeContext(initialContext);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public changeContext(os: OperatingSystem): void {
|
public changeContext(os: OperatingSystem): void {
|
||||||
assertInRange(os, OperatingSystem);
|
|
||||||
if (this.currentOs === os) {
|
if (this.currentOs === os) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const collection = this.app.getCollection(os);
|
|
||||||
this.collection = collection;
|
|
||||||
const event: IApplicationContextChangedEvent = {
|
const event: IApplicationContextChangedEvent = {
|
||||||
newState: this.states[os],
|
newState: this.getState(os),
|
||||||
oldState: this.states[this.currentOs],
|
oldState: this.getState(this.currentOs),
|
||||||
};
|
};
|
||||||
|
this.setContext(os);
|
||||||
this.contextChanged.notify(event);
|
this.contextChanged.notify(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
private setContext(os: OperatingSystem): void {
|
||||||
|
validateOperatingSystem(os, this.app);
|
||||||
|
this.collection = this.app.getCollection(os);
|
||||||
this.currentOs = os;
|
this.currentOs = os;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private getState(os: OperatingSystem): ICategoryCollectionState {
|
||||||
|
const state = this.states.get(os);
|
||||||
|
if (!state) {
|
||||||
|
throw new Error(`Operating system "${OperatingSystem[os]}" state is unknown.`);
|
||||||
|
}
|
||||||
|
return state;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateOperatingSystem(
|
||||||
|
os: OperatingSystem,
|
||||||
|
app: IApplication,
|
||||||
|
): void {
|
||||||
|
assertInRange(os, OperatingSystem);
|
||||||
|
if (!app.getSupportedOsList().includes(os)) {
|
||||||
|
throw new Error(`Operating system "${OperatingSystem[os]}" is not supported.`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function initializeStates(app: IApplication): StateMachine {
|
function initializeStates(app: IApplication): StateMachine {
|
||||||
const machine = new Map<OperatingSystem, ICategoryCollectionState>();
|
const machine = new Map<OperatingSystem, ICategoryCollectionState>();
|
||||||
for (const collection of app.collections) {
|
for (const collection of app.collections) {
|
||||||
machine[collection.os] = new CategoryCollectionState(collection);
|
machine.set(collection.os, new CategoryCollectionState(collection));
|
||||||
}
|
}
|
||||||
return machine;
|
return machine;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { ICategoryCollection } from '@/domain/ICategoryCollection';
|
import type { ICategoryCollection } from '@/domain/Collection/ICategoryCollection';
|
||||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||||
import { AdaptiveFilterContext } from './Filter/AdaptiveFilterContext';
|
import { AdaptiveFilterContext } from './Filter/AdaptiveFilterContext';
|
||||||
import { ApplicationCode } from './Code/ApplicationCode';
|
import { ApplicationCode } from './Code/ApplicationCode';
|
||||||
|
|||||||
@@ -1,18 +1,20 @@
|
|||||||
import type { IScript } from '@/domain/IScript';
|
import type { Script } from '@/domain/Executables/Script/Script';
|
||||||
import type { ICodePosition } from '@/application/Context/State/Code/Position/ICodePosition';
|
import type { ICodePosition } from '@/application/Context/State/Code/Position/ICodePosition';
|
||||||
import type { SelectedScript } from '@/application/Context/State/Selection/Script/SelectedScript';
|
import type { SelectedScript } from '@/application/Context/State/Selection/Script/SelectedScript';
|
||||||
|
import { splitTextIntoLines } from '@/application/Common/Text/SplitTextIntoLines';
|
||||||
|
import type { ExecutableId } from '@/domain/Executables/Identifiable';
|
||||||
import type { ICodeChangedEvent } from './ICodeChangedEvent';
|
import type { ICodeChangedEvent } from './ICodeChangedEvent';
|
||||||
|
|
||||||
export class CodeChangedEvent implements ICodeChangedEvent {
|
export class CodeChangedEvent implements ICodeChangedEvent {
|
||||||
public readonly code: string;
|
public readonly code: string;
|
||||||
|
|
||||||
public readonly addedScripts: ReadonlyArray<IScript>;
|
public readonly addedScripts: ReadonlyArray<Script>;
|
||||||
|
|
||||||
public readonly removedScripts: ReadonlyArray<IScript>;
|
public readonly removedScripts: ReadonlyArray<Script>;
|
||||||
|
|
||||||
public readonly changedScripts: ReadonlyArray<IScript>;
|
public readonly changedScripts: ReadonlyArray<Script>;
|
||||||
|
|
||||||
private readonly scripts: Map<IScript, ICodePosition>;
|
private readonly scripts: Map<Script, ICodePosition>;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
code: string,
|
code: string,
|
||||||
@@ -25,7 +27,7 @@ export class CodeChangedEvent implements ICodeChangedEvent {
|
|||||||
this.addedScripts = selectIfNotExists(newScripts, oldScripts);
|
this.addedScripts = selectIfNotExists(newScripts, oldScripts);
|
||||||
this.removedScripts = selectIfNotExists(oldScripts, newScripts);
|
this.removedScripts = selectIfNotExists(oldScripts, newScripts);
|
||||||
this.changedScripts = getChangedScripts(oldScripts, newScripts);
|
this.changedScripts = getChangedScripts(oldScripts, newScripts);
|
||||||
this.scripts = new Map<IScript, ICodePosition>();
|
this.scripts = new Map<Script, ICodePosition>();
|
||||||
scripts.forEach((position, selection) => {
|
scripts.forEach((position, selection) => {
|
||||||
this.scripts.set(selection.script, position);
|
this.scripts.set(selection.script, position);
|
||||||
});
|
});
|
||||||
@@ -35,13 +37,13 @@ export class CodeChangedEvent implements ICodeChangedEvent {
|
|||||||
return this.scripts.size === 0;
|
return this.scripts.size === 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
public getScriptPositionInCode(script: IScript): ICodePosition {
|
public getScriptPositionInCode(script: Script): ICodePosition {
|
||||||
return this.getPositionById(script.id);
|
return this.getPositionById(script.executableId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private getPositionById(scriptId: string): ICodePosition {
|
private getPositionById(scriptId: ExecutableId): ICodePosition {
|
||||||
const position = [...this.scripts.entries()]
|
const position = [...this.scripts.entries()]
|
||||||
.filter(([s]) => s.id === scriptId)
|
.filter(([s]) => s.executableId === scriptId)
|
||||||
.map(([, pos]) => pos)
|
.map(([, pos]) => pos)
|
||||||
.at(0);
|
.at(0);
|
||||||
if (!position) {
|
if (!position) {
|
||||||
@@ -52,12 +54,12 @@ export class CodeChangedEvent implements ICodeChangedEvent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function ensureAllPositionsExist(script: string, positions: ReadonlyArray<ICodePosition>) {
|
function ensureAllPositionsExist(script: string, positions: ReadonlyArray<ICodePosition>) {
|
||||||
const totalLines = script.split(/\r\n|\r|\n/).length;
|
const totalLines = splitTextIntoLines(script).length;
|
||||||
const missingPositions = positions.filter((position) => position.endLine > totalLines);
|
const missingPositions = positions.filter((position) => position.endLine > totalLines);
|
||||||
if (missingPositions.length > 0) {
|
if (missingPositions.length > 0) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Out of range script end line: "${missingPositions.map((pos) => pos.endLine).join('", "')}"`
|
`Out of range script end line: "${missingPositions.map((pos) => pos.endLine).join('", "')}"`
|
||||||
+ `(total code lines: ${totalLines}).`,
|
+ ` (total code lines: ${totalLines}).`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -65,7 +67,7 @@ function ensureAllPositionsExist(script: string, positions: ReadonlyArray<ICodeP
|
|||||||
function getChangedScripts(
|
function getChangedScripts(
|
||||||
oldScripts: ReadonlyArray<SelectedScript>,
|
oldScripts: ReadonlyArray<SelectedScript>,
|
||||||
newScripts: ReadonlyArray<SelectedScript>,
|
newScripts: ReadonlyArray<SelectedScript>,
|
||||||
): ReadonlyArray<IScript> {
|
): ReadonlyArray<Script> {
|
||||||
return newScripts
|
return newScripts
|
||||||
.filter((newScript) => oldScripts.find((oldScript) => oldScript.id === newScript.id
|
.filter((newScript) => oldScripts.find((oldScript) => oldScript.id === newScript.id
|
||||||
&& oldScript.revert !== newScript.revert))
|
&& oldScript.revert !== newScript.revert))
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import type { IScript } from '@/domain/IScript';
|
import type { Script } from '@/domain/Executables/Script/Script';
|
||||||
import type { ICodePosition } from '@/application/Context/State/Code/Position/ICodePosition';
|
import type { ICodePosition } from '@/application/Context/State/Code/Position/ICodePosition';
|
||||||
|
|
||||||
export interface ICodeChangedEvent {
|
export interface ICodeChangedEvent {
|
||||||
readonly code: string;
|
readonly code: string;
|
||||||
readonly addedScripts: ReadonlyArray<IScript>;
|
readonly addedScripts: ReadonlyArray<Script>;
|
||||||
readonly removedScripts: ReadonlyArray<IScript>;
|
readonly removedScripts: ReadonlyArray<Script>;
|
||||||
readonly changedScripts: ReadonlyArray<IScript>;
|
readonly changedScripts: ReadonlyArray<Script>;
|
||||||
isEmpty(): boolean;
|
isEmpty(): boolean;
|
||||||
getScriptPositionInCode(script: IScript): ICodePosition;
|
getScriptPositionInCode(script: Script): ICodePosition;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { splitTextIntoLines } from '@/application/Common/Text/SplitTextIntoLines';
|
||||||
import type { ICodeBuilder } from './ICodeBuilder';
|
import type { ICodeBuilder } from './ICodeBuilder';
|
||||||
|
|
||||||
const TotalFunctionSeparatorChars = 58;
|
const TotalFunctionSeparatorChars = 58;
|
||||||
@@ -15,7 +16,7 @@ export abstract class CodeBuilder implements ICodeBuilder {
|
|||||||
this.lines.push('');
|
this.lines.push('');
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
const lines = code.match(/[^\r\n]+/g);
|
const lines = splitTextIntoLines(code);
|
||||||
if (lines) {
|
if (lines) {
|
||||||
this.lines.push(...lines);
|
this.lines.push(...lines);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { EventSource } from '@/infrastructure/Events/EventSource';
|
import { EventSource } from '@/infrastructure/Events/EventSource';
|
||||||
import type { ICategoryCollection } from '@/domain/ICategoryCollection';
|
import type { ICategoryCollection } from '@/domain/Collection/ICategoryCollection';
|
||||||
import { FilterChange } from './Event/FilterChange';
|
import { FilterChange } from './Event/FilterChange';
|
||||||
import { LinearFilterStrategy } from './Strategy/LinearFilterStrategy';
|
import { LinearFilterStrategy } from './Strategy/LinearFilterStrategy';
|
||||||
import type { FilterResult } from './Result/FilterResult';
|
import type { FilterResult } from './Result/FilterResult';
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import type { IScript } from '@/domain/IScript';
|
import type { Script } from '@/domain/Executables/Script/Script';
|
||||||
import type { ICategory } from '@/domain/ICategory';
|
import type { Category } from '@/domain/Executables/Category/Category';
|
||||||
import type { FilterResult } from './FilterResult';
|
import type { FilterResult } from './FilterResult';
|
||||||
|
|
||||||
export class AppliedFilterResult implements FilterResult {
|
export class AppliedFilterResult implements FilterResult {
|
||||||
constructor(
|
constructor(
|
||||||
public readonly scriptMatches: ReadonlyArray<IScript>,
|
public readonly scriptMatches: ReadonlyArray<Script>,
|
||||||
public readonly categoryMatches: ReadonlyArray<ICategory>,
|
public readonly categoryMatches: ReadonlyArray<Category>,
|
||||||
public readonly query: string,
|
public readonly query: string,
|
||||||
) {
|
) {
|
||||||
if (!query) { throw new Error('Query is empty or undefined'); }
|
if (!query) { throw new Error('Query is empty or undefined'); }
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import type { IScript, ICategory } from '@/domain/ICategory';
|
import type { Category } from '@/domain/Executables/Category/Category';
|
||||||
|
import type { Script } from '@/domain/Executables/Script/Script';
|
||||||
|
|
||||||
export interface FilterResult {
|
export interface FilterResult {
|
||||||
readonly categoryMatches: ReadonlyArray<ICategory>;
|
readonly categoryMatches: ReadonlyArray<Category>;
|
||||||
readonly scriptMatches: ReadonlyArray<IScript>;
|
readonly scriptMatches: ReadonlyArray<Script>;
|
||||||
readonly query: string;
|
readonly query: string;
|
||||||
hasAnyMatches(): boolean;
|
hasAnyMatches(): boolean;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { ICategoryCollection } from '@/domain/ICategoryCollection';
|
import type { ICategoryCollection } from '@/domain/Collection/ICategoryCollection';
|
||||||
import type { FilterResult } from '../Result/FilterResult';
|
import type { FilterResult } from '../Result/FilterResult';
|
||||||
|
|
||||||
export interface FilterStrategy {
|
export interface FilterStrategy {
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import type { ICategory, IScript } from '@/domain/ICategory';
|
import type { Category } from '@/domain/Executables/Category/Category';
|
||||||
import type { IScriptCode } from '@/domain/IScriptCode';
|
import type { ScriptCode } from '@/domain/Executables/Script/Code/ScriptCode';
|
||||||
import type { IDocumentable } from '@/domain/IDocumentable';
|
import type { Documentable } from '@/domain/Executables/Documentable';
|
||||||
import type { ICategoryCollection } from '@/domain/ICategoryCollection';
|
import type { ICategoryCollection } from '@/domain/Collection/ICategoryCollection';
|
||||||
|
import type { Script } from '@/domain/Executables/Script/Script';
|
||||||
import { AppliedFilterResult } from '../Result/AppliedFilterResult';
|
import { AppliedFilterResult } from '../Result/AppliedFilterResult';
|
||||||
import type { FilterStrategy } from './FilterStrategy';
|
import type { FilterStrategy } from './FilterStrategy';
|
||||||
import type { FilterResult } from '../Result/FilterResult';
|
import type { FilterResult } from '../Result/FilterResult';
|
||||||
@@ -24,7 +25,7 @@ export class LinearFilterStrategy implements FilterStrategy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function matchesCategory(
|
function matchesCategory(
|
||||||
category: ICategory,
|
category: Category,
|
||||||
filterLowercase: string,
|
filterLowercase: string,
|
||||||
): boolean {
|
): boolean {
|
||||||
return matchesAny(
|
return matchesAny(
|
||||||
@@ -34,7 +35,7 @@ function matchesCategory(
|
|||||||
}
|
}
|
||||||
|
|
||||||
function matchesScript(
|
function matchesScript(
|
||||||
script: IScript,
|
script: Script,
|
||||||
filterLowercase: string,
|
filterLowercase: string,
|
||||||
): boolean {
|
): boolean {
|
||||||
return matchesAny(
|
return matchesAny(
|
||||||
@@ -58,7 +59,7 @@ function matchName(
|
|||||||
}
|
}
|
||||||
|
|
||||||
function matchCode(
|
function matchCode(
|
||||||
code: IScriptCode,
|
code: ScriptCode,
|
||||||
filterLowercase: string,
|
filterLowercase: string,
|
||||||
): boolean {
|
): boolean {
|
||||||
if (code.execute.toLowerCase().includes(filterLowercase)) {
|
if (code.execute.toLowerCase().includes(filterLowercase)) {
|
||||||
@@ -71,7 +72,7 @@ function matchCode(
|
|||||||
}
|
}
|
||||||
|
|
||||||
function matchDocumentation(
|
function matchDocumentation(
|
||||||
documentable: IDocumentable,
|
documentable: Documentable,
|
||||||
filterLowercase: string,
|
filterLowercase: string,
|
||||||
): boolean {
|
): boolean {
|
||||||
return documentable.docs.some(
|
return documentable.docs.some(
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { ICategoryCollection } from '@/domain/ICategoryCollection';
|
import type { ICategoryCollection } from '@/domain/Collection/ICategoryCollection';
|
||||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||||
import type { IApplicationCode } from './Code/IApplicationCode';
|
import type { IApplicationCode } from './Code/IApplicationCode';
|
||||||
import type { ReadonlyFilterContext, FilterContext } from './Filter/FilterContext';
|
import type { ReadonlyFilterContext, FilterContext } from './Filter/FilterContext';
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import type { ICategory } from '@/domain/ICategory';
|
import type { Category } from '@/domain/Executables/Category/Category';
|
||||||
import type { CategorySelectionChangeCommand } from './CategorySelectionChange';
|
import type { CategorySelectionChangeCommand } from './CategorySelectionChange';
|
||||||
|
|
||||||
export interface ReadonlyCategorySelection {
|
export interface ReadonlyCategorySelection {
|
||||||
areAllScriptsSelected(category: ICategory): boolean;
|
areAllScriptsSelected(category: Category): boolean;
|
||||||
isAnyScriptSelected(category: ICategory): boolean;
|
isAnyScriptSelected(category: Category): boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CategorySelection extends ReadonlyCategorySelection {
|
export interface CategorySelection extends ReadonlyCategorySelection {
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import type { ExecutableId } from '@/domain/Executables/Identifiable';
|
||||||
|
|
||||||
type CategorySelectionStatus = {
|
type CategorySelectionStatus = {
|
||||||
readonly isSelected: true;
|
readonly isSelected: true;
|
||||||
readonly isReverted: boolean;
|
readonly isReverted: boolean;
|
||||||
@@ -6,7 +8,7 @@ type CategorySelectionStatus = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export interface CategorySelectionChange {
|
export interface CategorySelectionChange {
|
||||||
readonly categoryId: number;
|
readonly categoryId: ExecutableId;
|
||||||
readonly newStatus: CategorySelectionStatus;
|
readonly newStatus: CategorySelectionStatus;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { ICategory } from '@/domain/ICategory';
|
import type { Category } from '@/domain/Executables/Category/Category';
|
||||||
import type { ICategoryCollection } from '@/domain/ICategoryCollection';
|
import type { ICategoryCollection } from '@/domain/Collection/ICategoryCollection';
|
||||||
import type { CategorySelectionChange, CategorySelectionChangeCommand } from './CategorySelectionChange';
|
import type { CategorySelectionChange, CategorySelectionChangeCommand } from './CategorySelectionChange';
|
||||||
import type { CategorySelection } from './CategorySelection';
|
import type { CategorySelection } from './CategorySelection';
|
||||||
import type { ScriptSelection } from '../Script/ScriptSelection';
|
import type { ScriptSelection } from '../Script/ScriptSelection';
|
||||||
@@ -13,7 +13,7 @@ export class ScriptToCategorySelectionMapper implements CategorySelection {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public areAllScriptsSelected(category: ICategory): boolean {
|
public areAllScriptsSelected(category: Category): boolean {
|
||||||
const { selectedScripts } = this.scriptSelection;
|
const { selectedScripts } = this.scriptSelection;
|
||||||
if (selectedScripts.length === 0) {
|
if (selectedScripts.length === 0) {
|
||||||
return false;
|
return false;
|
||||||
@@ -23,11 +23,11 @@ export class ScriptToCategorySelectionMapper implements CategorySelection {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return scripts.every(
|
return scripts.every(
|
||||||
(script) => selectedScripts.some((selected) => selected.id === script.id),
|
(script) => selectedScripts.some((selected) => selected.id === script.executableId),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public isAnyScriptSelected(category: ICategory): boolean {
|
public isAnyScriptSelected(category: Category): boolean {
|
||||||
const { selectedScripts } = this.scriptSelection;
|
const { selectedScripts } = this.scriptSelection;
|
||||||
if (selectedScripts.length === 0) {
|
if (selectedScripts.length === 0) {
|
||||||
return false;
|
return false;
|
||||||
@@ -50,7 +50,7 @@ export class ScriptToCategorySelectionMapper implements CategorySelection {
|
|||||||
const scripts = category.getAllScriptsRecursively();
|
const scripts = category.getAllScriptsRecursively();
|
||||||
const scriptsChangesInCategory = scripts
|
const scriptsChangesInCategory = scripts
|
||||||
.map((script): ScriptSelectionChange => ({
|
.map((script): ScriptSelectionChange => ({
|
||||||
scriptId: script.id,
|
scriptId: script.executableId,
|
||||||
newStatus: {
|
newStatus: {
|
||||||
...change.newStatus,
|
...change.newStatus,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import { InMemoryRepository } from '@/infrastructure/Repository/InMemoryRepository';
|
import { InMemoryRepository } from '@/infrastructure/Repository/InMemoryRepository';
|
||||||
import type { IScript } from '@/domain/IScript';
|
import type { Script } from '@/domain/Executables/Script/Script';
|
||||||
import { EventSource } from '@/infrastructure/Events/EventSource';
|
import { EventSource } from '@/infrastructure/Events/EventSource';
|
||||||
import type { ReadonlyRepository, Repository } from '@/application/Repository/Repository';
|
import type { ReadonlyRepository, Repository } from '@/application/Repository/Repository';
|
||||||
import type { ICategoryCollection } from '@/domain/ICategoryCollection';
|
import type { ICategoryCollection } from '@/domain/Collection/ICategoryCollection';
|
||||||
import { batchedDebounce } from '@/application/Common/Timing/BatchedDebounce';
|
import { batchedDebounce } from '@/application/Common/Timing/BatchedDebounce';
|
||||||
|
import type { ExecutableId } from '@/domain/Executables/Identifiable';
|
||||||
import { UserSelectedScript } from './UserSelectedScript';
|
import { UserSelectedScript } from './UserSelectedScript';
|
||||||
import type { ScriptSelection } from './ScriptSelection';
|
import type { ScriptSelection } from './ScriptSelection';
|
||||||
import type { ScriptSelectionChange, ScriptSelectionChangeCommand } from './ScriptSelectionChange';
|
import type { ScriptSelectionChange, ScriptSelectionChangeCommand } from './ScriptSelectionChange';
|
||||||
@@ -16,7 +17,7 @@ export type DebounceFunction = typeof batchedDebounce<ScriptSelectionChangeComma
|
|||||||
export class DebouncedScriptSelection implements ScriptSelection {
|
export class DebouncedScriptSelection implements ScriptSelection {
|
||||||
public readonly changed = new EventSource<ReadonlyArray<SelectedScript>>();
|
public readonly changed = new EventSource<ReadonlyArray<SelectedScript>>();
|
||||||
|
|
||||||
private readonly scripts: Repository<string, SelectedScript>;
|
private readonly scripts: Repository<SelectedScript>;
|
||||||
|
|
||||||
public readonly processChanges: ScriptSelection['processChanges'];
|
public readonly processChanges: ScriptSelection['processChanges'];
|
||||||
|
|
||||||
@@ -25,7 +26,7 @@ export class DebouncedScriptSelection implements ScriptSelection {
|
|||||||
selectedScripts: ReadonlyArray<SelectedScript>,
|
selectedScripts: ReadonlyArray<SelectedScript>,
|
||||||
debounce: DebounceFunction = batchedDebounce,
|
debounce: DebounceFunction = batchedDebounce,
|
||||||
) {
|
) {
|
||||||
this.scripts = new InMemoryRepository<string, SelectedScript>();
|
this.scripts = new InMemoryRepository<SelectedScript>();
|
||||||
for (const script of selectedScripts) {
|
for (const script of selectedScripts) {
|
||||||
this.scripts.addItem(script);
|
this.scripts.addItem(script);
|
||||||
}
|
}
|
||||||
@@ -38,8 +39,8 @@ export class DebouncedScriptSelection implements ScriptSelection {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
public isSelected(scriptId: string): boolean {
|
public isSelected(scriptExecutableId: ExecutableId): boolean {
|
||||||
return this.scripts.exists(scriptId);
|
return this.scripts.exists(scriptExecutableId);
|
||||||
}
|
}
|
||||||
|
|
||||||
public get selectedScripts(): readonly SelectedScript[] {
|
public get selectedScripts(): readonly SelectedScript[] {
|
||||||
@@ -49,7 +50,7 @@ export class DebouncedScriptSelection implements ScriptSelection {
|
|||||||
public selectAll(): void {
|
public selectAll(): void {
|
||||||
const scriptsToSelect = this.collection
|
const scriptsToSelect = this.collection
|
||||||
.getAllScripts()
|
.getAllScripts()
|
||||||
.filter((script) => !this.scripts.exists(script.id))
|
.filter((script) => !this.scripts.exists(script.executableId))
|
||||||
.map((script) => new UserSelectedScript(script, false));
|
.map((script) => new UserSelectedScript(script, false));
|
||||||
if (scriptsToSelect.length === 0) {
|
if (scriptsToSelect.length === 0) {
|
||||||
return;
|
return;
|
||||||
@@ -80,7 +81,7 @@ export class DebouncedScriptSelection implements ScriptSelection {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public selectOnly(scripts: readonly IScript[]): void {
|
public selectOnly(scripts: readonly Script[]): void {
|
||||||
assertNonEmptyScriptSelection(scripts);
|
assertNonEmptyScriptSelection(scripts);
|
||||||
this.processChanges({
|
this.processChanges({
|
||||||
changes: [
|
changes: [
|
||||||
@@ -116,12 +117,12 @@ export class DebouncedScriptSelection implements ScriptSelection {
|
|||||||
private applyChange(change: ScriptSelectionChange): number {
|
private applyChange(change: ScriptSelectionChange): number {
|
||||||
const script = this.collection.getScript(change.scriptId);
|
const script = this.collection.getScript(change.scriptId);
|
||||||
if (change.newStatus.isSelected) {
|
if (change.newStatus.isSelected) {
|
||||||
return this.addOrUpdateScript(script.id, change.newStatus.isReverted);
|
return this.addOrUpdateScript(script.executableId, change.newStatus.isReverted);
|
||||||
}
|
}
|
||||||
return this.removeScript(script.id);
|
return this.removeScript(script.executableId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private addOrUpdateScript(scriptId: string, revert: boolean): number {
|
private addOrUpdateScript(scriptId: ExecutableId, revert: boolean): number {
|
||||||
const script = this.collection.getScript(scriptId);
|
const script = this.collection.getScript(scriptId);
|
||||||
const selectedScript = new UserSelectedScript(script, revert);
|
const selectedScript = new UserSelectedScript(script, revert);
|
||||||
if (!this.scripts.exists(selectedScript.id)) {
|
if (!this.scripts.exists(selectedScript.id)) {
|
||||||
@@ -136,7 +137,7 @@ export class DebouncedScriptSelection implements ScriptSelection {
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
private removeScript(scriptId: string): number {
|
private removeScript(scriptId: ExecutableId): number {
|
||||||
if (!this.scripts.exists(scriptId)) {
|
if (!this.scripts.exists(scriptId)) {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
@@ -145,31 +146,31 @@ export class DebouncedScriptSelection implements ScriptSelection {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function assertNonEmptyScriptSelection(selectedItems: readonly IScript[]) {
|
function assertNonEmptyScriptSelection(selectedItems: readonly Script[]) {
|
||||||
if (selectedItems.length === 0) {
|
if (selectedItems.length === 0) {
|
||||||
throw new Error('Provided script array is empty. To deselect all scripts, please use the deselectAll() method instead.');
|
throw new Error('Provided script array is empty. To deselect all scripts, please use the deselectAll() method instead.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function getScriptIdsToBeSelected(
|
function getScriptIdsToBeSelected(
|
||||||
existingItems: ReadonlyRepository<string, SelectedScript>,
|
existingItems: ReadonlyRepository<SelectedScript>,
|
||||||
desiredScripts: readonly IScript[],
|
desiredScripts: readonly Script[],
|
||||||
): string[] {
|
): string[] {
|
||||||
return desiredScripts
|
return desiredScripts
|
||||||
.filter((script) => !existingItems.exists(script.id))
|
.filter((script) => !existingItems.exists(script.executableId))
|
||||||
.map((script) => script.id);
|
.map((script) => script.executableId);
|
||||||
}
|
}
|
||||||
|
|
||||||
function getScriptIdsToBeDeselected(
|
function getScriptIdsToBeDeselected(
|
||||||
existingItems: ReadonlyRepository<string, SelectedScript>,
|
existingItems: ReadonlyRepository<SelectedScript>,
|
||||||
desiredScripts: readonly IScript[],
|
desiredScripts: readonly Script[],
|
||||||
): string[] {
|
): string[] {
|
||||||
return existingItems
|
return existingItems
|
||||||
.getItems()
|
.getItems()
|
||||||
.filter((existing) => !desiredScripts.some((script) => existing.id === script.id))
|
.filter((existing) => !desiredScripts.some((script) => existing.id === script.executableId))
|
||||||
.map((script) => script.id);
|
.map((script) => script.id);
|
||||||
}
|
}
|
||||||
|
|
||||||
function equals(a: SelectedScript, b: SelectedScript): boolean {
|
function equals(a: SelectedScript, b: SelectedScript): boolean {
|
||||||
return a.script.equals(b.script.id) && a.revert === b.revert;
|
return a.script.executableId === b.script.executableId && a.revert === b.revert;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,17 @@
|
|||||||
import type { IEventSource } from '@/infrastructure/Events/IEventSource';
|
import type { IEventSource } from '@/infrastructure/Events/IEventSource';
|
||||||
import type { IScript } from '@/domain/IScript';
|
import type { Script } from '@/domain/Executables/Script/Script';
|
||||||
|
import type { ExecutableId } from '@/domain/Executables/Identifiable';
|
||||||
import type { SelectedScript } from './SelectedScript';
|
import type { SelectedScript } from './SelectedScript';
|
||||||
import type { ScriptSelectionChangeCommand } from './ScriptSelectionChange';
|
import type { ScriptSelectionChangeCommand } from './ScriptSelectionChange';
|
||||||
|
|
||||||
export interface ReadonlyScriptSelection {
|
export interface ReadonlyScriptSelection {
|
||||||
readonly changed: IEventSource<readonly SelectedScript[]>;
|
readonly changed: IEventSource<readonly SelectedScript[]>;
|
||||||
readonly selectedScripts: readonly SelectedScript[];
|
readonly selectedScripts: readonly SelectedScript[];
|
||||||
isSelected(scriptId: string): boolean;
|
isSelected(scriptExecutableId: ExecutableId): boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ScriptSelection extends ReadonlyScriptSelection {
|
export interface ScriptSelection extends ReadonlyScriptSelection {
|
||||||
selectOnly(scripts: readonly IScript[]): void;
|
selectOnly(scripts: readonly Script[]): void;
|
||||||
selectAll(): void;
|
selectAll(): void;
|
||||||
deselectAll(): void;
|
deselectAll(): void;
|
||||||
processChanges(action: ScriptSelectionChangeCommand): void;
|
processChanges(action: ScriptSelectionChangeCommand): void;
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import type { ExecutableId } from '@/domain/Executables/Identifiable';
|
||||||
|
|
||||||
export type ScriptSelectionStatus = {
|
export type ScriptSelectionStatus = {
|
||||||
readonly isSelected: true;
|
readonly isSelected: true;
|
||||||
readonly isReverted: boolean;
|
readonly isReverted: boolean;
|
||||||
@@ -7,7 +9,7 @@ export type ScriptSelectionStatus = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export interface ScriptSelectionChange {
|
export interface ScriptSelectionChange {
|
||||||
readonly scriptId: string;
|
readonly scriptId: ExecutableId;
|
||||||
readonly newStatus: ScriptSelectionStatus;
|
readonly newStatus: ScriptSelectionStatus;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
import type { IEntity } from '@/infrastructure/Entity/IEntity';
|
import type { Script } from '@/domain/Executables/Script/Script';
|
||||||
import type { IScript } from '@/domain/IScript';
|
import type { RepositoryEntity } from '@/application/Repository/RepositoryEntity';
|
||||||
|
|
||||||
type ScriptId = IScript['id'];
|
export interface SelectedScript extends RepositoryEntity {
|
||||||
|
readonly script: Script;
|
||||||
export interface SelectedScript extends IEntity<ScriptId> {
|
|
||||||
readonly script: IScript;
|
|
||||||
readonly revert: boolean;
|
readonly revert: boolean;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,16 @@
|
|||||||
import { BaseEntity } from '@/infrastructure/Entity/BaseEntity';
|
import type { Script } from '@/domain/Executables/Script/Script';
|
||||||
import type { IScript } from '@/domain/IScript';
|
import type { RepositoryEntity } from '@/application/Repository/RepositoryEntity';
|
||||||
import type { SelectedScript } from './SelectedScript';
|
|
||||||
|
|
||||||
type SelectedScriptId = SelectedScript['id'];
|
export class UserSelectedScript implements RepositoryEntity {
|
||||||
|
public readonly id: string;
|
||||||
|
|
||||||
export class UserSelectedScript extends BaseEntity<SelectedScriptId> {
|
|
||||||
constructor(
|
constructor(
|
||||||
public readonly script: IScript,
|
public readonly script: Script,
|
||||||
public readonly revert: boolean,
|
public readonly revert: boolean,
|
||||||
) {
|
) {
|
||||||
super(script.id);
|
this.id = script.executableId;
|
||||||
if (revert && !script.canRevert()) {
|
if (revert && !script.canRevert()) {
|
||||||
throw new Error(`The script with ID '${script.id}' is not reversible and cannot be reverted.`);
|
throw new Error(`The script with ID '${script.executableId}' is not reversible and cannot be reverted.`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { ICategoryCollection } from '@/domain/ICategoryCollection';
|
import type { ICategoryCollection } from '@/domain/Collection/ICategoryCollection';
|
||||||
import { ScriptToCategorySelectionMapper } from './Category/ScriptToCategorySelectionMapper';
|
import { ScriptToCategorySelectionMapper } from './Category/ScriptToCategorySelectionMapper';
|
||||||
import { DebouncedScriptSelection } from './Script/DebouncedScriptSelection';
|
import { DebouncedScriptSelection } from './Script/DebouncedScriptSelection';
|
||||||
import type { CategorySelection } from './Category/CategorySelection';
|
import type { CategorySelection } from './Category/CategorySelection';
|
||||||
|
|||||||
@@ -1,40 +1,48 @@
|
|||||||
import type { CollectionData } from '@/application/collections/';
|
import type { CollectionData } from '@/application/collections/';
|
||||||
import type { IApplication } from '@/domain/IApplication';
|
import type { IApplication } from '@/domain/IApplication';
|
||||||
import type { ProjectDetails } from '@/domain/Project/ProjectDetails';
|
|
||||||
import type { ICategoryCollection } from '@/domain/ICategoryCollection';
|
|
||||||
import WindowsData from '@/application/collections/windows.yaml';
|
import WindowsData from '@/application/collections/windows.yaml';
|
||||||
import MacOsData from '@/application/collections/macos.yaml';
|
import MacOsData from '@/application/collections/macos.yaml';
|
||||||
import LinuxData from '@/application/collections/linux.yaml';
|
import LinuxData from '@/application/collections/linux.yaml';
|
||||||
import { parseProjectDetails } from '@/application/Parser/ProjectDetailsParser';
|
import { parseProjectDetails, type ProjectDetailsParser } from '@/application/Parser/ProjectDetailsParser';
|
||||||
import { Application } from '@/domain/Application';
|
import { Application } from '@/domain/Application';
|
||||||
import type { IAppMetadata } from '@/infrastructure/EnvironmentVariables/IAppMetadata';
|
import { parseCategoryCollection, type CategoryCollectionParser } from './CategoryCollectionParser';
|
||||||
import { EnvironmentVariablesFactory } from '@/infrastructure/EnvironmentVariables/EnvironmentVariablesFactory';
|
import { createTypeValidator, type TypeValidator } from './Common/TypeValidator';
|
||||||
import { parseCategoryCollection } from './CategoryCollectionParser';
|
|
||||||
|
|
||||||
export function parseApplication(
|
export function parseApplication(
|
||||||
categoryParser = parseCategoryCollection,
|
collectionsData: readonly CollectionData[] = PreParsedCollections,
|
||||||
projectDetailsParser = parseProjectDetails,
|
utilities: ApplicationParserUtilities = DefaultUtilities,
|
||||||
metadata: IAppMetadata = EnvironmentVariablesFactory.Current.instance,
|
|
||||||
collectionsData = PreParsedCollections,
|
|
||||||
): IApplication {
|
): IApplication {
|
||||||
validateCollectionsData(collectionsData);
|
validateCollectionsData(collectionsData, utilities.validator);
|
||||||
const projectDetails = projectDetailsParser(metadata);
|
const projectDetails = utilities.parseProjectDetails();
|
||||||
const collections = collectionsData.map(
|
const collections = collectionsData.map(
|
||||||
(collection) => categoryParser(collection, projectDetails),
|
(collection) => utilities.parseCategoryCollection(collection, projectDetails),
|
||||||
);
|
);
|
||||||
const app = new Application(projectDetails, collections);
|
const app = new Application(projectDetails, collections);
|
||||||
return app;
|
return app;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type CategoryCollectionParserType
|
const PreParsedCollections: readonly CollectionData[] = [
|
||||||
= (file: CollectionData, projectDetails: ProjectDetails) => ICategoryCollection;
|
|
||||||
|
|
||||||
const PreParsedCollections: readonly CollectionData [] = [
|
|
||||||
WindowsData, MacOsData, LinuxData,
|
WindowsData, MacOsData, LinuxData,
|
||||||
];
|
];
|
||||||
|
|
||||||
function validateCollectionsData(collections: readonly CollectionData[]) {
|
function validateCollectionsData(
|
||||||
if (!collections.length) {
|
collections: readonly CollectionData[],
|
||||||
throw new Error('missing collections');
|
validator: TypeValidator,
|
||||||
}
|
) {
|
||||||
|
validator.assertNonEmptyCollection({
|
||||||
|
value: collections,
|
||||||
|
valueName: 'Collections',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ApplicationParserUtilities {
|
||||||
|
readonly parseCategoryCollection: CategoryCollectionParser;
|
||||||
|
readonly validator: TypeValidator;
|
||||||
|
readonly parseProjectDetails: ProjectDetailsParser;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DefaultUtilities: ApplicationParserUtilities = {
|
||||||
|
parseCategoryCollection,
|
||||||
|
parseProjectDetails,
|
||||||
|
validator: createTypeValidator(),
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,34 +1,75 @@
|
|||||||
import type { CollectionData } from '@/application/collections/';
|
import type { CollectionData } from '@/application/collections/';
|
||||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||||
import type { ICategoryCollection } from '@/domain/ICategoryCollection';
|
import type { ICategoryCollection } from '@/domain/Collection/ICategoryCollection';
|
||||||
import { CategoryCollection } from '@/domain/CategoryCollection';
|
import { CategoryCollection } from '@/domain/Collection/CategoryCollection';
|
||||||
import type { ProjectDetails } from '@/domain/Project/ProjectDetails';
|
import type { ProjectDetails } from '@/domain/Project/ProjectDetails';
|
||||||
import { createEnumParser } from '../Common/Enum';
|
import { createEnumParser, type EnumParser } from '../Common/Enum';
|
||||||
import { parseCategory } from './CategoryParser';
|
import { parseCategory, type CategoryParser } from './Executable/CategoryParser';
|
||||||
import { CategoryCollectionParseContext } from './Script/CategoryCollectionParseContext';
|
import { parseScriptingDefinition, type ScriptingDefinitionParser } from './ScriptingDefinition/ScriptingDefinitionParser';
|
||||||
import { ScriptingDefinitionParser } from './ScriptingDefinition/ScriptingDefinitionParser';
|
import { createTypeValidator, type TypeValidator } from './Common/TypeValidator';
|
||||||
|
import { createCategoryCollectionContext, type CategoryCollectionContextFactory } from './Executable/CategoryCollectionContext';
|
||||||
|
|
||||||
export function parseCategoryCollection(
|
export const parseCategoryCollection: CategoryCollectionParser = (
|
||||||
content: CollectionData,
|
content,
|
||||||
projectDetails: ProjectDetails,
|
projectDetails,
|
||||||
osParser = createEnumParser(OperatingSystem),
|
utilities: CategoryCollectionParserUtilities = DefaultUtilities,
|
||||||
): ICategoryCollection {
|
) => {
|
||||||
validate(content);
|
validateCollection(content, utilities.validator);
|
||||||
const scripting = new ScriptingDefinitionParser()
|
const scripting = utilities.parseScriptingDefinition(content.scripting, projectDetails);
|
||||||
.parse(content.scripting, projectDetails);
|
const collectionContext = utilities.createContext(content.functions, scripting.language);
|
||||||
const context = new CategoryCollectionParseContext(content.functions, scripting);
|
const categories = content.actions.map(
|
||||||
const categories = content.actions.map((action) => parseCategory(action, context));
|
(action) => utilities.parseCategory(action, collectionContext),
|
||||||
const os = osParser.parseEnum(content.os, 'os');
|
|
||||||
const collection = new CategoryCollection(
|
|
||||||
os,
|
|
||||||
categories,
|
|
||||||
scripting,
|
|
||||||
);
|
);
|
||||||
|
const os = utilities.osParser.parseEnum(content.os, 'os');
|
||||||
|
const collection = utilities.createCategoryCollection({
|
||||||
|
os, actions: categories, scripting,
|
||||||
|
});
|
||||||
return collection;
|
return collection;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CategoryCollectionFactory = (
|
||||||
|
...parameters: ConstructorParameters<typeof CategoryCollection>
|
||||||
|
) => ICategoryCollection;
|
||||||
|
|
||||||
|
export interface CategoryCollectionParser {
|
||||||
|
(
|
||||||
|
content: CollectionData,
|
||||||
|
projectDetails: ProjectDetails,
|
||||||
|
utilities?: CategoryCollectionParserUtilities,
|
||||||
|
): ICategoryCollection;
|
||||||
}
|
}
|
||||||
|
|
||||||
function validate(content: CollectionData): void {
|
function validateCollection(
|
||||||
if (!content.actions.length) {
|
content: CollectionData,
|
||||||
throw new Error('content does not define any action');
|
validator: TypeValidator,
|
||||||
}
|
): void {
|
||||||
|
validator.assertObject({
|
||||||
|
value: content,
|
||||||
|
valueName: 'Collection',
|
||||||
|
allowedProperties: [
|
||||||
|
'os', 'scripting', 'actions', 'functions',
|
||||||
|
],
|
||||||
|
});
|
||||||
|
validator.assertNonEmptyCollection({
|
||||||
|
value: content.actions,
|
||||||
|
valueName: '\'actions\' in collection',
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface CategoryCollectionParserUtilities {
|
||||||
|
readonly osParser: EnumParser<OperatingSystem>;
|
||||||
|
readonly validator: TypeValidator;
|
||||||
|
readonly parseScriptingDefinition: ScriptingDefinitionParser;
|
||||||
|
readonly createContext: CategoryCollectionContextFactory;
|
||||||
|
readonly parseCategory: CategoryParser;
|
||||||
|
readonly createCategoryCollection: CategoryCollectionFactory;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DefaultUtilities: CategoryCollectionParserUtilities = {
|
||||||
|
osParser: createEnumParser(OperatingSystem),
|
||||||
|
validator: createTypeValidator(),
|
||||||
|
parseScriptingDefinition,
|
||||||
|
createContext: createCategoryCollectionContext,
|
||||||
|
parseCategory,
|
||||||
|
createCategoryCollection: (...args) => new CategoryCollection(...args),
|
||||||
|
};
|
||||||
|
|||||||
@@ -1,133 +0,0 @@
|
|||||||
import type {
|
|
||||||
CategoryData, ScriptData, CategoryOrScriptData,
|
|
||||||
} from '@/application/collections/';
|
|
||||||
import { Script } from '@/domain/Script';
|
|
||||||
import { Category } from '@/domain/Category';
|
|
||||||
import { NodeValidator } from '@/application/Parser/NodeValidation/NodeValidator';
|
|
||||||
import { NodeType } from '@/application/Parser/NodeValidation/NodeType';
|
|
||||||
import { parseDocs } from './DocumentationParser';
|
|
||||||
import { parseScript } from './Script/ScriptParser';
|
|
||||||
import type { ICategoryCollectionParseContext } from './Script/ICategoryCollectionParseContext';
|
|
||||||
|
|
||||||
let categoryIdCounter = 0;
|
|
||||||
|
|
||||||
export function parseCategory(
|
|
||||||
category: CategoryData,
|
|
||||||
context: ICategoryCollectionParseContext,
|
|
||||||
factory: CategoryFactoryType = CategoryFactory,
|
|
||||||
): Category {
|
|
||||||
return parseCategoryRecursively({
|
|
||||||
categoryData: category,
|
|
||||||
context,
|
|
||||||
factory,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ICategoryParseContext {
|
|
||||||
readonly categoryData: CategoryData,
|
|
||||||
readonly context: ICategoryCollectionParseContext,
|
|
||||||
readonly factory: CategoryFactoryType,
|
|
||||||
readonly parentCategory?: CategoryData,
|
|
||||||
}
|
|
||||||
|
|
||||||
function parseCategoryRecursively(context: ICategoryParseContext): Category | never {
|
|
||||||
ensureValidCategory(context.categoryData, context.parentCategory);
|
|
||||||
const children: ICategoryChildren = {
|
|
||||||
subCategories: new Array<Category>(),
|
|
||||||
subScripts: new Array<Script>(),
|
|
||||||
};
|
|
||||||
for (const data of context.categoryData.children) {
|
|
||||||
parseNode({
|
|
||||||
nodeData: data,
|
|
||||||
children,
|
|
||||||
parent: context.categoryData,
|
|
||||||
factory: context.factory,
|
|
||||||
context: context.context,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
return context.factory(
|
|
||||||
/* id: */ categoryIdCounter++,
|
|
||||||
/* name: */ context.categoryData.category,
|
|
||||||
/* docs: */ parseDocs(context.categoryData),
|
|
||||||
/* categories: */ children.subCategories,
|
|
||||||
/* scripts: */ children.subScripts,
|
|
||||||
);
|
|
||||||
} catch (err) {
|
|
||||||
return new NodeValidator({
|
|
||||||
type: NodeType.Category,
|
|
||||||
selfNode: context.categoryData,
|
|
||||||
parentNode: context.parentCategory,
|
|
||||||
}).throw(err.message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function ensureValidCategory(category: CategoryData, parentCategory?: CategoryData) {
|
|
||||||
new NodeValidator({
|
|
||||||
type: NodeType.Category,
|
|
||||||
selfNode: category,
|
|
||||||
parentNode: parentCategory,
|
|
||||||
})
|
|
||||||
.assertDefined(category)
|
|
||||||
.assertValidName(category.category)
|
|
||||||
.assert(
|
|
||||||
() => category.children.length > 0,
|
|
||||||
`"${category.category}" has no children.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
interface ICategoryChildren {
|
|
||||||
subCategories: Category[];
|
|
||||||
subScripts: Script[];
|
|
||||||
}
|
|
||||||
|
|
||||||
interface INodeParseContext {
|
|
||||||
readonly nodeData: CategoryOrScriptData;
|
|
||||||
readonly children: ICategoryChildren;
|
|
||||||
readonly parent: CategoryData;
|
|
||||||
readonly factory: CategoryFactoryType;
|
|
||||||
readonly context: ICategoryCollectionParseContext;
|
|
||||||
}
|
|
||||||
function parseNode(context: INodeParseContext) {
|
|
||||||
const validator = new NodeValidator({ selfNode: context.nodeData, parentNode: context.parent });
|
|
||||||
validator.assertDefined(context.nodeData);
|
|
||||||
if (isCategory(context.nodeData)) {
|
|
||||||
const subCategory = parseCategoryRecursively({
|
|
||||||
categoryData: context.nodeData,
|
|
||||||
context: context.context,
|
|
||||||
factory: context.factory,
|
|
||||||
parentCategory: context.parent,
|
|
||||||
});
|
|
||||||
context.children.subCategories.push(subCategory);
|
|
||||||
} else if (isScript(context.nodeData)) {
|
|
||||||
const script = parseScript(context.nodeData, context.context);
|
|
||||||
context.children.subScripts.push(script);
|
|
||||||
} else {
|
|
||||||
validator.throw('Node is neither a category or a script.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function isScript(data: CategoryOrScriptData): data is ScriptData {
|
|
||||||
return hasCode(data) || hasCall(data);
|
|
||||||
}
|
|
||||||
|
|
||||||
function isCategory(data: CategoryOrScriptData): data is CategoryData {
|
|
||||||
return hasProperty(data, 'category');
|
|
||||||
}
|
|
||||||
|
|
||||||
function hasCode(data: unknown): boolean {
|
|
||||||
return hasProperty(data, 'code');
|
|
||||||
}
|
|
||||||
|
|
||||||
function hasCall(data: unknown) {
|
|
||||||
return hasProperty(data, 'call');
|
|
||||||
}
|
|
||||||
|
|
||||||
function hasProperty(object: unknown, propertyName: string) {
|
|
||||||
return Object.prototype.hasOwnProperty.call(object, propertyName);
|
|
||||||
}
|
|
||||||
|
|
||||||
export type CategoryFactoryType = (
|
|
||||||
...parameters: ConstructorParameters<typeof Category>) => Category;
|
|
||||||
|
|
||||||
const CategoryFactory: CategoryFactoryType = (...parameters) => new Category(...parameters);
|
|
||||||
116
src/application/Parser/Common/ContextualError.ts
Normal file
116
src/application/Parser/Common/ContextualError.ts
Normal file
@@ -0,0 +1,116 @@
|
|||||||
|
import { CustomError } from '@/application/Common/CustomError';
|
||||||
|
import { indentText } from '@/application/Common/Text/IndentText';
|
||||||
|
|
||||||
|
export interface ErrorWithContextWrapper {
|
||||||
|
(
|
||||||
|
innerError: Error,
|
||||||
|
additionalContext: string,
|
||||||
|
): Error;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const wrapErrorWithAdditionalContext: ErrorWithContextWrapper = (
|
||||||
|
innerError,
|
||||||
|
additionalContext,
|
||||||
|
) => {
|
||||||
|
if (!additionalContext) {
|
||||||
|
throw new Error('Missing additional context');
|
||||||
|
}
|
||||||
|
return new ContextualError({
|
||||||
|
innerError,
|
||||||
|
additionalContext,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class for building a detailed error trace.
|
||||||
|
*
|
||||||
|
* Alternatives considered:
|
||||||
|
* - `AggregateError`:
|
||||||
|
* Similar but not well-serialized or displayed by browsers such as Chromium (last tested v126).
|
||||||
|
* - `cause` property:
|
||||||
|
* Not displayed by all browsers (last tested v126).
|
||||||
|
* Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause
|
||||||
|
*
|
||||||
|
* This is immutable where the constructor sets the values because using getter functions such as
|
||||||
|
* `get cause()`, `get message()` does not work on Chromium (last tested v126), but works fine on
|
||||||
|
* Firefox (last tested v127).
|
||||||
|
*/
|
||||||
|
class ContextualError extends CustomError {
|
||||||
|
constructor(public readonly context: ErrorContext) {
|
||||||
|
super(
|
||||||
|
generateDetailedErrorMessageWithContext(context),
|
||||||
|
{
|
||||||
|
cause: context.innerError,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ErrorContext {
|
||||||
|
readonly innerError: Error;
|
||||||
|
readonly additionalContext: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function generateDetailedErrorMessageWithContext(
|
||||||
|
context: ErrorContext,
|
||||||
|
): string {
|
||||||
|
return [
|
||||||
|
'\n',
|
||||||
|
// Display the current error message first, then the root cause.
|
||||||
|
// This prevents repetitive main messages for errors with a `cause:` chain,
|
||||||
|
// aligning with browser error display conventions.
|
||||||
|
context.additionalContext,
|
||||||
|
'\n',
|
||||||
|
'Error Trace (starting from root cause):',
|
||||||
|
indentText(
|
||||||
|
formatErrorTrace(
|
||||||
|
// Displaying contexts from the top frame (deepest, most recent) aligns with
|
||||||
|
// common debugger/compiler standard.
|
||||||
|
extractErrorTraceAscendingFromDeepest(context),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
'\n',
|
||||||
|
].join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractErrorTraceAscendingFromDeepest(
|
||||||
|
context: ErrorContext,
|
||||||
|
): string[] {
|
||||||
|
const originalError = findRootError(context.innerError);
|
||||||
|
const contextsDescendingFromMostRecent: string[] = [
|
||||||
|
context.additionalContext,
|
||||||
|
...gatherContextsFromErrorChain(context.innerError),
|
||||||
|
originalError.toString(),
|
||||||
|
];
|
||||||
|
const contextsAscendingFromDeepest = contextsDescendingFromMostRecent.reverse();
|
||||||
|
return contextsAscendingFromDeepest;
|
||||||
|
}
|
||||||
|
|
||||||
|
function findRootError(error: Error): Error {
|
||||||
|
if (error instanceof ContextualError) {
|
||||||
|
return findRootError(error.context.innerError);
|
||||||
|
}
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
|
||||||
|
function gatherContextsFromErrorChain(
|
||||||
|
error: Error,
|
||||||
|
accumulatedContexts: string[] = [],
|
||||||
|
): string[] {
|
||||||
|
if (error instanceof ContextualError) {
|
||||||
|
accumulatedContexts.push(error.context.additionalContext);
|
||||||
|
return gatherContextsFromErrorChain(error.context.innerError, accumulatedContexts);
|
||||||
|
}
|
||||||
|
return accumulatedContexts;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatErrorTrace(
|
||||||
|
errorMessages: readonly string[],
|
||||||
|
): string {
|
||||||
|
if (errorMessages.length === 1) {
|
||||||
|
return errorMessages[0];
|
||||||
|
}
|
||||||
|
return errorMessages
|
||||||
|
.map((context, index) => `${index + 1}.${indentText(context)}`)
|
||||||
|
.join('\n');
|
||||||
|
}
|
||||||
131
src/application/Parser/Common/TypeValidator.ts
Normal file
131
src/application/Parser/Common/TypeValidator.ts
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
import type { PropertyKeys } from '@/TypeHelpers';
|
||||||
|
import {
|
||||||
|
isNullOrUndefined, isArray, isPlainObject, isString,
|
||||||
|
} from '@/TypeHelpers';
|
||||||
|
|
||||||
|
export interface TypeValidator {
|
||||||
|
assertObject<T>(assertion: ObjectAssertion<T>): void;
|
||||||
|
assertNonEmptyCollection(assertion: NonEmptyCollectionAssertion): void;
|
||||||
|
assertNonEmptyString(assertion: NonEmptyStringAssertion): void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NonEmptyCollectionAssertion {
|
||||||
|
readonly value: unknown;
|
||||||
|
readonly valueName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RegexValidationRule {
|
||||||
|
readonly expectedMatch: RegExp;
|
||||||
|
readonly errorMessage: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NonEmptyStringAssertion {
|
||||||
|
readonly value: unknown;
|
||||||
|
readonly valueName: string;
|
||||||
|
readonly rule?: RegexValidationRule;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ObjectAssertion<T> {
|
||||||
|
readonly value: T | unknown;
|
||||||
|
readonly valueName: string;
|
||||||
|
readonly allowedProperties?: readonly PropertyKeys<T>[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createTypeValidator(): TypeValidator {
|
||||||
|
return {
|
||||||
|
assertObject: (assertion) => {
|
||||||
|
assertDefined(assertion.value, assertion.valueName);
|
||||||
|
assertPlainObject(assertion.value, assertion.valueName);
|
||||||
|
assertNoEmptyProperties(assertion.value, assertion.valueName);
|
||||||
|
if (assertion.allowedProperties !== undefined) {
|
||||||
|
const allowedProperties = assertion.allowedProperties.map((p) => p as string);
|
||||||
|
assertAllowedProperties(assertion.value, assertion.valueName, allowedProperties);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
assertNonEmptyCollection: (assertion) => {
|
||||||
|
assertDefined(assertion.value, assertion.valueName);
|
||||||
|
assertArray(assertion.value, assertion.valueName);
|
||||||
|
assertNonEmpty(assertion.value, assertion.valueName);
|
||||||
|
},
|
||||||
|
assertNonEmptyString: (assertion) => {
|
||||||
|
assertDefined(assertion.value, assertion.valueName);
|
||||||
|
assertString(assertion.value, assertion.valueName);
|
||||||
|
if (assertion.value.length === 0) {
|
||||||
|
throw new Error(`'${assertion.valueName}' is missing.`);
|
||||||
|
}
|
||||||
|
if (assertion.rule) {
|
||||||
|
if (!assertion.value.match(assertion.rule.expectedMatch)) {
|
||||||
|
throw new Error(assertion.rule.errorMessage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertDefined<T>(
|
||||||
|
value: T,
|
||||||
|
valueName: string,
|
||||||
|
): asserts value is NonNullable<T> {
|
||||||
|
if (isNullOrUndefined(value)) {
|
||||||
|
throw new Error(`'${valueName}' is missing.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertPlainObject(
|
||||||
|
value: unknown,
|
||||||
|
valueName: string,
|
||||||
|
): asserts value is object {
|
||||||
|
if (!isPlainObject(value)) {
|
||||||
|
throw new Error(`'${valueName}' is not an object.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertNoEmptyProperties(
|
||||||
|
value: object,
|
||||||
|
valueName: string,
|
||||||
|
): void {
|
||||||
|
if (Object.keys(value).length === 0) {
|
||||||
|
throw new Error(`'${valueName}' is an empty object without properties.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertAllowedProperties(
|
||||||
|
value: object,
|
||||||
|
valueName: string,
|
||||||
|
allowedProperties: readonly string[],
|
||||||
|
): void {
|
||||||
|
const properties = Object.keys(value).map((p) => p as string);
|
||||||
|
const disallowedProperties = properties.filter(
|
||||||
|
(prop) => !allowedProperties.map((p) => p as string).includes(prop),
|
||||||
|
);
|
||||||
|
if (disallowedProperties.length > 0) {
|
||||||
|
throw new Error(`'${valueName}' has disallowed properties: ${disallowedProperties.join(', ')}.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertArray(
|
||||||
|
value: unknown,
|
||||||
|
valueName: string,
|
||||||
|
): asserts value is Array<unknown> {
|
||||||
|
if (!isArray(value)) {
|
||||||
|
throw new Error(`${valueName} should be of type 'array', but is of type '${typeof value}'.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertString(
|
||||||
|
value: unknown,
|
||||||
|
valueName: string,
|
||||||
|
): asserts value is string {
|
||||||
|
if (!isString(value)) {
|
||||||
|
throw new Error(`${valueName} should be of type 'string', but is of type '${typeof value}'.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertNonEmpty(
|
||||||
|
value: Array<unknown>,
|
||||||
|
valueName: string,
|
||||||
|
): void {
|
||||||
|
if (value.length === 0) {
|
||||||
|
throw new Error(`'${valueName}' cannot be an empty array.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import type { FunctionData } from '@/application/collections/';
|
||||||
|
import type { ScriptingLanguage } from '@/domain/ScriptingLanguage';
|
||||||
|
import { createScriptCompiler, type ScriptCompilerFactory } from './Script/Compiler/ScriptCompilerFactory';
|
||||||
|
import type { ScriptCompiler } from './Script/Compiler/ScriptCompiler';
|
||||||
|
|
||||||
|
export interface CategoryCollectionContext {
|
||||||
|
readonly compiler: ScriptCompiler;
|
||||||
|
readonly language: ScriptingLanguage;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CategoryCollectionContextFactory {
|
||||||
|
(
|
||||||
|
functionsData: ReadonlyArray<FunctionData> | undefined,
|
||||||
|
language: ScriptingLanguage,
|
||||||
|
compilerFactory?: ScriptCompilerFactory,
|
||||||
|
): CategoryCollectionContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const createCategoryCollectionContext: CategoryCollectionContextFactory = (
|
||||||
|
functionsData: ReadonlyArray<FunctionData> | undefined,
|
||||||
|
language: ScriptingLanguage,
|
||||||
|
compilerFactory: ScriptCompilerFactory = createScriptCompiler,
|
||||||
|
) => {
|
||||||
|
return {
|
||||||
|
compiler: compilerFactory({
|
||||||
|
categoryContext: {
|
||||||
|
functions: functionsData ?? [],
|
||||||
|
language,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
language,
|
||||||
|
};
|
||||||
|
};
|
||||||
181
src/application/Parser/Executable/CategoryParser.ts
Normal file
181
src/application/Parser/Executable/CategoryParser.ts
Normal file
@@ -0,0 +1,181 @@
|
|||||||
|
import type {
|
||||||
|
CategoryData, ScriptData, ExecutableData,
|
||||||
|
} from '@/application/collections/';
|
||||||
|
import { wrapErrorWithAdditionalContext, type ErrorWithContextWrapper } from '@/application/Parser/Common/ContextualError';
|
||||||
|
import type { Category } from '@/domain/Executables/Category/Category';
|
||||||
|
import type { Script } from '@/domain/Executables/Script/Script';
|
||||||
|
import { createCategory, type CategoryFactory } from '@/domain/Executables/Category/CategoryFactory';
|
||||||
|
import { parseDocs, type DocsParser } from './DocumentationParser';
|
||||||
|
import { parseScript, type ScriptParser } from './Script/ScriptParser';
|
||||||
|
import { createExecutableDataValidator, type ExecutableValidator, type ExecutableValidatorFactory } from './Validation/ExecutableValidator';
|
||||||
|
import { ExecutableType } from './Validation/ExecutableType';
|
||||||
|
import type { CategoryCollectionContext } from './CategoryCollectionContext';
|
||||||
|
|
||||||
|
export const parseCategory: CategoryParser = (
|
||||||
|
category: CategoryData,
|
||||||
|
collectionContext: CategoryCollectionContext,
|
||||||
|
categoryUtilities: CategoryParserUtilities = DefaultCategoryParserUtilities,
|
||||||
|
) => {
|
||||||
|
return parseCategoryRecursively({
|
||||||
|
categoryData: category,
|
||||||
|
collectionContext,
|
||||||
|
categoryUtilities,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface CategoryParser {
|
||||||
|
(
|
||||||
|
category: CategoryData,
|
||||||
|
collectionContext: CategoryCollectionContext,
|
||||||
|
categoryUtilities?: CategoryParserUtilities,
|
||||||
|
): Category;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CategoryParseContext {
|
||||||
|
readonly categoryData: CategoryData;
|
||||||
|
readonly collectionContext: CategoryCollectionContext;
|
||||||
|
readonly parentCategory?: CategoryData;
|
||||||
|
readonly categoryUtilities: CategoryParserUtilities;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseCategoryRecursively(
|
||||||
|
context: CategoryParseContext,
|
||||||
|
): Category | never {
|
||||||
|
const validator = ensureValidCategory(context);
|
||||||
|
const children: CategoryChildren = {
|
||||||
|
subcategories: new Array<Category>(),
|
||||||
|
subscripts: new Array<Script>(),
|
||||||
|
};
|
||||||
|
for (const data of context.categoryData.children) {
|
||||||
|
parseUnknownExecutable({
|
||||||
|
data,
|
||||||
|
children,
|
||||||
|
parent: context.categoryData,
|
||||||
|
categoryUtilities: context.categoryUtilities,
|
||||||
|
collectionContext: context.collectionContext,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return context.categoryUtilities.createCategory({
|
||||||
|
executableId: context.categoryData.category, // Pseudo-ID for uniqueness until real ID support
|
||||||
|
name: context.categoryData.category,
|
||||||
|
docs: context.categoryUtilities.parseDocs(context.categoryData),
|
||||||
|
subcategories: children.subcategories,
|
||||||
|
scripts: children.subscripts,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
throw context.categoryUtilities.wrapError(
|
||||||
|
error,
|
||||||
|
validator.createContextualErrorMessage('Failed to parse category.'),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureValidCategory(
|
||||||
|
context: CategoryParseContext,
|
||||||
|
): ExecutableValidator {
|
||||||
|
const category = context.categoryData;
|
||||||
|
const validator: ExecutableValidator = context.categoryUtilities.createValidator({
|
||||||
|
type: ExecutableType.Category,
|
||||||
|
self: context.categoryData,
|
||||||
|
parentCategory: context.parentCategory,
|
||||||
|
});
|
||||||
|
validator.assertType((v) => v.assertObject({
|
||||||
|
value: category,
|
||||||
|
valueName: category.category ? `Category '${category.category}'` : 'Category',
|
||||||
|
allowedProperties: [
|
||||||
|
'docs', 'children', 'category',
|
||||||
|
],
|
||||||
|
}));
|
||||||
|
validator.assertValidName(category.category);
|
||||||
|
validator.assertType((v) => v.assertNonEmptyCollection({
|
||||||
|
value: category.children,
|
||||||
|
valueName: category.category,
|
||||||
|
}));
|
||||||
|
return validator;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CategoryChildren {
|
||||||
|
readonly subcategories: Category[];
|
||||||
|
readonly subscripts: Script[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ExecutableParseContext {
|
||||||
|
readonly data: ExecutableData;
|
||||||
|
readonly children: CategoryChildren;
|
||||||
|
readonly parent: CategoryData;
|
||||||
|
readonly collectionContext: CategoryCollectionContext;
|
||||||
|
readonly categoryUtilities: CategoryParserUtilities;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseUnknownExecutable(context: ExecutableParseContext) {
|
||||||
|
const validator: ExecutableValidator = context.categoryUtilities.createValidator({
|
||||||
|
self: context.data,
|
||||||
|
parentCategory: context.parent,
|
||||||
|
});
|
||||||
|
validator.assertType((v) => v.assertObject({
|
||||||
|
value: context.data,
|
||||||
|
valueName: 'Executable',
|
||||||
|
}));
|
||||||
|
validator.assert(
|
||||||
|
() => isCategory(context.data) || isScript(context.data),
|
||||||
|
'Executable is neither a category or a script.',
|
||||||
|
);
|
||||||
|
if (isCategory(context.data)) {
|
||||||
|
const subCategory = parseCategoryRecursively({
|
||||||
|
categoryData: context.data,
|
||||||
|
collectionContext: context.collectionContext,
|
||||||
|
parentCategory: context.parent,
|
||||||
|
categoryUtilities: context.categoryUtilities,
|
||||||
|
});
|
||||||
|
context.children.subcategories.push(subCategory);
|
||||||
|
} else { // A script
|
||||||
|
const script = context.categoryUtilities.parseScript(context.data, context.collectionContext);
|
||||||
|
context.children.subscripts.push(script);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isScript(data: ExecutableData): data is ScriptData {
|
||||||
|
return hasCode(data) || hasCall(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isCategory(data: ExecutableData): data is CategoryData {
|
||||||
|
return hasProperty(data, 'category');
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasCode(data: unknown): boolean {
|
||||||
|
return hasProperty(data, 'code');
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasCall(data: unknown) {
|
||||||
|
return hasProperty(data, 'call');
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasProperty(
|
||||||
|
object: unknown,
|
||||||
|
propertyName: string,
|
||||||
|
): object is NonNullable<object> {
|
||||||
|
if (typeof object !== 'object') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (object === null) { // `typeof object` is `null`
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return Object.prototype.hasOwnProperty.call(object, propertyName);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CategoryParserUtilities {
|
||||||
|
readonly createCategory: CategoryFactory;
|
||||||
|
readonly wrapError: ErrorWithContextWrapper;
|
||||||
|
readonly createValidator: ExecutableValidatorFactory;
|
||||||
|
readonly parseScript: ScriptParser;
|
||||||
|
readonly parseDocs: DocsParser;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DefaultCategoryParserUtilities: CategoryParserUtilities = {
|
||||||
|
createCategory,
|
||||||
|
wrapError: wrapErrorWithAdditionalContext,
|
||||||
|
createValidator: createExecutableDataValidator,
|
||||||
|
parseScript,
|
||||||
|
parseDocs,
|
||||||
|
};
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import type { DocumentableData, DocumentationData } from '@/application/collections/';
|
import type { DocumentableData, DocumentationData } from '@/application/collections/';
|
||||||
import { isString, isArray } from '@/TypeHelpers';
|
import { isString, isArray } from '@/TypeHelpers';
|
||||||
|
|
||||||
export function parseDocs(documentable: DocumentableData): readonly string[] {
|
export const parseDocs: DocsParser = (documentable) => {
|
||||||
const { docs } = documentable;
|
const { docs } = documentable;
|
||||||
if (!docs) {
|
if (!docs) {
|
||||||
return [];
|
return [];
|
||||||
@@ -9,6 +9,12 @@ export function parseDocs(documentable: DocumentableData): readonly string[] {
|
|||||||
let result = new DocumentationContainer();
|
let result = new DocumentationContainer();
|
||||||
result = addDocs(docs, result);
|
result = addDocs(docs, result);
|
||||||
return result.getAll();
|
return result.getAll();
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface DocsParser {
|
||||||
|
(
|
||||||
|
documentable: DocumentableData,
|
||||||
|
): readonly string[];
|
||||||
}
|
}
|
||||||
|
|
||||||
function addDocs(
|
function addDocs(
|
||||||
@@ -44,5 +50,5 @@ class DocumentationContainer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function throwInvalidType(): never {
|
function throwInvalidType(): never {
|
||||||
throw new Error('docs field (documentation) must be an array of strings');
|
throw new Error('docs field (documentation) must be a single string or an array of strings.');
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { FunctionParameterCollection } from '@/application/Parser/Script/Compiler/Function/Parameter/FunctionParameterCollection';
|
import { FunctionParameterCollection } from '@/application/Parser/Executable/Script/Compiler/Function/Parameter/FunctionParameterCollection';
|
||||||
import { FunctionCallArgumentCollection } from '../../Function/Call/Argument/FunctionCallArgumentCollection';
|
import { FunctionCallArgumentCollection } from '../../Function/Call/Argument/FunctionCallArgumentCollection';
|
||||||
import { ExpressionEvaluationContext, type IExpressionEvaluationContext } from './ExpressionEvaluationContext';
|
import { ExpressionEvaluationContext, type IExpressionEvaluationContext } from './ExpressionEvaluationContext';
|
||||||
import { ExpressionPosition } from './ExpressionPosition';
|
import { ExpressionPosition } from './ExpressionPosition';
|
||||||
@@ -7,15 +7,18 @@ import type { IReadOnlyFunctionParameterCollection } from '../../Function/Parame
|
|||||||
import type { IExpression } from './IExpression';
|
import type { IExpression } from './IExpression';
|
||||||
|
|
||||||
export type ExpressionEvaluator = (context: IExpressionEvaluationContext) => string;
|
export type ExpressionEvaluator = (context: IExpressionEvaluationContext) => string;
|
||||||
|
|
||||||
export class Expression implements IExpression {
|
export class Expression implements IExpression {
|
||||||
public readonly parameters: IReadOnlyFunctionParameterCollection;
|
public readonly parameters: IReadOnlyFunctionParameterCollection;
|
||||||
|
|
||||||
constructor(
|
public readonly position: ExpressionPosition;
|
||||||
public readonly position: ExpressionPosition,
|
|
||||||
public readonly evaluator: ExpressionEvaluator,
|
public readonly evaluator: ExpressionEvaluator;
|
||||||
parameters?: IReadOnlyFunctionParameterCollection,
|
|
||||||
) {
|
constructor(parameters: ExpressionInitParameters) {
|
||||||
this.parameters = parameters ?? new FunctionParameterCollection();
|
this.parameters = parameters.parameters ?? new FunctionParameterCollection();
|
||||||
|
this.evaluator = parameters.evaluator;
|
||||||
|
this.position = parameters.position;
|
||||||
}
|
}
|
||||||
|
|
||||||
public evaluate(context: IExpressionEvaluationContext): string {
|
public evaluate(context: IExpressionEvaluationContext): string {
|
||||||
@@ -26,6 +29,12 @@ export class Expression implements IExpression {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ExpressionInitParameters {
|
||||||
|
readonly position: ExpressionPosition,
|
||||||
|
readonly evaluator: ExpressionEvaluator,
|
||||||
|
readonly parameters?: IReadOnlyFunctionParameterCollection,
|
||||||
|
}
|
||||||
|
|
||||||
function validateThatAllRequiredParametersAreSatisfied(
|
function validateThatAllRequiredParametersAreSatisfied(
|
||||||
parameters: IReadOnlyFunctionParameterCollection,
|
parameters: IReadOnlyFunctionParameterCollection,
|
||||||
args: IReadOnlyFunctionCallArgumentCollection,
|
args: IReadOnlyFunctionCallArgumentCollection,
|
||||||
@@ -1,8 +1,13 @@
|
|||||||
import { ExpressionPosition } from './ExpressionPosition';
|
import { ExpressionPosition } from './ExpressionPosition';
|
||||||
|
|
||||||
export function createPositionFromRegexFullMatch(
|
export interface ExpressionPositionFactory {
|
||||||
match: RegExpMatchArray,
|
(
|
||||||
): ExpressionPosition {
|
match: RegExpMatchArray,
|
||||||
|
): ExpressionPosition
|
||||||
|
}
|
||||||
|
|
||||||
|
export const createPositionFromRegexFullMatch
|
||||||
|
: ExpressionPositionFactory = (match) => {
|
||||||
const startPos = match.index;
|
const startPos = match.index;
|
||||||
if (startPos === undefined) {
|
if (startPos === undefined) {
|
||||||
throw new Error(`Regex match did not yield any results: ${JSON.stringify(match)}`);
|
throw new Error(`Regex match did not yield any results: ${JSON.stringify(match)}`);
|
||||||
@@ -13,4 +18,4 @@ export function createPositionFromRegexFullMatch(
|
|||||||
}
|
}
|
||||||
const endPos = startPos + fullMatch.length;
|
const endPos = startPos + fullMatch.length;
|
||||||
return new ExpressionPosition(startPos, endPos);
|
return new ExpressionPosition(startPos, endPos);
|
||||||
}
|
};
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { type IExpressionEvaluationContext, ExpressionEvaluationContext } from '@/application/Parser/Script/Compiler/Expressions/Expression/ExpressionEvaluationContext';
|
import { type IExpressionEvaluationContext, ExpressionEvaluationContext } from '@/application/Parser/Executable/Script/Compiler/Expressions/Expression/ExpressionEvaluationContext';
|
||||||
import { CompositeExpressionParser } from './Parser/CompositeExpressionParser';
|
import { CompositeExpressionParser } from './Parser/CompositeExpressionParser';
|
||||||
import type { IReadOnlyFunctionCallArgumentCollection } from '../Function/Call/Argument/IFunctionCallArgumentCollection';
|
import type { IReadOnlyFunctionCallArgumentCollection } from '../Function/Call/Argument/IFunctionCallArgumentCollection';
|
||||||
import type { IExpressionsCompiler } from './IExpressionsCompiler';
|
import type { IExpressionsCompiler } from './IExpressionsCompiler';
|
||||||
@@ -3,10 +3,10 @@ import { WithParser } from '../SyntaxParsers/WithParser';
|
|||||||
import type { IExpression } from '../Expression/IExpression';
|
import type { IExpression } from '../Expression/IExpression';
|
||||||
import type { IExpressionParser } from './IExpressionParser';
|
import type { IExpressionParser } from './IExpressionParser';
|
||||||
|
|
||||||
const Parsers = [
|
const Parsers: readonly IExpressionParser[] = [
|
||||||
new ParameterSubstitutionParser(),
|
new ParameterSubstitutionParser(),
|
||||||
new WithParser(),
|
new WithParser(),
|
||||||
];
|
] as const;
|
||||||
|
|
||||||
export class CompositeExpressionParser implements IExpressionParser {
|
export class CompositeExpressionParser implements IExpressionParser {
|
||||||
public constructor(private readonly leafs: readonly IExpressionParser[] = Parsers) {
|
public constructor(private readonly leafs: readonly IExpressionParser[] = Parsers) {
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
import { wrapErrorWithAdditionalContext, type ErrorWithContextWrapper } from '@/application/Parser/Common/ContextualError';
|
||||||
|
import { Expression, type ExpressionEvaluator } from '../../Expression/Expression';
|
||||||
|
import { createPositionFromRegexFullMatch, type ExpressionPositionFactory } from '../../Expression/ExpressionPositionFactory';
|
||||||
|
import { createFunctionParameterCollection, type FunctionParameterCollectionFactory } from '../../../Function/Parameter/FunctionParameterCollectionFactory';
|
||||||
|
import type { IExpressionParser } from '../IExpressionParser';
|
||||||
|
import type { IExpression } from '../../Expression/IExpression';
|
||||||
|
import type { FunctionParameter } from '../../../Function/Parameter/FunctionParameter';
|
||||||
|
import type { IFunctionParameterCollection, IReadOnlyFunctionParameterCollection } from '../../../Function/Parameter/IFunctionParameterCollection';
|
||||||
|
|
||||||
|
export interface RegexParserUtilities {
|
||||||
|
readonly wrapError: ErrorWithContextWrapper;
|
||||||
|
readonly createPosition: ExpressionPositionFactory;
|
||||||
|
readonly createExpression: ExpressionFactory;
|
||||||
|
readonly createParameterCollection: FunctionParameterCollectionFactory;
|
||||||
|
}
|
||||||
|
|
||||||
|
export abstract class RegexParser implements IExpressionParser {
|
||||||
|
protected abstract readonly regex: RegExp;
|
||||||
|
|
||||||
|
public constructor(
|
||||||
|
private readonly utilities: RegexParserUtilities = DefaultRegexParserUtilities,
|
||||||
|
) {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public findExpressions(code: string): IExpression[] {
|
||||||
|
return Array.from(this.findRegexExpressions(code));
|
||||||
|
}
|
||||||
|
|
||||||
|
protected abstract buildExpression(match: RegExpMatchArray): PrimitiveExpression;
|
||||||
|
|
||||||
|
private* findRegexExpressions(code: string): Iterable<IExpression> {
|
||||||
|
if (!code) {
|
||||||
|
throw new Error(
|
||||||
|
this.buildErrorMessageWithContext({ errorMessage: 'missing code', code: 'EMPTY' }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const createErrorContext = (message: string): ErrorContext => ({ code, errorMessage: message });
|
||||||
|
const matches = this.doOrRethrow(
|
||||||
|
() => code.matchAll(this.regex),
|
||||||
|
createErrorContext('Failed to match regex.'),
|
||||||
|
);
|
||||||
|
for (const match of matches) {
|
||||||
|
const primitiveExpression = this.doOrRethrow(
|
||||||
|
() => this.buildExpression(match),
|
||||||
|
createErrorContext('Failed to build expression.'),
|
||||||
|
);
|
||||||
|
const position = this.doOrRethrow(
|
||||||
|
() => this.utilities.createPosition(match),
|
||||||
|
createErrorContext('Failed to create position.'),
|
||||||
|
);
|
||||||
|
const parameters = this.doOrRethrow(
|
||||||
|
() => createParameters(
|
||||||
|
primitiveExpression,
|
||||||
|
this.utilities.createParameterCollection(),
|
||||||
|
),
|
||||||
|
createErrorContext('Failed to create parameters.'),
|
||||||
|
);
|
||||||
|
const expression = this.doOrRethrow(
|
||||||
|
() => this.utilities.createExpression({
|
||||||
|
position,
|
||||||
|
evaluator: primitiveExpression.evaluator,
|
||||||
|
parameters,
|
||||||
|
}),
|
||||||
|
createErrorContext('Failed to create expression.'),
|
||||||
|
);
|
||||||
|
yield expression;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private doOrRethrow<T>(
|
||||||
|
action: () => T,
|
||||||
|
context: ErrorContext,
|
||||||
|
): T {
|
||||||
|
try {
|
||||||
|
return action();
|
||||||
|
} catch (error) {
|
||||||
|
throw this.utilities.wrapError(
|
||||||
|
error,
|
||||||
|
this.buildErrorMessageWithContext(context),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildErrorMessageWithContext(context: ErrorContext): string {
|
||||||
|
return [
|
||||||
|
context.errorMessage,
|
||||||
|
`Class name: ${this.constructor.name}`,
|
||||||
|
`Regex pattern used: ${this.regex}`,
|
||||||
|
`Code: ${context.code}`,
|
||||||
|
].join('\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ErrorContext {
|
||||||
|
readonly errorMessage: string,
|
||||||
|
readonly code: string,
|
||||||
|
}
|
||||||
|
|
||||||
|
function createParameters(
|
||||||
|
expression: PrimitiveExpression,
|
||||||
|
parameterCollection: IFunctionParameterCollection,
|
||||||
|
): IReadOnlyFunctionParameterCollection {
|
||||||
|
return (expression.parameters || [])
|
||||||
|
.reduce((parameters, parameter) => {
|
||||||
|
parameters.addParameter(parameter);
|
||||||
|
return parameters;
|
||||||
|
}, parameterCollection);
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PrimitiveExpression {
|
||||||
|
readonly evaluator: ExpressionEvaluator;
|
||||||
|
readonly parameters?: readonly FunctionParameter[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ExpressionFactory {
|
||||||
|
(
|
||||||
|
...args: ConstructorParameters<typeof Expression>
|
||||||
|
): IExpression;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DefaultRegexParserUtilities: RegexParserUtilities = {
|
||||||
|
wrapError: wrapErrorWithAdditionalContext,
|
||||||
|
createPosition: createPositionFromRegexFullMatch,
|
||||||
|
createExpression: (...args) => new Expression(...args),
|
||||||
|
createParameterCollection: createFunctionParameterCollection,
|
||||||
|
};
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
export interface IPipe {
|
export interface Pipe {
|
||||||
readonly name: string;
|
readonly name: string;
|
||||||
apply(input: string): string;
|
apply(input: string): string;
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
import type { IPipe } from '../IPipe';
|
import type { Pipe } from '../Pipe';
|
||||||
|
|
||||||
export class EscapeDoubleQuotes implements IPipe {
|
export class EscapeDoubleQuotes implements Pipe {
|
||||||
public readonly name: string = 'escapeDoubleQuotes';
|
public readonly name: string = 'escapeDoubleQuotes';
|
||||||
|
|
||||||
public apply(raw: string): string {
|
public apply(raw: string): string {
|
||||||
if (!raw) {
|
if (!raw) {
|
||||||
return raw;
|
return '';
|
||||||
}
|
}
|
||||||
return raw.replaceAll('"', '"^""');
|
return raw.replaceAll('"', '"^""');
|
||||||
/* eslint-disable vue/max-len */
|
/* eslint-disable vue/max-len */
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { IPipe } from '../IPipe';
|
import { splitTextIntoLines } from '@/application/Common/Text/SplitTextIntoLines';
|
||||||
|
import type { Pipe } from '../Pipe';
|
||||||
|
|
||||||
export class InlinePowerShell implements IPipe {
|
export class InlinePowerShell implements Pipe {
|
||||||
public readonly name: string = 'inlinePowerShell';
|
public readonly name: string = 'inlinePowerShell';
|
||||||
|
|
||||||
public apply(code: string): string {
|
public apply(code: string): string {
|
||||||
@@ -8,9 +9,11 @@ export class InlinePowerShell implements IPipe {
|
|||||||
return code;
|
return code;
|
||||||
}
|
}
|
||||||
const processor = new Array<(data: string) => string>(...[ // for broken ESlint "indent"
|
const processor = new Array<(data: string) => string>(...[ // for broken ESlint "indent"
|
||||||
|
// Order is important
|
||||||
inlineComments,
|
inlineComments,
|
||||||
mergeLinesWithBacktick,
|
|
||||||
mergeHereStrings,
|
mergeHereStrings,
|
||||||
|
mergeLinesWithBacktick,
|
||||||
|
mergeLinesWithBracketCodeBlocks,
|
||||||
mergeNewLines,
|
mergeNewLines,
|
||||||
]).reduce((a, b) => (data) => b(a(data)));
|
]).reduce((a, b) => (data) => b(a(data)));
|
||||||
const newCode = processor(code);
|
const newCode = processor(code);
|
||||||
@@ -89,10 +92,6 @@ function inlineComments(code: string): string {
|
|||||||
*/
|
*/
|
||||||
}
|
}
|
||||||
|
|
||||||
function getLines(code: string): string[] {
|
|
||||||
return (code?.split(/\r\n|\r|\n/) || []);
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
Merges inline here-strings to a single lined string with Windows line terminator (\r\n)
|
Merges inline here-strings to a single lined string with Windows line terminator (\r\n)
|
||||||
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7.4#here-strings
|
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-7.4#here-strings
|
||||||
@@ -102,18 +101,18 @@ function mergeHereStrings(code: string) {
|
|||||||
return code.replaceAll(regex, (_$, quotes, scope) => {
|
return code.replaceAll(regex, (_$, quotes, scope) => {
|
||||||
const newString = getHereStringHandler(quotes);
|
const newString = getHereStringHandler(quotes);
|
||||||
const escaped = scope.replaceAll(quotes, newString.escapedQuotes);
|
const escaped = scope.replaceAll(quotes, newString.escapedQuotes);
|
||||||
const lines = getLines(escaped);
|
const lines = splitTextIntoLines(escaped);
|
||||||
const inlined = lines.join(newString.separator);
|
const inlined = lines.join(newString.separator);
|
||||||
const quoted = `${newString.quotesAround}${inlined}${newString.quotesAround}`;
|
const quoted = `${newString.quotesAround}${inlined}${newString.quotesAround}`;
|
||||||
return quoted;
|
return quoted;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
interface IInlinedHereString {
|
interface InlinedHereString {
|
||||||
readonly quotesAround: string;
|
readonly quotesAround: string;
|
||||||
readonly escapedQuotes: string;
|
readonly escapedQuotes: string;
|
||||||
readonly separator: string;
|
readonly separator: string;
|
||||||
}
|
}
|
||||||
function getHereStringHandler(quotes: string): IInlinedHereString {
|
function getHereStringHandler(quotes: string): InlinedHereString {
|
||||||
/*
|
/*
|
||||||
We handle @' and @" differently.
|
We handle @' and @" differently.
|
||||||
Single quotes are interpreted literally and doubles are expandable.
|
Single quotes are interpreted literally and doubles are expandable.
|
||||||
@@ -158,9 +157,33 @@ function mergeLinesWithBacktick(code: string) {
|
|||||||
return code.replaceAll(/ +`\s*(?:\r\n|\r|\n)\s*/g, ' ');
|
return code.replaceAll(/ +`\s*(?:\r\n|\r|\n)\s*/g, ' ');
|
||||||
}
|
}
|
||||||
|
|
||||||
function mergeNewLines(code: string) {
|
/**
|
||||||
return getLines(code)
|
* Inlines code blocks in PowerShell scripts while preserving correct syntax.
|
||||||
.map((line) => line.trim())
|
* It removes unnecessary newlines and spaces around brackets,
|
||||||
.filter((line) => line.length > 0)
|
* inlining the code where possible.
|
||||||
.join('; ');
|
* This prevents syntax errors like "Unexpected token '}'" when inlining brackets.
|
||||||
|
*/
|
||||||
|
function mergeLinesWithBracketCodeBlocks(code: string): string {
|
||||||
|
return code
|
||||||
|
// Opening bracket: [whitespace] Opening bracket (newline)
|
||||||
|
.replace(/(?<=.*)\s*{[\r\n][\s\r\n]*/g, ' { ')
|
||||||
|
// Closing bracket: [whitespace] Closing bracket (newline) (continuation keyword)
|
||||||
|
.replace(/\s*}[\r\n][\s\r\n]*(?=elseif|else|catch|finally|until)/g, ' } ')
|
||||||
|
.replace(/(?<=do\s*{.*)[\r\n\s]*}[\r\n][\r\n\s]*(?=while)/g, ' } '); // Do-While
|
||||||
|
}
|
||||||
|
|
||||||
|
function mergeNewLines(code: string) {
|
||||||
|
const nonEmptyLines = splitTextIntoLines(code)
|
||||||
|
.map((line) => line.trim())
|
||||||
|
.filter((line) => line.length > 0);
|
||||||
|
|
||||||
|
return nonEmptyLines
|
||||||
|
.map((line, index) => {
|
||||||
|
const isLastLine = index === nonEmptyLines.length - 1;
|
||||||
|
if (isLastLine) {
|
||||||
|
return line;
|
||||||
|
}
|
||||||
|
return line.endsWith(';') ? line : `${line};`;
|
||||||
|
})
|
||||||
|
.join(' ');
|
||||||
}
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { InlinePowerShell } from './PipeDefinitions/InlinePowerShell';
|
import { InlinePowerShell } from './PipeDefinitions/InlinePowerShell';
|
||||||
import { EscapeDoubleQuotes } from './PipeDefinitions/EscapeDoubleQuotes';
|
import { EscapeDoubleQuotes } from './PipeDefinitions/EscapeDoubleQuotes';
|
||||||
import type { IPipe } from './IPipe';
|
import type { Pipe } from './Pipe';
|
||||||
|
|
||||||
const RegisteredPipes = [
|
const RegisteredPipes = [
|
||||||
new EscapeDoubleQuotes(),
|
new EscapeDoubleQuotes(),
|
||||||
@@ -8,19 +8,19 @@ const RegisteredPipes = [
|
|||||||
];
|
];
|
||||||
|
|
||||||
export interface IPipeFactory {
|
export interface IPipeFactory {
|
||||||
get(pipeName: string): IPipe;
|
get(pipeName: string): Pipe;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class PipeFactory implements IPipeFactory {
|
export class PipeFactory implements IPipeFactory {
|
||||||
private readonly pipes = new Map<string, IPipe>();
|
private readonly pipes = new Map<string, Pipe>();
|
||||||
|
|
||||||
constructor(pipes: readonly IPipe[] = RegisteredPipes) {
|
constructor(pipes: readonly Pipe[] = RegisteredPipes) {
|
||||||
for (const pipe of pipes) {
|
for (const pipe of pipes) {
|
||||||
this.registerPipe(pipe);
|
this.registerPipe(pipe);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public get(pipeName: string): IPipe {
|
public get(pipeName: string): Pipe {
|
||||||
validatePipeName(pipeName);
|
validatePipeName(pipeName);
|
||||||
const pipe = this.pipes.get(pipeName);
|
const pipe = this.pipes.get(pipeName);
|
||||||
if (!pipe) {
|
if (!pipe) {
|
||||||
@@ -29,7 +29,7 @@ export class PipeFactory implements IPipeFactory {
|
|||||||
return pipe;
|
return pipe;
|
||||||
}
|
}
|
||||||
|
|
||||||
private registerPipe(pipe: IPipe): void {
|
private registerPipe(pipe: Pipe): void {
|
||||||
validatePipeName(pipe.name);
|
validatePipeName(pipe.name);
|
||||||
if (this.pipes.has(pipe.name)) {
|
if (this.pipes.has(pipe.name)) {
|
||||||
throw new Error(`Pipe name must be unique: "${pipe.name}"`);
|
throw new Error(`Pipe name must be unique: "${pipe.name}"`);
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
import { FunctionParameter } from '@/application/Parser/Script/Compiler/Function/Parameter/FunctionParameter';
|
import { RegexParser, type PrimitiveExpression } from '../Parser/Regex/RegexParser';
|
||||||
import { RegexParser, type IPrimitiveExpression } from '../Parser/Regex/RegexParser';
|
|
||||||
import { ExpressionRegexBuilder } from '../Parser/Regex/ExpressionRegexBuilder';
|
import { ExpressionRegexBuilder } from '../Parser/Regex/ExpressionRegexBuilder';
|
||||||
|
|
||||||
export class ParameterSubstitutionParser extends RegexParser {
|
export class ParameterSubstitutionParser extends RegexParser {
|
||||||
@@ -12,11 +11,14 @@ export class ParameterSubstitutionParser extends RegexParser {
|
|||||||
.expectExpressionEnd()
|
.expectExpressionEnd()
|
||||||
.buildRegExp();
|
.buildRegExp();
|
||||||
|
|
||||||
protected buildExpression(match: RegExpMatchArray): IPrimitiveExpression {
|
protected buildExpression(match: RegExpMatchArray): PrimitiveExpression {
|
||||||
const parameterName = match[1];
|
const parameterName = match[1];
|
||||||
const pipeline = match[2];
|
const pipeline = match[2];
|
||||||
return {
|
return {
|
||||||
parameters: [new FunctionParameter(parameterName, false)],
|
parameters: [{
|
||||||
|
name: parameterName,
|
||||||
|
isOptional: false,
|
||||||
|
}],
|
||||||
evaluator: (context) => {
|
evaluator: (context) => {
|
||||||
const { argumentValue } = context.args.getArgument(parameterName);
|
const { argumentValue } = context.args.getArgument(parameterName);
|
||||||
if (!pipeline) {
|
if (!pipeline) {
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
// eslint-disable-next-line max-classes-per-file
|
// eslint-disable-next-line max-classes-per-file
|
||||||
import type { IExpressionParser } from '@/application/Parser/Script/Compiler/Expressions/Parser/IExpressionParser';
|
import type { IExpressionParser } from '@/application/Parser/Executable/Script/Compiler/Expressions/Parser/IExpressionParser';
|
||||||
import { FunctionParameterCollection } from '@/application/Parser/Script/Compiler/Function/Parameter/FunctionParameterCollection';
|
import { FunctionParameterCollection } from '@/application/Parser/Executable/Script/Compiler/Function/Parameter/FunctionParameterCollection';
|
||||||
import { FunctionParameter } from '@/application/Parser/Script/Compiler/Function/Parameter/FunctionParameter';
|
|
||||||
import { ExpressionPosition } from '../Expression/ExpressionPosition';
|
import { ExpressionPosition } from '../Expression/ExpressionPosition';
|
||||||
import { ExpressionRegexBuilder } from '../Parser/Regex/ExpressionRegexBuilder';
|
import { ExpressionRegexBuilder } from '../Parser/Regex/ExpressionRegexBuilder';
|
||||||
import { createPositionFromRegexFullMatch } from '../Expression/ExpressionPositionFactory';
|
import { createPositionFromRegexFullMatch } from '../Expression/ExpressionPositionFactory';
|
||||||
@@ -84,7 +83,10 @@ class WithStatementBuilder {
|
|||||||
|
|
||||||
public buildExpression(endExpressionPosition: ExpressionPosition, input: string): IExpression {
|
public buildExpression(endExpressionPosition: ExpressionPosition, input: string): IExpression {
|
||||||
const parameters = new FunctionParameterCollection();
|
const parameters = new FunctionParameterCollection();
|
||||||
parameters.addParameter(new FunctionParameter(this.parameterName, true));
|
parameters.addParameter({
|
||||||
|
name: this.parameterName,
|
||||||
|
isOptional: true,
|
||||||
|
});
|
||||||
const position = new ExpressionPosition(
|
const position = new ExpressionPosition(
|
||||||
this.startExpressionPosition.start,
|
this.startExpressionPosition.start,
|
||||||
endExpressionPosition.end,
|
endExpressionPosition.end,
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import { createTypeValidator, type TypeValidator } from '@/application/Parser/Common/TypeValidator';
|
||||||
|
import { validateParameterName, type ParameterNameValidator } from '@/application/Parser/Executable/Script/Compiler/Function/Shared/ParameterNameValidator';
|
||||||
|
|
||||||
|
export interface FunctionCallArgument {
|
||||||
|
readonly parameterName: string;
|
||||||
|
readonly argumentValue: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FunctionCallArgumentFactory {
|
||||||
|
(
|
||||||
|
parameterName: string,
|
||||||
|
argumentValue: string,
|
||||||
|
utilities?: FunctionCallArgumentFactoryUtilities,
|
||||||
|
): FunctionCallArgument;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const createFunctionCallArgument: FunctionCallArgumentFactory = (
|
||||||
|
parameterName: string,
|
||||||
|
argumentValue: string,
|
||||||
|
utilities: FunctionCallArgumentFactoryUtilities = DefaultUtilities,
|
||||||
|
): FunctionCallArgument => {
|
||||||
|
utilities.validateParameterName(parameterName);
|
||||||
|
utilities.typeValidator.assertNonEmptyString({
|
||||||
|
value: argumentValue,
|
||||||
|
valueName: `Function parameter '${parameterName}'`,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
parameterName,
|
||||||
|
argumentValue,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
interface FunctionCallArgumentFactoryUtilities {
|
||||||
|
readonly typeValidator: TypeValidator;
|
||||||
|
readonly validateParameterName: ParameterNameValidator;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DefaultUtilities: FunctionCallArgumentFactoryUtilities = {
|
||||||
|
typeValidator: createTypeValidator(),
|
||||||
|
validateParameterName,
|
||||||
|
};
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
import type { IFunctionCallArgument } from './IFunctionCallArgument';
|
import type { FunctionCallArgument } from './FunctionCallArgument';
|
||||||
import type { IFunctionCallArgumentCollection } from './IFunctionCallArgumentCollection';
|
import type { IFunctionCallArgumentCollection } from './IFunctionCallArgumentCollection';
|
||||||
|
|
||||||
export class FunctionCallArgumentCollection implements IFunctionCallArgumentCollection {
|
export class FunctionCallArgumentCollection implements IFunctionCallArgumentCollection {
|
||||||
private readonly arguments = new Map<string, IFunctionCallArgument>();
|
private readonly arguments = new Map<string, FunctionCallArgument>();
|
||||||
|
|
||||||
public addArgument(argument: IFunctionCallArgument): void {
|
public addArgument(argument: FunctionCallArgument): void {
|
||||||
if (this.hasArgument(argument.parameterName)) {
|
if (this.hasArgument(argument.parameterName)) {
|
||||||
throw new Error(`argument value for parameter ${argument.parameterName} is already provided`);
|
throw new Error(`argument value for parameter ${argument.parameterName} is already provided`);
|
||||||
}
|
}
|
||||||
@@ -22,7 +22,7 @@ export class FunctionCallArgumentCollection implements IFunctionCallArgumentColl
|
|||||||
return this.arguments.has(parameterName);
|
return this.arguments.has(parameterName);
|
||||||
}
|
}
|
||||||
|
|
||||||
public getArgument(parameterName: string): IFunctionCallArgument {
|
public getArgument(parameterName: string): FunctionCallArgument {
|
||||||
if (!parameterName) {
|
if (!parameterName) {
|
||||||
throw new Error('missing parameter name');
|
throw new Error('missing parameter name');
|
||||||
}
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
import type { IFunctionCallArgument } from './IFunctionCallArgument';
|
import type { FunctionCallArgument } from './FunctionCallArgument';
|
||||||
|
|
||||||
export interface IReadOnlyFunctionCallArgumentCollection {
|
export interface IReadOnlyFunctionCallArgumentCollection {
|
||||||
getArgument(parameterName: string): IFunctionCallArgument;
|
getArgument(parameterName: string): FunctionCallArgument;
|
||||||
getAllParameterNames(): string[];
|
getAllParameterNames(): string[];
|
||||||
hasArgument(parameterName: string): boolean;
|
hasArgument(parameterName: string): boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IFunctionCallArgumentCollection extends IReadOnlyFunctionCallArgumentCollection {
|
export interface IFunctionCallArgumentCollection extends IReadOnlyFunctionCallArgumentCollection {
|
||||||
addArgument(argument: IFunctionCallArgument): void;
|
addArgument(argument: FunctionCallArgument): void;
|
||||||
}
|
}
|
||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { filterEmptyStrings } from '@/application/Common/Text/FilterEmptyStrings';
|
||||||
import type { CompiledCode } from '../CompiledCode';
|
import type { CompiledCode } from '../CompiledCode';
|
||||||
import type { CodeSegmentMerger } from './CodeSegmentMerger';
|
import type { CodeSegmentMerger } from './CodeSegmentMerger';
|
||||||
|
|
||||||
@@ -8,11 +9,9 @@ export class NewlineCodeSegmentMerger implements CodeSegmentMerger {
|
|||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
code: joinCodeParts(codeSegments.map((f) => f.code)),
|
code: joinCodeParts(codeSegments.map((f) => f.code)),
|
||||||
revertCode: joinCodeParts(
|
revertCode: joinCodeParts(filterEmptyStrings(
|
||||||
codeSegments
|
codeSegments.map((f) => f.revertCode),
|
||||||
.map((f) => f.revertCode)
|
)),
|
||||||
.filter((code): code is string => Boolean(code)),
|
|
||||||
),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { ISharedFunctionCollection } from '@/application/Parser/Script/Compiler/Function/ISharedFunctionCollection';
|
import type { ISharedFunctionCollection } from '@/application/Parser/Executable/Script/Compiler/Function/ISharedFunctionCollection';
|
||||||
import type { FunctionCall } from '../FunctionCall';
|
import type { FunctionCall } from '../FunctionCall';
|
||||||
import type { SingleCallCompiler } from './SingleCall/SingleCallCompiler';
|
import type { SingleCallCompiler } from './SingleCall/SingleCallCompiler';
|
||||||
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { ISharedFunctionCollection } from '@/application/Parser/Script/Compiler/Function/ISharedFunctionCollection';
|
import type { ISharedFunctionCollection } from '@/application/Parser/Executable/Script/Compiler/Function/ISharedFunctionCollection';
|
||||||
import type { CompiledCode } from './CompiledCode';
|
import type { CompiledCode } from './CompiledCode';
|
||||||
import type { FunctionCall } from '../FunctionCall';
|
import type { FunctionCall } from '../FunctionCall';
|
||||||
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { FunctionCall } from '@/application/Parser/Script/Compiler/Function/Call/FunctionCall';
|
import type { FunctionCall } from '@/application/Parser/Executable/Script/Compiler/Function/Call/FunctionCall';
|
||||||
import { NewlineCodeSegmentMerger } from './CodeSegmentJoin/NewlineCodeSegmentMerger';
|
import { NewlineCodeSegmentMerger } from './CodeSegmentJoin/NewlineCodeSegmentMerger';
|
||||||
import { AdaptiveFunctionCallCompiler } from './SingleCall/AdaptiveFunctionCallCompiler';
|
import { AdaptiveFunctionCallCompiler } from './SingleCall/AdaptiveFunctionCallCompiler';
|
||||||
import type { ISharedFunctionCollection } from '../../ISharedFunctionCollection';
|
import type { ISharedFunctionCollection } from '../../ISharedFunctionCollection';
|
||||||
@@ -72,7 +72,7 @@ function throwIfUnexpectedParametersExist(
|
|||||||
// eslint-disable-next-line prefer-template
|
// eslint-disable-next-line prefer-template
|
||||||
`Function "${functionName}" has unexpected parameter(s) provided: `
|
`Function "${functionName}" has unexpected parameter(s) provided: `
|
||||||
+ `"${unexpectedParameters.join('", "')}"`
|
+ `"${unexpectedParameters.join('", "')}"`
|
||||||
+ '. Expected parameter(s): '
|
+ '.\nExpected parameter(s): '
|
||||||
+ (expectedParameters.length ? `"${expectedParameters.join('", "')}"` : 'none'),
|
+ (expectedParameters.length ? `"${expectedParameters.join('", "')}".` : 'none'),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { ISharedFunction } from '@/application/Parser/Script/Compiler/Function/ISharedFunction';
|
import type { ISharedFunction } from '@/application/Parser/Executable/Script/Compiler/Function/ISharedFunction';
|
||||||
import type { FunctionCall } from '@/application/Parser/Script/Compiler/Function/Call/FunctionCall';
|
import type { FunctionCall } from '@/application/Parser/Executable/Script/Compiler/Function/Call/FunctionCall';
|
||||||
import type { CompiledCode } from '../CompiledCode';
|
import type { CompiledCode } from '../CompiledCode';
|
||||||
import type { FunctionCallCompilationContext } from '../FunctionCallCompilationContext';
|
import type { FunctionCallCompilationContext } from '../FunctionCallCompilationContext';
|
||||||
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { FunctionCall } from '@/application/Parser/Script/Compiler/Function/Call/FunctionCall';
|
import type { FunctionCall } from '@/application/Parser/Executable/Script/Compiler/Function/Call/FunctionCall';
|
||||||
import type { FunctionCallCompilationContext } from '@/application/Parser/Script/Compiler/Function/Call/Compiler/FunctionCallCompilationContext';
|
import type { FunctionCallCompilationContext } from '@/application/Parser/Executable/Script/Compiler/Function/Call/Compiler/FunctionCallCompilationContext';
|
||||||
|
|
||||||
export interface ArgumentCompiler {
|
export interface ArgumentCompiler {
|
||||||
createCompiledNestedCall(
|
createCompiledNestedCall(
|
||||||
@@ -1,17 +1,16 @@
|
|||||||
import type { IReadOnlyFunctionCallArgumentCollection } from '@/application/Parser/Script/Compiler/Function/Call/Argument/IFunctionCallArgumentCollection';
|
import type { IReadOnlyFunctionCallArgumentCollection } from '@/application/Parser/Executable/Script/Compiler/Function/Call/Argument/IFunctionCallArgumentCollection';
|
||||||
import { FunctionCallArgument } from '@/application/Parser/Script/Compiler/Function/Call/Argument/FunctionCallArgument';
|
import { FunctionCallArgumentCollection } from '@/application/Parser/Executable/Script/Compiler/Function/Call/Argument/FunctionCallArgumentCollection';
|
||||||
import { FunctionCallArgumentCollection } from '@/application/Parser/Script/Compiler/Function/Call/Argument/FunctionCallArgumentCollection';
|
import { ExpressionsCompiler } from '@/application/Parser/Executable/Script/Compiler/Expressions/ExpressionsCompiler';
|
||||||
import { ExpressionsCompiler } from '@/application/Parser/Script/Compiler/Expressions/ExpressionsCompiler';
|
import type { IExpressionsCompiler } from '@/application/Parser/Executable/Script/Compiler/Expressions/IExpressionsCompiler';
|
||||||
import type { IExpressionsCompiler } from '@/application/Parser/Script/Compiler/Expressions/IExpressionsCompiler';
|
import type { FunctionCall } from '@/application/Parser/Executable/Script/Compiler/Function/Call/FunctionCall';
|
||||||
import type { FunctionCall } from '@/application/Parser/Script/Compiler/Function/Call/FunctionCall';
|
import type { FunctionCallCompilationContext } from '@/application/Parser/Executable/Script/Compiler/Function/Call/Compiler/FunctionCallCompilationContext';
|
||||||
import type { FunctionCallCompilationContext } from '@/application/Parser/Script/Compiler/Function/Call/Compiler/FunctionCallCompilationContext';
|
import { ParsedFunctionCall } from '@/application/Parser/Executable/Script/Compiler/Function/Call/ParsedFunctionCall';
|
||||||
import { ParsedFunctionCall } from '@/application/Parser/Script/Compiler/Function/Call/ParsedFunctionCall';
|
import { wrapErrorWithAdditionalContext, type ErrorWithContextWrapper } from '@/application/Parser/Common/ContextualError';
|
||||||
|
import { createFunctionCallArgument, type FunctionCallArgument, type FunctionCallArgumentFactory } from '@/application/Parser/Executable/Script/Compiler/Function/Call/Argument/FunctionCallArgument';
|
||||||
import type { ArgumentCompiler } from './ArgumentCompiler';
|
import type { ArgumentCompiler } from './ArgumentCompiler';
|
||||||
|
|
||||||
export class NestedFunctionArgumentCompiler implements ArgumentCompiler {
|
export class NestedFunctionArgumentCompiler implements ArgumentCompiler {
|
||||||
constructor(
|
constructor(private readonly utilities: ArgumentCompilationUtilities = DefaultUtilities) { }
|
||||||
private readonly expressionsCompiler: IExpressionsCompiler = new ExpressionsCompiler(),
|
|
||||||
) { }
|
|
||||||
|
|
||||||
public createCompiledNestedCall(
|
public createCompiledNestedCall(
|
||||||
nestedFunction: FunctionCall,
|
nestedFunction: FunctionCall,
|
||||||
@@ -22,18 +21,24 @@ export class NestedFunctionArgumentCompiler implements ArgumentCompiler {
|
|||||||
nestedFunction,
|
nestedFunction,
|
||||||
parentFunction.args,
|
parentFunction.args,
|
||||||
context,
|
context,
|
||||||
this.expressionsCompiler,
|
this.utilities,
|
||||||
);
|
);
|
||||||
const compiledCall = new ParsedFunctionCall(nestedFunction.functionName, compiledArgs);
|
const compiledCall = new ParsedFunctionCall(nestedFunction.functionName, compiledArgs);
|
||||||
return compiledCall;
|
return compiledCall;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ArgumentCompilationUtilities {
|
||||||
|
readonly expressionsCompiler: IExpressionsCompiler,
|
||||||
|
readonly wrapError: ErrorWithContextWrapper;
|
||||||
|
readonly createCallArgument: FunctionCallArgumentFactory;
|
||||||
|
}
|
||||||
|
|
||||||
function compileNestedFunctionArguments(
|
function compileNestedFunctionArguments(
|
||||||
nestedFunction: FunctionCall,
|
nestedFunction: FunctionCall,
|
||||||
parentFunctionArgs: IReadOnlyFunctionCallArgumentCollection,
|
parentFunctionArgs: IReadOnlyFunctionCallArgumentCollection,
|
||||||
context: FunctionCallCompilationContext,
|
context: FunctionCallCompilationContext,
|
||||||
expressionsCompiler: IExpressionsCompiler,
|
utilities: ArgumentCompilationUtilities,
|
||||||
): IReadOnlyFunctionCallArgumentCollection {
|
): IReadOnlyFunctionCallArgumentCollection {
|
||||||
const requiredParameterNames = context
|
const requiredParameterNames = context
|
||||||
.allFunctions
|
.allFunctions
|
||||||
@@ -47,7 +52,7 @@ function compileNestedFunctionArguments(
|
|||||||
paramName,
|
paramName,
|
||||||
nestedFunction,
|
nestedFunction,
|
||||||
parentFunctionArgs,
|
parentFunctionArgs,
|
||||||
expressionsCompiler,
|
utilities,
|
||||||
),
|
),
|
||||||
}))
|
}))
|
||||||
// Filter out arguments with absent values
|
// Filter out arguments with absent values
|
||||||
@@ -67,7 +72,7 @@ function compileNestedFunctionArguments(
|
|||||||
.map(({
|
.map(({
|
||||||
parameterName,
|
parameterName,
|
||||||
compiledArgumentValue,
|
compiledArgumentValue,
|
||||||
}) => new FunctionCallArgument(parameterName, compiledArgumentValue));
|
}) => utilities.createCallArgument(parameterName, compiledArgumentValue));
|
||||||
return buildArgumentCollectionFromArguments(compiledArguments);
|
return buildArgumentCollectionFromArguments(compiledArguments);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,13 +94,13 @@ function compileArgument(
|
|||||||
parameterName: string,
|
parameterName: string,
|
||||||
nestedFunction: FunctionCall,
|
nestedFunction: FunctionCall,
|
||||||
parentFunctionArgs: IReadOnlyFunctionCallArgumentCollection,
|
parentFunctionArgs: IReadOnlyFunctionCallArgumentCollection,
|
||||||
expressionsCompiler: IExpressionsCompiler,
|
utilities: ArgumentCompilationUtilities,
|
||||||
): string {
|
): string {
|
||||||
try {
|
try {
|
||||||
const { argumentValue: codeInArgument } = nestedFunction.args.getArgument(parameterName);
|
const { argumentValue: codeInArgument } = nestedFunction.args.getArgument(parameterName);
|
||||||
return expressionsCompiler.compileExpressions(codeInArgument, parentFunctionArgs);
|
return utilities.expressionsCompiler.compileExpressions(codeInArgument, parentFunctionArgs);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
throw new AggregateError([err], `Error when compiling argument for "${parameterName}"`);
|
throw utilities.wrapError(error, `Error when compiling argument for "${parameterName}"`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -107,3 +112,9 @@ function buildArgumentCollectionFromArguments(
|
|||||||
return compiledArgs;
|
return compiledArgs;
|
||||||
}, new FunctionCallArgumentCollection());
|
}, new FunctionCallArgumentCollection());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const DefaultUtilities: ArgumentCompilationUtilities = {
|
||||||
|
expressionsCompiler: new ExpressionsCompiler(),
|
||||||
|
wrapError: wrapErrorWithAdditionalContext,
|
||||||
|
createCallArgument: createFunctionCallArgument,
|
||||||
|
};
|
||||||
@@ -1,8 +1,9 @@
|
|||||||
import { ExpressionsCompiler } from '@/application/Parser/Script/Compiler/Expressions/ExpressionsCompiler';
|
import { ExpressionsCompiler } from '@/application/Parser/Executable/Script/Compiler/Expressions/ExpressionsCompiler';
|
||||||
import type { IExpressionsCompiler } from '@/application/Parser/Script/Compiler/Expressions/IExpressionsCompiler';
|
import type { IExpressionsCompiler } from '@/application/Parser/Executable/Script/Compiler/Expressions/IExpressionsCompiler';
|
||||||
import { FunctionBodyType, type ISharedFunction } from '@/application/Parser/Script/Compiler/Function/ISharedFunction';
|
import { FunctionBodyType, type ISharedFunction } from '@/application/Parser/Executable/Script/Compiler/Function/ISharedFunction';
|
||||||
import type { FunctionCall } from '@/application/Parser/Script/Compiler/Function/Call/FunctionCall';
|
import type { FunctionCall } from '@/application/Parser/Executable/Script/Compiler/Function/Call/FunctionCall';
|
||||||
import type { CompiledCode } from '@/application/Parser/Script/Compiler/Function/Call/Compiler/CompiledCode';
|
import type { CompiledCode } from '@/application/Parser/Executable/Script/Compiler/Function/Call/Compiler/CompiledCode';
|
||||||
|
import { indentText } from '@/application/Common/Text/IndentText';
|
||||||
import type { SingleCallCompilerStrategy } from '../SingleCallCompilerStrategy';
|
import type { SingleCallCompilerStrategy } from '../SingleCallCompilerStrategy';
|
||||||
|
|
||||||
export class InlineFunctionCallCompiler implements SingleCallCompilerStrategy {
|
export class InlineFunctionCallCompiler implements SingleCallCompilerStrategy {
|
||||||
@@ -22,10 +23,12 @@ export class InlineFunctionCallCompiler implements SingleCallCompilerStrategy {
|
|||||||
if (calledFunction.body.type !== FunctionBodyType.Code) {
|
if (calledFunction.body.type !== FunctionBodyType.Code) {
|
||||||
throw new Error([
|
throw new Error([
|
||||||
'Unexpected function body type.',
|
'Unexpected function body type.',
|
||||||
`\tExpected: "${FunctionBodyType[FunctionBodyType.Code]}"`,
|
indentText([
|
||||||
`\tActual: "${FunctionBodyType[calledFunction.body.type]}"`,
|
`Expected: "${FunctionBodyType[FunctionBodyType.Code]}"`,
|
||||||
|
`Actual: "${FunctionBodyType[calledFunction.body.type]}"`,
|
||||||
|
].join('\n')),
|
||||||
'Function:',
|
'Function:',
|
||||||
`\t${JSON.stringify(callToFunction)}`,
|
indentText(JSON.stringify(callToFunction)),
|
||||||
].join('\n'));
|
].join('\n'));
|
||||||
}
|
}
|
||||||
const { code } = calledFunction.body;
|
const { code } = calledFunction.body;
|
||||||
@@ -1,14 +1,21 @@
|
|||||||
import { type CallFunctionBody, FunctionBodyType, type ISharedFunction } from '@/application/Parser/Script/Compiler/Function/ISharedFunction';
|
import {
|
||||||
import type { FunctionCall } from '@/application/Parser/Script/Compiler/Function/Call/FunctionCall';
|
type CallFunctionBody, FunctionBodyType,
|
||||||
import type { FunctionCallCompilationContext } from '@/application/Parser/Script/Compiler/Function/Call/Compiler/FunctionCallCompilationContext';
|
type ISharedFunction,
|
||||||
import type { CompiledCode } from '@/application/Parser/Script/Compiler/Function/Call/Compiler/CompiledCode';
|
} from '@/application/Parser/Executable/Script/Compiler/Function/ISharedFunction';
|
||||||
|
import type { FunctionCall } from '@/application/Parser/Executable/Script/Compiler/Function/Call/FunctionCall';
|
||||||
|
import type { FunctionCallCompilationContext } from '@/application/Parser/Executable/Script/Compiler/Function/Call/Compiler/FunctionCallCompilationContext';
|
||||||
|
import type { CompiledCode } from '@/application/Parser/Executable/Script/Compiler/Function/Call/Compiler/CompiledCode';
|
||||||
|
import { wrapErrorWithAdditionalContext, type ErrorWithContextWrapper } from '@/application/Parser/Common/ContextualError';
|
||||||
import { NestedFunctionArgumentCompiler } from './Argument/NestedFunctionArgumentCompiler';
|
import { NestedFunctionArgumentCompiler } from './Argument/NestedFunctionArgumentCompiler';
|
||||||
import type { SingleCallCompilerStrategy } from '../SingleCallCompilerStrategy';
|
import type { SingleCallCompilerStrategy } from '../SingleCallCompilerStrategy';
|
||||||
import type { ArgumentCompiler } from './Argument/ArgumentCompiler';
|
import type { ArgumentCompiler } from './Argument/ArgumentCompiler';
|
||||||
|
|
||||||
export class NestedFunctionCallCompiler implements SingleCallCompilerStrategy {
|
export class NestedFunctionCallCompiler implements SingleCallCompilerStrategy {
|
||||||
public constructor(
|
public constructor(
|
||||||
private readonly argumentCompiler: ArgumentCompiler = new NestedFunctionArgumentCompiler(),
|
private readonly argumentCompiler: ArgumentCompiler
|
||||||
|
= new NestedFunctionArgumentCompiler(),
|
||||||
|
private readonly wrapError: ErrorWithContextWrapper
|
||||||
|
= wrapErrorWithAdditionalContext,
|
||||||
) {
|
) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,8 +36,11 @@ export class NestedFunctionCallCompiler implements SingleCallCompilerStrategy {
|
|||||||
const compiledNestedCall = context.singleCallCompiler
|
const compiledNestedCall = context.singleCallCompiler
|
||||||
.compileSingleCall(compiledParentCall, context);
|
.compileSingleCall(compiledParentCall, context);
|
||||||
return compiledNestedCall;
|
return compiledNestedCall;
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
throw new AggregateError([err], `Error with call to "${nestedCall.functionName}" function from "${callToFunction.functionName}" function`);
|
throw this.wrapError(
|
||||||
|
error,
|
||||||
|
`Failed to call '${nestedCall.functionName}' (callee function) from '${callToFunction.functionName}' (caller function).`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}).flat();
|
}).flat();
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import type {
|
||||||
|
FunctionCallData,
|
||||||
|
FunctionCallsData,
|
||||||
|
FunctionCallParametersData,
|
||||||
|
} from '@/application/collections/';
|
||||||
|
import { isArray, isPlainObject } from '@/TypeHelpers';
|
||||||
|
import { createTypeValidator, type TypeValidator } from '@/application/Parser/Common/TypeValidator';
|
||||||
|
import { FunctionCallArgumentCollection } from './Argument/FunctionCallArgumentCollection';
|
||||||
|
import { ParsedFunctionCall } from './ParsedFunctionCall';
|
||||||
|
import { createFunctionCallArgument, type FunctionCallArgumentFactory } from './Argument/FunctionCallArgument';
|
||||||
|
import type { FunctionCall } from './FunctionCall';
|
||||||
|
|
||||||
|
export interface FunctionCallsParser {
|
||||||
|
(
|
||||||
|
calls: FunctionCallsData,
|
||||||
|
utilities?: FunctionCallParsingUtilities,
|
||||||
|
): FunctionCall[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface FunctionCallParsingUtilities {
|
||||||
|
readonly typeValidator: TypeValidator;
|
||||||
|
readonly createCallArgument: FunctionCallArgumentFactory;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DefaultUtilities: FunctionCallParsingUtilities = {
|
||||||
|
typeValidator: createTypeValidator(),
|
||||||
|
createCallArgument: createFunctionCallArgument,
|
||||||
|
};
|
||||||
|
|
||||||
|
export const parseFunctionCalls: FunctionCallsParser = (
|
||||||
|
calls,
|
||||||
|
utilities = DefaultUtilities,
|
||||||
|
) => {
|
||||||
|
const sequence = getCallSequence(calls, utilities.typeValidator);
|
||||||
|
return sequence.map((call) => parseFunctionCall(call, utilities));
|
||||||
|
};
|
||||||
|
|
||||||
|
function getCallSequence(calls: FunctionCallsData, validator: TypeValidator): FunctionCallData[] {
|
||||||
|
if (!isPlainObject(calls) && !isArray(calls)) {
|
||||||
|
throw new Error('called function(s) must be an object or array');
|
||||||
|
}
|
||||||
|
if (isArray(calls)) {
|
||||||
|
validator.assertNonEmptyCollection({
|
||||||
|
value: calls,
|
||||||
|
valueName: 'Function call sequence',
|
||||||
|
});
|
||||||
|
return calls as FunctionCallData[];
|
||||||
|
}
|
||||||
|
const singleCall = calls as FunctionCallData;
|
||||||
|
return [singleCall];
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseFunctionCall(
|
||||||
|
call: FunctionCallData,
|
||||||
|
utilities: FunctionCallParsingUtilities,
|
||||||
|
): FunctionCall {
|
||||||
|
utilities.typeValidator.assertObject({
|
||||||
|
value: call,
|
||||||
|
valueName: 'Function call',
|
||||||
|
allowedProperties: ['function', 'parameters'],
|
||||||
|
});
|
||||||
|
const callArgs = parseArgs(call.parameters, utilities.createCallArgument);
|
||||||
|
return new ParsedFunctionCall(call.function, callArgs);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseArgs(
|
||||||
|
parameters: FunctionCallParametersData | undefined,
|
||||||
|
createArgument: FunctionCallArgumentFactory,
|
||||||
|
): FunctionCallArgumentCollection {
|
||||||
|
const parametersMap = parameters ?? {};
|
||||||
|
return Object.keys(parametersMap)
|
||||||
|
.map((parameterName) => {
|
||||||
|
const argumentValue = parametersMap[parameterName];
|
||||||
|
return createArgument(parameterName, argumentValue);
|
||||||
|
})
|
||||||
|
.reduce((args, arg) => {
|
||||||
|
args.addArgument(arg);
|
||||||
|
return args;
|
||||||
|
}, new FunctionCallArgumentCollection());
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
export interface IFunctionParameter {
|
export interface FunctionParameter {
|
||||||
readonly name: string;
|
readonly name: string;
|
||||||
readonly isOptional: boolean;
|
readonly isOptional: boolean;
|
||||||
}
|
}
|
||||||
@@ -1,14 +1,14 @@
|
|||||||
import type { IFunctionParameterCollection } from './IFunctionParameterCollection';
|
import type { IFunctionParameterCollection } from './IFunctionParameterCollection';
|
||||||
import type { IFunctionParameter } from './IFunctionParameter';
|
import type { FunctionParameter } from './FunctionParameter';
|
||||||
|
|
||||||
export class FunctionParameterCollection implements IFunctionParameterCollection {
|
export class FunctionParameterCollection implements IFunctionParameterCollection {
|
||||||
private parameters = new Array<IFunctionParameter>();
|
private parameters = new Array<FunctionParameter>();
|
||||||
|
|
||||||
public get all(): readonly IFunctionParameter[] {
|
public get all(): readonly FunctionParameter[] {
|
||||||
return this.parameters;
|
return this.parameters;
|
||||||
}
|
}
|
||||||
|
|
||||||
public addParameter(parameter: IFunctionParameter) {
|
public addParameter(parameter: FunctionParameter) {
|
||||||
this.ensureValidParameter(parameter);
|
this.ensureValidParameter(parameter);
|
||||||
this.parameters.push(parameter);
|
this.parameters.push(parameter);
|
||||||
}
|
}
|
||||||
@@ -17,7 +17,7 @@ export class FunctionParameterCollection implements IFunctionParameterCollection
|
|||||||
return this.parameters.find((existingParameter) => existingParameter.name === name);
|
return this.parameters.find((existingParameter) => existingParameter.name === name);
|
||||||
}
|
}
|
||||||
|
|
||||||
private ensureValidParameter(parameter: IFunctionParameter) {
|
private ensureValidParameter(parameter: FunctionParameter) {
|
||||||
if (this.includesName(parameter.name)) {
|
if (this.includesName(parameter.name)) {
|
||||||
throw new Error(`duplicate parameter name: "${parameter.name}"`);
|
throw new Error(`duplicate parameter name: "${parameter.name}"`);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { FunctionParameterCollection } from './FunctionParameterCollection';
|
||||||
|
import type { IFunctionParameterCollection } from './IFunctionParameterCollection';
|
||||||
|
|
||||||
|
export interface FunctionParameterCollectionFactory {
|
||||||
|
(
|
||||||
|
...args: ConstructorParameters<typeof FunctionParameterCollection>
|
||||||
|
): IFunctionParameterCollection;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const createFunctionParameterCollection: FunctionParameterCollectionFactory = (...args) => {
|
||||||
|
return new FunctionParameterCollection(...args);
|
||||||
|
};
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import type { ParameterDefinitionData } from '@/application/collections/';
|
||||||
|
import { validateParameterName, type ParameterNameValidator } from '../Shared/ParameterNameValidator';
|
||||||
|
import type { FunctionParameter } from './FunctionParameter';
|
||||||
|
|
||||||
|
export interface FunctionParameterParser {
|
||||||
|
(
|
||||||
|
data: ParameterDefinitionData,
|
||||||
|
validator?: ParameterNameValidator,
|
||||||
|
): FunctionParameter;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const parseFunctionParameter: FunctionParameterParser = (
|
||||||
|
data,
|
||||||
|
validator = validateParameterName,
|
||||||
|
) => {
|
||||||
|
validator(data.name);
|
||||||
|
return {
|
||||||
|
name: data.name,
|
||||||
|
isOptional: data.optional || false,
|
||||||
|
};
|
||||||
|
};
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user