Compare commits
135 Commits
7a53228ec8
...
feature/in
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7d00a2dadb | ||
|
|
927cd7d2bb | ||
|
|
38b22287c7 | ||
|
|
0de2eee626 | ||
|
|
aa7a15e6fa | ||
|
|
b0a8ef09a8 | ||
|
|
efbaea5ac1 | ||
|
|
bbad327ea2 | ||
|
|
72273a3f1c | ||
|
|
8329244c69 | ||
|
|
b16603b50b | ||
|
|
c6eea88002 | ||
|
|
5876553515 | ||
|
|
d73bc78af5 | ||
|
|
393bfecff2 | ||
| aab478202b | |||
|
|
45e16313ba | ||
|
|
64c737c023 | ||
|
|
75d9149c76 | ||
|
|
28b3946e86 | ||
|
|
6a01a75cce | ||
|
|
189dd32f8c | ||
|
|
7461e8b123 | ||
|
|
f88c238b0a | ||
|
|
8caa1f45ae | ||
|
|
289284a532 | ||
|
|
089f4ce105 | ||
|
|
235dcf8e1d | ||
|
|
8dd60a8ec1 | ||
|
|
20679b6b53 | ||
|
|
53c4a99697 | ||
|
|
5ea33b7d0a | ||
|
|
13a752a69c | ||
|
|
0609a99839 | ||
|
|
dce82d5f7d | ||
|
|
1e8a8ce5f2 | ||
|
|
c0bdd3d8c2 | ||
|
|
2b98c4d229 | ||
|
|
ceae654a39 | ||
|
|
fb28fa95c9 | ||
|
|
419cb3d790 | ||
|
|
53a62fb05e | ||
|
|
322c88612a | ||
|
|
4aa53d79e7 | ||
|
|
3464754489 | ||
|
|
e56253b9c2 | ||
|
|
cb8cc7258c | ||
|
|
b576cd8c4a | ||
|
|
a773159016 | ||
|
|
a9521ad536 | ||
|
|
5456d7140c | ||
|
|
62cc910e1a | ||
|
|
6ec7bb5422 | ||
|
|
ce74750d85 | ||
|
|
d089f1545b | ||
|
|
7b06fef6c3 | ||
|
|
7be9f5a869 | ||
|
|
a7ebbe0635 | ||
|
|
3662f117f5 | ||
|
|
0899a84b42 | ||
|
|
85d23b0347 | ||
|
|
13db4abc0f | ||
|
|
57e434e4ff | ||
|
|
7c2901f453 | ||
| 6c67444b19 | |||
|
|
970b0a07da | ||
|
|
e2e5813b54 | ||
|
|
73567c185c | ||
| 0587762bbb | |||
|
|
cd6e9c3619 | ||
|
|
d8c3997f24 | ||
|
|
e44d49e190 | ||
| 4d2aad404b | |||
|
|
0453763c98 | ||
|
|
03c0011445 | ||
|
|
79f287ed61 | ||
|
|
e55e6bf4dd | ||
| 1fa3bf44b6 | |||
|
|
51d5552156 | ||
|
|
5a12c0e0d0 | ||
|
|
ee181cf6cb | ||
|
|
74d636117d | ||
|
|
ed458e6c3a | ||
|
|
9b9378477a | ||
|
|
1b4a26e31a | ||
|
|
45c32a6d1e | ||
|
|
63968280b8 | ||
|
|
3ccf31f479 | ||
|
|
c599598390 | ||
|
|
d0aa6fda08 | ||
|
|
62c39b8aa5 | ||
|
|
75eddcf85d | ||
|
|
0babfc90f4 | ||
|
|
7538054b20 | ||
|
|
117dd2cc75 | ||
|
|
b9e8778f8f | ||
|
|
9536158f58 | ||
|
|
783e13eb10 | ||
|
|
1794cf9a59 | ||
|
|
ee1c6ee299 | ||
|
|
a6aac42c78 | ||
|
|
071fc3099f | ||
|
|
78f1db7203 | ||
|
|
e21430f6ff | ||
|
|
b195208ddc | ||
|
|
5cb77235da | ||
|
|
a6d72ce37f | ||
|
|
663b322d97 | ||
|
|
15f2d0c6d9 | ||
|
|
6887e0b389 | ||
|
|
f266d3f304 | ||
|
|
4af4aafd98 | ||
|
|
81805289e4 | ||
|
|
9f2f58e23e | ||
|
|
53ea5e3fc1 | ||
|
|
d35fc11267 | ||
|
|
697eb64dd4 | ||
|
|
d36609d8c2 | ||
|
|
e23278d71e | ||
|
|
edd209238f | ||
|
|
4fbef8a5dc | ||
|
|
edb216347d | ||
|
|
508c4f129f | ||
|
|
1c0140292f | ||
|
|
53815c4814 | ||
|
|
df714a43a2 | ||
|
|
a8bb2c8164 | ||
|
|
5d0628878b | ||
|
|
dacc18fe5d | ||
|
|
9ab6377d16 | ||
|
|
197157cecb | ||
|
|
c273a8625a | ||
|
|
2a2666e75f | ||
|
|
1b57adab98 | ||
|
|
e1578ed11c |
@@ -1,6 +1,9 @@
|
||||
# Build artifacts
|
||||
target/
|
||||
dist/
|
||||
frontend/dist/
|
||||
backend/target/
|
||||
# Allow backend binary for multi-stage builds
|
||||
!backend/target/release/backend
|
||||
|
||||
# Git
|
||||
.git/
|
||||
@@ -21,8 +24,18 @@ Thumbs.db
|
||||
|
||||
# Documentation
|
||||
README.md
|
||||
*.md
|
||||
|
||||
# Docker
|
||||
Dockerfile
|
||||
.dockerignore
|
||||
# Development files
|
||||
CLAUDE.md
|
||||
*.txt
|
||||
test_*.js
|
||||
|
||||
# Database files
|
||||
*.db
|
||||
calendar.db
|
||||
|
||||
# Test files
|
||||
**/tests/
|
||||
|
||||
# Migrations (not needed for builds)
|
||||
migrations/
|
||||
|
||||
35
.gitea/workflows/docker.yml
Normal file
35
.gitea/workflows/docker.yml
Normal file
@@ -0,0 +1,35 @@
|
||||
name: Build and Push Docker Image
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
docker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Login to Docker Registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ vars.REGISTRY }}
|
||||
username: ${{ vars.USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v5
|
||||
with:
|
||||
context: .
|
||||
file: ./backend/Dockerfile
|
||||
push: true
|
||||
tags: |
|
||||
${{ vars.REGISTRY }}/connor/calendar:latest
|
||||
${{ vars.REGISTRY }}/connor/calendar:${{ github.sha }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
133
.gitea/workflows/integration-tests.yml
Normal file
133
.gitea/workflows/integration-tests.yml
Normal file
@@ -0,0 +1,133 @@
|
||||
name: Integration Tests
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main, feature/integration-testing ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
|
||||
jobs:
|
||||
e2e-tests:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
services:
|
||||
# Backend service for testing
|
||||
backend:
|
||||
image: ubuntu-latest
|
||||
ports:
|
||||
- 3000:3000
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Set up Rust
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
override: true
|
||||
components: rustfmt, clippy
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: '18'
|
||||
cache: 'npm'
|
||||
cache-dependency-path: frontend/e2e/package-lock.json
|
||||
|
||||
- name: Install Trunk
|
||||
uses: jetli/trunk-action@v0.4.0
|
||||
with:
|
||||
version: 'latest'
|
||||
|
||||
- name: Install wasm32 target
|
||||
run: rustup target add wasm32-unknown-unknown
|
||||
|
||||
- name: Build backend
|
||||
run: |
|
||||
cd backend
|
||||
cargo build --release
|
||||
|
||||
- name: Build frontend
|
||||
run: |
|
||||
trunk build --release
|
||||
|
||||
- name: Install E2E test dependencies
|
||||
run: |
|
||||
cd frontend/e2e
|
||||
npm ci
|
||||
npx playwright install chromium firefox
|
||||
# Install system dependencies for Ubuntu runner
|
||||
sudo apt-get update && sudo apt-get install -y \
|
||||
libnss3 libatk-bridge2.0-0 libdrm2 libgtk-3-0 \
|
||||
libgbm1 libasound2
|
||||
|
||||
- name: Start backend server
|
||||
run: |
|
||||
cd backend
|
||||
cargo run --release &
|
||||
# Wait for server to start
|
||||
sleep 10
|
||||
curl -f http://localhost:3000/health || exit 1
|
||||
env:
|
||||
CI: true
|
||||
|
||||
- name: Start frontend server
|
||||
run: |
|
||||
trunk serve --release --address 0.0.0.0 &
|
||||
# Wait for frontend to start
|
||||
sleep 10
|
||||
curl -f http://localhost:8080 || exit 1
|
||||
env:
|
||||
CI: true
|
||||
|
||||
- name: Run E2E tests
|
||||
run: |
|
||||
cd frontend/e2e
|
||||
npx playwright test --project=chromium --project=firefox
|
||||
env:
|
||||
CI: true
|
||||
TEST_CALDAV_SERVER: https://baikal.rcjohnstone.com/dav.php/
|
||||
TEST_CALDAV_USERNAME: test
|
||||
TEST_CALDAV_PASSWORD: I0W?7`|Cs6tA`s
|
||||
|
||||
- name: Upload test results
|
||||
uses: actions/upload-artifact@v3
|
||||
if: always()
|
||||
with:
|
||||
name: playwright-report
|
||||
path: frontend/e2e/playwright-report/
|
||||
retention-days: 30
|
||||
|
||||
unit-tests:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- name: Set up Rust
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
override: true
|
||||
components: rustfmt, clippy
|
||||
|
||||
- name: Install wasm32 target
|
||||
run: rustup target add wasm32-unknown-unknown
|
||||
|
||||
- name: Install wasm-pack
|
||||
run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh
|
||||
|
||||
- name: Run frontend unit tests
|
||||
run: |
|
||||
cd frontend
|
||||
wasm-pack test --headless --chrome --firefox
|
||||
|
||||
- name: Run backend unit tests
|
||||
run: |
|
||||
cd backend
|
||||
cargo test
|
||||
|
||||
- name: Run calendar-models tests
|
||||
run: |
|
||||
cd calendar-models
|
||||
cargo test --features wasm
|
||||
13
.gitignore
vendored
13
.gitignore
vendored
@@ -16,4 +16,15 @@ dist/
|
||||
# Environment variables (secrets)
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
.env.*.local
|
||||
|
||||
# Development notes (keep local)
|
||||
CLAUDE.md
|
||||
|
||||
data/
|
||||
|
||||
# SQLite database
|
||||
*.db
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
calendar.db
|
||||
|
||||
15
Caddyfile
Normal file
15
Caddyfile
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
default_sni rcjohnstone.com
|
||||
key_type rsa4096
|
||||
email c@rcjohnstone.com
|
||||
}
|
||||
|
||||
:80, :443 {
|
||||
@backend {
|
||||
path /api /api/*
|
||||
}
|
||||
reverse_proxy @backend calendar-backend:3000
|
||||
try_files {path} /index.html
|
||||
root * /srv/www
|
||||
file_server
|
||||
}
|
||||
73
Cargo.toml
73
Cargo.toml
@@ -1,65 +1,14 @@
|
||||
[package]
|
||||
name = "calendar-app"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
[workspace]
|
||||
members = [
|
||||
"frontend",
|
||||
"backend",
|
||||
"calendar-models"
|
||||
]
|
||||
resolver = "2"
|
||||
|
||||
# Frontend binary only
|
||||
|
||||
[dependencies]
|
||||
yew = { version = "0.21", features = ["csr"] }
|
||||
web-sys = { version = "0.3", features = [
|
||||
"console",
|
||||
"HtmlSelectElement",
|
||||
"HtmlInputElement",
|
||||
"HtmlTextAreaElement",
|
||||
"Event",
|
||||
"MouseEvent",
|
||||
"InputEvent",
|
||||
"Element",
|
||||
"Document",
|
||||
"Window",
|
||||
"Location",
|
||||
"Headers",
|
||||
"Request",
|
||||
"RequestInit",
|
||||
"RequestMode",
|
||||
"Response",
|
||||
] }
|
||||
wasm-bindgen = "0.2"
|
||||
|
||||
# HTTP client for CalDAV requests
|
||||
reqwest = { version = "0.11", features = ["json"] }
|
||||
# Calendar and iCal parsing
|
||||
ical = "0.7"
|
||||
[workspace.dependencies]
|
||||
calendar-models = { path = "calendar-models" }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
|
||||
# Date and time handling
|
||||
chrono = { version = "0.4", features = ["serde", "wasm-bindgen"] }
|
||||
chrono-tz = "0.8"
|
||||
|
||||
# Error handling
|
||||
anyhow = "1.0"
|
||||
thiserror = "1.0"
|
||||
|
||||
# Logging
|
||||
log = "0.4"
|
||||
console_log = "1.0"
|
||||
|
||||
# UUID generation for calendar events
|
||||
uuid = { version = "1.0", features = ["v4", "wasm-bindgen", "serde"] }
|
||||
getrandom = { version = "0.2", features = ["js"] }
|
||||
|
||||
# Environment variable handling
|
||||
dotenvy = "0.15"
|
||||
base64 = "0.21"
|
||||
|
||||
# XML/Regex parsing
|
||||
regex = "1.0"
|
||||
|
||||
# Yew routing and local storage (WASM only)
|
||||
yew-router = "0.18"
|
||||
gloo-storage = "0.3"
|
||||
gloo-timers = "0.3"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
|
||||
uuid = { version = "1.0", features = ["v4", "serde"] }
|
||||
67
Dockerfile
67
Dockerfile
@@ -1,67 +0,0 @@
|
||||
# Build stage
|
||||
# ---------------------------------------
|
||||
FROM rust:alpine AS builder
|
||||
|
||||
# Install build dependencies
|
||||
RUN apk add --no-cache \
|
||||
musl-dev \
|
||||
pkgconfig \
|
||||
openssl-dev \
|
||||
nodejs \
|
||||
npm
|
||||
|
||||
# Install trunk for building Yew apps
|
||||
RUN cargo install trunk wasm-pack
|
||||
|
||||
# Add wasm32 target
|
||||
RUN rustup target add wasm32-unknown-unknown
|
||||
|
||||
# Set working directory
|
||||
WORKDIR /app
|
||||
|
||||
# Copy dependency files
|
||||
COPY Cargo.toml ./
|
||||
COPY src ./src
|
||||
|
||||
# Copy web assets
|
||||
COPY index.html ./
|
||||
COPY Trunk.toml ./
|
||||
|
||||
# Build the application
|
||||
RUN trunk build --release
|
||||
|
||||
|
||||
|
||||
# Runtime stage
|
||||
# ---------------------------------------
|
||||
FROM docker.io/nginx:alpine
|
||||
|
||||
# Remove default nginx content
|
||||
RUN rm -rf /usr/share/nginx/html/*
|
||||
|
||||
# Copy built application from builder stage
|
||||
COPY --from=builder /app/dist/* /usr/share/nginx/html/
|
||||
|
||||
# Add nginx configuration for SPA
|
||||
RUN echo 'server { \
|
||||
listen 80; \
|
||||
server_name localhost; \
|
||||
root /usr/share/nginx/html; \
|
||||
index index.html; \
|
||||
location / { \
|
||||
try_files $uri $uri/ /index.html; \
|
||||
} \
|
||||
# Enable gzip compression \
|
||||
gzip on; \
|
||||
gzip_types text/css application/javascript application/wasm; \
|
||||
}' > /etc/nginx/conf.d/default.conf
|
||||
|
||||
# Expose port
|
||||
EXPOSE 80
|
||||
|
||||
# Health check
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD wget --quiet --tries=1 --spider http://localhost/ || exit 1
|
||||
|
||||
# Start nginx
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
173
README.md
173
README.md
@@ -1,46 +1,128 @@
|
||||
# Calendar App
|
||||
# Runway
|
||||
## _Passive infrastructure for life's coordination_
|
||||
|
||||
A full-stack calendar application built with Rust, featuring a Yew frontend and Axum backend with CalDAV integration.
|
||||

|
||||
|
||||
>[!WARNING]
|
||||
>This project was entirely vibe coded. It's my first attempt vibe coding anything, but I just sat down one day and realized this was something I've wanted to build for many years, but would just take way too long. With AI, I've been able to lay out the majority of the app in one long weekend. So proceed at your own risk, but I actually think the app is pretty solid.
|
||||
|
||||
A modern CalDAV web client built with Rust WebAssembly.
|
||||
|
||||
## The Name
|
||||
|
||||
Runway embodies the concept of **passive infrastructure** — unobtrusive systems that enable better coordination without getting in the way. Planes can fly and do lots of cool things, but without runways, they can't take off or land. Similarly, calendars and scheduling tools are essential for organizing our lives, but they should not dominate our attention.
|
||||
|
||||
The best infrastructure is invisible when working, essential when needed, and enables rather than constrains.
|
||||
|
||||
## Why Runway?
|
||||
|
||||
While there are many excellent self-hosted CalDAV server implementations (Nextcloud, Radicale, Baikal, etc.), the web client ecosystem remains limited. Existing solutions like [AgenDAV](https://github.com/agendav/agendav) often suffer from outdated interfaces, bugs, and poor user experience. Runway provides a modern, fast, and reliable web interface for CalDAV servers — infrastructure that just works.
|
||||
|
||||
## Features
|
||||
|
||||
- Interactive calendar interface
|
||||
- Event creation and management
|
||||
- CalDAV server integration
|
||||
- User authentication with JWT
|
||||
- iCal format support
|
||||
- Weekly recurrence patterns
|
||||
- Responsive web design
|
||||
### Calendar Management
|
||||
- **Interactive Calendar Views**: Month and week views with intuitive navigation
|
||||
- **Event Creation & Editing**: Comprehensive event forms with all standard iCalendar properties
|
||||
- **Drag & Drop**: Move events between dates and times with automatic timezone conversion
|
||||
- **CalDAV Integration**: Full bidirectional sync with any RFC-compliant CalDAV server
|
||||
|
||||
### Recurring Events
|
||||
- **RFC 5545 Compliance**: Complete RRULE support with proper parsing and generation
|
||||
- **Flexible Patterns**: Daily, weekly, monthly, and yearly recurrence with custom intervals
|
||||
- **Advanced Options**: BYDAY rules, COUNT limits, UNTIL dates, and exception handling
|
||||
- **Series Management**: Edit entire series or "this and future" events with proper UNTIL handling
|
||||
|
||||
### Modern Web Experience
|
||||
- **Fast & Responsive**: Rust WebAssembly frontend for native-like performance
|
||||
- **Clean Interface**: Modern, intuitive design built with web standards
|
||||
- **Real-time Updates**: Seamless synchronization with CalDAV servers
|
||||
- **Timezone Aware**: Proper local time display with UTC storage
|
||||
|
||||
### User Experience
|
||||
- **Persistent Preferences**: Settings sync across devices and sessions
|
||||
- **Remember Me**: Optional server/username remembering for convenience
|
||||
- **Session Management**: Secure session tokens with automatic expiry
|
||||
- **Cross-Device Sync**: User preferences stored in database, not just browser
|
||||
|
||||
## Architecture
|
||||
|
||||
- **Frontend**: Yew (Rust WebAssembly)
|
||||
- **Backend**: Axum (Rust async web framework)
|
||||
- **Protocol**: CalDAV for calendar synchronization
|
||||
- **Database**: SQLite (via migrations)
|
||||
- **Build Tool**: Trunk for frontend bundling
|
||||
### Frontend (Yew WebAssembly)
|
||||
- **Framework**: Yew for component-based UI development
|
||||
- **Performance**: Rust WebAssembly for near-native browser performance
|
||||
- **Models**: RFC 5545-compliant VEvent structures throughout
|
||||
- **Services**: HTTP client for backend API communication
|
||||
- **Views**: Responsive month/week calendar views with drag-and-drop
|
||||
|
||||
### Backend (Axum)
|
||||
- **Framework**: Axum async web framework with CORS support
|
||||
- **Authentication**: SQLite-backed session management with JWT tokens
|
||||
- **Database**: SQLite for user preferences and session storage
|
||||
- **CalDAV Client**: Full CalDAV protocol implementation for server sync
|
||||
- **API Design**: RESTful endpoints following calendar operation patterns
|
||||
- **Data Flow**: Proxy between frontend and CalDAV servers with proper authentication
|
||||
|
||||
### Key Technical Features
|
||||
- **RFC 5545 Compliance**: Complete iCalendar standard implementation
|
||||
- **RRULE Processing**: Advanced recurrence rule parsing and generation
|
||||
- **Timezone Handling**: Local time in UI, UTC for storage and CalDAV sync
|
||||
- **Event Series**: Proper handling of recurring event modifications and exceptions
|
||||
- **Build System**: Trunk for frontend bundling, Cargo workspaces for organization
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Prerequisites
|
||||
### Docker Deployment (Recommended)
|
||||
|
||||
The easiest way to run Runway is using Docker Compose:
|
||||
|
||||
1. **Clone the repository**:
|
||||
```bash
|
||||
git clone <repository-url>
|
||||
cd calendar
|
||||
```
|
||||
|
||||
2. **Start the application**:
|
||||
```bash
|
||||
docker compose up
|
||||
```
|
||||
|
||||
3. **Access the application** at `http://localhost`
|
||||
|
||||
The Docker setup includes:
|
||||
- **Automatic database migrations** on startup
|
||||
- **Persistent data storage** in `./data/db/` volume
|
||||
- **Frontend served via Caddy** on port 80
|
||||
- **Backend API** accessible on port 3000
|
||||
|
||||
### Development Setup
|
||||
|
||||
#### Prerequisites
|
||||
- Rust (latest stable version)
|
||||
- Trunk (`cargo install trunk`)
|
||||
|
||||
### Development
|
||||
#### Local Development
|
||||
|
||||
1. Start the backend server:
|
||||
1. **Start the backend server** (serves API at http://localhost:3000):
|
||||
```bash
|
||||
cd backend
|
||||
cargo run
|
||||
cargo run --manifest-path=backend/Cargo.toml
|
||||
```
|
||||
|
||||
2. Start the frontend development server:
|
||||
2. **Start the frontend development server** (serves at http://localhost:8080):
|
||||
```bash
|
||||
trunk serve
|
||||
```
|
||||
|
||||
3. Open your browser to `http://localhost:8080`
|
||||
3. **Access the application** at `http://localhost:8080`
|
||||
|
||||
#### Database Setup
|
||||
|
||||
For local development, run the database migrations:
|
||||
```bash
|
||||
# Install sqlx-cli if not already installed
|
||||
cargo install sqlx-cli --features sqlite
|
||||
|
||||
# Run migrations
|
||||
sqlx migrate run --database-url "sqlite:calendar.db" --source backend/migrations
|
||||
```
|
||||
|
||||
### Building for Production
|
||||
|
||||
@@ -48,9 +130,50 @@ A full-stack calendar application built with Rust, featuring a Yew frontend and
|
||||
trunk build --release
|
||||
```
|
||||
|
||||
### Development Commands
|
||||
|
||||
- `cargo check` - Check frontend compilation
|
||||
- `cargo check --manifest-path=backend/Cargo.toml` - Check backend compilation
|
||||
- `trunk serve` - Start frontend development server with hot reload
|
||||
|
||||
## Project Structure
|
||||
|
||||
- `src/` - Frontend Yew application
|
||||
- `backend/` - Axum backend server
|
||||
- `migrations/` - Database schema migrations
|
||||
- `dist/` - Built frontend assets
|
||||
```
|
||||
calendar/
|
||||
├── frontend/ # Yew WebAssembly frontend
|
||||
│ ├── src/
|
||||
│ │ ├── app.rs # Main app component with routing
|
||||
│ │ ├── components/ # UI components
|
||||
│ │ │ ├── calendar.rs # Main calendar container
|
||||
│ │ │ ├── month_view.rs # Month calendar view
|
||||
│ │ │ ├── week_view.rs # Week calendar view
|
||||
│ │ │ ├── create_event_modal.rs # Event creation form
|
||||
│ │ │ └── ...
|
||||
│ │ ├── models/
|
||||
│ │ │ └── ical.rs # RFC 5545 VEvent structures
|
||||
│ │ └── services/
|
||||
│ │ └── calendar_service.rs # HTTP client & RRULE logic
|
||||
│ ├── index.html # HTML template
|
||||
│ └── Trunk.toml # Frontend build config
|
||||
├── backend/ # Axum REST API server
|
||||
│ └── src/
|
||||
│ ├── main.rs # Server entry point
|
||||
│ ├── handlers/ # API endpoint handlers
|
||||
│ │ ├── events.rs # Event CRUD operations
|
||||
│ │ └── series.rs # Recurring event operations
|
||||
│ ├── auth.rs # JWT authentication
|
||||
│ └── calendar.rs # CalDAV client implementation
|
||||
└── CLAUDE.md # Development instructions
|
||||
```
|
||||
|
||||
## CalDAV Compatibility
|
||||
|
||||
This client is designed to work with any RFC-compliant CalDAV server:
|
||||
|
||||
- **Baikal** - ✅ Fully tested with complete event and recurrence support
|
||||
- **Nextcloud** - 🚧 Planned compatibility with Nextcloud calendar
|
||||
- **Radicale** - 🚧 Planned lightweight CalDAV server support
|
||||
- **Apple Calendar Server** - 🚧 Planned standards-compliant operation
|
||||
- **Google Calendar** - 🚧 Planned CalDAV API compatibility
|
||||
|
||||
*Note: While the client follows RFC standards and should work with any compliant CalDAV server, we have currently only tested extensively with Baikal. Testing with other servers is planned.*
|
||||
|
||||
16
Trunk.toml
16
Trunk.toml
@@ -1,16 +0,0 @@
|
||||
[build]
|
||||
target = "index.html"
|
||||
dist = "dist"
|
||||
|
||||
[env]
|
||||
BACKEND_API_URL = "http://localhost:3000/api"
|
||||
|
||||
[watch]
|
||||
watch = ["src", "Cargo.toml", "styles.css", "index.html"]
|
||||
ignore = ["backend/"]
|
||||
|
||||
[serve]
|
||||
address = "127.0.0.1"
|
||||
port = 8080
|
||||
open = false
|
||||
|
||||
@@ -8,6 +8,8 @@ name = "backend"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
calendar-models = { workspace = true }
|
||||
|
||||
# Backend authentication dependencies
|
||||
jsonwebtoken = "9.0"
|
||||
tokio = { version = "1.0", features = ["full"] }
|
||||
@@ -20,6 +22,7 @@ hyper = { version = "1.0", features = ["full"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
chrono-tz = "0.8"
|
||||
uuid = { version = "1.0", features = ["v4", "serde"] }
|
||||
anyhow = "1.0"
|
||||
|
||||
@@ -30,6 +33,14 @@ regex = "1.0"
|
||||
dotenvy = "0.15"
|
||||
base64 = "0.21"
|
||||
thiserror = "1.0"
|
||||
lazy_static = "1.4"
|
||||
|
||||
# Database dependencies
|
||||
sqlx = { version = "0.7", features = ["runtime-tokio", "sqlite", "uuid", "chrono", "json"] }
|
||||
tokio-rusqlite = "0.5"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1.0", features = ["macros", "rt"] }
|
||||
tokio = { version = "1.0", features = ["macros", "rt"] }
|
||||
reqwest = { version = "0.11", features = ["json"] }
|
||||
tower = { version = "0.4", features = ["util"] }
|
||||
hyper = "1.0"
|
||||
64
backend/Dockerfile
Normal file
64
backend/Dockerfile
Normal file
@@ -0,0 +1,64 @@
|
||||
# Build stage
|
||||
# -----------------------------------------------------------
|
||||
FROM rust:alpine AS builder
|
||||
|
||||
# Install build dependencies for backend
|
||||
WORKDIR /app
|
||||
RUN apk add --no-cache musl-dev pkgconfig openssl-dev openssl-libs-static
|
||||
|
||||
# Install sqlx-cli for migrations
|
||||
RUN cargo install sqlx-cli --no-default-features --features sqlite
|
||||
|
||||
# Copy workspace files to maintain workspace structure
|
||||
COPY ./Cargo.toml ./
|
||||
COPY ./calendar-models ./calendar-models
|
||||
|
||||
# Create empty frontend directory to satisfy workspace
|
||||
RUN mkdir -p frontend/src && \
|
||||
printf '[package]\nname = "runway"\nversion = "0.1.0"\nedition = "2021"\n\n[dependencies]\n' > frontend/Cargo.toml && \
|
||||
echo 'fn main() {}' > frontend/src/main.rs
|
||||
|
||||
# Copy backend files
|
||||
COPY backend/Cargo.toml ./backend/
|
||||
|
||||
# Create dummy backend source to build dependencies first
|
||||
RUN mkdir -p backend/src && \
|
||||
echo "fn main() {}" > backend/src/main.rs
|
||||
|
||||
# Build dependencies (this layer will be cached unless dependencies change)
|
||||
RUN cargo build --release
|
||||
|
||||
# Copy actual backend source and build
|
||||
COPY backend/src ./backend/src
|
||||
COPY backend/migrations ./backend/migrations
|
||||
RUN cargo build --release --bin backend
|
||||
|
||||
# Runtime stage
|
||||
# -----------------------------------------------------------
|
||||
FROM alpine:latest
|
||||
|
||||
# Install runtime dependencies
|
||||
RUN apk add --no-cache ca-certificates tzdata sqlite
|
||||
|
||||
# Copy backend binary and sqlx-cli
|
||||
COPY --from=builder /app/target/release/backend /usr/local/bin/backend
|
||||
COPY --from=builder /usr/local/cargo/bin/sqlx /usr/local/bin/sqlx
|
||||
|
||||
# Copy migrations for database setup
|
||||
COPY backend/migrations /migrations
|
||||
|
||||
# Create startup script to run migrations and start backend
|
||||
RUN mkdir -p /db
|
||||
RUN echo '#!/bin/sh' > /usr/local/bin/start.sh && \
|
||||
echo 'echo "Ensuring database directory exists..."' >> /usr/local/bin/start.sh && \
|
||||
echo 'mkdir -p /db && chmod 755 /db' >> /usr/local/bin/start.sh && \
|
||||
echo 'touch /db/calendar.db' >> /usr/local/bin/start.sh && \
|
||||
echo 'echo "Running database migrations..."' >> /usr/local/bin/start.sh && \
|
||||
echo 'sqlx migrate run --database-url "sqlite:///db/calendar.db" --source /migrations || echo "Migration failed but continuing..."' >> /usr/local/bin/start.sh && \
|
||||
echo 'echo "Starting backend server..."' >> /usr/local/bin/start.sh && \
|
||||
echo 'export DATABASE_URL="sqlite:///db/calendar.db"' >> /usr/local/bin/start.sh && \
|
||||
echo '/usr/local/bin/backend' >> /usr/local/bin/start.sh && \
|
||||
chmod +x /usr/local/bin/start.sh
|
||||
|
||||
# Start with script that runs migrations then starts backend
|
||||
CMD ["/usr/local/bin/start.sh"]
|
||||
8
backend/migrations/001_create_users_table.sql
Normal file
8
backend/migrations/001_create_users_table.sql
Normal file
@@ -0,0 +1,8 @@
|
||||
-- Create users table
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id TEXT PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
server_url TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
UNIQUE(username, server_url)
|
||||
);
|
||||
16
backend/migrations/002_create_sessions_table.sql
Normal file
16
backend/migrations/002_create_sessions_table.sql
Normal file
@@ -0,0 +1,16 @@
|
||||
-- Create sessions table
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
token TEXT NOT NULL UNIQUE,
|
||||
created_at TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL,
|
||||
last_accessed TEXT NOT NULL,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Index for faster token lookups
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_token ON sessions(token);
|
||||
|
||||
-- Index for cleanup of expired sessions
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_expires_at ON sessions(expires_at);
|
||||
11
backend/migrations/003_create_user_preferences_table.sql
Normal file
11
backend/migrations/003_create_user_preferences_table.sql
Normal file
@@ -0,0 +1,11 @@
|
||||
-- Create user preferences table
|
||||
CREATE TABLE IF NOT EXISTS user_preferences (
|
||||
user_id TEXT PRIMARY KEY,
|
||||
calendar_selected_date TEXT,
|
||||
calendar_time_increment INTEGER,
|
||||
calendar_view_mode TEXT,
|
||||
calendar_theme TEXT,
|
||||
calendar_colors TEXT, -- JSON string for calendar color mappings
|
||||
updated_at TEXT NOT NULL,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
2
backend/migrations/004_add_style_preference.sql
Normal file
2
backend/migrations/004_add_style_preference.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
-- Add calendar style preference to user preferences
|
||||
ALTER TABLE user_preferences ADD COLUMN calendar_style TEXT DEFAULT 'default';
|
||||
2
backend/migrations/005_add_last_used_calendar.sql
Normal file
2
backend/migrations/005_add_last_used_calendar.sql
Normal file
@@ -0,0 +1,2 @@
|
||||
-- Add last used calendar preference to user preferences
|
||||
ALTER TABLE user_preferences ADD COLUMN last_used_calendar TEXT;
|
||||
16
backend/migrations/006_create_external_calendars_table.sql
Normal file
16
backend/migrations/006_create_external_calendars_table.sql
Normal file
@@ -0,0 +1,16 @@
|
||||
-- Create external_calendars table
|
||||
CREATE TABLE external_calendars (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
url TEXT NOT NULL,
|
||||
color TEXT NOT NULL DEFAULT '#4285f4',
|
||||
is_visible BOOLEAN NOT NULL DEFAULT 1,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
last_fetched DATETIME,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
-- Create index for performance
|
||||
CREATE INDEX idx_external_calendars_user_id ON external_calendars(user_id);
|
||||
@@ -0,0 +1,14 @@
|
||||
-- Create external calendar cache table for storing ICS data
|
||||
CREATE TABLE external_calendar_cache (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
external_calendar_id INTEGER NOT NULL,
|
||||
ics_data TEXT NOT NULL,
|
||||
cached_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
etag TEXT,
|
||||
FOREIGN KEY (external_calendar_id) REFERENCES external_calendars(id) ON DELETE CASCADE,
|
||||
UNIQUE(external_calendar_id)
|
||||
);
|
||||
|
||||
-- Index for faster lookups
|
||||
CREATE INDEX idx_external_calendar_cache_calendar_id ON external_calendar_cache(external_calendar_id);
|
||||
CREATE INDEX idx_external_calendar_cache_cached_at ON external_calendar_cache(cached_at);
|
||||
@@ -1,27 +1,30 @@
|
||||
use chrono::{Duration, Utc};
|
||||
use jsonwebtoken::{decode, encode, Algorithm, DecodingKey, EncodingKey, Header, Validation};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::models::{CalDAVLoginRequest, AuthResponse, ApiError};
|
||||
use crate::config::CalDAVConfig;
|
||||
use crate::calendar::CalDAVClient;
|
||||
use crate::config::CalDAVConfig;
|
||||
use crate::db::{Database, PreferencesRepository, Session, SessionRepository, UserRepository};
|
||||
use crate::models::{ApiError, AuthResponse, CalDAVLoginRequest, UserPreferencesResponse};
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Claims {
|
||||
pub username: String,
|
||||
pub server_url: String,
|
||||
pub exp: i64, // Expiration time
|
||||
pub iat: i64, // Issued at
|
||||
pub exp: i64, // Expiration time
|
||||
pub iat: i64, // Issued at
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AuthService {
|
||||
jwt_secret: String,
|
||||
db: Database,
|
||||
}
|
||||
|
||||
impl AuthService {
|
||||
pub fn new(jwt_secret: String) -> Self {
|
||||
Self { jwt_secret }
|
||||
pub fn new(jwt_secret: String, db: Database) -> Self {
|
||||
Self { jwt_secret, db }
|
||||
}
|
||||
|
||||
/// Authenticate user directly against CalDAV server
|
||||
@@ -31,36 +34,75 @@ impl AuthService {
|
||||
println!("✅ Input validation passed");
|
||||
|
||||
// Create CalDAV config with provided credentials
|
||||
let caldav_config = CalDAVConfig {
|
||||
server_url: request.server_url.clone(),
|
||||
username: request.username.clone(),
|
||||
password: request.password.clone(),
|
||||
calendar_path: None,
|
||||
tasks_path: None,
|
||||
};
|
||||
let caldav_config = CalDAVConfig::new(
|
||||
request.server_url.clone(),
|
||||
request.username.clone(),
|
||||
request.password.clone(),
|
||||
);
|
||||
println!("📝 Created CalDAV config");
|
||||
|
||||
// Test authentication against CalDAV server
|
||||
let caldav_client = CalDAVClient::new(caldav_config.clone());
|
||||
println!("🔗 Created CalDAV client, attempting to discover calendars...");
|
||||
|
||||
|
||||
// Try to discover calendars as an authentication test
|
||||
match caldav_client.discover_calendars().await {
|
||||
Ok(calendars) => {
|
||||
println!("✅ Authentication successful! Found {} calendars", calendars.len());
|
||||
// Authentication successful, generate JWT token
|
||||
let token = self.generate_token(&request.username, &request.server_url)?;
|
||||
println!(
|
||||
"✅ Authentication successful! Found {} calendars",
|
||||
calendars.len()
|
||||
);
|
||||
|
||||
// Find or create user in database
|
||||
let user_repo = UserRepository::new(&self.db);
|
||||
let user = user_repo
|
||||
.find_or_create(&request.username, &request.server_url)
|
||||
.await
|
||||
.map_err(|e| ApiError::Database(format!("Failed to create user: {}", e)))?;
|
||||
|
||||
// Generate JWT token
|
||||
let jwt_token = self.generate_token(&request.username, &request.server_url)?;
|
||||
|
||||
// Generate session token
|
||||
let session_token = format!("sess_{}", Uuid::new_v4());
|
||||
|
||||
// Create session in database
|
||||
let session = Session::new(user.id.clone(), session_token.clone(), 24);
|
||||
let session_repo = SessionRepository::new(&self.db);
|
||||
session_repo
|
||||
.create(&session)
|
||||
.await
|
||||
.map_err(|e| ApiError::Database(format!("Failed to create session: {}", e)))?;
|
||||
|
||||
// Get or create user preferences
|
||||
let prefs_repo = PreferencesRepository::new(&self.db);
|
||||
let preferences = prefs_repo
|
||||
.get_or_create(&user.id)
|
||||
.await
|
||||
.map_err(|e| ApiError::Database(format!("Failed to get preferences: {}", e)))?;
|
||||
|
||||
Ok(AuthResponse {
|
||||
token,
|
||||
token: jwt_token,
|
||||
session_token,
|
||||
username: request.username,
|
||||
server_url: request.server_url,
|
||||
preferences: UserPreferencesResponse {
|
||||
calendar_selected_date: preferences.calendar_selected_date,
|
||||
calendar_time_increment: preferences.calendar_time_increment,
|
||||
calendar_view_mode: preferences.calendar_view_mode,
|
||||
calendar_theme: preferences.calendar_theme,
|
||||
calendar_style: preferences.calendar_style,
|
||||
calendar_colors: preferences.calendar_colors,
|
||||
last_used_calendar: preferences.last_used_calendar,
|
||||
},
|
||||
})
|
||||
}
|
||||
Err(err) => {
|
||||
println!("❌ Authentication failed: {:?}", err);
|
||||
// Authentication failed
|
||||
Err(ApiError::Unauthorized("Invalid CalDAV credentials or server unavailable".to_string()))
|
||||
Err(ApiError::Unauthorized(
|
||||
"Invalid CalDAV credentials or server unavailable".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -70,17 +112,30 @@ impl AuthService {
|
||||
self.decode_token(token)
|
||||
}
|
||||
|
||||
/// Create CalDAV config from token
|
||||
pub fn caldav_config_from_token(&self, token: &str, password: &str) -> Result<CalDAVConfig, ApiError> {
|
||||
/// Get user from token
|
||||
pub async fn get_user_from_token(&self, token: &str) -> Result<crate::db::User, ApiError> {
|
||||
let claims = self.verify_token(token)?;
|
||||
|
||||
Ok(CalDAVConfig {
|
||||
server_url: claims.server_url,
|
||||
username: claims.username,
|
||||
password: password.to_string(),
|
||||
calendar_path: None,
|
||||
tasks_path: None,
|
||||
})
|
||||
let user_repo = UserRepository::new(&self.db);
|
||||
user_repo
|
||||
.find_or_create(&claims.username, &claims.server_url)
|
||||
.await
|
||||
.map_err(|e| ApiError::Database(format!("Failed to get user: {}", e)))
|
||||
}
|
||||
|
||||
/// Create CalDAV config from token
|
||||
pub fn caldav_config_from_token(
|
||||
&self,
|
||||
token: &str,
|
||||
password: &str,
|
||||
) -> Result<CalDAVConfig, ApiError> {
|
||||
let claims = self.verify_token(token)?;
|
||||
|
||||
Ok(CalDAVConfig::new(
|
||||
claims.server_url,
|
||||
claims.username,
|
||||
password.to_string(),
|
||||
))
|
||||
}
|
||||
|
||||
fn validate_login(&self, request: &CalDAVLoginRequest) -> Result<(), ApiError> {
|
||||
@@ -97,14 +152,17 @@ impl AuthService {
|
||||
}
|
||||
|
||||
// Basic URL validation
|
||||
if !request.server_url.starts_with("http://") && !request.server_url.starts_with("https://") {
|
||||
return Err(ApiError::BadRequest("Server URL must start with http:// or https://".to_string()));
|
||||
if !request.server_url.starts_with("http://") && !request.server_url.starts_with("https://")
|
||||
{
|
||||
return Err(ApiError::BadRequest(
|
||||
"Server URL must start with http:// or https://".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn generate_token(&self, username: &str, server_url: &str) -> Result<String, ApiError> {
|
||||
pub fn generate_token(&self, username: &str, server_url: &str) -> Result<String, ApiError> {
|
||||
let now = Utc::now();
|
||||
let expires_at = now + Duration::hours(24); // Token valid for 24 hours
|
||||
|
||||
@@ -135,4 +193,33 @@ impl AuthService {
|
||||
|
||||
Ok(token_data.claims)
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate session token
|
||||
pub async fn validate_session(&self, session_token: &str) -> Result<String, ApiError> {
|
||||
let session_repo = SessionRepository::new(&self.db);
|
||||
|
||||
let session = session_repo
|
||||
.find_by_token(session_token)
|
||||
.await
|
||||
.map_err(|e| ApiError::Database(format!("Failed to find session: {}", e)))?
|
||||
.ok_or_else(|| ApiError::Unauthorized("Invalid session token".to_string()))?;
|
||||
|
||||
if session.is_expired() {
|
||||
return Err(ApiError::Unauthorized("Session expired".to_string()));
|
||||
}
|
||||
|
||||
Ok(session.user_id)
|
||||
}
|
||||
|
||||
/// Logout user by deleting session
|
||||
pub async fn logout(&self, session_token: &str) -> Result<(), ApiError> {
|
||||
let session_repo = SessionRepository::new(&self.db);
|
||||
|
||||
session_repo
|
||||
.delete(session_token)
|
||||
.await
|
||||
.map_err(|e| ApiError::Database(format!("Failed to delete session: {}", e)))?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,26 +1,30 @@
|
||||
use base64::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::env;
|
||||
use base64::prelude::*;
|
||||
|
||||
/// Configuration for CalDAV server connection and authentication.
|
||||
///
|
||||
///
|
||||
/// This struct holds all the necessary information to connect to a CalDAV server,
|
||||
/// including server URL, credentials, and optional collection paths.
|
||||
///
|
||||
///
|
||||
/// # Security Note
|
||||
///
|
||||
///
|
||||
/// The password field contains sensitive information and should be handled carefully.
|
||||
/// This struct implements `Debug` but in production, consider implementing a custom
|
||||
/// `Debug` that masks the password field.
|
||||
///
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
///
|
||||
/// ```rust
|
||||
/// use crate::config::CalDAVConfig;
|
||||
///
|
||||
/// // Load configuration from environment variables
|
||||
/// let config = CalDAVConfig::from_env()?;
|
||||
///
|
||||
/// # use calendar_backend::config::CalDAVConfig;
|
||||
/// let config = CalDAVConfig {
|
||||
/// server_url: "https://caldav.example.com".to_string(),
|
||||
/// username: "user@example.com".to_string(),
|
||||
/// password: "password".to_string(),
|
||||
/// calendar_path: None,
|
||||
/// tasks_path: None,
|
||||
/// };
|
||||
///
|
||||
/// // Use the configuration for HTTP requests
|
||||
/// let auth_header = format!("Basic {}", config.get_basic_auth());
|
||||
/// ```
|
||||
@@ -28,103 +32,66 @@ use base64::prelude::*;
|
||||
pub struct CalDAVConfig {
|
||||
/// The base URL of the CalDAV server (e.g., "https://caldav.example.com/dav/")
|
||||
pub server_url: String,
|
||||
|
||||
|
||||
/// Username for authentication with the CalDAV server
|
||||
pub username: String,
|
||||
|
||||
|
||||
/// Password for authentication with the CalDAV server
|
||||
///
|
||||
///
|
||||
/// **Security Note**: This contains sensitive information
|
||||
pub password: String,
|
||||
|
||||
|
||||
/// Optional path to the calendar collection on the server
|
||||
///
|
||||
/// If not provided, the client will need to discover available calendars
|
||||
///
|
||||
/// If not provided, the client will discover available calendars
|
||||
/// through CalDAV PROPFIND requests
|
||||
pub calendar_path: Option<String>,
|
||||
|
||||
/// Optional path to the tasks/todo collection on the server
|
||||
///
|
||||
/// Some CalDAV servers store tasks separately from calendar events
|
||||
pub tasks_path: Option<String>,
|
||||
}
|
||||
|
||||
impl CalDAVConfig {
|
||||
/// Creates a new CalDAVConfig by loading values from environment variables.
|
||||
///
|
||||
/// This method will attempt to load a `.env` file from the current directory
|
||||
/// and then read the following required environment variables:
|
||||
///
|
||||
/// - `CALDAV_SERVER_URL`: The CalDAV server base URL
|
||||
/// - `CALDAV_USERNAME`: Username for authentication
|
||||
/// - `CALDAV_PASSWORD`: Password for authentication
|
||||
///
|
||||
/// Optional environment variables:
|
||||
///
|
||||
/// - `CALDAV_CALENDAR_PATH`: Path to calendar collection
|
||||
/// - `CALDAV_TASKS_PATH`: Path to tasks collection
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `ConfigError::MissingVar` if any required environment variable
|
||||
/// is not set or cannot be read.
|
||||
///
|
||||
/// Creates a new CalDAVConfig with the given credentials.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `server_url` - The base URL of the CalDAV server
|
||||
/// * `username` - Username for authentication
|
||||
/// * `password` - Password for authentication
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
///
|
||||
/// ```rust
|
||||
/// use crate::config::CalDAVConfig;
|
||||
///
|
||||
/// match CalDAVConfig::from_env() {
|
||||
/// Ok(config) => {
|
||||
/// println!("Loaded config for server: {}", config.server_url);
|
||||
/// }
|
||||
/// Err(e) => {
|
||||
/// eprintln!("Failed to load config: {}", e);
|
||||
/// }
|
||||
/// }
|
||||
/// # use calendar_backend::config::CalDAVConfig;
|
||||
/// let config = CalDAVConfig::new(
|
||||
/// "https://caldav.example.com".to_string(),
|
||||
/// "user@example.com".to_string(),
|
||||
/// "password".to_string()
|
||||
/// );
|
||||
/// ```
|
||||
pub fn from_env() -> Result<Self, ConfigError> {
|
||||
// Attempt to load .env file, but don't fail if it doesn't exist
|
||||
dotenvy::dotenv().ok();
|
||||
|
||||
let server_url = env::var("CALDAV_SERVER_URL")
|
||||
.map_err(|_| ConfigError::MissingVar("CALDAV_SERVER_URL".to_string()))?;
|
||||
|
||||
let username = env::var("CALDAV_USERNAME")
|
||||
.map_err(|_| ConfigError::MissingVar("CALDAV_USERNAME".to_string()))?;
|
||||
|
||||
let password = env::var("CALDAV_PASSWORD")
|
||||
.map_err(|_| ConfigError::MissingVar("CALDAV_PASSWORD".to_string()))?;
|
||||
|
||||
// Optional paths - it's fine if these are not set
|
||||
let calendar_path = env::var("CALDAV_CALENDAR_PATH").ok();
|
||||
let tasks_path = env::var("CALDAV_TASKS_PATH").ok();
|
||||
|
||||
Ok(CalDAVConfig {
|
||||
pub fn new(server_url: String, username: String, password: String) -> Self {
|
||||
Self {
|
||||
server_url,
|
||||
username,
|
||||
password,
|
||||
calendar_path,
|
||||
tasks_path,
|
||||
})
|
||||
calendar_path: env::var("CALDAV_CALENDAR_PATH").ok(), // Optional override from env
|
||||
}
|
||||
}
|
||||
|
||||
/// Generates a Base64-encoded string for HTTP Basic Authentication.
|
||||
///
|
||||
///
|
||||
/// This method combines the username and password in the format
|
||||
/// `username:password` and encodes it using Base64, which is the
|
||||
/// standard format for the `Authorization: Basic` HTTP header.
|
||||
///
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
///
|
||||
/// A Base64-encoded string that can be used directly in the
|
||||
/// `Authorization` header: `Authorization: Basic <returned_value>`
|
||||
///
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
///
|
||||
/// ```rust
|
||||
/// use crate::config::CalDAVConfig;
|
||||
///
|
||||
/// # use calendar_backend::config::CalDAVConfig;
|
||||
///
|
||||
/// let config = CalDAVConfig {
|
||||
/// server_url: "https://example.com".to_string(),
|
||||
/// username: "user".to_string(),
|
||||
@@ -132,7 +99,7 @@ impl CalDAVConfig {
|
||||
/// calendar_path: None,
|
||||
/// tasks_path: None,
|
||||
/// };
|
||||
///
|
||||
///
|
||||
/// let auth_value = config.get_basic_auth();
|
||||
/// let auth_header = format!("Basic {}", auth_value);
|
||||
/// ```
|
||||
@@ -146,15 +113,15 @@ impl CalDAVConfig {
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConfigError {
|
||||
/// A required environment variable is missing or cannot be read.
|
||||
///
|
||||
///
|
||||
/// This error occurs when calling `CalDAVConfig::from_env()` and one of the
|
||||
/// required environment variables (`CALDAV_SERVER_URL`, `CALDAV_USERNAME`,
|
||||
/// or `CALDAV_PASSWORD`) is not set.
|
||||
#[error("Missing environment variable: {0}")]
|
||||
MissingVar(String),
|
||||
|
||||
|
||||
/// The configuration contains invalid or malformed values.
|
||||
///
|
||||
///
|
||||
/// This could include malformed URLs, invalid authentication credentials,
|
||||
/// or other configuration issues that prevent proper CalDAV operation.
|
||||
#[error("Invalid configuration: {0}")]
|
||||
@@ -172,7 +139,6 @@ mod tests {
|
||||
username: "testuser".to_string(),
|
||||
password: "testpass".to_string(),
|
||||
calendar_path: None,
|
||||
tasks_path: None,
|
||||
};
|
||||
|
||||
let auth = config.get_basic_auth();
|
||||
@@ -181,18 +147,21 @@ mod tests {
|
||||
}
|
||||
|
||||
/// Integration test that authenticates with the actual Baikal CalDAV server
|
||||
///
|
||||
///
|
||||
/// This test requires a valid .env file with:
|
||||
/// - CALDAV_SERVER_URL
|
||||
/// - CALDAV_USERNAME
|
||||
/// - CALDAV_PASSWORD
|
||||
///
|
||||
///
|
||||
/// Run with: `cargo test test_baikal_auth`
|
||||
#[tokio::test]
|
||||
async fn test_baikal_auth() {
|
||||
// Load config from .env
|
||||
let config = CalDAVConfig::from_env()
|
||||
.expect("Failed to load CalDAV config from environment");
|
||||
// Use test config - update these values to test with real server
|
||||
let config = CalDAVConfig::new(
|
||||
"https://example.com".to_string(),
|
||||
"test_user".to_string(),
|
||||
"test_password".to_string(),
|
||||
);
|
||||
|
||||
println!("Testing authentication to: {}", config.server_url);
|
||||
|
||||
@@ -202,7 +171,10 @@ mod tests {
|
||||
// Make a simple OPTIONS request to test authentication
|
||||
let response = client
|
||||
.request(reqwest::Method::OPTIONS, &config.server_url)
|
||||
.header("Authorization", format!("Basic {}", config.get_basic_auth()))
|
||||
.header(
|
||||
"Authorization",
|
||||
format!("Basic {}", config.get_basic_auth()),
|
||||
)
|
||||
.header("User-Agent", "calendar-app/0.1.0")
|
||||
.send()
|
||||
.await
|
||||
@@ -220,9 +192,9 @@ mod tests {
|
||||
|
||||
// For Baikal/CalDAV servers, we should see DAV headers
|
||||
assert!(
|
||||
response.headers().contains_key("dav") ||
|
||||
response.headers().contains_key("DAV") ||
|
||||
response.status().is_success(),
|
||||
response.headers().contains_key("dav")
|
||||
|| response.headers().contains_key("DAV")
|
||||
|| response.status().is_success(),
|
||||
"Server doesn't appear to be a CalDAV server - missing DAV headers"
|
||||
);
|
||||
|
||||
@@ -230,14 +202,18 @@ mod tests {
|
||||
}
|
||||
|
||||
/// Test making a PROPFIND request to discover calendars
|
||||
///
|
||||
///
|
||||
/// This test requires a valid .env file and makes an actual CalDAV PROPFIND request
|
||||
///
|
||||
///
|
||||
/// Run with: `cargo test test_propfind_calendars`
|
||||
#[tokio::test]
|
||||
async fn test_propfind_calendars() {
|
||||
let config = CalDAVConfig::from_env()
|
||||
.expect("Failed to load CalDAV config from environment");
|
||||
// Use test config - update these values to test with real server
|
||||
let config = CalDAVConfig::new(
|
||||
"https://example.com".to_string(),
|
||||
"test_user".to_string(),
|
||||
"test_password".to_string(),
|
||||
);
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
|
||||
@@ -253,8 +229,14 @@ mod tests {
|
||||
</d:propfind>"#;
|
||||
|
||||
let response = client
|
||||
.request(reqwest::Method::from_bytes(b"PROPFIND").unwrap(), &config.server_url)
|
||||
.header("Authorization", format!("Basic {}", config.get_basic_auth()))
|
||||
.request(
|
||||
reqwest::Method::from_bytes(b"PROPFIND").unwrap(),
|
||||
&config.server_url,
|
||||
)
|
||||
.header(
|
||||
"Authorization",
|
||||
format!("Basic {}", config.get_basic_auth()),
|
||||
)
|
||||
.header("Content-Type", "application/xml")
|
||||
.header("Depth", "1")
|
||||
.header("User-Agent", "calendar-app/0.1.0")
|
||||
@@ -265,7 +247,7 @@ mod tests {
|
||||
|
||||
let status = response.status();
|
||||
println!("PROPFIND Response status: {}", status);
|
||||
|
||||
|
||||
let body = response.text().await.expect("Failed to read response body");
|
||||
println!("PROPFIND Response body: {}", body);
|
||||
|
||||
@@ -277,8 +259,11 @@ mod tests {
|
||||
);
|
||||
|
||||
// The response should contain XML with calendar information
|
||||
assert!(body.contains("calendar"), "Response should contain calendar information");
|
||||
assert!(
|
||||
body.contains("calendar"),
|
||||
"Response should contain calendar information"
|
||||
);
|
||||
|
||||
println!("✓ PROPFIND calendars test passed!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
488
backend/src/db.rs
Normal file
488
backend/src/db.rs
Normal file
@@ -0,0 +1,488 @@
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sqlx::sqlite::{SqlitePool, SqlitePoolOptions};
|
||||
use sqlx::{FromRow, Result};
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Database connection pool wrapper
|
||||
#[derive(Clone)]
|
||||
pub struct Database {
|
||||
pool: Arc<SqlitePool>,
|
||||
}
|
||||
|
||||
impl Database {
|
||||
/// Create a new database connection pool
|
||||
pub async fn new(database_url: &str) -> Result<Self> {
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.max_connections(5)
|
||||
.connect(database_url)
|
||||
.await?;
|
||||
|
||||
// Run migrations
|
||||
sqlx::migrate!("./migrations").run(&pool).await?;
|
||||
|
||||
Ok(Self {
|
||||
pool: Arc::new(pool),
|
||||
})
|
||||
}
|
||||
|
||||
/// Get a reference to the connection pool
|
||||
pub fn pool(&self) -> &SqlitePool {
|
||||
&self.pool
|
||||
}
|
||||
}
|
||||
|
||||
/// User model representing a CalDAV user
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
|
||||
pub struct User {
|
||||
pub id: String, // UUID as string for SQLite
|
||||
pub username: String,
|
||||
pub server_url: String,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl User {
|
||||
/// Create a new user with generated UUID
|
||||
pub fn new(username: String, server_url: String) -> Self {
|
||||
Self {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
username,
|
||||
server_url,
|
||||
created_at: Utc::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Session model for user sessions
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
|
||||
pub struct Session {
|
||||
pub id: String, // UUID as string
|
||||
pub user_id: String, // Foreign key to User
|
||||
pub token: String, // Session token
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
pub last_accessed: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Create a new session for a user
|
||||
pub fn new(user_id: String, token: String, expires_in_hours: i64) -> Self {
|
||||
let now = Utc::now();
|
||||
Self {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
user_id,
|
||||
token,
|
||||
created_at: now,
|
||||
expires_at: now + chrono::Duration::hours(expires_in_hours),
|
||||
last_accessed: now,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if the session has expired
|
||||
pub fn is_expired(&self) -> bool {
|
||||
Utc::now() > self.expires_at
|
||||
}
|
||||
}
|
||||
|
||||
/// User preferences model
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
|
||||
pub struct UserPreferences {
|
||||
pub user_id: String,
|
||||
pub calendar_selected_date: Option<String>,
|
||||
pub calendar_time_increment: Option<i32>,
|
||||
pub calendar_view_mode: Option<String>,
|
||||
pub calendar_theme: Option<String>,
|
||||
pub calendar_style: Option<String>,
|
||||
pub calendar_colors: Option<String>, // JSON string
|
||||
pub last_used_calendar: Option<String>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// External calendar model
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
|
||||
pub struct ExternalCalendar {
|
||||
pub id: i32,
|
||||
pub user_id: String,
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
pub color: String,
|
||||
pub is_visible: bool,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
pub last_fetched: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
impl ExternalCalendar {
|
||||
/// Create a new external calendar
|
||||
pub fn new(user_id: String, name: String, url: String, color: String) -> Self {
|
||||
let now = Utc::now();
|
||||
Self {
|
||||
id: 0, // Will be set by database
|
||||
user_id,
|
||||
name,
|
||||
url,
|
||||
color,
|
||||
is_visible: true,
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
last_fetched: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UserPreferences {
|
||||
/// Create default preferences for a new user
|
||||
pub fn default_for_user(user_id: String) -> Self {
|
||||
Self {
|
||||
user_id,
|
||||
calendar_selected_date: None,
|
||||
calendar_time_increment: Some(15),
|
||||
calendar_view_mode: Some("month".to_string()),
|
||||
calendar_theme: Some("light".to_string()),
|
||||
calendar_style: Some("default".to_string()),
|
||||
calendar_colors: None,
|
||||
last_used_calendar: None,
|
||||
updated_at: Utc::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Repository for User operations
|
||||
pub struct UserRepository<'a> {
|
||||
db: &'a Database,
|
||||
}
|
||||
|
||||
impl<'a> UserRepository<'a> {
|
||||
pub fn new(db: &'a Database) -> Self {
|
||||
Self { db }
|
||||
}
|
||||
|
||||
/// Find or create a user by username and server URL
|
||||
pub async fn find_or_create(
|
||||
&self,
|
||||
username: &str,
|
||||
server_url: &str,
|
||||
) -> Result<User> {
|
||||
// Try to find existing user
|
||||
let existing = sqlx::query_as::<_, User>(
|
||||
"SELECT * FROM users WHERE username = ? AND server_url = ?",
|
||||
)
|
||||
.bind(username)
|
||||
.bind(server_url)
|
||||
.fetch_optional(self.db.pool())
|
||||
.await?;
|
||||
|
||||
if let Some(user) = existing {
|
||||
Ok(user)
|
||||
} else {
|
||||
// Create new user
|
||||
let user = User::new(username.to_string(), server_url.to_string());
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO users (id, username, server_url, created_at) VALUES (?, ?, ?, ?)",
|
||||
)
|
||||
.bind(&user.id)
|
||||
.bind(&user.username)
|
||||
.bind(&user.server_url)
|
||||
.bind(&user.created_at)
|
||||
.execute(self.db.pool())
|
||||
.await?;
|
||||
|
||||
Ok(user)
|
||||
}
|
||||
}
|
||||
|
||||
/// Find a user by ID
|
||||
pub async fn find_by_id(&self, user_id: &str) -> Result<Option<User>> {
|
||||
sqlx::query_as::<_, User>("SELECT * FROM users WHERE id = ?")
|
||||
.bind(user_id)
|
||||
.fetch_optional(self.db.pool())
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
/// Repository for Session operations
|
||||
pub struct SessionRepository<'a> {
|
||||
db: &'a Database,
|
||||
}
|
||||
|
||||
impl<'a> SessionRepository<'a> {
|
||||
pub fn new(db: &'a Database) -> Self {
|
||||
Self { db }
|
||||
}
|
||||
|
||||
/// Create a new session
|
||||
pub async fn create(&self, session: &Session) -> Result<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO sessions (id, user_id, token, created_at, expires_at, last_accessed)
|
||||
VALUES (?, ?, ?, ?, ?, ?)",
|
||||
)
|
||||
.bind(&session.id)
|
||||
.bind(&session.user_id)
|
||||
.bind(&session.token)
|
||||
.bind(&session.created_at)
|
||||
.bind(&session.expires_at)
|
||||
.bind(&session.last_accessed)
|
||||
.execute(self.db.pool())
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Find a session by token and update last_accessed
|
||||
pub async fn find_by_token(&self, token: &str) -> Result<Option<Session>> {
|
||||
let session = sqlx::query_as::<_, Session>("SELECT * FROM sessions WHERE token = ?")
|
||||
.bind(token)
|
||||
.fetch_optional(self.db.pool())
|
||||
.await?;
|
||||
|
||||
if let Some(ref s) = session {
|
||||
if !s.is_expired() {
|
||||
// Update last_accessed time
|
||||
sqlx::query("UPDATE sessions SET last_accessed = ? WHERE id = ?")
|
||||
.bind(Utc::now())
|
||||
.bind(&s.id)
|
||||
.execute(self.db.pool())
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
/// Delete a session (logout)
|
||||
pub async fn delete(&self, token: &str) -> Result<()> {
|
||||
sqlx::query("DELETE FROM sessions WHERE token = ?")
|
||||
.bind(token)
|
||||
.execute(self.db.pool())
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Clean up expired sessions
|
||||
pub async fn cleanup_expired(&self) -> Result<u64> {
|
||||
let result = sqlx::query("DELETE FROM sessions WHERE expires_at < ?")
|
||||
.bind(Utc::now())
|
||||
.execute(self.db.pool())
|
||||
.await?;
|
||||
|
||||
Ok(result.rows_affected())
|
||||
}
|
||||
}
|
||||
|
||||
/// Repository for UserPreferences operations
|
||||
pub struct PreferencesRepository<'a> {
|
||||
db: &'a Database,
|
||||
}
|
||||
|
||||
impl<'a> PreferencesRepository<'a> {
|
||||
pub fn new(db: &'a Database) -> Self {
|
||||
Self { db }
|
||||
}
|
||||
|
||||
/// Get user preferences, creating defaults if not exist
|
||||
pub async fn get_or_create(&self, user_id: &str) -> Result<UserPreferences> {
|
||||
let existing = sqlx::query_as::<_, UserPreferences>(
|
||||
"SELECT * FROM user_preferences WHERE user_id = ?",
|
||||
)
|
||||
.bind(user_id)
|
||||
.fetch_optional(self.db.pool())
|
||||
.await?;
|
||||
|
||||
if let Some(prefs) = existing {
|
||||
Ok(prefs)
|
||||
} else {
|
||||
// Create default preferences
|
||||
let prefs = UserPreferences::default_for_user(user_id.to_string());
|
||||
|
||||
sqlx::query(
|
||||
"INSERT INTO user_preferences
|
||||
(user_id, calendar_selected_date, calendar_time_increment,
|
||||
calendar_view_mode, calendar_theme, calendar_style, calendar_colors, last_used_calendar, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
)
|
||||
.bind(&prefs.user_id)
|
||||
.bind(&prefs.calendar_selected_date)
|
||||
.bind(&prefs.calendar_time_increment)
|
||||
.bind(&prefs.calendar_view_mode)
|
||||
.bind(&prefs.calendar_theme)
|
||||
.bind(&prefs.calendar_style)
|
||||
.bind(&prefs.calendar_colors)
|
||||
.bind(&prefs.last_used_calendar)
|
||||
.bind(&prefs.updated_at)
|
||||
.execute(self.db.pool())
|
||||
.await?;
|
||||
|
||||
Ok(prefs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Update user preferences
|
||||
pub async fn update(&self, prefs: &UserPreferences) -> Result<()> {
|
||||
sqlx::query(
|
||||
"UPDATE user_preferences
|
||||
SET calendar_selected_date = ?, calendar_time_increment = ?,
|
||||
calendar_view_mode = ?, calendar_theme = ?, calendar_style = ?,
|
||||
calendar_colors = ?, last_used_calendar = ?, updated_at = ?
|
||||
WHERE user_id = ?",
|
||||
)
|
||||
.bind(&prefs.calendar_selected_date)
|
||||
.bind(&prefs.calendar_time_increment)
|
||||
.bind(&prefs.calendar_view_mode)
|
||||
.bind(&prefs.calendar_theme)
|
||||
.bind(&prefs.calendar_style)
|
||||
.bind(&prefs.calendar_colors)
|
||||
.bind(&prefs.last_used_calendar)
|
||||
.bind(Utc::now())
|
||||
.bind(&prefs.user_id)
|
||||
.execute(self.db.pool())
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Repository for ExternalCalendar operations
|
||||
pub struct ExternalCalendarRepository<'a> {
|
||||
db: &'a Database,
|
||||
}
|
||||
|
||||
impl<'a> ExternalCalendarRepository<'a> {
|
||||
pub fn new(db: &'a Database) -> Self {
|
||||
Self { db }
|
||||
}
|
||||
|
||||
/// Get all external calendars for a user
|
||||
pub async fn get_by_user(&self, user_id: &str) -> Result<Vec<ExternalCalendar>> {
|
||||
sqlx::query_as::<_, ExternalCalendar>(
|
||||
"SELECT * FROM external_calendars WHERE user_id = ? ORDER BY created_at ASC",
|
||||
)
|
||||
.bind(user_id)
|
||||
.fetch_all(self.db.pool())
|
||||
.await
|
||||
}
|
||||
|
||||
/// Create a new external calendar
|
||||
pub async fn create(&self, calendar: &ExternalCalendar) -> Result<i32> {
|
||||
let result = sqlx::query(
|
||||
"INSERT INTO external_calendars (user_id, name, url, color, is_visible, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
)
|
||||
.bind(&calendar.user_id)
|
||||
.bind(&calendar.name)
|
||||
.bind(&calendar.url)
|
||||
.bind(&calendar.color)
|
||||
.bind(&calendar.is_visible)
|
||||
.bind(&calendar.created_at)
|
||||
.bind(&calendar.updated_at)
|
||||
.execute(self.db.pool())
|
||||
.await?;
|
||||
|
||||
Ok(result.last_insert_rowid() as i32)
|
||||
}
|
||||
|
||||
/// Update an external calendar
|
||||
pub async fn update(&self, id: i32, calendar: &ExternalCalendar) -> Result<()> {
|
||||
sqlx::query(
|
||||
"UPDATE external_calendars
|
||||
SET name = ?, url = ?, color = ?, is_visible = ?, updated_at = ?
|
||||
WHERE id = ? AND user_id = ?",
|
||||
)
|
||||
.bind(&calendar.name)
|
||||
.bind(&calendar.url)
|
||||
.bind(&calendar.color)
|
||||
.bind(&calendar.is_visible)
|
||||
.bind(Utc::now())
|
||||
.bind(id)
|
||||
.bind(&calendar.user_id)
|
||||
.execute(self.db.pool())
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete an external calendar
|
||||
pub async fn delete(&self, id: i32, user_id: &str) -> Result<()> {
|
||||
sqlx::query("DELETE FROM external_calendars WHERE id = ? AND user_id = ?")
|
||||
.bind(id)
|
||||
.bind(user_id)
|
||||
.execute(self.db.pool())
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Update last_fetched timestamp
|
||||
pub async fn update_last_fetched(&self, id: i32, user_id: &str) -> Result<()> {
|
||||
sqlx::query(
|
||||
"UPDATE external_calendars SET last_fetched = ? WHERE id = ? AND user_id = ?",
|
||||
)
|
||||
.bind(Utc::now())
|
||||
.bind(id)
|
||||
.bind(user_id)
|
||||
.execute(self.db.pool())
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get cached ICS data for an external calendar
|
||||
pub async fn get_cached_data(&self, external_calendar_id: i32) -> Result<Option<(String, DateTime<Utc>)>> {
|
||||
let result = sqlx::query_as::<_, (String, DateTime<Utc>)>(
|
||||
"SELECT ics_data, cached_at FROM external_calendar_cache WHERE external_calendar_id = ?",
|
||||
)
|
||||
.bind(external_calendar_id)
|
||||
.fetch_optional(self.db.pool())
|
||||
.await?;
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Update cache with new ICS data
|
||||
pub async fn update_cache(&self, external_calendar_id: i32, ics_data: &str, etag: Option<&str>) -> Result<()> {
|
||||
sqlx::query(
|
||||
"INSERT INTO external_calendar_cache (external_calendar_id, ics_data, etag, cached_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON CONFLICT(external_calendar_id) DO UPDATE SET
|
||||
ics_data = excluded.ics_data,
|
||||
etag = excluded.etag,
|
||||
cached_at = excluded.cached_at",
|
||||
)
|
||||
.bind(external_calendar_id)
|
||||
.bind(ics_data)
|
||||
.bind(etag)
|
||||
.bind(Utc::now())
|
||||
.execute(self.db.pool())
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check if cache is stale (older than max_age_minutes)
|
||||
pub async fn is_cache_stale(&self, external_calendar_id: i32, max_age_minutes: i64) -> Result<bool> {
|
||||
let cutoff_time = Utc::now() - Duration::minutes(max_age_minutes);
|
||||
|
||||
let result = sqlx::query_scalar::<_, i64>(
|
||||
"SELECT COUNT(*) FROM external_calendar_cache
|
||||
WHERE external_calendar_id = ? AND cached_at > ?",
|
||||
)
|
||||
.bind(external_calendar_id)
|
||||
.bind(cutoff_time)
|
||||
.fetch_one(self.db.pool())
|
||||
.await?;
|
||||
|
||||
Ok(result == 0)
|
||||
}
|
||||
|
||||
/// Clear cache for an external calendar
|
||||
pub async fn clear_cache(&self, external_calendar_id: i32) -> Result<()> {
|
||||
sqlx::query("DELETE FROM external_calendar_cache WHERE external_calendar_id = ?")
|
||||
.bind(external_calendar_id)
|
||||
.execute(self.db.pool())
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,12 @@ use crate::calendar::CalDAVClient;
|
||||
use crate::config::CalDAVConfig;
|
||||
|
||||
pub async fn debug_caldav_fetch() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let config = CalDAVConfig::from_env()?;
|
||||
// Use debug/test configuration
|
||||
let config = CalDAVConfig::new(
|
||||
"https://example.com".to_string(),
|
||||
"debug_user".to_string(),
|
||||
"debug_password".to_string()
|
||||
);
|
||||
let client = CalDAVClient::new(config);
|
||||
|
||||
println!("=== DEBUG: CalDAV Fetch ===");
|
||||
|
||||
@@ -1,608 +0,0 @@
|
||||
use axum::{
|
||||
extract::{State, Query, Path},
|
||||
http::HeaderMap,
|
||||
response::Json,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use std::sync::Arc;
|
||||
use chrono::Datelike;
|
||||
|
||||
use crate::{AppState, models::{CalDAVLoginRequest, AuthResponse, ApiError, UserInfo, CalendarInfo, CreateCalendarRequest, CreateCalendarResponse, DeleteCalendarRequest, DeleteCalendarResponse, DeleteEventRequest, DeleteEventResponse, CreateEventRequest, CreateEventResponse}};
|
||||
use crate::calendar::{CalDAVClient, CalendarEvent};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CalendarQuery {
|
||||
pub year: Option<i32>,
|
||||
pub month: Option<u32>,
|
||||
}
|
||||
|
||||
pub async fn get_calendar_events(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Query(params): Query<CalendarQuery>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<Vec<CalendarEvent>>, ApiError> {
|
||||
// Extract and verify token
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let password = extract_password_header(&headers)?;
|
||||
println!("🔑 API call with password length: {}", password.len());
|
||||
|
||||
// Create CalDAV config from token and password
|
||||
let config = state.auth_service.caldav_config_from_token(&token, &password)?;
|
||||
let client = CalDAVClient::new(config);
|
||||
|
||||
// Discover calendars if needed
|
||||
let calendar_paths = client.discover_calendars()
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to discover calendars: {}", e)))?;
|
||||
|
||||
if calendar_paths.is_empty() {
|
||||
return Ok(Json(vec![])); // No calendars found
|
||||
}
|
||||
|
||||
// Fetch events from the first calendar
|
||||
let calendar_path = &calendar_paths[0];
|
||||
let events = client.fetch_events(calendar_path)
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to fetch events: {}", e)))?;
|
||||
|
||||
// Filter events by month if specified
|
||||
let filtered_events = if let (Some(year), Some(month)) = (params.year, params.month) {
|
||||
events.into_iter().filter(|event| {
|
||||
let event_date = event.start.date_naive();
|
||||
event_date.year() == year && event_date.month() == month
|
||||
}).collect()
|
||||
} else {
|
||||
events
|
||||
};
|
||||
|
||||
Ok(Json(filtered_events))
|
||||
}
|
||||
|
||||
pub async fn refresh_event(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Path(uid): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<Option<CalendarEvent>>, ApiError> {
|
||||
// Extract and verify token
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let password = extract_password_header(&headers)?;
|
||||
|
||||
// Create CalDAV config from token and password
|
||||
let config = state.auth_service.caldav_config_from_token(&token, &password)?;
|
||||
let client = CalDAVClient::new(config);
|
||||
|
||||
// Discover calendars if needed
|
||||
let calendar_paths = client.discover_calendars()
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to discover calendars: {}", e)))?;
|
||||
|
||||
if calendar_paths.is_empty() {
|
||||
return Ok(Json(None)); // No calendars found
|
||||
}
|
||||
|
||||
// Fetch the specific event by UID from the first calendar
|
||||
let calendar_path = &calendar_paths[0];
|
||||
let event = client.fetch_event_by_uid(calendar_path, &uid)
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to fetch event: {}", e)))?;
|
||||
|
||||
Ok(Json(event))
|
||||
}
|
||||
|
||||
pub async fn login(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Json(request): Json<CalDAVLoginRequest>,
|
||||
) -> Result<Json<AuthResponse>, ApiError> {
|
||||
println!("🔐 Login attempt:");
|
||||
println!(" Server URL: {}", request.server_url);
|
||||
println!(" Username: {}", request.username);
|
||||
println!(" Password length: {}", request.password.len());
|
||||
|
||||
let response = state.auth_service.login(request).await?;
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
pub async fn verify_token(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<serde_json::Value>, ApiError> {
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let claims = state.auth_service.verify_token(&token)?;
|
||||
|
||||
Ok(Json(serde_json::json!({
|
||||
"valid": true,
|
||||
"username": claims.username,
|
||||
"server_url": claims.server_url
|
||||
})))
|
||||
}
|
||||
|
||||
pub async fn get_user_info(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<UserInfo>, ApiError> {
|
||||
// Extract and verify token
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let password = extract_password_header(&headers)?;
|
||||
let claims = state.auth_service.verify_token(&token)?;
|
||||
|
||||
// Create CalDAV config from token and password
|
||||
let config = state.auth_service.caldav_config_from_token(&token, &password)?;
|
||||
let client = CalDAVClient::new(config);
|
||||
|
||||
// Discover calendars
|
||||
let calendar_paths = client.discover_calendars()
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to discover calendars: {}", e)))?;
|
||||
|
||||
// Convert paths to CalendarInfo structs with display names, filtering out generic collections
|
||||
let calendars: Vec<CalendarInfo> = calendar_paths.into_iter()
|
||||
.filter_map(|path| {
|
||||
let display_name = extract_calendar_name(&path);
|
||||
// Skip generic collection names
|
||||
if display_name.eq_ignore_ascii_case("calendar") ||
|
||||
display_name.eq_ignore_ascii_case("calendars") ||
|
||||
display_name.eq_ignore_ascii_case("collection") {
|
||||
None
|
||||
} else {
|
||||
Some(CalendarInfo {
|
||||
path: path.clone(),
|
||||
display_name,
|
||||
color: generate_calendar_color(&path),
|
||||
})
|
||||
}
|
||||
}).collect();
|
||||
|
||||
Ok(Json(UserInfo {
|
||||
username: claims.username,
|
||||
server_url: claims.server_url,
|
||||
calendars,
|
||||
}))
|
||||
}
|
||||
|
||||
// Helper function to generate a consistent color for a calendar based on its path
|
||||
fn generate_calendar_color(path: &str) -> String {
|
||||
// Predefined set of attractive, accessible colors for calendars
|
||||
let colors = [
|
||||
"#3B82F6", // Blue
|
||||
"#10B981", // Emerald
|
||||
"#F59E0B", // Amber
|
||||
"#EF4444", // Red
|
||||
"#8B5CF6", // Violet
|
||||
"#06B6D4", // Cyan
|
||||
"#84CC16", // Lime
|
||||
"#F97316", // Orange
|
||||
"#EC4899", // Pink
|
||||
"#6366F1", // Indigo
|
||||
"#14B8A6", // Teal
|
||||
"#F3B806", // Yellow
|
||||
"#8B5A2B", // Brown
|
||||
"#6B7280", // Gray
|
||||
"#DC2626", // Red-600
|
||||
"#7C3AED", // Violet-600
|
||||
];
|
||||
|
||||
// Create a simple hash from the path to ensure consistent color assignment
|
||||
let mut hash: u32 = 0;
|
||||
for byte in path.bytes() {
|
||||
hash = hash.wrapping_mul(31).wrapping_add(byte as u32);
|
||||
}
|
||||
|
||||
// Use the hash to select a color from our palette
|
||||
let color_index = (hash as usize) % colors.len();
|
||||
colors[color_index].to_string()
|
||||
}
|
||||
|
||||
// Helper function to extract a readable calendar name from path
|
||||
fn extract_calendar_name(path: &str) -> String {
|
||||
// Extract the last meaningful part of the path
|
||||
// e.g., "/calendars/user/personal/" -> "personal"
|
||||
// or "/calendars/user/work-calendar/" -> "work-calendar"
|
||||
let parts: Vec<&str> = path.trim_end_matches('/').split('/').collect();
|
||||
|
||||
if let Some(last_part) = parts.last() {
|
||||
if !last_part.is_empty() && *last_part != "calendars" {
|
||||
// Convert kebab-case or snake_case to title case
|
||||
last_part
|
||||
.replace('-', " ")
|
||||
.replace('_', " ")
|
||||
.split_whitespace()
|
||||
.map(|word| {
|
||||
let mut chars = word.chars();
|
||||
match chars.next() {
|
||||
None => String::new(),
|
||||
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
} else if parts.len() > 1 {
|
||||
// If the last part is empty or "calendars", try the second to last
|
||||
extract_calendar_name(&parts[..parts.len()-1].join("/"))
|
||||
} else {
|
||||
"Calendar".to_string()
|
||||
}
|
||||
} else {
|
||||
"Calendar".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
fn extract_bearer_token(headers: &HeaderMap) -> Result<String, ApiError> {
|
||||
if let Some(auth_header) = headers.get("authorization") {
|
||||
let auth_str = auth_header
|
||||
.to_str()
|
||||
.map_err(|_| ApiError::Unauthorized("Invalid authorization header".to_string()))?;
|
||||
|
||||
if let Some(token) = auth_str.strip_prefix("Bearer ") {
|
||||
Ok(token.to_string())
|
||||
} else {
|
||||
Err(ApiError::Unauthorized("Authorization header must start with 'Bearer '".to_string()))
|
||||
}
|
||||
} else {
|
||||
Err(ApiError::Unauthorized("Authorization header required".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_password_header(headers: &HeaderMap) -> Result<String, ApiError> {
|
||||
if let Some(password_header) = headers.get("x-caldav-password") {
|
||||
let password = password_header
|
||||
.to_str()
|
||||
.map_err(|_| ApiError::BadRequest("Invalid password header".to_string()))?;
|
||||
Ok(password.to_string())
|
||||
} else {
|
||||
Err(ApiError::BadRequest("X-CalDAV-Password header required".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_calendar(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(request): Json<CreateCalendarRequest>,
|
||||
) -> Result<Json<CreateCalendarResponse>, ApiError> {
|
||||
println!("📝 Create calendar request received: name='{}', description={:?}, color={:?}",
|
||||
request.name, request.description, request.color);
|
||||
|
||||
// Extract and verify token
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let password = extract_password_header(&headers)?;
|
||||
|
||||
// Validate request
|
||||
if request.name.trim().is_empty() {
|
||||
return Err(ApiError::BadRequest("Calendar name is required".to_string()));
|
||||
}
|
||||
|
||||
if request.name.len() > 100 {
|
||||
return Err(ApiError::BadRequest("Calendar name too long (max 100 characters)".to_string()));
|
||||
}
|
||||
|
||||
// Create CalDAV config from token and password
|
||||
let config = state.auth_service.caldav_config_from_token(&token, &password)?;
|
||||
let client = CalDAVClient::new(config);
|
||||
|
||||
// Create the calendar
|
||||
client.create_calendar(
|
||||
&request.name,
|
||||
request.description.as_deref(),
|
||||
request.color.as_deref()
|
||||
)
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to create calendar: {}", e)))?;
|
||||
|
||||
Ok(Json(CreateCalendarResponse {
|
||||
success: true,
|
||||
message: "Calendar created successfully".to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn delete_calendar(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(request): Json<DeleteCalendarRequest>,
|
||||
) -> Result<Json<DeleteCalendarResponse>, ApiError> {
|
||||
println!("🗑️ Delete calendar request received: path='{}'", request.path);
|
||||
|
||||
// Extract and verify token
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let password = extract_password_header(&headers)?;
|
||||
|
||||
// Validate request
|
||||
if request.path.trim().is_empty() {
|
||||
return Err(ApiError::BadRequest("Calendar path is required".to_string()));
|
||||
}
|
||||
|
||||
// Create CalDAV config from token and password
|
||||
let config = state.auth_service.caldav_config_from_token(&token, &password)?;
|
||||
let client = CalDAVClient::new(config);
|
||||
|
||||
// Delete the calendar
|
||||
client.delete_calendar(&request.path)
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to delete calendar: {}", e)))?;
|
||||
|
||||
Ok(Json(DeleteCalendarResponse {
|
||||
success: true,
|
||||
message: "Calendar deleted successfully".to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn delete_event(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(request): Json<DeleteEventRequest>,
|
||||
) -> Result<Json<DeleteEventResponse>, ApiError> {
|
||||
println!("🗑️ Delete event request received: calendar_path='{}', event_href='{}'", request.calendar_path, request.event_href);
|
||||
|
||||
// Extract and verify token
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let password = extract_password_header(&headers)?;
|
||||
|
||||
// Validate request
|
||||
if request.calendar_path.trim().is_empty() {
|
||||
return Err(ApiError::BadRequest("Calendar path is required".to_string()));
|
||||
}
|
||||
if request.event_href.trim().is_empty() {
|
||||
return Err(ApiError::BadRequest("Event href is required".to_string()));
|
||||
}
|
||||
|
||||
// Create CalDAV config from token and password
|
||||
let config = state.auth_service.caldav_config_from_token(&token, &password)?;
|
||||
let client = CalDAVClient::new(config);
|
||||
|
||||
// Delete the event
|
||||
client.delete_event(&request.calendar_path, &request.event_href)
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to delete event: {}", e)))?;
|
||||
|
||||
Ok(Json(DeleteEventResponse {
|
||||
success: true,
|
||||
message: "Event deleted successfully".to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn create_event(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(request): Json<CreateEventRequest>,
|
||||
) -> Result<Json<CreateEventResponse>, ApiError> {
|
||||
println!("📝 Create event request received: title='{}', all_day={}, calendar_path={:?}",
|
||||
request.title, request.all_day, request.calendar_path);
|
||||
|
||||
// Extract and verify token
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let password = extract_password_header(&headers)?;
|
||||
|
||||
// Validate request
|
||||
if request.title.trim().is_empty() {
|
||||
return Err(ApiError::BadRequest("Event title is required".to_string()));
|
||||
}
|
||||
|
||||
if request.title.len() > 200 {
|
||||
return Err(ApiError::BadRequest("Event title too long (max 200 characters)".to_string()));
|
||||
}
|
||||
|
||||
// Create CalDAV config from token and password
|
||||
let config = state.auth_service.caldav_config_from_token(&token, &password)?;
|
||||
let client = CalDAVClient::new(config);
|
||||
|
||||
// Determine which calendar to use
|
||||
let calendar_path = if let Some(path) = request.calendar_path {
|
||||
path
|
||||
} else {
|
||||
// Use the first available calendar
|
||||
let calendar_paths = client.discover_calendars()
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to discover calendars: {}", e)))?;
|
||||
|
||||
if calendar_paths.is_empty() {
|
||||
return Err(ApiError::BadRequest("No calendars available for event creation".to_string()));
|
||||
}
|
||||
|
||||
calendar_paths[0].clone()
|
||||
};
|
||||
|
||||
// Parse dates and times
|
||||
let start_datetime = parse_event_datetime(&request.start_date, &request.start_time, request.all_day)
|
||||
.map_err(|e| ApiError::BadRequest(format!("Invalid start date/time: {}", e)))?;
|
||||
|
||||
let end_datetime = parse_event_datetime(&request.end_date, &request.end_time, request.all_day)
|
||||
.map_err(|e| ApiError::BadRequest(format!("Invalid end date/time: {}", e)))?;
|
||||
|
||||
// Validate that end is after start
|
||||
if end_datetime <= start_datetime {
|
||||
return Err(ApiError::BadRequest("End date/time must be after start date/time".to_string()));
|
||||
}
|
||||
|
||||
// Generate a unique UID for the event
|
||||
let uid = format!("{}-{}", uuid::Uuid::new_v4(), chrono::Utc::now().timestamp());
|
||||
|
||||
// Parse status
|
||||
let status = match request.status.to_lowercase().as_str() {
|
||||
"tentative" => crate::calendar::EventStatus::Tentative,
|
||||
"cancelled" => crate::calendar::EventStatus::Cancelled,
|
||||
_ => crate::calendar::EventStatus::Confirmed,
|
||||
};
|
||||
|
||||
// Parse class
|
||||
let class = match request.class.to_lowercase().as_str() {
|
||||
"private" => crate::calendar::EventClass::Private,
|
||||
"confidential" => crate::calendar::EventClass::Confidential,
|
||||
_ => crate::calendar::EventClass::Public,
|
||||
};
|
||||
|
||||
// Parse attendees (comma-separated email list)
|
||||
let attendees: Vec<String> = if request.attendees.trim().is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
request.attendees
|
||||
.split(',')
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect()
|
||||
};
|
||||
|
||||
// Parse categories (comma-separated list)
|
||||
let categories: Vec<String> = if request.categories.trim().is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
request.categories
|
||||
.split(',')
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect()
|
||||
};
|
||||
|
||||
// Parse reminders and convert to EventReminder structs
|
||||
let reminders: Vec<crate::calendar::EventReminder> = match request.reminder.to_lowercase().as_str() {
|
||||
"15min" => vec![crate::calendar::EventReminder {
|
||||
minutes_before: 15,
|
||||
action: crate::calendar::ReminderAction::Display,
|
||||
description: None,
|
||||
}],
|
||||
"30min" => vec![crate::calendar::EventReminder {
|
||||
minutes_before: 30,
|
||||
action: crate::calendar::ReminderAction::Display,
|
||||
description: None,
|
||||
}],
|
||||
"1hour" => vec![crate::calendar::EventReminder {
|
||||
minutes_before: 60,
|
||||
action: crate::calendar::ReminderAction::Display,
|
||||
description: None,
|
||||
}],
|
||||
"2hours" => vec![crate::calendar::EventReminder {
|
||||
minutes_before: 120,
|
||||
action: crate::calendar::ReminderAction::Display,
|
||||
description: None,
|
||||
}],
|
||||
"1day" => vec![crate::calendar::EventReminder {
|
||||
minutes_before: 1440, // 24 * 60
|
||||
action: crate::calendar::ReminderAction::Display,
|
||||
description: None,
|
||||
}],
|
||||
"2days" => vec![crate::calendar::EventReminder {
|
||||
minutes_before: 2880, // 48 * 60
|
||||
action: crate::calendar::ReminderAction::Display,
|
||||
description: None,
|
||||
}],
|
||||
"1week" => vec![crate::calendar::EventReminder {
|
||||
minutes_before: 10080, // 7 * 24 * 60
|
||||
action: crate::calendar::ReminderAction::Display,
|
||||
description: None,
|
||||
}],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
|
||||
// Parse recurrence with BYDAY support for weekly recurrence
|
||||
let recurrence_rule = match request.recurrence.to_lowercase().as_str() {
|
||||
"daily" => Some("FREQ=DAILY".to_string()),
|
||||
"weekly" => {
|
||||
// Handle weekly recurrence with optional BYDAY parameter
|
||||
let mut rrule = "FREQ=WEEKLY".to_string();
|
||||
|
||||
// Check if specific days are selected (recurrence_days has 7 elements: [Sun, Mon, Tue, Wed, Thu, Fri, Sat])
|
||||
if request.recurrence_days.len() == 7 {
|
||||
let selected_days: Vec<&str> = request.recurrence_days
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, &selected)| {
|
||||
if selected {
|
||||
Some(match i {
|
||||
0 => "SU", // Sunday
|
||||
1 => "MO", // Monday
|
||||
2 => "TU", // Tuesday
|
||||
3 => "WE", // Wednesday
|
||||
4 => "TH", // Thursday
|
||||
5 => "FR", // Friday
|
||||
6 => "SA", // Saturday
|
||||
_ => return None,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
if !selected_days.is_empty() {
|
||||
rrule.push_str(&format!(";BYDAY={}", selected_days.join(",")));
|
||||
}
|
||||
}
|
||||
|
||||
Some(rrule)
|
||||
},
|
||||
"monthly" => Some("FREQ=MONTHLY".to_string()),
|
||||
"yearly" => Some("FREQ=YEARLY".to_string()),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
// Create the CalendarEvent struct
|
||||
let event = crate::calendar::CalendarEvent {
|
||||
uid,
|
||||
summary: Some(request.title.clone()),
|
||||
description: if request.description.trim().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(request.description.clone())
|
||||
},
|
||||
start: start_datetime,
|
||||
end: Some(end_datetime),
|
||||
location: if request.location.trim().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(request.location.clone())
|
||||
},
|
||||
status,
|
||||
class,
|
||||
priority: request.priority,
|
||||
organizer: if request.organizer.trim().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(request.organizer.clone())
|
||||
},
|
||||
attendees,
|
||||
categories,
|
||||
created: Some(chrono::Utc::now()),
|
||||
last_modified: Some(chrono::Utc::now()),
|
||||
recurrence_rule,
|
||||
all_day: request.all_day,
|
||||
reminders,
|
||||
etag: None,
|
||||
href: None,
|
||||
calendar_path: Some(calendar_path.clone()),
|
||||
};
|
||||
|
||||
// Create the event on the CalDAV server
|
||||
let event_href = client.create_event(&calendar_path, &event)
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to create event: {}", e)))?;
|
||||
|
||||
Ok(Json(CreateEventResponse {
|
||||
success: true,
|
||||
message: "Event created successfully".to_string(),
|
||||
event_href: Some(event_href),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Parse date and time strings into a UTC DateTime
|
||||
fn parse_event_datetime(date_str: &str, time_str: &str, all_day: bool) -> Result<chrono::DateTime<chrono::Utc>, String> {
|
||||
use chrono::{NaiveDate, NaiveTime, NaiveDateTime, Utc, TimeZone};
|
||||
|
||||
// Parse the date
|
||||
let date = NaiveDate::parse_from_str(date_str, "%Y-%m-%d")
|
||||
.map_err(|_| format!("Invalid date format: {}. Expected YYYY-MM-DD", date_str))?;
|
||||
|
||||
if all_day {
|
||||
// For all-day events, use midnight UTC
|
||||
let datetime = date.and_hms_opt(0, 0, 0)
|
||||
.ok_or_else(|| "Failed to create midnight datetime".to_string())?;
|
||||
Ok(Utc.from_utc_datetime(&datetime))
|
||||
} else {
|
||||
// Parse the time
|
||||
let time = NaiveTime::parse_from_str(time_str, "%H:%M")
|
||||
.map_err(|_| format!("Invalid time format: {}. Expected HH:MM", time_str))?;
|
||||
|
||||
// Combine date and time
|
||||
let datetime = NaiveDateTime::new(date, time);
|
||||
|
||||
// Assume local time and convert to UTC (in a real app, you'd want timezone support)
|
||||
Ok(Utc.from_utc_datetime(&datetime))
|
||||
}
|
||||
}
|
||||
144
backend/src/handlers/auth.rs
Normal file
144
backend/src/handlers/auth.rs
Normal file
@@ -0,0 +1,144 @@
|
||||
use axum::{extract::State, http::HeaderMap, response::Json};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::calendar::CalDAVClient;
|
||||
use crate::{
|
||||
models::{ApiError, AuthResponse, CalDAVLoginRequest, CalendarInfo, UserInfo},
|
||||
AppState,
|
||||
};
|
||||
|
||||
pub fn extract_bearer_token(headers: &HeaderMap) -> Result<String, ApiError> {
|
||||
let auth_header = headers
|
||||
.get("authorization")
|
||||
.ok_or_else(|| ApiError::Unauthorized("Missing Authorization header".to_string()))?;
|
||||
|
||||
let auth_str = auth_header
|
||||
.to_str()
|
||||
.map_err(|_| ApiError::BadRequest("Invalid Authorization header".to_string()))?;
|
||||
|
||||
if let Some(token) = auth_str.strip_prefix("Bearer ") {
|
||||
Ok(token.to_string())
|
||||
} else {
|
||||
Err(ApiError::BadRequest(
|
||||
"Authorization header must be Bearer token".to_string(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn extract_password_header(headers: &HeaderMap) -> Result<String, ApiError> {
|
||||
let password_header = headers
|
||||
.get("x-caldav-password")
|
||||
.ok_or_else(|| ApiError::BadRequest("Missing X-CalDAV-Password header".to_string()))?;
|
||||
|
||||
password_header
|
||||
.to_str()
|
||||
.map(|s| s.to_string())
|
||||
.map_err(|_| ApiError::BadRequest("Invalid X-CalDAV-Password header".to_string()))
|
||||
}
|
||||
|
||||
pub async fn login(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Json(request): Json<CalDAVLoginRequest>,
|
||||
) -> Result<Json<AuthResponse>, ApiError> {
|
||||
println!("🔐 Login attempt:");
|
||||
println!(" Server URL: {}", request.server_url);
|
||||
println!(" Username: {}", request.username);
|
||||
println!(" Password length: {}", request.password.len());
|
||||
|
||||
// Use the auth service login method which now handles database, sessions, and preferences
|
||||
let response = state.auth_service.login(request).await?;
|
||||
|
||||
println!("✅ Login successful with session management");
|
||||
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
pub async fn verify_token(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<serde_json::Value>, ApiError> {
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let is_valid = state.auth_service.verify_token(&token).is_ok();
|
||||
|
||||
Ok(Json(serde_json::json!({ "valid": is_valid })))
|
||||
}
|
||||
|
||||
pub async fn get_user_info(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<UserInfo>, ApiError> {
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let password = extract_password_header(&headers)?;
|
||||
|
||||
// Create CalDAV config from token and password
|
||||
let config = state
|
||||
.auth_service
|
||||
.caldav_config_from_token(&token, &password)?;
|
||||
let client = CalDAVClient::new(config.clone());
|
||||
|
||||
// Discover calendars
|
||||
let calendar_paths = client
|
||||
.discover_calendars()
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to discover calendars: {}", e)))?;
|
||||
|
||||
println!(
|
||||
"✅ Authentication successful! Found {} calendars",
|
||||
calendar_paths.len()
|
||||
);
|
||||
|
||||
let calendars: Vec<CalendarInfo> = calendar_paths
|
||||
.iter()
|
||||
.map(|path| CalendarInfo {
|
||||
path: path.clone(),
|
||||
display_name: extract_calendar_name(path),
|
||||
color: generate_calendar_color(path),
|
||||
is_visible: true, // Default to visible
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ok(Json(UserInfo {
|
||||
username: config.username,
|
||||
server_url: config.server_url,
|
||||
calendars,
|
||||
}))
|
||||
}
|
||||
|
||||
fn generate_calendar_color(path: &str) -> String {
|
||||
// Generate a consistent color based on the calendar path
|
||||
// This is a simple hash-based approach
|
||||
let mut hash: u32 = 0;
|
||||
for byte in path.bytes() {
|
||||
hash = hash.wrapping_mul(31).wrapping_add(byte as u32);
|
||||
}
|
||||
|
||||
// Define a set of pleasant colors
|
||||
let colors = [
|
||||
"#3B82F6", "#10B981", "#F59E0B", "#EF4444", "#8B5CF6", "#06B6D4", "#84CC16", "#F97316",
|
||||
"#EC4899", "#6366F1", "#14B8A6", "#F3B806", "#8B5A2B", "#6B7280", "#DC2626", "#7C3AED",
|
||||
"#059669", "#D97706", "#BE185D", "#4F46E5",
|
||||
];
|
||||
|
||||
colors[(hash as usize) % colors.len()].to_string()
|
||||
}
|
||||
|
||||
fn extract_calendar_name(path: &str) -> String {
|
||||
// Extract calendar name from path
|
||||
// E.g., "/calendars/user/calendar-name/" -> "Calendar Name"
|
||||
path.split('/')
|
||||
.filter(|s| !s.is_empty())
|
||||
.last()
|
||||
.unwrap_or("Calendar")
|
||||
.replace('-', " ")
|
||||
.replace('_', " ")
|
||||
.split_whitespace()
|
||||
.map(|word| {
|
||||
let mut chars = word.chars();
|
||||
match chars.next() {
|
||||
None => String::new(),
|
||||
Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
|
||||
}
|
||||
})
|
||||
.collect::<Vec<String>>()
|
||||
.join(" ")
|
||||
}
|
||||
94
backend/src/handlers/calendar.rs
Normal file
94
backend/src/handlers/calendar.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
use axum::{extract::State, http::HeaderMap, response::Json};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::calendar::CalDAVClient;
|
||||
use crate::{
|
||||
models::{
|
||||
ApiError, CreateCalendarRequest, CreateCalendarResponse, DeleteCalendarRequest,
|
||||
DeleteCalendarResponse,
|
||||
},
|
||||
AppState,
|
||||
};
|
||||
|
||||
use super::auth::{extract_bearer_token, extract_password_header};
|
||||
|
||||
pub async fn create_calendar(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(request): Json<CreateCalendarRequest>,
|
||||
) -> Result<Json<CreateCalendarResponse>, ApiError> {
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let password = extract_password_header(&headers)?;
|
||||
|
||||
// Validate request
|
||||
if request.name.trim().is_empty() {
|
||||
return Err(ApiError::BadRequest(
|
||||
"Calendar name is required".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
// Create CalDAV config from token and password
|
||||
let config = state
|
||||
.auth_service
|
||||
.caldav_config_from_token(&token, &password)?;
|
||||
let client = CalDAVClient::new(config);
|
||||
|
||||
// Create calendar on CalDAV server
|
||||
match client
|
||||
.create_calendar(
|
||||
&request.name,
|
||||
request.description.as_deref(),
|
||||
request.color.as_deref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => Ok(Json(CreateCalendarResponse {
|
||||
success: true,
|
||||
message: "Calendar created successfully".to_string(),
|
||||
})),
|
||||
Err(e) => {
|
||||
eprintln!("Failed to create calendar: {}", e);
|
||||
Err(ApiError::Internal(format!(
|
||||
"Failed to create calendar: {}",
|
||||
e
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_calendar(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(request): Json<DeleteCalendarRequest>,
|
||||
) -> Result<Json<DeleteCalendarResponse>, ApiError> {
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let password = extract_password_header(&headers)?;
|
||||
|
||||
// Validate request
|
||||
if request.path.trim().is_empty() {
|
||||
return Err(ApiError::BadRequest(
|
||||
"Calendar path is required".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
// Create CalDAV config from token and password
|
||||
let config = state
|
||||
.auth_service
|
||||
.caldav_config_from_token(&token, &password)?;
|
||||
let client = CalDAVClient::new(config);
|
||||
|
||||
// Delete calendar on CalDAV server
|
||||
match client.delete_calendar(&request.path).await {
|
||||
Ok(_) => Ok(Json(DeleteCalendarResponse {
|
||||
success: true,
|
||||
message: "Calendar deleted successfully".to_string(),
|
||||
})),
|
||||
Err(e) => {
|
||||
eprintln!("Failed to delete calendar: {}", e);
|
||||
Err(ApiError::Internal(format!(
|
||||
"Failed to delete calendar: {}",
|
||||
e
|
||||
)))
|
||||
}
|
||||
}
|
||||
}
|
||||
872
backend/src/handlers/events.rs
Normal file
872
backend/src/handlers/events.rs
Normal file
@@ -0,0 +1,872 @@
|
||||
use axum::{
|
||||
extract::{Path, Query, State},
|
||||
http::HeaderMap,
|
||||
response::Json,
|
||||
};
|
||||
use chrono::Datelike;
|
||||
use serde::Deserialize;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::calendar::{CalDAVClient, CalendarEvent};
|
||||
use crate::{
|
||||
models::{
|
||||
ApiError, CreateEventRequest, CreateEventResponse, DeleteEventRequest, DeleteEventResponse,
|
||||
UpdateEventRequest, UpdateEventResponse,
|
||||
},
|
||||
AppState,
|
||||
};
|
||||
use calendar_models::{
|
||||
AlarmAction, AlarmTrigger, Attendee, CalendarUser, EventClass, EventStatus, VAlarm, VEvent,
|
||||
};
|
||||
|
||||
use super::auth::{extract_bearer_token, extract_password_header};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CalendarQuery {
|
||||
pub year: Option<i32>,
|
||||
pub month: Option<u32>,
|
||||
}
|
||||
|
||||
pub async fn get_calendar_events(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Query(params): Query<CalendarQuery>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<Vec<CalendarEvent>>, ApiError> {
|
||||
// Extract and verify token
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let password = extract_password_header(&headers)?;
|
||||
println!("🔑 API call with password length: {}", password.len());
|
||||
|
||||
// Create CalDAV config from token and password
|
||||
let config = state
|
||||
.auth_service
|
||||
.caldav_config_from_token(&token, &password)?;
|
||||
let client = CalDAVClient::new(config);
|
||||
|
||||
// Discover calendars if needed
|
||||
let calendar_paths = client
|
||||
.discover_calendars()
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to discover calendars: {}", e)))?;
|
||||
|
||||
if calendar_paths.is_empty() {
|
||||
return Ok(Json(vec![])); // No calendars found
|
||||
}
|
||||
|
||||
// Fetch events from all calendars
|
||||
let mut all_events = Vec::new();
|
||||
for calendar_path in &calendar_paths {
|
||||
match client.fetch_events(calendar_path).await {
|
||||
Ok(mut events) => {
|
||||
// Set calendar_path for each event to identify which calendar it belongs to
|
||||
for event in &mut events {
|
||||
event.calendar_path = Some(calendar_path.clone());
|
||||
}
|
||||
all_events.extend(events);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"Failed to fetch events from calendar {}: {}",
|
||||
calendar_path, e
|
||||
);
|
||||
// Continue with other calendars instead of failing completely
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If year and month are specified, filter events
|
||||
if let (Some(year), Some(month)) = (params.year, params.month) {
|
||||
let target_date = chrono::NaiveDate::from_ymd_opt(year, month, 1).unwrap();
|
||||
let month_start = target_date;
|
||||
let month_end = if month == 12 {
|
||||
chrono::NaiveDate::from_ymd_opt(year + 1, 1, 1).unwrap()
|
||||
} else {
|
||||
chrono::NaiveDate::from_ymd_opt(year, month + 1, 1).unwrap()
|
||||
} - chrono::Duration::days(1);
|
||||
|
||||
all_events.retain(|event| {
|
||||
let event_date = event.dtstart.date_naive();
|
||||
|
||||
// For non-recurring events, check if the event date is within the month
|
||||
if event.rrule.is_none() || event.rrule.as_ref().unwrap().is_empty() {
|
||||
let event_year = event.dtstart.year();
|
||||
let event_month = event.dtstart.month();
|
||||
return event_year == year && event_month == month;
|
||||
}
|
||||
|
||||
// For recurring events, check if they could have instances in this month
|
||||
// Include if:
|
||||
// 1. The event starts before or during the requested month
|
||||
// 2. The event doesn't have an UNTIL date, OR the UNTIL date is after the month start
|
||||
if event_date > month_end {
|
||||
// Event starts after the requested month
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check UNTIL date in RRULE if present
|
||||
if let Some(ref rrule) = event.rrule {
|
||||
if let Some(until_pos) = rrule.find("UNTIL=") {
|
||||
let until_part = &rrule[until_pos + 6..];
|
||||
let until_end = until_part.find(';').unwrap_or(until_part.len());
|
||||
let until_str = &until_part[..until_end];
|
||||
|
||||
// Try to parse UNTIL date (format: YYYYMMDDTHHMMSSZ or YYYYMMDD)
|
||||
if until_str.len() >= 8 {
|
||||
if let Ok(until_date) = chrono::NaiveDate::parse_from_str(&until_str[..8], "%Y%m%d") {
|
||||
if until_date < month_start {
|
||||
// Recurring event ended before the requested month
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Include the recurring event - the frontend will do proper expansion
|
||||
true
|
||||
});
|
||||
}
|
||||
|
||||
println!("📅 Returning {} events", all_events.len());
|
||||
Ok(Json(all_events))
|
||||
}
|
||||
|
||||
pub async fn refresh_event(
|
||||
State(state): State<Arc<AppState>>,
|
||||
Path(uid): Path<String>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<Json<Option<CalendarEvent>>, ApiError> {
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let password = extract_password_header(&headers)?;
|
||||
|
||||
// Create CalDAV config from token and password
|
||||
let config = state
|
||||
.auth_service
|
||||
.caldav_config_from_token(&token, &password)?;
|
||||
let client = CalDAVClient::new(config);
|
||||
|
||||
// Discover calendars
|
||||
let calendar_paths = client
|
||||
.discover_calendars()
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to discover calendars: {}", e)))?;
|
||||
|
||||
// Search for the event by UID across all calendars
|
||||
for calendar_path in &calendar_paths {
|
||||
if let Ok(Some(mut event)) = client.fetch_event_by_uid(calendar_path, &uid).await {
|
||||
event.calendar_path = Some(calendar_path.clone());
|
||||
return Ok(Json(Some(event)));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Json(None))
|
||||
}
|
||||
|
||||
async fn fetch_event_by_href(
|
||||
client: &CalDAVClient,
|
||||
calendar_path: &str,
|
||||
event_href: &str,
|
||||
) -> Result<Option<CalendarEvent>, crate::calendar::CalDAVError> {
|
||||
// This is a simplified implementation - in a real scenario, you'd want to fetch the specific event by href
|
||||
// For now, we'll fetch all events and find the matching one by href (inefficient but functional)
|
||||
let events = client.fetch_events(calendar_path).await?;
|
||||
|
||||
println!("🔍 fetch_event_by_href: looking for href='{}'", event_href);
|
||||
println!(
|
||||
"🔍 Available events with hrefs: {:?}",
|
||||
events.iter().map(|e| (&e.uid, &e.href)).collect::<Vec<_>>()
|
||||
);
|
||||
|
||||
// First try to match by exact href
|
||||
for event in &events {
|
||||
if let Some(stored_href) = &event.href {
|
||||
if stored_href == event_href {
|
||||
println!("✅ Found matching event by exact href: {}", event.uid);
|
||||
return Ok(Some(event.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: try to match by UID extracted from href filename
|
||||
let filename = event_href.split('/').last().unwrap_or(event_href);
|
||||
let uid_from_href = filename.trim_end_matches(".ics");
|
||||
|
||||
println!(
|
||||
"🔍 Fallback: trying UID match. filename='{}', uid='{}'",
|
||||
filename, uid_from_href
|
||||
);
|
||||
|
||||
for event in events {
|
||||
if event.uid == uid_from_href {
|
||||
println!("✅ Found matching event by UID: {}", event.uid);
|
||||
return Ok(Some(event));
|
||||
}
|
||||
}
|
||||
|
||||
println!("❌ No matching event found for href: {}", event_href);
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub async fn delete_event(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(request): Json<DeleteEventRequest>,
|
||||
) -> Result<Json<DeleteEventResponse>, ApiError> {
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let password = extract_password_header(&headers)?;
|
||||
|
||||
// Create CalDAV config from token and password
|
||||
let config = state
|
||||
.auth_service
|
||||
.caldav_config_from_token(&token, &password)?;
|
||||
let client = CalDAVClient::new(config);
|
||||
|
||||
// Handle different delete actions for recurring events
|
||||
match request.delete_action.as_str() {
|
||||
"delete_this" => {
|
||||
if let Some(event) =
|
||||
fetch_event_by_href(&client, &request.calendar_path, &request.event_href)
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to fetch event: {}", e)))?
|
||||
{
|
||||
// Check if this is a recurring event
|
||||
if event.rrule.is_some() && !event.rrule.as_ref().unwrap().is_empty() {
|
||||
// Recurring event - add EXDATE for this occurrence
|
||||
if let Some(occurrence_date) = &request.occurrence_date {
|
||||
let exception_utc = if let Ok(date) =
|
||||
chrono::DateTime::parse_from_rfc3339(occurrence_date)
|
||||
{
|
||||
// RFC3339 format (with time and timezone)
|
||||
date.with_timezone(&chrono::Utc)
|
||||
} else if let Ok(naive_date) =
|
||||
chrono::NaiveDate::parse_from_str(occurrence_date, "%Y-%m-%d")
|
||||
{
|
||||
// Simple date format (YYYY-MM-DD)
|
||||
naive_date.and_hms_opt(0, 0, 0).unwrap().and_utc()
|
||||
} else {
|
||||
return Err(ApiError::BadRequest(format!("Invalid occurrence date format: {}. Expected RFC3339 or YYYY-MM-DD", occurrence_date)));
|
||||
};
|
||||
|
||||
let mut updated_event = event;
|
||||
updated_event.exdate.push(exception_utc);
|
||||
|
||||
println!(
|
||||
"🔄 Adding EXDATE {} to recurring event {}",
|
||||
exception_utc.format("%Y%m%dT%H%M%SZ"),
|
||||
updated_event.uid
|
||||
);
|
||||
|
||||
// Update the event with the new EXDATE
|
||||
client
|
||||
.update_event(
|
||||
&request.calendar_path,
|
||||
&updated_event,
|
||||
&request.event_href,
|
||||
)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
ApiError::Internal(format!(
|
||||
"Failed to update event with EXDATE: {}",
|
||||
e
|
||||
))
|
||||
})?;
|
||||
|
||||
println!("✅ Successfully updated recurring event with EXDATE");
|
||||
|
||||
Ok(Json(DeleteEventResponse {
|
||||
success: true,
|
||||
message: "Single occurrence deleted successfully".to_string(),
|
||||
}))
|
||||
} else {
|
||||
Err(ApiError::BadRequest("Occurrence date is required for single occurrence deletion of recurring events".to_string()))
|
||||
}
|
||||
} else {
|
||||
// Non-recurring event - delete the entire event
|
||||
println!("🗑️ Deleting non-recurring event: {}", event.uid);
|
||||
|
||||
client
|
||||
.delete_event(&request.calendar_path, &request.event_href)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
ApiError::Internal(format!("Failed to delete event: {}", e))
|
||||
})?;
|
||||
|
||||
println!("✅ Successfully deleted non-recurring event");
|
||||
|
||||
Ok(Json(DeleteEventResponse {
|
||||
success: true,
|
||||
message: "Event deleted successfully".to_string(),
|
||||
}))
|
||||
}
|
||||
} else {
|
||||
Err(ApiError::NotFound("Event not found".to_string()))
|
||||
}
|
||||
}
|
||||
"delete_following" => {
|
||||
// For "this and following" deletion, we need to:
|
||||
// 1. Fetch the recurring event
|
||||
// 2. Modify the RRULE to end before this occurrence
|
||||
// 3. Update the event
|
||||
|
||||
if let Some(mut event) =
|
||||
fetch_event_by_href(&client, &request.calendar_path, &request.event_href)
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to fetch event: {}", e)))?
|
||||
{
|
||||
if let Some(occurrence_date) = &request.occurrence_date {
|
||||
let until_date = if let Ok(date) =
|
||||
chrono::DateTime::parse_from_rfc3339(occurrence_date)
|
||||
{
|
||||
// RFC3339 format (with time and timezone)
|
||||
date.with_timezone(&chrono::Utc)
|
||||
} else if let Ok(naive_date) =
|
||||
chrono::NaiveDate::parse_from_str(occurrence_date, "%Y-%m-%d")
|
||||
{
|
||||
// Simple date format (YYYY-MM-DD)
|
||||
naive_date.and_hms_opt(0, 0, 0).unwrap().and_utc()
|
||||
} else {
|
||||
return Err(ApiError::BadRequest(format!(
|
||||
"Invalid occurrence date format: {}. Expected RFC3339 or YYYY-MM-DD",
|
||||
occurrence_date
|
||||
)));
|
||||
};
|
||||
|
||||
// Modify the RRULE to add an UNTIL clause
|
||||
if let Some(rrule) = &event.rrule {
|
||||
// Remove existing UNTIL if present and add new one
|
||||
let parts: Vec<&str> = rrule
|
||||
.split(';')
|
||||
.filter(|part| {
|
||||
!part.starts_with("UNTIL=") && !part.starts_with("COUNT=")
|
||||
})
|
||||
.collect();
|
||||
|
||||
let new_rrule = format!(
|
||||
"{};UNTIL={}",
|
||||
parts.join(";"),
|
||||
until_date.format("%Y%m%dT%H%M%SZ")
|
||||
);
|
||||
event.rrule = Some(new_rrule);
|
||||
|
||||
// Update the event with the modified RRULE
|
||||
client
|
||||
.update_event(&request.calendar_path, &event, &request.event_href)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
ApiError::Internal(format!(
|
||||
"Failed to update event with modified RRULE: {}",
|
||||
e
|
||||
))
|
||||
})?;
|
||||
|
||||
Ok(Json(DeleteEventResponse {
|
||||
success: true,
|
||||
message: "This and following occurrences deleted successfully"
|
||||
.to_string(),
|
||||
}))
|
||||
} else {
|
||||
// No RRULE, just delete the single event
|
||||
client
|
||||
.delete_event(&request.calendar_path, &request.event_href)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
ApiError::Internal(format!("Failed to delete event: {}", e))
|
||||
})?;
|
||||
|
||||
Ok(Json(DeleteEventResponse {
|
||||
success: true,
|
||||
message: "Event deleted successfully".to_string(),
|
||||
}))
|
||||
}
|
||||
} else {
|
||||
Err(ApiError::BadRequest(
|
||||
"Occurrence date is required for following deletion".to_string(),
|
||||
))
|
||||
}
|
||||
} else {
|
||||
Err(ApiError::NotFound("Event not found".to_string()))
|
||||
}
|
||||
}
|
||||
"delete_series" | _ => {
|
||||
// Delete the entire event/series
|
||||
client
|
||||
.delete_event(&request.calendar_path, &request.event_href)
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to delete event: {}", e)))?;
|
||||
|
||||
Ok(Json(DeleteEventResponse {
|
||||
success: true,
|
||||
message: "Event deleted successfully".to_string(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_event(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(request): Json<CreateEventRequest>,
|
||||
) -> Result<Json<CreateEventResponse>, ApiError> {
|
||||
println!(
|
||||
"📝 Create event request received: title='{}', all_day={}, calendar_path={:?}",
|
||||
request.title, request.all_day, request.calendar_path
|
||||
);
|
||||
|
||||
// Extract and verify token
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let password = extract_password_header(&headers)?;
|
||||
|
||||
// Validate request
|
||||
if request.title.trim().is_empty() {
|
||||
return Err(ApiError::BadRequest("Event title is required".to_string()));
|
||||
}
|
||||
|
||||
if request.title.len() > 200 {
|
||||
return Err(ApiError::BadRequest(
|
||||
"Event title too long (max 200 characters)".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
// Create CalDAV config from token and password
|
||||
let config = state
|
||||
.auth_service
|
||||
.caldav_config_from_token(&token, &password)?;
|
||||
let client = CalDAVClient::new(config);
|
||||
|
||||
// Determine which calendar to use
|
||||
let calendar_path = if let Some(path) = request.calendar_path {
|
||||
path
|
||||
} else {
|
||||
// Use the first available calendar
|
||||
let calendar_paths = client
|
||||
.discover_calendars()
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to discover calendars: {}", e)))?;
|
||||
|
||||
if calendar_paths.is_empty() {
|
||||
return Err(ApiError::BadRequest(
|
||||
"No calendars available for event creation".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
calendar_paths[0].clone()
|
||||
};
|
||||
|
||||
// Parse dates and times
|
||||
let start_datetime =
|
||||
parse_event_datetime(&request.start_date, &request.start_time, request.all_day)
|
||||
.map_err(|e| ApiError::BadRequest(format!("Invalid start date/time: {}", e)))?;
|
||||
|
||||
let mut end_datetime = parse_event_datetime(&request.end_date, &request.end_time, request.all_day)
|
||||
.map_err(|e| ApiError::BadRequest(format!("Invalid end date/time: {}", e)))?;
|
||||
|
||||
// For all-day events, add one day to end date for RFC-5545 compliance
|
||||
// RFC-5545 uses exclusive end dates for all-day events
|
||||
if request.all_day {
|
||||
end_datetime = end_datetime + chrono::Duration::days(1);
|
||||
}
|
||||
|
||||
// Validate that end is after start (allow equal times for all-day events)
|
||||
if request.all_day {
|
||||
if end_datetime < start_datetime {
|
||||
return Err(ApiError::BadRequest(
|
||||
"End date must be on or after start date for all-day events".to_string(),
|
||||
));
|
||||
}
|
||||
} else {
|
||||
if end_datetime <= start_datetime {
|
||||
return Err(ApiError::BadRequest(
|
||||
"End date/time must be after start date/time".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Generate a unique UID for the event
|
||||
let uid = format!(
|
||||
"{}-{}",
|
||||
uuid::Uuid::new_v4(),
|
||||
chrono::Utc::now().timestamp()
|
||||
);
|
||||
|
||||
// Parse status
|
||||
let status = match request.status.to_lowercase().as_str() {
|
||||
"tentative" => EventStatus::Tentative,
|
||||
"cancelled" => EventStatus::Cancelled,
|
||||
_ => EventStatus::Confirmed,
|
||||
};
|
||||
|
||||
// Parse class
|
||||
let class = match request.class.to_lowercase().as_str() {
|
||||
"private" => EventClass::Private,
|
||||
"confidential" => EventClass::Confidential,
|
||||
_ => EventClass::Public,
|
||||
};
|
||||
|
||||
// Parse attendees (comma-separated email list)
|
||||
let attendees: Vec<String> = if request.attendees.trim().is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
request
|
||||
.attendees
|
||||
.split(',')
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect()
|
||||
};
|
||||
|
||||
// Parse categories (comma-separated list)
|
||||
let categories: Vec<String> = if request.categories.trim().is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
request
|
||||
.categories
|
||||
.split(',')
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect()
|
||||
};
|
||||
|
||||
// Parse alarms - convert from minutes string to EventReminder structs
|
||||
let alarms: Vec<crate::calendar::EventReminder> = if request.reminder.trim().is_empty() {
|
||||
Vec::new()
|
||||
} else {
|
||||
match request.reminder.parse::<i32>() {
|
||||
Ok(minutes) => vec![crate::calendar::EventReminder {
|
||||
minutes_before: minutes,
|
||||
action: crate::calendar::ReminderAction::Display,
|
||||
description: None,
|
||||
}],
|
||||
Err(_) => Vec::new(),
|
||||
}
|
||||
};
|
||||
|
||||
// Check if recurrence is already a full RRULE or just a simple type
|
||||
let rrule = if request.recurrence.starts_with("FREQ=") {
|
||||
// Frontend sent a complete RRULE string, use it directly
|
||||
if request.recurrence.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(request.recurrence.clone())
|
||||
}
|
||||
} else {
|
||||
// Legacy path: Parse recurrence with BYDAY support for weekly recurrence
|
||||
match request.recurrence.to_uppercase().as_str() {
|
||||
"DAILY" => Some("FREQ=DAILY".to_string()),
|
||||
"WEEKLY" => {
|
||||
// Handle weekly recurrence with optional BYDAY parameter
|
||||
let mut rrule = "FREQ=WEEKLY".to_string();
|
||||
|
||||
// Check if specific days are selected (recurrence_days has 7 elements: [Sun, Mon, Tue, Wed, Thu, Fri, Sat])
|
||||
if request.recurrence_days.len() == 7 {
|
||||
let selected_days: Vec<&str> = request
|
||||
.recurrence_days
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, &selected)| {
|
||||
if selected {
|
||||
Some(match i {
|
||||
0 => "SU", // Sunday
|
||||
1 => "MO", // Monday
|
||||
2 => "TU", // Tuesday
|
||||
3 => "WE", // Wednesday
|
||||
4 => "TH", // Thursday
|
||||
5 => "FR", // Friday
|
||||
6 => "SA", // Saturday
|
||||
_ => return None,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
if !selected_days.is_empty() {
|
||||
rrule = format!("{};BYDAY={}", rrule, selected_days.join(","));
|
||||
}
|
||||
}
|
||||
|
||||
Some(rrule)
|
||||
}
|
||||
"MONTHLY" => Some("FREQ=MONTHLY".to_string()),
|
||||
"YEARLY" => Some("FREQ=YEARLY".to_string()),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
|
||||
// Create the VEvent struct (RFC 5545 compliant)
|
||||
let mut event = VEvent::new(uid, start_datetime);
|
||||
event.dtend = Some(end_datetime);
|
||||
event.summary = if request.title.trim().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(request.title.clone())
|
||||
};
|
||||
event.description = if request.description.trim().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(request.description)
|
||||
};
|
||||
event.location = if request.location.trim().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(request.location)
|
||||
};
|
||||
event.status = Some(status);
|
||||
event.class = Some(class);
|
||||
event.priority = request.priority;
|
||||
event.organizer = if request.organizer.trim().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(CalendarUser {
|
||||
cal_address: request.organizer,
|
||||
common_name: None,
|
||||
dir_entry_ref: None,
|
||||
sent_by: None,
|
||||
language: None,
|
||||
})
|
||||
};
|
||||
event.attendees = attendees
|
||||
.into_iter()
|
||||
.map(|email| Attendee {
|
||||
cal_address: email,
|
||||
common_name: None,
|
||||
role: None,
|
||||
part_stat: None,
|
||||
rsvp: None,
|
||||
cu_type: None,
|
||||
member: Vec::new(),
|
||||
delegated_to: Vec::new(),
|
||||
delegated_from: Vec::new(),
|
||||
sent_by: None,
|
||||
dir_entry_ref: None,
|
||||
language: None,
|
||||
})
|
||||
.collect();
|
||||
event.categories = categories;
|
||||
event.rrule = rrule;
|
||||
event.all_day = request.all_day;
|
||||
event.alarms = alarms
|
||||
.into_iter()
|
||||
.map(|reminder| VAlarm {
|
||||
action: AlarmAction::Display,
|
||||
trigger: AlarmTrigger::Duration(chrono::Duration::minutes(
|
||||
-reminder.minutes_before as i64,
|
||||
)),
|
||||
duration: None,
|
||||
repeat: None,
|
||||
description: reminder.description,
|
||||
summary: None,
|
||||
attendees: Vec::new(),
|
||||
attach: Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
event.calendar_path = Some(calendar_path.clone());
|
||||
|
||||
// Create the event on the CalDAV server
|
||||
let event_href = client
|
||||
.create_event(&calendar_path, &event)
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to create event: {}", e)))?;
|
||||
|
||||
println!(
|
||||
"✅ Event created successfully with UID: {} at href: {}",
|
||||
event.uid, event_href
|
||||
);
|
||||
|
||||
Ok(Json(CreateEventResponse {
|
||||
success: true,
|
||||
message: "Event created successfully".to_string(),
|
||||
event_href: Some(event_href),
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn update_event(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(request): Json<UpdateEventRequest>,
|
||||
) -> Result<Json<UpdateEventResponse>, ApiError> {
|
||||
// Handle update request
|
||||
|
||||
// Extract and verify token
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let password = extract_password_header(&headers)?;
|
||||
|
||||
// Validate request
|
||||
if request.uid.trim().is_empty() {
|
||||
return Err(ApiError::BadRequest("Event UID is required".to_string()));
|
||||
}
|
||||
|
||||
if request.title.trim().is_empty() {
|
||||
return Err(ApiError::BadRequest("Event title is required".to_string()));
|
||||
}
|
||||
|
||||
if request.title.len() > 200 {
|
||||
return Err(ApiError::BadRequest(
|
||||
"Event title too long (max 200 characters)".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
// Create CalDAV config from token and password
|
||||
let config = state
|
||||
.auth_service
|
||||
.caldav_config_from_token(&token, &password)?;
|
||||
let client = CalDAVClient::new(config);
|
||||
|
||||
// Find the event across all calendars (or in the specified calendar)
|
||||
let calendar_paths = if let Some(path) = &request.calendar_path {
|
||||
vec![path.clone()]
|
||||
} else {
|
||||
client
|
||||
.discover_calendars()
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to discover calendars: {}", e)))?
|
||||
};
|
||||
|
||||
let mut found_event: Option<(CalendarEvent, String, String)> = None; // (event, calendar_path, event_href)
|
||||
|
||||
for calendar_path in &calendar_paths {
|
||||
match client.fetch_events(calendar_path).await {
|
||||
Ok(events) => {
|
||||
for event in events {
|
||||
if event.uid == request.uid {
|
||||
// Use the actual href from the event, or generate one if missing
|
||||
let event_href = event
|
||||
.href
|
||||
.clone()
|
||||
.unwrap_or_else(|| format!("{}.ics", event.uid));
|
||||
println!("🔍 Found event {} with href: {}", event.uid, event_href);
|
||||
found_event = Some((event, calendar_path.clone(), event_href));
|
||||
break;
|
||||
}
|
||||
}
|
||||
if found_event.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"Failed to fetch events from calendar {}: {}",
|
||||
calendar_path, e
|
||||
);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let (mut event, calendar_path, event_href) = found_event
|
||||
.ok_or_else(|| ApiError::NotFound(format!("Event with UID '{}' not found", request.uid)))?;
|
||||
|
||||
// Parse dates and times
|
||||
let start_datetime =
|
||||
parse_event_datetime(&request.start_date, &request.start_time, request.all_day)
|
||||
.map_err(|e| ApiError::BadRequest(format!("Invalid start date/time: {}", e)))?;
|
||||
|
||||
let mut end_datetime = parse_event_datetime(&request.end_date, &request.end_time, request.all_day)
|
||||
.map_err(|e| ApiError::BadRequest(format!("Invalid end date/time: {}", e)))?;
|
||||
|
||||
// For all-day events, add one day to end date for RFC-5545 compliance
|
||||
// RFC-5545 uses exclusive end dates for all-day events
|
||||
if request.all_day {
|
||||
end_datetime = end_datetime + chrono::Duration::days(1);
|
||||
}
|
||||
|
||||
// Validate that end is after start (allow equal times for all-day events)
|
||||
if request.all_day {
|
||||
if end_datetime < start_datetime {
|
||||
return Err(ApiError::BadRequest(
|
||||
"End date must be on or after start date for all-day events".to_string(),
|
||||
));
|
||||
}
|
||||
} else {
|
||||
if end_datetime <= start_datetime {
|
||||
return Err(ApiError::BadRequest(
|
||||
"End date/time must be after start date/time".to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Update event properties
|
||||
event.dtstart = start_datetime;
|
||||
event.dtend = Some(end_datetime);
|
||||
event.summary = if request.title.trim().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(request.title)
|
||||
};
|
||||
event.description = if request.description.trim().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(request.description)
|
||||
};
|
||||
event.location = if request.location.trim().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(request.location)
|
||||
};
|
||||
event.all_day = request.all_day;
|
||||
|
||||
// Parse and update status
|
||||
event.status = Some(match request.status.to_lowercase().as_str() {
|
||||
"tentative" => EventStatus::Tentative,
|
||||
"cancelled" => EventStatus::Cancelled,
|
||||
_ => EventStatus::Confirmed,
|
||||
});
|
||||
|
||||
// Parse and update class
|
||||
event.class = Some(match request.class.to_lowercase().as_str() {
|
||||
"private" => EventClass::Private,
|
||||
"confidential" => EventClass::Confidential,
|
||||
_ => EventClass::Public,
|
||||
});
|
||||
|
||||
event.priority = request.priority;
|
||||
|
||||
// Update the event on the CalDAV server
|
||||
println!(
|
||||
"📝 Updating event {} at calendar_path: {}, event_href: {}",
|
||||
event.uid, calendar_path, event_href
|
||||
);
|
||||
client
|
||||
.update_event(&calendar_path, &event, &event_href)
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to update event: {}", e)))?;
|
||||
|
||||
println!("✅ Successfully updated event {}", event.uid);
|
||||
|
||||
Ok(Json(UpdateEventResponse {
|
||||
success: true,
|
||||
message: "Event updated successfully".to_string(),
|
||||
}))
|
||||
}
|
||||
|
||||
fn parse_event_datetime(
|
||||
date_str: &str,
|
||||
time_str: &str,
|
||||
all_day: bool,
|
||||
) -> Result<chrono::DateTime<chrono::Utc>, String> {
|
||||
use chrono::{NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Utc};
|
||||
|
||||
// Parse the date
|
||||
let date = NaiveDate::parse_from_str(date_str, "%Y-%m-%d")
|
||||
.map_err(|_| format!("Invalid date format: {}. Expected YYYY-MM-DD", date_str))?;
|
||||
|
||||
if all_day {
|
||||
// For all-day events, use noon UTC to avoid timezone boundary issues
|
||||
// This ensures the date remains correct when converted to any local timezone
|
||||
let datetime = date
|
||||
.and_hms_opt(12, 0, 0)
|
||||
.ok_or_else(|| "Failed to create noon datetime".to_string())?;
|
||||
Ok(Utc.from_utc_datetime(&datetime))
|
||||
} else {
|
||||
// Parse the time
|
||||
let time = NaiveTime::parse_from_str(time_str, "%H:%M")
|
||||
.map_err(|_| format!("Invalid time format: {}. Expected HH:MM", time_str))?;
|
||||
|
||||
// Combine date and time
|
||||
let datetime = NaiveDateTime::new(date, time);
|
||||
|
||||
// Frontend now sends UTC times, so treat as UTC directly
|
||||
Ok(Utc.from_utc_datetime(&datetime))
|
||||
}
|
||||
}
|
||||
142
backend/src/handlers/external_calendars.rs
Normal file
142
backend/src/handlers/external_calendars.rs
Normal file
@@ -0,0 +1,142 @@
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
response::Json,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
db::{ExternalCalendar, ExternalCalendarRepository},
|
||||
models::ApiError,
|
||||
AppState,
|
||||
};
|
||||
|
||||
use super::auth::{extract_bearer_token};
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CreateExternalCalendarRequest {
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
pub color: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct UpdateExternalCalendarRequest {
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
pub color: String,
|
||||
pub is_visible: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ExternalCalendarResponse {
|
||||
pub id: i32,
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
pub color: String,
|
||||
pub is_visible: bool,
|
||||
pub created_at: chrono::DateTime<chrono::Utc>,
|
||||
pub updated_at: chrono::DateTime<chrono::Utc>,
|
||||
pub last_fetched: Option<chrono::DateTime<chrono::Utc>>,
|
||||
}
|
||||
|
||||
impl From<ExternalCalendar> for ExternalCalendarResponse {
|
||||
fn from(calendar: ExternalCalendar) -> Self {
|
||||
Self {
|
||||
id: calendar.id,
|
||||
name: calendar.name,
|
||||
url: calendar.url,
|
||||
color: calendar.color,
|
||||
is_visible: calendar.is_visible,
|
||||
created_at: calendar.created_at,
|
||||
updated_at: calendar.updated_at,
|
||||
last_fetched: calendar.last_fetched,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_external_calendars(
|
||||
headers: axum::http::HeaderMap,
|
||||
State(app_state): State<Arc<AppState>>,
|
||||
) -> Result<Json<Vec<ExternalCalendarResponse>>, ApiError> {
|
||||
// Extract and verify token, get user
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let user = app_state.auth_service.get_user_from_token(&token).await?;
|
||||
|
||||
let repo = ExternalCalendarRepository::new(&app_state.db);
|
||||
let calendars = repo
|
||||
.get_by_user(&user.id)
|
||||
.await
|
||||
.map_err(|e| ApiError::Database(format!("Failed to get external calendars: {}", e)))?;
|
||||
|
||||
let response: Vec<ExternalCalendarResponse> = calendars.into_iter().map(Into::into).collect();
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
pub async fn create_external_calendar(
|
||||
headers: axum::http::HeaderMap,
|
||||
State(app_state): State<Arc<AppState>>,
|
||||
Json(request): Json<CreateExternalCalendarRequest>,
|
||||
) -> Result<Json<ExternalCalendarResponse>, ApiError> {
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let user = app_state.auth_service.get_user_from_token(&token).await?;
|
||||
|
||||
let calendar = ExternalCalendar::new(
|
||||
user.id,
|
||||
request.name,
|
||||
request.url,
|
||||
request.color,
|
||||
);
|
||||
|
||||
let repo = ExternalCalendarRepository::new(&app_state.db);
|
||||
let id = repo
|
||||
.create(&calendar)
|
||||
.await
|
||||
.map_err(|e| ApiError::Database(format!("Failed to create external calendar: {}", e)))?;
|
||||
|
||||
let mut created_calendar = calendar;
|
||||
created_calendar.id = id;
|
||||
|
||||
Ok(Json(created_calendar.into()))
|
||||
}
|
||||
|
||||
pub async fn update_external_calendar(
|
||||
headers: axum::http::HeaderMap,
|
||||
State(app_state): State<Arc<AppState>>,
|
||||
Path(id): Path<i32>,
|
||||
Json(request): Json<UpdateExternalCalendarRequest>,
|
||||
) -> Result<Json<()>, ApiError> {
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let user = app_state.auth_service.get_user_from_token(&token).await?;
|
||||
|
||||
let mut calendar = ExternalCalendar::new(
|
||||
user.id,
|
||||
request.name,
|
||||
request.url,
|
||||
request.color,
|
||||
);
|
||||
calendar.is_visible = request.is_visible;
|
||||
|
||||
let repo = ExternalCalendarRepository::new(&app_state.db);
|
||||
repo.update(id, &calendar)
|
||||
.await
|
||||
.map_err(|e| ApiError::Database(format!("Failed to update external calendar: {}", e)))?;
|
||||
|
||||
Ok(Json(()))
|
||||
}
|
||||
|
||||
pub async fn delete_external_calendar(
|
||||
headers: axum::http::HeaderMap,
|
||||
State(app_state): State<Arc<AppState>>,
|
||||
Path(id): Path<i32>,
|
||||
) -> Result<Json<()>, ApiError> {
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let user = app_state.auth_service.get_user_from_token(&token).await?;
|
||||
|
||||
let repo = ExternalCalendarRepository::new(&app_state.db);
|
||||
repo.delete(id, &user.id)
|
||||
.await
|
||||
.map_err(|e| ApiError::Database(format!("Failed to delete external calendar: {}", e)))?;
|
||||
|
||||
Ok(Json(()))
|
||||
}
|
||||
848
backend/src/handlers/ics_fetcher.rs
Normal file
848
backend/src/handlers/ics_fetcher.rs
Normal file
@@ -0,0 +1,848 @@
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
response::Json,
|
||||
};
|
||||
use chrono::{DateTime, Utc, Datelike};
|
||||
use ical::parser::ical::component::IcalEvent;
|
||||
use reqwest::Client;
|
||||
use serde::Serialize;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
db::ExternalCalendarRepository,
|
||||
models::ApiError,
|
||||
AppState,
|
||||
};
|
||||
|
||||
// Import VEvent from calendar-models shared crate
|
||||
use calendar_models::VEvent;
|
||||
|
||||
use super::auth::{extract_bearer_token};
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct ExternalCalendarEventsResponse {
|
||||
pub events: Vec<VEvent>,
|
||||
pub last_fetched: DateTime<Utc>,
|
||||
}
|
||||
|
||||
pub async fn fetch_external_calendar_events(
|
||||
headers: axum::http::HeaderMap,
|
||||
State(app_state): State<Arc<AppState>>,
|
||||
Path(id): Path<i32>,
|
||||
) -> Result<Json<ExternalCalendarEventsResponse>, ApiError> {
|
||||
let token = extract_bearer_token(&headers)?;
|
||||
let user = app_state.auth_service.get_user_from_token(&token).await?;
|
||||
|
||||
let repo = ExternalCalendarRepository::new(&app_state.db);
|
||||
|
||||
// Get user's external calendars to verify ownership and get URL
|
||||
let calendars = repo
|
||||
.get_by_user(&user.id)
|
||||
.await
|
||||
.map_err(|e| ApiError::Database(format!("Failed to get external calendars: {}", e)))?;
|
||||
|
||||
let calendar = calendars
|
||||
.into_iter()
|
||||
.find(|c| c.id == id)
|
||||
.ok_or_else(|| ApiError::NotFound("External calendar not found".to_string()))?;
|
||||
|
||||
if !calendar.is_visible {
|
||||
return Ok(Json(ExternalCalendarEventsResponse {
|
||||
events: vec![],
|
||||
last_fetched: Utc::now(),
|
||||
}));
|
||||
}
|
||||
|
||||
// Check cache first
|
||||
let cache_max_age_minutes = 5;
|
||||
let mut ics_content = String::new();
|
||||
let mut last_fetched = Utc::now();
|
||||
let mut fetched_from_cache = false;
|
||||
|
||||
// Try to get from cache if not stale
|
||||
match repo.is_cache_stale(id, cache_max_age_minutes).await {
|
||||
Ok(is_stale) => {
|
||||
if !is_stale {
|
||||
// Cache is fresh, use it
|
||||
if let Ok(Some((cached_data, cached_at))) = repo.get_cached_data(id).await {
|
||||
ics_content = cached_data;
|
||||
last_fetched = cached_at;
|
||||
fetched_from_cache = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
// If cache check fails, proceed to fetch from URL
|
||||
}
|
||||
}
|
||||
|
||||
// If not fetched from cache, get from external URL
|
||||
if !fetched_from_cache {
|
||||
let client = Client::new();
|
||||
let response = client
|
||||
.get(&calendar.url)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to fetch calendar: {}", e)))?;
|
||||
|
||||
if !response.status().is_success() {
|
||||
return Err(ApiError::Internal(format!("Calendar server returned: {}", response.status())));
|
||||
}
|
||||
|
||||
ics_content = response
|
||||
.text()
|
||||
.await
|
||||
.map_err(|e| ApiError::Internal(format!("Failed to read calendar content: {}", e)))?;
|
||||
|
||||
// Store in cache for future requests
|
||||
let etag = None; // TODO: Extract ETag from response headers if available
|
||||
if let Err(_) = repo.update_cache(id, &ics_content, etag).await {
|
||||
// Log error but don't fail the request
|
||||
}
|
||||
|
||||
// Update last_fetched timestamp
|
||||
if let Err(_) = repo.update_last_fetched(id, &user.id).await {
|
||||
}
|
||||
|
||||
last_fetched = Utc::now();
|
||||
}
|
||||
|
||||
// Parse ICS content
|
||||
let events = parse_ics_content(&ics_content)
|
||||
.map_err(|e| ApiError::BadRequest(format!("Failed to parse calendar: {}", e)))?;
|
||||
|
||||
Ok(Json(ExternalCalendarEventsResponse {
|
||||
events,
|
||||
last_fetched,
|
||||
}))
|
||||
}
|
||||
|
||||
fn parse_ics_content(ics_content: &str) -> Result<Vec<VEvent>, Box<dyn std::error::Error>> {
|
||||
let reader = ical::IcalParser::new(ics_content.as_bytes());
|
||||
let mut events = Vec::new();
|
||||
let mut _total_components = 0;
|
||||
let mut _failed_conversions = 0;
|
||||
|
||||
for calendar in reader {
|
||||
let calendar = calendar?;
|
||||
for component in calendar.events {
|
||||
_total_components += 1;
|
||||
match convert_ical_to_vevent(component) {
|
||||
Ok(vevent) => {
|
||||
events.push(vevent);
|
||||
}
|
||||
Err(_) => {
|
||||
_failed_conversions += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Deduplicate events based on UID, start time, and summary
|
||||
// Outlook sometimes includes duplicate events (recurring exceptions may appear multiple times)
|
||||
events = deduplicate_events(events);
|
||||
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
fn convert_ical_to_vevent(ical_event: IcalEvent) -> Result<VEvent, Box<dyn std::error::Error>> {
|
||||
use uuid::Uuid;
|
||||
|
||||
let mut summary = None;
|
||||
let mut description = None;
|
||||
let mut location = None;
|
||||
let mut dtstart = None;
|
||||
let mut dtend = None;
|
||||
let mut uid = None;
|
||||
let mut all_day = false;
|
||||
let mut rrule = None;
|
||||
|
||||
|
||||
// Extract properties
|
||||
for property in ical_event.properties {
|
||||
match property.name.as_str() {
|
||||
"SUMMARY" => {
|
||||
summary = property.value;
|
||||
}
|
||||
"DESCRIPTION" => {
|
||||
description = property.value;
|
||||
}
|
||||
"LOCATION" => {
|
||||
location = property.value;
|
||||
}
|
||||
"DTSTART" => {
|
||||
if let Some(value) = property.value {
|
||||
// Check if it's a date-only value (all-day event)
|
||||
if value.len() == 8 && !value.contains('T') {
|
||||
all_day = true;
|
||||
// Parse YYYYMMDD format
|
||||
if let Ok(date) = chrono::NaiveDate::parse_from_str(&value, "%Y%m%d") {
|
||||
dtstart = Some(chrono::TimeZone::from_utc_datetime(&Utc, &date.and_hms_opt(12, 0, 0).unwrap()));
|
||||
}
|
||||
} else {
|
||||
// Extract timezone info from parameters
|
||||
let tzid = property.params.as_ref()
|
||||
.and_then(|params| params.iter().find(|(k, _)| k == "TZID"))
|
||||
.and_then(|(_, v)| v.first().cloned());
|
||||
|
||||
// Parse datetime with timezone information
|
||||
if let Some(dt) = parse_datetime_with_tz(&value, tzid.as_deref()) {
|
||||
dtstart = Some(dt);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"DTEND" => {
|
||||
if let Some(value) = property.value {
|
||||
if all_day && value.len() == 8 && !value.contains('T') {
|
||||
// For all-day events, DTEND is exclusive so use the date as-is at noon
|
||||
if let Ok(date) = chrono::NaiveDate::parse_from_str(&value, "%Y%m%d") {
|
||||
dtend = Some(chrono::TimeZone::from_utc_datetime(&Utc, &date.and_hms_opt(12, 0, 0).unwrap()));
|
||||
}
|
||||
} else {
|
||||
// Extract timezone info from parameters
|
||||
let tzid = property.params.as_ref()
|
||||
.and_then(|params| params.iter().find(|(k, _)| k == "TZID"))
|
||||
.and_then(|(_, v)| v.first().cloned());
|
||||
|
||||
// Parse datetime with timezone information
|
||||
if let Some(dt) = parse_datetime_with_tz(&value, tzid.as_deref()) {
|
||||
dtend = Some(dt);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"UID" => {
|
||||
uid = property.value;
|
||||
}
|
||||
"RRULE" => {
|
||||
rrule = property.value;
|
||||
}
|
||||
_ => {} // Ignore other properties for now
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
let dtstart = dtstart.ok_or("Missing DTSTART")?;
|
||||
|
||||
let vevent = VEvent {
|
||||
uid: uid.unwrap_or_else(|| Uuid::new_v4().to_string()),
|
||||
dtstart,
|
||||
dtend,
|
||||
summary,
|
||||
description,
|
||||
location,
|
||||
all_day,
|
||||
rrule,
|
||||
exdate: Vec::new(), // External calendars don't need exception handling
|
||||
recurrence_id: None,
|
||||
created: None,
|
||||
last_modified: None,
|
||||
dtstamp: Utc::now(),
|
||||
sequence: Some(0),
|
||||
status: None,
|
||||
transp: None,
|
||||
organizer: None,
|
||||
attendees: Vec::new(),
|
||||
url: None,
|
||||
attachments: Vec::new(),
|
||||
categories: Vec::new(),
|
||||
priority: None,
|
||||
resources: Vec::new(),
|
||||
related_to: None,
|
||||
geo: None,
|
||||
duration: None,
|
||||
class: None,
|
||||
contact: None,
|
||||
comment: None,
|
||||
rdate: Vec::new(),
|
||||
alarms: Vec::new(),
|
||||
etag: None,
|
||||
href: None,
|
||||
calendar_path: None,
|
||||
};
|
||||
|
||||
Ok(vevent)
|
||||
}
|
||||
|
||||
fn parse_datetime_with_tz(datetime_str: &str, tzid: Option<&str>) -> Option<DateTime<Utc>> {
|
||||
use chrono::TimeZone;
|
||||
use chrono_tz::Tz;
|
||||
|
||||
|
||||
// Try various datetime formats commonly found in ICS files
|
||||
|
||||
// Format: 20231201T103000Z (UTC) - handle as naive datetime first
|
||||
if datetime_str.ends_with('Z') {
|
||||
let datetime_without_z = &datetime_str[..datetime_str.len()-1];
|
||||
if let Ok(naive_dt) = chrono::NaiveDateTime::parse_from_str(datetime_without_z, "%Y%m%dT%H%M%S") {
|
||||
return Some(naive_dt.and_utc());
|
||||
}
|
||||
}
|
||||
|
||||
// Format: 20231201T103000-0500 (with timezone offset)
|
||||
if let Ok(dt) = DateTime::parse_from_str(datetime_str, "%Y%m%dT%H%M%S%z") {
|
||||
return Some(dt.with_timezone(&Utc));
|
||||
}
|
||||
|
||||
// Format: 2023-12-01T10:30:00Z (ISO format)
|
||||
if let Ok(dt) = DateTime::parse_from_str(datetime_str, "%Y-%m-%dT%H:%M:%SZ") {
|
||||
return Some(dt.with_timezone(&Utc));
|
||||
}
|
||||
|
||||
// Handle naive datetime with timezone parameter
|
||||
let naive_dt = if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(datetime_str, "%Y%m%dT%H%M%S") {
|
||||
Some(dt)
|
||||
} else if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(datetime_str, "%Y-%m-%dT%H:%M:%S") {
|
||||
Some(dt)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
if let Some(naive_dt) = naive_dt {
|
||||
// If TZID is provided, try to parse it
|
||||
if let Some(tzid_str) = tzid {
|
||||
// Handle common timezone formats
|
||||
let tz_result = if tzid_str.starts_with("/mozilla.org/") {
|
||||
// Mozilla/Thunderbird format: /mozilla.org/20070129_1/Europe/London
|
||||
tzid_str.split('/').last().and_then(|tz_name| tz_name.parse::<Tz>().ok())
|
||||
} else if tzid_str.contains('/') {
|
||||
// Standard timezone format: America/New_York, Europe/London
|
||||
tzid_str.parse::<Tz>().ok()
|
||||
} else {
|
||||
// Try common abbreviations and Windows timezone names
|
||||
match tzid_str {
|
||||
// Standard abbreviations
|
||||
"EST" => Some(Tz::America__New_York),
|
||||
"PST" => Some(Tz::America__Los_Angeles),
|
||||
"MST" => Some(Tz::America__Denver),
|
||||
"CST" => Some(Tz::America__Chicago),
|
||||
|
||||
// North America - Windows timezone names to IANA mapping
|
||||
"Mountain Standard Time" => Some(Tz::America__Denver),
|
||||
"Eastern Standard Time" => Some(Tz::America__New_York),
|
||||
"Central Standard Time" => Some(Tz::America__Chicago),
|
||||
"Pacific Standard Time" => Some(Tz::America__Los_Angeles),
|
||||
"Mountain Daylight Time" => Some(Tz::America__Denver),
|
||||
"Eastern Daylight Time" => Some(Tz::America__New_York),
|
||||
"Central Daylight Time" => Some(Tz::America__Chicago),
|
||||
"Pacific Daylight Time" => Some(Tz::America__Los_Angeles),
|
||||
"Hawaiian Standard Time" => Some(Tz::Pacific__Honolulu),
|
||||
"Alaskan Standard Time" => Some(Tz::America__Anchorage),
|
||||
"Alaskan Daylight Time" => Some(Tz::America__Anchorage),
|
||||
"Atlantic Standard Time" => Some(Tz::America__Halifax),
|
||||
"Newfoundland Standard Time" => Some(Tz::America__St_Johns),
|
||||
|
||||
// Europe
|
||||
"GMT Standard Time" => Some(Tz::Europe__London),
|
||||
"Greenwich Standard Time" => Some(Tz::UTC),
|
||||
"W. Europe Standard Time" => Some(Tz::Europe__Berlin),
|
||||
"Central Europe Standard Time" => Some(Tz::Europe__Warsaw),
|
||||
"Romance Standard Time" => Some(Tz::Europe__Paris),
|
||||
"Central European Standard Time" => Some(Tz::Europe__Belgrade),
|
||||
"E. Europe Standard Time" => Some(Tz::Europe__Bucharest),
|
||||
"FLE Standard Time" => Some(Tz::Europe__Helsinki),
|
||||
"GTB Standard Time" => Some(Tz::Europe__Athens),
|
||||
"Russian Standard Time" => Some(Tz::Europe__Moscow),
|
||||
"Turkey Standard Time" => Some(Tz::Europe__Istanbul),
|
||||
|
||||
// Asia
|
||||
"China Standard Time" => Some(Tz::Asia__Shanghai),
|
||||
"Tokyo Standard Time" => Some(Tz::Asia__Tokyo),
|
||||
"Korea Standard Time" => Some(Tz::Asia__Seoul),
|
||||
"Singapore Standard Time" => Some(Tz::Asia__Singapore),
|
||||
"India Standard Time" => Some(Tz::Asia__Kolkata),
|
||||
"Pakistan Standard Time" => Some(Tz::Asia__Karachi),
|
||||
"Bangladesh Standard Time" => Some(Tz::Asia__Dhaka),
|
||||
"Thailand Standard Time" => Some(Tz::Asia__Bangkok),
|
||||
"SE Asia Standard Time" => Some(Tz::Asia__Bangkok),
|
||||
"Myanmar Standard Time" => Some(Tz::Asia__Yangon),
|
||||
"Sri Lanka Standard Time" => Some(Tz::Asia__Colombo),
|
||||
"Nepal Standard Time" => Some(Tz::Asia__Kathmandu),
|
||||
"Central Asia Standard Time" => Some(Tz::Asia__Almaty),
|
||||
"West Asia Standard Time" => Some(Tz::Asia__Tashkent),
|
||||
"Afghanistan Standard Time" => Some(Tz::Asia__Kabul),
|
||||
"Iran Standard Time" => Some(Tz::Asia__Tehran),
|
||||
"Arabian Standard Time" => Some(Tz::Asia__Dubai),
|
||||
"Arab Standard Time" => Some(Tz::Asia__Riyadh),
|
||||
"Israel Standard Time" => Some(Tz::Asia__Jerusalem),
|
||||
"Jordan Standard Time" => Some(Tz::Asia__Amman),
|
||||
"Syria Standard Time" => Some(Tz::Asia__Damascus),
|
||||
"Middle East Standard Time" => Some(Tz::Asia__Beirut),
|
||||
"Egypt Standard Time" => Some(Tz::Africa__Cairo),
|
||||
"South Africa Standard Time" => Some(Tz::Africa__Johannesburg),
|
||||
"E. Africa Standard Time" => Some(Tz::Africa__Nairobi),
|
||||
"W. Central Africa Standard Time" => Some(Tz::Africa__Lagos),
|
||||
|
||||
// Asia Pacific
|
||||
"AUS Eastern Standard Time" => Some(Tz::Australia__Sydney),
|
||||
"AUS Central Standard Time" => Some(Tz::Australia__Darwin),
|
||||
"W. Australia Standard Time" => Some(Tz::Australia__Perth),
|
||||
"Tasmania Standard Time" => Some(Tz::Australia__Hobart),
|
||||
"New Zealand Standard Time" => Some(Tz::Pacific__Auckland),
|
||||
"Fiji Standard Time" => Some(Tz::Pacific__Fiji),
|
||||
"Tonga Standard Time" => Some(Tz::Pacific__Tongatapu),
|
||||
|
||||
// South America
|
||||
"Argentina Standard Time" => Some(Tz::America__Buenos_Aires),
|
||||
"E. South America Standard Time" => Some(Tz::America__Sao_Paulo),
|
||||
"SA Eastern Standard Time" => Some(Tz::America__Cayenne),
|
||||
"SA Pacific Standard Time" => Some(Tz::America__Bogota),
|
||||
"SA Western Standard Time" => Some(Tz::America__La_Paz),
|
||||
"Pacific SA Standard Time" => Some(Tz::America__Santiago),
|
||||
"Venezuela Standard Time" => Some(Tz::America__Caracas),
|
||||
"Montevideo Standard Time" => Some(Tz::America__Montevideo),
|
||||
|
||||
// Try parsing as IANA name
|
||||
_ => tzid_str.parse::<Tz>().ok()
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(tz) = tz_result {
|
||||
if let Some(dt_with_tz) = tz.from_local_datetime(&naive_dt).single() {
|
||||
return Some(dt_with_tz.with_timezone(&Utc));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If no timezone info or parsing failed, treat as UTC (safer than local time assumptions)
|
||||
return Some(chrono::TimeZone::from_utc_datetime(&Utc, &naive_dt));
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Deduplicate events based on UID, start time, and summary
|
||||
/// Some calendar systems (like Outlook) may include duplicate events in ICS feeds
|
||||
/// This includes both exact duplicates and recurring event instances that would be
|
||||
/// generated by existing RRULE patterns, and events with same title but different
|
||||
/// RRULE patterns that should be consolidated
|
||||
fn deduplicate_events(mut events: Vec<VEvent>) -> Vec<VEvent> {
|
||||
use std::collections::HashMap;
|
||||
|
||||
let original_count = events.len();
|
||||
|
||||
// First pass: Group by UID and prefer recurring events over single events with same UID
|
||||
let mut uid_groups: HashMap<String, Vec<VEvent>> = HashMap::new();
|
||||
|
||||
for event in events.drain(..) {
|
||||
// Debug logging to understand what's happening
|
||||
println!("🔍 Event: '{}' at {} (RRULE: {}) - UID: {}",
|
||||
event.summary.as_ref().unwrap_or(&"No Title".to_string()),
|
||||
event.dtstart.format("%Y-%m-%d %H:%M"),
|
||||
if event.rrule.is_some() { "Yes" } else { "No" },
|
||||
event.uid
|
||||
);
|
||||
|
||||
uid_groups.entry(event.uid.clone()).or_insert_with(Vec::new).push(event);
|
||||
}
|
||||
|
||||
let mut uid_deduplicated_events = Vec::new();
|
||||
|
||||
for (uid, mut events_with_uid) in uid_groups.drain() {
|
||||
if events_with_uid.len() == 1 {
|
||||
// Only one event with this UID, keep it
|
||||
uid_deduplicated_events.push(events_with_uid.into_iter().next().unwrap());
|
||||
} else {
|
||||
// Multiple events with same UID - prefer recurring over non-recurring
|
||||
println!("🔍 Found {} events with UID '{}'", events_with_uid.len(), uid);
|
||||
|
||||
// Sort by preference: recurring events first, then by completeness
|
||||
events_with_uid.sort_by(|a, b| {
|
||||
let a_has_rrule = a.rrule.is_some();
|
||||
let b_has_rrule = b.rrule.is_some();
|
||||
|
||||
match (a_has_rrule, b_has_rrule) {
|
||||
(true, false) => std::cmp::Ordering::Less, // a (recurring) comes first
|
||||
(false, true) => std::cmp::Ordering::Greater, // b (recurring) comes first
|
||||
_ => {
|
||||
// Both same type (both recurring or both single) - compare by completeness
|
||||
event_completeness_score(b).cmp(&event_completeness_score(a))
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Keep the first (preferred) event
|
||||
let preferred_event = events_with_uid.into_iter().next().unwrap();
|
||||
println!("🔄 UID dedup: Keeping '{}' (RRULE: {})",
|
||||
preferred_event.summary.as_ref().unwrap_or(&"No Title".to_string()),
|
||||
if preferred_event.rrule.is_some() { "Yes" } else { "No" }
|
||||
);
|
||||
uid_deduplicated_events.push(preferred_event);
|
||||
}
|
||||
}
|
||||
|
||||
// Second pass: separate recurring and single events from UID-deduplicated set
|
||||
let mut recurring_events = Vec::new();
|
||||
let mut single_events = Vec::new();
|
||||
|
||||
for event in uid_deduplicated_events.drain(..) {
|
||||
if event.rrule.is_some() {
|
||||
recurring_events.push(event);
|
||||
} else {
|
||||
single_events.push(event);
|
||||
}
|
||||
}
|
||||
|
||||
// Third pass: Group recurring events by normalized title and consolidate different RRULE patterns
|
||||
let mut title_groups: HashMap<String, Vec<VEvent>> = HashMap::new();
|
||||
|
||||
for event in recurring_events.drain(..) {
|
||||
let title = normalize_title(event.summary.as_ref().unwrap_or(&String::new()));
|
||||
title_groups.entry(title).or_insert_with(Vec::new).push(event);
|
||||
}
|
||||
|
||||
let mut deduplicated_recurring = Vec::new();
|
||||
|
||||
for (title, events_with_title) in title_groups.drain() {
|
||||
if events_with_title.len() == 1 {
|
||||
// Single event with this title, keep as-is
|
||||
deduplicated_recurring.push(events_with_title.into_iter().next().unwrap());
|
||||
} else {
|
||||
// Multiple events with same title - consolidate or deduplicate
|
||||
println!("🔍 Found {} events with title '{}'", events_with_title.len(), title);
|
||||
|
||||
// Check if these are actually different recurring patterns for the same logical event
|
||||
let consolidated = consolidate_same_title_events(events_with_title);
|
||||
deduplicated_recurring.extend(consolidated);
|
||||
}
|
||||
}
|
||||
|
||||
// Fourth pass: filter single events, removing those that would be generated by recurring events
|
||||
let mut deduplicated_single = Vec::new();
|
||||
let mut seen_single: HashMap<String, usize> = HashMap::new();
|
||||
|
||||
for event in single_events.drain(..) {
|
||||
let normalized_title = normalize_title(event.summary.as_ref().unwrap_or(&String::new()));
|
||||
let dedup_key = format!(
|
||||
"{}|{}",
|
||||
event.dtstart.format("%Y%m%dT%H%M%S"),
|
||||
normalized_title
|
||||
);
|
||||
|
||||
// First check for exact duplicates among single events
|
||||
if let Some(&existing_index) = seen_single.get(&dedup_key) {
|
||||
let existing_event: &VEvent = &deduplicated_single[existing_index];
|
||||
let current_completeness = event_completeness_score(&event);
|
||||
let existing_completeness = event_completeness_score(existing_event);
|
||||
|
||||
if current_completeness > existing_completeness {
|
||||
println!("🔄 Replacing single event: Keeping '{}' over '{}'",
|
||||
event.summary.as_ref().unwrap_or(&"No Title".to_string()),
|
||||
existing_event.summary.as_ref().unwrap_or(&"No Title".to_string())
|
||||
);
|
||||
deduplicated_single[existing_index] = event;
|
||||
} else {
|
||||
println!("🚫 Discarding duplicate single event: Keeping existing '{}'",
|
||||
existing_event.summary.as_ref().unwrap_or(&"No Title".to_string())
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Check if this single event would be generated by any recurring event
|
||||
let is_rrule_generated = deduplicated_recurring.iter().any(|recurring_event| {
|
||||
// Check if this single event matches the recurring event's pattern (use normalized titles)
|
||||
let single_title = normalize_title(event.summary.as_ref().unwrap_or(&String::new()));
|
||||
let recurring_title = normalize_title(recurring_event.summary.as_ref().unwrap_or(&String::new()));
|
||||
|
||||
if single_title != recurring_title {
|
||||
return false; // Different events
|
||||
}
|
||||
|
||||
// Check if this single event would be generated by the recurring event
|
||||
would_event_be_generated_by_rrule(recurring_event, &event)
|
||||
});
|
||||
|
||||
if is_rrule_generated {
|
||||
println!("🚫 Discarding RRULE-generated instance: '{}' at {} would be generated by recurring event",
|
||||
event.summary.as_ref().unwrap_or(&"No Title".to_string()),
|
||||
event.dtstart.format("%Y-%m-%d %H:%M")
|
||||
);
|
||||
} else {
|
||||
// This is a unique single event
|
||||
seen_single.insert(dedup_key, deduplicated_single.len());
|
||||
deduplicated_single.push(event);
|
||||
}
|
||||
}
|
||||
|
||||
// Combine recurring and single events
|
||||
let mut result = deduplicated_recurring;
|
||||
result.extend(deduplicated_single);
|
||||
|
||||
println!("📊 Deduplication complete: {} -> {} events ({} recurring, {} single)",
|
||||
original_count, result.len(),
|
||||
result.iter().filter(|e| e.rrule.is_some()).count(),
|
||||
result.iter().filter(|e| e.rrule.is_none()).count()
|
||||
);
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
/// Normalize title for grouping similar events
|
||||
fn normalize_title(title: &str) -> String {
|
||||
title.trim()
|
||||
.to_lowercase()
|
||||
.chars()
|
||||
.filter(|c| c.is_alphanumeric() || c.is_whitespace())
|
||||
.collect::<String>()
|
||||
.split_whitespace()
|
||||
.collect::<Vec<&str>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
/// Consolidate events with the same title but potentially different RRULE patterns
|
||||
/// This handles cases where calendar systems provide multiple recurring definitions
|
||||
/// for the same logical meeting (e.g., one RRULE for Tuesdays, another for Thursdays)
|
||||
fn consolidate_same_title_events(events: Vec<VEvent>) -> Vec<VEvent> {
|
||||
if events.is_empty() {
|
||||
return events;
|
||||
}
|
||||
|
||||
// Log the RRULEs we're working with
|
||||
for event in &events {
|
||||
if let Some(rrule) = &event.rrule {
|
||||
println!("🔍 RRULE for '{}': {}",
|
||||
event.summary.as_ref().unwrap_or(&"No Title".to_string()),
|
||||
rrule
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Check if all events have similar time patterns and could be consolidated
|
||||
let first_event = &events[0];
|
||||
let base_time = first_event.dtstart.time();
|
||||
let base_duration = if let Some(end) = first_event.dtend {
|
||||
Some(end.signed_duration_since(first_event.dtstart))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Check if all events have the same time and duration
|
||||
let can_consolidate = events.iter().all(|event| {
|
||||
let same_time = event.dtstart.time() == base_time;
|
||||
let same_duration = match (event.dtend, base_duration) {
|
||||
(Some(end), Some(base_dur)) => end.signed_duration_since(event.dtstart) == base_dur,
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
};
|
||||
same_time && same_duration
|
||||
});
|
||||
|
||||
if !can_consolidate {
|
||||
println!("🚫 Cannot consolidate events - different times or durations");
|
||||
// Just deduplicate exact duplicates
|
||||
return deduplicate_exact_recurring_events(events);
|
||||
}
|
||||
|
||||
// Try to detect if these are complementary weekly patterns
|
||||
let weekly_events: Vec<_> = events.iter()
|
||||
.filter(|e| e.rrule.as_ref().map_or(false, |r| r.contains("FREQ=WEEKLY")))
|
||||
.collect();
|
||||
|
||||
if weekly_events.len() >= 2 && weekly_events.len() == events.len() {
|
||||
// All events are weekly - try to consolidate into a single multi-day weekly pattern
|
||||
if let Some(consolidated) = consolidate_weekly_patterns(&events) {
|
||||
println!("✅ Successfully consolidated {} weekly patterns into one", events.len());
|
||||
return vec![consolidated];
|
||||
}
|
||||
}
|
||||
|
||||
// If we can't consolidate, just deduplicate exact matches and keep the most complete one
|
||||
println!("🚫 Cannot consolidate - keeping most complete event");
|
||||
let deduplicated = deduplicate_exact_recurring_events(events);
|
||||
|
||||
// If we still have multiple events, keep only the most complete one
|
||||
if deduplicated.len() > 1 {
|
||||
let best_event = deduplicated.into_iter()
|
||||
.max_by_key(|e| event_completeness_score(e))
|
||||
.unwrap();
|
||||
|
||||
println!("🎯 Kept most complete event: '{}'",
|
||||
best_event.summary.as_ref().unwrap_or(&"No Title".to_string())
|
||||
);
|
||||
vec![best_event]
|
||||
} else {
|
||||
deduplicated
|
||||
}
|
||||
}
|
||||
|
||||
/// Deduplicate exact recurring event matches
|
||||
fn deduplicate_exact_recurring_events(events: Vec<VEvent>) -> Vec<VEvent> {
|
||||
use std::collections::HashMap;
|
||||
|
||||
let mut seen: HashMap<String, usize> = HashMap::new();
|
||||
let mut deduplicated = Vec::new();
|
||||
|
||||
for event in events {
|
||||
let dedup_key = format!(
|
||||
"{}|{}|{}",
|
||||
event.dtstart.format("%Y%m%dT%H%M%S"),
|
||||
event.summary.as_ref().unwrap_or(&String::new()),
|
||||
event.rrule.as_ref().unwrap_or(&String::new())
|
||||
);
|
||||
|
||||
if let Some(&existing_index) = seen.get(&dedup_key) {
|
||||
let existing_event: &VEvent = &deduplicated[existing_index];
|
||||
let current_completeness = event_completeness_score(&event);
|
||||
let existing_completeness = event_completeness_score(existing_event);
|
||||
|
||||
if current_completeness > existing_completeness {
|
||||
println!("🔄 Replacing exact duplicate: Keeping more complete event");
|
||||
deduplicated[existing_index] = event;
|
||||
}
|
||||
} else {
|
||||
seen.insert(dedup_key, deduplicated.len());
|
||||
deduplicated.push(event);
|
||||
}
|
||||
}
|
||||
|
||||
deduplicated
|
||||
}
|
||||
|
||||
/// Attempt to consolidate multiple weekly RRULE patterns into a single pattern
|
||||
fn consolidate_weekly_patterns(events: &[VEvent]) -> Option<VEvent> {
|
||||
use std::collections::HashSet;
|
||||
|
||||
let mut all_days = HashSet::new();
|
||||
let mut base_event = None;
|
||||
|
||||
for event in events {
|
||||
let Some(rrule) = &event.rrule else { continue; };
|
||||
|
||||
if !rrule.contains("FREQ=WEEKLY") {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Extract BYDAY if present
|
||||
if let Some(byday_part) = rrule.split(';').find(|part| part.starts_with("BYDAY=")) {
|
||||
let days_str = byday_part.strip_prefix("BYDAY=").unwrap_or("");
|
||||
for day in days_str.split(',') {
|
||||
all_days.insert(day.trim().to_string());
|
||||
}
|
||||
} else {
|
||||
// If no BYDAY specified, use the weekday from the start date
|
||||
let weekday = match event.dtstart.weekday() {
|
||||
chrono::Weekday::Mon => "MO",
|
||||
chrono::Weekday::Tue => "TU",
|
||||
chrono::Weekday::Wed => "WE",
|
||||
chrono::Weekday::Thu => "TH",
|
||||
chrono::Weekday::Fri => "FR",
|
||||
chrono::Weekday::Sat => "SA",
|
||||
chrono::Weekday::Sun => "SU",
|
||||
};
|
||||
all_days.insert(weekday.to_string());
|
||||
}
|
||||
|
||||
// Use the first event as the base (we already know they have same time/duration)
|
||||
if base_event.is_none() {
|
||||
base_event = Some(event.clone());
|
||||
}
|
||||
}
|
||||
|
||||
if all_days.is_empty() || base_event.is_none() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Create consolidated RRULE
|
||||
let mut base = base_event.unwrap();
|
||||
let days_list: Vec<_> = all_days.into_iter().collect();
|
||||
let byday_str = days_list.join(",");
|
||||
|
||||
// Build new RRULE with consolidated BYDAY
|
||||
let new_rrule = if let Some(existing_rrule) = &base.rrule {
|
||||
// Remove existing BYDAY and add our consolidated one
|
||||
let parts: Vec<_> = existing_rrule.split(';')
|
||||
.filter(|part| !part.starts_with("BYDAY="))
|
||||
.collect();
|
||||
format!("{};BYDAY={}", parts.join(";"), byday_str)
|
||||
} else {
|
||||
format!("FREQ=WEEKLY;BYDAY={}", byday_str)
|
||||
};
|
||||
|
||||
base.rrule = Some(new_rrule);
|
||||
|
||||
println!("🔗 Consolidated weekly pattern: BYDAY={}", byday_str);
|
||||
Some(base)
|
||||
}
|
||||
|
||||
/// Check if a single event would be generated by a recurring event's RRULE
|
||||
fn would_event_be_generated_by_rrule(recurring_event: &VEvent, single_event: &VEvent) -> bool {
|
||||
let Some(rrule) = &recurring_event.rrule else {
|
||||
return false; // No RRULE to check against
|
||||
};
|
||||
|
||||
// Parse basic RRULE patterns
|
||||
if rrule.contains("FREQ=DAILY") {
|
||||
// Daily recurrence
|
||||
let interval = extract_interval_from_rrule(rrule).unwrap_or(1);
|
||||
let days_diff = (single_event.dtstart.date_naive() - recurring_event.dtstart.date_naive()).num_days();
|
||||
|
||||
if days_diff >= 0 && days_diff % interval as i64 == 0 {
|
||||
// Check if times match (allowing for timezone differences within same day)
|
||||
let recurring_time = recurring_event.dtstart.time();
|
||||
let single_time = single_event.dtstart.time();
|
||||
return recurring_time == single_time;
|
||||
}
|
||||
} else if rrule.contains("FREQ=WEEKLY") {
|
||||
// Weekly recurrence
|
||||
let interval = extract_interval_from_rrule(rrule).unwrap_or(1);
|
||||
let days_diff = (single_event.dtstart.date_naive() - recurring_event.dtstart.date_naive()).num_days();
|
||||
|
||||
// First check if it's the same day of week and time
|
||||
let recurring_weekday = recurring_event.dtstart.weekday();
|
||||
let single_weekday = single_event.dtstart.weekday();
|
||||
let recurring_time = recurring_event.dtstart.time();
|
||||
let single_time = single_event.dtstart.time();
|
||||
|
||||
if recurring_weekday == single_weekday && recurring_time == single_time && days_diff >= 0 {
|
||||
// Calculate how many weeks apart they are
|
||||
let weeks_diff = days_diff / 7;
|
||||
// Check if this falls on an interval boundary
|
||||
return weeks_diff % interval as i64 == 0;
|
||||
}
|
||||
} else if rrule.contains("FREQ=MONTHLY") {
|
||||
// Monthly recurrence - simplified check
|
||||
let months_diff = (single_event.dtstart.year() - recurring_event.dtstart.year()) * 12
|
||||
+ (single_event.dtstart.month() as i32 - recurring_event.dtstart.month() as i32);
|
||||
|
||||
if months_diff >= 0 {
|
||||
let interval = extract_interval_from_rrule(rrule).unwrap_or(1) as i32;
|
||||
if months_diff % interval == 0 {
|
||||
// Same day of month and time
|
||||
return recurring_event.dtstart.day() == single_event.dtstart.day()
|
||||
&& recurring_event.dtstart.time() == single_event.dtstart.time();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
/// Extract INTERVAL value from RRULE string, defaulting to 1 if not found
|
||||
fn extract_interval_from_rrule(rrule: &str) -> Option<u32> {
|
||||
for part in rrule.split(';') {
|
||||
if part.starts_with("INTERVAL=") {
|
||||
return part.strip_prefix("INTERVAL=")
|
||||
.and_then(|s| s.parse().ok());
|
||||
}
|
||||
}
|
||||
Some(1) // Default interval is 1 if not specified
|
||||
}
|
||||
|
||||
/// Calculate a completeness score for an event based on how many optional fields are filled
|
||||
fn event_completeness_score(event: &VEvent) -> u32 {
|
||||
let mut score = 0;
|
||||
|
||||
if event.summary.is_some() { score += 1; }
|
||||
if event.description.is_some() { score += 1; }
|
||||
if event.location.is_some() { score += 1; }
|
||||
if event.dtend.is_some() { score += 1; }
|
||||
if event.rrule.is_some() { score += 1; }
|
||||
if !event.categories.is_empty() { score += 1; }
|
||||
if !event.alarms.is_empty() { score += 1; }
|
||||
if event.organizer.is_some() { score += 1; }
|
||||
if !event.attendees.is_empty() { score += 1; }
|
||||
|
||||
score
|
||||
}
|
||||
15
backend/src/handlers/mod.rs
Normal file
15
backend/src/handlers/mod.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
pub mod auth;
|
||||
pub mod calendar;
|
||||
pub mod events;
|
||||
pub mod external_calendars;
|
||||
pub mod ics_fetcher;
|
||||
pub mod preferences;
|
||||
pub mod series;
|
||||
|
||||
pub use auth::*;
|
||||
pub use calendar::*;
|
||||
pub use events::*;
|
||||
pub use external_calendars::*;
|
||||
pub use ics_fetcher::*;
|
||||
pub use preferences::*;
|
||||
pub use series::*;
|
||||
133
backend/src/handlers/preferences.rs
Normal file
133
backend/src/handlers/preferences.rs
Normal file
@@ -0,0 +1,133 @@
|
||||
use axum::{
|
||||
extract::State,
|
||||
http::{HeaderMap, StatusCode},
|
||||
response::IntoResponse,
|
||||
Json,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
db::PreferencesRepository,
|
||||
models::{ApiError, UpdatePreferencesRequest, UserPreferencesResponse},
|
||||
AppState,
|
||||
};
|
||||
|
||||
/// Get user preferences
|
||||
pub async fn get_preferences(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<impl IntoResponse, ApiError> {
|
||||
// Extract session token from headers
|
||||
let session_token = headers
|
||||
.get("X-Session-Token")
|
||||
.and_then(|h| h.to_str().ok())
|
||||
.ok_or_else(|| ApiError::Unauthorized("Missing session token".to_string()))?;
|
||||
|
||||
// Validate session and get user ID
|
||||
let user_id = state.auth_service.validate_session(session_token).await?;
|
||||
|
||||
// Get preferences from database
|
||||
let prefs_repo = PreferencesRepository::new(&state.db);
|
||||
let preferences = prefs_repo
|
||||
.get_or_create(&user_id)
|
||||
.await
|
||||
.map_err(|e| ApiError::Database(format!("Failed to get preferences: {}", e)))?;
|
||||
|
||||
Ok(Json(UserPreferencesResponse {
|
||||
calendar_selected_date: preferences.calendar_selected_date,
|
||||
calendar_time_increment: preferences.calendar_time_increment,
|
||||
calendar_view_mode: preferences.calendar_view_mode,
|
||||
calendar_theme: preferences.calendar_theme,
|
||||
calendar_style: preferences.calendar_style,
|
||||
calendar_colors: preferences.calendar_colors,
|
||||
last_used_calendar: preferences.last_used_calendar,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Update user preferences
|
||||
pub async fn update_preferences(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
Json(request): Json<UpdatePreferencesRequest>,
|
||||
) -> Result<impl IntoResponse, ApiError> {
|
||||
// Extract session token from headers
|
||||
let session_token = headers
|
||||
.get("X-Session-Token")
|
||||
.and_then(|h| h.to_str().ok())
|
||||
.ok_or_else(|| ApiError::Unauthorized("Missing session token".to_string()))?;
|
||||
|
||||
// Validate session and get user ID
|
||||
let user_id = state.auth_service.validate_session(session_token).await?;
|
||||
|
||||
// Update preferences in database
|
||||
let prefs_repo = PreferencesRepository::new(&state.db);
|
||||
|
||||
let mut preferences = prefs_repo
|
||||
.get_or_create(&user_id)
|
||||
.await
|
||||
.map_err(|e| ApiError::Database(format!("Failed to get preferences: {}", e)))?;
|
||||
|
||||
// Update only provided fields
|
||||
if request.calendar_selected_date.is_some() {
|
||||
preferences.calendar_selected_date = request.calendar_selected_date;
|
||||
}
|
||||
if request.calendar_time_increment.is_some() {
|
||||
preferences.calendar_time_increment = request.calendar_time_increment;
|
||||
}
|
||||
if request.calendar_view_mode.is_some() {
|
||||
preferences.calendar_view_mode = request.calendar_view_mode;
|
||||
}
|
||||
if request.calendar_theme.is_some() {
|
||||
preferences.calendar_theme = request.calendar_theme;
|
||||
}
|
||||
if request.calendar_style.is_some() {
|
||||
preferences.calendar_style = request.calendar_style;
|
||||
}
|
||||
if request.calendar_colors.is_some() {
|
||||
preferences.calendar_colors = request.calendar_colors;
|
||||
}
|
||||
if request.last_used_calendar.is_some() {
|
||||
preferences.last_used_calendar = request.last_used_calendar;
|
||||
}
|
||||
|
||||
prefs_repo
|
||||
.update(&preferences)
|
||||
.await
|
||||
.map_err(|e| ApiError::Database(format!("Failed to update preferences: {}", e)))?;
|
||||
|
||||
Ok((
|
||||
StatusCode::OK,
|
||||
Json(UserPreferencesResponse {
|
||||
calendar_selected_date: preferences.calendar_selected_date,
|
||||
calendar_time_increment: preferences.calendar_time_increment,
|
||||
calendar_view_mode: preferences.calendar_view_mode,
|
||||
calendar_theme: preferences.calendar_theme,
|
||||
calendar_style: preferences.calendar_style,
|
||||
calendar_colors: preferences.calendar_colors,
|
||||
last_used_calendar: preferences.last_used_calendar,
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
/// Logout user
|
||||
pub async fn logout(
|
||||
State(state): State<Arc<AppState>>,
|
||||
headers: HeaderMap,
|
||||
) -> Result<impl IntoResponse, ApiError> {
|
||||
// Extract session token from headers
|
||||
let session_token = headers
|
||||
.get("X-Session-Token")
|
||||
.and_then(|h| h.to_str().ok())
|
||||
.ok_or_else(|| ApiError::Unauthorized("Missing session token".to_string()))?;
|
||||
|
||||
// Delete session
|
||||
state.auth_service.logout(session_token).await?;
|
||||
|
||||
Ok((
|
||||
StatusCode::OK,
|
||||
Json(serde_json::json!({
|
||||
"success": true,
|
||||
"message": "Logged out successfully"
|
||||
})),
|
||||
))
|
||||
}
|
||||
1198
backend/src/handlers/series.rs
Normal file
1198
backend/src/handlers/series.rs
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,35 +1,45 @@
|
||||
use axum::{
|
||||
response::Json,
|
||||
routing::{get, post},
|
||||
routing::{delete, get, post},
|
||||
Router,
|
||||
};
|
||||
use tower_http::cors::{CorsLayer, Any};
|
||||
use std::sync::Arc;
|
||||
use tower_http::cors::{Any, CorsLayer};
|
||||
|
||||
mod auth;
|
||||
mod models;
|
||||
mod handlers;
|
||||
mod calendar;
|
||||
mod config;
|
||||
pub mod auth;
|
||||
pub mod calendar;
|
||||
pub mod config;
|
||||
pub mod db;
|
||||
pub mod handlers;
|
||||
pub mod models;
|
||||
|
||||
use auth::AuthService;
|
||||
use db::Database;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub auth_service: AuthService,
|
||||
pub db: Database,
|
||||
}
|
||||
|
||||
pub async fn run_server() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Initialize logging
|
||||
println!("🚀 Starting Calendar Backend Server");
|
||||
|
||||
// Initialize database
|
||||
let database_url = std::env::var("DATABASE_URL")
|
||||
.unwrap_or_else(|_| "sqlite:calendar.db".to_string());
|
||||
|
||||
let db = Database::new(&database_url).await?;
|
||||
println!("✅ Database initialized");
|
||||
|
||||
// Create auth service
|
||||
let jwt_secret = std::env::var("JWT_SECRET")
|
||||
.unwrap_or_else(|_| "your-super-secret-jwt-key-change-in-production".to_string());
|
||||
|
||||
let auth_service = AuthService::new(jwt_secret);
|
||||
|
||||
let app_state = AppState { auth_service };
|
||||
|
||||
let auth_service = AuthService::new(jwt_secret, db.clone());
|
||||
|
||||
let app_state = AppState { auth_service, db };
|
||||
|
||||
// Build our application with routes
|
||||
let app = Router::new()
|
||||
@@ -42,8 +52,32 @@ pub async fn run_server() -> Result<(), Box<dyn std::error::Error>> {
|
||||
.route("/api/calendar/delete", post(handlers::delete_calendar))
|
||||
.route("/api/calendar/events", get(handlers::get_calendar_events))
|
||||
.route("/api/calendar/events/create", post(handlers::create_event))
|
||||
.route("/api/calendar/events/update", post(handlers::update_event))
|
||||
.route("/api/calendar/events/delete", post(handlers::delete_event))
|
||||
.route("/api/calendar/events/:uid", get(handlers::refresh_event))
|
||||
// Event series-specific endpoints
|
||||
.route(
|
||||
"/api/calendar/events/series/create",
|
||||
post(handlers::create_event_series),
|
||||
)
|
||||
.route(
|
||||
"/api/calendar/events/series/update",
|
||||
post(handlers::update_event_series),
|
||||
)
|
||||
.route(
|
||||
"/api/calendar/events/series/delete",
|
||||
post(handlers::delete_event_series),
|
||||
)
|
||||
// User preferences endpoints
|
||||
.route("/api/preferences", get(handlers::get_preferences))
|
||||
.route("/api/preferences", post(handlers::update_preferences))
|
||||
.route("/api/auth/logout", post(handlers::logout))
|
||||
// External calendars endpoints
|
||||
.route("/api/external-calendars", get(handlers::get_external_calendars))
|
||||
.route("/api/external-calendars", post(handlers::create_external_calendar))
|
||||
.route("/api/external-calendars/:id", post(handlers::update_external_calendar))
|
||||
.route("/api/external-calendars/:id", delete(handlers::delete_external_calendar))
|
||||
.route("/api/external-calendars/:id/events", get(handlers::fetch_external_calendar_events))
|
||||
.layer(
|
||||
CorsLayer::new()
|
||||
.allow_origin(Any)
|
||||
@@ -55,7 +89,7 @@ pub async fn run_server() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Start server
|
||||
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
|
||||
println!("📡 Server listening on http://0.0.0.0:3000");
|
||||
|
||||
|
||||
axum::serve(listener, app).await?;
|
||||
|
||||
Ok(())
|
||||
@@ -71,4 +105,4 @@ async fn health_check() -> Json<serde_json::Value> {
|
||||
"service": "calendar-backend",
|
||||
"version": "0.1.0"
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,4 +4,4 @@ use calendar_backend::*;
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
run_server().await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,8 +16,32 @@ pub struct CalDAVLoginRequest {
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct AuthResponse {
|
||||
pub token: String,
|
||||
pub session_token: String,
|
||||
pub username: String,
|
||||
pub server_url: String,
|
||||
pub preferences: UserPreferencesResponse,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
pub struct UserPreferencesResponse {
|
||||
pub calendar_selected_date: Option<String>,
|
||||
pub calendar_time_increment: Option<i32>,
|
||||
pub calendar_view_mode: Option<String>,
|
||||
pub calendar_theme: Option<String>,
|
||||
pub calendar_style: Option<String>,
|
||||
pub calendar_colors: Option<String>,
|
||||
pub last_used_calendar: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct UpdatePreferencesRequest {
|
||||
pub calendar_selected_date: Option<String>,
|
||||
pub calendar_time_increment: Option<i32>,
|
||||
pub calendar_view_mode: Option<String>,
|
||||
pub calendar_theme: Option<String>,
|
||||
pub calendar_style: Option<String>,
|
||||
pub calendar_colors: Option<String>,
|
||||
pub last_used_calendar: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -32,6 +56,7 @@ pub struct CalendarInfo {
|
||||
pub path: String,
|
||||
pub display_name: String,
|
||||
pub color: String,
|
||||
pub is_visible: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -62,6 +87,8 @@ pub struct DeleteCalendarResponse {
|
||||
pub struct DeleteEventRequest {
|
||||
pub calendar_path: String,
|
||||
pub event_href: String,
|
||||
pub delete_action: String, // "delete_this", "delete_following", or "delete_series"
|
||||
pub occurrence_date: Option<String>, // ISO date string for the specific occurrence
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -74,21 +101,21 @@ pub struct DeleteEventResponse {
|
||||
pub struct CreateEventRequest {
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub start_date: String, // YYYY-MM-DD format
|
||||
pub start_time: String, // HH:MM format
|
||||
pub end_date: String, // YYYY-MM-DD format
|
||||
pub end_time: String, // HH:MM format
|
||||
pub start_date: String, // YYYY-MM-DD format
|
||||
pub start_time: String, // HH:MM format
|
||||
pub end_date: String, // YYYY-MM-DD format
|
||||
pub end_time: String, // HH:MM format
|
||||
pub location: String,
|
||||
pub all_day: bool,
|
||||
pub status: String, // confirmed, tentative, cancelled
|
||||
pub class: String, // public, private, confidential
|
||||
pub priority: Option<u8>, // 0-9 priority level
|
||||
pub organizer: String, // organizer email
|
||||
pub attendees: String, // comma-separated attendee emails
|
||||
pub categories: String, // comma-separated categories
|
||||
pub reminder: String, // reminder type
|
||||
pub recurrence: String, // recurrence type
|
||||
pub recurrence_days: Vec<bool>, // [Sun, Mon, Tue, Wed, Thu, Fri, Sat] for weekly recurrence
|
||||
pub status: String, // confirmed, tentative, cancelled
|
||||
pub class: String, // public, private, confidential
|
||||
pub priority: Option<u8>, // 0-9 priority level
|
||||
pub organizer: String, // organizer email
|
||||
pub attendees: String, // comma-separated attendee emails
|
||||
pub categories: String, // comma-separated categories
|
||||
pub reminder: String, // reminder type
|
||||
pub recurrence: String, // recurrence type
|
||||
pub recurrence_days: Vec<bool>, // [Sun, Mon, Tue, Wed, Thu, Fri, Sat] for weekly recurrence
|
||||
pub calendar_path: Option<String>, // Optional - use first calendar if not specified
|
||||
}
|
||||
|
||||
@@ -99,6 +126,135 @@ pub struct CreateEventResponse {
|
||||
pub event_href: Option<String>, // The created event's href/filename
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct UpdateEventRequest {
|
||||
pub uid: String, // Event UID to identify which event to update
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub start_date: String, // YYYY-MM-DD format
|
||||
pub start_time: String, // HH:MM format
|
||||
pub end_date: String, // YYYY-MM-DD format
|
||||
pub end_time: String, // HH:MM format
|
||||
pub location: String,
|
||||
pub all_day: bool,
|
||||
pub status: String, // confirmed, tentative, cancelled
|
||||
pub class: String, // public, private, confidential
|
||||
pub priority: Option<u8>, // 0-9 priority level
|
||||
pub organizer: String, // organizer email
|
||||
pub attendees: String, // comma-separated attendee emails
|
||||
pub categories: String, // comma-separated categories
|
||||
pub reminder: String, // reminder type
|
||||
pub recurrence: String, // recurrence type
|
||||
pub recurrence_days: Vec<bool>, // [Sun, Mon, Tue, Wed, Thu, Fri, Sat] for weekly recurrence
|
||||
pub calendar_path: Option<String>, // Optional - search all calendars if not specified
|
||||
pub update_action: Option<String>, // "update_series" for recurring events
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub until_date: Option<String>, // ISO datetime string for RRULE UNTIL clause
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct UpdateEventResponse {
|
||||
pub success: bool,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
// ==================== EVENT SERIES MODELS ====================
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CreateEventSeriesRequest {
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub start_date: String, // YYYY-MM-DD format
|
||||
pub start_time: String, // HH:MM format
|
||||
pub end_date: String, // YYYY-MM-DD format
|
||||
pub end_time: String, // HH:MM format
|
||||
pub location: String,
|
||||
pub all_day: bool,
|
||||
pub status: String, // confirmed, tentative, cancelled
|
||||
pub class: String, // public, private, confidential
|
||||
pub priority: Option<u8>, // 0-9 priority level
|
||||
pub organizer: String, // organizer email
|
||||
pub attendees: String, // comma-separated attendee emails
|
||||
pub categories: String, // comma-separated categories
|
||||
pub reminder: String, // reminder type
|
||||
|
||||
// Series-specific fields
|
||||
pub recurrence: String, // recurrence type (daily, weekly, monthly, yearly)
|
||||
pub recurrence_days: Vec<bool>, // [Sun, Mon, Tue, Wed, Thu, Fri, Sat] for weekly recurrence
|
||||
pub recurrence_interval: Option<u32>, // Every N days/weeks/months/years
|
||||
pub recurrence_end_date: Option<String>, // When the series ends (YYYY-MM-DD)
|
||||
pub recurrence_count: Option<u32>, // Number of occurrences
|
||||
pub calendar_path: Option<String>, // Optional - search all calendars if not specified
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct CreateEventSeriesResponse {
|
||||
pub success: bool,
|
||||
pub message: String,
|
||||
pub series_uid: Option<String>, // The base UID for the series
|
||||
pub occurrences_created: Option<u32>, // Number of individual events created
|
||||
pub event_href: Option<String>, // The created series' href/filename
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct UpdateEventSeriesRequest {
|
||||
pub series_uid: String, // Series UID to identify which series to update
|
||||
pub title: String,
|
||||
pub description: String,
|
||||
pub start_date: String, // YYYY-MM-DD format
|
||||
pub start_time: String, // HH:MM format
|
||||
pub end_date: String, // YYYY-MM-DD format
|
||||
pub end_time: String, // HH:MM format
|
||||
pub location: String,
|
||||
pub all_day: bool,
|
||||
pub status: String, // confirmed, tentative, cancelled
|
||||
pub class: String, // public, private, confidential
|
||||
pub priority: Option<u8>, // 0-9 priority level
|
||||
pub organizer: String, // organizer email
|
||||
pub attendees: String, // comma-separated attendee emails
|
||||
pub categories: String, // comma-separated categories
|
||||
pub reminder: String, // reminder type
|
||||
|
||||
// Series-specific fields
|
||||
pub recurrence: String, // recurrence type (daily, weekly, monthly, yearly)
|
||||
pub recurrence_days: Vec<bool>, // [Sun, Mon, Tue, Wed, Thu, Fri, Sat] for weekly recurrence
|
||||
pub recurrence_interval: Option<u32>, // Every N days/weeks/months/years
|
||||
pub recurrence_end_date: Option<String>, // When the series ends (YYYY-MM-DD)
|
||||
pub recurrence_count: Option<u32>, // Number of occurrences
|
||||
pub calendar_path: Option<String>, // Optional - search all calendars if not specified
|
||||
|
||||
// Update scope control
|
||||
pub update_scope: String, // "this_only", "this_and_future", "all_in_series"
|
||||
pub occurrence_date: Option<String>, // ISO date string for specific occurrence being updated
|
||||
pub changed_fields: Option<Vec<String>>, // List of field names that were changed (for optimization)
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct UpdateEventSeriesResponse {
|
||||
pub success: bool,
|
||||
pub message: String,
|
||||
pub series_uid: Option<String>,
|
||||
pub occurrences_affected: Option<u32>, // Number of events updated
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct DeleteEventSeriesRequest {
|
||||
pub series_uid: String, // Series UID to identify which series to delete
|
||||
pub calendar_path: String,
|
||||
pub event_href: String,
|
||||
|
||||
// Delete scope control
|
||||
pub delete_scope: String, // "this_only", "this_and_future", "all_in_series"
|
||||
pub occurrence_date: Option<String>, // ISO date string for specific occurrence being deleted
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct DeleteEventSeriesResponse {
|
||||
pub success: bool,
|
||||
pub message: String,
|
||||
pub occurrences_affected: Option<u32>, // Number of events deleted
|
||||
}
|
||||
|
||||
// Error handling
|
||||
#[derive(Debug)]
|
||||
pub enum ApiError {
|
||||
@@ -143,4 +299,4 @@ impl std::fmt::Display for ApiError {
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ApiError {}
|
||||
impl std::error::Error for ApiError {}
|
||||
|
||||
726
backend/tests/integration_tests.rs
Normal file
726
backend/tests/integration_tests.rs
Normal file
@@ -0,0 +1,726 @@
|
||||
use axum::{
|
||||
response::Json,
|
||||
routing::{get, post},
|
||||
Router,
|
||||
};
|
||||
use calendar_backend::auth::AuthService;
|
||||
use calendar_backend::AppState;
|
||||
use reqwest::Client;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::time::sleep;
|
||||
use tower_http::cors::{Any, CorsLayer};
|
||||
|
||||
/// Test utilities for integration testing
|
||||
mod test_utils {
|
||||
use super::*;
|
||||
|
||||
pub struct TestServer {
|
||||
pub base_url: String,
|
||||
pub client: Client,
|
||||
}
|
||||
|
||||
impl TestServer {
|
||||
pub async fn start() -> Self {
|
||||
// Create auth service
|
||||
let jwt_secret = "test-secret-key-for-integration-tests".to_string();
|
||||
let auth_service = AuthService::new(jwt_secret);
|
||||
let app_state = AppState { auth_service };
|
||||
|
||||
// Build application with routes
|
||||
let app = Router::new()
|
||||
.route("/", get(root))
|
||||
.route("/api/health", get(health_check))
|
||||
.route("/api/auth/login", post(calendar_backend::handlers::login))
|
||||
.route(
|
||||
"/api/auth/verify",
|
||||
get(calendar_backend::handlers::verify_token),
|
||||
)
|
||||
.route(
|
||||
"/api/user/info",
|
||||
get(calendar_backend::handlers::get_user_info),
|
||||
)
|
||||
.route(
|
||||
"/api/calendar/create",
|
||||
post(calendar_backend::handlers::create_calendar),
|
||||
)
|
||||
.route(
|
||||
"/api/calendar/delete",
|
||||
post(calendar_backend::handlers::delete_calendar),
|
||||
)
|
||||
.route(
|
||||
"/api/calendar/events",
|
||||
get(calendar_backend::handlers::get_calendar_events),
|
||||
)
|
||||
.route(
|
||||
"/api/calendar/events/create",
|
||||
post(calendar_backend::handlers::create_event),
|
||||
)
|
||||
.route(
|
||||
"/api/calendar/events/update",
|
||||
post(calendar_backend::handlers::update_event),
|
||||
)
|
||||
.route(
|
||||
"/api/calendar/events/delete",
|
||||
post(calendar_backend::handlers::delete_event),
|
||||
)
|
||||
.route(
|
||||
"/api/calendar/events/:uid",
|
||||
get(calendar_backend::handlers::refresh_event),
|
||||
)
|
||||
// Event series-specific endpoints
|
||||
.route(
|
||||
"/api/calendar/events/series/create",
|
||||
post(calendar_backend::handlers::create_event_series),
|
||||
)
|
||||
.route(
|
||||
"/api/calendar/events/series/update",
|
||||
post(calendar_backend::handlers::update_event_series),
|
||||
)
|
||||
.route(
|
||||
"/api/calendar/events/series/delete",
|
||||
post(calendar_backend::handlers::delete_event_series),
|
||||
)
|
||||
.layer(
|
||||
CorsLayer::new()
|
||||
.allow_origin(Any)
|
||||
.allow_methods(Any)
|
||||
.allow_headers(Any),
|
||||
)
|
||||
.with_state(Arc::new(app_state));
|
||||
|
||||
// Start server on a random port
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let base_url = format!("http://127.0.0.1:{}", addr.port());
|
||||
|
||||
tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
|
||||
// Wait for server to start
|
||||
sleep(Duration::from_millis(100)).await;
|
||||
|
||||
let client = Client::new();
|
||||
TestServer { base_url, client }
|
||||
}
|
||||
|
||||
pub async fn login(&self) -> String {
|
||||
let login_payload = json!({
|
||||
"username": "test".to_string(),
|
||||
"password": "test".to_string(),
|
||||
"server_url": "https://example.com".to_string()
|
||||
});
|
||||
|
||||
let response = self
|
||||
.client
|
||||
.post(&format!("{}/api/auth/login", self.base_url))
|
||||
.json(&login_payload)
|
||||
.send()
|
||||
.await
|
||||
.expect("Failed to send login request");
|
||||
|
||||
assert!(
|
||||
response.status().is_success(),
|
||||
"Login failed with status: {}",
|
||||
response.status()
|
||||
);
|
||||
|
||||
let login_response: serde_json::Value = response.json().await.unwrap();
|
||||
login_response["token"]
|
||||
.as_str()
|
||||
.expect("Login response should contain token")
|
||||
.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
async fn root() -> &'static str {
|
||||
"Calendar Backend API v0.1.0"
|
||||
}
|
||||
|
||||
async fn health_check() -> Json<serde_json::Value> {
|
||||
Json(serde_json::json!({
|
||||
"status": "healthy",
|
||||
"service": "calendar-backend",
|
||||
"version": "0.1.0"
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::test_utils::*;
|
||||
use super::*;
|
||||
|
||||
/// Test the health endpoint
|
||||
#[tokio::test]
|
||||
async fn test_health_endpoint() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
let response = server
|
||||
.client
|
||||
.get(&format!("{}/api/health", server.base_url))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(response.status(), 200);
|
||||
|
||||
let health_response: serde_json::Value = response.json().await.unwrap();
|
||||
assert_eq!(health_response["status"], "healthy");
|
||||
assert_eq!(health_response["service"], "calendar-backend");
|
||||
|
||||
println!("✓ Health endpoint test passed");
|
||||
}
|
||||
|
||||
/// Test authentication login endpoint
|
||||
#[tokio::test]
|
||||
async fn test_auth_login() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
// Use test credentials
|
||||
let username = "test".to_string();
|
||||
let password = "test".to_string();
|
||||
let server_url = "https://example.com".to_string();
|
||||
|
||||
let login_payload = json!({
|
||||
"username": username,
|
||||
"password": password,
|
||||
"server_url": server_url
|
||||
});
|
||||
|
||||
let response = server
|
||||
.client
|
||||
.post(&format!("{}/api/auth/login", server.base_url))
|
||||
.json(&login_payload)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(
|
||||
response.status().is_success(),
|
||||
"Login failed with status: {}",
|
||||
response.status()
|
||||
);
|
||||
|
||||
let login_response: serde_json::Value = response.json().await.unwrap();
|
||||
assert!(
|
||||
login_response["token"].is_string(),
|
||||
"Login response should contain a token"
|
||||
);
|
||||
assert!(
|
||||
login_response["username"].is_string(),
|
||||
"Login response should contain username"
|
||||
);
|
||||
|
||||
println!("✓ Authentication login test passed");
|
||||
}
|
||||
|
||||
/// Test authentication verify endpoint
|
||||
#[tokio::test]
|
||||
async fn test_auth_verify() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
// First login to get a token
|
||||
let token = server.login().await;
|
||||
|
||||
let response = server
|
||||
.client
|
||||
.get(&format!("{}/api/auth/verify", server.base_url))
|
||||
.header("Authorization", format!("Bearer {}", token))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(response.status(), 200);
|
||||
|
||||
let verify_response: serde_json::Value = response.json().await.unwrap();
|
||||
assert!(verify_response["valid"].as_bool().unwrap_or(false));
|
||||
|
||||
println!("✓ Authentication verify test passed");
|
||||
}
|
||||
|
||||
/// Test user info endpoint
|
||||
#[tokio::test]
|
||||
async fn test_user_info() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
// First login to get a token
|
||||
let token = server.login().await;
|
||||
|
||||
// Load password from env for CalDAV requests
|
||||
dotenvy::dotenv().ok();
|
||||
let password = "test".to_string();
|
||||
|
||||
let response = server
|
||||
.client
|
||||
.get(&format!("{}/api/user/info", server.base_url))
|
||||
.header("Authorization", format!("Bearer {}", token))
|
||||
.header("X-CalDAV-Password", password)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Note: This might fail if CalDAV server discovery fails, which can happen
|
||||
if response.status().is_success() {
|
||||
let user_info: serde_json::Value = response.json().await.unwrap();
|
||||
assert!(user_info["username"].is_string());
|
||||
println!("✓ User info test passed");
|
||||
} else {
|
||||
println!(
|
||||
"⚠ User info test skipped (CalDAV server issues): {}",
|
||||
response.status()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Test calendar events listing endpoint
|
||||
#[tokio::test]
|
||||
async fn test_get_calendar_events() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
// First login to get a token
|
||||
let token = server.login().await;
|
||||
|
||||
// Load password from env for CalDAV requests
|
||||
dotenvy::dotenv().ok();
|
||||
let password = "test".to_string();
|
||||
|
||||
let response = server
|
||||
.client
|
||||
.get(&format!(
|
||||
"{}/api/calendar/events?year=2024&month=12",
|
||||
server.base_url
|
||||
))
|
||||
.header("Authorization", format!("Bearer {}", token))
|
||||
.header("X-CalDAV-Password", password)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(
|
||||
response.status().is_success(),
|
||||
"Get events failed with status: {}",
|
||||
response.status()
|
||||
);
|
||||
|
||||
let events: serde_json::Value = response.json().await.unwrap();
|
||||
assert!(events.is_array());
|
||||
|
||||
println!(
|
||||
"✓ Get calendar events test passed (found {} events)",
|
||||
events.as_array().unwrap().len()
|
||||
);
|
||||
}
|
||||
|
||||
/// Test event creation endpoint
|
||||
#[tokio::test]
|
||||
async fn test_create_event() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
// First login to get a token
|
||||
let token = server.login().await;
|
||||
|
||||
// Load password from env for CalDAV requests
|
||||
dotenvy::dotenv().ok();
|
||||
let password = "test".to_string();
|
||||
|
||||
let create_payload = json!({
|
||||
"title": "Integration Test Event",
|
||||
"description": "Created by integration test",
|
||||
"start_date": "2024-12-25",
|
||||
"start_time": "10:00",
|
||||
"end_date": "2024-12-25",
|
||||
"end_time": "11:00",
|
||||
"location": "Test Location",
|
||||
"all_day": false,
|
||||
"status": "confirmed",
|
||||
"class": "public",
|
||||
"priority": 5,
|
||||
"organizer": "test@example.com",
|
||||
"attendees": "",
|
||||
"categories": "test",
|
||||
"reminder": "15min",
|
||||
"recurrence": "none",
|
||||
"recurrence_days": [false, false, false, false, false, false, false]
|
||||
});
|
||||
|
||||
let response = server
|
||||
.client
|
||||
.post(&format!("{}/api/calendar/events/create", server.base_url))
|
||||
.header("Authorization", format!("Bearer {}", token))
|
||||
.header("X-CalDAV-Password", password)
|
||||
.json(&create_payload)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let status = response.status();
|
||||
println!("Create event response status: {}", status);
|
||||
|
||||
// Note: This might fail if CalDAV server is not accessible, which is expected in CI
|
||||
if status.is_success() {
|
||||
let create_response: serde_json::Value = response.json().await.unwrap();
|
||||
assert!(create_response["success"].as_bool().unwrap_or(false));
|
||||
println!("✓ Create event test passed");
|
||||
} else {
|
||||
println!("⚠ Create event test skipped (CalDAV server not accessible)");
|
||||
}
|
||||
}
|
||||
|
||||
/// Test event refresh endpoint
|
||||
#[tokio::test]
|
||||
async fn test_refresh_event() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
// First login to get a token
|
||||
let token = server.login().await;
|
||||
|
||||
// Load password from env for CalDAV requests
|
||||
dotenvy::dotenv().ok();
|
||||
let password = "test".to_string();
|
||||
|
||||
// Use a dummy UID for testing - this will likely return 404 but we're testing the endpoint structure
|
||||
let test_uid = "test-event-uid";
|
||||
|
||||
let response = server
|
||||
.client
|
||||
.get(&format!(
|
||||
"{}/api/calendar/events/{}",
|
||||
server.base_url, test_uid
|
||||
))
|
||||
.header("Authorization", format!("Bearer {}", token))
|
||||
.header("X-CalDAV-Password", password)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// We expect either 200 (if event exists) or 404 (if not found) - both are valid responses
|
||||
assert!(
|
||||
response.status() == 200 || response.status() == 404,
|
||||
"Refresh event failed with unexpected status: {}",
|
||||
response.status()
|
||||
);
|
||||
|
||||
println!("✓ Refresh event endpoint test passed");
|
||||
}
|
||||
|
||||
/// Test invalid authentication
|
||||
#[tokio::test]
|
||||
async fn test_invalid_auth() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
let response = server
|
||||
.client
|
||||
.get(&format!("{}/api/user/info", server.base_url))
|
||||
.header("Authorization", "Bearer invalid-token")
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Accept both 400 and 401 as valid responses for invalid tokens
|
||||
assert!(
|
||||
response.status() == 401 || response.status() == 400,
|
||||
"Expected 401 or 400 for invalid token, got {}",
|
||||
response.status()
|
||||
);
|
||||
println!("✓ Invalid authentication test passed");
|
||||
}
|
||||
|
||||
/// Test missing authentication
|
||||
#[tokio::test]
|
||||
async fn test_missing_auth() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
let response = server
|
||||
.client
|
||||
.get(&format!("{}/api/user/info", server.base_url))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(response.status(), 401);
|
||||
println!("✓ Missing authentication test passed");
|
||||
}
|
||||
|
||||
// ==================== EVENT SERIES TESTS ====================
|
||||
|
||||
/// Test event series creation endpoint
|
||||
#[tokio::test]
|
||||
async fn test_create_event_series() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
// First login to get a token
|
||||
let token = server.login().await;
|
||||
|
||||
// Load password from env for CalDAV requests
|
||||
dotenvy::dotenv().ok();
|
||||
let password = "test".to_string();
|
||||
|
||||
let create_payload = json!({
|
||||
"title": "Integration Test Series",
|
||||
"description": "Created by integration test for series",
|
||||
"start_date": "2024-12-25",
|
||||
"start_time": "10:00",
|
||||
"end_date": "2024-12-25",
|
||||
"end_time": "11:00",
|
||||
"location": "Test Series Location",
|
||||
"all_day": false,
|
||||
"status": "confirmed",
|
||||
"class": "public",
|
||||
"priority": 5,
|
||||
"organizer": "test@example.com",
|
||||
"attendees": "",
|
||||
"categories": "test-series",
|
||||
"reminder": "15min",
|
||||
"recurrence": "weekly",
|
||||
"recurrence_days": [false, true, false, false, false, false, false], // Monday only
|
||||
"recurrence_interval": 1,
|
||||
"recurrence_count": 4,
|
||||
"calendar_path": "/calendars/test/default/" // Provide explicit path to bypass discovery
|
||||
});
|
||||
|
||||
let response = server
|
||||
.client
|
||||
.post(&format!(
|
||||
"{}/api/calendar/events/series/create",
|
||||
server.base_url
|
||||
))
|
||||
.header("Authorization", format!("Bearer {}", token))
|
||||
.header("X-CalDAV-Password", password)
|
||||
.json(&create_payload)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let status = response.status();
|
||||
println!("Create series response status: {}", status);
|
||||
|
||||
// Note: This might fail if CalDAV server is not accessible, which is expected in CI
|
||||
if status.is_success() {
|
||||
let create_response: serde_json::Value = response.json().await.unwrap();
|
||||
assert!(create_response["success"].as_bool().unwrap_or(false));
|
||||
assert!(create_response["series_uid"].is_string());
|
||||
println!("✓ Create event series test passed");
|
||||
} else {
|
||||
println!("⚠ Create event series test skipped (CalDAV server not accessible)");
|
||||
}
|
||||
}
|
||||
|
||||
/// Test event series update endpoint
|
||||
#[tokio::test]
|
||||
async fn test_update_event_series() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
// First login to get a token
|
||||
let token = server.login().await;
|
||||
|
||||
// Load password from env for CalDAV requests
|
||||
dotenvy::dotenv().ok();
|
||||
let password = "test".to_string();
|
||||
|
||||
let update_payload = json!({
|
||||
"series_uid": "test-series-uid",
|
||||
"title": "Updated Series Title",
|
||||
"description": "Updated by integration test",
|
||||
"start_date": "2024-12-26",
|
||||
"start_time": "14:00",
|
||||
"end_date": "2024-12-26",
|
||||
"end_time": "15:00",
|
||||
"location": "Updated Location",
|
||||
"all_day": false,
|
||||
"status": "confirmed",
|
||||
"class": "public",
|
||||
"priority": 3,
|
||||
"organizer": "test@example.com",
|
||||
"attendees": "attendee@example.com",
|
||||
"categories": "updated-series",
|
||||
"reminder": "30min",
|
||||
"recurrence": "daily",
|
||||
"recurrence_days": [false, false, false, false, false, false, false],
|
||||
"recurrence_interval": 2,
|
||||
"recurrence_count": 10,
|
||||
"update_scope": "all_in_series",
|
||||
"calendar_path": "/calendars/test/default/" // Provide explicit path to bypass discovery
|
||||
});
|
||||
|
||||
let response = server
|
||||
.client
|
||||
.post(&format!(
|
||||
"{}/api/calendar/events/series/update",
|
||||
server.base_url
|
||||
))
|
||||
.header("Authorization", format!("Bearer {}", token))
|
||||
.header("X-CalDAV-Password", password)
|
||||
.json(&update_payload)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let status = response.status();
|
||||
println!("Update series response status: {}", status);
|
||||
|
||||
// Note: This might fail if CalDAV server is not accessible or event doesn't exist, which is expected in CI
|
||||
if status.is_success() {
|
||||
let update_response: serde_json::Value = response.json().await.unwrap();
|
||||
assert!(update_response["success"].as_bool().unwrap_or(false));
|
||||
assert_eq!(
|
||||
update_response["series_uid"].as_str().unwrap(),
|
||||
"test-series-uid"
|
||||
);
|
||||
println!("✓ Update event series test passed");
|
||||
} else if status == 404 {
|
||||
println!(
|
||||
"⚠ Update event series test skipped (event not found - expected for test data)"
|
||||
);
|
||||
} else {
|
||||
println!("⚠ Update event series test skipped (CalDAV server not accessible)");
|
||||
}
|
||||
}
|
||||
|
||||
/// Test event series deletion endpoint
|
||||
#[tokio::test]
|
||||
async fn test_delete_event_series() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
// First login to get a token
|
||||
let token = server.login().await;
|
||||
|
||||
// Load password from env for CalDAV requests
|
||||
dotenvy::dotenv().ok();
|
||||
let password = "test".to_string();
|
||||
|
||||
let delete_payload = json!({
|
||||
"series_uid": "test-series-to-delete",
|
||||
"calendar_path": "/calendars/test/default/",
|
||||
"event_href": "test-series.ics",
|
||||
"delete_scope": "all_in_series"
|
||||
});
|
||||
|
||||
let response = server
|
||||
.client
|
||||
.post(&format!(
|
||||
"{}/api/calendar/events/series/delete",
|
||||
server.base_url
|
||||
))
|
||||
.header("Authorization", format!("Bearer {}", token))
|
||||
.header("X-CalDAV-Password", password)
|
||||
.json(&delete_payload)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let status = response.status();
|
||||
println!("Delete series response status: {}", status);
|
||||
|
||||
// Note: This might fail if CalDAV server is not accessible or event doesn't exist, which is expected in CI
|
||||
if status.is_success() {
|
||||
let delete_response: serde_json::Value = response.json().await.unwrap();
|
||||
assert!(delete_response["success"].as_bool().unwrap_or(false));
|
||||
println!("✓ Delete event series test passed");
|
||||
} else if status == 404 {
|
||||
println!(
|
||||
"⚠ Delete event series test skipped (event not found - expected for test data)"
|
||||
);
|
||||
} else {
|
||||
println!("⚠ Delete event series test skipped (CalDAV server not accessible)");
|
||||
}
|
||||
}
|
||||
|
||||
/// Test invalid update scope
|
||||
#[tokio::test]
|
||||
async fn test_invalid_update_scope() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
// First login to get a token
|
||||
let token = server.login().await;
|
||||
|
||||
let invalid_payload = json!({
|
||||
"series_uid": "test-series-uid",
|
||||
"title": "Test Title",
|
||||
"description": "Test",
|
||||
"start_date": "2024-12-25",
|
||||
"start_time": "10:00",
|
||||
"end_date": "2024-12-25",
|
||||
"end_time": "11:00",
|
||||
"location": "Test",
|
||||
"all_day": false,
|
||||
"status": "confirmed",
|
||||
"class": "public",
|
||||
"organizer": "test@example.com",
|
||||
"attendees": "",
|
||||
"categories": "",
|
||||
"reminder": "none",
|
||||
"recurrence": "none",
|
||||
"recurrence_days": [false, false, false, false, false, false, false],
|
||||
"update_scope": "invalid_scope" // This should cause a 400 error
|
||||
});
|
||||
|
||||
let response = server
|
||||
.client
|
||||
.post(&format!(
|
||||
"{}/api/calendar/events/series/update",
|
||||
server.base_url
|
||||
))
|
||||
.header("Authorization", format!("Bearer {}", token))
|
||||
.json(&invalid_payload)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
400,
|
||||
"Expected 400 for invalid update scope"
|
||||
);
|
||||
println!("✓ Invalid update scope test passed");
|
||||
}
|
||||
|
||||
/// Test non-recurring event rejection in series endpoint
|
||||
#[tokio::test]
|
||||
async fn test_non_recurring_series_rejection() {
|
||||
let server = TestServer::start().await;
|
||||
|
||||
// First login to get a token
|
||||
let token = server.login().await;
|
||||
|
||||
let non_recurring_payload = json!({
|
||||
"title": "Non-recurring Event",
|
||||
"description": "This should be rejected",
|
||||
"start_date": "2024-12-25",
|
||||
"start_time": "10:00",
|
||||
"end_date": "2024-12-25",
|
||||
"end_time": "11:00",
|
||||
"location": "Test",
|
||||
"all_day": false,
|
||||
"status": "confirmed",
|
||||
"class": "public",
|
||||
"organizer": "test@example.com",
|
||||
"attendees": "",
|
||||
"categories": "",
|
||||
"reminder": "none",
|
||||
"recurrence": "none", // This should cause rejection
|
||||
"recurrence_days": [false, false, false, false, false, false, false]
|
||||
});
|
||||
|
||||
let response = server
|
||||
.client
|
||||
.post(&format!(
|
||||
"{}/api/calendar/events/series/create",
|
||||
server.base_url
|
||||
))
|
||||
.header("Authorization", format!("Bearer {}", token))
|
||||
.json(&non_recurring_payload)
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
response.status(),
|
||||
400,
|
||||
"Expected 400 for non-recurring event in series endpoint"
|
||||
);
|
||||
println!("✓ Non-recurring series rejection test passed");
|
||||
}
|
||||
}
|
||||
13
calendar-models/Cargo.toml
Normal file
13
calendar-models/Cargo.toml
Normal file
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
name = "calendar-models"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
uuid = { version = "1.0", features = ["v4", "serde"] }
|
||||
|
||||
[features]
|
||||
default = []
|
||||
wasm = ["chrono/wasm-bindgen", "uuid/wasm-bindgen"]
|
||||
220
calendar-models/src/common.rs
Normal file
220
calendar-models/src/common.rs
Normal file
@@ -0,0 +1,220 @@
|
||||
//! Common types and enums used across calendar components
|
||||
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// ==================== ENUMS AND COMMON TYPES ====================
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum EventStatus {
|
||||
Tentative,
|
||||
Confirmed,
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum EventClass {
|
||||
Public,
|
||||
Private,
|
||||
Confidential,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum TimeTransparency {
|
||||
Opaque, // OPAQUE - time is not available
|
||||
Transparent, // TRANSPARENT - time is available
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum TodoStatus {
|
||||
NeedsAction,
|
||||
Completed,
|
||||
InProcess,
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum AttendeeRole {
|
||||
Chair,
|
||||
ReqParticipant,
|
||||
OptParticipant,
|
||||
NonParticipant,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum ParticipationStatus {
|
||||
NeedsAction,
|
||||
Accepted,
|
||||
Declined,
|
||||
Tentative,
|
||||
Delegated,
|
||||
Completed,
|
||||
InProcess,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum AlarmAction {
|
||||
Audio,
|
||||
Display,
|
||||
Email,
|
||||
Procedure,
|
||||
}
|
||||
|
||||
// ==================== STRUCTURED TYPES ====================
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct CalendarUser {
|
||||
pub cal_address: String, // Calendar user address (usually email)
|
||||
pub common_name: Option<String>, // CN parameter - display name
|
||||
pub dir_entry_ref: Option<String>, // DIR parameter - directory entry
|
||||
pub sent_by: Option<String>, // SENT-BY parameter
|
||||
pub language: Option<String>, // LANGUAGE parameter
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Attendee {
|
||||
pub cal_address: String, // Calendar user address
|
||||
pub common_name: Option<String>, // CN parameter
|
||||
pub role: Option<AttendeeRole>, // ROLE parameter
|
||||
pub part_stat: Option<ParticipationStatus>, // PARTSTAT parameter
|
||||
pub rsvp: Option<bool>, // RSVP parameter
|
||||
pub cu_type: Option<String>, // CUTYPE parameter (INDIVIDUAL, GROUP, RESOURCE, ROOM, UNKNOWN)
|
||||
pub member: Vec<String>, // MEMBER parameter
|
||||
pub delegated_to: Vec<String>, // DELEGATED-TO parameter
|
||||
pub delegated_from: Vec<String>, // DELEGATED-FROM parameter
|
||||
pub sent_by: Option<String>, // SENT-BY parameter
|
||||
pub dir_entry_ref: Option<String>, // DIR parameter
|
||||
pub language: Option<String>, // LANGUAGE parameter
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct VAlarm {
|
||||
pub action: AlarmAction, // Action (ACTION) - REQUIRED
|
||||
pub trigger: AlarmTrigger, // Trigger (TRIGGER) - REQUIRED
|
||||
pub duration: Option<Duration>, // Duration (DURATION)
|
||||
pub repeat: Option<u32>, // Repeat count (REPEAT)
|
||||
pub description: Option<String>, // Description for DISPLAY/EMAIL
|
||||
pub summary: Option<String>, // Summary for EMAIL
|
||||
pub attendees: Vec<Attendee>, // Attendees for EMAIL
|
||||
pub attach: Vec<Attachment>, // Attachments for AUDIO/EMAIL
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub enum AlarmTrigger {
|
||||
DateTime(DateTime<Utc>), // Absolute trigger time
|
||||
Duration(Duration), // Duration relative to start/end
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Attachment {
|
||||
pub format_type: Option<String>, // FMTTYPE parameter (MIME type)
|
||||
pub encoding: Option<String>, // ENCODING parameter
|
||||
pub value: Option<String>, // VALUE parameter (BINARY or URI)
|
||||
pub uri: Option<String>, // URI reference
|
||||
pub binary_data: Option<Vec<u8>>, // Binary data (when ENCODING=BASE64)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct GeographicPosition {
|
||||
pub latitude: f64, // Latitude in decimal degrees
|
||||
pub longitude: f64, // Longitude in decimal degrees
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct VTimeZone {
|
||||
pub tzid: String, // Time zone ID (TZID) - REQUIRED
|
||||
pub last_modified: Option<DateTime<Utc>>, // Last modified (LAST-MODIFIED)
|
||||
pub tzurl: Option<String>, // Time zone URL (TZURL)
|
||||
pub standard_components: Vec<TimeZoneComponent>, // STANDARD components
|
||||
pub daylight_components: Vec<TimeZoneComponent>, // DAYLIGHT components
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct TimeZoneComponent {
|
||||
pub dtstart: DateTime<Utc>, // Start of this time zone definition
|
||||
pub tzoffset_to: String, // UTC offset for this component
|
||||
pub tzoffset_from: String, // UTC offset before this component
|
||||
pub rrule: Option<String>, // Recurrence rule
|
||||
pub rdate: Vec<DateTime<Utc>>, // Recurrence dates
|
||||
pub tzname: Vec<String>, // Time zone names
|
||||
pub comment: Vec<String>, // Comments
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct VJournal {
|
||||
// Required properties
|
||||
pub dtstamp: DateTime<Utc>, // Date-time stamp (DTSTAMP) - REQUIRED
|
||||
pub uid: String, // Unique identifier (UID) - REQUIRED
|
||||
|
||||
// Optional properties
|
||||
pub dtstart: Option<DateTime<Utc>>, // Start date-time (DTSTART)
|
||||
pub summary: Option<String>, // Summary/title (SUMMARY)
|
||||
pub description: Option<String>, // Description (DESCRIPTION)
|
||||
|
||||
// Classification and status
|
||||
pub class: Option<EventClass>, // Classification (CLASS)
|
||||
pub status: Option<String>, // Status (STATUS)
|
||||
|
||||
// People and organization
|
||||
pub organizer: Option<CalendarUser>, // Organizer (ORGANIZER)
|
||||
pub attendees: Vec<Attendee>, // Attendees (ATTENDEE)
|
||||
|
||||
// Categorization
|
||||
pub categories: Vec<String>, // Categories (CATEGORIES)
|
||||
|
||||
// Versioning and modification
|
||||
pub sequence: Option<u32>, // Sequence number (SEQUENCE)
|
||||
pub created: Option<DateTime<Utc>>, // Creation time (CREATED)
|
||||
pub last_modified: Option<DateTime<Utc>>, // Last modified (LAST-MODIFIED)
|
||||
|
||||
// Recurrence
|
||||
pub rrule: Option<String>, // Recurrence rule (RRULE)
|
||||
pub rdate: Vec<DateTime<Utc>>, // Recurrence dates (RDATE)
|
||||
pub exdate: Vec<DateTime<Utc>>, // Exception dates (EXDATE)
|
||||
pub recurrence_id: Option<DateTime<Utc>>, // Recurrence ID (RECURRENCE-ID)
|
||||
|
||||
// Attachments
|
||||
pub attachments: Vec<Attachment>, // Attachments (ATTACH)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct VFreeBusy {
|
||||
// Required properties
|
||||
pub dtstamp: DateTime<Utc>, // Date-time stamp (DTSTAMP) - REQUIRED
|
||||
pub uid: String, // Unique identifier (UID) - REQUIRED
|
||||
|
||||
// Optional date-time properties
|
||||
pub dtstart: Option<DateTime<Utc>>, // Start date-time (DTSTART)
|
||||
pub dtend: Option<DateTime<Utc>>, // End date-time (DTEND)
|
||||
|
||||
// People
|
||||
pub organizer: Option<CalendarUser>, // Organizer (ORGANIZER)
|
||||
pub attendees: Vec<Attendee>, // Attendees (ATTENDEE)
|
||||
|
||||
// Free/busy time
|
||||
pub freebusy: Vec<FreeBusyTime>, // Free/busy time periods
|
||||
pub url: Option<String>, // URL (URL)
|
||||
pub comment: Vec<String>, // Comments (COMMENT)
|
||||
pub contact: Option<String>, // Contact information (CONTACT)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct FreeBusyTime {
|
||||
pub fb_type: FreeBusyType, // Free/busy type
|
||||
pub periods: Vec<Period>, // Time periods
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum FreeBusyType {
|
||||
Free,
|
||||
Busy,
|
||||
BusyUnavailable,
|
||||
BusyTentative,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct Period {
|
||||
pub start: DateTime<Utc>, // Period start
|
||||
pub end: Option<DateTime<Utc>>, // Period end
|
||||
pub duration: Option<Duration>, // Period duration (alternative to end)
|
||||
}
|
||||
10
calendar-models/src/lib.rs
Normal file
10
calendar-models/src/lib.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
//! RFC 5545 Compliant Calendar Models
|
||||
//!
|
||||
//! This crate provides shared data structures for calendar applications
|
||||
//! that comply with RFC 5545 (iCalendar) specification.
|
||||
|
||||
pub mod common;
|
||||
pub mod vevent;
|
||||
|
||||
pub use common::*;
|
||||
pub use vevent::*;
|
||||
185
calendar-models/src/vevent.rs
Normal file
185
calendar-models/src/vevent.rs
Normal file
@@ -0,0 +1,185 @@
|
||||
//! VEvent - RFC 5545 compliant calendar event structure
|
||||
|
||||
use crate::common::*;
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// ==================== VEVENT COMPONENT ====================
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct VEvent {
|
||||
// Required properties
|
||||
pub dtstamp: DateTime<Utc>, // Date-time stamp (DTSTAMP) - REQUIRED
|
||||
pub uid: String, // Unique identifier (UID) - REQUIRED
|
||||
pub dtstart: DateTime<Utc>, // Start date-time (DTSTART) - REQUIRED
|
||||
|
||||
// Optional properties (commonly used)
|
||||
pub dtend: Option<DateTime<Utc>>, // End date-time (DTEND)
|
||||
pub duration: Option<Duration>, // Duration (DURATION) - alternative to DTEND
|
||||
pub summary: Option<String>, // Summary/title (SUMMARY)
|
||||
pub description: Option<String>, // Description (DESCRIPTION)
|
||||
pub location: Option<String>, // Location (LOCATION)
|
||||
|
||||
// Classification and status
|
||||
pub class: Option<EventClass>, // Classification (CLASS)
|
||||
pub status: Option<EventStatus>, // Status (STATUS)
|
||||
pub transp: Option<TimeTransparency>, // Time transparency (TRANSP)
|
||||
pub priority: Option<u8>, // Priority 0-9 (PRIORITY)
|
||||
|
||||
// People and organization
|
||||
pub organizer: Option<CalendarUser>, // Organizer (ORGANIZER)
|
||||
pub attendees: Vec<Attendee>, // Attendees (ATTENDEE)
|
||||
pub contact: Option<String>, // Contact information (CONTACT)
|
||||
|
||||
// Categorization and relationships
|
||||
pub categories: Vec<String>, // Categories (CATEGORIES)
|
||||
pub comment: Option<String>, // Comment (COMMENT)
|
||||
pub resources: Vec<String>, // Resources (RESOURCES)
|
||||
pub related_to: Option<String>, // Related component (RELATED-TO)
|
||||
pub url: Option<String>, // URL (URL)
|
||||
|
||||
// Geographical
|
||||
pub geo: Option<GeographicPosition>, // Geographic position (GEO)
|
||||
|
||||
// Versioning and modification
|
||||
pub sequence: Option<u32>, // Sequence number (SEQUENCE)
|
||||
pub created: Option<DateTime<Utc>>, // Creation time (CREATED)
|
||||
pub last_modified: Option<DateTime<Utc>>, // Last modified (LAST-MODIFIED)
|
||||
|
||||
// Recurrence
|
||||
pub rrule: Option<String>, // Recurrence rule (RRULE)
|
||||
pub rdate: Vec<DateTime<Utc>>, // Recurrence dates (RDATE)
|
||||
pub exdate: Vec<DateTime<Utc>>, // Exception dates (EXDATE)
|
||||
pub recurrence_id: Option<DateTime<Utc>>, // Recurrence ID (RECURRENCE-ID)
|
||||
|
||||
// Alarms and attachments
|
||||
pub alarms: Vec<VAlarm>, // VALARM components
|
||||
pub attachments: Vec<Attachment>, // Attachments (ATTACH)
|
||||
|
||||
// CalDAV specific (for implementation)
|
||||
pub etag: Option<String>, // ETag for CalDAV
|
||||
pub href: Option<String>, // Href for CalDAV
|
||||
pub calendar_path: Option<String>, // Calendar path
|
||||
pub all_day: bool, // All-day event flag
|
||||
}
|
||||
|
||||
impl VEvent {
|
||||
/// Create a new VEvent with required fields
|
||||
pub fn new(uid: String, dtstart: DateTime<Utc>) -> Self {
|
||||
Self {
|
||||
dtstamp: Utc::now(),
|
||||
uid,
|
||||
dtstart,
|
||||
dtend: None,
|
||||
duration: None,
|
||||
summary: None,
|
||||
description: None,
|
||||
location: None,
|
||||
class: None,
|
||||
status: None,
|
||||
transp: None,
|
||||
priority: None,
|
||||
organizer: None,
|
||||
attendees: Vec::new(),
|
||||
contact: None,
|
||||
categories: Vec::new(),
|
||||
comment: None,
|
||||
resources: Vec::new(),
|
||||
related_to: None,
|
||||
url: None,
|
||||
geo: None,
|
||||
sequence: None,
|
||||
created: Some(Utc::now()),
|
||||
last_modified: Some(Utc::now()),
|
||||
rrule: None,
|
||||
rdate: Vec::new(),
|
||||
exdate: Vec::new(),
|
||||
recurrence_id: None,
|
||||
alarms: Vec::new(),
|
||||
attachments: Vec::new(),
|
||||
etag: None,
|
||||
href: None,
|
||||
calendar_path: None,
|
||||
all_day: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper method to get effective end time (dtend or dtstart + duration)
|
||||
pub fn get_end_time(&self) -> DateTime<Utc> {
|
||||
if let Some(dtend) = self.dtend {
|
||||
dtend
|
||||
} else if let Some(duration) = self.duration {
|
||||
self.dtstart + duration
|
||||
} else {
|
||||
// Default to 1 hour if no end or duration specified
|
||||
self.dtstart + Duration::hours(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper method to get event duration
|
||||
pub fn get_duration(&self) -> Duration {
|
||||
if let Some(duration) = self.duration {
|
||||
duration
|
||||
} else if let Some(dtend) = self.dtend {
|
||||
dtend - self.dtstart
|
||||
} else {
|
||||
Duration::hours(1) // Default duration
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper method to get display title (summary or "Untitled Event")
|
||||
pub fn get_title(&self) -> String {
|
||||
self.summary
|
||||
.clone()
|
||||
.unwrap_or_else(|| "Untitled Event".to_string())
|
||||
}
|
||||
|
||||
/// Helper method to get start date for UI compatibility
|
||||
pub fn get_date(&self) -> chrono::NaiveDate {
|
||||
self.dtstart.date_naive()
|
||||
}
|
||||
|
||||
/// Check if event is recurring
|
||||
pub fn is_recurring(&self) -> bool {
|
||||
self.rrule.is_some()
|
||||
}
|
||||
|
||||
/// Check if this is an exception to a recurring series
|
||||
pub fn is_exception(&self) -> bool {
|
||||
self.recurrence_id.is_some()
|
||||
}
|
||||
|
||||
/// Get display string for status
|
||||
pub fn get_status_display(&self) -> &'static str {
|
||||
match &self.status {
|
||||
Some(EventStatus::Tentative) => "Tentative",
|
||||
Some(EventStatus::Confirmed) => "Confirmed",
|
||||
Some(EventStatus::Cancelled) => "Cancelled",
|
||||
None => "Confirmed", // Default
|
||||
}
|
||||
}
|
||||
|
||||
/// Get display string for class
|
||||
pub fn get_class_display(&self) -> &'static str {
|
||||
match &self.class {
|
||||
Some(EventClass::Public) => "Public",
|
||||
Some(EventClass::Private) => "Private",
|
||||
Some(EventClass::Confidential) => "Confidential",
|
||||
None => "Public", // Default
|
||||
}
|
||||
}
|
||||
|
||||
/// Get display string for priority
|
||||
pub fn get_priority_display(&self) -> String {
|
||||
match self.priority {
|
||||
None => "Not set".to_string(),
|
||||
Some(0) => "Undefined".to_string(),
|
||||
Some(1) => "High".to_string(),
|
||||
Some(p) if p <= 4 => "High".to_string(),
|
||||
Some(5) => "Medium".to_string(),
|
||||
Some(p) if p <= 8 => "Low".to_string(),
|
||||
Some(9) => "Low".to_string(),
|
||||
Some(p) => format!("Priority {}", p),
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
calendar.db
BIN
calendar.db
Binary file not shown.
22
compose.yml
Normal file
22
compose.yml
Normal file
@@ -0,0 +1,22 @@
|
||||
services:
|
||||
calendar-backend:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: ./backend/Dockerfile
|
||||
ports:
|
||||
- "3000:3000"
|
||||
volumes:
|
||||
- ./data/db:/db
|
||||
|
||||
calendar-frontend:
|
||||
image: caddy
|
||||
environment:
|
||||
- BACKEND_API_URL=http://localhost:3000/api
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
volumes:
|
||||
- ./frontend/dist:/srv/www:ro
|
||||
- ./Caddyfile:/etc/caddy/Caddyfile:ro
|
||||
- ./data/caddy/data:/data
|
||||
- ./data/caddy/config:/config
|
||||
6
deploy_frontend.sh
Executable file
6
deploy_frontend.sh
Executable file
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
|
||||
export BACKEND_API_URL="https://runway.rcjohnstone.com/api"
|
||||
trunk build --release --config /home/connor/docs/projects/calendar/frontend/Trunk.toml
|
||||
sudo rsync -azX --delete --info=progress2 -e 'ssh -T -q' --rsync-path='sudo rsync' /home/connor/docs/projects/calendar/frontend/dist connor@server.rcjohnstone.com:/home/connor/data/runway/
|
||||
unset BACKEND_API_URL
|
||||
BIN
favicon_big.png
Normal file
BIN
favicon_big.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 952 KiB |
76
frontend/Cargo.toml
Normal file
76
frontend/Cargo.toml
Normal file
@@ -0,0 +1,76 @@
|
||||
[package]
|
||||
name = "runway"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# Frontend binary only
|
||||
|
||||
[dependencies]
|
||||
calendar-models = { workspace = true, features = ["wasm"] }
|
||||
yew = { version = "0.21", features = ["csr"] }
|
||||
web-sys = { version = "0.3", features = [
|
||||
"console",
|
||||
"HtmlSelectElement",
|
||||
"HtmlInputElement",
|
||||
"HtmlTextAreaElement",
|
||||
"HtmlLinkElement",
|
||||
"HtmlHeadElement",
|
||||
"Event",
|
||||
"MouseEvent",
|
||||
"InputEvent",
|
||||
"Element",
|
||||
"Document",
|
||||
"Window",
|
||||
"Location",
|
||||
"Navigator",
|
||||
"DomTokenList",
|
||||
"Headers",
|
||||
"Request",
|
||||
"RequestInit",
|
||||
"RequestMode",
|
||||
"Response",
|
||||
"CssStyleDeclaration",
|
||||
] }
|
||||
wasm-bindgen = "0.2"
|
||||
js-sys = "0.3"
|
||||
|
||||
# HTTP client for CalDAV requests
|
||||
reqwest = { version = "0.11", features = ["json"] }
|
||||
# Calendar and iCal parsing
|
||||
ical = "0.7"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
serde-wasm-bindgen = "0.6"
|
||||
|
||||
# Date and time handling
|
||||
chrono = { version = "0.4", features = ["serde", "wasm-bindgen"] }
|
||||
chrono-tz = "0.8"
|
||||
|
||||
# Error handling
|
||||
anyhow = "1.0"
|
||||
thiserror = "1.0"
|
||||
|
||||
# Logging
|
||||
log = "0.4"
|
||||
console_log = "1.0"
|
||||
|
||||
# UUID generation for calendar events
|
||||
uuid = { version = "1.0", features = ["v4", "wasm-bindgen", "serde"] }
|
||||
getrandom = { version = "0.2", features = ["js"] }
|
||||
|
||||
# Environment variable handling
|
||||
dotenvy = "0.15"
|
||||
base64 = "0.21"
|
||||
|
||||
# XML/Regex parsing
|
||||
regex = "1.0"
|
||||
|
||||
# Yew routing and local storage (WASM only)
|
||||
yew-router = "0.18"
|
||||
gloo-storage = "0.3"
|
||||
gloo-timers = "0.3"
|
||||
wasm-bindgen-futures = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
wasm-bindgen-test = "0.3"
|
||||
|
||||
16
frontend/Trunk.toml
Normal file
16
frontend/Trunk.toml
Normal file
@@ -0,0 +1,16 @@
|
||||
[build]
|
||||
target = "index.html"
|
||||
dist = "dist"
|
||||
|
||||
[env]
|
||||
BACKEND_API_URL = "http://localhost:3000/api"
|
||||
|
||||
[watch]
|
||||
watch = ["src", "Cargo.toml", "../calendar-models/src", "styles.css", "index.html"]
|
||||
ignore = ["../backend/", "../target/"]
|
||||
|
||||
[serve]
|
||||
addresses = ["127.0.0.1"]
|
||||
port = 8080
|
||||
open = false
|
||||
|
||||
59
frontend/e2e/README.md
Normal file
59
frontend/e2e/README.md
Normal file
@@ -0,0 +1,59 @@
|
||||
# Runway E2E Tests
|
||||
|
||||
End-to-end tests for the Runway Calendar application using Playwright.
|
||||
|
||||
## Setup
|
||||
|
||||
1. Install dependencies:
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
|
||||
2. Install browser binaries:
|
||||
```bash
|
||||
npm run install-browsers
|
||||
```
|
||||
|
||||
3. Install system dependencies (Arch Linux):
|
||||
```bash
|
||||
npm run install-deps
|
||||
```
|
||||
|
||||
## Running Tests
|
||||
|
||||
### Local Development
|
||||
- Run all tests: `npm test`
|
||||
- Run tests with browser UI: `npm run test:headed`
|
||||
- Debug tests: `npm run test:debug`
|
||||
- Interactive UI mode: `npm run test:ui`
|
||||
|
||||
### Browser-specific Tests
|
||||
- Chrome only: `npm run test:chromium`
|
||||
- Firefox only: `npm run test:firefox`
|
||||
|
||||
### CI/Headless Testing
|
||||
Tests automatically run in headless mode when `CI=true` environment variable is set.
|
||||
|
||||
## Test Structure
|
||||
|
||||
- `tests/auth.spec.ts` - Authentication flow tests
|
||||
- `tests/calendar-ui.spec.ts` - General UI interaction tests
|
||||
- `tests/drag-and-drop.spec.ts` - Drag and drop functionality tests
|
||||
- `helpers/auth-helpers.ts` - Authentication test utilities
|
||||
- `helpers/calendar-helpers.ts` - Calendar interaction utilities
|
||||
|
||||
## Environment Variables
|
||||
|
||||
For CI and automated testing:
|
||||
- `TEST_CALDAV_SERVER` - CalDAV server URL (default: http://localhost:3000/baikal)
|
||||
- `TEST_CALDAV_USERNAME` - Test user username (default: testuser)
|
||||
- `TEST_CALDAV_PASSWORD` - Test user password (default: testpass)
|
||||
- `CI` - Set to true for headless testing
|
||||
|
||||
## Configuration
|
||||
|
||||
Test configuration is in `playwright.config.ts`:
|
||||
- Chromium and Firefox browsers for CI compatibility
|
||||
- Automatic headless mode in CI environments
|
||||
- Screenshot and video capture on failure
|
||||
- Timeout and retry settings optimized for WebAssembly apps
|
||||
BIN
frontend/e2e/debug-after-end-time-fill.png
Normal file
BIN
frontend/e2e/debug-after-end-time-fill.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 102 KiB |
BIN
frontend/e2e/debug-after-event-creation.png
Normal file
BIN
frontend/e2e/debug-after-event-creation.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 94 KiB |
BIN
frontend/e2e/debug-after-start-time-fill.png
Normal file
BIN
frontend/e2e/debug-after-start-time-fill.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 102 KiB |
BIN
frontend/e2e/debug-after-title-fill.png
Normal file
BIN
frontend/e2e/debug-after-title-fill.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 96 KiB |
BIN
frontend/e2e/debug-before-submit-click.png
Normal file
BIN
frontend/e2e/debug-before-submit-click.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 102 KiB |
63
frontend/e2e/helpers/auth-helpers.ts
Normal file
63
frontend/e2e/helpers/auth-helpers.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { Page, expect } from '@playwright/test';
|
||||
|
||||
export class AuthHelpers {
|
||||
constructor(private page: Page) {}
|
||||
|
||||
async loginWithTestCredentials() {
|
||||
await this.page.goto('/login');
|
||||
|
||||
// Use environment variables for test credentials
|
||||
const serverUrl = process.env.TEST_CALDAV_SERVER || 'https://baikal.rcjohnstone.com/dav.php/';
|
||||
const username = process.env.TEST_CALDAV_USERNAME || 'test';
|
||||
const password = process.env.TEST_CALDAV_PASSWORD || 'I0W?7`|Cs6tA`s';
|
||||
|
||||
await this.page.getByLabel('CalDAV Server URL').fill(serverUrl);
|
||||
await this.page.getByRole('textbox', { name: 'Username' }).fill(username);
|
||||
await this.page.getByLabel('Password').fill(password);
|
||||
|
||||
await this.page.getByRole('button', { name: 'Sign In' }).click();
|
||||
|
||||
// Wait for login to complete - either success (redirect) or error message
|
||||
await Promise.race([
|
||||
this.page.waitForURL(/.*\/calendar/, { timeout: 10000 }),
|
||||
this.page.locator('.error-message').waitFor({ state: 'visible', timeout: 10000 })
|
||||
]);
|
||||
|
||||
// If we're on the calendar page, verify the interface loaded
|
||||
if (this.page.url().includes('/calendar') || (!this.page.url().includes('/login'))) {
|
||||
await expect(this.page.locator('.calendar-grid').or(this.page.locator('.sidebar'))).toBeVisible({ timeout: 5000 });
|
||||
}
|
||||
}
|
||||
|
||||
async logout() {
|
||||
// Look for logout button in sidebar - it might be text or button
|
||||
const logoutButton = this.page.locator('text=Logout').or(this.page.getByRole('button', { name: 'Logout' }));
|
||||
await logoutButton.click();
|
||||
|
||||
// Should redirect to login page
|
||||
await expect(this.page).toHaveURL(/.*\/login/);
|
||||
}
|
||||
|
||||
async isLoggedIn(): Promise<boolean> {
|
||||
try {
|
||||
// Check if we're on the calendar page
|
||||
const currentUrl = this.page.url();
|
||||
if (!currentUrl.includes('/calendar') && !currentUrl.includes('/') || currentUrl.includes('/login')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Look for calendar interface elements instead of user-info
|
||||
await expect(this.page.locator('.calendar-grid').or(this.page.locator('.sidebar'))).toBeVisible({ timeout: 5000 });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async ensureLoggedIn() {
|
||||
const loggedIn = await this.isLoggedIn();
|
||||
if (!loggedIn) {
|
||||
await this.loginWithTestCredentials();
|
||||
}
|
||||
}
|
||||
}
|
||||
278
frontend/e2e/helpers/calendar-helpers.ts
Normal file
278
frontend/e2e/helpers/calendar-helpers.ts
Normal file
@@ -0,0 +1,278 @@
|
||||
import { Page, expect, Locator, TestInfo } from '@playwright/test';
|
||||
|
||||
export class CalendarHelpers {
|
||||
constructor(private page: Page) {}
|
||||
|
||||
async waitForCalendarLoad() {
|
||||
// Wait for calendar to be visible (either month view grid or week view container)
|
||||
await expect(
|
||||
this.page.locator('.calendar-grid').or(this.page.locator('.week-view-container'))
|
||||
).toBeVisible({ timeout: 5000 });
|
||||
|
||||
// Wait for any loading spinners to disappear (optional, may not exist)
|
||||
try {
|
||||
await this.page.waitForSelector('.calendar-loading', { state: 'hidden', timeout: 2000 });
|
||||
} catch {
|
||||
// Loading spinner might not exist, that's ok
|
||||
}
|
||||
}
|
||||
|
||||
async switchToWeekView() {
|
||||
await this.page.selectOption('.view-selector-dropdown', 'week');
|
||||
await this.waitForCalendarLoad();
|
||||
}
|
||||
|
||||
async switchToMonthView() {
|
||||
await this.page.selectOption('.view-selector-dropdown', 'month');
|
||||
await this.waitForCalendarLoad();
|
||||
}
|
||||
|
||||
async getCurrentView(): Promise<'week' | 'month'> {
|
||||
const selectedValue = await this.page.locator('.view-selector-dropdown').inputValue();
|
||||
return selectedValue as 'week' | 'month';
|
||||
}
|
||||
|
||||
async navigateToNextPeriod() {
|
||||
await this.page.getByRole('button', { name: '›' }).click();
|
||||
await this.waitForCalendarLoad();
|
||||
}
|
||||
|
||||
async navigateToPreviousPeriod() {
|
||||
await this.page.getByRole('button', { name: '‹' }).click();
|
||||
await this.waitForCalendarLoad();
|
||||
}
|
||||
|
||||
async navigateToToday() {
|
||||
await this.page.getByRole('button', { name: 'Today' }).click();
|
||||
await this.waitForCalendarLoad();
|
||||
}
|
||||
|
||||
async openCreateEventModal(timeSlot?: string) {
|
||||
// Check if we're in week view or month view to determine creation method
|
||||
const isWeekView = await this.page.locator('.week-view-container').count() > 0;
|
||||
|
||||
if (isWeekView) {
|
||||
// In week view, try element-based drag first (simpler and more reliable)
|
||||
const timeSlots = this.page.locator('.time-slot');
|
||||
if (await timeSlots.count() > 1) {
|
||||
const startSlot = timeSlots.first();
|
||||
const endSlot = timeSlots.nth(2); // Skip one to create a longer event
|
||||
|
||||
// Force the drag
|
||||
await startSlot.dragTo(endSlot, { force: true });
|
||||
|
||||
// Wait for the create event modal to appear
|
||||
await expect(this.page.locator('.create-event-modal, .modal')).toBeVisible({ timeout: 5000 });
|
||||
} else {
|
||||
throw new Error('Not enough time slots available for drag-to-create event');
|
||||
}
|
||||
} else {
|
||||
// In month view, try right-clicking on calendar day
|
||||
const calendarDay = this.page.locator('.calendar-day').first();
|
||||
if (await calendarDay.count() > 0) {
|
||||
await calendarDay.click({ button: 'right' });
|
||||
|
||||
// Wait for context menu to appear
|
||||
await expect(this.page.locator('.context-menu, .calendar-context-menu')).toBeVisible({ timeout: 3000 });
|
||||
|
||||
// Click "Create Event" in the context menu
|
||||
const createEventOption = this.page.getByText(/create event/i);
|
||||
await expect(createEventOption).toBeVisible();
|
||||
await createEventOption.click();
|
||||
|
||||
// Wait for the create event modal to appear
|
||||
await expect(this.page.locator('.create-event-modal, .modal')).toBeVisible({ timeout: 5000 });
|
||||
} else {
|
||||
throw new Error('Could not find calendar day for event creation in month view');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async createEvent(eventData: {
|
||||
title: string;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
description?: string;
|
||||
calendar?: string;
|
||||
}, testInfo?: TestInfo) {
|
||||
// Open modal by clicking on calendar (using default 14:00 time slot if available)
|
||||
await this.openCreateEventModal(eventData.startTime || '14:00');
|
||||
|
||||
// Fill in event details - use exact label match
|
||||
const titleInput = this.page.getByLabel('Event Title *').or(this.page.locator('#event-title'));
|
||||
await titleInput.fill(eventData.title);
|
||||
const titleScreenshot = await this.page.screenshot({ fullPage: true });
|
||||
if (testInfo) await testInfo.attach('debug-after-title-fill.png', { body: titleScreenshot, contentType: 'image/png' });
|
||||
|
||||
if (eventData.startTime) {
|
||||
const startTimeInput = this.page.locator('#start-time');
|
||||
await startTimeInput.fill(eventData.startTime);
|
||||
const startTimeScreenshot = await this.page.screenshot({ fullPage: true });
|
||||
if (testInfo) await testInfo.attach('debug-after-start-time-fill.png', { body: startTimeScreenshot, contentType: 'image/png' });
|
||||
}
|
||||
|
||||
if (eventData.endTime) {
|
||||
const endTimeInput = this.page.locator('#end-time');
|
||||
await endTimeInput.fill(eventData.endTime);
|
||||
const endTimeScreenshot = await this.page.screenshot({ fullPage: true });
|
||||
if (testInfo) await testInfo.attach('debug-after-end-time-fill.png', { body: endTimeScreenshot, contentType: 'image/png' });
|
||||
}
|
||||
|
||||
if (eventData.description) {
|
||||
const descInput = this.page.getByLabel('Description').or(this.page.getByLabel('Notes'));
|
||||
await descInput.fill(eventData.description);
|
||||
}
|
||||
|
||||
if (eventData.calendar) {
|
||||
await this.page.selectOption('[name="calendar"], .calendar-select', eventData.calendar);
|
||||
}
|
||||
|
||||
// Submit the form
|
||||
const submitButton = this.page.getByRole('button', { name: 'Create Event' })
|
||||
.or(this.page.getByRole('button', { name: 'Save' }))
|
||||
.or(this.page.getByRole('button', { name: 'Create' }));
|
||||
|
||||
// Take screenshot before clicking submit button
|
||||
const beforeSubmitScreenshot = await this.page.screenshot({ fullPage: true });
|
||||
if (testInfo) await testInfo.attach('debug-before-submit-click.png', { body: beforeSubmitScreenshot, contentType: 'image/png' });
|
||||
|
||||
// Wait for button to be visible and click with force (since normal click times out)
|
||||
await expect(submitButton).toBeVisible({ timeout: 5000 });
|
||||
await this.page.waitForTimeout(500); // Give form time to stabilize
|
||||
await submitButton.click({ force: true });
|
||||
|
||||
// Wait for modal to close
|
||||
await expect(this.page.locator('.create-event-modal, .modal')).toBeHidden({ timeout: 10000 });
|
||||
|
||||
// Take screenshot after modal closes
|
||||
const afterCloseScreenshot = await this.page.screenshot({ fullPage: true });
|
||||
if (testInfo) await testInfo.attach('debug-after-modal-close.png', { body: afterCloseScreenshot, contentType: 'image/png' });
|
||||
|
||||
// Wait for calendar to update
|
||||
await this.page.waitForTimeout(2000);
|
||||
await this.waitForCalendarLoad();
|
||||
|
||||
// Refresh the calendar data if needed
|
||||
try {
|
||||
const refreshButton = this.page.locator('button').filter({ hasText: /refresh|reload/i });
|
||||
if (await refreshButton.count() > 0) {
|
||||
await refreshButton.click();
|
||||
await this.waitForCalendarLoad();
|
||||
}
|
||||
} catch {
|
||||
// Refresh button doesn't exist, that's ok
|
||||
}
|
||||
}
|
||||
|
||||
async getEventByTitle(title: string): Promise<Locator> {
|
||||
// Check current view to use appropriate selector
|
||||
const isWeekView = await this.page.locator('.week-view-container').count() > 0;
|
||||
|
||||
if (isWeekView) {
|
||||
// In week view, events use .week-event class, and text is in .event-title
|
||||
return this.page.locator('.week-event').filter({ hasText: title });
|
||||
} else {
|
||||
// In month view, check for different possible selectors
|
||||
return this.page.locator('.month-event, .calendar-event').filter({ hasText: title });
|
||||
}
|
||||
}
|
||||
|
||||
async dragEventToNewTime(eventTitle: string, targetTimeSlot: string) {
|
||||
const event = await this.getEventByTitle(eventTitle);
|
||||
const target = this.page.locator(`[data-time="${targetTimeSlot}"]`);
|
||||
|
||||
await event.dragTo(target);
|
||||
await this.waitForCalendarLoad();
|
||||
}
|
||||
|
||||
async openCalendarManagementModal() {
|
||||
await this.page.getByRole('button', { name: '+ Add Calendar' }).click();
|
||||
await expect(this.page.locator('.calendar-management-modal')).toBeVisible();
|
||||
}
|
||||
|
||||
async createCalendar(calendarData: {
|
||||
name: string;
|
||||
color?: string;
|
||||
type: 'caldav' | 'external';
|
||||
url?: string;
|
||||
}) {
|
||||
await this.openCalendarManagementModal();
|
||||
|
||||
// Switch to appropriate tab
|
||||
if (calendarData.type === 'caldav') {
|
||||
await this.page.locator('.tab-button', { hasText: 'Create Calendar' }).click();
|
||||
} else {
|
||||
await this.page.locator('.tab-button', { hasText: 'Add External' }).click();
|
||||
}
|
||||
|
||||
// Fill in calendar details
|
||||
await this.page.getByLabel('Calendar Name').fill(calendarData.name);
|
||||
|
||||
if (calendarData.url) {
|
||||
await this.page.getByLabel('Calendar URL').fill(calendarData.url);
|
||||
}
|
||||
|
||||
if (calendarData.color) {
|
||||
// Click color picker and select color
|
||||
await this.page.locator('.color-picker').getByTestId(calendarData.color).click();
|
||||
}
|
||||
|
||||
// Submit the form
|
||||
const buttonText = calendarData.type === 'caldav' ? 'Create Calendar' : 'Add External Calendar';
|
||||
await this.page.getByRole('button', { name: buttonText }).click();
|
||||
|
||||
// Wait for modal to close
|
||||
await expect(this.page.locator('.calendar-management-modal')).toBeHidden();
|
||||
}
|
||||
|
||||
async toggleCalendarVisibility(calendarName: string) {
|
||||
// Look for the calendar in regular calendar list first, then external
|
||||
const regularCalendarItem = this.page.locator('.calendar-list li').filter({ hasText: calendarName });
|
||||
const externalCalendarItem = this.page.locator('.external-calendar-item').filter({ hasText: calendarName });
|
||||
|
||||
if (await regularCalendarItem.count() > 0) {
|
||||
await regularCalendarItem.locator('input[type="checkbox"]').click();
|
||||
} else if (await externalCalendarItem.count() > 0) {
|
||||
await externalCalendarItem.locator('input[type="checkbox"]').click();
|
||||
}
|
||||
|
||||
await this.waitForCalendarLoad();
|
||||
}
|
||||
|
||||
async changeTheme(theme: string) {
|
||||
await this.page.selectOption('.theme-selector-dropdown', theme);
|
||||
|
||||
// Wait for theme to apply
|
||||
await this.page.waitForTimeout(500);
|
||||
}
|
||||
|
||||
async changeStyle(style: string) {
|
||||
await this.page.selectOption('.style-selector-dropdown', style);
|
||||
|
||||
// Wait for style to apply
|
||||
await this.page.waitForTimeout(500);
|
||||
}
|
||||
|
||||
async deleteEvent(eventTitle: string) {
|
||||
const event = await this.getEventByTitle(eventTitle);
|
||||
await expect(event).toBeVisible({ timeout: 5000 });
|
||||
|
||||
// Right-click to open context menu
|
||||
await event.click({ button: 'right' });
|
||||
|
||||
// Wait for context menu and click delete
|
||||
const deleteOption = this.page.getByText(/delete|remove/i);
|
||||
await expect(deleteOption).toBeVisible({ timeout: 3000 });
|
||||
await deleteOption.click();
|
||||
|
||||
// Confirm deletion if there's a confirmation dialog
|
||||
const confirmButton = this.page.getByRole('button', { name: /delete|confirm|yes/i });
|
||||
if (await confirmButton.count() > 0) {
|
||||
await confirmButton.click();
|
||||
}
|
||||
|
||||
// Wait for the event to be removed
|
||||
await expect(event).toBeHidden({ timeout: 5000 });
|
||||
await this.waitForCalendarLoad();
|
||||
}
|
||||
}
|
||||
1
frontend/e2e/node_modules/.bin/playwright
generated
vendored
Symbolic link
1
frontend/e2e/node_modules/.bin/playwright
generated
vendored
Symbolic link
@@ -0,0 +1 @@
|
||||
../@playwright/test/cli.js
|
||||
1
frontend/e2e/node_modules/.bin/playwright-core
generated
vendored
Symbolic link
1
frontend/e2e/node_modules/.bin/playwright-core
generated
vendored
Symbolic link
@@ -0,0 +1 @@
|
||||
../playwright-core/cli.js
|
||||
1
frontend/e2e/node_modules/.bin/tsc
generated
vendored
Symbolic link
1
frontend/e2e/node_modules/.bin/tsc
generated
vendored
Symbolic link
@@ -0,0 +1 @@
|
||||
../typescript/bin/tsc
|
||||
1
frontend/e2e/node_modules/.bin/tsserver
generated
vendored
Symbolic link
1
frontend/e2e/node_modules/.bin/tsserver
generated
vendored
Symbolic link
@@ -0,0 +1 @@
|
||||
../typescript/bin/tsserver
|
||||
103
frontend/e2e/node_modules/.package-lock.json
generated
vendored
Normal file
103
frontend/e2e/node_modules/.package-lock.json
generated
vendored
Normal file
@@ -0,0 +1,103 @@
|
||||
{
|
||||
"name": "runway-e2e-tests",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"node_modules/@playwright/test": {
|
||||
"version": "1.55.0",
|
||||
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.55.0.tgz",
|
||||
"integrity": "sha512-04IXzPwHrW69XusN/SIdDdKZBzMfOT9UNT/YiJit/xpy2VuAoB8NHc8Aplb96zsWDddLnbkPL3TsmrS04ZU2xQ==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright": "1.55.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/node": {
|
||||
"version": "20.19.13",
|
||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.13.tgz",
|
||||
"integrity": "sha512-yCAeZl7a0DxgNVteXFHt9+uyFbqXGy/ShC4BlcHkoE0AfGXYv/BUiplV72DjMYXHDBXFjhvr6DD1NiRVfB4j8g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"undici-types": "~6.21.0"
|
||||
}
|
||||
},
|
||||
"node_modules/fsevents": {
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"ideallyInert": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.55.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.55.0.tgz",
|
||||
"integrity": "sha512-sdCWStblvV1YU909Xqx0DhOjPZE4/5lJsIS84IfN9dAZfcl/CIZ5O8l3o0j7hPMjDvqoTF8ZUcc+i/GL5erstA==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.55.0"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"fsevents": "2.3.2"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.55.0",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.55.0.tgz",
|
||||
"integrity": "sha512-GvZs4vU3U5ro2nZpeiwyb0zuFaqb9sUiAJuyrWpcGouD8y9/HLgGbNRjIph7zU9D3hnPaisMl9zG9CgFi/biIg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/typescript": {
|
||||
"version": "5.9.2",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.2.tgz",
|
||||
"integrity": "sha512-CWBzXQrc/qOkhidw1OzBTQuYRbfyxDXJMVJ1XNwUHGROVmuaeiEm3OslpZ1RV96d7SKKjZKrSJu3+t/xlw3R9A==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
"tsserver": "bin/tsserver"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.17"
|
||||
}
|
||||
},
|
||||
"node_modules/undici-types": {
|
||||
"version": "6.21.0",
|
||||
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
|
||||
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
}
|
||||
}
|
||||
}
|
||||
202
frontend/e2e/node_modules/@playwright/test/LICENSE
generated
vendored
Normal file
202
frontend/e2e/node_modules/@playwright/test/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,202 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Portions Copyright (c) Microsoft Corporation.
|
||||
Portions Copyright 2017 Google Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
5
frontend/e2e/node_modules/@playwright/test/NOTICE
generated
vendored
Normal file
5
frontend/e2e/node_modules/@playwright/test/NOTICE
generated
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
Playwright
|
||||
Copyright (c) Microsoft Corporation
|
||||
|
||||
This software contains code derived from the Puppeteer project (https://github.com/puppeteer/puppeteer),
|
||||
available under the Apache 2.0 license (https://github.com/puppeteer/puppeteer/blob/master/LICENSE).
|
||||
168
frontend/e2e/node_modules/@playwright/test/README.md
generated
vendored
Normal file
168
frontend/e2e/node_modules/@playwright/test/README.md
generated
vendored
Normal file
@@ -0,0 +1,168 @@
|
||||
# 🎭 Playwright
|
||||
|
||||
[](https://www.npmjs.com/package/playwright) <!-- GEN:chromium-version-badge -->[](https://www.chromium.org/Home)<!-- GEN:stop --> <!-- GEN:firefox-version-badge -->[](https://www.mozilla.org/en-US/firefox/new/)<!-- GEN:stop --> <!-- GEN:webkit-version-badge -->[](https://webkit.org/)<!-- GEN:stop --> [](https://aka.ms/playwright/discord)
|
||||
|
||||
## [Documentation](https://playwright.dev) | [API reference](https://playwright.dev/docs/api/class-playwright)
|
||||
|
||||
Playwright is a framework for Web Testing and Automation. It allows testing [Chromium](https://www.chromium.org/Home), [Firefox](https://www.mozilla.org/en-US/firefox/new/) and [WebKit](https://webkit.org/) with a single API. Playwright is built to enable cross-browser web automation that is **ever-green**, **capable**, **reliable** and **fast**.
|
||||
|
||||
| | Linux | macOS | Windows |
|
||||
| :--- | :---: | :---: | :---: |
|
||||
| Chromium <!-- GEN:chromium-version -->140.0.7339.16<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
|
||||
| WebKit <!-- GEN:webkit-version -->26.0<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
|
||||
| Firefox <!-- GEN:firefox-version -->141.0<!-- GEN:stop --> | :white_check_mark: | :white_check_mark: | :white_check_mark: |
|
||||
|
||||
Headless execution is supported for all browsers on all platforms. Check out [system requirements](https://playwright.dev/docs/intro#system-requirements) for details.
|
||||
|
||||
Looking for Playwright for [Python](https://playwright.dev/python/docs/intro), [.NET](https://playwright.dev/dotnet/docs/intro), or [Java](https://playwright.dev/java/docs/intro)?
|
||||
|
||||
## Installation
|
||||
|
||||
Playwright has its own test runner for end-to-end tests, we call it Playwright Test.
|
||||
|
||||
### Using init command
|
||||
|
||||
The easiest way to get started with Playwright Test is to run the init command.
|
||||
|
||||
```Shell
|
||||
# Run from your project's root directory
|
||||
npm init playwright@latest
|
||||
# Or create a new project
|
||||
npm init playwright@latest new-project
|
||||
```
|
||||
|
||||
This will create a configuration file, optionally add examples, a GitHub Action workflow and a first test example.spec.ts. You can now jump directly to writing assertions section.
|
||||
|
||||
### Manually
|
||||
|
||||
Add dependency and install browsers.
|
||||
|
||||
```Shell
|
||||
npm i -D @playwright/test
|
||||
# install supported browsers
|
||||
npx playwright install
|
||||
```
|
||||
|
||||
You can optionally install only selected browsers, see [install browsers](https://playwright.dev/docs/cli#install-browsers) for more details. Or you can install no browsers at all and use existing [browser channels](https://playwright.dev/docs/browsers).
|
||||
|
||||
* [Getting started](https://playwright.dev/docs/intro)
|
||||
* [API reference](https://playwright.dev/docs/api/class-playwright)
|
||||
|
||||
## Capabilities
|
||||
|
||||
### Resilient • No flaky tests
|
||||
|
||||
**Auto-wait**. Playwright waits for elements to be actionable prior to performing actions. It also has a rich set of introspection events. The combination of the two eliminates the need for artificial timeouts - a primary cause of flaky tests.
|
||||
|
||||
**Web-first assertions**. Playwright assertions are created specifically for the dynamic web. Checks are automatically retried until the necessary conditions are met.
|
||||
|
||||
**Tracing**. Configure test retry strategy, capture execution trace, videos and screenshots to eliminate flakes.
|
||||
|
||||
### No trade-offs • No limits
|
||||
|
||||
Browsers run web content belonging to different origins in different processes. Playwright is aligned with the architecture of the modern browsers and runs tests out-of-process. This makes Playwright free of the typical in-process test runner limitations.
|
||||
|
||||
**Multiple everything**. Test scenarios that span multiple tabs, multiple origins and multiple users. Create scenarios with different contexts for different users and run them against your server, all in one test.
|
||||
|
||||
**Trusted events**. Hover elements, interact with dynamic controls and produce trusted events. Playwright uses real browser input pipeline indistinguishable from the real user.
|
||||
|
||||
Test frames, pierce Shadow DOM. Playwright selectors pierce shadow DOM and allow entering frames seamlessly.
|
||||
|
||||
### Full isolation • Fast execution
|
||||
|
||||
**Browser contexts**. Playwright creates a browser context for each test. Browser context is equivalent to a brand new browser profile. This delivers full test isolation with zero overhead. Creating a new browser context only takes a handful of milliseconds.
|
||||
|
||||
**Log in once**. Save the authentication state of the context and reuse it in all the tests. This bypasses repetitive log-in operations in each test, yet delivers full isolation of independent tests.
|
||||
|
||||
### Powerful Tooling
|
||||
|
||||
**[Codegen](https://playwright.dev/docs/codegen)**. Generate tests by recording your actions. Save them into any language.
|
||||
|
||||
**[Playwright inspector](https://playwright.dev/docs/inspector)**. Inspect page, generate selectors, step through the test execution, see click points and explore execution logs.
|
||||
|
||||
**[Trace Viewer](https://playwright.dev/docs/trace-viewer)**. Capture all the information to investigate the test failure. Playwright trace contains test execution screencast, live DOM snapshots, action explorer, test source and many more.
|
||||
|
||||
Looking for Playwright for [TypeScript](https://playwright.dev/docs/intro), [JavaScript](https://playwright.dev/docs/intro), [Python](https://playwright.dev/python/docs/intro), [.NET](https://playwright.dev/dotnet/docs/intro), or [Java](https://playwright.dev/java/docs/intro)?
|
||||
|
||||
## Examples
|
||||
|
||||
To learn how to run these Playwright Test examples, check out our [getting started docs](https://playwright.dev/docs/intro).
|
||||
|
||||
#### Page screenshot
|
||||
|
||||
This code snippet navigates to Playwright homepage and saves a screenshot.
|
||||
|
||||
```TypeScript
|
||||
import { test } from '@playwright/test';
|
||||
|
||||
test('Page Screenshot', async ({ page }) => {
|
||||
await page.goto('https://playwright.dev/');
|
||||
await page.screenshot({ path: `example.png` });
|
||||
});
|
||||
```
|
||||
|
||||
#### Mobile and geolocation
|
||||
|
||||
This snippet emulates Mobile Safari on a device at given geolocation, navigates to maps.google.com, performs the action and takes a screenshot.
|
||||
|
||||
```TypeScript
|
||||
import { test, devices } from '@playwright/test';
|
||||
|
||||
test.use({
|
||||
...devices['iPhone 13 Pro'],
|
||||
locale: 'en-US',
|
||||
geolocation: { longitude: 12.492507, latitude: 41.889938 },
|
||||
permissions: ['geolocation'],
|
||||
})
|
||||
|
||||
test('Mobile and geolocation', async ({ page }) => {
|
||||
await page.goto('https://maps.google.com');
|
||||
await page.getByText('Your location').click();
|
||||
await page.waitForRequest(/.*preview\/pwa/);
|
||||
await page.screenshot({ path: 'colosseum-iphone.png' });
|
||||
});
|
||||
```
|
||||
|
||||
#### Evaluate in browser context
|
||||
|
||||
This code snippet navigates to example.com, and executes a script in the page context.
|
||||
|
||||
```TypeScript
|
||||
import { test } from '@playwright/test';
|
||||
|
||||
test('Evaluate in browser context', async ({ page }) => {
|
||||
await page.goto('https://www.example.com/');
|
||||
const dimensions = await page.evaluate(() => {
|
||||
return {
|
||||
width: document.documentElement.clientWidth,
|
||||
height: document.documentElement.clientHeight,
|
||||
deviceScaleFactor: window.devicePixelRatio
|
||||
}
|
||||
});
|
||||
console.log(dimensions);
|
||||
});
|
||||
```
|
||||
|
||||
#### Intercept network requests
|
||||
|
||||
This code snippet sets up request routing for a page to log all network requests.
|
||||
|
||||
```TypeScript
|
||||
import { test } from '@playwright/test';
|
||||
|
||||
test('Intercept network requests', async ({ page }) => {
|
||||
// Log and continue all network requests
|
||||
await page.route('**', route => {
|
||||
console.log(route.request().url());
|
||||
route.continue();
|
||||
});
|
||||
await page.goto('http://todomvc.com');
|
||||
});
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
* [Documentation](https://playwright.dev)
|
||||
* [API reference](https://playwright.dev/docs/api/class-playwright/)
|
||||
* [Contribution guide](CONTRIBUTING.md)
|
||||
* [Changelog](https://github.com/microsoft/playwright/releases)
|
||||
19
frontend/e2e/node_modules/@playwright/test/cli.js
generated
vendored
Executable file
19
frontend/e2e/node_modules/@playwright/test/cli.js
generated
vendored
Executable file
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
const { program } = require('playwright/lib/program');
|
||||
program.parse(process.argv);
|
||||
18
frontend/e2e/node_modules/@playwright/test/index.d.ts
generated
vendored
Normal file
18
frontend/e2e/node_modules/@playwright/test/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export * from 'playwright/test';
|
||||
export { default } from 'playwright/test';
|
||||
17
frontend/e2e/node_modules/@playwright/test/index.js
generated
vendored
Normal file
17
frontend/e2e/node_modules/@playwright/test/index.js
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
module.exports = require('playwright/test');
|
||||
18
frontend/e2e/node_modules/@playwright/test/index.mjs
generated
vendored
Normal file
18
frontend/e2e/node_modules/@playwright/test/index.mjs
generated
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export * from 'playwright/test';
|
||||
export { default } from 'playwright/test';
|
||||
35
frontend/e2e/node_modules/@playwright/test/package.json
generated
vendored
Normal file
35
frontend/e2e/node_modules/@playwright/test/package.json
generated
vendored
Normal file
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"name": "@playwright/test",
|
||||
"version": "1.55.0",
|
||||
"description": "A high-level API to automate web browsers",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/microsoft/playwright.git"
|
||||
},
|
||||
"homepage": "https://playwright.dev",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"author": {
|
||||
"name": "Microsoft Corporation"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./index.d.ts",
|
||||
"import": "./index.mjs",
|
||||
"require": "./index.js",
|
||||
"default": "./index.js"
|
||||
},
|
||||
"./cli": "./cli.js",
|
||||
"./package.json": "./package.json",
|
||||
"./reporter": "./reporter.js"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"scripts": {},
|
||||
"dependencies": {
|
||||
"playwright": "1.55.0"
|
||||
}
|
||||
}
|
||||
17
frontend/e2e/node_modules/@playwright/test/reporter.d.ts
generated
vendored
Normal file
17
frontend/e2e/node_modules/@playwright/test/reporter.d.ts
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
export * from 'playwright/types/testReporter';
|
||||
17
frontend/e2e/node_modules/@playwright/test/reporter.js
generated
vendored
Normal file
17
frontend/e2e/node_modules/@playwright/test/reporter.js
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// We only export types in reporter.d.ts.
|
||||
17
frontend/e2e/node_modules/@playwright/test/reporter.mjs
generated
vendored
Normal file
17
frontend/e2e/node_modules/@playwright/test/reporter.mjs
generated
vendored
Normal file
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Copyright (c) Microsoft Corporation.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
// We only export types in reporter.d.ts.
|
||||
21
frontend/e2e/node_modules/@types/node/LICENSE
generated
vendored
Normal file
21
frontend/e2e/node_modules/@types/node/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) Microsoft Corporation.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE
|
||||
15
frontend/e2e/node_modules/@types/node/README.md
generated
vendored
Normal file
15
frontend/e2e/node_modules/@types/node/README.md
generated
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
# Installation
|
||||
> `npm install --save @types/node`
|
||||
|
||||
# Summary
|
||||
This package contains type definitions for node (https://nodejs.org/).
|
||||
|
||||
# Details
|
||||
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node/v20.
|
||||
|
||||
### Additional Details
|
||||
* Last updated: Thu, 04 Sep 2025 10:02:38 GMT
|
||||
* Dependencies: [undici-types](https://npmjs.com/package/undici-types)
|
||||
|
||||
# Credits
|
||||
These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [David Junger](https://github.com/touffy), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Sebastian Silbermann](https://github.com/eps1lon), [Wilco Bakker](https://github.com/WilcoBakker), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), and [Dmitry Semigradsky](https://github.com/Semigradsky).
|
||||
1044
frontend/e2e/node_modules/@types/node/assert.d.ts
generated
vendored
Normal file
1044
frontend/e2e/node_modules/@types/node/assert.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
8
frontend/e2e/node_modules/@types/node/assert/strict.d.ts
generated
vendored
Normal file
8
frontend/e2e/node_modules/@types/node/assert/strict.d.ts
generated
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
declare module "assert/strict" {
|
||||
import { strict } from "node:assert";
|
||||
export = strict;
|
||||
}
|
||||
declare module "node:assert/strict" {
|
||||
import { strict } from "node:assert";
|
||||
export = strict;
|
||||
}
|
||||
605
frontend/e2e/node_modules/@types/node/async_hooks.d.ts
generated
vendored
Normal file
605
frontend/e2e/node_modules/@types/node/async_hooks.d.ts
generated
vendored
Normal file
@@ -0,0 +1,605 @@
|
||||
/**
|
||||
* We strongly discourage the use of the `async_hooks` API.
|
||||
* Other APIs that can cover most of its use cases include:
|
||||
*
|
||||
* * [`AsyncLocalStorage`](https://nodejs.org/docs/latest-v20.x/api/async_context.html#class-asynclocalstorage) tracks async context
|
||||
* * [`process.getActiveResourcesInfo()`](https://nodejs.org/docs/latest-v20.x/api/process.html#processgetactiveresourcesinfo) tracks active resources
|
||||
*
|
||||
* The `node:async_hooks` module provides an API to track asynchronous resources.
|
||||
* It can be accessed using:
|
||||
*
|
||||
* ```js
|
||||
* import async_hooks from 'node:async_hooks';
|
||||
* ```
|
||||
* @experimental
|
||||
* @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/async_hooks.js)
|
||||
*/
|
||||
declare module "async_hooks" {
|
||||
/**
|
||||
* ```js
|
||||
* import { executionAsyncId } from 'node:async_hooks';
|
||||
* import fs from 'node:fs';
|
||||
*
|
||||
* console.log(executionAsyncId()); // 1 - bootstrap
|
||||
* const path = '.';
|
||||
* fs.open(path, 'r', (err, fd) => {
|
||||
* console.log(executionAsyncId()); // 6 - open()
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* The ID returned from `executionAsyncId()` is related to execution timing, not
|
||||
* causality (which is covered by `triggerAsyncId()`):
|
||||
*
|
||||
* ```js
|
||||
* const server = net.createServer((conn) => {
|
||||
* // Returns the ID of the server, not of the new connection, because the
|
||||
* // callback runs in the execution scope of the server's MakeCallback().
|
||||
* async_hooks.executionAsyncId();
|
||||
*
|
||||
* }).listen(port, () => {
|
||||
* // Returns the ID of a TickObject (process.nextTick()) because all
|
||||
* // callbacks passed to .listen() are wrapped in a nextTick().
|
||||
* async_hooks.executionAsyncId();
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Promise contexts may not get precise `executionAsyncIds` by default.
|
||||
* See the section on [promise execution tracking](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html#promise-execution-tracking).
|
||||
* @since v8.1.0
|
||||
* @return The `asyncId` of the current execution context. Useful to track when something calls.
|
||||
*/
|
||||
function executionAsyncId(): number;
|
||||
/**
|
||||
* Resource objects returned by `executionAsyncResource()` are most often internal
|
||||
* Node.js handle objects with undocumented APIs. Using any functions or properties
|
||||
* on the object is likely to crash your application and should be avoided.
|
||||
*
|
||||
* Using `executionAsyncResource()` in the top-level execution context will
|
||||
* return an empty object as there is no handle or request object to use,
|
||||
* but having an object representing the top-level can be helpful.
|
||||
*
|
||||
* ```js
|
||||
* import { open } from 'node:fs';
|
||||
* import { executionAsyncId, executionAsyncResource } from 'node:async_hooks';
|
||||
*
|
||||
* console.log(executionAsyncId(), executionAsyncResource()); // 1 {}
|
||||
* open(new URL(import.meta.url), 'r', (err, fd) => {
|
||||
* console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* This can be used to implement continuation local storage without the
|
||||
* use of a tracking `Map` to store the metadata:
|
||||
*
|
||||
* ```js
|
||||
* import { createServer } from 'node:http';
|
||||
* import {
|
||||
* executionAsyncId,
|
||||
* executionAsyncResource,
|
||||
* createHook,
|
||||
* } from 'async_hooks';
|
||||
* const sym = Symbol('state'); // Private symbol to avoid pollution
|
||||
*
|
||||
* createHook({
|
||||
* init(asyncId, type, triggerAsyncId, resource) {
|
||||
* const cr = executionAsyncResource();
|
||||
* if (cr) {
|
||||
* resource[sym] = cr[sym];
|
||||
* }
|
||||
* },
|
||||
* }).enable();
|
||||
*
|
||||
* const server = createServer((req, res) => {
|
||||
* executionAsyncResource()[sym] = { state: req.url };
|
||||
* setTimeout(function() {
|
||||
* res.end(JSON.stringify(executionAsyncResource()[sym]));
|
||||
* }, 100);
|
||||
* }).listen(3000);
|
||||
* ```
|
||||
* @since v13.9.0, v12.17.0
|
||||
* @return The resource representing the current execution. Useful to store data within the resource.
|
||||
*/
|
||||
function executionAsyncResource(): object;
|
||||
/**
|
||||
* ```js
|
||||
* const server = net.createServer((conn) => {
|
||||
* // The resource that caused (or triggered) this callback to be called
|
||||
* // was that of the new connection. Thus the return value of triggerAsyncId()
|
||||
* // is the asyncId of "conn".
|
||||
* async_hooks.triggerAsyncId();
|
||||
*
|
||||
* }).listen(port, () => {
|
||||
* // Even though all callbacks passed to .listen() are wrapped in a nextTick()
|
||||
* // the callback itself exists because the call to the server's .listen()
|
||||
* // was made. So the return value would be the ID of the server.
|
||||
* async_hooks.triggerAsyncId();
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Promise contexts may not get valid `triggerAsyncId`s by default. See
|
||||
* the section on [promise execution tracking](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html#promise-execution-tracking).
|
||||
* @return The ID of the resource responsible for calling the callback that is currently being executed.
|
||||
*/
|
||||
function triggerAsyncId(): number;
|
||||
interface HookCallbacks {
|
||||
/**
|
||||
* Called when a class is constructed that has the possibility to emit an asynchronous event.
|
||||
* @param asyncId A unique ID for the async resource
|
||||
* @param type The type of the async resource
|
||||
* @param triggerAsyncId The unique ID of the async resource in whose execution context this async resource was created
|
||||
* @param resource Reference to the resource representing the async operation, needs to be released during destroy
|
||||
*/
|
||||
init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void;
|
||||
/**
|
||||
* When an asynchronous operation is initiated or completes a callback is called to notify the user.
|
||||
* The before callback is called just before said callback is executed.
|
||||
* @param asyncId the unique identifier assigned to the resource about to execute the callback.
|
||||
*/
|
||||
before?(asyncId: number): void;
|
||||
/**
|
||||
* Called immediately after the callback specified in `before` is completed.
|
||||
*
|
||||
* If an uncaught exception occurs during execution of the callback, then `after` will run after the `'uncaughtException'` event is emitted or a `domain`'s handler runs.
|
||||
* @param asyncId the unique identifier assigned to the resource which has executed the callback.
|
||||
*/
|
||||
after?(asyncId: number): void;
|
||||
/**
|
||||
* Called when a promise has resolve() called. This may not be in the same execution id
|
||||
* as the promise itself.
|
||||
* @param asyncId the unique id for the promise that was resolve()d.
|
||||
*/
|
||||
promiseResolve?(asyncId: number): void;
|
||||
/**
|
||||
* Called after the resource corresponding to asyncId is destroyed
|
||||
* @param asyncId a unique ID for the async resource
|
||||
*/
|
||||
destroy?(asyncId: number): void;
|
||||
}
|
||||
interface AsyncHook {
|
||||
/**
|
||||
* Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop.
|
||||
*/
|
||||
enable(): this;
|
||||
/**
|
||||
* Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled.
|
||||
*/
|
||||
disable(): this;
|
||||
}
|
||||
/**
|
||||
* Registers functions to be called for different lifetime events of each async
|
||||
* operation.
|
||||
*
|
||||
* The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the
|
||||
* respective asynchronous event during a resource's lifetime.
|
||||
*
|
||||
* All callbacks are optional. For example, if only resource cleanup needs to
|
||||
* be tracked, then only the `destroy` callback needs to be passed. The
|
||||
* specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section.
|
||||
*
|
||||
* ```js
|
||||
* import { createHook } from 'node:async_hooks';
|
||||
*
|
||||
* const asyncHook = createHook({
|
||||
* init(asyncId, type, triggerAsyncId, resource) { },
|
||||
* destroy(asyncId) { },
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* The callbacks will be inherited via the prototype chain:
|
||||
*
|
||||
* ```js
|
||||
* class MyAsyncCallbacks {
|
||||
* init(asyncId, type, triggerAsyncId, resource) { }
|
||||
* destroy(asyncId) {}
|
||||
* }
|
||||
*
|
||||
* class MyAddedCallbacks extends MyAsyncCallbacks {
|
||||
* before(asyncId) { }
|
||||
* after(asyncId) { }
|
||||
* }
|
||||
*
|
||||
* const asyncHook = async_hooks.createHook(new MyAddedCallbacks());
|
||||
* ```
|
||||
*
|
||||
* Because promises are asynchronous resources whose lifecycle is tracked
|
||||
* via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises.
|
||||
* @since v8.1.0
|
||||
* @param callbacks The `Hook Callbacks` to register
|
||||
* @return Instance used for disabling and enabling hooks
|
||||
*/
|
||||
function createHook(callbacks: HookCallbacks): AsyncHook;
|
||||
interface AsyncResourceOptions {
|
||||
/**
|
||||
* The ID of the execution context that created this async event.
|
||||
* @default executionAsyncId()
|
||||
*/
|
||||
triggerAsyncId?: number | undefined;
|
||||
/**
|
||||
* Disables automatic `emitDestroy` when the object is garbage collected.
|
||||
* This usually does not need to be set (even if `emitDestroy` is called
|
||||
* manually), unless the resource's `asyncId` is retrieved and the
|
||||
* sensitive API's `emitDestroy` is called with it.
|
||||
* @default false
|
||||
*/
|
||||
requireManualDestroy?: boolean | undefined;
|
||||
}
|
||||
/**
|
||||
* The class `AsyncResource` is designed to be extended by the embedder's async
|
||||
* resources. Using this, users can easily trigger the lifetime events of their
|
||||
* own resources.
|
||||
*
|
||||
* The `init` hook will trigger when an `AsyncResource` is instantiated.
|
||||
*
|
||||
* The following is an overview of the `AsyncResource` API.
|
||||
*
|
||||
* ```js
|
||||
* import { AsyncResource, executionAsyncId } from 'node:async_hooks';
|
||||
*
|
||||
* // AsyncResource() is meant to be extended. Instantiating a
|
||||
* // new AsyncResource() also triggers init. If triggerAsyncId is omitted then
|
||||
* // async_hook.executionAsyncId() is used.
|
||||
* const asyncResource = new AsyncResource(
|
||||
* type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false },
|
||||
* );
|
||||
*
|
||||
* // Run a function in the execution context of the resource. This will
|
||||
* // * establish the context of the resource
|
||||
* // * trigger the AsyncHooks before callbacks
|
||||
* // * call the provided function `fn` with the supplied arguments
|
||||
* // * trigger the AsyncHooks after callbacks
|
||||
* // * restore the original execution context
|
||||
* asyncResource.runInAsyncScope(fn, thisArg, ...args);
|
||||
*
|
||||
* // Call AsyncHooks destroy callbacks.
|
||||
* asyncResource.emitDestroy();
|
||||
*
|
||||
* // Return the unique ID assigned to the AsyncResource instance.
|
||||
* asyncResource.asyncId();
|
||||
*
|
||||
* // Return the trigger ID for the AsyncResource instance.
|
||||
* asyncResource.triggerAsyncId();
|
||||
* ```
|
||||
*/
|
||||
class AsyncResource {
|
||||
/**
|
||||
* AsyncResource() is meant to be extended. Instantiating a
|
||||
* new AsyncResource() also triggers init. If triggerAsyncId is omitted then
|
||||
* async_hook.executionAsyncId() is used.
|
||||
* @param type The type of async event.
|
||||
* @param triggerAsyncId The ID of the execution context that created
|
||||
* this async event (default: `executionAsyncId()`), or an
|
||||
* AsyncResourceOptions object (since v9.3.0)
|
||||
*/
|
||||
constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions);
|
||||
/**
|
||||
* Binds the given function to the current execution context.
|
||||
* @since v14.8.0, v12.19.0
|
||||
* @param fn The function to bind to the current execution context.
|
||||
* @param type An optional name to associate with the underlying `AsyncResource`.
|
||||
*/
|
||||
static bind<Func extends (this: ThisArg, ...args: any[]) => any, ThisArg>(
|
||||
fn: Func,
|
||||
type?: string,
|
||||
thisArg?: ThisArg,
|
||||
): Func;
|
||||
/**
|
||||
* Binds the given function to execute to this `AsyncResource`'s scope.
|
||||
* @since v14.8.0, v12.19.0
|
||||
* @param fn The function to bind to the current `AsyncResource`.
|
||||
*/
|
||||
bind<Func extends (...args: any[]) => any>(fn: Func): Func;
|
||||
/**
|
||||
* Call the provided function with the provided arguments in the execution context
|
||||
* of the async resource. This will establish the context, trigger the AsyncHooks
|
||||
* before callbacks, call the function, trigger the AsyncHooks after callbacks, and
|
||||
* then restore the original execution context.
|
||||
* @since v9.6.0
|
||||
* @param fn The function to call in the execution context of this async resource.
|
||||
* @param thisArg The receiver to be used for the function call.
|
||||
* @param args Optional arguments to pass to the function.
|
||||
*/
|
||||
runInAsyncScope<This, Result>(
|
||||
fn: (this: This, ...args: any[]) => Result,
|
||||
thisArg?: This,
|
||||
...args: any[]
|
||||
): Result;
|
||||
/**
|
||||
* Call all `destroy` hooks. This should only ever be called once. An error will
|
||||
* be thrown if it is called more than once. This **must** be manually called. If
|
||||
* the resource is left to be collected by the GC then the `destroy` hooks will
|
||||
* never be called.
|
||||
* @return A reference to `asyncResource`.
|
||||
*/
|
||||
emitDestroy(): this;
|
||||
/**
|
||||
* @return The unique `asyncId` assigned to the resource.
|
||||
*/
|
||||
asyncId(): number;
|
||||
/**
|
||||
* @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor.
|
||||
*/
|
||||
triggerAsyncId(): number;
|
||||
}
|
||||
/**
|
||||
* This class creates stores that stay coherent through asynchronous operations.
|
||||
*
|
||||
* While you can create your own implementation on top of the `node:async_hooks` module, `AsyncLocalStorage` should be preferred as it is a performant and memory
|
||||
* safe implementation that involves significant optimizations that are non-obvious
|
||||
* to implement.
|
||||
*
|
||||
* The following example uses `AsyncLocalStorage` to build a simple logger
|
||||
* that assigns IDs to incoming HTTP requests and includes them in messages
|
||||
* logged within each request.
|
||||
*
|
||||
* ```js
|
||||
* import http from 'node:http';
|
||||
* import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
*
|
||||
* const asyncLocalStorage = new AsyncLocalStorage();
|
||||
*
|
||||
* function logWithId(msg) {
|
||||
* const id = asyncLocalStorage.getStore();
|
||||
* console.log(`${id !== undefined ? id : '-'}:`, msg);
|
||||
* }
|
||||
*
|
||||
* let idSeq = 0;
|
||||
* http.createServer((req, res) => {
|
||||
* asyncLocalStorage.run(idSeq++, () => {
|
||||
* logWithId('start');
|
||||
* // Imagine any chain of async operations here
|
||||
* setImmediate(() => {
|
||||
* logWithId('finish');
|
||||
* res.end();
|
||||
* });
|
||||
* });
|
||||
* }).listen(8080);
|
||||
*
|
||||
* http.get('http://localhost:8080');
|
||||
* http.get('http://localhost:8080');
|
||||
* // Prints:
|
||||
* // 0: start
|
||||
* // 1: start
|
||||
* // 0: finish
|
||||
* // 1: finish
|
||||
* ```
|
||||
*
|
||||
* Each instance of `AsyncLocalStorage` maintains an independent storage context.
|
||||
* Multiple instances can safely exist simultaneously without risk of interfering
|
||||
* with each other's data.
|
||||
* @since v13.10.0, v12.17.0
|
||||
*/
|
||||
class AsyncLocalStorage<T> {
|
||||
/**
|
||||
* Binds the given function to the current execution context.
|
||||
* @since v19.8.0
|
||||
* @experimental
|
||||
* @param fn The function to bind to the current execution context.
|
||||
* @return A new function that calls `fn` within the captured execution context.
|
||||
*/
|
||||
static bind<Func extends (...args: any[]) => any>(fn: Func): Func;
|
||||
/**
|
||||
* Captures the current execution context and returns a function that accepts a
|
||||
* function as an argument. Whenever the returned function is called, it
|
||||
* calls the function passed to it within the captured context.
|
||||
*
|
||||
* ```js
|
||||
* const asyncLocalStorage = new AsyncLocalStorage();
|
||||
* const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot());
|
||||
* const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore()));
|
||||
* console.log(result); // returns 123
|
||||
* ```
|
||||
*
|
||||
* AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple
|
||||
* async context tracking purposes, for example:
|
||||
*
|
||||
* ```js
|
||||
* class Foo {
|
||||
* #runInAsyncScope = AsyncLocalStorage.snapshot();
|
||||
*
|
||||
* get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); }
|
||||
* }
|
||||
*
|
||||
* const foo = asyncLocalStorage.run(123, () => new Foo());
|
||||
* console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123
|
||||
* ```
|
||||
* @since v19.8.0
|
||||
* @experimental
|
||||
* @return A new function with the signature `(fn: (...args) : R, ...args) : R`.
|
||||
*/
|
||||
static snapshot(): <R, TArgs extends any[]>(fn: (...args: TArgs) => R, ...args: TArgs) => R;
|
||||
/**
|
||||
* Disables the instance of `AsyncLocalStorage`. All subsequent calls
|
||||
* to `asyncLocalStorage.getStore()` will return `undefined` until `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again.
|
||||
*
|
||||
* When calling `asyncLocalStorage.disable()`, all current contexts linked to the
|
||||
* instance will be exited.
|
||||
*
|
||||
* Calling `asyncLocalStorage.disable()` is required before the `asyncLocalStorage` can be garbage collected. This does not apply to stores
|
||||
* provided by the `asyncLocalStorage`, as those objects are garbage collected
|
||||
* along with the corresponding async resources.
|
||||
*
|
||||
* Use this method when the `asyncLocalStorage` is not in use anymore
|
||||
* in the current process.
|
||||
* @since v13.10.0, v12.17.0
|
||||
* @experimental
|
||||
*/
|
||||
disable(): void;
|
||||
/**
|
||||
* Returns the current store.
|
||||
* If called outside of an asynchronous context initialized by
|
||||
* calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it
|
||||
* returns `undefined`.
|
||||
* @since v13.10.0, v12.17.0
|
||||
*/
|
||||
getStore(): T | undefined;
|
||||
/**
|
||||
* Runs a function synchronously within a context and returns its
|
||||
* return value. The store is not accessible outside of the callback function.
|
||||
* The store is accessible to any asynchronous operations created within the
|
||||
* callback.
|
||||
*
|
||||
* The optional `args` are passed to the callback function.
|
||||
*
|
||||
* If the callback function throws an error, the error is thrown by `run()` too.
|
||||
* The stacktrace is not impacted by this call and the context is exited.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* ```js
|
||||
* const store = { id: 2 };
|
||||
* try {
|
||||
* asyncLocalStorage.run(store, () => {
|
||||
* asyncLocalStorage.getStore(); // Returns the store object
|
||||
* setTimeout(() => {
|
||||
* asyncLocalStorage.getStore(); // Returns the store object
|
||||
* }, 200);
|
||||
* throw new Error();
|
||||
* });
|
||||
* } catch (e) {
|
||||
* asyncLocalStorage.getStore(); // Returns undefined
|
||||
* // The error will be caught here
|
||||
* }
|
||||
* ```
|
||||
* @since v13.10.0, v12.17.0
|
||||
*/
|
||||
run<R>(store: T, callback: () => R): R;
|
||||
run<R, TArgs extends any[]>(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R;
|
||||
/**
|
||||
* Runs a function synchronously outside of a context and returns its
|
||||
* return value. The store is not accessible within the callback function or
|
||||
* the asynchronous operations created within the callback. Any `getStore()` call done within the callback function will always return `undefined`.
|
||||
*
|
||||
* The optional `args` are passed to the callback function.
|
||||
*
|
||||
* If the callback function throws an error, the error is thrown by `exit()` too.
|
||||
* The stacktrace is not impacted by this call and the context is re-entered.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* ```js
|
||||
* // Within a call to run
|
||||
* try {
|
||||
* asyncLocalStorage.getStore(); // Returns the store object or value
|
||||
* asyncLocalStorage.exit(() => {
|
||||
* asyncLocalStorage.getStore(); // Returns undefined
|
||||
* throw new Error();
|
||||
* });
|
||||
* } catch (e) {
|
||||
* asyncLocalStorage.getStore(); // Returns the same object or value
|
||||
* // The error will be caught here
|
||||
* }
|
||||
* ```
|
||||
* @since v13.10.0, v12.17.0
|
||||
* @experimental
|
||||
*/
|
||||
exit<R, TArgs extends any[]>(callback: (...args: TArgs) => R, ...args: TArgs): R;
|
||||
/**
|
||||
* Transitions into the context for the remainder of the current
|
||||
* synchronous execution and then persists the store through any following
|
||||
* asynchronous calls.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* ```js
|
||||
* const store = { id: 1 };
|
||||
* // Replaces previous store with the given store object
|
||||
* asyncLocalStorage.enterWith(store);
|
||||
* asyncLocalStorage.getStore(); // Returns the store object
|
||||
* someAsyncOperation(() => {
|
||||
* asyncLocalStorage.getStore(); // Returns the same object
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* This transition will continue for the _entire_ synchronous execution.
|
||||
* This means that if, for example, the context is entered within an event
|
||||
* handler subsequent event handlers will also run within that context unless
|
||||
* specifically bound to another context with an `AsyncResource`. That is why `run()` should be preferred over `enterWith()` unless there are strong reasons
|
||||
* to use the latter method.
|
||||
*
|
||||
* ```js
|
||||
* const store = { id: 1 };
|
||||
*
|
||||
* emitter.on('my-event', () => {
|
||||
* asyncLocalStorage.enterWith(store);
|
||||
* });
|
||||
* emitter.on('my-event', () => {
|
||||
* asyncLocalStorage.getStore(); // Returns the same object
|
||||
* });
|
||||
*
|
||||
* asyncLocalStorage.getStore(); // Returns undefined
|
||||
* emitter.emit('my-event');
|
||||
* asyncLocalStorage.getStore(); // Returns the same object
|
||||
* ```
|
||||
* @since v13.11.0, v12.17.0
|
||||
* @experimental
|
||||
*/
|
||||
enterWith(store: T): void;
|
||||
}
|
||||
/**
|
||||
* @since v17.2.0, v16.14.0
|
||||
* @return A map of provider types to the corresponding numeric id.
|
||||
* This map contains all the event types that might be emitted by the `async_hooks.init()` event.
|
||||
*/
|
||||
namespace asyncWrapProviders {
|
||||
const NONE: number;
|
||||
const DIRHANDLE: number;
|
||||
const DNSCHANNEL: number;
|
||||
const ELDHISTOGRAM: number;
|
||||
const FILEHANDLE: number;
|
||||
const FILEHANDLECLOSEREQ: number;
|
||||
const FIXEDSIZEBLOBCOPY: number;
|
||||
const FSEVENTWRAP: number;
|
||||
const FSREQCALLBACK: number;
|
||||
const FSREQPROMISE: number;
|
||||
const GETADDRINFOREQWRAP: number;
|
||||
const GETNAMEINFOREQWRAP: number;
|
||||
const HEAPSNAPSHOT: number;
|
||||
const HTTP2SESSION: number;
|
||||
const HTTP2STREAM: number;
|
||||
const HTTP2PING: number;
|
||||
const HTTP2SETTINGS: number;
|
||||
const HTTPINCOMINGMESSAGE: number;
|
||||
const HTTPCLIENTREQUEST: number;
|
||||
const JSSTREAM: number;
|
||||
const JSUDPWRAP: number;
|
||||
const MESSAGEPORT: number;
|
||||
const PIPECONNECTWRAP: number;
|
||||
const PIPESERVERWRAP: number;
|
||||
const PIPEWRAP: number;
|
||||
const PROCESSWRAP: number;
|
||||
const PROMISE: number;
|
||||
const QUERYWRAP: number;
|
||||
const SHUTDOWNWRAP: number;
|
||||
const SIGNALWRAP: number;
|
||||
const STATWATCHER: number;
|
||||
const STREAMPIPE: number;
|
||||
const TCPCONNECTWRAP: number;
|
||||
const TCPSERVERWRAP: number;
|
||||
const TCPWRAP: number;
|
||||
const TTYWRAP: number;
|
||||
const UDPSENDWRAP: number;
|
||||
const UDPWRAP: number;
|
||||
const SIGINTWATCHDOG: number;
|
||||
const WORKER: number;
|
||||
const WORKERHEAPSNAPSHOT: number;
|
||||
const WRITEWRAP: number;
|
||||
const ZLIB: number;
|
||||
const CHECKPRIMEREQUEST: number;
|
||||
const PBKDF2REQUEST: number;
|
||||
const KEYPAIRGENREQUEST: number;
|
||||
const KEYGENREQUEST: number;
|
||||
const KEYEXPORTREQUEST: number;
|
||||
const CIPHERREQUEST: number;
|
||||
const DERIVEBITSREQUEST: number;
|
||||
const HASHREQUEST: number;
|
||||
const RANDOMBYTESREQUEST: number;
|
||||
const RANDOMPRIMEREQUEST: number;
|
||||
const SCRYPTREQUEST: number;
|
||||
const SIGNREQUEST: number;
|
||||
const TLSWRAP: number;
|
||||
const VERIFYREQUEST: number;
|
||||
}
|
||||
}
|
||||
declare module "node:async_hooks" {
|
||||
export * from "async_hooks";
|
||||
}
|
||||
462
frontend/e2e/node_modules/@types/node/buffer.buffer.d.ts
generated
vendored
Normal file
462
frontend/e2e/node_modules/@types/node/buffer.buffer.d.ts
generated
vendored
Normal file
@@ -0,0 +1,462 @@
|
||||
declare module "buffer" {
|
||||
type ImplicitArrayBuffer<T extends WithImplicitCoercion<ArrayBufferLike>> = T extends
|
||||
{ valueOf(): infer V extends ArrayBufferLike } ? V : T;
|
||||
global {
|
||||
interface BufferConstructor {
|
||||
// see buffer.d.ts for implementation shared with all TypeScript versions
|
||||
|
||||
/**
|
||||
* Allocates a new buffer containing the given {str}.
|
||||
*
|
||||
* @param str String to store in buffer.
|
||||
* @param encoding encoding to use, optional. Default is 'utf8'
|
||||
* @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead.
|
||||
*/
|
||||
new(str: string, encoding?: BufferEncoding): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Allocates a new buffer of {size} octets.
|
||||
*
|
||||
* @param size count of octets to allocate.
|
||||
* @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`).
|
||||
*/
|
||||
new(size: number): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Allocates a new buffer containing the given {array} of octets.
|
||||
*
|
||||
* @param array The octets to store.
|
||||
* @deprecated since v10.0.0 - Use `Buffer.from(array)` instead.
|
||||
*/
|
||||
new(array: ArrayLike<number>): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Produces a Buffer backed by the same allocated memory as
|
||||
* the given {ArrayBuffer}/{SharedArrayBuffer}.
|
||||
*
|
||||
* @param arrayBuffer The ArrayBuffer with which to share memory.
|
||||
* @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead.
|
||||
*/
|
||||
new<TArrayBuffer extends ArrayBufferLike = ArrayBuffer>(arrayBuffer: TArrayBuffer): Buffer<TArrayBuffer>;
|
||||
/**
|
||||
* Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`.
|
||||
* Array entries outside that range will be truncated to fit into it.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'.
|
||||
* const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
|
||||
* ```
|
||||
*
|
||||
* If `array` is an `Array`-like object (that is, one with a `length` property of
|
||||
* type `number`), it is treated as if it is an array, unless it is a `Buffer` or
|
||||
* a `Uint8Array`. This means all other `TypedArray` variants get treated as an
|
||||
* `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use
|
||||
* `Buffer.copyBytesFrom()`.
|
||||
*
|
||||
* A `TypeError` will be thrown if `array` is not an `Array` or another type
|
||||
* appropriate for `Buffer.from()` variants.
|
||||
*
|
||||
* `Buffer.from(array)` and `Buffer.from(string)` may also use the internal
|
||||
* `Buffer` pool like `Buffer.allocUnsafe()` does.
|
||||
* @since v5.10.0
|
||||
*/
|
||||
from(array: WithImplicitCoercion<ArrayLike<number>>): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* This creates a view of the `ArrayBuffer` without copying the underlying
|
||||
* memory. For example, when passed a reference to the `.buffer` property of a
|
||||
* `TypedArray` instance, the newly created `Buffer` will share the same
|
||||
* allocated memory as the `TypedArray`'s underlying `ArrayBuffer`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const arr = new Uint16Array(2);
|
||||
*
|
||||
* arr[0] = 5000;
|
||||
* arr[1] = 4000;
|
||||
*
|
||||
* // Shares memory with `arr`.
|
||||
* const buf = Buffer.from(arr.buffer);
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 88 13 a0 0f>
|
||||
*
|
||||
* // Changing the original Uint16Array changes the Buffer also.
|
||||
* arr[1] = 6000;
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 88 13 70 17>
|
||||
* ```
|
||||
*
|
||||
* The optional `byteOffset` and `length` arguments specify a memory range within
|
||||
* the `arrayBuffer` that will be shared by the `Buffer`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const ab = new ArrayBuffer(10);
|
||||
* const buf = Buffer.from(ab, 0, 2);
|
||||
*
|
||||
* console.log(buf.length);
|
||||
* // Prints: 2
|
||||
* ```
|
||||
*
|
||||
* A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer` or a
|
||||
* `SharedArrayBuffer` or another type appropriate for `Buffer.from()`
|
||||
* variants.
|
||||
*
|
||||
* It is important to remember that a backing `ArrayBuffer` can cover a range
|
||||
* of memory that extends beyond the bounds of a `TypedArray` view. A new
|
||||
* `Buffer` created using the `buffer` property of a `TypedArray` may extend
|
||||
* beyond the range of the `TypedArray`:
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const arrA = Uint8Array.from([0x63, 0x64, 0x65, 0x66]); // 4 elements
|
||||
* const arrB = new Uint8Array(arrA.buffer, 1, 2); // 2 elements
|
||||
* console.log(arrA.buffer === arrB.buffer); // true
|
||||
*
|
||||
* const buf = Buffer.from(arrB.buffer);
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 63 64 65 66>
|
||||
* ```
|
||||
* @since v5.10.0
|
||||
* @param arrayBuffer An `ArrayBuffer`, `SharedArrayBuffer`, for example the
|
||||
* `.buffer` property of a `TypedArray`.
|
||||
* @param byteOffset Index of first byte to expose. **Default:** `0`.
|
||||
* @param length Number of bytes to expose. **Default:**
|
||||
* `arrayBuffer.byteLength - byteOffset`.
|
||||
*/
|
||||
from<TArrayBuffer extends WithImplicitCoercion<ArrayBufferLike>>(
|
||||
arrayBuffer: TArrayBuffer,
|
||||
byteOffset?: number,
|
||||
length?: number,
|
||||
): Buffer<ImplicitArrayBuffer<TArrayBuffer>>;
|
||||
/**
|
||||
* Creates a new `Buffer` containing `string`. The `encoding` parameter identifies
|
||||
* the character encoding to be used when converting `string` into bytes.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf1 = Buffer.from('this is a tést');
|
||||
* const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
|
||||
*
|
||||
* console.log(buf1.toString());
|
||||
* // Prints: this is a tést
|
||||
* console.log(buf2.toString());
|
||||
* // Prints: this is a tést
|
||||
* console.log(buf1.toString('latin1'));
|
||||
* // Prints: this is a tést
|
||||
* ```
|
||||
*
|
||||
* A `TypeError` will be thrown if `string` is not a string or another type
|
||||
* appropriate for `Buffer.from()` variants.
|
||||
*
|
||||
* `Buffer.from(string)` may also use the internal `Buffer` pool like
|
||||
* `Buffer.allocUnsafe()` does.
|
||||
* @since v5.10.0
|
||||
* @param string A string to encode.
|
||||
* @param encoding The encoding of `string`. **Default:** `'utf8'`.
|
||||
*/
|
||||
from(string: WithImplicitCoercion<string>, encoding?: BufferEncoding): Buffer<ArrayBuffer>;
|
||||
from(arrayOrString: WithImplicitCoercion<ArrayLike<number> | string>): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Creates a new Buffer using the passed {data}
|
||||
* @param values to create a new Buffer
|
||||
*/
|
||||
of(...items: number[]): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together.
|
||||
*
|
||||
* If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned.
|
||||
*
|
||||
* If `totalLength` is not provided, it is calculated from the `Buffer` instances
|
||||
* in `list` by adding their lengths.
|
||||
*
|
||||
* If `totalLength` is provided, it is coerced to an unsigned integer. If the
|
||||
* combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is
|
||||
* truncated to `totalLength`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* // Create a single `Buffer` from a list of three `Buffer` instances.
|
||||
*
|
||||
* const buf1 = Buffer.alloc(10);
|
||||
* const buf2 = Buffer.alloc(14);
|
||||
* const buf3 = Buffer.alloc(18);
|
||||
* const totalLength = buf1.length + buf2.length + buf3.length;
|
||||
*
|
||||
* console.log(totalLength);
|
||||
* // Prints: 42
|
||||
*
|
||||
* const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
|
||||
*
|
||||
* console.log(bufA);
|
||||
* // Prints: <Buffer 00 00 00 00 ...>
|
||||
* console.log(bufA.length);
|
||||
* // Prints: 42
|
||||
* ```
|
||||
*
|
||||
* `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does.
|
||||
* @since v0.7.11
|
||||
* @param list List of `Buffer` or {@link Uint8Array} instances to concatenate.
|
||||
* @param totalLength Total length of the `Buffer` instances in `list` when concatenated.
|
||||
*/
|
||||
concat(list: readonly Uint8Array[], totalLength?: number): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Copies the underlying memory of `view` into a new `Buffer`.
|
||||
*
|
||||
* ```js
|
||||
* const u16 = new Uint16Array([0, 0xffff]);
|
||||
* const buf = Buffer.copyBytesFrom(u16, 1, 1);
|
||||
* u16[1] = 0;
|
||||
* console.log(buf.length); // 2
|
||||
* console.log(buf[0]); // 255
|
||||
* console.log(buf[1]); // 255
|
||||
* ```
|
||||
* @since v19.8.0
|
||||
* @param view The {TypedArray} to copy.
|
||||
* @param [offset=0] The starting offset within `view`.
|
||||
* @param [length=view.length - offset] The number of elements from `view` to copy.
|
||||
*/
|
||||
copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.alloc(5);
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 00 00 00 00 00>
|
||||
* ```
|
||||
*
|
||||
* If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown.
|
||||
*
|
||||
* If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.alloc(5, 'a');
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 61 61 61 61 61>
|
||||
* ```
|
||||
*
|
||||
* If both `fill` and `encoding` are specified, the allocated `Buffer` will be
|
||||
* initialized by calling `buf.fill(fill, encoding)`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
|
||||
* ```
|
||||
*
|
||||
* Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance
|
||||
* contents will never contain sensitive data from previous allocations, including
|
||||
* data that might not have been allocated for `Buffer`s.
|
||||
*
|
||||
* A `TypeError` will be thrown if `size` is not a number.
|
||||
* @since v5.10.0
|
||||
* @param size The desired length of the new `Buffer`.
|
||||
* @param [fill=0] A value to pre-fill the new `Buffer` with.
|
||||
* @param [encoding='utf8'] If `fill` is a string, this is its encoding.
|
||||
*/
|
||||
alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown.
|
||||
*
|
||||
* The underlying memory for `Buffer` instances created in this way is _not_
|
||||
* _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.allocUnsafe(10);
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints (contents may vary): <Buffer a0 8b 28 3f 01 00 00 00 50 32>
|
||||
*
|
||||
* buf.fill(0);
|
||||
*
|
||||
* console.log(buf);
|
||||
* // Prints: <Buffer 00 00 00 00 00 00 00 00 00 00>
|
||||
* ```
|
||||
*
|
||||
* A `TypeError` will be thrown if `size` is not a number.
|
||||
*
|
||||
* The `Buffer` module pre-allocates an internal `Buffer` instance of
|
||||
* size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`,
|
||||
* and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two).
|
||||
*
|
||||
* Use of this pre-allocated internal memory pool is a key difference between
|
||||
* calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
|
||||
* Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less
|
||||
* than or equal to half `Buffer.poolSize`. The
|
||||
* difference is subtle but can be important when an application requires the
|
||||
* additional performance that `Buffer.allocUnsafe()` provides.
|
||||
* @since v5.10.0
|
||||
* @param size The desired length of the new `Buffer`.
|
||||
*/
|
||||
allocUnsafe(size: number): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if
|
||||
* `size` is 0.
|
||||
*
|
||||
* The underlying memory for `Buffer` instances created in this way is _not_
|
||||
* _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize
|
||||
* such `Buffer` instances with zeroes.
|
||||
*
|
||||
* When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances,
|
||||
* allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This
|
||||
* allows applications to avoid the garbage collection overhead of creating many
|
||||
* individually allocated `Buffer` instances. This approach improves both
|
||||
* performance and memory usage by eliminating the need to track and clean up as
|
||||
* many individual `ArrayBuffer` objects.
|
||||
*
|
||||
* However, in the case where a developer may need to retain a small chunk of
|
||||
* memory from a pool for an indeterminate amount of time, it may be appropriate
|
||||
* to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and
|
||||
* then copying out the relevant bits.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* // Need to keep around a few small chunks of memory.
|
||||
* const store = [];
|
||||
*
|
||||
* socket.on('readable', () => {
|
||||
* let data;
|
||||
* while (null !== (data = readable.read())) {
|
||||
* // Allocate for retained data.
|
||||
* const sb = Buffer.allocUnsafeSlow(10);
|
||||
*
|
||||
* // Copy the data into the new allocation.
|
||||
* data.copy(sb, 0, 0, 10);
|
||||
*
|
||||
* store.push(sb);
|
||||
* }
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* A `TypeError` will be thrown if `size` is not a number.
|
||||
* @since v5.12.0
|
||||
* @param size The desired length of the new `Buffer`.
|
||||
*/
|
||||
allocUnsafeSlow(size: number): Buffer<ArrayBuffer>;
|
||||
}
|
||||
interface Buffer<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> extends Uint8Array<TArrayBuffer> {
|
||||
// see buffer.d.ts for implementation shared with all TypeScript versions
|
||||
|
||||
/**
|
||||
* Returns a new `Buffer` that references the same memory as the original, but
|
||||
* offset and cropped by the `start` and `end` indices.
|
||||
*
|
||||
* This method is not compatible with the `Uint8Array.prototype.slice()`,
|
||||
* which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.from('buffer');
|
||||
*
|
||||
* const copiedBuf = Uint8Array.prototype.slice.call(buf);
|
||||
* copiedBuf[0]++;
|
||||
* console.log(copiedBuf.toString());
|
||||
* // Prints: cuffer
|
||||
*
|
||||
* console.log(buf.toString());
|
||||
* // Prints: buffer
|
||||
*
|
||||
* // With buf.slice(), the original buffer is modified.
|
||||
* const notReallyCopiedBuf = buf.slice();
|
||||
* notReallyCopiedBuf[0]++;
|
||||
* console.log(notReallyCopiedBuf.toString());
|
||||
* // Prints: cuffer
|
||||
* console.log(buf.toString());
|
||||
* // Also prints: cuffer (!)
|
||||
* ```
|
||||
* @since v0.3.0
|
||||
* @deprecated Use `subarray` instead.
|
||||
* @param [start=0] Where the new `Buffer` will start.
|
||||
* @param [end=buf.length] Where the new `Buffer` will end (not inclusive).
|
||||
*/
|
||||
slice(start?: number, end?: number): Buffer<ArrayBuffer>;
|
||||
/**
|
||||
* Returns a new `Buffer` that references the same memory as the original, but
|
||||
* offset and cropped by the `start` and `end` indices.
|
||||
*
|
||||
* Specifying `end` greater than `buf.length` will return the same result as
|
||||
* that of `end` equal to `buf.length`.
|
||||
*
|
||||
* This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray).
|
||||
*
|
||||
* Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte
|
||||
* // from the original `Buffer`.
|
||||
*
|
||||
* const buf1 = Buffer.allocUnsafe(26);
|
||||
*
|
||||
* for (let i = 0; i < 26; i++) {
|
||||
* // 97 is the decimal ASCII value for 'a'.
|
||||
* buf1[i] = i + 97;
|
||||
* }
|
||||
*
|
||||
* const buf2 = buf1.subarray(0, 3);
|
||||
*
|
||||
* console.log(buf2.toString('ascii', 0, buf2.length));
|
||||
* // Prints: abc
|
||||
*
|
||||
* buf1[0] = 33;
|
||||
*
|
||||
* console.log(buf2.toString('ascii', 0, buf2.length));
|
||||
* // Prints: !bc
|
||||
* ```
|
||||
*
|
||||
* Specifying negative indexes causes the slice to be generated relative to the
|
||||
* end of `buf` rather than the beginning.
|
||||
*
|
||||
* ```js
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf = Buffer.from('buffer');
|
||||
*
|
||||
* console.log(buf.subarray(-6, -1).toString());
|
||||
* // Prints: buffe
|
||||
* // (Equivalent to buf.subarray(0, 5).)
|
||||
*
|
||||
* console.log(buf.subarray(-6, -2).toString());
|
||||
* // Prints: buff
|
||||
* // (Equivalent to buf.subarray(0, 4).)
|
||||
*
|
||||
* console.log(buf.subarray(-5, -2).toString());
|
||||
* // Prints: uff
|
||||
* // (Equivalent to buf.subarray(1, 4).)
|
||||
* ```
|
||||
* @since v3.0.0
|
||||
* @param [start=0] Where the new `Buffer` will start.
|
||||
* @param [end=buf.length] Where the new `Buffer` will end (not inclusive).
|
||||
*/
|
||||
subarray(start?: number, end?: number): Buffer<TArrayBuffer>;
|
||||
}
|
||||
type NonSharedBuffer = Buffer<ArrayBuffer>;
|
||||
type AllowSharedBuffer = Buffer<ArrayBufferLike>;
|
||||
}
|
||||
/** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */
|
||||
var SlowBuffer: {
|
||||
/** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */
|
||||
new(size: number): Buffer<ArrayBuffer>;
|
||||
prototype: Buffer;
|
||||
};
|
||||
}
|
||||
1932
frontend/e2e/node_modules/@types/node/buffer.d.ts
generated
vendored
Normal file
1932
frontend/e2e/node_modules/@types/node/buffer.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1452
frontend/e2e/node_modules/@types/node/child_process.d.ts
generated
vendored
Normal file
1452
frontend/e2e/node_modules/@types/node/child_process.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
578
frontend/e2e/node_modules/@types/node/cluster.d.ts
generated
vendored
Normal file
578
frontend/e2e/node_modules/@types/node/cluster.d.ts
generated
vendored
Normal file
@@ -0,0 +1,578 @@
|
||||
/**
|
||||
* Clusters of Node.js processes can be used to run multiple instances of Node.js
|
||||
* that can distribute workloads among their application threads. When process isolation
|
||||
* is not needed, use the [`worker_threads`](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html)
|
||||
* module instead, which allows running multiple application threads within a single Node.js instance.
|
||||
*
|
||||
* The cluster module allows easy creation of child processes that all share
|
||||
* server ports.
|
||||
*
|
||||
* ```js
|
||||
* import cluster from 'node:cluster';
|
||||
* import http from 'node:http';
|
||||
* import { availableParallelism } from 'node:os';
|
||||
* import process from 'node:process';
|
||||
*
|
||||
* const numCPUs = availableParallelism();
|
||||
*
|
||||
* if (cluster.isPrimary) {
|
||||
* console.log(`Primary ${process.pid} is running`);
|
||||
*
|
||||
* // Fork workers.
|
||||
* for (let i = 0; i < numCPUs; i++) {
|
||||
* cluster.fork();
|
||||
* }
|
||||
*
|
||||
* cluster.on('exit', (worker, code, signal) => {
|
||||
* console.log(`worker ${worker.process.pid} died`);
|
||||
* });
|
||||
* } else {
|
||||
* // Workers can share any TCP connection
|
||||
* // In this case it is an HTTP server
|
||||
* http.createServer((req, res) => {
|
||||
* res.writeHead(200);
|
||||
* res.end('hello world\n');
|
||||
* }).listen(8000);
|
||||
*
|
||||
* console.log(`Worker ${process.pid} started`);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* Running Node.js will now share port 8000 between the workers:
|
||||
*
|
||||
* ```console
|
||||
* $ node server.js
|
||||
* Primary 3596 is running
|
||||
* Worker 4324 started
|
||||
* Worker 4520 started
|
||||
* Worker 6056 started
|
||||
* Worker 5644 started
|
||||
* ```
|
||||
*
|
||||
* On Windows, it is not yet possible to set up a named pipe server in a worker.
|
||||
* @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/cluster.js)
|
||||
*/
|
||||
declare module "cluster" {
|
||||
import * as child from "node:child_process";
|
||||
import EventEmitter = require("node:events");
|
||||
import * as net from "node:net";
|
||||
type SerializationType = "json" | "advanced";
|
||||
export interface ClusterSettings {
|
||||
/**
|
||||
* List of string arguments passed to the Node.js executable.
|
||||
* @default process.execArgv
|
||||
*/
|
||||
execArgv?: string[] | undefined;
|
||||
/**
|
||||
* File path to worker file.
|
||||
* @default process.argv[1]
|
||||
*/
|
||||
exec?: string | undefined;
|
||||
/**
|
||||
* String arguments passed to worker.
|
||||
* @default process.argv.slice(2)
|
||||
*/
|
||||
args?: string[] | undefined;
|
||||
/**
|
||||
* Whether or not to send output to parent's stdio.
|
||||
* @default false
|
||||
*/
|
||||
silent?: boolean | undefined;
|
||||
/**
|
||||
* Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must
|
||||
* contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-v20.x/api/child_process.html#child_processspawncommand-args-options)'s
|
||||
* [`stdio`](https://nodejs.org/docs/latest-v20.x/api/child_process.html#optionsstdio).
|
||||
*/
|
||||
stdio?: any[] | undefined;
|
||||
/**
|
||||
* Sets the user identity of the process. (See [`setuid(2)`](https://man7.org/linux/man-pages/man2/setuid.2.html).)
|
||||
*/
|
||||
uid?: number | undefined;
|
||||
/**
|
||||
* Sets the group identity of the process. (See [`setgid(2)`](https://man7.org/linux/man-pages/man2/setgid.2.html).)
|
||||
*/
|
||||
gid?: number | undefined;
|
||||
/**
|
||||
* Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number.
|
||||
* By default each worker gets its own port, incremented from the primary's `process.debugPort`.
|
||||
*/
|
||||
inspectPort?: number | (() => number) | undefined;
|
||||
/**
|
||||
* Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`.
|
||||
* See [Advanced serialization for `child_process`](https://nodejs.org/docs/latest-v20.x/api/child_process.html#advanced-serialization) for more details.
|
||||
* @default false
|
||||
*/
|
||||
serialization?: SerializationType | undefined;
|
||||
/**
|
||||
* Current working directory of the worker process.
|
||||
* @default undefined (inherits from parent process)
|
||||
*/
|
||||
cwd?: string | undefined;
|
||||
/**
|
||||
* Hide the forked processes console window that would normally be created on Windows systems.
|
||||
* @default false
|
||||
*/
|
||||
windowsHide?: boolean | undefined;
|
||||
}
|
||||
export interface Address {
|
||||
address: string;
|
||||
port: number;
|
||||
/**
|
||||
* The `addressType` is one of:
|
||||
*
|
||||
* * `4` (TCPv4)
|
||||
* * `6` (TCPv6)
|
||||
* * `-1` (Unix domain socket)
|
||||
* * `'udp4'` or `'udp6'` (UDPv4 or UDPv6)
|
||||
*/
|
||||
addressType: 4 | 6 | -1 | "udp4" | "udp6";
|
||||
}
|
||||
/**
|
||||
* A `Worker` object contains all public information and method about a worker.
|
||||
* In the primary it can be obtained using `cluster.workers`. In a worker
|
||||
* it can be obtained using `cluster.worker`.
|
||||
* @since v0.7.0
|
||||
*/
|
||||
export class Worker extends EventEmitter {
|
||||
/**
|
||||
* Each new worker is given its own unique id, this id is stored in the `id`.
|
||||
*
|
||||
* While a worker is alive, this is the key that indexes it in `cluster.workers`.
|
||||
* @since v0.8.0
|
||||
*/
|
||||
id: number;
|
||||
/**
|
||||
* All workers are created using [`child_process.fork()`](https://nodejs.org/docs/latest-v20.x/api/child_process.html#child_processforkmodulepath-args-options), the returned object
|
||||
* from this function is stored as `.process`. In a worker, the global `process` is stored.
|
||||
*
|
||||
* See: [Child Process module](https://nodejs.org/docs/latest-v20.x/api/child_process.html#child_processforkmodulepath-args-options).
|
||||
*
|
||||
* Workers will call `process.exit(0)` if the `'disconnect'` event occurs
|
||||
* on `process` and `.exitedAfterDisconnect` is not `true`. This protects against
|
||||
* accidental disconnection.
|
||||
* @since v0.7.0
|
||||
*/
|
||||
process: child.ChildProcess;
|
||||
/**
|
||||
* Send a message to a worker or primary, optionally with a handle.
|
||||
*
|
||||
* In the primary, this sends a message to a specific worker. It is identical to [`ChildProcess.send()`](https://nodejs.org/docs/latest-v20.x/api/child_process.html#subprocesssendmessage-sendhandle-options-callback).
|
||||
*
|
||||
* In a worker, this sends a message to the primary. It is identical to `process.send()`.
|
||||
*
|
||||
* This example will echo back all messages from the primary:
|
||||
*
|
||||
* ```js
|
||||
* if (cluster.isPrimary) {
|
||||
* const worker = cluster.fork();
|
||||
* worker.send('hi there');
|
||||
*
|
||||
* } else if (cluster.isWorker) {
|
||||
* process.on('message', (msg) => {
|
||||
* process.send(msg);
|
||||
* });
|
||||
* }
|
||||
* ```
|
||||
* @since v0.7.0
|
||||
* @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles.
|
||||
*/
|
||||
send(message: child.Serializable, callback?: (error: Error | null) => void): boolean;
|
||||
send(
|
||||
message: child.Serializable,
|
||||
sendHandle: child.SendHandle,
|
||||
callback?: (error: Error | null) => void,
|
||||
): boolean;
|
||||
send(
|
||||
message: child.Serializable,
|
||||
sendHandle: child.SendHandle,
|
||||
options?: child.MessageOptions,
|
||||
callback?: (error: Error | null) => void,
|
||||
): boolean;
|
||||
/**
|
||||
* This function will kill the worker. In the primary worker, it does this by
|
||||
* disconnecting the `worker.process`, and once disconnected, killing with `signal`. In the worker, it does it by killing the process with `signal`.
|
||||
*
|
||||
* The `kill()` function kills the worker process without waiting for a graceful
|
||||
* disconnect, it has the same behavior as `worker.process.kill()`.
|
||||
*
|
||||
* This method is aliased as `worker.destroy()` for backwards compatibility.
|
||||
*
|
||||
* In a worker, `process.kill()` exists, but it is not this function;
|
||||
* it is [`kill()`](https://nodejs.org/docs/latest-v20.x/api/process.html#processkillpid-signal).
|
||||
* @since v0.9.12
|
||||
* @param [signal='SIGTERM'] Name of the kill signal to send to the worker process.
|
||||
*/
|
||||
kill(signal?: string): void;
|
||||
destroy(signal?: string): void;
|
||||
/**
|
||||
* In a worker, this function will close all servers, wait for the `'close'` event
|
||||
* on those servers, and then disconnect the IPC channel.
|
||||
*
|
||||
* In the primary, an internal message is sent to the worker causing it to call `.disconnect()` on itself.
|
||||
*
|
||||
* Causes `.exitedAfterDisconnect` to be set.
|
||||
*
|
||||
* After a server is closed, it will no longer accept new connections,
|
||||
* but connections may be accepted by any other listening worker. Existing
|
||||
* connections will be allowed to close as usual. When no more connections exist,
|
||||
* see `server.close()`, the IPC channel to the worker will close allowing it
|
||||
* to die gracefully.
|
||||
*
|
||||
* The above applies _only_ to server connections, client connections are not
|
||||
* automatically closed by workers, and disconnect does not wait for them to close
|
||||
* before exiting.
|
||||
*
|
||||
* In a worker, `process.disconnect` exists, but it is not this function;
|
||||
* it is `disconnect()`.
|
||||
*
|
||||
* Because long living server connections may block workers from disconnecting, it
|
||||
* may be useful to send a message, so application specific actions may be taken to
|
||||
* close them. It also may be useful to implement a timeout, killing a worker if
|
||||
* the `'disconnect'` event has not been emitted after some time.
|
||||
*
|
||||
* ```js
|
||||
* import net from 'node:net';
|
||||
* if (cluster.isPrimary) {
|
||||
* const worker = cluster.fork();
|
||||
* let timeout;
|
||||
*
|
||||
* worker.on('listening', (address) => {
|
||||
* worker.send('shutdown');
|
||||
* worker.disconnect();
|
||||
* timeout = setTimeout(() => {
|
||||
* worker.kill();
|
||||
* }, 2000);
|
||||
* });
|
||||
*
|
||||
* worker.on('disconnect', () => {
|
||||
* clearTimeout(timeout);
|
||||
* });
|
||||
*
|
||||
* } else if (cluster.isWorker) {
|
||||
* const server = net.createServer((socket) => {
|
||||
* // Connections never end
|
||||
* });
|
||||
*
|
||||
* server.listen(8000);
|
||||
*
|
||||
* process.on('message', (msg) => {
|
||||
* if (msg === 'shutdown') {
|
||||
* // Initiate graceful close of any connections to server
|
||||
* }
|
||||
* });
|
||||
* }
|
||||
* ```
|
||||
* @since v0.7.7
|
||||
* @return A reference to `worker`.
|
||||
*/
|
||||
disconnect(): this;
|
||||
/**
|
||||
* This function returns `true` if the worker is connected to its primary via its
|
||||
* IPC channel, `false` otherwise. A worker is connected to its primary after it
|
||||
* has been created. It is disconnected after the `'disconnect'` event is emitted.
|
||||
* @since v0.11.14
|
||||
*/
|
||||
isConnected(): boolean;
|
||||
/**
|
||||
* This function returns `true` if the worker's process has terminated (either
|
||||
* because of exiting or being signaled). Otherwise, it returns `false`.
|
||||
*
|
||||
* ```js
|
||||
* import cluster from 'node:cluster';
|
||||
* import http from 'node:http';
|
||||
* import { availableParallelism } from 'node:os';
|
||||
* import process from 'node:process';
|
||||
*
|
||||
* const numCPUs = availableParallelism();
|
||||
*
|
||||
* if (cluster.isPrimary) {
|
||||
* console.log(`Primary ${process.pid} is running`);
|
||||
*
|
||||
* // Fork workers.
|
||||
* for (let i = 0; i < numCPUs; i++) {
|
||||
* cluster.fork();
|
||||
* }
|
||||
*
|
||||
* cluster.on('fork', (worker) => {
|
||||
* console.log('worker is dead:', worker.isDead());
|
||||
* });
|
||||
*
|
||||
* cluster.on('exit', (worker, code, signal) => {
|
||||
* console.log('worker is dead:', worker.isDead());
|
||||
* });
|
||||
* } else {
|
||||
* // Workers can share any TCP connection. In this case, it is an HTTP server.
|
||||
* http.createServer((req, res) => {
|
||||
* res.writeHead(200);
|
||||
* res.end(`Current process\n ${process.pid}`);
|
||||
* process.kill(process.pid);
|
||||
* }).listen(8000);
|
||||
* }
|
||||
* ```
|
||||
* @since v0.11.14
|
||||
*/
|
||||
isDead(): boolean;
|
||||
/**
|
||||
* This property is `true` if the worker exited due to `.disconnect()`.
|
||||
* If the worker exited any other way, it is `false`. If the
|
||||
* worker has not exited, it is `undefined`.
|
||||
*
|
||||
* The boolean `worker.exitedAfterDisconnect` allows distinguishing between
|
||||
* voluntary and accidental exit, the primary may choose not to respawn a worker
|
||||
* based on this value.
|
||||
*
|
||||
* ```js
|
||||
* cluster.on('exit', (worker, code, signal) => {
|
||||
* if (worker.exitedAfterDisconnect === true) {
|
||||
* console.log('Oh, it was just voluntary – no need to worry');
|
||||
* }
|
||||
* });
|
||||
*
|
||||
* // kill worker
|
||||
* worker.kill();
|
||||
* ```
|
||||
* @since v6.0.0
|
||||
*/
|
||||
exitedAfterDisconnect: boolean;
|
||||
/**
|
||||
* events.EventEmitter
|
||||
* 1. disconnect
|
||||
* 2. error
|
||||
* 3. exit
|
||||
* 4. listening
|
||||
* 5. message
|
||||
* 6. online
|
||||
*/
|
||||
addListener(event: string, listener: (...args: any[]) => void): this;
|
||||
addListener(event: "disconnect", listener: () => void): this;
|
||||
addListener(event: "error", listener: (error: Error) => void): this;
|
||||
addListener(event: "exit", listener: (code: number, signal: string) => void): this;
|
||||
addListener(event: "listening", listener: (address: Address) => void): this;
|
||||
addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||
addListener(event: "online", listener: () => void): this;
|
||||
emit(event: string | symbol, ...args: any[]): boolean;
|
||||
emit(event: "disconnect"): boolean;
|
||||
emit(event: "error", error: Error): boolean;
|
||||
emit(event: "exit", code: number, signal: string): boolean;
|
||||
emit(event: "listening", address: Address): boolean;
|
||||
emit(event: "message", message: any, handle: net.Socket | net.Server): boolean;
|
||||
emit(event: "online"): boolean;
|
||||
on(event: string, listener: (...args: any[]) => void): this;
|
||||
on(event: "disconnect", listener: () => void): this;
|
||||
on(event: "error", listener: (error: Error) => void): this;
|
||||
on(event: "exit", listener: (code: number, signal: string) => void): this;
|
||||
on(event: "listening", listener: (address: Address) => void): this;
|
||||
on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||
on(event: "online", listener: () => void): this;
|
||||
once(event: string, listener: (...args: any[]) => void): this;
|
||||
once(event: "disconnect", listener: () => void): this;
|
||||
once(event: "error", listener: (error: Error) => void): this;
|
||||
once(event: "exit", listener: (code: number, signal: string) => void): this;
|
||||
once(event: "listening", listener: (address: Address) => void): this;
|
||||
once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||
once(event: "online", listener: () => void): this;
|
||||
prependListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependListener(event: "disconnect", listener: () => void): this;
|
||||
prependListener(event: "error", listener: (error: Error) => void): this;
|
||||
prependListener(event: "exit", listener: (code: number, signal: string) => void): this;
|
||||
prependListener(event: "listening", listener: (address: Address) => void): this;
|
||||
prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||
prependListener(event: "online", listener: () => void): this;
|
||||
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependOnceListener(event: "disconnect", listener: () => void): this;
|
||||
prependOnceListener(event: "error", listener: (error: Error) => void): this;
|
||||
prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this;
|
||||
prependOnceListener(event: "listening", listener: (address: Address) => void): this;
|
||||
prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||
prependOnceListener(event: "online", listener: () => void): this;
|
||||
}
|
||||
export interface Cluster extends EventEmitter {
|
||||
disconnect(callback?: () => void): void;
|
||||
/**
|
||||
* Spawn a new worker process.
|
||||
*
|
||||
* This can only be called from the primary process.
|
||||
* @param env Key/value pairs to add to worker process environment.
|
||||
* @since v0.6.0
|
||||
*/
|
||||
fork(env?: any): Worker;
|
||||
/** @deprecated since v16.0.0 - use isPrimary. */
|
||||
readonly isMaster: boolean;
|
||||
/**
|
||||
* True if the process is a primary. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID`
|
||||
* is undefined, then `isPrimary` is `true`.
|
||||
* @since v16.0.0
|
||||
*/
|
||||
readonly isPrimary: boolean;
|
||||
/**
|
||||
* True if the process is not a primary (it is the negation of `cluster.isPrimary`).
|
||||
* @since v0.6.0
|
||||
*/
|
||||
readonly isWorker: boolean;
|
||||
/**
|
||||
* The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a
|
||||
* global setting and effectively frozen once either the first worker is spawned, or [`.setupPrimary()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clustersetupprimarysettings)
|
||||
* is called, whichever comes first.
|
||||
*
|
||||
* `SCHED_RR` is the default on all operating systems except Windows. Windows will change to `SCHED_RR` once libuv is able to effectively distribute
|
||||
* IOCP handles without incurring a large performance hit.
|
||||
*
|
||||
* `cluster.schedulingPolicy` can also be set through the `NODE_CLUSTER_SCHED_POLICY` environment variable. Valid values are `'rr'` and `'none'`.
|
||||
* @since v0.11.2
|
||||
*/
|
||||
schedulingPolicy: number;
|
||||
/**
|
||||
* After calling [`.setupPrimary()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clustersetupprimarysettings)
|
||||
* (or [`.fork()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clusterforkenv)) this settings object will contain
|
||||
* the settings, including the default values.
|
||||
*
|
||||
* This object is not intended to be changed or set manually.
|
||||
* @since v0.7.1
|
||||
*/
|
||||
readonly settings: ClusterSettings;
|
||||
/** @deprecated since v16.0.0 - use [`.setupPrimary()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clustersetupprimarysettings) instead. */
|
||||
setupMaster(settings?: ClusterSettings): void;
|
||||
/**
|
||||
* `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`.
|
||||
*
|
||||
* Any settings changes only affect future calls to [`.fork()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clusterforkenv)
|
||||
* and have no effect on workers that are already running.
|
||||
*
|
||||
* The only attribute of a worker that cannot be set via `.setupPrimary()` is the `env` passed to
|
||||
* [`.fork()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clusterforkenv).
|
||||
*
|
||||
* The defaults above apply to the first call only; the defaults for later calls are the current values at the time of
|
||||
* `cluster.setupPrimary()` is called.
|
||||
*
|
||||
* ```js
|
||||
* import cluster from 'node:cluster';
|
||||
*
|
||||
* cluster.setupPrimary({
|
||||
* exec: 'worker.js',
|
||||
* args: ['--use', 'https'],
|
||||
* silent: true,
|
||||
* });
|
||||
* cluster.fork(); // https worker
|
||||
* cluster.setupPrimary({
|
||||
* exec: 'worker.js',
|
||||
* args: ['--use', 'http'],
|
||||
* });
|
||||
* cluster.fork(); // http worker
|
||||
* ```
|
||||
*
|
||||
* This can only be called from the primary process.
|
||||
* @since v16.0.0
|
||||
*/
|
||||
setupPrimary(settings?: ClusterSettings): void;
|
||||
/**
|
||||
* A reference to the current worker object. Not available in the primary process.
|
||||
*
|
||||
* ```js
|
||||
* import cluster from 'node:cluster';
|
||||
*
|
||||
* if (cluster.isPrimary) {
|
||||
* console.log('I am primary');
|
||||
* cluster.fork();
|
||||
* cluster.fork();
|
||||
* } else if (cluster.isWorker) {
|
||||
* console.log(`I am worker #${cluster.worker.id}`);
|
||||
* }
|
||||
* ```
|
||||
* @since v0.7.0
|
||||
*/
|
||||
readonly worker?: Worker | undefined;
|
||||
/**
|
||||
* A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process.
|
||||
*
|
||||
* A worker is removed from `cluster.workers` after the worker has disconnected _and_ exited. The order between these two events cannot be determined in advance. However, it
|
||||
* is guaranteed that the removal from the `cluster.workers` list happens before the last `'disconnect'` or `'exit'` event is emitted.
|
||||
*
|
||||
* ```js
|
||||
* import cluster from 'node:cluster';
|
||||
*
|
||||
* for (const worker of Object.values(cluster.workers)) {
|
||||
* worker.send('big announcement to all workers');
|
||||
* }
|
||||
* ```
|
||||
* @since v0.7.0
|
||||
*/
|
||||
readonly workers?: NodeJS.Dict<Worker> | undefined;
|
||||
readonly SCHED_NONE: number;
|
||||
readonly SCHED_RR: number;
|
||||
/**
|
||||
* events.EventEmitter
|
||||
* 1. disconnect
|
||||
* 2. exit
|
||||
* 3. fork
|
||||
* 4. listening
|
||||
* 5. message
|
||||
* 6. online
|
||||
* 7. setup
|
||||
*/
|
||||
addListener(event: string, listener: (...args: any[]) => void): this;
|
||||
addListener(event: "disconnect", listener: (worker: Worker) => void): this;
|
||||
addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
|
||||
addListener(event: "fork", listener: (worker: Worker) => void): this;
|
||||
addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
|
||||
addListener(
|
||||
event: "message",
|
||||
listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void,
|
||||
): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||
addListener(event: "online", listener: (worker: Worker) => void): this;
|
||||
addListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
|
||||
emit(event: string | symbol, ...args: any[]): boolean;
|
||||
emit(event: "disconnect", worker: Worker): boolean;
|
||||
emit(event: "exit", worker: Worker, code: number, signal: string): boolean;
|
||||
emit(event: "fork", worker: Worker): boolean;
|
||||
emit(event: "listening", worker: Worker, address: Address): boolean;
|
||||
emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean;
|
||||
emit(event: "online", worker: Worker): boolean;
|
||||
emit(event: "setup", settings: ClusterSettings): boolean;
|
||||
on(event: string, listener: (...args: any[]) => void): this;
|
||||
on(event: "disconnect", listener: (worker: Worker) => void): this;
|
||||
on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
|
||||
on(event: "fork", listener: (worker: Worker) => void): this;
|
||||
on(event: "listening", listener: (worker: Worker, address: Address) => void): this;
|
||||
on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||
on(event: "online", listener: (worker: Worker) => void): this;
|
||||
on(event: "setup", listener: (settings: ClusterSettings) => void): this;
|
||||
once(event: string, listener: (...args: any[]) => void): this;
|
||||
once(event: "disconnect", listener: (worker: Worker) => void): this;
|
||||
once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
|
||||
once(event: "fork", listener: (worker: Worker) => void): this;
|
||||
once(event: "listening", listener: (worker: Worker, address: Address) => void): this;
|
||||
once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined.
|
||||
once(event: "online", listener: (worker: Worker) => void): this;
|
||||
once(event: "setup", listener: (settings: ClusterSettings) => void): this;
|
||||
prependListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependListener(event: "disconnect", listener: (worker: Worker) => void): this;
|
||||
prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
|
||||
prependListener(event: "fork", listener: (worker: Worker) => void): this;
|
||||
prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
|
||||
// the handle is a net.Socket or net.Server object, or undefined.
|
||||
prependListener(
|
||||
event: "message",
|
||||
listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void,
|
||||
): this;
|
||||
prependListener(event: "online", listener: (worker: Worker) => void): this;
|
||||
prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
|
||||
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this;
|
||||
prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
|
||||
prependOnceListener(event: "fork", listener: (worker: Worker) => void): this;
|
||||
prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
|
||||
// the handle is a net.Socket or net.Server object, or undefined.
|
||||
prependOnceListener(
|
||||
event: "message",
|
||||
listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void,
|
||||
): this;
|
||||
prependOnceListener(event: "online", listener: (worker: Worker) => void): this;
|
||||
prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this;
|
||||
}
|
||||
const cluster: Cluster;
|
||||
export default cluster;
|
||||
}
|
||||
declare module "node:cluster" {
|
||||
export * from "cluster";
|
||||
export { default as default } from "cluster";
|
||||
}
|
||||
16
frontend/e2e/node_modules/@types/node/compatibility/disposable.d.ts
generated
vendored
Normal file
16
frontend/e2e/node_modules/@types/node/compatibility/disposable.d.ts
generated
vendored
Normal file
@@ -0,0 +1,16 @@
|
||||
// Polyfills for the explicit resource management types added in TypeScript 5.2.
|
||||
// TODO: remove once this package no longer supports TS 5.1, and replace with a
|
||||
// <reference> to TypeScript's disposable library in index.d.ts.
|
||||
|
||||
interface SymbolConstructor {
|
||||
readonly dispose: unique symbol;
|
||||
readonly asyncDispose: unique symbol;
|
||||
}
|
||||
|
||||
interface Disposable {
|
||||
[Symbol.dispose](): void;
|
||||
}
|
||||
|
||||
interface AsyncDisposable {
|
||||
[Symbol.asyncDispose](): PromiseLike<void>;
|
||||
}
|
||||
9
frontend/e2e/node_modules/@types/node/compatibility/index.d.ts
generated
vendored
Normal file
9
frontend/e2e/node_modules/@types/node/compatibility/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,9 @@
|
||||
// Declaration files in this directory contain types relating to TypeScript library features
|
||||
// that are not included in all TypeScript versions supported by DefinitelyTyped, but
|
||||
// which can be made backwards-compatible without needing `typesVersions`.
|
||||
// If adding declarations to this directory, please specify which versions of TypeScript require them,
|
||||
// so that they can be removed when no longer needed.
|
||||
|
||||
/// <reference path="disposable.d.ts" />
|
||||
/// <reference path="indexable.d.ts" />
|
||||
/// <reference path="iterators.d.ts" />
|
||||
20
frontend/e2e/node_modules/@types/node/compatibility/indexable.d.ts
generated
vendored
Normal file
20
frontend/e2e/node_modules/@types/node/compatibility/indexable.d.ts
generated
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
// Polyfill for ES2022's .at() method on string/array prototypes, added to TypeScript in 4.6.
|
||||
|
||||
interface RelativeIndexable<T> {
|
||||
at(index: number): T | undefined;
|
||||
}
|
||||
|
||||
interface String extends RelativeIndexable<string> {}
|
||||
interface Array<T> extends RelativeIndexable<T> {}
|
||||
interface ReadonlyArray<T> extends RelativeIndexable<T> {}
|
||||
interface Int8Array extends RelativeIndexable<number> {}
|
||||
interface Uint8Array extends RelativeIndexable<number> {}
|
||||
interface Uint8ClampedArray extends RelativeIndexable<number> {}
|
||||
interface Int16Array extends RelativeIndexable<number> {}
|
||||
interface Uint16Array extends RelativeIndexable<number> {}
|
||||
interface Int32Array extends RelativeIndexable<number> {}
|
||||
interface Uint32Array extends RelativeIndexable<number> {}
|
||||
interface Float32Array extends RelativeIndexable<number> {}
|
||||
interface Float64Array extends RelativeIndexable<number> {}
|
||||
interface BigInt64Array extends RelativeIndexable<bigint> {}
|
||||
interface BigUint64Array extends RelativeIndexable<bigint> {}
|
||||
21
frontend/e2e/node_modules/@types/node/compatibility/iterators.d.ts
generated
vendored
Normal file
21
frontend/e2e/node_modules/@types/node/compatibility/iterators.d.ts
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
// Backwards-compatible iterator interfaces, augmented with iterator helper methods by lib.esnext.iterator in TypeScript 5.6.
|
||||
// The IterableIterator interface does not contain these methods, which creates assignability issues in places where IteratorObjects
|
||||
// are expected (eg. DOM-compatible APIs) if lib.esnext.iterator is loaded.
|
||||
// Also ensures that iterators returned by the Node API, which inherit from Iterator.prototype, correctly expose the iterator helper methods
|
||||
// if lib.esnext.iterator is loaded.
|
||||
// TODO: remove once this package no longer supports TS 5.5, and replace NodeJS.BuiltinIteratorReturn with BuiltinIteratorReturn.
|
||||
|
||||
// Placeholders for TS <5.6
|
||||
interface IteratorObject<T, TReturn, TNext> {}
|
||||
interface AsyncIteratorObject<T, TReturn, TNext> {}
|
||||
|
||||
declare namespace NodeJS {
|
||||
// Populate iterator methods for TS <5.6
|
||||
interface Iterator<T, TReturn, TNext> extends globalThis.Iterator<T, TReturn, TNext> {}
|
||||
interface AsyncIterator<T, TReturn, TNext> extends globalThis.AsyncIterator<T, TReturn, TNext> {}
|
||||
|
||||
// Polyfill for TS 5.6's instrinsic BuiltinIteratorReturn type, required for DOM-compatible iterators
|
||||
type BuiltinIteratorReturn = ReturnType<any[][typeof Symbol.iterator]> extends
|
||||
globalThis.Iterator<any, infer TReturn> ? TReturn
|
||||
: any;
|
||||
}
|
||||
452
frontend/e2e/node_modules/@types/node/console.d.ts
generated
vendored
Normal file
452
frontend/e2e/node_modules/@types/node/console.d.ts
generated
vendored
Normal file
@@ -0,0 +1,452 @@
|
||||
/**
|
||||
* The `node:console` module provides a simple debugging console that is similar to
|
||||
* the JavaScript console mechanism provided by web browsers.
|
||||
*
|
||||
* The module exports two specific components:
|
||||
*
|
||||
* * A `Console` class with methods such as `console.log()`, `console.error()`, and `console.warn()` that can be used to write to any Node.js stream.
|
||||
* * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and
|
||||
* [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
|
||||
*
|
||||
* _**Warning**_: The global console object's methods are neither consistently
|
||||
* synchronous like the browser APIs they resemble, nor are they consistently
|
||||
* asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for
|
||||
* more information.
|
||||
*
|
||||
* Example using the global `console`:
|
||||
*
|
||||
* ```js
|
||||
* console.log('hello world');
|
||||
* // Prints: hello world, to stdout
|
||||
* console.log('hello %s', 'world');
|
||||
* // Prints: hello world, to stdout
|
||||
* console.error(new Error('Whoops, something bad happened'));
|
||||
* // Prints error message and stack trace to stderr:
|
||||
* // Error: Whoops, something bad happened
|
||||
* // at [eval]:5:15
|
||||
* // at Script.runInThisContext (node:vm:132:18)
|
||||
* // at Object.runInThisContext (node:vm:309:38)
|
||||
* // at node:internal/process/execution:77:19
|
||||
* // at [eval]-wrapper:6:22
|
||||
* // at evalScript (node:internal/process/execution:76:60)
|
||||
* // at node:internal/main/eval_string:23:3
|
||||
*
|
||||
* const name = 'Will Robinson';
|
||||
* console.warn(`Danger ${name}! Danger!`);
|
||||
* // Prints: Danger Will Robinson! Danger!, to stderr
|
||||
* ```
|
||||
*
|
||||
* Example using the `Console` class:
|
||||
*
|
||||
* ```js
|
||||
* const out = getStreamSomehow();
|
||||
* const err = getStreamSomehow();
|
||||
* const myConsole = new console.Console(out, err);
|
||||
*
|
||||
* myConsole.log('hello world');
|
||||
* // Prints: hello world, to out
|
||||
* myConsole.log('hello %s', 'world');
|
||||
* // Prints: hello world, to out
|
||||
* myConsole.error(new Error('Whoops, something bad happened'));
|
||||
* // Prints: [Error: Whoops, something bad happened], to err
|
||||
*
|
||||
* const name = 'Will Robinson';
|
||||
* myConsole.warn(`Danger ${name}! Danger!`);
|
||||
* // Prints: Danger Will Robinson! Danger!, to err
|
||||
* ```
|
||||
* @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/console.js)
|
||||
*/
|
||||
declare module "console" {
|
||||
import console = require("node:console");
|
||||
export = console;
|
||||
}
|
||||
declare module "node:console" {
|
||||
import { InspectOptions } from "node:util";
|
||||
global {
|
||||
// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build
|
||||
interface Console {
|
||||
Console: console.ConsoleConstructor;
|
||||
/**
|
||||
* `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only
|
||||
* writes a message and does not otherwise affect execution. The output always
|
||||
* starts with `"Assertion failed"`. If provided, `message` is formatted using
|
||||
* [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args).
|
||||
*
|
||||
* If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens.
|
||||
*
|
||||
* ```js
|
||||
* console.assert(true, 'does nothing');
|
||||
*
|
||||
* console.assert(false, 'Whoops %s work', 'didn\'t');
|
||||
* // Assertion failed: Whoops didn't work
|
||||
*
|
||||
* console.assert();
|
||||
* // Assertion failed
|
||||
* ```
|
||||
* @since v0.1.101
|
||||
* @param value The value tested for being truthy.
|
||||
* @param message All arguments besides `value` are used as error message.
|
||||
*/
|
||||
assert(value: any, message?: string, ...optionalParams: any[]): void;
|
||||
/**
|
||||
* When `stdout` is a TTY, calling `console.clear()` will attempt to clear the
|
||||
* TTY. When `stdout` is not a TTY, this method does nothing.
|
||||
*
|
||||
* The specific operation of `console.clear()` can vary across operating systems
|
||||
* and terminal types. For most Linux operating systems, `console.clear()` operates similarly to the `clear` shell command. On Windows, `console.clear()` will clear only the output in the
|
||||
* current terminal viewport for the Node.js
|
||||
* binary.
|
||||
* @since v8.3.0
|
||||
*/
|
||||
clear(): void;
|
||||
/**
|
||||
* Maintains an internal counter specific to `label` and outputs to `stdout` the
|
||||
* number of times `console.count()` has been called with the given `label`.
|
||||
*
|
||||
* ```js
|
||||
* > console.count()
|
||||
* default: 1
|
||||
* undefined
|
||||
* > console.count('default')
|
||||
* default: 2
|
||||
* undefined
|
||||
* > console.count('abc')
|
||||
* abc: 1
|
||||
* undefined
|
||||
* > console.count('xyz')
|
||||
* xyz: 1
|
||||
* undefined
|
||||
* > console.count('abc')
|
||||
* abc: 2
|
||||
* undefined
|
||||
* > console.count()
|
||||
* default: 3
|
||||
* undefined
|
||||
* >
|
||||
* ```
|
||||
* @since v8.3.0
|
||||
* @param [label='default'] The display label for the counter.
|
||||
*/
|
||||
count(label?: string): void;
|
||||
/**
|
||||
* Resets the internal counter specific to `label`.
|
||||
*
|
||||
* ```js
|
||||
* > console.count('abc');
|
||||
* abc: 1
|
||||
* undefined
|
||||
* > console.countReset('abc');
|
||||
* undefined
|
||||
* > console.count('abc');
|
||||
* abc: 1
|
||||
* undefined
|
||||
* >
|
||||
* ```
|
||||
* @since v8.3.0
|
||||
* @param [label='default'] The display label for the counter.
|
||||
*/
|
||||
countReset(label?: string): void;
|
||||
/**
|
||||
* The `console.debug()` function is an alias for {@link log}.
|
||||
* @since v8.0.0
|
||||
*/
|
||||
debug(message?: any, ...optionalParams: any[]): void;
|
||||
/**
|
||||
* Uses [`util.inspect()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilinspectobject-options) on `obj` and prints the resulting string to `stdout`.
|
||||
* This function bypasses any custom `inspect()` function defined on `obj`.
|
||||
* @since v0.1.101
|
||||
*/
|
||||
dir(obj: any, options?: InspectOptions): void;
|
||||
/**
|
||||
* This method calls `console.log()` passing it the arguments received.
|
||||
* This method does not produce any XML formatting.
|
||||
* @since v8.0.0
|
||||
*/
|
||||
dirxml(...data: any[]): void;
|
||||
/**
|
||||
* Prints to `stderr` with newline. Multiple arguments can be passed, with the
|
||||
* first used as the primary message and all additional used as substitution
|
||||
* values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
|
||||
* (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)).
|
||||
*
|
||||
* ```js
|
||||
* const code = 5;
|
||||
* console.error('error #%d', code);
|
||||
* // Prints: error #5, to stderr
|
||||
* console.error('error', code);
|
||||
* // Prints: error 5, to stderr
|
||||
* ```
|
||||
*
|
||||
* If formatting elements (e.g. `%d`) are not found in the first string then
|
||||
* [`util.inspect()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilinspectobject-options) is called on each argument and the
|
||||
* resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)
|
||||
* for more information.
|
||||
* @since v0.1.100
|
||||
*/
|
||||
error(message?: any, ...optionalParams: any[]): void;
|
||||
/**
|
||||
* Increases indentation of subsequent lines by spaces for `groupIndentation` length.
|
||||
*
|
||||
* If one or more `label`s are provided, those are printed first without the
|
||||
* additional indentation.
|
||||
* @since v8.5.0
|
||||
*/
|
||||
group(...label: any[]): void;
|
||||
/**
|
||||
* An alias for {@link group}.
|
||||
* @since v8.5.0
|
||||
*/
|
||||
groupCollapsed(...label: any[]): void;
|
||||
/**
|
||||
* Decreases indentation of subsequent lines by spaces for `groupIndentation` length.
|
||||
* @since v8.5.0
|
||||
*/
|
||||
groupEnd(): void;
|
||||
/**
|
||||
* The `console.info()` function is an alias for {@link log}.
|
||||
* @since v0.1.100
|
||||
*/
|
||||
info(message?: any, ...optionalParams: any[]): void;
|
||||
/**
|
||||
* Prints to `stdout` with newline. Multiple arguments can be passed, with the
|
||||
* first used as the primary message and all additional used as substitution
|
||||
* values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
|
||||
* (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)).
|
||||
*
|
||||
* ```js
|
||||
* const count = 5;
|
||||
* console.log('count: %d', count);
|
||||
* // Prints: count: 5, to stdout
|
||||
* console.log('count:', count);
|
||||
* // Prints: count: 5, to stdout
|
||||
* ```
|
||||
*
|
||||
* See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information.
|
||||
* @since v0.1.100
|
||||
*/
|
||||
log(message?: any, ...optionalParams: any[]): void;
|
||||
/**
|
||||
* Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just
|
||||
* logging the argument if it can't be parsed as tabular.
|
||||
*
|
||||
* ```js
|
||||
* // These can't be parsed as tabular data
|
||||
* console.table(Symbol());
|
||||
* // Symbol()
|
||||
*
|
||||
* console.table(undefined);
|
||||
* // undefined
|
||||
*
|
||||
* console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]);
|
||||
* // ┌─────────┬─────┬─────┐
|
||||
* // │ (index) │ a │ b │
|
||||
* // ├─────────┼─────┼─────┤
|
||||
* // │ 0 │ 1 │ 'Y' │
|
||||
* // │ 1 │ 'Z' │ 2 │
|
||||
* // └─────────┴─────┴─────┘
|
||||
*
|
||||
* console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']);
|
||||
* // ┌─────────┬─────┐
|
||||
* // │ (index) │ a │
|
||||
* // ├─────────┼─────┤
|
||||
* // │ 0 │ 1 │
|
||||
* // │ 1 │ 'Z' │
|
||||
* // └─────────┴─────┘
|
||||
* ```
|
||||
* @since v10.0.0
|
||||
* @param properties Alternate properties for constructing the table.
|
||||
*/
|
||||
table(tabularData: any, properties?: readonly string[]): void;
|
||||
/**
|
||||
* Starts a timer that can be used to compute the duration of an operation. Timers
|
||||
* are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in
|
||||
* suitable time units to `stdout`. For example, if the elapsed
|
||||
* time is 3869ms, `console.timeEnd()` displays "3.869s".
|
||||
* @since v0.1.104
|
||||
* @param [label='default']
|
||||
*/
|
||||
time(label?: string): void;
|
||||
/**
|
||||
* Stops a timer that was previously started by calling {@link time} and
|
||||
* prints the result to `stdout`:
|
||||
*
|
||||
* ```js
|
||||
* console.time('bunch-of-stuff');
|
||||
* // Do a bunch of stuff.
|
||||
* console.timeEnd('bunch-of-stuff');
|
||||
* // Prints: bunch-of-stuff: 225.438ms
|
||||
* ```
|
||||
* @since v0.1.104
|
||||
* @param [label='default']
|
||||
*/
|
||||
timeEnd(label?: string): void;
|
||||
/**
|
||||
* For a timer that was previously started by calling {@link time}, prints
|
||||
* the elapsed time and other `data` arguments to `stdout`:
|
||||
*
|
||||
* ```js
|
||||
* console.time('process');
|
||||
* const value = expensiveProcess1(); // Returns 42
|
||||
* console.timeLog('process', value);
|
||||
* // Prints "process: 365.227ms 42".
|
||||
* doExpensiveProcess2(value);
|
||||
* console.timeEnd('process');
|
||||
* ```
|
||||
* @since v10.7.0
|
||||
* @param [label='default']
|
||||
*/
|
||||
timeLog(label?: string, ...data: any[]): void;
|
||||
/**
|
||||
* Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)
|
||||
* formatted message and stack trace to the current position in the code.
|
||||
*
|
||||
* ```js
|
||||
* console.trace('Show me');
|
||||
* // Prints: (stack trace will vary based on where trace is called)
|
||||
* // Trace: Show me
|
||||
* // at repl:2:9
|
||||
* // at REPLServer.defaultEval (repl.js:248:27)
|
||||
* // at bound (domain.js:287:14)
|
||||
* // at REPLServer.runBound [as eval] (domain.js:300:12)
|
||||
* // at REPLServer.<anonymous> (repl.js:412:12)
|
||||
* // at emitOne (events.js:82:20)
|
||||
* // at REPLServer.emit (events.js:169:7)
|
||||
* // at REPLServer.Interface._onLine (readline.js:210:10)
|
||||
* // at REPLServer.Interface._line (readline.js:549:8)
|
||||
* // at REPLServer.Interface._ttyWrite (readline.js:826:14)
|
||||
* ```
|
||||
* @since v0.1.104
|
||||
*/
|
||||
trace(message?: any, ...optionalParams: any[]): void;
|
||||
/**
|
||||
* The `console.warn()` function is an alias for {@link error}.
|
||||
* @since v0.1.100
|
||||
*/
|
||||
warn(message?: any, ...optionalParams: any[]): void;
|
||||
// --- Inspector mode only ---
|
||||
/**
|
||||
* This method does not display anything unless used in the inspector. The `console.profile()`
|
||||
* method starts a JavaScript CPU profile with an optional label until {@link profileEnd}
|
||||
* is called. The profile is then added to the Profile panel of the inspector.
|
||||
*
|
||||
* ```js
|
||||
* console.profile('MyLabel');
|
||||
* // Some code
|
||||
* console.profileEnd('MyLabel');
|
||||
* // Adds the profile 'MyLabel' to the Profiles panel of the inspector.
|
||||
* ```
|
||||
* @since v8.0.0
|
||||
*/
|
||||
profile(label?: string): void;
|
||||
/**
|
||||
* This method does not display anything unless used in the inspector. Stops the current
|
||||
* JavaScript CPU profiling session if one has been started and prints the report to the
|
||||
* Profiles panel of the inspector. See {@link profile} for an example.
|
||||
*
|
||||
* If this method is called without a label, the most recently started profile is stopped.
|
||||
* @since v8.0.0
|
||||
*/
|
||||
profileEnd(label?: string): void;
|
||||
/**
|
||||
* This method does not display anything unless used in the inspector. The `console.timeStamp()`
|
||||
* method adds an event with the label `'label'` to the Timeline panel of the inspector.
|
||||
* @since v8.0.0
|
||||
*/
|
||||
timeStamp(label?: string): void;
|
||||
}
|
||||
/**
|
||||
* The `console` module provides a simple debugging console that is similar to the
|
||||
* JavaScript console mechanism provided by web browsers.
|
||||
*
|
||||
* The module exports two specific components:
|
||||
*
|
||||
* * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
|
||||
* * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and
|
||||
* [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
|
||||
*
|
||||
* _**Warning**_: The global console object's methods are neither consistently
|
||||
* synchronous like the browser APIs they resemble, nor are they consistently
|
||||
* asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for
|
||||
* more information.
|
||||
*
|
||||
* Example using the global `console`:
|
||||
*
|
||||
* ```js
|
||||
* console.log('hello world');
|
||||
* // Prints: hello world, to stdout
|
||||
* console.log('hello %s', 'world');
|
||||
* // Prints: hello world, to stdout
|
||||
* console.error(new Error('Whoops, something bad happened'));
|
||||
* // Prints error message and stack trace to stderr:
|
||||
* // Error: Whoops, something bad happened
|
||||
* // at [eval]:5:15
|
||||
* // at Script.runInThisContext (node:vm:132:18)
|
||||
* // at Object.runInThisContext (node:vm:309:38)
|
||||
* // at node:internal/process/execution:77:19
|
||||
* // at [eval]-wrapper:6:22
|
||||
* // at evalScript (node:internal/process/execution:76:60)
|
||||
* // at node:internal/main/eval_string:23:3
|
||||
*
|
||||
* const name = 'Will Robinson';
|
||||
* console.warn(`Danger ${name}! Danger!`);
|
||||
* // Prints: Danger Will Robinson! Danger!, to stderr
|
||||
* ```
|
||||
*
|
||||
* Example using the `Console` class:
|
||||
*
|
||||
* ```js
|
||||
* const out = getStreamSomehow();
|
||||
* const err = getStreamSomehow();
|
||||
* const myConsole = new console.Console(out, err);
|
||||
*
|
||||
* myConsole.log('hello world');
|
||||
* // Prints: hello world, to out
|
||||
* myConsole.log('hello %s', 'world');
|
||||
* // Prints: hello world, to out
|
||||
* myConsole.error(new Error('Whoops, something bad happened'));
|
||||
* // Prints: [Error: Whoops, something bad happened], to err
|
||||
*
|
||||
* const name = 'Will Robinson';
|
||||
* myConsole.warn(`Danger ${name}! Danger!`);
|
||||
* // Prints: Danger Will Robinson! Danger!, to err
|
||||
* ```
|
||||
* @see [source](https://github.com/nodejs/node/blob/v20.11.1/lib/console.js)
|
||||
*/
|
||||
namespace console {
|
||||
interface ConsoleConstructorOptions {
|
||||
stdout: NodeJS.WritableStream;
|
||||
stderr?: NodeJS.WritableStream | undefined;
|
||||
/**
|
||||
* Ignore errors when writing to the underlying streams.
|
||||
* @default true
|
||||
*/
|
||||
ignoreErrors?: boolean | undefined;
|
||||
/**
|
||||
* Set color support for this `Console` instance. Setting to true enables coloring while inspecting
|
||||
* values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color
|
||||
* support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the
|
||||
* respective stream. This option can not be used, if `inspectOptions.colors` is set as well.
|
||||
* @default auto
|
||||
*/
|
||||
colorMode?: boolean | "auto" | undefined;
|
||||
/**
|
||||
* Specifies options that are passed along to
|
||||
* [`util.inspect()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilinspectobject-options).
|
||||
*/
|
||||
inspectOptions?: InspectOptions | undefined;
|
||||
/**
|
||||
* Set group indentation.
|
||||
* @default 2
|
||||
*/
|
||||
groupIndentation?: number | undefined;
|
||||
}
|
||||
interface ConsoleConstructor {
|
||||
prototype: Console;
|
||||
new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console;
|
||||
new(options: ConsoleConstructorOptions): Console;
|
||||
}
|
||||
}
|
||||
var console: Console;
|
||||
}
|
||||
export = globalThis.console;
|
||||
}
|
||||
21
frontend/e2e/node_modules/@types/node/constants.d.ts
generated
vendored
Normal file
21
frontend/e2e/node_modules/@types/node/constants.d.ts
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* @deprecated The `node:constants` module is deprecated. When requiring access to constants
|
||||
* relevant to specific Node.js builtin modules, developers should instead refer
|
||||
* to the `constants` property exposed by the relevant module. For instance,
|
||||
* `require('node:fs').constants` and `require('node:os').constants`.
|
||||
*/
|
||||
declare module "constants" {
|
||||
const constants:
|
||||
& typeof import("node:os").constants.dlopen
|
||||
& typeof import("node:os").constants.errno
|
||||
& typeof import("node:os").constants.priority
|
||||
& typeof import("node:os").constants.signals
|
||||
& typeof import("node:fs").constants
|
||||
& typeof import("node:crypto").constants;
|
||||
export = constants;
|
||||
}
|
||||
|
||||
declare module "node:constants" {
|
||||
import constants = require("constants");
|
||||
export = constants;
|
||||
}
|
||||
4570
frontend/e2e/node_modules/@types/node/crypto.d.ts
generated
vendored
Normal file
4570
frontend/e2e/node_modules/@types/node/crypto.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
596
frontend/e2e/node_modules/@types/node/dgram.d.ts
generated
vendored
Normal file
596
frontend/e2e/node_modules/@types/node/dgram.d.ts
generated
vendored
Normal file
@@ -0,0 +1,596 @@
|
||||
/**
|
||||
* The `node:dgram` module provides an implementation of UDP datagram sockets.
|
||||
*
|
||||
* ```js
|
||||
* import dgram from 'node:dgram';
|
||||
*
|
||||
* const server = dgram.createSocket('udp4');
|
||||
*
|
||||
* server.on('error', (err) => {
|
||||
* console.error(`server error:\n${err.stack}`);
|
||||
* server.close();
|
||||
* });
|
||||
*
|
||||
* server.on('message', (msg, rinfo) => {
|
||||
* console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
|
||||
* });
|
||||
*
|
||||
* server.on('listening', () => {
|
||||
* const address = server.address();
|
||||
* console.log(`server listening ${address.address}:${address.port}`);
|
||||
* });
|
||||
*
|
||||
* server.bind(41234);
|
||||
* // Prints: server listening 0.0.0.0:41234
|
||||
* ```
|
||||
* @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/dgram.js)
|
||||
*/
|
||||
declare module "dgram" {
|
||||
import { AddressInfo } from "node:net";
|
||||
import * as dns from "node:dns";
|
||||
import { Abortable, EventEmitter } from "node:events";
|
||||
interface RemoteInfo {
|
||||
address: string;
|
||||
family: "IPv4" | "IPv6";
|
||||
port: number;
|
||||
size: number;
|
||||
}
|
||||
interface BindOptions {
|
||||
port?: number | undefined;
|
||||
address?: string | undefined;
|
||||
exclusive?: boolean | undefined;
|
||||
fd?: number | undefined;
|
||||
}
|
||||
type SocketType = "udp4" | "udp6";
|
||||
interface SocketOptions extends Abortable {
|
||||
type: SocketType;
|
||||
reuseAddr?: boolean | undefined;
|
||||
/**
|
||||
* @default false
|
||||
*/
|
||||
ipv6Only?: boolean | undefined;
|
||||
recvBufferSize?: number | undefined;
|
||||
sendBufferSize?: number | undefined;
|
||||
lookup?:
|
||||
| ((
|
||||
hostname: string,
|
||||
options: dns.LookupOneOptions,
|
||||
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
|
||||
) => void)
|
||||
| undefined;
|
||||
}
|
||||
/**
|
||||
* Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram
|
||||
* messages. When `address` and `port` are not passed to `socket.bind()` the
|
||||
* method will bind the socket to the "all interfaces" address on a random port
|
||||
* (it does the right thing for both `udp4` and `udp6` sockets). The bound address
|
||||
* and port can be retrieved using `socket.address().address` and `socket.address().port`.
|
||||
*
|
||||
* If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.close()` on the socket:
|
||||
*
|
||||
* ```js
|
||||
* const controller = new AbortController();
|
||||
* const { signal } = controller;
|
||||
* const server = dgram.createSocket({ type: 'udp4', signal });
|
||||
* server.on('message', (msg, rinfo) => {
|
||||
* console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
|
||||
* });
|
||||
* // Later, when you want to close the server.
|
||||
* controller.abort();
|
||||
* ```
|
||||
* @since v0.11.13
|
||||
* @param options Available options are:
|
||||
* @param callback Attached as a listener for `'message'` events. Optional.
|
||||
*/
|
||||
function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;
|
||||
function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;
|
||||
/**
|
||||
* Encapsulates the datagram functionality.
|
||||
*
|
||||
* New instances of `dgram.Socket` are created using {@link createSocket}.
|
||||
* The `new` keyword is not to be used to create `dgram.Socket` instances.
|
||||
* @since v0.1.99
|
||||
*/
|
||||
class Socket extends EventEmitter {
|
||||
/**
|
||||
* Tells the kernel to join a multicast group at the given `multicastAddress` and `multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the `multicastInterface` argument is not
|
||||
* specified, the operating system will choose
|
||||
* one interface and will add membership to it. To add membership to every
|
||||
* available interface, call `addMembership` multiple times, once per interface.
|
||||
*
|
||||
* When called on an unbound socket, this method will implicitly bind to a random
|
||||
* port, listening on all interfaces.
|
||||
*
|
||||
* When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur:
|
||||
*
|
||||
* ```js
|
||||
* import cluster from 'node:cluster';
|
||||
* import dgram from 'node:dgram';
|
||||
*
|
||||
* if (cluster.isPrimary) {
|
||||
* cluster.fork(); // Works ok.
|
||||
* cluster.fork(); // Fails with EADDRINUSE.
|
||||
* } else {
|
||||
* const s = dgram.createSocket('udp4');
|
||||
* s.bind(1234, () => {
|
||||
* s.addMembership('224.0.0.114');
|
||||
* });
|
||||
* }
|
||||
* ```
|
||||
* @since v0.6.9
|
||||
*/
|
||||
addMembership(multicastAddress: string, multicastInterface?: string): void;
|
||||
/**
|
||||
* Returns an object containing the address information for a socket.
|
||||
* For UDP sockets, this object will contain `address`, `family`, and `port` properties.
|
||||
*
|
||||
* This method throws `EBADF` if called on an unbound socket.
|
||||
* @since v0.1.99
|
||||
*/
|
||||
address(): AddressInfo;
|
||||
/**
|
||||
* For UDP sockets, causes the `dgram.Socket` to listen for datagram
|
||||
* messages on a named `port` and optional `address`. If `port` is not
|
||||
* specified or is `0`, the operating system will attempt to bind to a
|
||||
* random port. If `address` is not specified, the operating system will
|
||||
* attempt to listen on all addresses. Once binding is complete, a `'listening'` event is emitted and the optional `callback` function is
|
||||
* called.
|
||||
*
|
||||
* Specifying both a `'listening'` event listener and passing a `callback` to the `socket.bind()` method is not harmful but not very
|
||||
* useful.
|
||||
*
|
||||
* A bound datagram socket keeps the Node.js process running to receive
|
||||
* datagram messages.
|
||||
*
|
||||
* If binding fails, an `'error'` event is generated. In rare case (e.g.
|
||||
* attempting to bind with a closed socket), an `Error` may be thrown.
|
||||
*
|
||||
* Example of a UDP server listening on port 41234:
|
||||
*
|
||||
* ```js
|
||||
* import dgram from 'node:dgram';
|
||||
*
|
||||
* const server = dgram.createSocket('udp4');
|
||||
*
|
||||
* server.on('error', (err) => {
|
||||
* console.error(`server error:\n${err.stack}`);
|
||||
* server.close();
|
||||
* });
|
||||
*
|
||||
* server.on('message', (msg, rinfo) => {
|
||||
* console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
|
||||
* });
|
||||
*
|
||||
* server.on('listening', () => {
|
||||
* const address = server.address();
|
||||
* console.log(`server listening ${address.address}:${address.port}`);
|
||||
* });
|
||||
*
|
||||
* server.bind(41234);
|
||||
* // Prints: server listening 0.0.0.0:41234
|
||||
* ```
|
||||
* @since v0.1.99
|
||||
* @param callback with no parameters. Called when binding is complete.
|
||||
*/
|
||||
bind(port?: number, address?: string, callback?: () => void): this;
|
||||
bind(port?: number, callback?: () => void): this;
|
||||
bind(callback?: () => void): this;
|
||||
bind(options: BindOptions, callback?: () => void): this;
|
||||
/**
|
||||
* Close the underlying socket and stop listening for data on it. If a callback is
|
||||
* provided, it is added as a listener for the `'close'` event.
|
||||
* @since v0.1.99
|
||||
* @param callback Called when the socket has been closed.
|
||||
*/
|
||||
close(callback?: () => void): this;
|
||||
/**
|
||||
* Associates the `dgram.Socket` to a remote address and port. Every
|
||||
* message sent by this handle is automatically sent to that destination. Also,
|
||||
* the socket will only receive messages from that remote peer.
|
||||
* Trying to call `connect()` on an already connected socket will result
|
||||
* in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not
|
||||
* provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets)
|
||||
* will be used by default. Once the connection is complete, a `'connect'` event
|
||||
* is emitted and the optional `callback` function is called. In case of failure,
|
||||
* the `callback` is called or, failing this, an `'error'` event is emitted.
|
||||
* @since v12.0.0
|
||||
* @param callback Called when the connection is completed or on error.
|
||||
*/
|
||||
connect(port: number, address?: string, callback?: () => void): void;
|
||||
connect(port: number, callback: () => void): void;
|
||||
/**
|
||||
* A synchronous function that disassociates a connected `dgram.Socket` from
|
||||
* its remote address. Trying to call `disconnect()` on an unbound or already
|
||||
* disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception.
|
||||
* @since v12.0.0
|
||||
*/
|
||||
disconnect(): void;
|
||||
/**
|
||||
* Instructs the kernel to leave a multicast group at `multicastAddress` using the `IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the
|
||||
* kernel when the socket is closed or the process terminates, so most apps will
|
||||
* never have reason to call this.
|
||||
*
|
||||
* If `multicastInterface` is not specified, the operating system will attempt to
|
||||
* drop membership on all valid interfaces.
|
||||
* @since v0.6.9
|
||||
*/
|
||||
dropMembership(multicastAddress: string, multicastInterface?: string): void;
|
||||
/**
|
||||
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket.
|
||||
* @since v8.7.0
|
||||
* @return the `SO_RCVBUF` socket receive buffer size in bytes.
|
||||
*/
|
||||
getRecvBufferSize(): number;
|
||||
/**
|
||||
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket.
|
||||
* @since v8.7.0
|
||||
* @return the `SO_SNDBUF` socket send buffer size in bytes.
|
||||
*/
|
||||
getSendBufferSize(): number;
|
||||
/**
|
||||
* @since v18.8.0, v16.19.0
|
||||
* @return Number of bytes queued for sending.
|
||||
*/
|
||||
getSendQueueSize(): number;
|
||||
/**
|
||||
* @since v18.8.0, v16.19.0
|
||||
* @return Number of send requests currently in the queue awaiting to be processed.
|
||||
*/
|
||||
getSendQueueCount(): number;
|
||||
/**
|
||||
* By default, binding a socket will cause it to block the Node.js process from
|
||||
* exiting as long as the socket is open. The `socket.unref()` method can be used
|
||||
* to exclude the socket from the reference counting that keeps the Node.js
|
||||
* process active. The `socket.ref()` method adds the socket back to the reference
|
||||
* counting and restores the default behavior.
|
||||
*
|
||||
* Calling `socket.ref()` multiples times will have no additional effect.
|
||||
*
|
||||
* The `socket.ref()` method returns a reference to the socket so calls can be
|
||||
* chained.
|
||||
* @since v0.9.1
|
||||
*/
|
||||
ref(): this;
|
||||
/**
|
||||
* Returns an object containing the `address`, `family`, and `port` of the remote
|
||||
* endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception
|
||||
* if the socket is not connected.
|
||||
* @since v12.0.0
|
||||
*/
|
||||
remoteAddress(): AddressInfo;
|
||||
/**
|
||||
* Broadcasts a datagram on the socket.
|
||||
* For connectionless sockets, the destination `port` and `address` must be
|
||||
* specified. Connected sockets, on the other hand, will use their associated
|
||||
* remote endpoint, so the `port` and `address` arguments must not be set.
|
||||
*
|
||||
* The `msg` argument contains the message to be sent.
|
||||
* Depending on its type, different behavior can apply. If `msg` is a `Buffer`,
|
||||
* any `TypedArray` or a `DataView`,
|
||||
* the `offset` and `length` specify the offset within the `Buffer` where the
|
||||
* message begins and the number of bytes in the message, respectively.
|
||||
* If `msg` is a `String`, then it is automatically converted to a `Buffer` with `'utf8'` encoding. With messages that
|
||||
* contain multi-byte characters, `offset` and `length` will be calculated with
|
||||
* respect to `byte length` and not the character position.
|
||||
* If `msg` is an array, `offset` and `length` must not be specified.
|
||||
*
|
||||
* The `address` argument is a string. If the value of `address` is a host name,
|
||||
* DNS will be used to resolve the address of the host. If `address` is not
|
||||
* provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) will be used by default.
|
||||
*
|
||||
* If the socket has not been previously bound with a call to `bind`, the socket
|
||||
* is assigned a random port number and is bound to the "all interfaces" address
|
||||
* (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.)
|
||||
*
|
||||
* An optional `callback` function may be specified to as a way of reporting
|
||||
* DNS errors or for determining when it is safe to reuse the `buf` object.
|
||||
* DNS lookups delay the time to send for at least one tick of the
|
||||
* Node.js event loop.
|
||||
*
|
||||
* The only way to know for sure that the datagram has been sent is by using a `callback`. If an error occurs and a `callback` is given, the error will be
|
||||
* passed as the first argument to the `callback`. If a `callback` is not given,
|
||||
* the error is emitted as an `'error'` event on the `socket` object.
|
||||
*
|
||||
* Offset and length are optional but both _must_ be set if either are used.
|
||||
* They are supported only when the first argument is a `Buffer`, a `TypedArray`,
|
||||
* or a `DataView`.
|
||||
*
|
||||
* This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket.
|
||||
*
|
||||
* Example of sending a UDP packet to a port on `localhost`;
|
||||
*
|
||||
* ```js
|
||||
* import dgram from 'node:dgram';
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const message = Buffer.from('Some bytes');
|
||||
* const client = dgram.createSocket('udp4');
|
||||
* client.send(message, 41234, 'localhost', (err) => {
|
||||
* client.close();
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`;
|
||||
*
|
||||
* ```js
|
||||
* import dgram from 'node:dgram';
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const buf1 = Buffer.from('Some ');
|
||||
* const buf2 = Buffer.from('bytes');
|
||||
* const client = dgram.createSocket('udp4');
|
||||
* client.send([buf1, buf2], 41234, (err) => {
|
||||
* client.close();
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Sending multiple buffers might be faster or slower depending on the
|
||||
* application and operating system. Run benchmarks to
|
||||
* determine the optimal strategy on a case-by-case basis. Generally speaking,
|
||||
* however, sending multiple buffers is faster.
|
||||
*
|
||||
* Example of sending a UDP packet using a socket connected to a port on `localhost`:
|
||||
*
|
||||
* ```js
|
||||
* import dgram from 'node:dgram';
|
||||
* import { Buffer } from 'node:buffer';
|
||||
*
|
||||
* const message = Buffer.from('Some bytes');
|
||||
* const client = dgram.createSocket('udp4');
|
||||
* client.connect(41234, 'localhost', (err) => {
|
||||
* client.send(message, (err) => {
|
||||
* client.close();
|
||||
* });
|
||||
* });
|
||||
* ```
|
||||
* @since v0.1.99
|
||||
* @param msg Message to be sent.
|
||||
* @param offset Offset in the buffer where the message starts.
|
||||
* @param length Number of bytes in the message.
|
||||
* @param port Destination port.
|
||||
* @param address Destination host name or IP address.
|
||||
* @param callback Called when the message has been sent.
|
||||
*/
|
||||
send(
|
||||
msg: string | NodeJS.ArrayBufferView | readonly any[],
|
||||
port?: number,
|
||||
address?: string,
|
||||
callback?: (error: Error | null, bytes: number) => void,
|
||||
): void;
|
||||
send(
|
||||
msg: string | NodeJS.ArrayBufferView | readonly any[],
|
||||
port?: number,
|
||||
callback?: (error: Error | null, bytes: number) => void,
|
||||
): void;
|
||||
send(
|
||||
msg: string | NodeJS.ArrayBufferView | readonly any[],
|
||||
callback?: (error: Error | null, bytes: number) => void,
|
||||
): void;
|
||||
send(
|
||||
msg: string | NodeJS.ArrayBufferView,
|
||||
offset: number,
|
||||
length: number,
|
||||
port?: number,
|
||||
address?: string,
|
||||
callback?: (error: Error | null, bytes: number) => void,
|
||||
): void;
|
||||
send(
|
||||
msg: string | NodeJS.ArrayBufferView,
|
||||
offset: number,
|
||||
length: number,
|
||||
port?: number,
|
||||
callback?: (error: Error | null, bytes: number) => void,
|
||||
): void;
|
||||
send(
|
||||
msg: string | NodeJS.ArrayBufferView,
|
||||
offset: number,
|
||||
length: number,
|
||||
callback?: (error: Error | null, bytes: number) => void,
|
||||
): void;
|
||||
/**
|
||||
* Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP
|
||||
* packets may be sent to a local interface's broadcast address.
|
||||
*
|
||||
* This method throws `EBADF` if called on an unbound socket.
|
||||
* @since v0.6.9
|
||||
*/
|
||||
setBroadcast(flag: boolean): void;
|
||||
/**
|
||||
* _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC
|
||||
* 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_
|
||||
* _with a scope index is written as `'IP%scope'` where scope is an interface name_
|
||||
* _or interface number._
|
||||
*
|
||||
* Sets the default outgoing multicast interface of the socket to a chosen
|
||||
* interface or back to system interface selection. The `multicastInterface` must
|
||||
* be a valid string representation of an IP from the socket's family.
|
||||
*
|
||||
* For IPv4 sockets, this should be the IP configured for the desired physical
|
||||
* interface. All packets sent to multicast on the socket will be sent on the
|
||||
* interface determined by the most recent successful use of this call.
|
||||
*
|
||||
* For IPv6 sockets, `multicastInterface` should include a scope to indicate the
|
||||
* interface as in the examples that follow. In IPv6, individual `send` calls can
|
||||
* also use explicit scope in addresses, so only packets sent to a multicast
|
||||
* address without specifying an explicit scope are affected by the most recent
|
||||
* successful use of this call.
|
||||
*
|
||||
* This method throws `EBADF` if called on an unbound socket.
|
||||
*
|
||||
* #### Example: IPv6 outgoing multicast interface
|
||||
*
|
||||
* On most systems, where scope format uses the interface name:
|
||||
*
|
||||
* ```js
|
||||
* const socket = dgram.createSocket('udp6');
|
||||
*
|
||||
* socket.bind(1234, () => {
|
||||
* socket.setMulticastInterface('::%eth1');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* On Windows, where scope format uses an interface number:
|
||||
*
|
||||
* ```js
|
||||
* const socket = dgram.createSocket('udp6');
|
||||
*
|
||||
* socket.bind(1234, () => {
|
||||
* socket.setMulticastInterface('::%2');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* #### Example: IPv4 outgoing multicast interface
|
||||
*
|
||||
* All systems use an IP of the host on the desired physical interface:
|
||||
*
|
||||
* ```js
|
||||
* const socket = dgram.createSocket('udp4');
|
||||
*
|
||||
* socket.bind(1234, () => {
|
||||
* socket.setMulticastInterface('10.0.0.2');
|
||||
* });
|
||||
* ```
|
||||
* @since v8.6.0
|
||||
*/
|
||||
setMulticastInterface(multicastInterface: string): void;
|
||||
/**
|
||||
* Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`,
|
||||
* multicast packets will also be received on the local interface.
|
||||
*
|
||||
* This method throws `EBADF` if called on an unbound socket.
|
||||
* @since v0.3.8
|
||||
*/
|
||||
setMulticastLoopback(flag: boolean): boolean;
|
||||
/**
|
||||
* Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for
|
||||
* "Time to Live", in this context it specifies the number of IP hops that a
|
||||
* packet is allowed to travel through, specifically for multicast traffic. Each
|
||||
* router or gateway that forwards a packet decrements the TTL. If the TTL is
|
||||
* decremented to 0 by a router, it will not be forwarded.
|
||||
*
|
||||
* The `ttl` argument may be between 0 and 255\. The default on most systems is `1`.
|
||||
*
|
||||
* This method throws `EBADF` if called on an unbound socket.
|
||||
* @since v0.3.8
|
||||
*/
|
||||
setMulticastTTL(ttl: number): number;
|
||||
/**
|
||||
* Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer
|
||||
* in bytes.
|
||||
*
|
||||
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket.
|
||||
* @since v8.7.0
|
||||
*/
|
||||
setRecvBufferSize(size: number): void;
|
||||
/**
|
||||
* Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer
|
||||
* in bytes.
|
||||
*
|
||||
* This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket.
|
||||
* @since v8.7.0
|
||||
*/
|
||||
setSendBufferSize(size: number): void;
|
||||
/**
|
||||
* Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live",
|
||||
* in this context it specifies the number of IP hops that a packet is allowed to
|
||||
* travel through. Each router or gateway that forwards a packet decrements the
|
||||
* TTL. If the TTL is decremented to 0 by a router, it will not be forwarded.
|
||||
* Changing TTL values is typically done for network probes or when multicasting.
|
||||
*
|
||||
* The `ttl` argument may be between 1 and 255\. The default on most systems
|
||||
* is 64.
|
||||
*
|
||||
* This method throws `EBADF` if called on an unbound socket.
|
||||
* @since v0.1.101
|
||||
*/
|
||||
setTTL(ttl: number): number;
|
||||
/**
|
||||
* By default, binding a socket will cause it to block the Node.js process from
|
||||
* exiting as long as the socket is open. The `socket.unref()` method can be used
|
||||
* to exclude the socket from the reference counting that keeps the Node.js
|
||||
* process active, allowing the process to exit even if the socket is still
|
||||
* listening.
|
||||
*
|
||||
* Calling `socket.unref()` multiple times will have no additional effect.
|
||||
*
|
||||
* The `socket.unref()` method returns a reference to the socket so calls can be
|
||||
* chained.
|
||||
* @since v0.9.1
|
||||
*/
|
||||
unref(): this;
|
||||
/**
|
||||
* Tells the kernel to join a source-specific multicast channel at the given `sourceAddress` and `groupAddress`, using the `multicastInterface` with the `IP_ADD_SOURCE_MEMBERSHIP` socket
|
||||
* option. If the `multicastInterface` argument
|
||||
* is not specified, the operating system will choose one interface and will add
|
||||
* membership to it. To add membership to every available interface, call `socket.addSourceSpecificMembership()` multiple times, once per interface.
|
||||
*
|
||||
* When called on an unbound socket, this method will implicitly bind to a random
|
||||
* port, listening on all interfaces.
|
||||
* @since v13.1.0, v12.16.0
|
||||
*/
|
||||
addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void;
|
||||
/**
|
||||
* Instructs the kernel to leave a source-specific multicast channel at the given `sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP` socket option. This method is
|
||||
* automatically called by the kernel when the
|
||||
* socket is closed or the process terminates, so most apps will never have
|
||||
* reason to call this.
|
||||
*
|
||||
* If `multicastInterface` is not specified, the operating system will attempt to
|
||||
* drop membership on all valid interfaces.
|
||||
* @since v13.1.0, v12.16.0
|
||||
*/
|
||||
dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void;
|
||||
/**
|
||||
* events.EventEmitter
|
||||
* 1. close
|
||||
* 2. connect
|
||||
* 3. error
|
||||
* 4. listening
|
||||
* 5. message
|
||||
*/
|
||||
addListener(event: string, listener: (...args: any[]) => void): this;
|
||||
addListener(event: "close", listener: () => void): this;
|
||||
addListener(event: "connect", listener: () => void): this;
|
||||
addListener(event: "error", listener: (err: Error) => void): this;
|
||||
addListener(event: "listening", listener: () => void): this;
|
||||
addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
|
||||
emit(event: string | symbol, ...args: any[]): boolean;
|
||||
emit(event: "close"): boolean;
|
||||
emit(event: "connect"): boolean;
|
||||
emit(event: "error", err: Error): boolean;
|
||||
emit(event: "listening"): boolean;
|
||||
emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean;
|
||||
on(event: string, listener: (...args: any[]) => void): this;
|
||||
on(event: "close", listener: () => void): this;
|
||||
on(event: "connect", listener: () => void): this;
|
||||
on(event: "error", listener: (err: Error) => void): this;
|
||||
on(event: "listening", listener: () => void): this;
|
||||
on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
|
||||
once(event: string, listener: (...args: any[]) => void): this;
|
||||
once(event: "close", listener: () => void): this;
|
||||
once(event: "connect", listener: () => void): this;
|
||||
once(event: "error", listener: (err: Error) => void): this;
|
||||
once(event: "listening", listener: () => void): this;
|
||||
once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
|
||||
prependListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependListener(event: "close", listener: () => void): this;
|
||||
prependListener(event: "connect", listener: () => void): this;
|
||||
prependListener(event: "error", listener: (err: Error) => void): this;
|
||||
prependListener(event: "listening", listener: () => void): this;
|
||||
prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
|
||||
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependOnceListener(event: "close", listener: () => void): this;
|
||||
prependOnceListener(event: "connect", listener: () => void): this;
|
||||
prependOnceListener(event: "error", listener: (err: Error) => void): this;
|
||||
prependOnceListener(event: "listening", listener: () => void): this;
|
||||
prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this;
|
||||
/**
|
||||
* Calls `socket.close()` and returns a promise that fulfills when the socket has closed.
|
||||
* @since v20.5.0
|
||||
*/
|
||||
[Symbol.asyncDispose](): Promise<void>;
|
||||
}
|
||||
}
|
||||
declare module "node:dgram" {
|
||||
export * from "dgram";
|
||||
}
|
||||
578
frontend/e2e/node_modules/@types/node/diagnostics_channel.d.ts
generated
vendored
Normal file
578
frontend/e2e/node_modules/@types/node/diagnostics_channel.d.ts
generated
vendored
Normal file
@@ -0,0 +1,578 @@
|
||||
/**
|
||||
* The `node:diagnostics_channel` module provides an API to create named channels
|
||||
* to report arbitrary message data for diagnostics purposes.
|
||||
*
|
||||
* It can be accessed using:
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
* ```
|
||||
*
|
||||
* It is intended that a module writer wanting to report diagnostics messages
|
||||
* will create one or many top-level channels to report messages through.
|
||||
* Channels may also be acquired at runtime but it is not encouraged
|
||||
* due to the additional overhead of doing so. Channels may be exported for
|
||||
* convenience, but as long as the name is known it can be acquired anywhere.
|
||||
*
|
||||
* If you intend for your module to produce diagnostics data for others to
|
||||
* consume it is recommended that you include documentation of what named
|
||||
* channels are used along with the shape of the message data. Channel names
|
||||
* should generally include the module name to avoid collisions with data from
|
||||
* other modules.
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/diagnostics_channel.js)
|
||||
*/
|
||||
declare module "diagnostics_channel" {
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
/**
|
||||
* Check if there are active subscribers to the named channel. This is helpful if
|
||||
* the message you want to send might be expensive to prepare.
|
||||
*
|
||||
* This API is optional but helpful when trying to publish messages from very
|
||||
* performance-sensitive code.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* if (diagnostics_channel.hasSubscribers('my-channel')) {
|
||||
* // There are subscribers, prepare and publish message
|
||||
* }
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param name The channel name
|
||||
* @return If there are active subscribers
|
||||
*/
|
||||
function hasSubscribers(name: string | symbol): boolean;
|
||||
/**
|
||||
* This is the primary entry-point for anyone wanting to publish to a named
|
||||
* channel. It produces a channel object which is optimized to reduce overhead at
|
||||
* publish time as much as possible.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param name The channel name
|
||||
* @return The named channel object
|
||||
*/
|
||||
function channel(name: string | symbol): Channel;
|
||||
type ChannelListener = (message: unknown, name: string | symbol) => void;
|
||||
/**
|
||||
* Register a message handler to subscribe to this channel. This message handler
|
||||
* will be run synchronously whenever a message is published to the channel. Any
|
||||
* errors thrown in the message handler will trigger an `'uncaughtException'`.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* diagnostics_channel.subscribe('my-channel', (message, name) => {
|
||||
* // Received data
|
||||
* });
|
||||
* ```
|
||||
* @since v18.7.0, v16.17.0
|
||||
* @param name The channel name
|
||||
* @param onMessage The handler to receive channel messages
|
||||
*/
|
||||
function subscribe(name: string | symbol, onMessage: ChannelListener): void;
|
||||
/**
|
||||
* Remove a message handler previously registered to this channel with {@link subscribe}.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* function onMessage(message, name) {
|
||||
* // Received data
|
||||
* }
|
||||
*
|
||||
* diagnostics_channel.subscribe('my-channel', onMessage);
|
||||
*
|
||||
* diagnostics_channel.unsubscribe('my-channel', onMessage);
|
||||
* ```
|
||||
* @since v18.7.0, v16.17.0
|
||||
* @param name The channel name
|
||||
* @param onMessage The previous subscribed handler to remove
|
||||
* @return `true` if the handler was found, `false` otherwise.
|
||||
*/
|
||||
function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean;
|
||||
/**
|
||||
* Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing
|
||||
* channels will be created in the form of `tracing:${name}:${eventType}` where `eventType` corresponds to the types of `TracingChannel Channels`.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channelsByName = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* // or...
|
||||
*
|
||||
* const channelsByCollection = diagnostics_channel.tracingChannel({
|
||||
* start: diagnostics_channel.channel('tracing:my-channel:start'),
|
||||
* end: diagnostics_channel.channel('tracing:my-channel:end'),
|
||||
* asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'),
|
||||
* asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'),
|
||||
* error: diagnostics_channel.channel('tracing:my-channel:error'),
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param nameOrChannels Channel name or object containing all the `TracingChannel Channels`
|
||||
* @return Collection of channels to trace with
|
||||
*/
|
||||
function tracingChannel<
|
||||
StoreType = unknown,
|
||||
ContextType extends object = StoreType extends object ? StoreType : object,
|
||||
>(
|
||||
nameOrChannels: string | TracingChannelCollection<StoreType, ContextType>,
|
||||
): TracingChannel<StoreType, ContextType>;
|
||||
/**
|
||||
* The class `Channel` represents an individual named channel within the data
|
||||
* pipeline. It is used to track subscribers and to publish messages when there
|
||||
* are subscribers present. It exists as a separate object to avoid channel
|
||||
* lookups at publish time, enabling very fast publish speeds and allowing
|
||||
* for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly
|
||||
* with `new Channel(name)` is not supported.
|
||||
* @since v15.1.0, v14.17.0
|
||||
*/
|
||||
class Channel<StoreType = unknown, ContextType = StoreType> {
|
||||
readonly name: string | symbol;
|
||||
/**
|
||||
* Check if there are active subscribers to this channel. This is helpful if
|
||||
* the message you want to send might be expensive to prepare.
|
||||
*
|
||||
* This API is optional but helpful when trying to publish messages from very
|
||||
* performance-sensitive code.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* if (channel.hasSubscribers) {
|
||||
* // There are subscribers, prepare and publish message
|
||||
* }
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
*/
|
||||
readonly hasSubscribers: boolean;
|
||||
private constructor(name: string | symbol);
|
||||
/**
|
||||
* Publish a message to any subscribers to the channel. This will trigger
|
||||
* message handlers synchronously so they will execute within the same context.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* channel.publish({
|
||||
* some: 'message',
|
||||
* });
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param message The message to send to the channel subscribers
|
||||
*/
|
||||
publish(message: unknown): void;
|
||||
/**
|
||||
* Register a message handler to subscribe to this channel. This message handler
|
||||
* will be run synchronously whenever a message is published to the channel. Any
|
||||
* errors thrown in the message handler will trigger an `'uncaughtException'`.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* channel.subscribe((message, name) => {
|
||||
* // Received data
|
||||
* });
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)}
|
||||
* @param onMessage The handler to receive channel messages
|
||||
*/
|
||||
subscribe(onMessage: ChannelListener): void;
|
||||
/**
|
||||
* Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* function onMessage(message, name) {
|
||||
* // Received data
|
||||
* }
|
||||
*
|
||||
* channel.subscribe(onMessage);
|
||||
*
|
||||
* channel.unsubscribe(onMessage);
|
||||
* ```
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)}
|
||||
* @param onMessage The previous subscribed handler to remove
|
||||
* @return `true` if the handler was found, `false` otherwise.
|
||||
*/
|
||||
unsubscribe(onMessage: ChannelListener): void;
|
||||
/**
|
||||
* When `channel.runStores(context, ...)` is called, the given context data
|
||||
* will be applied to any store bound to the channel. If the store has already been
|
||||
* bound the previous `transform` function will be replaced with the new one.
|
||||
* The `transform` function may be omitted to set the given context data as the
|
||||
* context directly.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
* import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
*
|
||||
* const store = new AsyncLocalStorage();
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* channel.bindStore(store, (data) => {
|
||||
* return { data };
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param store The store to which to bind the context data
|
||||
* @param transform Transform context data before setting the store context
|
||||
*/
|
||||
bindStore(store: AsyncLocalStorage<StoreType>, transform?: (context: ContextType) => StoreType): void;
|
||||
/**
|
||||
* Remove a message handler previously registered to this channel with `channel.bindStore(store)`.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
* import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
*
|
||||
* const store = new AsyncLocalStorage();
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* channel.bindStore(store);
|
||||
* channel.unbindStore(store);
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param store The store to unbind from the channel.
|
||||
* @return `true` if the store was found, `false` otherwise.
|
||||
*/
|
||||
unbindStore(store: AsyncLocalStorage<StoreType>): boolean;
|
||||
/**
|
||||
* Applies the given data to any AsyncLocalStorage instances bound to the channel
|
||||
* for the duration of the given function, then publishes to the channel within
|
||||
* the scope of that data is applied to the stores.
|
||||
*
|
||||
* If a transform function was given to `channel.bindStore(store)` it will be
|
||||
* applied to transform the message data before it becomes the context value for
|
||||
* the store. The prior storage context is accessible from within the transform
|
||||
* function in cases where context linking is required.
|
||||
*
|
||||
* The context applied to the store should be accessible in any async code which
|
||||
* continues from execution which began during the given function, however
|
||||
* there are some situations in which `context loss` may occur.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
* import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
*
|
||||
* const store = new AsyncLocalStorage();
|
||||
*
|
||||
* const channel = diagnostics_channel.channel('my-channel');
|
||||
*
|
||||
* channel.bindStore(store, (message) => {
|
||||
* const parent = store.getStore();
|
||||
* return new Span(message, parent);
|
||||
* });
|
||||
* channel.runStores({ some: 'message' }, () => {
|
||||
* store.getStore(); // Span({ some: 'message' })
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param context Message to send to subscribers and bind to stores
|
||||
* @param fn Handler to run within the entered storage context
|
||||
* @param thisArg The receiver to be used for the function call.
|
||||
* @param args Optional arguments to pass to the function.
|
||||
*/
|
||||
runStores<ThisArg = any, Args extends any[] = any[], Result = any>(
|
||||
context: ContextType,
|
||||
fn: (this: ThisArg, ...args: Args) => Result,
|
||||
thisArg?: ThisArg,
|
||||
...args: Args
|
||||
): Result;
|
||||
}
|
||||
interface TracingChannelSubscribers<ContextType extends object> {
|
||||
start: (message: ContextType) => void;
|
||||
end: (
|
||||
message: ContextType & {
|
||||
error?: unknown;
|
||||
result?: unknown;
|
||||
},
|
||||
) => void;
|
||||
asyncStart: (
|
||||
message: ContextType & {
|
||||
error?: unknown;
|
||||
result?: unknown;
|
||||
},
|
||||
) => void;
|
||||
asyncEnd: (
|
||||
message: ContextType & {
|
||||
error?: unknown;
|
||||
result?: unknown;
|
||||
},
|
||||
) => void;
|
||||
error: (
|
||||
message: ContextType & {
|
||||
error: unknown;
|
||||
},
|
||||
) => void;
|
||||
}
|
||||
interface TracingChannelCollection<StoreType = unknown, ContextType = StoreType> {
|
||||
start: Channel<StoreType, ContextType>;
|
||||
end: Channel<StoreType, ContextType>;
|
||||
asyncStart: Channel<StoreType, ContextType>;
|
||||
asyncEnd: Channel<StoreType, ContextType>;
|
||||
error: Channel<StoreType, ContextType>;
|
||||
}
|
||||
/**
|
||||
* The class `TracingChannel` is a collection of `TracingChannel Channels` which
|
||||
* together express a single traceable action. It is used to formalize and
|
||||
* simplify the process of producing events for tracing application flow. {@link tracingChannel} is used to construct a `TracingChannel`. As with `Channel` it is recommended to create and reuse a
|
||||
* single `TracingChannel` at the top-level of the file rather than creating them
|
||||
* dynamically.
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
*/
|
||||
class TracingChannel<StoreType = unknown, ContextType extends object = {}> implements TracingChannelCollection {
|
||||
start: Channel<StoreType, ContextType>;
|
||||
end: Channel<StoreType, ContextType>;
|
||||
asyncStart: Channel<StoreType, ContextType>;
|
||||
asyncEnd: Channel<StoreType, ContextType>;
|
||||
error: Channel<StoreType, ContextType>;
|
||||
/**
|
||||
* Helper to subscribe a collection of functions to the corresponding channels.
|
||||
* This is the same as calling `channel.subscribe(onMessage)` on each channel
|
||||
* individually.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* channels.subscribe({
|
||||
* start(message) {
|
||||
* // Handle start message
|
||||
* },
|
||||
* end(message) {
|
||||
* // Handle end message
|
||||
* },
|
||||
* asyncStart(message) {
|
||||
* // Handle asyncStart message
|
||||
* },
|
||||
* asyncEnd(message) {
|
||||
* // Handle asyncEnd message
|
||||
* },
|
||||
* error(message) {
|
||||
* // Handle error message
|
||||
* },
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param subscribers Set of `TracingChannel Channels` subscribers
|
||||
*/
|
||||
subscribe(subscribers: TracingChannelSubscribers<ContextType>): void;
|
||||
/**
|
||||
* Helper to unsubscribe a collection of functions from the corresponding channels.
|
||||
* This is the same as calling `channel.unsubscribe(onMessage)` on each channel
|
||||
* individually.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* channels.unsubscribe({
|
||||
* start(message) {
|
||||
* // Handle start message
|
||||
* },
|
||||
* end(message) {
|
||||
* // Handle end message
|
||||
* },
|
||||
* asyncStart(message) {
|
||||
* // Handle asyncStart message
|
||||
* },
|
||||
* asyncEnd(message) {
|
||||
* // Handle asyncEnd message
|
||||
* },
|
||||
* error(message) {
|
||||
* // Handle error message
|
||||
* },
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param subscribers Set of `TracingChannel Channels` subscribers
|
||||
* @return `true` if all handlers were successfully unsubscribed, and `false` otherwise.
|
||||
*/
|
||||
unsubscribe(subscribers: TracingChannelSubscribers<ContextType>): void;
|
||||
/**
|
||||
* Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error.
|
||||
* This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
|
||||
* events should have any bound stores set to match this trace context.
|
||||
*
|
||||
* To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions
|
||||
* which are added after the trace begins will not receive future events from that trace, only future traces will be seen.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* channels.traceSync(() => {
|
||||
* // Do something
|
||||
* }, {
|
||||
* some: 'thing',
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param fn Function to wrap a trace around
|
||||
* @param context Shared object to correlate events through
|
||||
* @param thisArg The receiver to be used for the function call
|
||||
* @param args Optional arguments to pass to the function
|
||||
* @return The return value of the given function
|
||||
*/
|
||||
traceSync<ThisArg = any, Args extends any[] = any[], Result = any>(
|
||||
fn: (this: ThisArg, ...args: Args) => Result,
|
||||
context?: ContextType,
|
||||
thisArg?: ThisArg,
|
||||
...args: Args
|
||||
): Result;
|
||||
/**
|
||||
* Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the
|
||||
* function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also
|
||||
* produce an `error event` if the given function throws an error or the
|
||||
* returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
|
||||
* events should have any bound stores set to match this trace context.
|
||||
*
|
||||
* To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions
|
||||
* which are added after the trace begins will not receive future events from that trace, only future traces will be seen.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* channels.tracePromise(async () => {
|
||||
* // Do something
|
||||
* }, {
|
||||
* some: 'thing',
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param fn Promise-returning function to wrap a trace around
|
||||
* @param context Shared object to correlate trace events through
|
||||
* @param thisArg The receiver to be used for the function call
|
||||
* @param args Optional arguments to pass to the function
|
||||
* @return Chained from promise returned by the given function
|
||||
*/
|
||||
tracePromise<ThisArg = any, Args extends any[] = any[], Result = any>(
|
||||
fn: (this: ThisArg, ...args: Args) => Promise<Result>,
|
||||
context?: ContextType,
|
||||
thisArg?: ThisArg,
|
||||
...args: Args
|
||||
): Promise<Result>;
|
||||
/**
|
||||
* Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the
|
||||
* function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or
|
||||
* the returned
|
||||
* promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all
|
||||
* events should have any bound stores set to match this trace context.
|
||||
*
|
||||
* The `position` will be -1 by default to indicate the final argument should
|
||||
* be used as the callback.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* channels.traceCallback((arg1, callback) => {
|
||||
* // Do something
|
||||
* callback(null, 'result');
|
||||
* }, 1, {
|
||||
* some: 'thing',
|
||||
* }, thisArg, arg1, callback);
|
||||
* ```
|
||||
*
|
||||
* The callback will also be run with `channel.runStores(context, ...)` which
|
||||
* enables context loss recovery in some cases.
|
||||
*
|
||||
* To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions
|
||||
* which are added after the trace begins will not receive future events from that trace, only future traces will be seen.
|
||||
*
|
||||
* ```js
|
||||
* import diagnostics_channel from 'node:diagnostics_channel';
|
||||
* import { AsyncLocalStorage } from 'node:async_hooks';
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
* const myStore = new AsyncLocalStorage();
|
||||
*
|
||||
* // The start channel sets the initial store data to something
|
||||
* // and stores that store data value on the trace context object
|
||||
* channels.start.bindStore(myStore, (data) => {
|
||||
* const span = new Span(data);
|
||||
* data.span = span;
|
||||
* return span;
|
||||
* });
|
||||
*
|
||||
* // Then asyncStart can restore from that data it stored previously
|
||||
* channels.asyncStart.bindStore(myStore, (data) => {
|
||||
* return data.span;
|
||||
* });
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
* @experimental
|
||||
* @param fn callback using function to wrap a trace around
|
||||
* @param position Zero-indexed argument position of expected callback
|
||||
* @param context Shared object to correlate trace events through
|
||||
* @param thisArg The receiver to be used for the function call
|
||||
* @param args Optional arguments to pass to the function
|
||||
* @return The return value of the given function
|
||||
*/
|
||||
traceCallback<ThisArg = any, Args extends any[] = any[], Result = any>(
|
||||
fn: (this: ThisArg, ...args: Args) => Result,
|
||||
position?: number,
|
||||
context?: ContextType,
|
||||
thisArg?: ThisArg,
|
||||
...args: Args
|
||||
): Result;
|
||||
/**
|
||||
* `true` if any of the individual channels has a subscriber, `false` if not.
|
||||
*
|
||||
* This is a helper method available on a {@link TracingChannel} instance to check
|
||||
* if any of the [TracingChannel Channels](https://nodejs.org/api/diagnostics_channel.html#tracingchannel-channels) have subscribers.
|
||||
* A `true` is returned if any of them have at least one subscriber, a `false` is returned otherwise.
|
||||
*
|
||||
* ```js
|
||||
* const diagnostics_channel = require('node:diagnostics_channel');
|
||||
*
|
||||
* const channels = diagnostics_channel.tracingChannel('my-channel');
|
||||
*
|
||||
* if (channels.hasSubscribers) {
|
||||
* // Do something
|
||||
* }
|
||||
* ```
|
||||
* @since v22.0.0, v20.13.0
|
||||
*/
|
||||
readonly hasSubscribers: boolean;
|
||||
}
|
||||
}
|
||||
declare module "node:diagnostics_channel" {
|
||||
export * from "diagnostics_channel";
|
||||
}
|
||||
871
frontend/e2e/node_modules/@types/node/dns.d.ts
generated
vendored
Normal file
871
frontend/e2e/node_modules/@types/node/dns.d.ts
generated
vendored
Normal file
@@ -0,0 +1,871 @@
|
||||
/**
|
||||
* The `node:dns` module enables name resolution. For example, use it to look up IP
|
||||
* addresses of host names.
|
||||
*
|
||||
* Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the
|
||||
* DNS protocol for lookups. {@link lookup} uses the operating system
|
||||
* facilities to perform name resolution. It may not need to perform any network
|
||||
* communication. To perform name resolution the way other applications on the same
|
||||
* system do, use {@link lookup}.
|
||||
*
|
||||
* ```js
|
||||
* import dns from 'node:dns';
|
||||
*
|
||||
* dns.lookup('example.org', (err, address, family) => {
|
||||
* console.log('address: %j family: IPv%s', address, family);
|
||||
* });
|
||||
* // address: "93.184.216.34" family: IPv4
|
||||
* ```
|
||||
*
|
||||
* All other functions in the `node:dns` module connect to an actual DNS server to
|
||||
* perform name resolution. They will always use the network to perform DNS
|
||||
* queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform
|
||||
* DNS queries, bypassing other name-resolution facilities.
|
||||
*
|
||||
* ```js
|
||||
* import dns from 'node:dns';
|
||||
*
|
||||
* dns.resolve4('archive.org', (err, addresses) => {
|
||||
* if (err) throw err;
|
||||
*
|
||||
* console.log(`addresses: ${JSON.stringify(addresses)}`);
|
||||
*
|
||||
* addresses.forEach((a) => {
|
||||
* dns.reverse(a, (err, hostnames) => {
|
||||
* if (err) {
|
||||
* throw err;
|
||||
* }
|
||||
* console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
|
||||
* });
|
||||
* });
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* See the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) for more information.
|
||||
* @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/dns.js)
|
||||
*/
|
||||
declare module "dns" {
|
||||
import * as dnsPromises from "node:dns/promises";
|
||||
// Supported getaddrinfo flags.
|
||||
/**
|
||||
* Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are
|
||||
* only returned if the current system has at least one IPv4 address configured.
|
||||
*/
|
||||
export const ADDRCONFIG: number;
|
||||
/**
|
||||
* If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported
|
||||
* on some operating systems (e.g. FreeBSD 10.1).
|
||||
*/
|
||||
export const V4MAPPED: number;
|
||||
/**
|
||||
* If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as
|
||||
* well as IPv4 mapped IPv6 addresses.
|
||||
*/
|
||||
export const ALL: number;
|
||||
export interface LookupOptions {
|
||||
/**
|
||||
* The record family. Must be `4`, `6`, or `0`. For backward compatibility reasons, `'IPv4'` and `'IPv6'` are interpreted
|
||||
* as `4` and `6` respectively. The value 0 indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used
|
||||
* with `{ all: true } (see below)`, both IPv4 and IPv6 addresses are returned.
|
||||
* @default 0
|
||||
*/
|
||||
family?: number | "IPv4" | "IPv6" | undefined;
|
||||
/**
|
||||
* One or more [supported `getaddrinfo`](https://nodejs.org/docs/latest-v20.x/api/dns.html#supported-getaddrinfo-flags) flags. Multiple flags may be
|
||||
* passed by bitwise `OR`ing their values.
|
||||
*/
|
||||
hints?: number | undefined;
|
||||
/**
|
||||
* When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address.
|
||||
* @default false
|
||||
*/
|
||||
all?: boolean | undefined;
|
||||
/**
|
||||
* When `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted
|
||||
* by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6
|
||||
* addresses before IPv4 addresses. Default value is configurable using
|
||||
* {@link setDefaultResultOrder} or [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder).
|
||||
* @default `verbatim` (addresses are not reordered)
|
||||
*/
|
||||
order?: "ipv4first" | "ipv6first" | "verbatim" | undefined;
|
||||
/**
|
||||
* When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4
|
||||
* addresses are placed before IPv6 addresses. This option will be deprecated in favor of `order`. When both are specified,
|
||||
* `order` has higher precedence. New code should only use `order`. Default value is configurable using {@link setDefaultResultOrder}
|
||||
* or [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder).
|
||||
* @default true (addresses are not reordered)
|
||||
*/
|
||||
verbatim?: boolean | undefined;
|
||||
}
|
||||
export interface LookupOneOptions extends LookupOptions {
|
||||
all?: false | undefined;
|
||||
}
|
||||
export interface LookupAllOptions extends LookupOptions {
|
||||
all: true;
|
||||
}
|
||||
export interface LookupAddress {
|
||||
/**
|
||||
* A string representation of an IPv4 or IPv6 address.
|
||||
*/
|
||||
address: string;
|
||||
/**
|
||||
* `4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a
|
||||
* bug in the name resolution service used by the operating system.
|
||||
*/
|
||||
family: number;
|
||||
}
|
||||
/**
|
||||
* Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or
|
||||
* AAAA (IPv6) record. All `option` properties are optional. If `options` is an
|
||||
* integer, then it must be `4` or `6` – if `options` is `0` or not provided, then
|
||||
* IPv4 and IPv6 addresses are both returned if found.
|
||||
*
|
||||
* With the `all` option set to `true`, the arguments for `callback` change to `(err, addresses)`, with `addresses` being an array of objects with the
|
||||
* properties `address` and `family`.
|
||||
*
|
||||
* On error, `err` is an `Error` object, where `err.code` is the error code.
|
||||
* Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when
|
||||
* the host name does not exist but also when the lookup fails in other ways
|
||||
* such as no available file descriptors.
|
||||
*
|
||||
* `dns.lookup()` does not necessarily have anything to do with the DNS protocol.
|
||||
* The implementation uses an operating system facility that can associate names
|
||||
* with addresses and vice versa. This implementation can have subtle but
|
||||
* important consequences on the behavior of any Node.js program. Please take some
|
||||
* time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations)
|
||||
* before using `dns.lookup()`.
|
||||
*
|
||||
* Example usage:
|
||||
*
|
||||
* ```js
|
||||
* import dns from 'node:dns';
|
||||
* const options = {
|
||||
* family: 6,
|
||||
* hints: dns.ADDRCONFIG | dns.V4MAPPED,
|
||||
* };
|
||||
* dns.lookup('example.com', options, (err, address, family) =>
|
||||
* console.log('address: %j family: IPv%s', address, family));
|
||||
* // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
|
||||
*
|
||||
* // When options.all is true, the result will be an Array.
|
||||
* options.all = true;
|
||||
* dns.lookup('example.com', options, (err, addresses) =>
|
||||
* console.log('addresses: %j', addresses));
|
||||
* // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
|
||||
* ```
|
||||
*
|
||||
* If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v20.x/api/util.html#utilpromisifyoriginal) ed
|
||||
* version, and `all` is not set to `true`, it returns a `Promise` for an `Object` with `address` and `family` properties.
|
||||
* @since v0.1.90
|
||||
*/
|
||||
export function lookup(
|
||||
hostname: string,
|
||||
family: number,
|
||||
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
|
||||
): void;
|
||||
export function lookup(
|
||||
hostname: string,
|
||||
options: LookupOneOptions,
|
||||
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
|
||||
): void;
|
||||
export function lookup(
|
||||
hostname: string,
|
||||
options: LookupAllOptions,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void,
|
||||
): void;
|
||||
export function lookup(
|
||||
hostname: string,
|
||||
options: LookupOptions,
|
||||
callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void,
|
||||
): void;
|
||||
export function lookup(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void,
|
||||
): void;
|
||||
export namespace lookup {
|
||||
function __promisify__(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>;
|
||||
function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<LookupAddress>;
|
||||
function __promisify__(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>;
|
||||
}
|
||||
/**
|
||||
* Resolves the given `address` and `port` into a host name and service using
|
||||
* the operating system's underlying `getnameinfo` implementation.
|
||||
*
|
||||
* If `address` is not a valid IP address, a `TypeError` will be thrown.
|
||||
* The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown.
|
||||
*
|
||||
* On an error, `err` is an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object,
|
||||
* where `err.code` is the error code.
|
||||
*
|
||||
* ```js
|
||||
* import dns from 'node:dns';
|
||||
* dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
|
||||
* console.log(hostname, service);
|
||||
* // Prints: localhost ssh
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v20.x/api/util.html#utilpromisifyoriginal) ed
|
||||
* version, it returns a `Promise` for an `Object` with `hostname` and `service` properties.
|
||||
* @since v0.11.14
|
||||
*/
|
||||
export function lookupService(
|
||||
address: string,
|
||||
port: number,
|
||||
callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void,
|
||||
): void;
|
||||
export namespace lookupService {
|
||||
function __promisify__(
|
||||
address: string,
|
||||
port: number,
|
||||
): Promise<{
|
||||
hostname: string;
|
||||
service: string;
|
||||
}>;
|
||||
}
|
||||
export interface ResolveOptions {
|
||||
ttl: boolean;
|
||||
}
|
||||
export interface ResolveWithTtlOptions extends ResolveOptions {
|
||||
ttl: true;
|
||||
}
|
||||
export interface RecordWithTtl {
|
||||
address: string;
|
||||
ttl: number;
|
||||
}
|
||||
/** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */
|
||||
export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord;
|
||||
export interface AnyARecord extends RecordWithTtl {
|
||||
type: "A";
|
||||
}
|
||||
export interface AnyAaaaRecord extends RecordWithTtl {
|
||||
type: "AAAA";
|
||||
}
|
||||
export interface CaaRecord {
|
||||
critical: number;
|
||||
issue?: string | undefined;
|
||||
issuewild?: string | undefined;
|
||||
iodef?: string | undefined;
|
||||
contactemail?: string | undefined;
|
||||
contactphone?: string | undefined;
|
||||
}
|
||||
export interface AnyCaaRecord extends CaaRecord {
|
||||
type: "CAA";
|
||||
}
|
||||
export interface MxRecord {
|
||||
priority: number;
|
||||
exchange: string;
|
||||
}
|
||||
export interface AnyMxRecord extends MxRecord {
|
||||
type: "MX";
|
||||
}
|
||||
export interface NaptrRecord {
|
||||
flags: string;
|
||||
service: string;
|
||||
regexp: string;
|
||||
replacement: string;
|
||||
order: number;
|
||||
preference: number;
|
||||
}
|
||||
export interface AnyNaptrRecord extends NaptrRecord {
|
||||
type: "NAPTR";
|
||||
}
|
||||
export interface SoaRecord {
|
||||
nsname: string;
|
||||
hostmaster: string;
|
||||
serial: number;
|
||||
refresh: number;
|
||||
retry: number;
|
||||
expire: number;
|
||||
minttl: number;
|
||||
}
|
||||
export interface AnySoaRecord extends SoaRecord {
|
||||
type: "SOA";
|
||||
}
|
||||
export interface SrvRecord {
|
||||
priority: number;
|
||||
weight: number;
|
||||
port: number;
|
||||
name: string;
|
||||
}
|
||||
export interface AnySrvRecord extends SrvRecord {
|
||||
type: "SRV";
|
||||
}
|
||||
export interface AnyTxtRecord {
|
||||
type: "TXT";
|
||||
entries: string[];
|
||||
}
|
||||
export interface AnyNsRecord {
|
||||
type: "NS";
|
||||
value: string;
|
||||
}
|
||||
export interface AnyPtrRecord {
|
||||
type: "PTR";
|
||||
value: string;
|
||||
}
|
||||
export interface AnyCnameRecord {
|
||||
type: "CNAME";
|
||||
value: string;
|
||||
}
|
||||
export type AnyRecord =
|
||||
| AnyARecord
|
||||
| AnyAaaaRecord
|
||||
| AnyCaaRecord
|
||||
| AnyCnameRecord
|
||||
| AnyMxRecord
|
||||
| AnyNaptrRecord
|
||||
| AnyNsRecord
|
||||
| AnyPtrRecord
|
||||
| AnySoaRecord
|
||||
| AnySrvRecord
|
||||
| AnyTxtRecord;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array
|
||||
* of the resource records. The `callback` function has arguments `(err, records)`. When successful, `records` will be an array of resource
|
||||
* records. The type and structure of individual results varies based on `rrtype`:
|
||||
*
|
||||
* <omitted>
|
||||
*
|
||||
* On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object,
|
||||
* where `err.code` is one of the `DNS error codes`.
|
||||
* @since v0.1.27
|
||||
* @param hostname Host name to resolve.
|
||||
* @param [rrtype='A'] Resource record type.
|
||||
*/
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR",
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "ANY",
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "CAA",
|
||||
callback: (err: NodeJS.ErrnoException | null, address: CaaRecord[]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "MX",
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "NAPTR",
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "SOA",
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "SRV",
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: "TXT",
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void,
|
||||
): void;
|
||||
export function resolve(
|
||||
hostname: string,
|
||||
rrtype: string,
|
||||
callback: (
|
||||
err: NodeJS.ErrnoException | null,
|
||||
addresses:
|
||||
| string[]
|
||||
| CaaRecord[]
|
||||
| MxRecord[]
|
||||
| NaptrRecord[]
|
||||
| SoaRecord
|
||||
| SrvRecord[]
|
||||
| string[][]
|
||||
| AnyRecord[],
|
||||
) => void,
|
||||
): void;
|
||||
export namespace resolve {
|
||||
function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>;
|
||||
function __promisify__(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;
|
||||
function __promisify__(hostname: string, rrtype: "CAA"): Promise<CaaRecord[]>;
|
||||
function __promisify__(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;
|
||||
function __promisify__(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;
|
||||
function __promisify__(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
|
||||
function __promisify__(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;
|
||||
function __promisify__(hostname: string, rrtype: "TXT"): Promise<string[][]>;
|
||||
function __promisify__(
|
||||
hostname: string,
|
||||
rrtype: string,
|
||||
): Promise<
|
||||
| string[]
|
||||
| CaaRecord[]
|
||||
| MxRecord[]
|
||||
| NaptrRecord[]
|
||||
| SoaRecord
|
||||
| SrvRecord[]
|
||||
| string[][]
|
||||
| AnyRecord[]
|
||||
>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function
|
||||
* will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
|
||||
* @since v0.1.16
|
||||
* @param hostname Host name to resolve.
|
||||
*/
|
||||
export function resolve4(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
|
||||
): void;
|
||||
export function resolve4(
|
||||
hostname: string,
|
||||
options: ResolveWithTtlOptions,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void,
|
||||
): void;
|
||||
export function resolve4(
|
||||
hostname: string,
|
||||
options: ResolveOptions,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void,
|
||||
): void;
|
||||
export namespace resolve4 {
|
||||
function __promisify__(hostname: string): Promise<string[]>;
|
||||
function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
|
||||
function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. The `addresses` argument passed to the `callback` function
|
||||
* will contain an array of IPv6 addresses.
|
||||
* @since v0.1.16
|
||||
* @param hostname Host name to resolve.
|
||||
*/
|
||||
export function resolve6(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
|
||||
): void;
|
||||
export function resolve6(
|
||||
hostname: string,
|
||||
options: ResolveWithTtlOptions,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void,
|
||||
): void;
|
||||
export function resolve6(
|
||||
hostname: string,
|
||||
options: ResolveOptions,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void,
|
||||
): void;
|
||||
export namespace resolve6 {
|
||||
function __promisify__(hostname: string): Promise<string[]>;
|
||||
function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
|
||||
function __promisify__(hostname: string, options?: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The `addresses` argument passed to the `callback` function
|
||||
* will contain an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`).
|
||||
* @since v0.3.2
|
||||
*/
|
||||
export function resolveCname(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
|
||||
): void;
|
||||
export namespace resolveCname {
|
||||
function __promisify__(hostname: string): Promise<string[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve `CAA` records for the `hostname`. The `addresses` argument passed to the `callback` function
|
||||
* will contain an array of certification authority authorization records
|
||||
* available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`).
|
||||
* @since v15.0.0, v14.17.0
|
||||
*/
|
||||
export function resolveCaa(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void,
|
||||
): void;
|
||||
export namespace resolveCaa {
|
||||
function __promisify__(hostname: string): Promise<CaaRecord[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. The `addresses` argument passed to the `callback` function will
|
||||
* contain an array of objects containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`).
|
||||
* @since v0.1.27
|
||||
*/
|
||||
export function resolveMx(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void,
|
||||
): void;
|
||||
export namespace resolveMx {
|
||||
function __promisify__(hostname: string): Promise<MxRecord[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of
|
||||
* objects with the following properties:
|
||||
*
|
||||
* * `flags`
|
||||
* * `service`
|
||||
* * `regexp`
|
||||
* * `replacement`
|
||||
* * `order`
|
||||
* * `preference`
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* flags: 's',
|
||||
* service: 'SIP+D2U',
|
||||
* regexp: '',
|
||||
* replacement: '_sip._udp.example.com',
|
||||
* order: 30,
|
||||
* preference: 100
|
||||
* }
|
||||
* ```
|
||||
* @since v0.9.12
|
||||
*/
|
||||
export function resolveNaptr(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void,
|
||||
): void;
|
||||
export namespace resolveNaptr {
|
||||
function __promisify__(hostname: string): Promise<NaptrRecord[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. The `addresses` argument passed to the `callback` function will
|
||||
* contain an array of name server records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`).
|
||||
* @since v0.1.90
|
||||
*/
|
||||
export function resolveNs(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
|
||||
): void;
|
||||
export namespace resolveNs {
|
||||
function __promisify__(hostname: string): Promise<string[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will
|
||||
* be an array of strings containing the reply records.
|
||||
* @since v6.0.0
|
||||
*/
|
||||
export function resolvePtr(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
|
||||
): void;
|
||||
export namespace resolvePtr {
|
||||
function __promisify__(hostname: string): Promise<string[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve a start of authority record (`SOA` record) for
|
||||
* the `hostname`. The `address` argument passed to the `callback` function will
|
||||
* be an object with the following properties:
|
||||
*
|
||||
* * `nsname`
|
||||
* * `hostmaster`
|
||||
* * `serial`
|
||||
* * `refresh`
|
||||
* * `retry`
|
||||
* * `expire`
|
||||
* * `minttl`
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* nsname: 'ns.example.com',
|
||||
* hostmaster: 'root.example.com',
|
||||
* serial: 2013101809,
|
||||
* refresh: 10000,
|
||||
* retry: 2400,
|
||||
* expire: 604800,
|
||||
* minttl: 3600
|
||||
* }
|
||||
* ```
|
||||
* @since v0.11.10
|
||||
*/
|
||||
export function resolveSoa(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void,
|
||||
): void;
|
||||
export namespace resolveSoa {
|
||||
function __promisify__(hostname: string): Promise<SoaRecord>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. The `addresses` argument passed to the `callback` function will
|
||||
* be an array of objects with the following properties:
|
||||
*
|
||||
* * `priority`
|
||||
* * `weight`
|
||||
* * `port`
|
||||
* * `name`
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* priority: 10,
|
||||
* weight: 5,
|
||||
* port: 21223,
|
||||
* name: 'service.example.com'
|
||||
* }
|
||||
* ```
|
||||
* @since v0.1.27
|
||||
*/
|
||||
export function resolveSrv(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void,
|
||||
): void;
|
||||
export namespace resolveSrv {
|
||||
function __promisify__(hostname: string): Promise<SrvRecord[]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a
|
||||
* two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
|
||||
* one record. Depending on the use case, these could be either joined together or
|
||||
* treated separately.
|
||||
* @since v0.1.27
|
||||
*/
|
||||
export function resolveTxt(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void,
|
||||
): void;
|
||||
export namespace resolveTxt {
|
||||
function __promisify__(hostname: string): Promise<string[][]>;
|
||||
}
|
||||
/**
|
||||
* Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query).
|
||||
* The `ret` argument passed to the `callback` function will be an array containing
|
||||
* various types of records. Each object has a property `type` that indicates the
|
||||
* type of the current record. And depending on the `type`, additional properties
|
||||
* will be present on the object:
|
||||
*
|
||||
* <omitted>
|
||||
*
|
||||
* Here is an example of the `ret` object passed to the callback:
|
||||
*
|
||||
* ```js
|
||||
* [ { type: 'A', address: '127.0.0.1', ttl: 299 },
|
||||
* { type: 'CNAME', value: 'example.com' },
|
||||
* { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
|
||||
* { type: 'NS', value: 'ns1.example.com' },
|
||||
* { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
|
||||
* { type: 'SOA',
|
||||
* nsname: 'ns1.example.com',
|
||||
* hostmaster: 'admin.example.com',
|
||||
* serial: 156696742,
|
||||
* refresh: 900,
|
||||
* retry: 900,
|
||||
* expire: 1800,
|
||||
* minttl: 60 } ]
|
||||
* ```
|
||||
*
|
||||
* DNS server operators may choose not to respond to `ANY` queries. It may be better to call individual methods like {@link resolve4}, {@link resolveMx}, and so on. For more details, see
|
||||
* [RFC 8482](https://tools.ietf.org/html/rfc8482).
|
||||
*/
|
||||
export function resolveAny(
|
||||
hostname: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void,
|
||||
): void;
|
||||
export namespace resolveAny {
|
||||
function __promisify__(hostname: string): Promise<AnyRecord[]>;
|
||||
}
|
||||
/**
|
||||
* Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
|
||||
* array of host names.
|
||||
*
|
||||
* On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is
|
||||
* one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes).
|
||||
* @since v0.1.16
|
||||
*/
|
||||
export function reverse(
|
||||
ip: string,
|
||||
callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void,
|
||||
): void;
|
||||
/**
|
||||
* Get the default value for `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options).
|
||||
* The value could be:
|
||||
*
|
||||
* * `ipv4first`: for `order` defaulting to `ipv4first`.
|
||||
* * `ipv6first`: for `order` defaulting to `ipv6first`.
|
||||
* * `verbatim`: for `order` defaulting to `verbatim`.
|
||||
* @since v18.17.0
|
||||
*/
|
||||
export function getDefaultResultOrder(): "ipv4first" | "ipv6first" | "verbatim";
|
||||
/**
|
||||
* Sets the IP address and port of servers to be used when performing DNS
|
||||
* resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted
|
||||
* addresses. If the port is the IANA default DNS port (53) it can be omitted.
|
||||
*
|
||||
* ```js
|
||||
* dns.setServers([
|
||||
* '4.4.4.4',
|
||||
* '[2001:4860:4860::8888]',
|
||||
* '4.4.4.4:1053',
|
||||
* '[2001:4860:4860::8888]:1053',
|
||||
* ]);
|
||||
* ```
|
||||
*
|
||||
* An error will be thrown if an invalid address is provided.
|
||||
*
|
||||
* The `dns.setServers()` method must not be called while a DNS query is in
|
||||
* progress.
|
||||
*
|
||||
* The {@link setServers} method affects only {@link resolve}, `dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}).
|
||||
*
|
||||
* This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html).
|
||||
* That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with
|
||||
* subsequent servers provided. Fallback DNS servers will only be used if the
|
||||
* earlier ones time out or result in some other error.
|
||||
* @since v0.11.3
|
||||
* @param servers array of [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952#section-6) formatted addresses
|
||||
*/
|
||||
export function setServers(servers: readonly string[]): void;
|
||||
/**
|
||||
* Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6),
|
||||
* that are currently configured for DNS resolution. A string will include a port
|
||||
* section if a custom port is used.
|
||||
*
|
||||
* ```js
|
||||
* [
|
||||
* '4.4.4.4',
|
||||
* '2001:4860:4860::8888',
|
||||
* '4.4.4.4:1053',
|
||||
* '[2001:4860:4860::8888]:1053',
|
||||
* ]
|
||||
* ```
|
||||
* @since v0.11.3
|
||||
*/
|
||||
export function getServers(): string[];
|
||||
/**
|
||||
* Set the default value of `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options).
|
||||
* The value could be:
|
||||
*
|
||||
* * `ipv4first`: sets default `order` to `ipv4first`.
|
||||
* * `ipv6first`: sets default `order` to `ipv6first`.
|
||||
* * `verbatim`: sets default `order` to `verbatim`.
|
||||
*
|
||||
* The default is `verbatim` and {@link setDefaultResultOrder} have higher
|
||||
* priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). When using
|
||||
* [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), {@link setDefaultResultOrder} from the main
|
||||
* thread won't affect the default dns orders in workers.
|
||||
* @since v16.4.0, v14.18.0
|
||||
* @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`.
|
||||
*/
|
||||
export function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void;
|
||||
// Error codes
|
||||
export const NODATA: "ENODATA";
|
||||
export const FORMERR: "EFORMERR";
|
||||
export const SERVFAIL: "ESERVFAIL";
|
||||
export const NOTFOUND: "ENOTFOUND";
|
||||
export const NOTIMP: "ENOTIMP";
|
||||
export const REFUSED: "EREFUSED";
|
||||
export const BADQUERY: "EBADQUERY";
|
||||
export const BADNAME: "EBADNAME";
|
||||
export const BADFAMILY: "EBADFAMILY";
|
||||
export const BADRESP: "EBADRESP";
|
||||
export const CONNREFUSED: "ECONNREFUSED";
|
||||
export const TIMEOUT: "ETIMEOUT";
|
||||
export const EOF: "EOF";
|
||||
export const FILE: "EFILE";
|
||||
export const NOMEM: "ENOMEM";
|
||||
export const DESTRUCTION: "EDESTRUCTION";
|
||||
export const BADSTR: "EBADSTR";
|
||||
export const BADFLAGS: "EBADFLAGS";
|
||||
export const NONAME: "ENONAME";
|
||||
export const BADHINTS: "EBADHINTS";
|
||||
export const NOTINITIALIZED: "ENOTINITIALIZED";
|
||||
export const LOADIPHLPAPI: "ELOADIPHLPAPI";
|
||||
export const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS";
|
||||
export const CANCELLED: "ECANCELLED";
|
||||
export interface ResolverOptions {
|
||||
/**
|
||||
* Query timeout in milliseconds, or `-1` to use the default timeout.
|
||||
*/
|
||||
timeout?: number | undefined;
|
||||
/**
|
||||
* The number of tries the resolver will try contacting each name server before giving up.
|
||||
* @default 4
|
||||
*/
|
||||
tries?: number;
|
||||
}
|
||||
/**
|
||||
* An independent resolver for DNS requests.
|
||||
*
|
||||
* Creating a new resolver uses the default server settings. Setting
|
||||
* the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnssetserversservers) does not affect
|
||||
* other resolvers:
|
||||
*
|
||||
* ```js
|
||||
* import { Resolver } from 'node:dns';
|
||||
* const resolver = new Resolver();
|
||||
* resolver.setServers(['4.4.4.4']);
|
||||
*
|
||||
* // This request will use the server at 4.4.4.4, independent of global settings.
|
||||
* resolver.resolve4('example.org', (err, addresses) => {
|
||||
* // ...
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* The following methods from the `node:dns` module are available:
|
||||
*
|
||||
* * `resolver.getServers()`
|
||||
* * `resolver.resolve()`
|
||||
* * `resolver.resolve4()`
|
||||
* * `resolver.resolve6()`
|
||||
* * `resolver.resolveAny()`
|
||||
* * `resolver.resolveCaa()`
|
||||
* * `resolver.resolveCname()`
|
||||
* * `resolver.resolveMx()`
|
||||
* * `resolver.resolveNaptr()`
|
||||
* * `resolver.resolveNs()`
|
||||
* * `resolver.resolvePtr()`
|
||||
* * `resolver.resolveSoa()`
|
||||
* * `resolver.resolveSrv()`
|
||||
* * `resolver.resolveTxt()`
|
||||
* * `resolver.reverse()`
|
||||
* * `resolver.setServers()`
|
||||
* @since v8.3.0
|
||||
*/
|
||||
export class Resolver {
|
||||
constructor(options?: ResolverOptions);
|
||||
/**
|
||||
* Cancel all outstanding DNS queries made by this resolver. The corresponding
|
||||
* callbacks will be called with an error with code `ECANCELLED`.
|
||||
* @since v8.3.0
|
||||
*/
|
||||
cancel(): void;
|
||||
getServers: typeof getServers;
|
||||
resolve: typeof resolve;
|
||||
resolve4: typeof resolve4;
|
||||
resolve6: typeof resolve6;
|
||||
resolveAny: typeof resolveAny;
|
||||
resolveCaa: typeof resolveCaa;
|
||||
resolveCname: typeof resolveCname;
|
||||
resolveMx: typeof resolveMx;
|
||||
resolveNaptr: typeof resolveNaptr;
|
||||
resolveNs: typeof resolveNs;
|
||||
resolvePtr: typeof resolvePtr;
|
||||
resolveSoa: typeof resolveSoa;
|
||||
resolveSrv: typeof resolveSrv;
|
||||
resolveTxt: typeof resolveTxt;
|
||||
reverse: typeof reverse;
|
||||
/**
|
||||
* The resolver instance will send its requests from the specified IP address.
|
||||
* This allows programs to specify outbound interfaces when used on multi-homed
|
||||
* systems.
|
||||
*
|
||||
* If a v4 or v6 address is not specified, it is set to the default and the
|
||||
* operating system will choose a local address automatically.
|
||||
*
|
||||
* The resolver will use the v4 local address when making requests to IPv4 DNS
|
||||
* servers, and the v6 local address when making requests to IPv6 DNS servers.
|
||||
* The `rrtype` of resolution requests has no impact on the local address used.
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param [ipv4='0.0.0.0'] A string representation of an IPv4 address.
|
||||
* @param [ipv6='::0'] A string representation of an IPv6 address.
|
||||
*/
|
||||
setLocalAddress(ipv4?: string, ipv6?: string): void;
|
||||
setServers: typeof setServers;
|
||||
}
|
||||
export { dnsPromises as promises };
|
||||
}
|
||||
declare module "node:dns" {
|
||||
export * from "dns";
|
||||
}
|
||||
479
frontend/e2e/node_modules/@types/node/dns/promises.d.ts
generated
vendored
Normal file
479
frontend/e2e/node_modules/@types/node/dns/promises.d.ts
generated
vendored
Normal file
@@ -0,0 +1,479 @@
|
||||
/**
|
||||
* The `dns.promises` API provides an alternative set of asynchronous DNS methods
|
||||
* that return `Promise` objects rather than using callbacks. The API is accessible
|
||||
* via `import { promises } from 'node:dns'` or `import dnsPromises from 'node:dns/promises'`.
|
||||
* @since v10.6.0
|
||||
*/
|
||||
declare module "dns/promises" {
|
||||
import {
|
||||
AnyRecord,
|
||||
CaaRecord,
|
||||
LookupAddress,
|
||||
LookupAllOptions,
|
||||
LookupOneOptions,
|
||||
LookupOptions,
|
||||
MxRecord,
|
||||
NaptrRecord,
|
||||
RecordWithTtl,
|
||||
ResolveOptions,
|
||||
ResolverOptions,
|
||||
ResolveWithTtlOptions,
|
||||
SoaRecord,
|
||||
SrvRecord,
|
||||
} from "node:dns";
|
||||
/**
|
||||
* Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6),
|
||||
* that are currently configured for DNS resolution. A string will include a port
|
||||
* section if a custom port is used.
|
||||
*
|
||||
* ```js
|
||||
* [
|
||||
* '4.4.4.4',
|
||||
* '2001:4860:4860::8888',
|
||||
* '4.4.4.4:1053',
|
||||
* '[2001:4860:4860::8888]:1053',
|
||||
* ]
|
||||
* ```
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function getServers(): string[];
|
||||
/**
|
||||
* Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or
|
||||
* AAAA (IPv6) record. All `option` properties are optional. If `options` is an
|
||||
* integer, then it must be `4` or `6` – if `options` is not provided, then IPv4
|
||||
* and IPv6 addresses are both returned if found.
|
||||
*
|
||||
* With the `all` option set to `true`, the `Promise` is resolved with `addresses` being an array of objects with the properties `address` and `family`.
|
||||
*
|
||||
* On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code.
|
||||
* Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when
|
||||
* the host name does not exist but also when the lookup fails in other ways
|
||||
* such as no available file descriptors.
|
||||
*
|
||||
* [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options) does not necessarily have anything to do with the DNS
|
||||
* protocol. The implementation uses an operating system facility that can
|
||||
* associate names with addresses and vice versa. This implementation can have
|
||||
* subtle but important consequences on the behavior of any Node.js program. Please
|
||||
* take some time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) before
|
||||
* using `dnsPromises.lookup()`.
|
||||
*
|
||||
* Example usage:
|
||||
*
|
||||
* ```js
|
||||
* import dns from 'node:dns';
|
||||
* const dnsPromises = dns.promises;
|
||||
* const options = {
|
||||
* family: 6,
|
||||
* hints: dns.ADDRCONFIG | dns.V4MAPPED,
|
||||
* };
|
||||
*
|
||||
* dnsPromises.lookup('example.com', options).then((result) => {
|
||||
* console.log('address: %j family: IPv%s', result.address, result.family);
|
||||
* // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
|
||||
* });
|
||||
*
|
||||
* // When options.all is true, the result will be an Array.
|
||||
* options.all = true;
|
||||
* dnsPromises.lookup('example.com', options).then((result) => {
|
||||
* console.log('addresses: %j', result);
|
||||
* // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
|
||||
* });
|
||||
* ```
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function lookup(hostname: string, family: number): Promise<LookupAddress>;
|
||||
function lookup(hostname: string, options: LookupOneOptions): Promise<LookupAddress>;
|
||||
function lookup(hostname: string, options: LookupAllOptions): Promise<LookupAddress[]>;
|
||||
function lookup(hostname: string, options: LookupOptions): Promise<LookupAddress | LookupAddress[]>;
|
||||
function lookup(hostname: string): Promise<LookupAddress>;
|
||||
/**
|
||||
* Resolves the given `address` and `port` into a host name and service using
|
||||
* the operating system's underlying `getnameinfo` implementation.
|
||||
*
|
||||
* If `address` is not a valid IP address, a `TypeError` will be thrown.
|
||||
* The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown.
|
||||
*
|
||||
* On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code.
|
||||
*
|
||||
* ```js
|
||||
* import dns from 'node:dns';
|
||||
* dns.promises.lookupService('127.0.0.1', 22).then((result) => {
|
||||
* console.log(result.hostname, result.service);
|
||||
* // Prints: localhost ssh
|
||||
* });
|
||||
* ```
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function lookupService(
|
||||
address: string,
|
||||
port: number,
|
||||
): Promise<{
|
||||
hostname: string;
|
||||
service: string;
|
||||
}>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array
|
||||
* of the resource records. When successful, the `Promise` is resolved with an
|
||||
* array of resource records. The type and structure of individual results vary
|
||||
* based on `rrtype`:
|
||||
*
|
||||
* <omitted>
|
||||
*
|
||||
* On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code`
|
||||
* is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes).
|
||||
* @since v10.6.0
|
||||
* @param hostname Host name to resolve.
|
||||
* @param [rrtype='A'] Resource record type.
|
||||
*/
|
||||
function resolve(hostname: string): Promise<string[]>;
|
||||
function resolve(hostname: string, rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>;
|
||||
function resolve(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;
|
||||
function resolve(hostname: string, rrtype: "CAA"): Promise<CaaRecord[]>;
|
||||
function resolve(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;
|
||||
function resolve(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;
|
||||
function resolve(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
|
||||
function resolve(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;
|
||||
function resolve(hostname: string, rrtype: "TXT"): Promise<string[][]>;
|
||||
function resolve(hostname: string, rrtype: string): Promise<
|
||||
| string[]
|
||||
| CaaRecord[]
|
||||
| MxRecord[]
|
||||
| NaptrRecord[]
|
||||
| SoaRecord
|
||||
| SrvRecord[]
|
||||
| string[][]
|
||||
| AnyRecord[]
|
||||
>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4
|
||||
* addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
|
||||
* @since v10.6.0
|
||||
* @param hostname Host name to resolve.
|
||||
*/
|
||||
function resolve4(hostname: string): Promise<string[]>;
|
||||
function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
|
||||
function resolve4(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv6
|
||||
* addresses.
|
||||
* @since v10.6.0
|
||||
* @param hostname Host name to resolve.
|
||||
*/
|
||||
function resolve6(hostname: string): Promise<string[]>;
|
||||
function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise<RecordWithTtl[]>;
|
||||
function resolve6(hostname: string, options: ResolveOptions): Promise<string[] | RecordWithTtl[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query).
|
||||
* On success, the `Promise` is resolved with an array containing various types of
|
||||
* records. Each object has a property `type` that indicates the type of the
|
||||
* current record. And depending on the `type`, additional properties will be
|
||||
* present on the object:
|
||||
*
|
||||
* <omitted>
|
||||
*
|
||||
* Here is an example of the result object:
|
||||
*
|
||||
* ```js
|
||||
* [ { type: 'A', address: '127.0.0.1', ttl: 299 },
|
||||
* { type: 'CNAME', value: 'example.com' },
|
||||
* { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 },
|
||||
* { type: 'NS', value: 'ns1.example.com' },
|
||||
* { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] },
|
||||
* { type: 'SOA',
|
||||
* nsname: 'ns1.example.com',
|
||||
* hostmaster: 'admin.example.com',
|
||||
* serial: 156696742,
|
||||
* refresh: 900,
|
||||
* retry: 900,
|
||||
* expire: 1800,
|
||||
* minttl: 60 } ]
|
||||
* ```
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolveAny(hostname: string): Promise<AnyRecord[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success,
|
||||
* the `Promise` is resolved with an array of objects containing available
|
||||
* certification authority authorization records available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`).
|
||||
* @since v15.0.0, v14.17.0
|
||||
*/
|
||||
function resolveCaa(hostname: string): Promise<CaaRecord[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success,
|
||||
* the `Promise` is resolved with an array of canonical name records available for
|
||||
* the `hostname` (e.g. `['bar.example.com']`).
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolveCname(hostname: string): Promise<string[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects
|
||||
* containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`).
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolveMx(hostname: string): Promise<MxRecord[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. On success, the `Promise` is resolved with an array
|
||||
* of objects with the following properties:
|
||||
*
|
||||
* * `flags`
|
||||
* * `service`
|
||||
* * `regexp`
|
||||
* * `replacement`
|
||||
* * `order`
|
||||
* * `preference`
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* flags: 's',
|
||||
* service: 'SIP+D2U',
|
||||
* regexp: '',
|
||||
* replacement: '_sip._udp.example.com',
|
||||
* order: 30,
|
||||
* preference: 100
|
||||
* }
|
||||
* ```
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolveNaptr(hostname: string): Promise<NaptrRecord[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. On success, the `Promise` is resolved with an array of name server
|
||||
* records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`).
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolveNs(hostname: string): Promise<string[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. On success, the `Promise` is resolved with an array of strings
|
||||
* containing the reply records.
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolvePtr(hostname: string): Promise<string[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve a start of authority record (`SOA` record) for
|
||||
* the `hostname`. On success, the `Promise` is resolved with an object with the
|
||||
* following properties:
|
||||
*
|
||||
* * `nsname`
|
||||
* * `hostmaster`
|
||||
* * `serial`
|
||||
* * `refresh`
|
||||
* * `retry`
|
||||
* * `expire`
|
||||
* * `minttl`
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* nsname: 'ns.example.com',
|
||||
* hostmaster: 'root.example.com',
|
||||
* serial: 2013101809,
|
||||
* refresh: 10000,
|
||||
* retry: 2400,
|
||||
* expire: 604800,
|
||||
* minttl: 3600
|
||||
* }
|
||||
* ```
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolveSoa(hostname: string): Promise<SoaRecord>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects with
|
||||
* the following properties:
|
||||
*
|
||||
* * `priority`
|
||||
* * `weight`
|
||||
* * `port`
|
||||
* * `name`
|
||||
*
|
||||
* ```js
|
||||
* {
|
||||
* priority: 10,
|
||||
* weight: 5,
|
||||
* port: 21223,
|
||||
* name: 'service.example.com'
|
||||
* }
|
||||
* ```
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolveSrv(hostname: string): Promise<SrvRecord[]>;
|
||||
/**
|
||||
* Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array
|
||||
* of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
|
||||
* one record. Depending on the use case, these could be either joined together or
|
||||
* treated separately.
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function resolveTxt(hostname: string): Promise<string[][]>;
|
||||
/**
|
||||
* Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
|
||||
* array of host names.
|
||||
*
|
||||
* On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code`
|
||||
* is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes).
|
||||
* @since v10.6.0
|
||||
*/
|
||||
function reverse(ip: string): Promise<string[]>;
|
||||
/**
|
||||
* Get the default value for `verbatim` in {@link lookup} and [dnsPromises.lookup()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options).
|
||||
* The value could be:
|
||||
*
|
||||
* * `ipv4first`: for `verbatim` defaulting to `false`.
|
||||
* * `verbatim`: for `verbatim` defaulting to `true`.
|
||||
* @since v20.1.0
|
||||
*/
|
||||
function getDefaultResultOrder(): "ipv4first" | "verbatim";
|
||||
/**
|
||||
* Sets the IP address and port of servers to be used when performing DNS
|
||||
* resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted
|
||||
* addresses. If the port is the IANA default DNS port (53) it can be omitted.
|
||||
*
|
||||
* ```js
|
||||
* dnsPromises.setServers([
|
||||
* '4.4.4.4',
|
||||
* '[2001:4860:4860::8888]',
|
||||
* '4.4.4.4:1053',
|
||||
* '[2001:4860:4860::8888]:1053',
|
||||
* ]);
|
||||
* ```
|
||||
*
|
||||
* An error will be thrown if an invalid address is provided.
|
||||
*
|
||||
* The `dnsPromises.setServers()` method must not be called while a DNS query is in
|
||||
* progress.
|
||||
*
|
||||
* This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html).
|
||||
* That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with
|
||||
* subsequent servers provided. Fallback DNS servers will only be used if the
|
||||
* earlier ones time out or result in some other error.
|
||||
* @since v10.6.0
|
||||
* @param servers array of `RFC 5952` formatted addresses
|
||||
*/
|
||||
function setServers(servers: readonly string[]): void;
|
||||
/**
|
||||
* Set the default value of `order` in `dns.lookup()` and `{@link lookup}`. The value could be:
|
||||
*
|
||||
* * `ipv4first`: sets default `order` to `ipv4first`.
|
||||
* * `ipv6first`: sets default `order` to `ipv6first`.
|
||||
* * `verbatim`: sets default `order` to `verbatim`.
|
||||
*
|
||||
* The default is `verbatim` and [dnsPromises.setDefaultResultOrder()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder)
|
||||
* have higher priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder).
|
||||
* When using [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), [`dnsPromises.setDefaultResultOrder()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder)
|
||||
* from the main thread won't affect the default dns orders in workers.
|
||||
* @since v16.4.0, v14.18.0
|
||||
* @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`.
|
||||
*/
|
||||
function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void;
|
||||
// Error codes
|
||||
const NODATA: "ENODATA";
|
||||
const FORMERR: "EFORMERR";
|
||||
const SERVFAIL: "ESERVFAIL";
|
||||
const NOTFOUND: "ENOTFOUND";
|
||||
const NOTIMP: "ENOTIMP";
|
||||
const REFUSED: "EREFUSED";
|
||||
const BADQUERY: "EBADQUERY";
|
||||
const BADNAME: "EBADNAME";
|
||||
const BADFAMILY: "EBADFAMILY";
|
||||
const BADRESP: "EBADRESP";
|
||||
const CONNREFUSED: "ECONNREFUSED";
|
||||
const TIMEOUT: "ETIMEOUT";
|
||||
const EOF: "EOF";
|
||||
const FILE: "EFILE";
|
||||
const NOMEM: "ENOMEM";
|
||||
const DESTRUCTION: "EDESTRUCTION";
|
||||
const BADSTR: "EBADSTR";
|
||||
const BADFLAGS: "EBADFLAGS";
|
||||
const NONAME: "ENONAME";
|
||||
const BADHINTS: "EBADHINTS";
|
||||
const NOTINITIALIZED: "ENOTINITIALIZED";
|
||||
const LOADIPHLPAPI: "ELOADIPHLPAPI";
|
||||
const ADDRGETNETWORKPARAMS: "EADDRGETNETWORKPARAMS";
|
||||
const CANCELLED: "ECANCELLED";
|
||||
|
||||
/**
|
||||
* An independent resolver for DNS requests.
|
||||
*
|
||||
* Creating a new resolver uses the default server settings. Setting
|
||||
* the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetserversservers) does not affect
|
||||
* other resolvers:
|
||||
*
|
||||
* ```js
|
||||
* import dns from 'node:dns';
|
||||
* const { Resolver } = dns.promises;
|
||||
* const resolver = new Resolver();
|
||||
* resolver.setServers(['4.4.4.4']);
|
||||
*
|
||||
* // This request will use the server at 4.4.4.4, independent of global settings.
|
||||
* resolver.resolve4('example.org').then((addresses) => {
|
||||
* // ...
|
||||
* });
|
||||
*
|
||||
* // Alternatively, the same code can be written using async-await style.
|
||||
* (async function() {
|
||||
* const addresses = await resolver.resolve4('example.org');
|
||||
* })();
|
||||
* ```
|
||||
*
|
||||
* The following methods from the `dnsPromises` API are available:
|
||||
*
|
||||
* * `resolver.getServers()`
|
||||
* * `resolver.resolve()`
|
||||
* * `resolver.resolve4()`
|
||||
* * `resolver.resolve6()`
|
||||
* * `resolver.resolveAny()`
|
||||
* * `resolver.resolveCaa()`
|
||||
* * `resolver.resolveCname()`
|
||||
* * `resolver.resolveMx()`
|
||||
* * `resolver.resolveNaptr()`
|
||||
* * `resolver.resolveNs()`
|
||||
* * `resolver.resolvePtr()`
|
||||
* * `resolver.resolveSoa()`
|
||||
* * `resolver.resolveSrv()`
|
||||
* * `resolver.resolveTxt()`
|
||||
* * `resolver.reverse()`
|
||||
* * `resolver.setServers()`
|
||||
* @since v10.6.0
|
||||
*/
|
||||
class Resolver {
|
||||
constructor(options?: ResolverOptions);
|
||||
/**
|
||||
* Cancel all outstanding DNS queries made by this resolver. The corresponding
|
||||
* callbacks will be called with an error with code `ECANCELLED`.
|
||||
* @since v8.3.0
|
||||
*/
|
||||
cancel(): void;
|
||||
getServers: typeof getServers;
|
||||
resolve: typeof resolve;
|
||||
resolve4: typeof resolve4;
|
||||
resolve6: typeof resolve6;
|
||||
resolveAny: typeof resolveAny;
|
||||
resolveCaa: typeof resolveCaa;
|
||||
resolveCname: typeof resolveCname;
|
||||
resolveMx: typeof resolveMx;
|
||||
resolveNaptr: typeof resolveNaptr;
|
||||
resolveNs: typeof resolveNs;
|
||||
resolvePtr: typeof resolvePtr;
|
||||
resolveSoa: typeof resolveSoa;
|
||||
resolveSrv: typeof resolveSrv;
|
||||
resolveTxt: typeof resolveTxt;
|
||||
reverse: typeof reverse;
|
||||
/**
|
||||
* The resolver instance will send its requests from the specified IP address.
|
||||
* This allows programs to specify outbound interfaces when used on multi-homed
|
||||
* systems.
|
||||
*
|
||||
* If a v4 or v6 address is not specified, it is set to the default and the
|
||||
* operating system will choose a local address automatically.
|
||||
*
|
||||
* The resolver will use the v4 local address when making requests to IPv4 DNS
|
||||
* servers, and the v6 local address when making requests to IPv6 DNS servers.
|
||||
* The `rrtype` of resolution requests has no impact on the local address used.
|
||||
* @since v15.1.0, v14.17.0
|
||||
* @param [ipv4='0.0.0.0'] A string representation of an IPv4 address.
|
||||
* @param [ipv6='::0'] A string representation of an IPv6 address.
|
||||
*/
|
||||
setLocalAddress(ipv4?: string, ipv6?: string): void;
|
||||
setServers: typeof setServers;
|
||||
}
|
||||
}
|
||||
declare module "node:dns/promises" {
|
||||
export * from "dns/promises";
|
||||
}
|
||||
170
frontend/e2e/node_modules/@types/node/domain.d.ts
generated
vendored
Normal file
170
frontend/e2e/node_modules/@types/node/domain.d.ts
generated
vendored
Normal file
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* **This module is pending deprecation.** Once a replacement API has been
|
||||
* finalized, this module will be fully deprecated. Most developers should
|
||||
* **not** have cause to use this module. Users who absolutely must have
|
||||
* the functionality that domains provide may rely on it for the time being
|
||||
* but should expect to have to migrate to a different solution
|
||||
* in the future.
|
||||
*
|
||||
* Domains provide a way to handle multiple different IO operations as a
|
||||
* single group. If any of the event emitters or callbacks registered to a
|
||||
* domain emit an `'error'` event, or throw an error, then the domain object
|
||||
* will be notified, rather than losing the context of the error in the `process.on('uncaughtException')` handler, or causing the program to
|
||||
* exit immediately with an error code.
|
||||
* @deprecated Since v1.4.2 - Deprecated
|
||||
* @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/domain.js)
|
||||
*/
|
||||
declare module "domain" {
|
||||
import EventEmitter = require("node:events");
|
||||
/**
|
||||
* The `Domain` class encapsulates the functionality of routing errors and
|
||||
* uncaught exceptions to the active `Domain` object.
|
||||
*
|
||||
* To handle the errors that it catches, listen to its `'error'` event.
|
||||
*/
|
||||
class Domain extends EventEmitter {
|
||||
/**
|
||||
* An array of timers and event emitters that have been explicitly added
|
||||
* to the domain.
|
||||
*/
|
||||
members: Array<EventEmitter | NodeJS.Timer>;
|
||||
/**
|
||||
* The `enter()` method is plumbing used by the `run()`, `bind()`, and `intercept()` methods to set the active domain. It sets `domain.active` and `process.domain` to the domain, and implicitly
|
||||
* pushes the domain onto the domain
|
||||
* stack managed by the domain module (see {@link exit} for details on the
|
||||
* domain stack). The call to `enter()` delimits the beginning of a chain of
|
||||
* asynchronous calls and I/O operations bound to a domain.
|
||||
*
|
||||
* Calling `enter()` changes only the active domain, and does not alter the domain
|
||||
* itself. `enter()` and `exit()` can be called an arbitrary number of times on a
|
||||
* single domain.
|
||||
*/
|
||||
enter(): void;
|
||||
/**
|
||||
* The `exit()` method exits the current domain, popping it off the domain stack.
|
||||
* Any time execution is going to switch to the context of a different chain of
|
||||
* asynchronous calls, it's important to ensure that the current domain is exited.
|
||||
* The call to `exit()` delimits either the end of or an interruption to the chain
|
||||
* of asynchronous calls and I/O operations bound to a domain.
|
||||
*
|
||||
* If there are multiple, nested domains bound to the current execution context, `exit()` will exit any domains nested within this domain.
|
||||
*
|
||||
* Calling `exit()` changes only the active domain, and does not alter the domain
|
||||
* itself. `enter()` and `exit()` can be called an arbitrary number of times on a
|
||||
* single domain.
|
||||
*/
|
||||
exit(): void;
|
||||
/**
|
||||
* Run the supplied function in the context of the domain, implicitly
|
||||
* binding all event emitters, timers, and low-level requests that are
|
||||
* created in that context. Optionally, arguments can be passed to
|
||||
* the function.
|
||||
*
|
||||
* This is the most basic way to use a domain.
|
||||
*
|
||||
* ```js
|
||||
* import domain from 'node:domain';
|
||||
* import fs from 'node:fs';
|
||||
* const d = domain.create();
|
||||
* d.on('error', (er) => {
|
||||
* console.error('Caught error!', er);
|
||||
* });
|
||||
* d.run(() => {
|
||||
* process.nextTick(() => {
|
||||
* setTimeout(() => { // Simulating some various async stuff
|
||||
* fs.open('non-existent file', 'r', (er, fd) => {
|
||||
* if (er) throw er;
|
||||
* // proceed...
|
||||
* });
|
||||
* }, 100);
|
||||
* });
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* In this example, the `d.on('error')` handler will be triggered, rather
|
||||
* than crashing the program.
|
||||
*/
|
||||
run<T>(fn: (...args: any[]) => T, ...args: any[]): T;
|
||||
/**
|
||||
* Explicitly adds an emitter to the domain. If any event handlers called by
|
||||
* the emitter throw an error, or if the emitter emits an `'error'` event, it
|
||||
* will be routed to the domain's `'error'` event, just like with implicit
|
||||
* binding.
|
||||
*
|
||||
* This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by
|
||||
* the domain `'error'` handler.
|
||||
*
|
||||
* If the Timer or `EventEmitter` was already bound to a domain, it is removed
|
||||
* from that one, and bound to this one instead.
|
||||
* @param emitter emitter or timer to be added to the domain
|
||||
*/
|
||||
add(emitter: EventEmitter | NodeJS.Timer): void;
|
||||
/**
|
||||
* The opposite of {@link add}. Removes domain handling from the
|
||||
* specified emitter.
|
||||
* @param emitter emitter or timer to be removed from the domain
|
||||
*/
|
||||
remove(emitter: EventEmitter | NodeJS.Timer): void;
|
||||
/**
|
||||
* The returned function will be a wrapper around the supplied callback
|
||||
* function. When the returned function is called, any errors that are
|
||||
* thrown will be routed to the domain's `'error'` event.
|
||||
*
|
||||
* ```js
|
||||
* const d = domain.create();
|
||||
*
|
||||
* function readSomeFile(filename, cb) {
|
||||
* fs.readFile(filename, 'utf8', d.bind((er, data) => {
|
||||
* // If this throws, it will also be passed to the domain.
|
||||
* return cb(er, data ? JSON.parse(data) : null);
|
||||
* }));
|
||||
* }
|
||||
*
|
||||
* d.on('error', (er) => {
|
||||
* // An error occurred somewhere. If we throw it now, it will crash the program
|
||||
* // with the normal line number and stack message.
|
||||
* });
|
||||
* ```
|
||||
* @param callback The callback function
|
||||
* @return The bound function
|
||||
*/
|
||||
bind<T extends Function>(callback: T): T;
|
||||
/**
|
||||
* This method is almost identical to {@link bind}. However, in
|
||||
* addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function.
|
||||
*
|
||||
* In this way, the common `if (err) return callback(err);` pattern can be replaced
|
||||
* with a single error handler in a single place.
|
||||
*
|
||||
* ```js
|
||||
* const d = domain.create();
|
||||
*
|
||||
* function readSomeFile(filename, cb) {
|
||||
* fs.readFile(filename, 'utf8', d.intercept((data) => {
|
||||
* // Note, the first argument is never passed to the
|
||||
* // callback since it is assumed to be the 'Error' argument
|
||||
* // and thus intercepted by the domain.
|
||||
*
|
||||
* // If this throws, it will also be passed to the domain
|
||||
* // so the error-handling logic can be moved to the 'error'
|
||||
* // event on the domain instead of being repeated throughout
|
||||
* // the program.
|
||||
* return cb(null, JSON.parse(data));
|
||||
* }));
|
||||
* }
|
||||
*
|
||||
* d.on('error', (er) => {
|
||||
* // An error occurred somewhere. If we throw it now, it will crash the program
|
||||
* // with the normal line number and stack message.
|
||||
* });
|
||||
* ```
|
||||
* @param callback The callback function
|
||||
* @return The intercepted function
|
||||
*/
|
||||
intercept<T extends Function>(callback: T): T;
|
||||
}
|
||||
function create(): Domain;
|
||||
}
|
||||
declare module "node:domain" {
|
||||
export * from "domain";
|
||||
}
|
||||
931
frontend/e2e/node_modules/@types/node/events.d.ts
generated
vendored
Normal file
931
frontend/e2e/node_modules/@types/node/events.d.ts
generated
vendored
Normal file
@@ -0,0 +1,931 @@
|
||||
/**
|
||||
* Much of the Node.js core API is built around an idiomatic asynchronous
|
||||
* event-driven architecture in which certain kinds of objects (called "emitters")
|
||||
* emit named events that cause `Function` objects ("listeners") to be called.
|
||||
*
|
||||
* For instance: a `net.Server` object emits an event each time a peer
|
||||
* connects to it; a `fs.ReadStream` emits an event when the file is opened;
|
||||
* a `stream` emits an event whenever data is available to be read.
|
||||
*
|
||||
* All objects that emit events are instances of the `EventEmitter` class. These
|
||||
* objects expose an `eventEmitter.on()` function that allows one or more
|
||||
* functions to be attached to named events emitted by the object. Typically,
|
||||
* event names are camel-cased strings but any valid JavaScript property key
|
||||
* can be used.
|
||||
*
|
||||
* When the `EventEmitter` object emits an event, all of the functions attached
|
||||
* to that specific event are called _synchronously_. Any values returned by the
|
||||
* called listeners are _ignored_ and discarded.
|
||||
*
|
||||
* The following example shows a simple `EventEmitter` instance with a single
|
||||
* listener. The `eventEmitter.on()` method is used to register listeners, while
|
||||
* the `eventEmitter.emit()` method is used to trigger the event.
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
*
|
||||
* class MyEmitter extends EventEmitter {}
|
||||
*
|
||||
* const myEmitter = new MyEmitter();
|
||||
* myEmitter.on('event', () => {
|
||||
* console.log('an event occurred!');
|
||||
* });
|
||||
* myEmitter.emit('event');
|
||||
* ```
|
||||
* @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/events.js)
|
||||
*/
|
||||
declare module "events" {
|
||||
import { AsyncResource, AsyncResourceOptions } from "node:async_hooks";
|
||||
// NOTE: This class is in the docs but is **not actually exported** by Node.
|
||||
// If https://github.com/nodejs/node/issues/39903 gets resolved and Node
|
||||
// actually starts exporting the class, uncomment below.
|
||||
// import { EventListener, EventListenerObject } from '__dom-events';
|
||||
// /** The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API. */
|
||||
// interface NodeEventTarget extends EventTarget {
|
||||
// /**
|
||||
// * Node.js-specific extension to the `EventTarget` class that emulates the equivalent `EventEmitter` API.
|
||||
// * The only difference between `addListener()` and `addEventListener()` is that addListener() will return a reference to the EventTarget.
|
||||
// */
|
||||
// addListener(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this;
|
||||
// /** Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. */
|
||||
// eventNames(): string[];
|
||||
// /** Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. */
|
||||
// listenerCount(type: string): number;
|
||||
// /** Node.js-specific alias for `eventTarget.removeListener()`. */
|
||||
// off(type: string, listener: EventListener | EventListenerObject): this;
|
||||
// /** Node.js-specific alias for `eventTarget.addListener()`. */
|
||||
// on(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this;
|
||||
// /** Node.js-specific extension to the `EventTarget` class that adds a `once` listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. */
|
||||
// once(type: string, listener: EventListener | EventListenerObject): this;
|
||||
// /**
|
||||
// * Node.js-specific extension to the `EventTarget` class.
|
||||
// * If `type` is specified, removes all registered listeners for `type`,
|
||||
// * otherwise removes all registered listeners.
|
||||
// */
|
||||
// removeAllListeners(type: string): this;
|
||||
// /**
|
||||
// * Node.js-specific extension to the `EventTarget` class that removes the listener for the given `type`.
|
||||
// * The only difference between `removeListener()` and `removeEventListener()` is that `removeListener()` will return a reference to the `EventTarget`.
|
||||
// */
|
||||
// removeListener(type: string, listener: EventListener | EventListenerObject): this;
|
||||
// }
|
||||
interface EventEmitterOptions {
|
||||
/**
|
||||
* Enables automatic capturing of promise rejection.
|
||||
*/
|
||||
captureRejections?: boolean | undefined;
|
||||
}
|
||||
interface StaticEventEmitterOptions {
|
||||
/**
|
||||
* Can be used to cancel awaiting events.
|
||||
*/
|
||||
signal?: AbortSignal | undefined;
|
||||
}
|
||||
interface StaticEventEmitterIteratorOptions extends StaticEventEmitterOptions {
|
||||
/**
|
||||
* Names of events that will end the iteration.
|
||||
*/
|
||||
close?: string[] | undefined;
|
||||
/**
|
||||
* The high watermark. The emitter is paused every time the size of events being buffered is higher than it.
|
||||
* Supported only on emitters implementing `pause()` and `resume()` methods.
|
||||
* @default Number.MAX_SAFE_INTEGER
|
||||
*/
|
||||
highWaterMark?: number | undefined;
|
||||
/**
|
||||
* The low watermark. The emitter is resumed every time the size of events being buffered is lower than it.
|
||||
* Supported only on emitters implementing `pause()` and `resume()` methods.
|
||||
* @default 1
|
||||
*/
|
||||
lowWaterMark?: number | undefined;
|
||||
}
|
||||
interface EventEmitter<T extends EventMap<T> = DefaultEventMap> extends NodeJS.EventEmitter<T> {}
|
||||
type EventMap<T> = Record<keyof T, any[]> | DefaultEventMap;
|
||||
type DefaultEventMap = [never];
|
||||
type AnyRest = [...args: any[]];
|
||||
type Args<K, T> = T extends DefaultEventMap ? AnyRest : (
|
||||
K extends keyof T ? T[K] : never
|
||||
);
|
||||
type Key<K, T> = T extends DefaultEventMap ? string | symbol : K | keyof T;
|
||||
type Key2<K, T> = T extends DefaultEventMap ? string | symbol : K & keyof T;
|
||||
type Listener<K, T, F> = T extends DefaultEventMap ? F : (
|
||||
K extends keyof T ? (
|
||||
T[K] extends unknown[] ? (...args: T[K]) => void : never
|
||||
)
|
||||
: never
|
||||
);
|
||||
type Listener1<K, T> = Listener<K, T, (...args: any[]) => void>;
|
||||
type Listener2<K, T> = Listener<K, T, Function>;
|
||||
|
||||
/**
|
||||
* The `EventEmitter` class is defined and exposed by the `node:events` module:
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
* ```
|
||||
*
|
||||
* All `EventEmitter`s emit the event `'newListener'` when new listeners are
|
||||
* added and `'removeListener'` when existing listeners are removed.
|
||||
*
|
||||
* It supports the following option:
|
||||
* @since v0.1.26
|
||||
*/
|
||||
class EventEmitter<T extends EventMap<T> = DefaultEventMap> {
|
||||
constructor(options?: EventEmitterOptions);
|
||||
|
||||
[EventEmitter.captureRejectionSymbol]?<K>(error: Error, event: Key<K, T>, ...args: Args<K, T>): void;
|
||||
|
||||
/**
|
||||
* Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given
|
||||
* event or that is rejected if the `EventEmitter` emits `'error'` while waiting.
|
||||
* The `Promise` will resolve with an array of all the arguments emitted to the
|
||||
* given event.
|
||||
*
|
||||
* This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event
|
||||
* semantics and does not listen to the `'error'` event.
|
||||
*
|
||||
* ```js
|
||||
* import { once, EventEmitter } from 'node:events';
|
||||
* import process from 'node:process';
|
||||
*
|
||||
* const ee = new EventEmitter();
|
||||
*
|
||||
* process.nextTick(() => {
|
||||
* ee.emit('myevent', 42);
|
||||
* });
|
||||
*
|
||||
* const [value] = await once(ee, 'myevent');
|
||||
* console.log(value);
|
||||
*
|
||||
* const err = new Error('kaboom');
|
||||
* process.nextTick(() => {
|
||||
* ee.emit('error', err);
|
||||
* });
|
||||
*
|
||||
* try {
|
||||
* await once(ee, 'myevent');
|
||||
* } catch (err) {
|
||||
* console.error('error happened', err);
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* The special handling of the `'error'` event is only used when `events.once()` is used to wait for another event. If `events.once()` is used to wait for the
|
||||
* '`error'` event itself, then it is treated as any other kind of event without
|
||||
* special handling:
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter, once } from 'node:events';
|
||||
*
|
||||
* const ee = new EventEmitter();
|
||||
*
|
||||
* once(ee, 'error')
|
||||
* .then(([err]) => console.log('ok', err.message))
|
||||
* .catch((err) => console.error('error', err.message));
|
||||
*
|
||||
* ee.emit('error', new Error('boom'));
|
||||
*
|
||||
* // Prints: ok boom
|
||||
* ```
|
||||
*
|
||||
* An `AbortSignal` can be used to cancel waiting for the event:
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter, once } from 'node:events';
|
||||
*
|
||||
* const ee = new EventEmitter();
|
||||
* const ac = new AbortController();
|
||||
*
|
||||
* async function foo(emitter, event, signal) {
|
||||
* try {
|
||||
* await once(emitter, event, { signal });
|
||||
* console.log('event emitted!');
|
||||
* } catch (error) {
|
||||
* if (error.name === 'AbortError') {
|
||||
* console.error('Waiting for the event was canceled!');
|
||||
* } else {
|
||||
* console.error('There was an error', error.message);
|
||||
* }
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* foo(ee, 'foo', ac.signal);
|
||||
* ac.abort(); // Abort waiting for the event
|
||||
* ee.emit('foo'); // Prints: Waiting for the event was canceled!
|
||||
* ```
|
||||
* @since v11.13.0, v10.16.0
|
||||
*/
|
||||
static once(
|
||||
emitter: NodeJS.EventEmitter,
|
||||
eventName: string | symbol,
|
||||
options?: StaticEventEmitterOptions,
|
||||
): Promise<any[]>;
|
||||
static once(emitter: EventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise<any[]>;
|
||||
/**
|
||||
* ```js
|
||||
* import { on, EventEmitter } from 'node:events';
|
||||
* import process from 'node:process';
|
||||
*
|
||||
* const ee = new EventEmitter();
|
||||
*
|
||||
* // Emit later on
|
||||
* process.nextTick(() => {
|
||||
* ee.emit('foo', 'bar');
|
||||
* ee.emit('foo', 42);
|
||||
* });
|
||||
*
|
||||
* for await (const event of on(ee, 'foo')) {
|
||||
* // The execution of this inner block is synchronous and it
|
||||
* // processes one event at a time (even with await). Do not use
|
||||
* // if concurrent execution is required.
|
||||
* console.log(event); // prints ['bar'] [42]
|
||||
* }
|
||||
* // Unreachable here
|
||||
* ```
|
||||
*
|
||||
* Returns an `AsyncIterator` that iterates `eventName` events. It will throw
|
||||
* if the `EventEmitter` emits `'error'`. It removes all listeners when
|
||||
* exiting the loop. The `value` returned by each iteration is an array
|
||||
* composed of the emitted event arguments.
|
||||
*
|
||||
* An `AbortSignal` can be used to cancel waiting on events:
|
||||
*
|
||||
* ```js
|
||||
* import { on, EventEmitter } from 'node:events';
|
||||
* import process from 'node:process';
|
||||
*
|
||||
* const ac = new AbortController();
|
||||
*
|
||||
* (async () => {
|
||||
* const ee = new EventEmitter();
|
||||
*
|
||||
* // Emit later on
|
||||
* process.nextTick(() => {
|
||||
* ee.emit('foo', 'bar');
|
||||
* ee.emit('foo', 42);
|
||||
* });
|
||||
*
|
||||
* for await (const event of on(ee, 'foo', { signal: ac.signal })) {
|
||||
* // The execution of this inner block is synchronous and it
|
||||
* // processes one event at a time (even with await). Do not use
|
||||
* // if concurrent execution is required.
|
||||
* console.log(event); // prints ['bar'] [42]
|
||||
* }
|
||||
* // Unreachable here
|
||||
* })();
|
||||
*
|
||||
* process.nextTick(() => ac.abort());
|
||||
* ```
|
||||
*
|
||||
* Use the `close` option to specify an array of event names that will end the iteration:
|
||||
*
|
||||
* ```js
|
||||
* import { on, EventEmitter } from 'node:events';
|
||||
* import process from 'node:process';
|
||||
*
|
||||
* const ee = new EventEmitter();
|
||||
*
|
||||
* // Emit later on
|
||||
* process.nextTick(() => {
|
||||
* ee.emit('foo', 'bar');
|
||||
* ee.emit('foo', 42);
|
||||
* ee.emit('close');
|
||||
* });
|
||||
*
|
||||
* for await (const event of on(ee, 'foo', { close: ['close'] })) {
|
||||
* console.log(event); // prints ['bar'] [42]
|
||||
* }
|
||||
* // the loop will exit after 'close' is emitted
|
||||
* console.log('done'); // prints 'done'
|
||||
* ```
|
||||
* @since v13.6.0, v12.16.0
|
||||
* @return An `AsyncIterator` that iterates `eventName` events emitted by the `emitter`
|
||||
*/
|
||||
static on(
|
||||
emitter: NodeJS.EventEmitter,
|
||||
eventName: string | symbol,
|
||||
options?: StaticEventEmitterIteratorOptions,
|
||||
): NodeJS.AsyncIterator<any[]>;
|
||||
static on(
|
||||
emitter: EventTarget,
|
||||
eventName: string,
|
||||
options?: StaticEventEmitterIteratorOptions,
|
||||
): NodeJS.AsyncIterator<any[]>;
|
||||
/**
|
||||
* A class method that returns the number of listeners for the given `eventName` registered on the given `emitter`.
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter, listenerCount } from 'node:events';
|
||||
*
|
||||
* const myEmitter = new EventEmitter();
|
||||
* myEmitter.on('event', () => {});
|
||||
* myEmitter.on('event', () => {});
|
||||
* console.log(listenerCount(myEmitter, 'event'));
|
||||
* // Prints: 2
|
||||
* ```
|
||||
* @since v0.9.12
|
||||
* @deprecated Since v3.2.0 - Use `listenerCount` instead.
|
||||
* @param emitter The emitter to query
|
||||
* @param eventName The event name
|
||||
*/
|
||||
static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number;
|
||||
/**
|
||||
* Returns a copy of the array of listeners for the event named `eventName`.
|
||||
*
|
||||
* For `EventEmitter`s this behaves exactly the same as calling `.listeners` on
|
||||
* the emitter.
|
||||
*
|
||||
* For `EventTarget`s this is the only way to get the event listeners for the
|
||||
* event target. This is useful for debugging and diagnostic purposes.
|
||||
*
|
||||
* ```js
|
||||
* import { getEventListeners, EventEmitter } from 'node:events';
|
||||
*
|
||||
* {
|
||||
* const ee = new EventEmitter();
|
||||
* const listener = () => console.log('Events are fun');
|
||||
* ee.on('foo', listener);
|
||||
* console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ]
|
||||
* }
|
||||
* {
|
||||
* const et = new EventTarget();
|
||||
* const listener = () => console.log('Events are fun');
|
||||
* et.addEventListener('foo', listener);
|
||||
* console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ]
|
||||
* }
|
||||
* ```
|
||||
* @since v15.2.0, v14.17.0
|
||||
*/
|
||||
static getEventListeners(emitter: EventTarget | NodeJS.EventEmitter, name: string | symbol): Function[];
|
||||
/**
|
||||
* Returns the currently set max amount of listeners.
|
||||
*
|
||||
* For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on
|
||||
* the emitter.
|
||||
*
|
||||
* For `EventTarget`s this is the only way to get the max event listeners for the
|
||||
* event target. If the number of event handlers on a single EventTarget exceeds
|
||||
* the max set, the EventTarget will print a warning.
|
||||
*
|
||||
* ```js
|
||||
* import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
|
||||
*
|
||||
* {
|
||||
* const ee = new EventEmitter();
|
||||
* console.log(getMaxListeners(ee)); // 10
|
||||
* setMaxListeners(11, ee);
|
||||
* console.log(getMaxListeners(ee)); // 11
|
||||
* }
|
||||
* {
|
||||
* const et = new EventTarget();
|
||||
* console.log(getMaxListeners(et)); // 10
|
||||
* setMaxListeners(11, et);
|
||||
* console.log(getMaxListeners(et)); // 11
|
||||
* }
|
||||
* ```
|
||||
* @since v19.9.0
|
||||
*/
|
||||
static getMaxListeners(emitter: EventTarget | NodeJS.EventEmitter): number;
|
||||
/**
|
||||
* ```js
|
||||
* import { setMaxListeners, EventEmitter } from 'node:events';
|
||||
*
|
||||
* const target = new EventTarget();
|
||||
* const emitter = new EventEmitter();
|
||||
*
|
||||
* setMaxListeners(5, target, emitter);
|
||||
* ```
|
||||
* @since v15.4.0
|
||||
* @param n A non-negative number. The maximum number of listeners per `EventTarget` event.
|
||||
* @param eventTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter}
|
||||
* objects.
|
||||
*/
|
||||
static setMaxListeners(n?: number, ...eventTargets: Array<EventTarget | NodeJS.EventEmitter>): void;
|
||||
/**
|
||||
* Listens once to the `abort` event on the provided `signal`.
|
||||
*
|
||||
* Listening to the `abort` event on abort signals is unsafe and may
|
||||
* lead to resource leaks since another third party with the signal can
|
||||
* call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change
|
||||
* this since it would violate the web standard. Additionally, the original
|
||||
* API makes it easy to forget to remove listeners.
|
||||
*
|
||||
* This API allows safely using `AbortSignal`s in Node.js APIs by solving these
|
||||
* two issues by listening to the event such that `stopImmediatePropagation` does
|
||||
* not prevent the listener from running.
|
||||
*
|
||||
* Returns a disposable so that it may be unsubscribed from more easily.
|
||||
*
|
||||
* ```js
|
||||
* import { addAbortListener } from 'node:events';
|
||||
*
|
||||
* function example(signal) {
|
||||
* let disposable;
|
||||
* try {
|
||||
* signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
|
||||
* disposable = addAbortListener(signal, (e) => {
|
||||
* // Do something when signal is aborted.
|
||||
* });
|
||||
* } finally {
|
||||
* disposable?.[Symbol.dispose]();
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
* @since v20.5.0
|
||||
* @experimental
|
||||
* @return Disposable that removes the `abort` listener.
|
||||
*/
|
||||
static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable;
|
||||
/**
|
||||
* This symbol shall be used to install a listener for only monitoring `'error'` events. Listeners installed using this symbol are called before the regular `'error'` listeners are called.
|
||||
*
|
||||
* Installing a listener using this symbol does not change the behavior once an `'error'` event is emitted. Therefore, the process will still crash if no
|
||||
* regular `'error'` listener is installed.
|
||||
* @since v13.6.0, v12.17.0
|
||||
*/
|
||||
static readonly errorMonitor: unique symbol;
|
||||
/**
|
||||
* Value: `Symbol.for('nodejs.rejection')`
|
||||
*
|
||||
* See how to write a custom `rejection handler`.
|
||||
* @since v13.4.0, v12.16.0
|
||||
*/
|
||||
static readonly captureRejectionSymbol: unique symbol;
|
||||
/**
|
||||
* Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
|
||||
*
|
||||
* Change the default `captureRejections` option on all new `EventEmitter` objects.
|
||||
* @since v13.4.0, v12.16.0
|
||||
*/
|
||||
static captureRejections: boolean;
|
||||
/**
|
||||
* By default, a maximum of `10` listeners can be registered for any single
|
||||
* event. This limit can be changed for individual `EventEmitter` instances
|
||||
* using the `emitter.setMaxListeners(n)` method. To change the default
|
||||
* for _all_`EventEmitter` instances, the `events.defaultMaxListeners` property
|
||||
* can be used. If this value is not a positive number, a `RangeError` is thrown.
|
||||
*
|
||||
* Take caution when setting the `events.defaultMaxListeners` because the
|
||||
* change affects _all_ `EventEmitter` instances, including those created before
|
||||
* the change is made. However, calling `emitter.setMaxListeners(n)` still has
|
||||
* precedence over `events.defaultMaxListeners`.
|
||||
*
|
||||
* This is not a hard limit. The `EventEmitter` instance will allow
|
||||
* more listeners to be added but will output a trace warning to stderr indicating
|
||||
* that a "possible EventEmitter memory leak" has been detected. For any single
|
||||
* `EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` methods can be used to
|
||||
* temporarily avoid this warning:
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
* const emitter = new EventEmitter();
|
||||
* emitter.setMaxListeners(emitter.getMaxListeners() + 1);
|
||||
* emitter.once('event', () => {
|
||||
* // do stuff
|
||||
* emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* The `--trace-warnings` command-line flag can be used to display the
|
||||
* stack trace for such warnings.
|
||||
*
|
||||
* The emitted warning can be inspected with `process.on('warning')` and will
|
||||
* have the additional `emitter`, `type`, and `count` properties, referring to
|
||||
* the event emitter instance, the event's name and the number of attached
|
||||
* listeners, respectively.
|
||||
* Its `name` property is set to `'MaxListenersExceededWarning'`.
|
||||
* @since v0.11.2
|
||||
*/
|
||||
static defaultMaxListeners: number;
|
||||
}
|
||||
import internal = require("node:events");
|
||||
namespace EventEmitter {
|
||||
// Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4
|
||||
export { internal as EventEmitter };
|
||||
export interface Abortable {
|
||||
/**
|
||||
* When provided the corresponding `AbortController` can be used to cancel an asynchronous action.
|
||||
*/
|
||||
signal?: AbortSignal | undefined;
|
||||
}
|
||||
|
||||
export interface EventEmitterReferencingAsyncResource extends AsyncResource {
|
||||
readonly eventEmitter: EventEmitterAsyncResource;
|
||||
}
|
||||
|
||||
export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions {
|
||||
/**
|
||||
* The type of async event, this is required when instantiating `EventEmitterAsyncResource`
|
||||
* directly rather than as a child class.
|
||||
* @default new.target.name if instantiated as a child class.
|
||||
*/
|
||||
name?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that
|
||||
* require manual async tracking. Specifically, all events emitted by instances
|
||||
* of `events.EventEmitterAsyncResource` will run within its `async context`.
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitterAsyncResource, EventEmitter } from 'node:events';
|
||||
* import { notStrictEqual, strictEqual } from 'node:assert';
|
||||
* import { executionAsyncId, triggerAsyncId } from 'node:async_hooks';
|
||||
*
|
||||
* // Async tracking tooling will identify this as 'Q'.
|
||||
* const ee1 = new EventEmitterAsyncResource({ name: 'Q' });
|
||||
*
|
||||
* // 'foo' listeners will run in the EventEmitters async context.
|
||||
* ee1.on('foo', () => {
|
||||
* strictEqual(executionAsyncId(), ee1.asyncId);
|
||||
* strictEqual(triggerAsyncId(), ee1.triggerAsyncId);
|
||||
* });
|
||||
*
|
||||
* const ee2 = new EventEmitter();
|
||||
*
|
||||
* // 'foo' listeners on ordinary EventEmitters that do not track async
|
||||
* // context, however, run in the same async context as the emit().
|
||||
* ee2.on('foo', () => {
|
||||
* notStrictEqual(executionAsyncId(), ee2.asyncId);
|
||||
* notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId);
|
||||
* });
|
||||
*
|
||||
* Promise.resolve().then(() => {
|
||||
* ee1.emit('foo');
|
||||
* ee2.emit('foo');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* The `EventEmitterAsyncResource` class has the same methods and takes the
|
||||
* same options as `EventEmitter` and `AsyncResource` themselves.
|
||||
* @since v17.4.0, v16.14.0
|
||||
*/
|
||||
export class EventEmitterAsyncResource extends EventEmitter {
|
||||
/**
|
||||
* @param options Only optional in child class.
|
||||
*/
|
||||
constructor(options?: EventEmitterAsyncResourceOptions);
|
||||
/**
|
||||
* Call all `destroy` hooks. This should only ever be called once. An error will
|
||||
* be thrown if it is called more than once. This **must** be manually called. If
|
||||
* the resource is left to be collected by the GC then the `destroy` hooks will
|
||||
* never be called.
|
||||
*/
|
||||
emitDestroy(): void;
|
||||
/**
|
||||
* The unique `asyncId` assigned to the resource.
|
||||
*/
|
||||
readonly asyncId: number;
|
||||
/**
|
||||
* The same triggerAsyncId that is passed to the AsyncResource constructor.
|
||||
*/
|
||||
readonly triggerAsyncId: number;
|
||||
/**
|
||||
* The returned `AsyncResource` object has an additional `eventEmitter` property
|
||||
* that provides a reference to this `EventEmitterAsyncResource`.
|
||||
*/
|
||||
readonly asyncResource: EventEmitterReferencingAsyncResource;
|
||||
}
|
||||
}
|
||||
global {
|
||||
namespace NodeJS {
|
||||
interface EventEmitter<T extends EventMap<T> = DefaultEventMap> {
|
||||
[EventEmitter.captureRejectionSymbol]?<K>(error: Error, event: Key<K, T>, ...args: Args<K, T>): void;
|
||||
/**
|
||||
* Alias for `emitter.on(eventName, listener)`.
|
||||
* @since v0.1.26
|
||||
*/
|
||||
addListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
||||
/**
|
||||
* Adds the `listener` function to the end of the listeners array for the event
|
||||
* named `eventName`. No checks are made to see if the `listener` has already
|
||||
* been added. Multiple calls passing the same combination of `eventName` and
|
||||
* `listener` will result in the `listener` being added, and called, multiple times.
|
||||
*
|
||||
* ```js
|
||||
* server.on('connection', (stream) => {
|
||||
* console.log('someone connected!');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* By default, event listeners are invoked in the order they are added. The `emitter.prependListener()` method can be used as an alternative to add the
|
||||
* event listener to the beginning of the listeners array.
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
* const myEE = new EventEmitter();
|
||||
* myEE.on('foo', () => console.log('a'));
|
||||
* myEE.prependListener('foo', () => console.log('b'));
|
||||
* myEE.emit('foo');
|
||||
* // Prints:
|
||||
* // b
|
||||
* // a
|
||||
* ```
|
||||
* @since v0.1.101
|
||||
* @param eventName The name of the event.
|
||||
* @param listener The callback function
|
||||
*/
|
||||
on<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
||||
/**
|
||||
* Adds a **one-time** `listener` function for the event named `eventName`. The
|
||||
* next time `eventName` is triggered, this listener is removed and then invoked.
|
||||
*
|
||||
* ```js
|
||||
* server.once('connection', (stream) => {
|
||||
* console.log('Ah, we have our first user!');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
*
|
||||
* By default, event listeners are invoked in the order they are added. The `emitter.prependOnceListener()` method can be used as an alternative to add the
|
||||
* event listener to the beginning of the listeners array.
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
* const myEE = new EventEmitter();
|
||||
* myEE.once('foo', () => console.log('a'));
|
||||
* myEE.prependOnceListener('foo', () => console.log('b'));
|
||||
* myEE.emit('foo');
|
||||
* // Prints:
|
||||
* // b
|
||||
* // a
|
||||
* ```
|
||||
* @since v0.3.0
|
||||
* @param eventName The name of the event.
|
||||
* @param listener The callback function
|
||||
*/
|
||||
once<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
||||
/**
|
||||
* Removes the specified `listener` from the listener array for the event named `eventName`.
|
||||
*
|
||||
* ```js
|
||||
* const callback = (stream) => {
|
||||
* console.log('someone connected!');
|
||||
* };
|
||||
* server.on('connection', callback);
|
||||
* // ...
|
||||
* server.removeListener('connection', callback);
|
||||
* ```
|
||||
*
|
||||
* `removeListener()` will remove, at most, one instance of a listener from the
|
||||
* listener array. If any single listener has been added multiple times to the
|
||||
* listener array for the specified `eventName`, then `removeListener()` must be
|
||||
* called multiple times to remove each instance.
|
||||
*
|
||||
* Once an event is emitted, all listeners attached to it at the
|
||||
* time of emitting are called in order. This implies that any `removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution
|
||||
* will not remove them from`emit()` in progress. Subsequent events behave as expected.
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
* class MyEmitter extends EventEmitter {}
|
||||
* const myEmitter = new MyEmitter();
|
||||
*
|
||||
* const callbackA = () => {
|
||||
* console.log('A');
|
||||
* myEmitter.removeListener('event', callbackB);
|
||||
* };
|
||||
*
|
||||
* const callbackB = () => {
|
||||
* console.log('B');
|
||||
* };
|
||||
*
|
||||
* myEmitter.on('event', callbackA);
|
||||
*
|
||||
* myEmitter.on('event', callbackB);
|
||||
*
|
||||
* // callbackA removes listener callbackB but it will still be called.
|
||||
* // Internal listener array at time of emit [callbackA, callbackB]
|
||||
* myEmitter.emit('event');
|
||||
* // Prints:
|
||||
* // A
|
||||
* // B
|
||||
*
|
||||
* // callbackB is now removed.
|
||||
* // Internal listener array [callbackA]
|
||||
* myEmitter.emit('event');
|
||||
* // Prints:
|
||||
* // A
|
||||
* ```
|
||||
*
|
||||
* Because listeners are managed using an internal array, calling this will
|
||||
* change the position indices of any listener registered _after_ the listener
|
||||
* being removed. This will not impact the order in which listeners are called,
|
||||
* but it means that any copies of the listener array as returned by
|
||||
* the `emitter.listeners()` method will need to be recreated.
|
||||
*
|
||||
* When a single function has been added as a handler multiple times for a single
|
||||
* event (as in the example below), `removeListener()` will remove the most
|
||||
* recently added instance. In the example the `once('ping')` listener is removed:
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
* const ee = new EventEmitter();
|
||||
*
|
||||
* function pong() {
|
||||
* console.log('pong');
|
||||
* }
|
||||
*
|
||||
* ee.on('ping', pong);
|
||||
* ee.once('ping', pong);
|
||||
* ee.removeListener('ping', pong);
|
||||
*
|
||||
* ee.emit('ping');
|
||||
* ee.emit('ping');
|
||||
* ```
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
* @since v0.1.26
|
||||
*/
|
||||
removeListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
||||
/**
|
||||
* Alias for `emitter.removeListener()`.
|
||||
* @since v10.0.0
|
||||
*/
|
||||
off<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
||||
/**
|
||||
* Removes all listeners, or those of the specified `eventName`.
|
||||
*
|
||||
* It is bad practice to remove listeners added elsewhere in the code,
|
||||
* particularly when the `EventEmitter` instance was created by some other
|
||||
* component or module (e.g. sockets or file streams).
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
* @since v0.1.26
|
||||
*/
|
||||
removeAllListeners(eventName?: Key<unknown, T>): this;
|
||||
/**
|
||||
* By default `EventEmitter`s will print a warning if more than `10` listeners are
|
||||
* added for a particular event. This is a useful default that helps finding
|
||||
* memory leaks. The `emitter.setMaxListeners()` method allows the limit to be
|
||||
* modified for this specific `EventEmitter` instance. The value can be set to `Infinity` (or `0`) to indicate an unlimited number of listeners.
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
* @since v0.3.5
|
||||
*/
|
||||
setMaxListeners(n: number): this;
|
||||
/**
|
||||
* Returns the current max listener value for the `EventEmitter` which is either
|
||||
* set by `emitter.setMaxListeners(n)` or defaults to {@link EventEmitter.defaultMaxListeners}.
|
||||
* @since v1.0.0
|
||||
*/
|
||||
getMaxListeners(): number;
|
||||
/**
|
||||
* Returns a copy of the array of listeners for the event named `eventName`.
|
||||
*
|
||||
* ```js
|
||||
* server.on('connection', (stream) => {
|
||||
* console.log('someone connected!');
|
||||
* });
|
||||
* console.log(util.inspect(server.listeners('connection')));
|
||||
* // Prints: [ [Function] ]
|
||||
* ```
|
||||
* @since v0.1.26
|
||||
*/
|
||||
listeners<K>(eventName: Key<K, T>): Array<Listener2<K, T>>;
|
||||
/**
|
||||
* Returns a copy of the array of listeners for the event named `eventName`,
|
||||
* including any wrappers (such as those created by `.once()`).
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
* const emitter = new EventEmitter();
|
||||
* emitter.once('log', () => console.log('log once'));
|
||||
*
|
||||
* // Returns a new Array with a function `onceWrapper` which has a property
|
||||
* // `listener` which contains the original listener bound above
|
||||
* const listeners = emitter.rawListeners('log');
|
||||
* const logFnWrapper = listeners[0];
|
||||
*
|
||||
* // Logs "log once" to the console and does not unbind the `once` event
|
||||
* logFnWrapper.listener();
|
||||
*
|
||||
* // Logs "log once" to the console and removes the listener
|
||||
* logFnWrapper();
|
||||
*
|
||||
* emitter.on('log', () => console.log('log persistently'));
|
||||
* // Will return a new Array with a single function bound by `.on()` above
|
||||
* const newListeners = emitter.rawListeners('log');
|
||||
*
|
||||
* // Logs "log persistently" twice
|
||||
* newListeners[0]();
|
||||
* emitter.emit('log');
|
||||
* ```
|
||||
* @since v9.4.0
|
||||
*/
|
||||
rawListeners<K>(eventName: Key<K, T>): Array<Listener2<K, T>>;
|
||||
/**
|
||||
* Synchronously calls each of the listeners registered for the event named `eventName`, in the order they were registered, passing the supplied arguments
|
||||
* to each.
|
||||
*
|
||||
* Returns `true` if the event had listeners, `false` otherwise.
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
* const myEmitter = new EventEmitter();
|
||||
*
|
||||
* // First listener
|
||||
* myEmitter.on('event', function firstListener() {
|
||||
* console.log('Helloooo! first listener');
|
||||
* });
|
||||
* // Second listener
|
||||
* myEmitter.on('event', function secondListener(arg1, arg2) {
|
||||
* console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
|
||||
* });
|
||||
* // Third listener
|
||||
* myEmitter.on('event', function thirdListener(...args) {
|
||||
* const parameters = args.join(', ');
|
||||
* console.log(`event with parameters ${parameters} in third listener`);
|
||||
* });
|
||||
*
|
||||
* console.log(myEmitter.listeners('event'));
|
||||
*
|
||||
* myEmitter.emit('event', 1, 2, 3, 4, 5);
|
||||
*
|
||||
* // Prints:
|
||||
* // [
|
||||
* // [Function: firstListener],
|
||||
* // [Function: secondListener],
|
||||
* // [Function: thirdListener]
|
||||
* // ]
|
||||
* // Helloooo! first listener
|
||||
* // event with parameters 1, 2 in second listener
|
||||
* // event with parameters 1, 2, 3, 4, 5 in third listener
|
||||
* ```
|
||||
* @since v0.1.26
|
||||
*/
|
||||
emit<K>(eventName: Key<K, T>, ...args: Args<K, T>): boolean;
|
||||
/**
|
||||
* Returns the number of listeners listening for the event named `eventName`.
|
||||
* If `listener` is provided, it will return how many times the listener is found
|
||||
* in the list of the listeners of the event.
|
||||
* @since v3.2.0
|
||||
* @param eventName The name of the event being listened for
|
||||
* @param listener The event handler function
|
||||
*/
|
||||
listenerCount<K>(eventName: Key<K, T>, listener?: Listener2<K, T>): number;
|
||||
/**
|
||||
* Adds the `listener` function to the _beginning_ of the listeners array for the
|
||||
* event named `eventName`. No checks are made to see if the `listener` has
|
||||
* already been added. Multiple calls passing the same combination of `eventName`
|
||||
* and `listener` will result in the `listener` being added, and called, multiple times.
|
||||
*
|
||||
* ```js
|
||||
* server.prependListener('connection', (stream) => {
|
||||
* console.log('someone connected!');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
* @since v6.0.0
|
||||
* @param eventName The name of the event.
|
||||
* @param listener The callback function
|
||||
*/
|
||||
prependListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
||||
/**
|
||||
* Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this
|
||||
* listener is removed, and then invoked.
|
||||
*
|
||||
* ```js
|
||||
* server.prependOnceListener('connection', (stream) => {
|
||||
* console.log('Ah, we have our first user!');
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Returns a reference to the `EventEmitter`, so that calls can be chained.
|
||||
* @since v6.0.0
|
||||
* @param eventName The name of the event.
|
||||
* @param listener The callback function
|
||||
*/
|
||||
prependOnceListener<K>(eventName: Key<K, T>, listener: Listener1<K, T>): this;
|
||||
/**
|
||||
* Returns an array listing the events for which the emitter has registered
|
||||
* listeners. The values in the array are strings or `Symbol`s.
|
||||
*
|
||||
* ```js
|
||||
* import { EventEmitter } from 'node:events';
|
||||
*
|
||||
* const myEE = new EventEmitter();
|
||||
* myEE.on('foo', () => {});
|
||||
* myEE.on('bar', () => {});
|
||||
*
|
||||
* const sym = Symbol('symbol');
|
||||
* myEE.on(sym, () => {});
|
||||
*
|
||||
* console.log(myEE.eventNames());
|
||||
* // Prints: [ 'foo', 'bar', Symbol(symbol) ]
|
||||
* ```
|
||||
* @since v6.0.0
|
||||
*/
|
||||
eventNames(): Array<(string | symbol) & Key2<unknown, T>>;
|
||||
}
|
||||
}
|
||||
}
|
||||
export = EventEmitter;
|
||||
}
|
||||
declare module "node:events" {
|
||||
import events = require("events");
|
||||
export = events;
|
||||
}
|
||||
4362
frontend/e2e/node_modules/@types/node/fs.d.ts
generated
vendored
Normal file
4362
frontend/e2e/node_modules/@types/node/fs.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1248
frontend/e2e/node_modules/@types/node/fs/promises.d.ts
generated
vendored
Normal file
1248
frontend/e2e/node_modules/@types/node/fs/promises.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
170
frontend/e2e/node_modules/@types/node/globals.d.ts
generated
vendored
Normal file
170
frontend/e2e/node_modules/@types/node/globals.d.ts
generated
vendored
Normal file
@@ -0,0 +1,170 @@
|
||||
declare var global: typeof globalThis;
|
||||
|
||||
declare var process: NodeJS.Process;
|
||||
declare var console: Console;
|
||||
|
||||
interface ErrorConstructor {
|
||||
/**
|
||||
* Creates a `.stack` property on `targetObject`, which when accessed returns
|
||||
* a string representing the location in the code at which
|
||||
* `Error.captureStackTrace()` was called.
|
||||
*
|
||||
* ```js
|
||||
* const myObject = {};
|
||||
* Error.captureStackTrace(myObject);
|
||||
* myObject.stack; // Similar to `new Error().stack`
|
||||
* ```
|
||||
*
|
||||
* The first line of the trace will be prefixed with
|
||||
* `${myObject.name}: ${myObject.message}`.
|
||||
*
|
||||
* The optional `constructorOpt` argument accepts a function. If given, all frames
|
||||
* above `constructorOpt`, including `constructorOpt`, will be omitted from the
|
||||
* generated stack trace.
|
||||
*
|
||||
* The `constructorOpt` argument is useful for hiding implementation
|
||||
* details of error generation from the user. For instance:
|
||||
*
|
||||
* ```js
|
||||
* function a() {
|
||||
* b();
|
||||
* }
|
||||
*
|
||||
* function b() {
|
||||
* c();
|
||||
* }
|
||||
*
|
||||
* function c() {
|
||||
* // Create an error without stack trace to avoid calculating the stack trace twice.
|
||||
* const { stackTraceLimit } = Error;
|
||||
* Error.stackTraceLimit = 0;
|
||||
* const error = new Error();
|
||||
* Error.stackTraceLimit = stackTraceLimit;
|
||||
*
|
||||
* // Capture the stack trace above function b
|
||||
* Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
|
||||
* throw error;
|
||||
* }
|
||||
*
|
||||
* a();
|
||||
* ```
|
||||
*/
|
||||
captureStackTrace(targetObject: object, constructorOpt?: Function): void;
|
||||
/**
|
||||
* @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces
|
||||
*/
|
||||
prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any;
|
||||
/**
|
||||
* The `Error.stackTraceLimit` property specifies the number of stack frames
|
||||
* collected by a stack trace (whether generated by `new Error().stack` or
|
||||
* `Error.captureStackTrace(obj)`).
|
||||
*
|
||||
* The default value is `10` but may be set to any valid JavaScript number. Changes
|
||||
* will affect any stack trace captured _after_ the value has been changed.
|
||||
*
|
||||
* If set to a non-number value, or set to a negative number, stack traces will
|
||||
* not capture any frames.
|
||||
*/
|
||||
stackTraceLimit: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enable this API with the `--expose-gc` CLI flag.
|
||||
*/
|
||||
declare var gc: NodeJS.GCFunction | undefined;
|
||||
|
||||
declare namespace NodeJS {
|
||||
interface CallSite {
|
||||
getColumnNumber(): number | null;
|
||||
getEnclosingColumnNumber(): number | null;
|
||||
getEnclosingLineNumber(): number | null;
|
||||
getEvalOrigin(): string | undefined;
|
||||
getFileName(): string | null;
|
||||
getFunction(): Function | undefined;
|
||||
getFunctionName(): string | null;
|
||||
getLineNumber(): number | null;
|
||||
getMethodName(): string | null;
|
||||
getPosition(): number;
|
||||
getPromiseIndex(): number | null;
|
||||
getScriptHash(): string;
|
||||
getScriptNameOrSourceURL(): string | null;
|
||||
getThis(): unknown;
|
||||
getTypeName(): string | null;
|
||||
isAsync(): boolean;
|
||||
isConstructor(): boolean;
|
||||
isEval(): boolean;
|
||||
isNative(): boolean;
|
||||
isPromiseAll(): boolean;
|
||||
isToplevel(): boolean;
|
||||
}
|
||||
|
||||
interface ErrnoException extends Error {
|
||||
errno?: number | undefined;
|
||||
code?: string | undefined;
|
||||
path?: string | undefined;
|
||||
syscall?: string | undefined;
|
||||
}
|
||||
|
||||
interface ReadableStream extends EventEmitter {
|
||||
readable: boolean;
|
||||
read(size?: number): string | Buffer;
|
||||
setEncoding(encoding: BufferEncoding): this;
|
||||
pause(): this;
|
||||
resume(): this;
|
||||
isPaused(): boolean;
|
||||
pipe<T extends WritableStream>(destination: T, options?: { end?: boolean | undefined }): T;
|
||||
unpipe(destination?: WritableStream): this;
|
||||
unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void;
|
||||
wrap(oldStream: ReadableStream): this;
|
||||
[Symbol.asyncIterator](): AsyncIterableIterator<string | Buffer>;
|
||||
}
|
||||
|
||||
interface WritableStream extends EventEmitter {
|
||||
writable: boolean;
|
||||
write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean;
|
||||
write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean;
|
||||
end(cb?: () => void): this;
|
||||
end(data: string | Uint8Array, cb?: () => void): this;
|
||||
end(str: string, encoding?: BufferEncoding, cb?: () => void): this;
|
||||
}
|
||||
|
||||
interface ReadWriteStream extends ReadableStream, WritableStream {}
|
||||
|
||||
interface RefCounted {
|
||||
ref(): this;
|
||||
unref(): this;
|
||||
}
|
||||
|
||||
interface Dict<T> {
|
||||
[key: string]: T | undefined;
|
||||
}
|
||||
|
||||
interface ReadOnlyDict<T> {
|
||||
readonly [key: string]: T | undefined;
|
||||
}
|
||||
|
||||
interface GCFunction {
|
||||
(minor?: boolean): void;
|
||||
(options: NodeJS.GCOptions & { execution: "async" }): Promise<void>;
|
||||
(options: NodeJS.GCOptions): void;
|
||||
}
|
||||
|
||||
interface GCOptions {
|
||||
execution?: "sync" | "async" | undefined;
|
||||
flavor?: "regular" | "last-resort" | undefined;
|
||||
type?: "major-snapshot" | "major" | "minor" | undefined;
|
||||
filename?: string | undefined;
|
||||
}
|
||||
|
||||
/** An iterable iterator returned by the Node.js API. */
|
||||
// Default TReturn/TNext in v20 is `any`, for compatibility with the previously-used IterableIterator.
|
||||
interface Iterator<T, TReturn = any, TNext = any> extends IteratorObject<T, TReturn, TNext> {
|
||||
[Symbol.iterator](): NodeJS.Iterator<T, TReturn, TNext>;
|
||||
}
|
||||
|
||||
/** An async iterable iterator returned by the Node.js API. */
|
||||
// Default TReturn/TNext in v20 is `any`, for compatibility with the previously-used AsyncIterableIterator.
|
||||
interface AsyncIterator<T, TReturn = any, TNext = any> extends AsyncIteratorObject<T, TReturn, TNext> {
|
||||
[Symbol.asyncIterator](): NodeJS.AsyncIterator<T, TReturn, TNext>;
|
||||
}
|
||||
}
|
||||
21
frontend/e2e/node_modules/@types/node/globals.typedarray.d.ts
generated
vendored
Normal file
21
frontend/e2e/node_modules/@types/node/globals.typedarray.d.ts
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
export {}; // Make this a module
|
||||
|
||||
declare global {
|
||||
namespace NodeJS {
|
||||
type TypedArray<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> =
|
||||
| Uint8Array<TArrayBuffer>
|
||||
| Uint8ClampedArray<TArrayBuffer>
|
||||
| Uint16Array<TArrayBuffer>
|
||||
| Uint32Array<TArrayBuffer>
|
||||
| Int8Array<TArrayBuffer>
|
||||
| Int16Array<TArrayBuffer>
|
||||
| Int32Array<TArrayBuffer>
|
||||
| BigUint64Array<TArrayBuffer>
|
||||
| BigInt64Array<TArrayBuffer>
|
||||
| Float32Array<TArrayBuffer>
|
||||
| Float64Array<TArrayBuffer>;
|
||||
type ArrayBufferView<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> =
|
||||
| TypedArray<TArrayBuffer>
|
||||
| DataView<TArrayBuffer>;
|
||||
}
|
||||
}
|
||||
2031
frontend/e2e/node_modules/@types/node/http.d.ts
generated
vendored
Normal file
2031
frontend/e2e/node_modules/@types/node/http.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
2623
frontend/e2e/node_modules/@types/node/http2.d.ts
generated
vendored
Normal file
2623
frontend/e2e/node_modules/@types/node/http2.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
544
frontend/e2e/node_modules/@types/node/https.d.ts
generated
vendored
Normal file
544
frontend/e2e/node_modules/@types/node/https.d.ts
generated
vendored
Normal file
@@ -0,0 +1,544 @@
|
||||
/**
|
||||
* HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
|
||||
* separate module.
|
||||
* @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/https.js)
|
||||
*/
|
||||
declare module "https" {
|
||||
import { Duplex } from "node:stream";
|
||||
import * as tls from "node:tls";
|
||||
import * as http from "node:http";
|
||||
import { URL } from "node:url";
|
||||
type ServerOptions<
|
||||
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
|
||||
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
|
||||
> = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions<Request, Response>;
|
||||
type RequestOptions =
|
||||
& http.RequestOptions
|
||||
& tls.SecureContextOptions
|
||||
& {
|
||||
checkServerIdentity?: typeof tls.checkServerIdentity | undefined;
|
||||
rejectUnauthorized?: boolean | undefined; // Defaults to true
|
||||
servername?: string | undefined; // SNI TLS Extension
|
||||
};
|
||||
interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions {
|
||||
rejectUnauthorized?: boolean | undefined;
|
||||
maxCachedSessions?: number | undefined;
|
||||
}
|
||||
/**
|
||||
* An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information.
|
||||
* @since v0.4.5
|
||||
*/
|
||||
class Agent extends http.Agent {
|
||||
constructor(options?: AgentOptions);
|
||||
options: AgentOptions;
|
||||
}
|
||||
interface Server<
|
||||
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
|
||||
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
|
||||
> extends http.Server<Request, Response> {}
|
||||
/**
|
||||
* See `http.Server` for more information.
|
||||
* @since v0.3.4
|
||||
*/
|
||||
class Server<
|
||||
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
|
||||
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
|
||||
> extends tls.Server {
|
||||
constructor(requestListener?: http.RequestListener<Request, Response>);
|
||||
constructor(
|
||||
options: ServerOptions<Request, Response>,
|
||||
requestListener?: http.RequestListener<Request, Response>,
|
||||
);
|
||||
/**
|
||||
* Closes all connections connected to this server.
|
||||
* @since v18.2.0
|
||||
*/
|
||||
closeAllConnections(): void;
|
||||
/**
|
||||
* Closes all connections connected to this server which are not sending a request or waiting for a response.
|
||||
* @since v18.2.0
|
||||
*/
|
||||
closeIdleConnections(): void;
|
||||
addListener(event: string, listener: (...args: any[]) => void): this;
|
||||
addListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this;
|
||||
addListener(
|
||||
event: "newSession",
|
||||
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void,
|
||||
): this;
|
||||
addListener(
|
||||
event: "OCSPRequest",
|
||||
listener: (
|
||||
certificate: Buffer,
|
||||
issuer: Buffer,
|
||||
callback: (err: Error | null, resp: Buffer) => void,
|
||||
) => void,
|
||||
): this;
|
||||
addListener(
|
||||
event: "resumeSession",
|
||||
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void,
|
||||
): this;
|
||||
addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
|
||||
addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
|
||||
addListener(event: "close", listener: () => void): this;
|
||||
addListener(event: "connection", listener: (socket: Duplex) => void): this;
|
||||
addListener(event: "error", listener: (err: Error) => void): this;
|
||||
addListener(event: "listening", listener: () => void): this;
|
||||
addListener(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
|
||||
addListener(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
|
||||
addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
|
||||
addListener(
|
||||
event: "connect",
|
||||
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
|
||||
): this;
|
||||
addListener(event: "request", listener: http.RequestListener<Request, Response>): this;
|
||||
addListener(
|
||||
event: "upgrade",
|
||||
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
|
||||
): this;
|
||||
emit(event: string, ...args: any[]): boolean;
|
||||
emit(event: "keylog", line: Buffer, tlsSocket: tls.TLSSocket): boolean;
|
||||
emit(
|
||||
event: "newSession",
|
||||
sessionId: Buffer,
|
||||
sessionData: Buffer,
|
||||
callback: (err: Error, resp: Buffer) => void,
|
||||
): boolean;
|
||||
emit(
|
||||
event: "OCSPRequest",
|
||||
certificate: Buffer,
|
||||
issuer: Buffer,
|
||||
callback: (err: Error | null, resp: Buffer) => void,
|
||||
): boolean;
|
||||
emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean;
|
||||
emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean;
|
||||
emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean;
|
||||
emit(event: "close"): boolean;
|
||||
emit(event: "connection", socket: Duplex): boolean;
|
||||
emit(event: "error", err: Error): boolean;
|
||||
emit(event: "listening"): boolean;
|
||||
emit(
|
||||
event: "checkContinue",
|
||||
req: InstanceType<Request>,
|
||||
res: InstanceType<Response>,
|
||||
): boolean;
|
||||
emit(
|
||||
event: "checkExpectation",
|
||||
req: InstanceType<Request>,
|
||||
res: InstanceType<Response>,
|
||||
): boolean;
|
||||
emit(event: "clientError", err: Error, socket: Duplex): boolean;
|
||||
emit(event: "connect", req: InstanceType<Request>, socket: Duplex, head: Buffer): boolean;
|
||||
emit(
|
||||
event: "request",
|
||||
req: InstanceType<Request>,
|
||||
res: InstanceType<Response>,
|
||||
): boolean;
|
||||
emit(event: "upgrade", req: InstanceType<Request>, socket: Duplex, head: Buffer): boolean;
|
||||
on(event: string, listener: (...args: any[]) => void): this;
|
||||
on(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this;
|
||||
on(
|
||||
event: "newSession",
|
||||
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void,
|
||||
): this;
|
||||
on(
|
||||
event: "OCSPRequest",
|
||||
listener: (
|
||||
certificate: Buffer,
|
||||
issuer: Buffer,
|
||||
callback: (err: Error | null, resp: Buffer) => void,
|
||||
) => void,
|
||||
): this;
|
||||
on(
|
||||
event: "resumeSession",
|
||||
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void,
|
||||
): this;
|
||||
on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
|
||||
on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
|
||||
on(event: "close", listener: () => void): this;
|
||||
on(event: "connection", listener: (socket: Duplex) => void): this;
|
||||
on(event: "error", listener: (err: Error) => void): this;
|
||||
on(event: "listening", listener: () => void): this;
|
||||
on(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
|
||||
on(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
|
||||
on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
|
||||
on(event: "connect", listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this;
|
||||
on(event: "request", listener: http.RequestListener<Request, Response>): this;
|
||||
on(event: "upgrade", listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this;
|
||||
once(event: string, listener: (...args: any[]) => void): this;
|
||||
once(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this;
|
||||
once(
|
||||
event: "newSession",
|
||||
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void,
|
||||
): this;
|
||||
once(
|
||||
event: "OCSPRequest",
|
||||
listener: (
|
||||
certificate: Buffer,
|
||||
issuer: Buffer,
|
||||
callback: (err: Error | null, resp: Buffer) => void,
|
||||
) => void,
|
||||
): this;
|
||||
once(
|
||||
event: "resumeSession",
|
||||
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void,
|
||||
): this;
|
||||
once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
|
||||
once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
|
||||
once(event: "close", listener: () => void): this;
|
||||
once(event: "connection", listener: (socket: Duplex) => void): this;
|
||||
once(event: "error", listener: (err: Error) => void): this;
|
||||
once(event: "listening", listener: () => void): this;
|
||||
once(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
|
||||
once(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
|
||||
once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
|
||||
once(event: "connect", listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this;
|
||||
once(event: "request", listener: http.RequestListener<Request, Response>): this;
|
||||
once(event: "upgrade", listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this;
|
||||
prependListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this;
|
||||
prependListener(
|
||||
event: "newSession",
|
||||
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void,
|
||||
): this;
|
||||
prependListener(
|
||||
event: "OCSPRequest",
|
||||
listener: (
|
||||
certificate: Buffer,
|
||||
issuer: Buffer,
|
||||
callback: (err: Error | null, resp: Buffer) => void,
|
||||
) => void,
|
||||
): this;
|
||||
prependListener(
|
||||
event: "resumeSession",
|
||||
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void,
|
||||
): this;
|
||||
prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
|
||||
prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
|
||||
prependListener(event: "close", listener: () => void): this;
|
||||
prependListener(event: "connection", listener: (socket: Duplex) => void): this;
|
||||
prependListener(event: "error", listener: (err: Error) => void): this;
|
||||
prependListener(event: "listening", listener: () => void): this;
|
||||
prependListener(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
|
||||
prependListener(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
|
||||
prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
|
||||
prependListener(
|
||||
event: "connect",
|
||||
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
|
||||
): this;
|
||||
prependListener(event: "request", listener: http.RequestListener<Request, Response>): this;
|
||||
prependListener(
|
||||
event: "upgrade",
|
||||
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
|
||||
): this;
|
||||
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
|
||||
prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this;
|
||||
prependOnceListener(
|
||||
event: "newSession",
|
||||
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void,
|
||||
): this;
|
||||
prependOnceListener(
|
||||
event: "OCSPRequest",
|
||||
listener: (
|
||||
certificate: Buffer,
|
||||
issuer: Buffer,
|
||||
callback: (err: Error | null, resp: Buffer) => void,
|
||||
) => void,
|
||||
): this;
|
||||
prependOnceListener(
|
||||
event: "resumeSession",
|
||||
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void,
|
||||
): this;
|
||||
prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
|
||||
prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
|
||||
prependOnceListener(event: "close", listener: () => void): this;
|
||||
prependOnceListener(event: "connection", listener: (socket: Duplex) => void): this;
|
||||
prependOnceListener(event: "error", listener: (err: Error) => void): this;
|
||||
prependOnceListener(event: "listening", listener: () => void): this;
|
||||
prependOnceListener(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
|
||||
prependOnceListener(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
|
||||
prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
|
||||
prependOnceListener(
|
||||
event: "connect",
|
||||
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
|
||||
): this;
|
||||
prependOnceListener(event: "request", listener: http.RequestListener<Request, Response>): this;
|
||||
prependOnceListener(
|
||||
event: "upgrade",
|
||||
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void,
|
||||
): this;
|
||||
}
|
||||
/**
|
||||
* ```js
|
||||
* // curl -k https://localhost:8000/
|
||||
* import https from 'node:https';
|
||||
* import fs from 'node:fs';
|
||||
*
|
||||
* const options = {
|
||||
* key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
|
||||
* cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
|
||||
* };
|
||||
*
|
||||
* https.createServer(options, (req, res) => {
|
||||
* res.writeHead(200);
|
||||
* res.end('hello world\n');
|
||||
* }).listen(8000);
|
||||
* ```
|
||||
*
|
||||
* Or
|
||||
*
|
||||
* ```js
|
||||
* import https from 'node:https';
|
||||
* import fs from 'node:fs';
|
||||
*
|
||||
* const options = {
|
||||
* pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
|
||||
* passphrase: 'sample',
|
||||
* };
|
||||
*
|
||||
* https.createServer(options, (req, res) => {
|
||||
* res.writeHead(200);
|
||||
* res.end('hello world\n');
|
||||
* }).listen(8000);
|
||||
* ```
|
||||
* @since v0.3.4
|
||||
* @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`.
|
||||
* @param requestListener A listener to be added to the `'request'` event.
|
||||
*/
|
||||
function createServer<
|
||||
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
|
||||
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
|
||||
>(requestListener?: http.RequestListener<Request, Response>): Server<Request, Response>;
|
||||
function createServer<
|
||||
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
|
||||
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
|
||||
>(
|
||||
options: ServerOptions<Request, Response>,
|
||||
requestListener?: http.RequestListener<Request, Response>,
|
||||
): Server<Request, Response>;
|
||||
/**
|
||||
* Makes a request to a secure web server.
|
||||
*
|
||||
* The following additional `options` from `tls.connect()` are also accepted: `ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`,
|
||||
* `pfx`, `rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`.
|
||||
*
|
||||
* `options` can be an object, a string, or a `URL` object. If `options` is a
|
||||
* string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
|
||||
*
|
||||
* `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to
|
||||
* upload a file with a POST request, then write to the `ClientRequest` object.
|
||||
*
|
||||
* ```js
|
||||
* import https from 'node:https';
|
||||
*
|
||||
* const options = {
|
||||
* hostname: 'encrypted.google.com',
|
||||
* port: 443,
|
||||
* path: '/',
|
||||
* method: 'GET',
|
||||
* };
|
||||
*
|
||||
* const req = https.request(options, (res) => {
|
||||
* console.log('statusCode:', res.statusCode);
|
||||
* console.log('headers:', res.headers);
|
||||
*
|
||||
* res.on('data', (d) => {
|
||||
* process.stdout.write(d);
|
||||
* });
|
||||
* });
|
||||
*
|
||||
* req.on('error', (e) => {
|
||||
* console.error(e);
|
||||
* });
|
||||
* req.end();
|
||||
* ```
|
||||
*
|
||||
* Example using options from `tls.connect()`:
|
||||
*
|
||||
* ```js
|
||||
* const options = {
|
||||
* hostname: 'encrypted.google.com',
|
||||
* port: 443,
|
||||
* path: '/',
|
||||
* method: 'GET',
|
||||
* key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
|
||||
* cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
|
||||
* };
|
||||
* options.agent = new https.Agent(options);
|
||||
*
|
||||
* const req = https.request(options, (res) => {
|
||||
* // ...
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Alternatively, opt out of connection pooling by not using an `Agent`.
|
||||
*
|
||||
* ```js
|
||||
* const options = {
|
||||
* hostname: 'encrypted.google.com',
|
||||
* port: 443,
|
||||
* path: '/',
|
||||
* method: 'GET',
|
||||
* key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
|
||||
* cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
|
||||
* agent: false,
|
||||
* };
|
||||
*
|
||||
* const req = https.request(options, (res) => {
|
||||
* // ...
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Example using a `URL` as `options`:
|
||||
*
|
||||
* ```js
|
||||
* const options = new URL('https://abc:xyz@example.com');
|
||||
*
|
||||
* const req = https.request(options, (res) => {
|
||||
* // ...
|
||||
* });
|
||||
* ```
|
||||
*
|
||||
* Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`):
|
||||
*
|
||||
* ```js
|
||||
* import tls from 'node:tls';
|
||||
* import https from 'node:https';
|
||||
* import crypto from 'node:crypto';
|
||||
*
|
||||
* function sha256(s) {
|
||||
* return crypto.createHash('sha256').update(s).digest('base64');
|
||||
* }
|
||||
* const options = {
|
||||
* hostname: 'github.com',
|
||||
* port: 443,
|
||||
* path: '/',
|
||||
* method: 'GET',
|
||||
* checkServerIdentity: function(host, cert) {
|
||||
* // Make sure the certificate is issued to the host we are connected to
|
||||
* const err = tls.checkServerIdentity(host, cert);
|
||||
* if (err) {
|
||||
* return err;
|
||||
* }
|
||||
*
|
||||
* // Pin the public key, similar to HPKP pin-sha256 pinning
|
||||
* const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';
|
||||
* if (sha256(cert.pubkey) !== pubkey256) {
|
||||
* const msg = 'Certificate verification error: ' +
|
||||
* `The public key of '${cert.subject.CN}' ` +
|
||||
* 'does not match our pinned fingerprint';
|
||||
* return new Error(msg);
|
||||
* }
|
||||
*
|
||||
* // Pin the exact certificate, rather than the pub key
|
||||
* const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' +
|
||||
* 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16';
|
||||
* if (cert.fingerprint256 !== cert256) {
|
||||
* const msg = 'Certificate verification error: ' +
|
||||
* `The certificate of '${cert.subject.CN}' ` +
|
||||
* 'does not match our pinned fingerprint';
|
||||
* return new Error(msg);
|
||||
* }
|
||||
*
|
||||
* // This loop is informational only.
|
||||
* // Print the certificate and public key fingerprints of all certs in the
|
||||
* // chain. Its common to pin the public key of the issuer on the public
|
||||
* // internet, while pinning the public key of the service in sensitive
|
||||
* // environments.
|
||||
* do {
|
||||
* console.log('Subject Common Name:', cert.subject.CN);
|
||||
* console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256);
|
||||
*
|
||||
* hash = crypto.createHash('sha256');
|
||||
* console.log(' Public key ping-sha256:', sha256(cert.pubkey));
|
||||
*
|
||||
* lastprint256 = cert.fingerprint256;
|
||||
* cert = cert.issuerCertificate;
|
||||
* } while (cert.fingerprint256 !== lastprint256);
|
||||
*
|
||||
* },
|
||||
* };
|
||||
*
|
||||
* options.agent = new https.Agent(options);
|
||||
* const req = https.request(options, (res) => {
|
||||
* console.log('All OK. Server matched our pinned cert or public key');
|
||||
* console.log('statusCode:', res.statusCode);
|
||||
* // Print the HPKP values
|
||||
* console.log('headers:', res.headers['public-key-pins']);
|
||||
*
|
||||
* res.on('data', (d) => {});
|
||||
* });
|
||||
*
|
||||
* req.on('error', (e) => {
|
||||
* console.error(e.message);
|
||||
* });
|
||||
* req.end();
|
||||
* ```
|
||||
*
|
||||
* Outputs for example:
|
||||
*
|
||||
* ```text
|
||||
* Subject Common Name: github.com
|
||||
* Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16
|
||||
* Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=
|
||||
* Subject Common Name: DigiCert SHA2 Extended Validation Server CA
|
||||
* Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A
|
||||
* Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=
|
||||
* Subject Common Name: DigiCert High Assurance EV Root CA
|
||||
* Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF
|
||||
* Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=
|
||||
* All OK. Server matched our pinned cert or public key
|
||||
* statusCode: 200
|
||||
* headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=";
|
||||
* pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4=";
|
||||
* pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains
|
||||
* ```
|
||||
* @since v0.3.6
|
||||
* @param options Accepts all `options` from `request`, with some differences in default values:
|
||||
*/
|
||||
function request(
|
||||
options: RequestOptions | string | URL,
|
||||
callback?: (res: http.IncomingMessage) => void,
|
||||
): http.ClientRequest;
|
||||
function request(
|
||||
url: string | URL,
|
||||
options: RequestOptions,
|
||||
callback?: (res: http.IncomingMessage) => void,
|
||||
): http.ClientRequest;
|
||||
/**
|
||||
* Like `http.get()` but for HTTPS.
|
||||
*
|
||||
* `options` can be an object, a string, or a `URL` object. If `options` is a
|
||||
* string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object.
|
||||
*
|
||||
* ```js
|
||||
* import https from 'node:https';
|
||||
*
|
||||
* https.get('https://encrypted.google.com/', (res) => {
|
||||
* console.log('statusCode:', res.statusCode);
|
||||
* console.log('headers:', res.headers);
|
||||
*
|
||||
* res.on('data', (d) => {
|
||||
* process.stdout.write(d);
|
||||
* });
|
||||
*
|
||||
* }).on('error', (e) => {
|
||||
* console.error(e);
|
||||
* });
|
||||
* ```
|
||||
* @since v0.3.6
|
||||
* @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`.
|
||||
*/
|
||||
function get(
|
||||
options: RequestOptions | string | URL,
|
||||
callback?: (res: http.IncomingMessage) => void,
|
||||
): http.ClientRequest;
|
||||
function get(
|
||||
url: string | URL,
|
||||
options: RequestOptions,
|
||||
callback?: (res: http.IncomingMessage) => void,
|
||||
): http.ClientRequest;
|
||||
let globalAgent: Agent;
|
||||
}
|
||||
declare module "node:https" {
|
||||
export * from "https";
|
||||
}
|
||||
94
frontend/e2e/node_modules/@types/node/index.d.ts
generated
vendored
Normal file
94
frontend/e2e/node_modules/@types/node/index.d.ts
generated
vendored
Normal file
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* License for programmatically and manually incorporated
|
||||
* documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc
|
||||
*
|
||||
* Copyright Node.js contributors. All rights reserved.
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to
|
||||
* deal in the Software without restriction, including without limitation the
|
||||
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
* sell copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
// NOTE: These definitions support Node.js and TypeScript 5.7+.
|
||||
|
||||
// Reference required TypeScript libs:
|
||||
/// <reference lib="es2020" />
|
||||
|
||||
// TypeScript backwards-compatibility definitions:
|
||||
/// <reference path="compatibility/index.d.ts" />
|
||||
|
||||
// Definitions specific to TypeScript 5.7+:
|
||||
/// <reference path="globals.typedarray.d.ts" />
|
||||
/// <reference path="buffer.buffer.d.ts" />
|
||||
|
||||
// Definitions for Node.js modules that are not specific to any version of TypeScript:
|
||||
/// <reference path="globals.d.ts" />
|
||||
/// <reference path="web-globals/abortcontroller.d.ts" />
|
||||
/// <reference path="web-globals/domexception.d.ts" />
|
||||
/// <reference path="web-globals/events.d.ts" />
|
||||
/// <reference path="web-globals/fetch.d.ts" />
|
||||
/// <reference path="assert.d.ts" />
|
||||
/// <reference path="assert/strict.d.ts" />
|
||||
/// <reference path="async_hooks.d.ts" />
|
||||
/// <reference path="buffer.d.ts" />
|
||||
/// <reference path="child_process.d.ts" />
|
||||
/// <reference path="cluster.d.ts" />
|
||||
/// <reference path="console.d.ts" />
|
||||
/// <reference path="constants.d.ts" />
|
||||
/// <reference path="crypto.d.ts" />
|
||||
/// <reference path="dgram.d.ts" />
|
||||
/// <reference path="diagnostics_channel.d.ts" />
|
||||
/// <reference path="dns.d.ts" />
|
||||
/// <reference path="dns/promises.d.ts" />
|
||||
/// <reference path="dns/promises.d.ts" />
|
||||
/// <reference path="domain.d.ts" />
|
||||
/// <reference path="events.d.ts" />
|
||||
/// <reference path="fs.d.ts" />
|
||||
/// <reference path="fs/promises.d.ts" />
|
||||
/// <reference path="http.d.ts" />
|
||||
/// <reference path="http2.d.ts" />
|
||||
/// <reference path="https.d.ts" />
|
||||
/// <reference path="inspector.d.ts" />
|
||||
/// <reference path="module.d.ts" />
|
||||
/// <reference path="net.d.ts" />
|
||||
/// <reference path="os.d.ts" />
|
||||
/// <reference path="path.d.ts" />
|
||||
/// <reference path="perf_hooks.d.ts" />
|
||||
/// <reference path="process.d.ts" />
|
||||
/// <reference path="punycode.d.ts" />
|
||||
/// <reference path="querystring.d.ts" />
|
||||
/// <reference path="readline.d.ts" />
|
||||
/// <reference path="readline/promises.d.ts" />
|
||||
/// <reference path="repl.d.ts" />
|
||||
/// <reference path="sea.d.ts" />
|
||||
/// <reference path="stream.d.ts" />
|
||||
/// <reference path="stream/promises.d.ts" />
|
||||
/// <reference path="stream/consumers.d.ts" />
|
||||
/// <reference path="stream/web.d.ts" />
|
||||
/// <reference path="string_decoder.d.ts" />
|
||||
/// <reference path="test.d.ts" />
|
||||
/// <reference path="timers.d.ts" />
|
||||
/// <reference path="timers/promises.d.ts" />
|
||||
/// <reference path="tls.d.ts" />
|
||||
/// <reference path="trace_events.d.ts" />
|
||||
/// <reference path="tty.d.ts" />
|
||||
/// <reference path="url.d.ts" />
|
||||
/// <reference path="util.d.ts" />
|
||||
/// <reference path="v8.d.ts" />
|
||||
/// <reference path="vm.d.ts" />
|
||||
/// <reference path="wasi.d.ts" />
|
||||
/// <reference path="worker_threads.d.ts" />
|
||||
/// <reference path="zlib.d.ts" />
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user