Added Statistics calculation
Statistics now show calculated values
This commit is contained in:
parent
fe87374e47
commit
fc0f69dacb
2147 changed files with 141321 additions and 39 deletions
319
node_modules/bun-types/docs/api/secrets.md
generated
vendored
Normal file
319
node_modules/bun-types/docs/api/secrets.md
generated
vendored
Normal file
|
|
@ -0,0 +1,319 @@
|
|||
Store and retrieve sensitive credentials securely using the operating system's native credential storage APIs.
|
||||
|
||||
**Experimental:** This API is new and experimental. It may change in the future.
|
||||
|
||||
```typescript
|
||||
import { secrets } from "bun";
|
||||
|
||||
const githubToken = await secrets.get({
|
||||
service: "my-cli-tool",
|
||||
name: "github-token",
|
||||
});
|
||||
|
||||
if (!githubToken) {
|
||||
const response = await fetch("https://api.github.com/name", {
|
||||
headers: { "Authorization": `token ${githubToken}` },
|
||||
});
|
||||
console.log("Please enter your GitHub token");
|
||||
} else {
|
||||
await secrets.set({
|
||||
service: "my-cli-tool",
|
||||
name: "github-token",
|
||||
value: prompt("Please enter your GitHub token"),
|
||||
});
|
||||
console.log("GitHub token stored");
|
||||
}
|
||||
```
|
||||
|
||||
## Overview
|
||||
|
||||
`Bun.secrets` provides a cross-platform API for managing sensitive credentials that CLI tools and development applications typically store in plaintext files like `~/.npmrc`, `~/.aws/credentials`, or `.env` files. It uses:
|
||||
|
||||
- **macOS**: Keychain Services
|
||||
- **Linux**: libsecret (GNOME Keyring, KWallet, etc.)
|
||||
- **Windows**: Windows Credential Manager
|
||||
|
||||
All operations are asynchronous and non-blocking, running on Bun's threadpool.
|
||||
|
||||
Note: in the future, we may add an additional `provider` option to make this better for production deployment secrets, but today this API is mostly useful for local development tools.
|
||||
|
||||
## API
|
||||
|
||||
### `Bun.secrets.get(options)`
|
||||
|
||||
Retrieve a stored credential.
|
||||
|
||||
```typescript
|
||||
import { secrets } from "bun";
|
||||
|
||||
const password = await Bun.secrets.get({
|
||||
service: "my-app",
|
||||
name: "alice@example.com",
|
||||
});
|
||||
// Returns: string | null
|
||||
|
||||
// Or if you prefer without an object
|
||||
const password = await Bun.secrets.get("my-app", "alice@example.com");
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `options.service` (string, required) - The service or application name
|
||||
- `options.name` (string, required) - The username or account identifier
|
||||
|
||||
**Returns:**
|
||||
|
||||
- `Promise<string | null>` - The stored password, or `null` if not found
|
||||
|
||||
### `Bun.secrets.set(options, value)`
|
||||
|
||||
Store or update a credential.
|
||||
|
||||
```typescript
|
||||
import { secrets } from "bun";
|
||||
|
||||
await secrets.set({
|
||||
service: "my-app",
|
||||
name: "alice@example.com",
|
||||
value: "super-secret-password",
|
||||
});
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `options.service` (string, required) - The service or application name
|
||||
- `options.name` (string, required) - The username or account identifier
|
||||
- `value` (string, required) - The password or secret to store
|
||||
|
||||
**Notes:**
|
||||
|
||||
- If a credential already exists for the given service/name combination, it will be replaced
|
||||
- The stored value is encrypted by the operating system
|
||||
|
||||
### `Bun.secrets.delete(options)`
|
||||
|
||||
Delete a stored credential.
|
||||
|
||||
```typescript
|
||||
const deleted = await Bun.secrets.delete({
|
||||
service: "my-app",
|
||||
name: "alice@example.com",
|
||||
value: "super-secret-password",
|
||||
});
|
||||
// Returns: boolean
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
|
||||
- `options.service` (string, required) - The service or application name
|
||||
- `options.name` (string, required) - The username or account identifier
|
||||
|
||||
**Returns:**
|
||||
|
||||
- `Promise<boolean>` - `true` if a credential was deleted, `false` if not found
|
||||
|
||||
## Examples
|
||||
|
||||
### Storing CLI Tool Credentials
|
||||
|
||||
```javascript
|
||||
// Store GitHub CLI token (instead of ~/.config/gh/hosts.yml)
|
||||
await Bun.secrets.set({
|
||||
service: "my-app.com",
|
||||
name: "github-token",
|
||||
value: "ghp_xxxxxxxxxxxxxxxxxxxx",
|
||||
});
|
||||
|
||||
// Or if you prefer without an object
|
||||
await Bun.secrets.set("my-app.com", "github-token", "ghp_xxxxxxxxxxxxxxxxxxxx");
|
||||
|
||||
// Store npm registry token (instead of ~/.npmrc)
|
||||
await Bun.secrets.set({
|
||||
service: "npm-registry",
|
||||
name: "https://registry.npmjs.org",
|
||||
value: "npm_xxxxxxxxxxxxxxxxxxxx",
|
||||
});
|
||||
|
||||
// Retrieve for API calls
|
||||
const token = await Bun.secrets.get({
|
||||
service: "gh-cli",
|
||||
name: "github.com",
|
||||
});
|
||||
|
||||
if (token) {
|
||||
const response = await fetch("https://api.github.com/name", {
|
||||
headers: {
|
||||
"Authorization": `token ${token}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
### Migrating from Plaintext Config Files
|
||||
|
||||
```javascript
|
||||
// Instead of storing in ~/.aws/credentials
|
||||
await Bun.secrets.set({
|
||||
service: "aws-cli",
|
||||
name: "AWS_SECRET_ACCESS_KEY",
|
||||
value: process.env.AWS_SECRET_ACCESS_KEY,
|
||||
});
|
||||
|
||||
// Instead of .env files with sensitive data
|
||||
await Bun.secrets.set({
|
||||
service: "my-app",
|
||||
name: "api-key",
|
||||
value: "sk_live_xxxxxxxxxxxxxxxxxxxx",
|
||||
});
|
||||
|
||||
// Load at runtime
|
||||
const apiKey =
|
||||
(await Bun.secrets.get({
|
||||
service: "my-app",
|
||||
name: "api-key",
|
||||
})) || process.env.API_KEY; // Fallback for CI/production
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
```javascript
|
||||
try {
|
||||
await Bun.secrets.set({
|
||||
service: "my-app",
|
||||
name: "alice",
|
||||
value: "password123",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Failed to store credential:", error.message);
|
||||
}
|
||||
|
||||
// Check if a credential exists
|
||||
const password = await Bun.secrets.get({
|
||||
service: "my-app",
|
||||
name: "alice",
|
||||
});
|
||||
|
||||
if (password === null) {
|
||||
console.log("No credential found");
|
||||
}
|
||||
```
|
||||
|
||||
### Updating Credentials
|
||||
|
||||
```javascript
|
||||
// Initial password
|
||||
await Bun.secrets.set({
|
||||
service: "email-server",
|
||||
name: "admin@example.com",
|
||||
value: "old-password",
|
||||
});
|
||||
|
||||
// Update to new password
|
||||
await Bun.secrets.set({
|
||||
service: "email-server",
|
||||
name: "admin@example.com",
|
||||
value: "new-password",
|
||||
});
|
||||
|
||||
// The old password is replaced
|
||||
```
|
||||
|
||||
## Platform Behavior
|
||||
|
||||
### macOS (Keychain)
|
||||
|
||||
- Credentials are stored in the name's login keychain
|
||||
- The keychain may prompt for access permission on first use
|
||||
- Credentials persist across system restarts
|
||||
- Accessible by the name who stored them
|
||||
|
||||
### Linux (libsecret)
|
||||
|
||||
- Requires a secret service daemon (GNOME Keyring, KWallet, etc.)
|
||||
- Credentials are stored in the default collection
|
||||
- May prompt for unlock if the keyring is locked
|
||||
- The secret service must be running
|
||||
|
||||
### Windows (Credential Manager)
|
||||
|
||||
- Credentials are stored in Windows Credential Manager
|
||||
- Visible in Control Panel → Credential Manager → Windows Credentials
|
||||
- Persist with `CRED_PERSIST_ENTERPRISE` flag so it's scoped per user
|
||||
- Encrypted using Windows Data Protection API
|
||||
|
||||
## Security Considerations
|
||||
|
||||
1. **Encryption**: Credentials are encrypted by the operating system's credential manager
|
||||
2. **Access Control**: Only the name who stored the credential can retrieve it
|
||||
3. **No Plain Text**: Passwords are never stored in plain text
|
||||
4. **Memory Safety**: Bun zeros out password memory after use
|
||||
5. **Process Isolation**: Credentials are isolated per name account
|
||||
|
||||
## Limitations
|
||||
|
||||
- Maximum password length varies by platform (typically 2048-4096 bytes)
|
||||
- Service and name names should be reasonable lengths (< 256 characters)
|
||||
- Some special characters may need escaping depending on the platform
|
||||
- Requires appropriate system services:
|
||||
- Linux: Secret service daemon must be running
|
||||
- macOS: Keychain Access must be available
|
||||
- Windows: Credential Manager service must be enabled
|
||||
|
||||
## Comparison with Environment Variables
|
||||
|
||||
Unlike environment variables, `Bun.secrets`:
|
||||
|
||||
- ✅ Encrypts credentials at rest (thanks to the operating system)
|
||||
- ✅ Avoids exposing secrets in process memory dumps (memory is zeroed after its no longer needed)
|
||||
- ✅ Survives application restarts
|
||||
- ✅ Can be updated without restarting the application
|
||||
- ✅ Provides name-level access control
|
||||
- ❌ Requires OS credential service
|
||||
- ❌ Not very useful for deployment secrets (use environment variables in production)
|
||||
|
||||
## Best Practices
|
||||
|
||||
1. **Use descriptive service names**: Match the tool or application name
|
||||
If you're building a CLI for external use, you probably should use a UTI (Uniform Type Identifier) for the service name.
|
||||
|
||||
```javascript
|
||||
// Good - matches the actual tool
|
||||
{ service: "com.docker.hub", name: "username" }
|
||||
{ service: "com.vercel.cli", name: "team-name" }
|
||||
|
||||
// Avoid - too generic
|
||||
{ service: "api", name: "key" }
|
||||
```
|
||||
|
||||
2. **Credentials-only**: Don't store application configuration in this API
|
||||
This API is slow, you probably still need to use a config file for some things.
|
||||
|
||||
3. **Use for local development tools**:
|
||||
- ✅ CLI tools (gh, npm, docker, kubectl)
|
||||
- ✅ Local development servers
|
||||
- ✅ Personal API keys for testing
|
||||
- ❌ Production servers (use proper secret management)
|
||||
|
||||
## TypeScript
|
||||
|
||||
```typescript
|
||||
namespace Bun {
|
||||
interface SecretsOptions {
|
||||
service: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface Secrets {
|
||||
get(options: SecretsOptions): Promise<string | null>;
|
||||
set(options: SecretsOptions, value: string): Promise<void>;
|
||||
delete(options: SecretsOptions): Promise<boolean>;
|
||||
}
|
||||
|
||||
const secrets: Secrets;
|
||||
}
|
||||
```
|
||||
|
||||
## See Also
|
||||
|
||||
- [Environment Variables](./env.md) - For deployment configuration
|
||||
- [Bun.password](./password.md) - For password hashing and verification
|
||||
459
node_modules/bun-types/docs/api/yaml.md
generated
vendored
Normal file
459
node_modules/bun-types/docs/api/yaml.md
generated
vendored
Normal file
|
|
@ -0,0 +1,459 @@
|
|||
In Bun, YAML is a first-class citizen alongside JSON and TOML.
|
||||
|
||||
Bun provides built-in support for YAML files through both runtime APIs and bundler integration. You can
|
||||
|
||||
- Parse YAML strings with `Bun.YAML.parse`
|
||||
- import & require YAML files as modules at runtime (including hot reloading & watch mode support)
|
||||
- import & require YAML files in frontend apps via bun's bundler
|
||||
|
||||
## Conformance
|
||||
|
||||
Bun's YAML parser currently passes over 90% of the official YAML test suite. While we're actively working on reaching 100% conformance, the current implementation covers the vast majority of real-world use cases. The parser is written in Zig for optimal performance and is continuously being improved.
|
||||
|
||||
## Runtime API
|
||||
|
||||
### `Bun.YAML.parse()`
|
||||
|
||||
Parse a YAML string into a JavaScript object.
|
||||
|
||||
```ts
|
||||
import { YAML } from "bun";
|
||||
const text = `
|
||||
name: John Doe
|
||||
age: 30
|
||||
email: john@example.com
|
||||
hobbies:
|
||||
- reading
|
||||
- coding
|
||||
- hiking
|
||||
`;
|
||||
|
||||
const data = YAML.parse(text);
|
||||
console.log(data);
|
||||
// {
|
||||
// name: "John Doe",
|
||||
// age: 30,
|
||||
// email: "john@example.com",
|
||||
// hobbies: ["reading", "coding", "hiking"]
|
||||
// }
|
||||
```
|
||||
|
||||
#### Multi-document YAML
|
||||
|
||||
When parsing YAML with multiple documents (separated by `---`), `Bun.YAML.parse()` returns an array:
|
||||
|
||||
```ts
|
||||
const multiDoc = `
|
||||
---
|
||||
name: Document 1
|
||||
---
|
||||
name: Document 2
|
||||
---
|
||||
name: Document 3
|
||||
`;
|
||||
|
||||
const docs = Bun.YAML.parse(multiDoc);
|
||||
console.log(docs);
|
||||
// [
|
||||
// { name: "Document 1" },
|
||||
// { name: "Document 2" },
|
||||
// { name: "Document 3" }
|
||||
// ]
|
||||
```
|
||||
|
||||
#### Supported YAML Features
|
||||
|
||||
Bun's YAML parser supports the full YAML 1.2 specification, including:
|
||||
|
||||
- **Scalars**: strings, numbers, booleans, null values
|
||||
- **Collections**: sequences (arrays) and mappings (objects)
|
||||
- **Anchors and Aliases**: reusable nodes with `&` and `*`
|
||||
- **Tags**: type hints like `!!str`, `!!int`, `!!float`, `!!bool`, `!!null`
|
||||
- **Multi-line strings**: literal (`|`) and folded (`>`) scalars
|
||||
- **Comments**: using `#`
|
||||
- **Directives**: `%YAML` and `%TAG`
|
||||
|
||||
```ts
|
||||
const yaml = `
|
||||
# Employee record
|
||||
employee: &emp
|
||||
name: Jane Smith
|
||||
department: Engineering
|
||||
skills:
|
||||
- JavaScript
|
||||
- TypeScript
|
||||
- React
|
||||
|
||||
manager: *emp # Reference to employee
|
||||
|
||||
config: !!str 123 # Explicit string type
|
||||
|
||||
description: |
|
||||
This is a multi-line
|
||||
literal string that preserves
|
||||
line breaks and spacing.
|
||||
|
||||
summary: >
|
||||
This is a folded string
|
||||
that joins lines with spaces
|
||||
unless there are blank lines.
|
||||
`;
|
||||
|
||||
const data = Bun.YAML.parse(yaml);
|
||||
```
|
||||
|
||||
#### Error Handling
|
||||
|
||||
`Bun.YAML.parse()` throws a `SyntaxError` if the YAML is invalid:
|
||||
|
||||
```ts
|
||||
try {
|
||||
Bun.YAML.parse("invalid: yaml: content:");
|
||||
} catch (error) {
|
||||
console.error("Failed to parse YAML:", error.message);
|
||||
}
|
||||
```
|
||||
|
||||
## Module Import
|
||||
|
||||
### ES Modules
|
||||
|
||||
You can import YAML files directly as ES modules. The YAML content is parsed and made available as both default and named exports:
|
||||
|
||||
```yaml#config.yaml
|
||||
database:
|
||||
host: localhost
|
||||
port: 5432
|
||||
name: myapp
|
||||
|
||||
redis:
|
||||
host: localhost
|
||||
port: 6379
|
||||
|
||||
features:
|
||||
auth: true
|
||||
rateLimit: true
|
||||
analytics: false
|
||||
```
|
||||
|
||||
#### Default Import
|
||||
|
||||
```ts#app.ts
|
||||
import config from "./config.yaml";
|
||||
|
||||
console.log(config.database.host); // "localhost"
|
||||
console.log(config.redis.port); // 6379
|
||||
```
|
||||
|
||||
#### Named Imports
|
||||
|
||||
You can destructure top-level YAML properties as named imports:
|
||||
|
||||
```ts
|
||||
import { database, redis, features } from "./config.yaml";
|
||||
|
||||
console.log(database.host); // "localhost"
|
||||
console.log(redis.port); // 6379
|
||||
console.log(features.auth); // true
|
||||
```
|
||||
|
||||
Or combine both:
|
||||
|
||||
```ts
|
||||
import config, { database, features } from "./config.yaml";
|
||||
|
||||
// Use the full config object
|
||||
console.log(config);
|
||||
|
||||
// Or use specific parts
|
||||
if (features.rateLimit) {
|
||||
setupRateLimiting(database);
|
||||
}
|
||||
```
|
||||
|
||||
### CommonJS
|
||||
|
||||
YAML files can also be required in CommonJS:
|
||||
|
||||
```js
|
||||
const config = require("./config.yaml");
|
||||
console.log(config.database.name); // "myapp"
|
||||
|
||||
// Destructuring also works
|
||||
const { database, redis } = require("./config.yaml");
|
||||
console.log(database.port); // 5432
|
||||
```
|
||||
|
||||
## Hot Reloading with YAML
|
||||
|
||||
One of the most powerful features of Bun's YAML support is hot reloading. When you run your application with `bun --hot`, changes to YAML files are automatically detected and reloaded without closing connections
|
||||
|
||||
### Configuration Hot Reloading
|
||||
|
||||
```yaml#config.yaml
|
||||
server:
|
||||
port: 3000
|
||||
host: localhost
|
||||
|
||||
features:
|
||||
debug: true
|
||||
verbose: false
|
||||
```
|
||||
|
||||
```ts#server.ts
|
||||
import { server, features } from "./config.yaml";
|
||||
|
||||
console.log(`Starting server on ${server.host}:${server.port}`);
|
||||
|
||||
if (features.debug) {
|
||||
console.log("Debug mode enabled");
|
||||
}
|
||||
|
||||
// Your server code here
|
||||
Bun.serve({
|
||||
port: server.port,
|
||||
hostname: server.host,
|
||||
fetch(req) {
|
||||
if (features.verbose) {
|
||||
console.log(`${req.method} ${req.url}`);
|
||||
}
|
||||
return new Response("Hello World");
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Run with hot reloading:
|
||||
|
||||
```bash
|
||||
bun --hot server.ts
|
||||
```
|
||||
|
||||
Now when you modify `config.yaml`, the changes are immediately reflected in your running application. This is perfect for:
|
||||
|
||||
- Adjusting configuration during development
|
||||
- Testing different settings without restarts
|
||||
- Live debugging with configuration changes
|
||||
- Feature flag toggling
|
||||
|
||||
## Configuration Management
|
||||
|
||||
### Environment-Based Configuration
|
||||
|
||||
YAML excels at managing configuration across different environments:
|
||||
|
||||
```yaml#config.yaml
|
||||
defaults: &defaults
|
||||
timeout: 5000
|
||||
retries: 3
|
||||
cache:
|
||||
enabled: true
|
||||
ttl: 3600
|
||||
|
||||
development:
|
||||
<<: *defaults
|
||||
api:
|
||||
url: http://localhost:4000
|
||||
key: dev_key_12345
|
||||
logging:
|
||||
level: debug
|
||||
pretty: true
|
||||
|
||||
staging:
|
||||
<<: *defaults
|
||||
api:
|
||||
url: https://staging-api.example.com
|
||||
key: ${STAGING_API_KEY}
|
||||
logging:
|
||||
level: info
|
||||
pretty: false
|
||||
|
||||
production:
|
||||
<<: *defaults
|
||||
api:
|
||||
url: https://api.example.com
|
||||
key: ${PROD_API_KEY}
|
||||
cache:
|
||||
enabled: true
|
||||
ttl: 86400
|
||||
logging:
|
||||
level: error
|
||||
pretty: false
|
||||
```
|
||||
|
||||
```ts#app.ts
|
||||
import configs from "./config.yaml";
|
||||
|
||||
const env = process.env.NODE_ENV || "development";
|
||||
const config = configs[env];
|
||||
|
||||
// Environment variables in YAML values can be interpolated
|
||||
function interpolateEnvVars(obj: any): any {
|
||||
if (typeof obj === "string") {
|
||||
return obj.replace(/\${(\w+)}/g, (_, key) => process.env[key] || "");
|
||||
}
|
||||
if (typeof obj === "object") {
|
||||
for (const key in obj) {
|
||||
obj[key] = interpolateEnvVars(obj[key]);
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
export default interpolateEnvVars(config);
|
||||
```
|
||||
|
||||
### Feature Flags Configuration
|
||||
|
||||
```yaml#features.yaml
|
||||
features:
|
||||
newDashboard:
|
||||
enabled: true
|
||||
rolloutPercentage: 50
|
||||
allowedUsers:
|
||||
- admin@example.com
|
||||
- beta@example.com
|
||||
|
||||
experimentalAPI:
|
||||
enabled: false
|
||||
endpoints:
|
||||
- /api/v2/experimental
|
||||
- /api/v2/beta
|
||||
|
||||
darkMode:
|
||||
enabled: true
|
||||
default: auto # auto, light, dark
|
||||
```
|
||||
|
||||
```ts#feature-flags.ts
|
||||
import { features } from "./features.yaml";
|
||||
|
||||
export function isFeatureEnabled(
|
||||
featureName: string,
|
||||
userEmail?: string,
|
||||
): boolean {
|
||||
const feature = features[featureName];
|
||||
|
||||
if (!feature?.enabled) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check rollout percentage
|
||||
if (feature.rolloutPercentage < 100) {
|
||||
const hash = hashCode(userEmail || "anonymous");
|
||||
if (hash % 100 >= feature.rolloutPercentage) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Check allowed users
|
||||
if (feature.allowedUsers && userEmail) {
|
||||
return feature.allowedUsers.includes(userEmail);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Use with hot reloading to toggle features in real-time
|
||||
if (isFeatureEnabled("newDashboard", user.email)) {
|
||||
renderNewDashboard();
|
||||
} else {
|
||||
renderLegacyDashboard();
|
||||
}
|
||||
```
|
||||
|
||||
### Database Configuration
|
||||
|
||||
```yaml#database.yaml
|
||||
connections:
|
||||
primary:
|
||||
type: postgres
|
||||
host: ${DB_HOST:-localhost}
|
||||
port: ${DB_PORT:-5432}
|
||||
database: ${DB_NAME:-myapp}
|
||||
username: ${DB_USER:-postgres}
|
||||
password: ${DB_PASS}
|
||||
pool:
|
||||
min: 2
|
||||
max: 10
|
||||
idleTimeout: 30000
|
||||
|
||||
cache:
|
||||
type: redis
|
||||
host: ${REDIS_HOST:-localhost}
|
||||
port: ${REDIS_PORT:-6379}
|
||||
password: ${REDIS_PASS}
|
||||
db: 0
|
||||
|
||||
analytics:
|
||||
type: clickhouse
|
||||
host: ${ANALYTICS_HOST:-localhost}
|
||||
port: 8123
|
||||
database: analytics
|
||||
|
||||
migrations:
|
||||
autoRun: ${AUTO_MIGRATE:-false}
|
||||
directory: ./migrations
|
||||
|
||||
seeds:
|
||||
enabled: ${SEED_DB:-false}
|
||||
directory: ./seeds
|
||||
```
|
||||
|
||||
```ts#db.ts
|
||||
import { connections, migrations } from "./database.yaml";
|
||||
import { createConnection } from "./database-driver";
|
||||
|
||||
// Parse environment variables with defaults
|
||||
function parseConfig(config: any) {
|
||||
return JSON.parse(
|
||||
JSON.stringify(config).replace(
|
||||
/\${([^:-]+)(?::([^}]+))?}/g,
|
||||
(_, key, defaultValue) => process.env[key] || defaultValue || "",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const dbConfig = parseConfig(connections);
|
||||
|
||||
export const db = await createConnection(dbConfig.primary);
|
||||
export const cache = await createConnection(dbConfig.cache);
|
||||
export const analytics = await createConnection(dbConfig.analytics);
|
||||
|
||||
// Auto-run migrations if configured
|
||||
if (parseConfig(migrations).autoRun === "true") {
|
||||
await runMigrations(db, migrations.directory);
|
||||
}
|
||||
```
|
||||
|
||||
### Bundler Integration
|
||||
|
||||
When you import YAML files in your application and bundle it with Bun, the YAML is parsed at build time and included as a JavaScript module:
|
||||
|
||||
```bash
|
||||
bun build app.ts --outdir=dist
|
||||
```
|
||||
|
||||
This means:
|
||||
|
||||
- Zero runtime YAML parsing overhead in production
|
||||
- Smaller bundle sizes
|
||||
- Tree-shaking support for unused configuration (named imports)
|
||||
|
||||
### Dynamic Imports
|
||||
|
||||
YAML files can be dynamically imported, useful for loading configuration on demand:
|
||||
|
||||
```ts#Load configuration based on environment
|
||||
const env = process.env.NODE_ENV || "development";
|
||||
const config = await import(`./configs/${env}.yaml`);
|
||||
|
||||
// Load user-specific settings
|
||||
async function loadUserSettings(userId: string) {
|
||||
try {
|
||||
const settings = await import(`./users/${userId}/settings.yaml`);
|
||||
return settings.default;
|
||||
} catch {
|
||||
return await import("./users/default-settings.yaml");
|
||||
}
|
||||
}
|
||||
```
|
||||
76
node_modules/bun-types/docs/guides/runtime/import-yaml.md
generated
vendored
Normal file
76
node_modules/bun-types/docs/guides/runtime/import-yaml.md
generated
vendored
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
---
|
||||
name: Import a YAML file
|
||||
---
|
||||
|
||||
Bun natively supports `.yaml` and `.yml` imports.
|
||||
|
||||
```yaml#config.yaml
|
||||
database:
|
||||
host: localhost
|
||||
port: 5432
|
||||
name: myapp
|
||||
|
||||
server:
|
||||
port: 3000
|
||||
timeout: 30
|
||||
|
||||
features:
|
||||
auth: true
|
||||
rateLimit: true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
Import the file like any other source file.
|
||||
|
||||
```ts
|
||||
import config from "./config.yaml";
|
||||
|
||||
config.database.host; // => "localhost"
|
||||
config.server.port; // => 3000
|
||||
config.features.auth; // => true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
You can also use named imports to destructure top-level properties:
|
||||
|
||||
```ts
|
||||
import { database, server, features } from "./config.yaml";
|
||||
|
||||
console.log(database.name); // => "myapp"
|
||||
console.log(server.timeout); // => 30
|
||||
console.log(features.rateLimit); // => true
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
Bun also supports [Import Attributes](https://github.com/tc39/proposal-import-attributes) syntax:
|
||||
|
||||
```ts
|
||||
import config from "./config.yaml" with { type: "yaml" };
|
||||
|
||||
config.database.port; // => 5432
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
For parsing YAML strings at runtime, use `Bun.YAML.parse()`:
|
||||
|
||||
```ts
|
||||
const yamlString = `
|
||||
name: John Doe
|
||||
age: 30
|
||||
hobbies:
|
||||
- reading
|
||||
- coding
|
||||
`;
|
||||
|
||||
const data = Bun.YAML.parse(yamlString);
|
||||
console.log(data.name); // => "John Doe"
|
||||
console.log(data.hobbies); // => ["reading", "coding"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
See [Docs > API > YAML](https://bun.com/docs/api/yaml) for complete documentation on YAML support in Bun.
|
||||
195
node_modules/bun-types/docs/install/isolated.md
generated
vendored
Normal file
195
node_modules/bun-types/docs/install/isolated.md
generated
vendored
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
Bun provides an alternative package installation strategy called **isolated installs** that creates strict dependency isolation similar to pnpm's approach. This mode prevents phantom dependencies and ensures reproducible, deterministic builds.
|
||||
|
||||
## What are isolated installs?
|
||||
|
||||
Isolated installs create a non-hoisted dependency structure where packages can only access their explicitly declared dependencies. This differs from the traditional "hoisted" installation strategy used by npm and Yarn, where dependencies are flattened into a shared `node_modules` directory.
|
||||
|
||||
### Key benefits
|
||||
|
||||
- **Prevents phantom dependencies** — Packages cannot accidentally import dependencies they haven't declared
|
||||
- **Deterministic resolution** — Same dependency tree regardless of what else is installed
|
||||
- **Better for monorepos** — Workspace isolation prevents cross-contamination between packages
|
||||
- **Reproducible builds** — More predictable resolution behavior across environments
|
||||
|
||||
## Using isolated installs
|
||||
|
||||
### Command line
|
||||
|
||||
Use the `--linker` flag to specify the installation strategy:
|
||||
|
||||
```bash
|
||||
# Use isolated installs
|
||||
$ bun install --linker isolated
|
||||
|
||||
# Use traditional hoisted installs
|
||||
$ bun install --linker hoisted
|
||||
```
|
||||
|
||||
### Configuration file
|
||||
|
||||
Set the default linker strategy in your `bunfig.toml`:
|
||||
|
||||
```toml
|
||||
[install]
|
||||
linker = "isolated"
|
||||
```
|
||||
|
||||
### Default behavior
|
||||
|
||||
By default, Bun uses the **hoisted** installation strategy for all projects. To use isolated installs, you must explicitly specify the `--linker isolated` flag or set it in your configuration file.
|
||||
|
||||
## How isolated installs work
|
||||
|
||||
### Directory structure
|
||||
|
||||
Instead of hoisting dependencies, isolated installs create a two-tier structure:
|
||||
|
||||
```
|
||||
node_modules/
|
||||
├── .bun/ # Central package store
|
||||
│ ├── package@1.0.0/ # Versioned package installations
|
||||
│ │ └── node_modules/
|
||||
│ │ └── package/ # Actual package files
|
||||
│ ├── @scope+package@2.1.0/ # Scoped packages (+ replaces /)
|
||||
│ │ └── node_modules/
|
||||
│ │ └── @scope/
|
||||
│ │ └── package/
|
||||
│ └── ...
|
||||
└── package-name -> .bun/package@1.0.0/node_modules/package # Symlinks
|
||||
```
|
||||
|
||||
### Resolution algorithm
|
||||
|
||||
1. **Central store** — All packages are installed in `node_modules/.bun/package@version/` directories
|
||||
2. **Symlinks** — Top-level `node_modules` contains symlinks pointing to the central store
|
||||
3. **Peer resolution** — Complex peer dependencies create specialized directory names
|
||||
4. **Deduplication** — Packages with identical package IDs and peer dependency sets are shared
|
||||
|
||||
### Workspace handling
|
||||
|
||||
In monorepos, workspace dependencies are handled specially:
|
||||
|
||||
- **Workspace packages** — Symlinked directly to their source directories, not the store
|
||||
- **Workspace dependencies** — Can access other workspace packages in the monorepo
|
||||
- **External dependencies** — Installed in the isolated store with proper isolation
|
||||
|
||||
## Comparison with hoisted installs
|
||||
|
||||
| Aspect | Hoisted (npm/Yarn) | Isolated (pnpm-like) |
|
||||
| ------------------------- | ------------------------------------------ | --------------------------------------- |
|
||||
| **Dependency access** | Packages can access any hoisted dependency | Packages only see declared dependencies |
|
||||
| **Phantom dependencies** | ❌ Possible | ✅ Prevented |
|
||||
| **Disk usage** | ✅ Lower (shared installs) | ✅ Similar (uses symlinks) |
|
||||
| **Determinism** | ❌ Less deterministic | ✅ More deterministic |
|
||||
| **Node.js compatibility** | ✅ Standard behavior | ✅ Compatible via symlinks |
|
||||
| **Best for** | Single projects, legacy code | Monorepos, strict dependency management |
|
||||
|
||||
## Advanced features
|
||||
|
||||
### Peer dependency handling
|
||||
|
||||
Isolated installs handle peer dependencies through sophisticated resolution:
|
||||
|
||||
```bash
|
||||
# Package with peer dependencies creates specialized paths
|
||||
node_modules/.bun/package@1.0.0_react@18.2.0/
|
||||
```
|
||||
|
||||
The directory name encodes both the package version and its peer dependency versions, ensuring each unique combination gets its own installation.
|
||||
|
||||
### Backend strategies
|
||||
|
||||
Bun uses different file operation strategies for performance:
|
||||
|
||||
- **Clonefile** (macOS) — Copy-on-write filesystem clones for maximum efficiency
|
||||
- **Hardlink** (Linux/Windows) — Hardlinks to save disk space
|
||||
- **Copyfile** (fallback) — Full file copies when other methods aren't available
|
||||
|
||||
### Debugging isolated installs
|
||||
|
||||
Enable verbose logging to understand the installation process:
|
||||
|
||||
```bash
|
||||
$ bun install --linker isolated --verbose
|
||||
```
|
||||
|
||||
This shows:
|
||||
|
||||
- Store entry creation
|
||||
- Symlink operations
|
||||
- Peer dependency resolution
|
||||
- Deduplication decisions
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Compatibility issues
|
||||
|
||||
Some packages may not work correctly with isolated installs due to:
|
||||
|
||||
- **Hardcoded paths** — Packages that assume a flat `node_modules` structure
|
||||
- **Dynamic imports** — Runtime imports that don't follow Node.js resolution
|
||||
- **Build tools** — Tools that scan `node_modules` directly
|
||||
|
||||
If you encounter issues, you can:
|
||||
|
||||
1. **Switch to hoisted mode** for specific projects:
|
||||
|
||||
```bash
|
||||
$ bun install --linker hoisted
|
||||
```
|
||||
|
||||
2. **Report compatibility issues** to help improve isolated install support
|
||||
|
||||
### Performance considerations
|
||||
|
||||
- **Install time** — May be slightly slower due to symlink operations
|
||||
- **Disk usage** — Similar to hoisted (uses symlinks, not file copies)
|
||||
- **Memory usage** — Higher during install due to complex peer resolution
|
||||
|
||||
## Migration guide
|
||||
|
||||
### From npm/Yarn
|
||||
|
||||
```bash
|
||||
# Remove existing node_modules and lockfiles
|
||||
$ rm -rf node_modules package-lock.json yarn.lock
|
||||
|
||||
# Install with isolated linker
|
||||
$ bun install --linker isolated
|
||||
```
|
||||
|
||||
### From pnpm
|
||||
|
||||
Isolated installs are conceptually similar to pnpm, so migration should be straightforward:
|
||||
|
||||
```bash
|
||||
# Remove pnpm files
|
||||
$ rm -rf node_modules pnpm-lock.yaml
|
||||
|
||||
# Install with Bun's isolated linker
|
||||
$ bun install --linker isolated
|
||||
```
|
||||
|
||||
The main difference is that Bun uses symlinks in `node_modules` while pnpm uses a global store with symlinks.
|
||||
|
||||
## When to use isolated installs
|
||||
|
||||
**Use isolated installs when:**
|
||||
|
||||
- Working in monorepos with multiple packages
|
||||
- Strict dependency management is required
|
||||
- Preventing phantom dependencies is important
|
||||
- Building libraries that need deterministic dependencies
|
||||
|
||||
**Use hoisted installs when:**
|
||||
|
||||
- Working with legacy code that assumes flat `node_modules`
|
||||
- Compatibility with existing build tools is required
|
||||
- Working in environments where symlinks aren't well supported
|
||||
- You prefer the simpler traditional npm behavior
|
||||
|
||||
## Related documentation
|
||||
|
||||
- [Package manager > Workspaces](https://bun.com/docs/install/workspaces) — Monorepo workspace management
|
||||
- [Package manager > Lockfile](https://bun.com/docs/install/lockfile) — Understanding Bun's lockfile format
|
||||
- [CLI > install](https://bun.com/docs/cli/install) — Complete `bun install` command reference
|
||||
81
node_modules/bun-types/docs/install/security-scanner-api.md
generated
vendored
Normal file
81
node_modules/bun-types/docs/install/security-scanner-api.md
generated
vendored
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
Bun's package manager can scan packages for security vulnerabilities before installation, helping protect your applications from supply chain attacks and known vulnerabilities.
|
||||
|
||||
## Quick Start
|
||||
|
||||
Configure a security scanner in your `bunfig.toml`:
|
||||
|
||||
```toml
|
||||
[install.security]
|
||||
scanner = "@acme/bun-security-scanner"
|
||||
```
|
||||
|
||||
When configured, Bun will:
|
||||
|
||||
- Scan all packages before installation
|
||||
- Display security warnings and advisories
|
||||
- Cancel installation if critical vulnerabilities are found
|
||||
- Automatically disable auto-install for security
|
||||
|
||||
## How It Works
|
||||
|
||||
Security scanners analyze packages during `bun install`, `bun add`, and other package operations. They can detect:
|
||||
|
||||
- Known security vulnerabilities (CVEs)
|
||||
- Malicious packages
|
||||
- License compliance issues
|
||||
- ...and more!
|
||||
|
||||
### Security Levels
|
||||
|
||||
Scanners report issues at two severity levels:
|
||||
|
||||
- **`fatal`** - Installation stops immediately, exits with non-zero code
|
||||
- **`warn`** - In interactive terminals, prompts to continue; in CI, exits immediately
|
||||
|
||||
## Using Pre-built Scanners
|
||||
|
||||
Many security companies publish Bun security scanners as npm packages that you can install and use immediately.
|
||||
|
||||
### Installing a Scanner
|
||||
|
||||
Install a security scanner from npm:
|
||||
|
||||
```bash
|
||||
$ bun add -d @acme/bun-security-scanner
|
||||
```
|
||||
|
||||
> **Note:** Consult your security scanner's documentation for their specific package name and installation instructions. Most scanners will be installed with `bun add`.
|
||||
|
||||
### Configuring the Scanner
|
||||
|
||||
After installation, configure it in your `bunfig.toml`:
|
||||
|
||||
```toml
|
||||
[install.security]
|
||||
scanner = "@acme/bun-security-scanner"
|
||||
```
|
||||
|
||||
### Enterprise Configuration
|
||||
|
||||
Some enterprise scanners might support authentication and/or configuration through environment variables:
|
||||
|
||||
```bash
|
||||
# This might go in ~/.bashrc, for example
|
||||
export SECURITY_API_KEY="your-api-key"
|
||||
|
||||
# The scanner will now use these credentials automatically
|
||||
bun install
|
||||
```
|
||||
|
||||
Consult your security scanner's documentation to learn which environment variables to set and if any additional configuration is required.
|
||||
|
||||
### Authoring your own scanner
|
||||
|
||||
For a complete example with tests and CI setup, see the official template:
|
||||
[github.com/oven-sh/security-scanner-template](https://github.com/oven-sh/security-scanner-template)
|
||||
|
||||
## Related
|
||||
|
||||
- [Configuration (bunfig.toml)](/docs/runtime/bunfig#installsecurityscanner)
|
||||
- [Package Manager](/docs/install)
|
||||
- [Security Scanner Template](https://github.com/oven-sh/security-scanner-template)
|
||||
101
node_modules/bun-types/security.d.ts
generated
vendored
Normal file
101
node_modules/bun-types/security.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
declare module "bun" {
|
||||
/**
|
||||
* `bun install` security related declarations
|
||||
*/
|
||||
export namespace Security {
|
||||
export interface Package {
|
||||
/**
|
||||
* The name of the package
|
||||
*/
|
||||
name: string;
|
||||
|
||||
/**
|
||||
* The resolved version to be installed that matches the requested range.
|
||||
*
|
||||
* This is the exact version string, **not** a range.
|
||||
*/
|
||||
version: string;
|
||||
|
||||
/**
|
||||
* The URL of the tgz of this package that Bun will download
|
||||
*/
|
||||
tarball: string;
|
||||
|
||||
/**
|
||||
* The range that was requested by the command
|
||||
*
|
||||
* This could be a tag like `beta` or a semver range like `>=4.0.0`
|
||||
*/
|
||||
requestedRange: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Advisory represents the result of a security scan result of a package
|
||||
*/
|
||||
export interface Advisory {
|
||||
/**
|
||||
* Level represents the degree of danger for a security advisory
|
||||
*
|
||||
* Bun behaves differently depending on the values returned from the
|
||||
* {@link Scanner.scan `scan()`} hook:
|
||||
*
|
||||
* > In any case, Bun *always* pretty prints *all* the advisories,
|
||||
* > but...
|
||||
* >
|
||||
* > → if any **fatal**, Bun will immediately cancel the installation
|
||||
* > and quit with a non-zero exit code
|
||||
* >
|
||||
* > → else if any **warn**, Bun will either ask the user if they'd like
|
||||
* > to continue with the install if in a TTY environment, or
|
||||
* > immediately exit if not.
|
||||
*/
|
||||
level: "fatal" | "warn";
|
||||
|
||||
/**
|
||||
* The name of the package attempting to be installed.
|
||||
*/
|
||||
package: string;
|
||||
|
||||
/**
|
||||
* If available, this is a url linking to a CVE or report online so
|
||||
* users can learn more about the advisory.
|
||||
*/
|
||||
url: string | null;
|
||||
|
||||
/**
|
||||
* If available, this is a brief description of the advisory that Bun
|
||||
* will print to the user.
|
||||
*/
|
||||
description: string | null;
|
||||
}
|
||||
|
||||
export interface Scanner {
|
||||
/**
|
||||
* This is the version of the scanner implementation. It may change in
|
||||
* future versions, so we will use this version to discriminate between
|
||||
* such versions. It's entirely possible this API changes in the future
|
||||
* so much that version 1 would no longer be supported.
|
||||
*
|
||||
* The version is required because third-party scanner package versions
|
||||
* are inherently unrelated to Bun versions
|
||||
*/
|
||||
version: "1";
|
||||
|
||||
/**
|
||||
* Perform an advisory check when a user ran `bun add <package>
|
||||
* [...packages]` or other related/similar commands.
|
||||
*
|
||||
* If this function throws an error, Bun will immediately stop the
|
||||
* install process and print the error to the user.
|
||||
*
|
||||
* @param info An object containing an array of packages to be added.
|
||||
* The package array will contain all proposed dependencies, including
|
||||
* transitive ones. More simply, that means it will include dependencies
|
||||
* of the packages the user wants to add.
|
||||
*
|
||||
* @returns A list of advisories.
|
||||
*/
|
||||
scan: (info: { packages: Package[] }) => Promise<Advisory[]>;
|
||||
}
|
||||
}
|
||||
}
|
||||
809
node_modules/bun-types/sql.d.ts
generated
vendored
Normal file
809
node_modules/bun-types/sql.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,809 @@
|
|||
import type * as BunSQLite from "bun:sqlite";
|
||||
|
||||
declare module "bun" {
|
||||
/**
|
||||
* Represents a reserved connection from the connection pool Extends SQL with
|
||||
* additional release functionality
|
||||
*/
|
||||
interface ReservedSQL extends SQL, Disposable {
|
||||
/**
|
||||
* Releases the client back to the connection pool
|
||||
*/
|
||||
release(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a client within a transaction context Extends SQL with savepoint
|
||||
* functionality
|
||||
*/
|
||||
interface TransactionSQL extends SQL {
|
||||
/**
|
||||
* Creates a savepoint within the current transaction
|
||||
*/
|
||||
savepoint<T>(name: string, fn: SQL.SavepointContextCallback<T>): Promise<T>;
|
||||
savepoint<T>(fn: SQL.SavepointContextCallback<T>): Promise<T>;
|
||||
|
||||
/**
|
||||
* The reserve method pulls out a connection from the pool, and returns a
|
||||
* client that wraps the single connection.
|
||||
*
|
||||
* Using reserve() inside of a transaction will return a brand new
|
||||
* connection, not one related to the transaction. This matches the
|
||||
* behaviour of the `postgres` package.
|
||||
*/
|
||||
reserve(): Promise<ReservedSQL>;
|
||||
}
|
||||
|
||||
namespace SQL {
|
||||
class SQLError extends Error {
|
||||
constructor(message: string);
|
||||
}
|
||||
|
||||
class PostgresError extends SQLError {
|
||||
public readonly code: string;
|
||||
public readonly errno: string | undefined;
|
||||
public readonly detail: string | undefined;
|
||||
public readonly hint: string | undefined;
|
||||
public readonly severity: string | undefined;
|
||||
public readonly position: string | undefined;
|
||||
public readonly internalPosition: string | undefined;
|
||||
public readonly internalQuery: string | undefined;
|
||||
public readonly where: string | undefined;
|
||||
public readonly schema: string | undefined;
|
||||
public readonly table: string | undefined;
|
||||
public readonly column: string | undefined;
|
||||
public readonly dataType: string | undefined;
|
||||
public readonly constraint: string | undefined;
|
||||
public readonly file: string | undefined;
|
||||
public readonly line: string | undefined;
|
||||
public readonly routine: string | undefined;
|
||||
|
||||
constructor(
|
||||
message: string,
|
||||
options: {
|
||||
code: string;
|
||||
errno?: string | undefined;
|
||||
detail?: string;
|
||||
hint?: string | undefined;
|
||||
severity?: string | undefined;
|
||||
position?: string | undefined;
|
||||
internalPosition?: string;
|
||||
internalQuery?: string;
|
||||
where?: string | undefined;
|
||||
schema?: string;
|
||||
table?: string | undefined;
|
||||
column?: string | undefined;
|
||||
dataType?: string | undefined;
|
||||
constraint?: string;
|
||||
file?: string | undefined;
|
||||
line?: string | undefined;
|
||||
routine?: string | undefined;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
class MySQLError extends SQLError {
|
||||
public readonly code: string;
|
||||
public readonly errno: number | undefined;
|
||||
public readonly sqlState: string | undefined;
|
||||
constructor(message: string, options: { code: string; errno: number | undefined; sqlState: string | undefined });
|
||||
}
|
||||
|
||||
class SQLiteError extends SQLError {
|
||||
public readonly code: string;
|
||||
public readonly errno: number;
|
||||
public readonly byteOffset?: number | undefined;
|
||||
|
||||
constructor(message: string, options: { code: string; errno: number; byteOffset?: number | undefined });
|
||||
}
|
||||
|
||||
type AwaitPromisesArray<T extends Array<PromiseLike<any>>> = {
|
||||
[K in keyof T]: Awaited<T[K]>;
|
||||
};
|
||||
|
||||
type ContextCallbackResult<T> = T extends Array<PromiseLike<any>> ? AwaitPromisesArray<T> : Awaited<T>;
|
||||
type ContextCallback<T, SQL> = (sql: SQL) => Bun.MaybePromise<T>;
|
||||
|
||||
interface SQLiteOptions extends BunSQLite.DatabaseOptions {
|
||||
adapter?: "sqlite";
|
||||
|
||||
/**
|
||||
* Specify the path to the database file
|
||||
*
|
||||
* Examples:
|
||||
*
|
||||
* - `sqlite://:memory:`
|
||||
* - `sqlite://./path/to/database.db`
|
||||
* - `sqlite:///Users/bun/projects/my-app/database.db`
|
||||
* - `./dev.db`
|
||||
* - `:memory:`
|
||||
*
|
||||
* @default ":memory:"
|
||||
*/
|
||||
filename?: URL | ":memory:" | (string & {}) | undefined;
|
||||
|
||||
/**
|
||||
* Callback executed when a connection attempt completes (SQLite)
|
||||
* Receives an Error on failure, or null on success.
|
||||
*/
|
||||
onconnect?: ((err: Error | null) => void) | undefined;
|
||||
|
||||
/**
|
||||
* Callback executed when a connection is closed (SQLite)
|
||||
* Receives the closing Error or null.
|
||||
*/
|
||||
onclose?: ((err: Error | null) => void) | undefined;
|
||||
}
|
||||
|
||||
interface PostgresOrMySQLOptions {
|
||||
/**
|
||||
* Connection URL (can be string or URL object)
|
||||
*/
|
||||
url?: URL | string | undefined;
|
||||
|
||||
/**
|
||||
* Database server hostname
|
||||
* @default "localhost"
|
||||
*/
|
||||
host?: string | undefined;
|
||||
|
||||
/**
|
||||
* Database server hostname (alias for host)
|
||||
* @deprecated Prefer {@link host}
|
||||
* @default "localhost"
|
||||
*/
|
||||
hostname?: string | undefined;
|
||||
|
||||
/**
|
||||
* Database server port number
|
||||
* @default 5432
|
||||
*/
|
||||
port?: number | string | undefined;
|
||||
|
||||
/**
|
||||
* Database user for authentication
|
||||
* @default "postgres"
|
||||
*/
|
||||
username?: string | undefined;
|
||||
|
||||
/**
|
||||
* Database user for authentication (alias for username)
|
||||
* @deprecated Prefer {@link username}
|
||||
* @default "postgres"
|
||||
*/
|
||||
user?: string | undefined;
|
||||
|
||||
/**
|
||||
* Database password for authentication
|
||||
* @default ""
|
||||
*/
|
||||
password?: string | (() => MaybePromise<string>) | undefined;
|
||||
|
||||
/**
|
||||
* Database password for authentication (alias for password)
|
||||
* @deprecated Prefer {@link password}
|
||||
* @default ""
|
||||
*/
|
||||
pass?: string | (() => MaybePromise<string>) | undefined;
|
||||
|
||||
/**
|
||||
* Name of the database to connect to
|
||||
* @default The username value
|
||||
*/
|
||||
database?: string | undefined;
|
||||
|
||||
/**
|
||||
* Name of the database to connect to (alias for database)
|
||||
* @deprecated Prefer {@link database}
|
||||
* @default The username value
|
||||
*/
|
||||
db?: string | undefined;
|
||||
|
||||
/**
|
||||
* Database adapter/driver to use
|
||||
* @default "postgres"
|
||||
*/
|
||||
adapter?: "postgres" | "mysql" | "mariadb";
|
||||
|
||||
/**
|
||||
* Maximum time in seconds to wait for connection to become available
|
||||
* @default 0 (no timeout)
|
||||
*/
|
||||
idleTimeout?: number | undefined;
|
||||
|
||||
/**
|
||||
* Maximum time in seconds to wait for connection to become available (alias for idleTimeout)
|
||||
* @deprecated Prefer {@link idleTimeout}
|
||||
* @default 0 (no timeout)
|
||||
*/
|
||||
idle_timeout?: number | undefined;
|
||||
|
||||
/**
|
||||
* Maximum time in seconds to wait when establishing a connection
|
||||
* @default 30
|
||||
*/
|
||||
connectionTimeout?: number | undefined;
|
||||
|
||||
/**
|
||||
* Maximum time in seconds to wait when establishing a connection (alias for connectionTimeout)
|
||||
* @deprecated Prefer {@link connectionTimeout}
|
||||
* @default 30
|
||||
*/
|
||||
connection_timeout?: number | undefined;
|
||||
|
||||
/**
|
||||
* Maximum time in seconds to wait when establishing a connection (alias
|
||||
* for connectionTimeout)
|
||||
* @deprecated Prefer {@link connectionTimeout}
|
||||
* @default 30
|
||||
*/
|
||||
connectTimeout?: number | undefined;
|
||||
|
||||
/**
|
||||
* Maximum time in seconds to wait when establishing a connection (alias
|
||||
* for connectionTimeout)
|
||||
* @deprecated Prefer {@link connectionTimeout}
|
||||
* @default 30
|
||||
*/
|
||||
connect_timeout?: number | undefined;
|
||||
|
||||
/**
|
||||
* Maximum lifetime in seconds of a connection
|
||||
* @default 0 (no maximum lifetime)
|
||||
*/
|
||||
maxLifetime?: number | undefined;
|
||||
|
||||
/**
|
||||
* Maximum lifetime in seconds of a connection (alias for maxLifetime)
|
||||
* @deprecated Prefer {@link maxLifetime}
|
||||
* @default 0 (no maximum lifetime)
|
||||
*/
|
||||
max_lifetime?: number | undefined;
|
||||
|
||||
/**
|
||||
* Whether to use TLS/SSL for the connection
|
||||
* @default false
|
||||
*/
|
||||
tls?: TLSOptions | boolean | undefined;
|
||||
|
||||
/**
|
||||
* Whether to use TLS/SSL for the connection (alias for tls)
|
||||
* @default false
|
||||
*/
|
||||
ssl?: TLSOptions | boolean | undefined;
|
||||
|
||||
/**
|
||||
* Unix domain socket path for connection
|
||||
* @default undefined
|
||||
*/
|
||||
path?: string | undefined;
|
||||
|
||||
/**
|
||||
* Callback executed when a connection attempt completes
|
||||
* Receives an Error on failure, or null on success.
|
||||
*/
|
||||
onconnect?: ((err: Error | null) => void) | undefined;
|
||||
|
||||
/**
|
||||
* Callback executed when a connection is closed
|
||||
* Receives the closing Error or null.
|
||||
*/
|
||||
onclose?: ((err: Error | null) => void) | undefined;
|
||||
|
||||
/**
|
||||
* Postgres client runtime configuration options
|
||||
*
|
||||
* @see https://www.postgresql.org/docs/current/runtime-config-client.html
|
||||
*/
|
||||
connection?: Record<string, string | boolean | number> | undefined;
|
||||
|
||||
/**
|
||||
* Maximum number of connections in the pool
|
||||
* @default 10
|
||||
*/
|
||||
max?: number | undefined;
|
||||
|
||||
/**
|
||||
* By default values outside i32 range are returned as strings. If this is
|
||||
* true, values outside i32 range are returned as BigInts.
|
||||
* @default false
|
||||
*/
|
||||
bigint?: boolean | undefined;
|
||||
|
||||
/**
|
||||
* Automatic creation of prepared statements
|
||||
* @default true
|
||||
*/
|
||||
prepare?: boolean | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration options for SQL client connection and behavior
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const config: Bun.SQL.Options = {
|
||||
* host: 'localhost',
|
||||
* port: 5432,
|
||||
* user: 'dbuser',
|
||||
* password: 'secretpass',
|
||||
* database: 'myapp',
|
||||
* idleTimeout: 30,
|
||||
* max: 20,
|
||||
* onconnect: (client) => {
|
||||
* console.log('Connected to database');
|
||||
* }
|
||||
* };
|
||||
* ```
|
||||
*/
|
||||
type Options = SQLiteOptions | PostgresOrMySQLOptions;
|
||||
|
||||
/**
|
||||
* Represents a SQL query that can be executed, with additional control
|
||||
* methods Extends Promise to allow for async/await usage
|
||||
*/
|
||||
interface Query<T> extends Promise<T> {
|
||||
/**
|
||||
* Indicates if the query is currently executing
|
||||
*/
|
||||
active: boolean;
|
||||
|
||||
/**
|
||||
* Indicates if the query has been cancelled
|
||||
*/
|
||||
cancelled: boolean;
|
||||
|
||||
/**
|
||||
* Cancels the executing query
|
||||
*/
|
||||
cancel(): Query<T>;
|
||||
|
||||
/**
|
||||
* Executes the query as a simple query, no parameters are allowed but can
|
||||
* execute multiple commands separated by semicolons
|
||||
*/
|
||||
simple(): Query<T>;
|
||||
|
||||
/**
|
||||
* Executes the query
|
||||
*/
|
||||
execute(): Query<T>;
|
||||
|
||||
/**
|
||||
* Returns the raw query result
|
||||
*/
|
||||
raw(): Query<T>;
|
||||
|
||||
/**
|
||||
* Returns only the values from the query result
|
||||
*/
|
||||
values(): Query<T>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Callback function type for transaction contexts
|
||||
* @param sql Function to execute SQL queries within the transaction
|
||||
*/
|
||||
type TransactionContextCallback<T> = ContextCallback<T, TransactionSQL>;
|
||||
|
||||
/**
|
||||
* Callback function type for savepoint contexts
|
||||
* @param sql Function to execute SQL queries within the savepoint
|
||||
*/
|
||||
type SavepointContextCallback<T> = ContextCallback<T, SavepointSQL>;
|
||||
|
||||
/**
|
||||
* SQL.Helper represents a parameter or serializable
|
||||
* value inside of a query.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const helper = sql(users, 'id');
|
||||
* await sql`insert into users ${helper}`;
|
||||
* ```
|
||||
*/
|
||||
interface Helper<T> {
|
||||
readonly value: T[];
|
||||
readonly columns: (keyof T)[];
|
||||
}
|
||||
}
|
||||
|
||||
interface SQL extends AsyncDisposable {
|
||||
/**
|
||||
* Executes a SQL query using template literals
|
||||
* @example
|
||||
* ```ts
|
||||
* const [user] = await sql<Users[]>`select * from users where id = ${1}`;
|
||||
* ```
|
||||
*/
|
||||
<T = any>(strings: TemplateStringsArray, ...values: unknown[]): SQL.Query<T>;
|
||||
|
||||
/**
|
||||
* Execute a SQL query using a string
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const users = await sql<User[]>`SELECT * FROM users WHERE id = ${1}`;
|
||||
* ```
|
||||
*/
|
||||
<T = any>(string: string): SQL.Query<T>;
|
||||
|
||||
/**
|
||||
* Helper function for inserting an object into a query
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* // Insert an object
|
||||
* const result = await sql`insert into users ${sql(users)} returning *`;
|
||||
*
|
||||
* // Or pick specific columns
|
||||
* const result = await sql`insert into users ${sql(users, "id", "name")} returning *`;
|
||||
*
|
||||
* // Or a single object
|
||||
* const result = await sql`insert into users ${sql(user)} returning *`;
|
||||
* ```
|
||||
*/
|
||||
<T extends { [Key in PropertyKey]: unknown }>(obj: T | T[] | readonly T[]): SQL.Helper<T>; // Contributor note: This is the same as the signature below with the exception of the columns and the Pick<T, Keys>
|
||||
|
||||
/**
|
||||
* Helper function for inserting an object into a query, supporting specific columns
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* // Insert an object
|
||||
* const result = await sql`insert into users ${sql(users)} returning *`;
|
||||
*
|
||||
* // Or pick specific columns
|
||||
* const result = await sql`insert into users ${sql(users, "id", "name")} returning *`;
|
||||
*
|
||||
* // Or a single object
|
||||
* const result = await sql`insert into users ${sql(user)} returning *`;
|
||||
* ```
|
||||
*/
|
||||
<T extends { [Key in PropertyKey]: unknown }, Keys extends keyof T = keyof T>(
|
||||
obj: T | T[] | readonly T[],
|
||||
...columns: readonly Keys[]
|
||||
): SQL.Helper<Pick<T, Keys>>; // Contributor note: This is the same as the signature above with the exception of this signature tracking keys
|
||||
|
||||
/**
|
||||
* Helper function for inserting any serializable value into a query
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const result = await sql`SELECT * FROM users WHERE id IN ${sql([1, 2, 3])}`;
|
||||
* ```
|
||||
*/
|
||||
<T>(value: T): SQL.Helper<T>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Main SQL client interface providing connection and transaction management
|
||||
*/
|
||||
class SQL {
|
||||
/**
|
||||
* Creates a new SQL client instance
|
||||
*
|
||||
* @param connectionString - The connection string for the SQL client
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const sql = new SQL("postgres://localhost:5432/mydb");
|
||||
* const sql = new SQL(new URL("postgres://localhost:5432/mydb"));
|
||||
* ```
|
||||
*/
|
||||
constructor(connectionString: string | URL);
|
||||
|
||||
/**
|
||||
* Creates a new SQL client instance with options
|
||||
*
|
||||
* @param connectionString - The connection string for the SQL client
|
||||
* @param options - The options for the SQL client
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const sql = new SQL("postgres://localhost:5432/mydb", { idleTimeout: 1000 });
|
||||
* ```
|
||||
*/
|
||||
constructor(
|
||||
connectionString: string | URL,
|
||||
options: Bun.__internal.DistributedOmit<SQL.Options, "url" | "filename">,
|
||||
);
|
||||
|
||||
/**
|
||||
* Creates a new SQL client instance with options
|
||||
*
|
||||
* @param options - The options for the SQL client
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const sql = new SQL({ url: "postgres://localhost:5432/mydb", idleTimeout: 1000 });
|
||||
* ```
|
||||
*/
|
||||
constructor(options?: SQL.Options);
|
||||
|
||||
/**
|
||||
* Current client options
|
||||
*/
|
||||
options: Bun.__internal.DistributedMerge<SQL.Options>;
|
||||
|
||||
/**
|
||||
* Commits a distributed transaction also know as prepared transaction in postgres or XA transaction in MySQL
|
||||
*
|
||||
* @param name - The name of the distributed transaction
|
||||
*
|
||||
* @throws {Error} If the adapter does not support distributed transactions (e.g., SQLite)
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* await sql.commitDistributed("my_distributed_transaction");
|
||||
* ```
|
||||
*/
|
||||
commitDistributed(name: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* Rolls back a distributed transaction also know as prepared transaction in postgres or XA transaction in MySQL
|
||||
*
|
||||
* @param name - The name of the distributed transaction
|
||||
*
|
||||
* @throws {Error} If the adapter does not support distributed transactions (e.g., SQLite)
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* await sql.rollbackDistributed("my_distributed_transaction");
|
||||
* ```
|
||||
*/
|
||||
rollbackDistributed(name: string): Promise<void>;
|
||||
|
||||
/** Waits for the database connection to be established
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* await sql.connect();
|
||||
* ```
|
||||
*/
|
||||
connect(): Promise<SQL>;
|
||||
|
||||
/**
|
||||
* Closes the database connection with optional timeout in seconds. If timeout is 0, it will close immediately, if is not provided it will wait for all queries to finish before closing.
|
||||
*
|
||||
* @param options - The options for the close
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* await sql.close({ timeout: 1 });
|
||||
* ```
|
||||
*/
|
||||
close(options?: { timeout?: number }): Promise<void>;
|
||||
|
||||
/**
|
||||
* Closes the database connection with optional timeout in seconds. If timeout is 0, it will close immediately, if is not provided it will wait for all queries to finish before closing.
|
||||
* This is an alias of {@link SQL.close}
|
||||
*
|
||||
* @param options - The options for the close
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* await sql.end({ timeout: 1 });
|
||||
* ```
|
||||
*/
|
||||
end(options?: { timeout?: number }): Promise<void>;
|
||||
|
||||
/**
|
||||
* Flushes any pending operations
|
||||
*
|
||||
* @throws {Error} If the adapter does not support flushing (e.g., SQLite)
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* sql.flush();
|
||||
* ```
|
||||
*/
|
||||
flush(): void;
|
||||
|
||||
/**
|
||||
* The reserve method pulls out a connection from the pool, and returns a client that wraps the single connection.
|
||||
*
|
||||
* This can be used for running queries on an isolated connection.
|
||||
* Calling reserve in a reserved Sql will return a new reserved connection, not the same connection (behavior matches postgres package).
|
||||
*
|
||||
* @throws {Error} If the adapter does not support connection pooling (e.g., SQLite)s
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const reserved = await sql.reserve();
|
||||
* await reserved`select * from users`;
|
||||
* await reserved.release();
|
||||
* // with in a production scenario would be something more like
|
||||
* const reserved = await sql.reserve();
|
||||
* try {
|
||||
* // ... queries
|
||||
* } finally {
|
||||
* await reserved.release();
|
||||
* }
|
||||
*
|
||||
* // Bun supports Symbol.dispose and Symbol.asyncDispose
|
||||
* // always release after context (safer)
|
||||
* using reserved = await sql.reserve()
|
||||
* await reserved`select * from users`
|
||||
* ```
|
||||
*/
|
||||
reserve(): Promise<ReservedSQL>;
|
||||
|
||||
/**
|
||||
* Begins a new transaction.
|
||||
*
|
||||
* Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.begin will resolve with the returned value from the callback function.
|
||||
* BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.
|
||||
* @example
|
||||
* const [user, account] = await sql.begin(async sql => {
|
||||
* const [user] = await sql`
|
||||
* insert into users (
|
||||
* name
|
||||
* ) values (
|
||||
* 'Murray'
|
||||
* )
|
||||
* returning *
|
||||
* `
|
||||
* const [account] = await sql`
|
||||
* insert into accounts (
|
||||
* user_id
|
||||
* ) values (
|
||||
* ${ user.user_id }
|
||||
* )
|
||||
* returning *
|
||||
* `
|
||||
* return [user, account]
|
||||
* })
|
||||
*/
|
||||
begin<const T>(fn: SQL.TransactionContextCallback<T>): Promise<SQL.ContextCallbackResult<T>>;
|
||||
|
||||
/**
|
||||
* Begins a new transaction with options.
|
||||
*
|
||||
* Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.begin will resolve with the returned value from the callback function.
|
||||
* BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.
|
||||
* @example
|
||||
* const [user, account] = await sql.begin("read write", async sql => {
|
||||
* const [user] = await sql`
|
||||
* insert into users (
|
||||
* name
|
||||
* ) values (
|
||||
* 'Murray'
|
||||
* )
|
||||
* returning *
|
||||
* `
|
||||
* const [account] = await sql`
|
||||
* insert into accounts (
|
||||
* user_id
|
||||
* ) values (
|
||||
* ${ user.user_id }
|
||||
* )
|
||||
* returning *
|
||||
* `
|
||||
* return [user, account]
|
||||
* })
|
||||
*/
|
||||
begin<const T>(options: string, fn: SQL.TransactionContextCallback<T>): Promise<SQL.ContextCallbackResult<T>>;
|
||||
|
||||
/**
|
||||
* Alternative method to begin a transaction.
|
||||
*
|
||||
* Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.transaction will resolve with the returned value from the callback function.
|
||||
* BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.
|
||||
* @alias begin
|
||||
* @example
|
||||
* const [user, account] = await sql.transaction(async sql => {
|
||||
* const [user] = await sql`
|
||||
* insert into users (
|
||||
* name
|
||||
* ) values (
|
||||
* 'Murray'
|
||||
* )
|
||||
* returning *
|
||||
* `
|
||||
* const [account] = await sql`
|
||||
* insert into accounts (
|
||||
* user_id
|
||||
* ) values (
|
||||
* ${ user.user_id }
|
||||
* )
|
||||
* returning *
|
||||
* `
|
||||
* return [user, account]
|
||||
* })
|
||||
*/
|
||||
transaction<const T>(fn: SQL.TransactionContextCallback<T>): Promise<SQL.ContextCallbackResult<T>>;
|
||||
|
||||
/**
|
||||
* Alternative method to begin a transaction with options
|
||||
* Will reserve a connection for the transaction and supply a scoped sql instance for all transaction uses in the callback function. sql.transaction will resolve with the returned value from the callback function.
|
||||
* BEGIN is automatically sent with the optional options, and if anything fails ROLLBACK will be called so the connection can be released and execution can continue.
|
||||
*
|
||||
* @alias {@link begin}
|
||||
*
|
||||
* @example
|
||||
* const [user, account] = await sql.transaction("read write", async sql => {
|
||||
* const [user] = await sql`
|
||||
* insert into users (
|
||||
* name
|
||||
* ) values (
|
||||
* 'Murray'
|
||||
* )
|
||||
* returning *
|
||||
* `
|
||||
* const [account] = await sql`
|
||||
* insert into accounts (
|
||||
* user_id
|
||||
* ) values (
|
||||
* ${ user.user_id }
|
||||
* )
|
||||
* returning *
|
||||
* `
|
||||
* return [user, account]
|
||||
* });
|
||||
*/
|
||||
transaction<const T>(options: string, fn: SQL.TransactionContextCallback<T>): Promise<SQL.ContextCallbackResult<T>>;
|
||||
|
||||
/**
|
||||
* Begins a distributed transaction
|
||||
* Also know as Two-Phase Commit, in a distributed transaction, Phase 1 involves the coordinator preparing nodes by ensuring data is written and ready to commit, while Phase 2 finalizes with nodes committing or rolling back based on the coordinator's decision, ensuring durability and releasing locks.
|
||||
* In PostgreSQL and MySQL distributed transactions persist beyond the original session, allowing privileged users or coordinators to commit/rollback them, ensuring support for distributed transactions, recovery, and administrative tasks.
|
||||
* beginDistributed will automatic rollback if any exception are not caught, and you can commit and rollback later if everything goes well.
|
||||
* PostgreSQL natively supports distributed transactions using PREPARE TRANSACTION, while MySQL uses XA Transactions, and MSSQL also supports distributed/XA transactions. However, in MSSQL, distributed transactions are tied to the original session, the DTC coordinator, and the specific connection.
|
||||
* These transactions are automatically committed or rolled back following the same rules as regular transactions, with no option for manual intervention from other sessions, in MSSQL distributed transactions are used to coordinate transactions using Linked Servers.
|
||||
*
|
||||
* @throws {Error} If the adapter does not support distributed transactions (e.g., SQLite)
|
||||
*
|
||||
* @example
|
||||
* await sql.beginDistributed("numbers", async sql => {
|
||||
* await sql`create table if not exists numbers (a int)`;
|
||||
* await sql`insert into numbers values(1)`;
|
||||
* });
|
||||
* // later you can call
|
||||
* await sql.commitDistributed("numbers");
|
||||
* // or await sql.rollbackDistributed("numbers");
|
||||
*/
|
||||
beginDistributed<const T>(
|
||||
name: string,
|
||||
fn: SQL.TransactionContextCallback<T>,
|
||||
): Promise<SQL.ContextCallbackResult<T>>;
|
||||
|
||||
/** Alternative method to begin a distributed transaction
|
||||
* @alias {@link beginDistributed}
|
||||
*/
|
||||
distributed<const T>(name: string, fn: SQL.TransactionContextCallback<T>): Promise<SQL.ContextCallbackResult<T>>;
|
||||
|
||||
/**If you know what you're doing, you can use unsafe to pass any string you'd like.
|
||||
* Please note that this can lead to SQL injection if you're not careful.
|
||||
* You can also nest sql.unsafe within a safe sql expression. This is useful if only part of your fraction has unsafe elements.
|
||||
* @example
|
||||
* const result = await sql.unsafe(`select ${danger} from users where id = ${dragons}`)
|
||||
*/
|
||||
unsafe<T = any>(string: string, values?: any[]): SQL.Query<T>;
|
||||
|
||||
/**
|
||||
* Reads a file and uses the contents as a query.
|
||||
* Optional parameters can be used if the file includes $1, $2, etc
|
||||
* @example
|
||||
* const result = await sql.file("query.sql", [1, 2, 3]);
|
||||
*/
|
||||
file<T = any>(filename: string, values?: any[]): SQL.Query<T>;
|
||||
}
|
||||
|
||||
/**
|
||||
* SQL client
|
||||
*/
|
||||
const sql: SQL;
|
||||
|
||||
/**
|
||||
* SQL client for PostgreSQL
|
||||
*
|
||||
* @deprecated Prefer {@link Bun.sql}
|
||||
*/
|
||||
const postgres: SQL;
|
||||
|
||||
/**
|
||||
* Represents a savepoint within a transaction
|
||||
*/
|
||||
interface SavepointSQL extends SQL {}
|
||||
}
|
||||
283
node_modules/bun-types/vendor/expect-type/branding.d.ts
generated
vendored
Normal file
283
node_modules/bun-types/vendor/expect-type/branding.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,283 @@
|
|||
/*
|
||||
Copyright 2024 Misha Kaletsky
|
||||
|
||||
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.
|
||||
|
||||
|
||||
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
|
||||
*/
|
||||
|
||||
import type { ConstructorOverloadParameters, NumOverloads, OverloadsInfoUnion } from "./overloads";
|
||||
import type {
|
||||
IsAny,
|
||||
IsNever,
|
||||
IsUnknown,
|
||||
MutuallyExtends,
|
||||
OptionalKeys,
|
||||
ReadonlyKeys,
|
||||
RequiredKeys,
|
||||
UnionToTuple,
|
||||
} from "./utils";
|
||||
/**
|
||||
* Represents a deeply branded type.
|
||||
*
|
||||
* Recursively walk a type and replace it with a branded type related to the
|
||||
* original. This is useful for equality-checking stricter than
|
||||
* `A extends B ? B extends A ? true : false : false`, because it detects the
|
||||
* difference between a few edge-case types that vanilla TypeScript
|
||||
* doesn't by default:
|
||||
* - `any` vs `unknown`
|
||||
* - `{ readonly a: string }` vs `{ a: string }`
|
||||
* - `{ a?: string }` vs `{ a: string | undefined }`
|
||||
*
|
||||
* __Note__: not very performant for complex types - this should only be used
|
||||
* when you know you need it. If doing an equality check, it's almost always
|
||||
* better to use {@linkcode StrictEqualUsingTSInternalIdenticalToOperator}.
|
||||
*/
|
||||
export type DeepBrand<T> =
|
||||
IsNever<T> extends true
|
||||
? {
|
||||
type: "never";
|
||||
}
|
||||
: IsAny<T> extends true
|
||||
? {
|
||||
type: "any";
|
||||
}
|
||||
: IsUnknown<T> extends true
|
||||
? {
|
||||
type: "unknown";
|
||||
}
|
||||
: T extends string | number | boolean | symbol | bigint | null | undefined | void
|
||||
? {
|
||||
type: "primitive";
|
||||
value: T;
|
||||
}
|
||||
: T extends new (...args: any[]) => any
|
||||
? {
|
||||
type: "constructor";
|
||||
params: ConstructorOverloadParameters<T>;
|
||||
instance: DeepBrand<InstanceType<Extract<T, new (...args: any) => any>>>;
|
||||
}
|
||||
: T extends (...args: infer P) => infer R
|
||||
? NumOverloads<T> extends 1
|
||||
? {
|
||||
type: "function";
|
||||
params: DeepBrand<P>;
|
||||
return: DeepBrand<R>;
|
||||
this: DeepBrand<ThisParameterType<T>>;
|
||||
props: DeepBrand<Omit<T, keyof Function>>;
|
||||
}
|
||||
: UnionToTuple<OverloadsInfoUnion<T>> extends infer OverloadsTuple
|
||||
? {
|
||||
type: "overloads";
|
||||
overloads: {
|
||||
[K in keyof OverloadsTuple]: DeepBrand<OverloadsTuple[K]>;
|
||||
};
|
||||
}
|
||||
: never
|
||||
: T extends any[]
|
||||
? {
|
||||
type: "array";
|
||||
items: {
|
||||
[K in keyof T]: T[K];
|
||||
};
|
||||
}
|
||||
: {
|
||||
type: "object";
|
||||
properties: {
|
||||
[K in keyof T]: DeepBrand<T[K]>;
|
||||
};
|
||||
readonly: ReadonlyKeys<T>;
|
||||
required: RequiredKeys<T>;
|
||||
optional: OptionalKeys<T>;
|
||||
constructorParams: DeepBrand<ConstructorOverloadParameters<T>>;
|
||||
};
|
||||
/**
|
||||
* Checks if two types are strictly equal using branding.
|
||||
*/
|
||||
export type StrictEqualUsingBranding<Left, Right> = MutuallyExtends<DeepBrand<Left>, DeepBrand<Right>>;
|
||||
1207
node_modules/bun-types/vendor/expect-type/index.d.ts
generated
vendored
Normal file
1207
node_modules/bun-types/vendor/expect-type/index.d.ts
generated
vendored
Normal file
File diff suppressed because it is too large
Load diff
395
node_modules/bun-types/vendor/expect-type/messages.d.ts
generated
vendored
Normal file
395
node_modules/bun-types/vendor/expect-type/messages.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,395 @@
|
|||
/*
|
||||
Copyright 2024 Misha Kaletsky
|
||||
|
||||
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.
|
||||
|
||||
|
||||
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
|
||||
*/
|
||||
|
||||
import type { StrictEqualUsingBranding } from "./branding";
|
||||
import type { And, Extends, ExtendsExcludingAnyOrNever, IsAny, IsNever, IsUnknown, Not, UsefulKeys } from "./utils";
|
||||
/**
|
||||
* Determines the printable type representation for a given type.
|
||||
*/
|
||||
export type PrintType<T> =
|
||||
IsUnknown<T> extends true
|
||||
? "unknown"
|
||||
: IsNever<T> extends true
|
||||
? "never"
|
||||
: IsAny<T> extends true
|
||||
? never
|
||||
: boolean extends T
|
||||
? "boolean"
|
||||
: T extends boolean
|
||||
? `literal boolean: ${T}`
|
||||
: string extends T
|
||||
? "string"
|
||||
: T extends string
|
||||
? `literal string: ${T}`
|
||||
: number extends T
|
||||
? "number"
|
||||
: T extends number
|
||||
? `literal number: ${T}`
|
||||
: bigint extends T
|
||||
? "bigint"
|
||||
: T extends bigint
|
||||
? `literal bigint: ${T}`
|
||||
: T extends null
|
||||
? "null"
|
||||
: T extends undefined
|
||||
? "undefined"
|
||||
: T extends (...args: any[]) => any
|
||||
? "function"
|
||||
: "...";
|
||||
/**
|
||||
* Helper for showing end-user a hint why their type assertion is failing.
|
||||
* This swaps "leaf" types with a literal message about what the actual and
|
||||
* expected types are. Needs to check for `Not<IsAny<Actual>>` because
|
||||
* otherwise `LeafTypeOf<Actual>` returns `never`, which extends everything 🤔
|
||||
*/
|
||||
export type MismatchInfo<Actual, Expected> =
|
||||
And<[Extends<PrintType<Actual>, "...">, Not<IsAny<Actual>>]> extends true
|
||||
? And<[Extends<any[], Actual>, Extends<any[], Expected>]> extends true
|
||||
? Array<MismatchInfo<Extract<Actual, any[]>[number], Extract<Expected, any[]>[number]>>
|
||||
: {
|
||||
[K in UsefulKeys<Actual> | UsefulKeys<Expected>]: MismatchInfo<
|
||||
K extends keyof Actual ? Actual[K] : never,
|
||||
K extends keyof Expected ? Expected[K] : never
|
||||
>;
|
||||
}
|
||||
: StrictEqualUsingBranding<Actual, Expected> extends true
|
||||
? Actual
|
||||
: `Expected: ${PrintType<Expected>}, Actual: ${PrintType<Exclude<Actual, Expected>>}`;
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const inverted: unique symbol;
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
type Inverted<T> = {
|
||||
[inverted]: T;
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const expectNull: unique symbol;
|
||||
export type ExpectNull<T> = {
|
||||
[expectNull]: T;
|
||||
result: ExtendsExcludingAnyOrNever<T, null>;
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const expectUndefined: unique symbol;
|
||||
export type ExpectUndefined<T> = {
|
||||
[expectUndefined]: T;
|
||||
result: ExtendsExcludingAnyOrNever<T, undefined>;
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const expectNumber: unique symbol;
|
||||
export type ExpectNumber<T> = {
|
||||
[expectNumber]: T;
|
||||
result: ExtendsExcludingAnyOrNever<T, number>;
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const expectString: unique symbol;
|
||||
export type ExpectString<T> = {
|
||||
[expectString]: T;
|
||||
result: ExtendsExcludingAnyOrNever<T, string>;
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const expectBoolean: unique symbol;
|
||||
export type ExpectBoolean<T> = {
|
||||
[expectBoolean]: T;
|
||||
result: ExtendsExcludingAnyOrNever<T, boolean>;
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const expectVoid: unique symbol;
|
||||
export type ExpectVoid<T> = {
|
||||
[expectVoid]: T;
|
||||
result: ExtendsExcludingAnyOrNever<T, void>;
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const expectFunction: unique symbol;
|
||||
export type ExpectFunction<T> = {
|
||||
[expectFunction]: T;
|
||||
result: ExtendsExcludingAnyOrNever<T, (...args: any[]) => any>;
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const expectObject: unique symbol;
|
||||
export type ExpectObject<T> = {
|
||||
[expectObject]: T;
|
||||
result: ExtendsExcludingAnyOrNever<T, object>;
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const expectArray: unique symbol;
|
||||
export type ExpectArray<T> = {
|
||||
[expectArray]: T;
|
||||
result: ExtendsExcludingAnyOrNever<T, any[]>;
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const expectSymbol: unique symbol;
|
||||
export type ExpectSymbol<T> = {
|
||||
[expectSymbol]: T;
|
||||
result: ExtendsExcludingAnyOrNever<T, symbol>;
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const expectAny: unique symbol;
|
||||
export type ExpectAny<T> = {
|
||||
[expectAny]: T;
|
||||
result: IsAny<T>;
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const expectUnknown: unique symbol;
|
||||
export type ExpectUnknown<T> = {
|
||||
[expectUnknown]: T;
|
||||
result: IsUnknown<T>;
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const expectNever: unique symbol;
|
||||
export type ExpectNever<T> = {
|
||||
[expectNever]: T;
|
||||
result: IsNever<T>;
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const expectNullable: unique symbol;
|
||||
export type ExpectNullable<T> = {
|
||||
[expectNullable]: T;
|
||||
result: Not<StrictEqualUsingBranding<T, NonNullable<T>>>;
|
||||
};
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const expectBigInt: unique symbol;
|
||||
export type ExpectBigInt<T> = {
|
||||
[expectBigInt]: T;
|
||||
result: ExtendsExcludingAnyOrNever<T, bigint>;
|
||||
};
|
||||
/**
|
||||
* Checks if the result of an expecter matches the specified options, and
|
||||
* resolves to a fairly readable error message if not.
|
||||
*/
|
||||
export type Scolder<
|
||||
Expecter extends {
|
||||
result: boolean;
|
||||
},
|
||||
Options extends {
|
||||
positive: boolean;
|
||||
},
|
||||
> = Expecter["result"] extends Options["positive"]
|
||||
? () => true
|
||||
: Options["positive"] extends true
|
||||
? Expecter
|
||||
: Inverted<Expecter>;
|
||||
export {};
|
||||
669
node_modules/bun-types/vendor/expect-type/overloads.d.ts
generated
vendored
Normal file
669
node_modules/bun-types/vendor/expect-type/overloads.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,669 @@
|
|||
/*
|
||||
Copyright 2024 Misha Kaletsky
|
||||
|
||||
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.
|
||||
|
||||
|
||||
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
|
||||
*/
|
||||
|
||||
import type {
|
||||
IsNever,
|
||||
StrictEqualUsingTSInternalIdenticalToOperator,
|
||||
UnionToIntersection,
|
||||
UnionToTuple,
|
||||
} from "./utils";
|
||||
/**
|
||||
* The simple(ish) way to get overload info from a function
|
||||
* {@linkcode FunctionType}. Recent versions of TypeScript will match any
|
||||
* function against a generic 10-overload type, filling in slots with
|
||||
* duplicates of the function. So, we can just match against a single type
|
||||
* and get all the overloads.
|
||||
*
|
||||
* For older versions of TypeScript, we'll need to painstakingly do
|
||||
* ten separate matches.
|
||||
*/
|
||||
export type TSPost53OverloadsInfoUnion<FunctionType> = FunctionType extends {
|
||||
(...args: infer A1): infer R1;
|
||||
(...args: infer A2): infer R2;
|
||||
(...args: infer A3): infer R3;
|
||||
(...args: infer A4): infer R4;
|
||||
(...args: infer A5): infer R5;
|
||||
(...args: infer A6): infer R6;
|
||||
(...args: infer A7): infer R7;
|
||||
(...args: infer A8): infer R8;
|
||||
(...args: infer A9): infer R9;
|
||||
(...args: infer A10): infer R10;
|
||||
}
|
||||
?
|
||||
| ((...p: A1) => R1)
|
||||
| ((...p: A2) => R2)
|
||||
| ((...p: A3) => R3)
|
||||
| ((...p: A4) => R4)
|
||||
| ((...p: A5) => R5)
|
||||
| ((...p: A6) => R6)
|
||||
| ((...p: A7) => R7)
|
||||
| ((...p: A8) => R8)
|
||||
| ((...p: A9) => R9)
|
||||
| ((...p: A10) => R10)
|
||||
: never;
|
||||
/**
|
||||
* A function with `unknown` parameters and return type.
|
||||
*/
|
||||
export type UnknownFunction = (...args: unknown[]) => unknown;
|
||||
/**
|
||||
* `true` iff {@linkcode FunctionType} is
|
||||
* equivalent to `(...args: unknown[]) => unknown`,
|
||||
* which is what an overload variant looks like for a non-existent overload.
|
||||
* This is useful because older versions of TypeScript end up with
|
||||
* 9 "useless" overloads and one real one for parameterless/generic functions.
|
||||
*
|
||||
* @see {@link https://github.com/microsoft/TypeScript/issues/28867 | Related}
|
||||
*/
|
||||
export type IsUselessOverloadInfo<FunctionType> = StrictEqualUsingTSInternalIdenticalToOperator<
|
||||
FunctionType,
|
||||
UnknownFunction
|
||||
>;
|
||||
/**
|
||||
* Old versions of TypeScript can sometimes seem to refuse to separate out
|
||||
* union members unless you put them each in a pointless tuple and add an
|
||||
* extra `infer X` expression. There may be a better way to work around this
|
||||
* problem, but since it's not a problem in newer versions of TypeScript,
|
||||
* it's not a priority right now.
|
||||
*/
|
||||
export type Tuplify<Union> = Union extends infer X ? [X] : never;
|
||||
/**
|
||||
* For older versions of TypeScript, we need two separate workarounds
|
||||
* to get overload info. First, we need need to use
|
||||
* {@linkcode DecreasingOverloadsInfoUnion} to get the overload info for
|
||||
* functions with 1-10 overloads. Then, we need to filter out the
|
||||
* "useless" overloads that are present in older versions of TypeScript,
|
||||
* for parameterless functions. To do this we use
|
||||
* {@linkcode IsUselessOverloadInfo} to remove useless overloads.
|
||||
*
|
||||
* @see {@link https://github.com/microsoft/TypeScript/issues/28867 | Related}
|
||||
*/
|
||||
export type TSPre53OverloadsInfoUnion<FunctionType> =
|
||||
Tuplify<DecreasingOverloadsInfoUnion<FunctionType>> extends infer Tup
|
||||
? Tup extends [infer Fn]
|
||||
? IsUselessOverloadInfo<Fn> extends true
|
||||
? never
|
||||
: Fn
|
||||
: never
|
||||
: never;
|
||||
/**
|
||||
* For versions of TypeScript below 5.3, we need to check for 10 overloads,
|
||||
* then 9, then 8, etc., to get a union of the overload variants.
|
||||
*/
|
||||
export type DecreasingOverloadsInfoUnion<F> = F extends {
|
||||
(...args: infer A1): infer R1;
|
||||
(...args: infer A2): infer R2;
|
||||
(...args: infer A3): infer R3;
|
||||
(...args: infer A4): infer R4;
|
||||
(...args: infer A5): infer R5;
|
||||
(...args: infer A6): infer R6;
|
||||
(...args: infer A7): infer R7;
|
||||
(...args: infer A8): infer R8;
|
||||
(...args: infer A9): infer R9;
|
||||
(...args: infer A10): infer R10;
|
||||
}
|
||||
?
|
||||
| ((...p: A1) => R1)
|
||||
| ((...p: A2) => R2)
|
||||
| ((...p: A3) => R3)
|
||||
| ((...p: A4) => R4)
|
||||
| ((...p: A5) => R5)
|
||||
| ((...p: A6) => R6)
|
||||
| ((...p: A7) => R7)
|
||||
| ((...p: A8) => R8)
|
||||
| ((...p: A9) => R9)
|
||||
| ((...p: A10) => R10)
|
||||
: F extends {
|
||||
(...args: infer A1): infer R1;
|
||||
(...args: infer A2): infer R2;
|
||||
(...args: infer A3): infer R3;
|
||||
(...args: infer A4): infer R4;
|
||||
(...args: infer A5): infer R5;
|
||||
(...args: infer A6): infer R6;
|
||||
(...args: infer A7): infer R7;
|
||||
(...args: infer A8): infer R8;
|
||||
(...args: infer A9): infer R9;
|
||||
}
|
||||
?
|
||||
| ((...p: A1) => R1)
|
||||
| ((...p: A2) => R2)
|
||||
| ((...p: A3) => R3)
|
||||
| ((...p: A4) => R4)
|
||||
| ((...p: A5) => R5)
|
||||
| ((...p: A6) => R6)
|
||||
| ((...p: A7) => R7)
|
||||
| ((...p: A8) => R8)
|
||||
| ((...p: A9) => R9)
|
||||
: F extends {
|
||||
(...args: infer A1): infer R1;
|
||||
(...args: infer A2): infer R2;
|
||||
(...args: infer A3): infer R3;
|
||||
(...args: infer A4): infer R4;
|
||||
(...args: infer A5): infer R5;
|
||||
(...args: infer A6): infer R6;
|
||||
(...args: infer A7): infer R7;
|
||||
(...args: infer A8): infer R8;
|
||||
}
|
||||
?
|
||||
| ((...p: A1) => R1)
|
||||
| ((...p: A2) => R2)
|
||||
| ((...p: A3) => R3)
|
||||
| ((...p: A4) => R4)
|
||||
| ((...p: A5) => R5)
|
||||
| ((...p: A6) => R6)
|
||||
| ((...p: A7) => R7)
|
||||
| ((...p: A8) => R8)
|
||||
: F extends {
|
||||
(...args: infer A1): infer R1;
|
||||
(...args: infer A2): infer R2;
|
||||
(...args: infer A3): infer R3;
|
||||
(...args: infer A4): infer R4;
|
||||
(...args: infer A5): infer R5;
|
||||
(...args: infer A6): infer R6;
|
||||
(...args: infer A7): infer R7;
|
||||
}
|
||||
?
|
||||
| ((...p: A1) => R1)
|
||||
| ((...p: A2) => R2)
|
||||
| ((...p: A3) => R3)
|
||||
| ((...p: A4) => R4)
|
||||
| ((...p: A5) => R5)
|
||||
| ((...p: A6) => R6)
|
||||
| ((...p: A7) => R7)
|
||||
: F extends {
|
||||
(...args: infer A1): infer R1;
|
||||
(...args: infer A2): infer R2;
|
||||
(...args: infer A3): infer R3;
|
||||
(...args: infer A4): infer R4;
|
||||
(...args: infer A5): infer R5;
|
||||
(...args: infer A6): infer R6;
|
||||
}
|
||||
?
|
||||
| ((...p: A1) => R1)
|
||||
| ((...p: A2) => R2)
|
||||
| ((...p: A3) => R3)
|
||||
| ((...p: A4) => R4)
|
||||
| ((...p: A5) => R5)
|
||||
| ((...p: A6) => R6)
|
||||
: F extends {
|
||||
(...args: infer A1): infer R1;
|
||||
(...args: infer A2): infer R2;
|
||||
(...args: infer A3): infer R3;
|
||||
(...args: infer A4): infer R4;
|
||||
(...args: infer A5): infer R5;
|
||||
}
|
||||
? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4) | ((...p: A5) => R5)
|
||||
: F extends {
|
||||
(...args: infer A1): infer R1;
|
||||
(...args: infer A2): infer R2;
|
||||
(...args: infer A3): infer R3;
|
||||
(...args: infer A4): infer R4;
|
||||
}
|
||||
? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3) | ((...p: A4) => R4)
|
||||
: F extends {
|
||||
(...args: infer A1): infer R1;
|
||||
(...args: infer A2): infer R2;
|
||||
(...args: infer A3): infer R3;
|
||||
}
|
||||
? ((...p: A1) => R1) | ((...p: A2) => R2) | ((...p: A3) => R3)
|
||||
: F extends {
|
||||
(...args: infer A1): infer R1;
|
||||
(...args: infer A2): infer R2;
|
||||
}
|
||||
? ((...p: A1) => R1) | ((...p: A2) => R2)
|
||||
: F extends (...args: infer A1) => infer R1
|
||||
? (...p: A1) => R1
|
||||
: never;
|
||||
/**
|
||||
* Get a union of overload variants for a function {@linkcode FunctionType}.
|
||||
* Does a check for whether we can do the one-shot
|
||||
* 10-overload matcher (which works for ts\>5.3), and if not,
|
||||
* falls back to the more complicated utility.
|
||||
*/
|
||||
export type OverloadsInfoUnion<FunctionType> =
|
||||
IsNever<TSPost53OverloadsInfoUnion<(a: 1) => 2>> extends true
|
||||
? TSPre53OverloadsInfoUnion<FunctionType>
|
||||
: TSPost53OverloadsInfoUnion<FunctionType>;
|
||||
/**
|
||||
* Allows inferring any function using the `infer` keyword.
|
||||
*/
|
||||
export type InferFunctionType<FunctionType extends (...args: any) => any> = FunctionType;
|
||||
/**
|
||||
* A union type of the parameters allowed for any
|
||||
* overload of function {@linkcode FunctionType}.
|
||||
*/
|
||||
export type OverloadParameters<FunctionType> =
|
||||
OverloadsInfoUnion<FunctionType> extends InferFunctionType<infer Fn> ? Parameters<Fn> : never;
|
||||
/**
|
||||
* A union type of the return types for any overload of
|
||||
* function {@linkcode FunctionType}.
|
||||
*/
|
||||
export type OverloadReturnTypes<FunctionType> =
|
||||
OverloadsInfoUnion<FunctionType> extends InferFunctionType<infer Fn> ? ReturnType<Fn> : never;
|
||||
/**
|
||||
* Takes an overload variants {@linkcode Union},
|
||||
* produced from {@linkcode OverloadsInfoUnion} and rejects
|
||||
* the ones incompatible with parameters {@linkcode Args}.
|
||||
*/
|
||||
export type SelectOverloadsInfo<Union extends UnknownFunction, Args extends unknown[]> =
|
||||
Union extends InferFunctionType<infer Fn> ? (Args extends Parameters<Fn> ? Fn : never) : never;
|
||||
/**
|
||||
* Creates a new overload (an intersection type) from an existing one,
|
||||
* which only includes variant(s) which can accept
|
||||
* {@linkcode Args} as parameters.
|
||||
*/
|
||||
export type OverloadsNarrowedByParameters<
|
||||
FunctionType,
|
||||
Args extends OverloadParameters<FunctionType>,
|
||||
> = UnionToIntersection<SelectOverloadsInfo<OverloadsInfoUnion<FunctionType>, Args>>;
|
||||
/**
|
||||
* The simple(ish) way to get overload info from a constructor
|
||||
* {@linkcode ConstructorType}. Recent versions of TypeScript will match any
|
||||
* constructor against a generic 10-overload type, filling in slots with
|
||||
* duplicates of the constructor. So, we can just match against a single type
|
||||
* and get all the overloads.
|
||||
*
|
||||
* For older versions of TypeScript,
|
||||
* we'll need to painstakingly do ten separate matches.
|
||||
*/
|
||||
export type TSPost53ConstructorOverloadsInfoUnion<ConstructorType> = ConstructorType extends {
|
||||
new (...args: infer A1): infer R1;
|
||||
new (...args: infer A2): infer R2;
|
||||
new (...args: infer A3): infer R3;
|
||||
new (...args: infer A4): infer R4;
|
||||
new (...args: infer A5): infer R5;
|
||||
new (...args: infer A6): infer R6;
|
||||
new (...args: infer A7): infer R7;
|
||||
new (...args: infer A8): infer R8;
|
||||
new (...args: infer A9): infer R9;
|
||||
new (...args: infer A10): infer R10;
|
||||
}
|
||||
?
|
||||
| (new (...p: A1) => R1)
|
||||
| (new (...p: A2) => R2)
|
||||
| (new (...p: A3) => R3)
|
||||
| (new (...p: A4) => R4)
|
||||
| (new (...p: A5) => R5)
|
||||
| (new (...p: A6) => R6)
|
||||
| (new (...p: A7) => R7)
|
||||
| (new (...p: A8) => R8)
|
||||
| (new (...p: A9) => R9)
|
||||
| (new (...p: A10) => R10)
|
||||
: never;
|
||||
/**
|
||||
* A constructor function with `unknown` parameters and return type.
|
||||
*/
|
||||
export type UnknownConstructor = new (...args: unknown[]) => unknown;
|
||||
/**
|
||||
* Same as {@linkcode IsUselessOverloadInfo}, but for constructors.
|
||||
*/
|
||||
export type IsUselessConstructorOverloadInfo<FunctionType> = StrictEqualUsingTSInternalIdenticalToOperator<
|
||||
FunctionType,
|
||||
UnknownConstructor
|
||||
>;
|
||||
/**
|
||||
* For older versions of TypeScript, we need two separate workarounds to
|
||||
* get constructor overload info. First, we need need to use
|
||||
* {@linkcode DecreasingConstructorOverloadsInfoUnion} to get the overload
|
||||
* info for constructors with 1-10 overloads. Then, we need to filter out the
|
||||
* "useless" overloads that are present in older versions of TypeScript,
|
||||
* for parameterless constructors. To do this we use
|
||||
* {@linkcode IsUselessConstructorOverloadInfo} to remove useless overloads.
|
||||
*
|
||||
* @see {@link https://github.com/microsoft/TypeScript/issues/28867 | Related}
|
||||
*/
|
||||
export type TSPre53ConstructorOverloadsInfoUnion<ConstructorType> =
|
||||
Tuplify<DecreasingConstructorOverloadsInfoUnion<ConstructorType>> extends infer Tup
|
||||
? Tup extends [infer Ctor]
|
||||
? IsUselessConstructorOverloadInfo<Ctor> extends true
|
||||
? never
|
||||
: Ctor
|
||||
: never
|
||||
: never;
|
||||
/**
|
||||
* For versions of TypeScript below 5.3, we need to check for 10 overloads,
|
||||
* then 9, then 8, etc., to get a union of the overload variants.
|
||||
*/
|
||||
export type DecreasingConstructorOverloadsInfoUnion<ConstructorType> = ConstructorType extends {
|
||||
new (...args: infer A1): infer R1;
|
||||
new (...args: infer A2): infer R2;
|
||||
new (...args: infer A3): infer R3;
|
||||
new (...args: infer A4): infer R4;
|
||||
new (...args: infer A5): infer R5;
|
||||
new (...args: infer A6): infer R6;
|
||||
new (...args: infer A7): infer R7;
|
||||
new (...args: infer A8): infer R8;
|
||||
new (...args: infer A9): infer R9;
|
||||
new (...args: infer A10): infer R10;
|
||||
}
|
||||
?
|
||||
| (new (...p: A1) => R1)
|
||||
| (new (...p: A2) => R2)
|
||||
| (new (...p: A3) => R3)
|
||||
| (new (...p: A4) => R4)
|
||||
| (new (...p: A5) => R5)
|
||||
| (new (...p: A6) => R6)
|
||||
| (new (...p: A7) => R7)
|
||||
| (new (...p: A8) => R8)
|
||||
| (new (...p: A9) => R9)
|
||||
| (new (...p: A10) => R10)
|
||||
: ConstructorType extends {
|
||||
new (...args: infer A1): infer R1;
|
||||
new (...args: infer A2): infer R2;
|
||||
new (...args: infer A3): infer R3;
|
||||
new (...args: infer A4): infer R4;
|
||||
new (...args: infer A5): infer R5;
|
||||
new (...args: infer A6): infer R6;
|
||||
new (...args: infer A7): infer R7;
|
||||
new (...args: infer A8): infer R8;
|
||||
new (...args: infer A9): infer R9;
|
||||
}
|
||||
?
|
||||
| (new (...p: A1) => R1)
|
||||
| (new (...p: A2) => R2)
|
||||
| (new (...p: A3) => R3)
|
||||
| (new (...p: A4) => R4)
|
||||
| (new (...p: A5) => R5)
|
||||
| (new (...p: A6) => R6)
|
||||
| (new (...p: A7) => R7)
|
||||
| (new (...p: A8) => R8)
|
||||
| (new (...p: A9) => R9)
|
||||
: ConstructorType extends {
|
||||
new (...args: infer A1): infer R1;
|
||||
new (...args: infer A2): infer R2;
|
||||
new (...args: infer A3): infer R3;
|
||||
new (...args: infer A4): infer R4;
|
||||
new (...args: infer A5): infer R5;
|
||||
new (...args: infer A6): infer R6;
|
||||
new (...args: infer A7): infer R7;
|
||||
new (...args: infer A8): infer R8;
|
||||
}
|
||||
?
|
||||
| (new (...p: A1) => R1)
|
||||
| (new (...p: A2) => R2)
|
||||
| (new (...p: A3) => R3)
|
||||
| (new (...p: A4) => R4)
|
||||
| (new (...p: A5) => R5)
|
||||
| (new (...p: A6) => R6)
|
||||
| (new (...p: A7) => R7)
|
||||
| (new (...p: A8) => R8)
|
||||
: ConstructorType extends {
|
||||
new (...args: infer A1): infer R1;
|
||||
new (...args: infer A2): infer R2;
|
||||
new (...args: infer A3): infer R3;
|
||||
new (...args: infer A4): infer R4;
|
||||
new (...args: infer A5): infer R5;
|
||||
new (...args: infer A6): infer R6;
|
||||
new (...args: infer A7): infer R7;
|
||||
}
|
||||
?
|
||||
| (new (...p: A1) => R1)
|
||||
| (new (...p: A2) => R2)
|
||||
| (new (...p: A3) => R3)
|
||||
| (new (...p: A4) => R4)
|
||||
| (new (...p: A5) => R5)
|
||||
| (new (...p: A6) => R6)
|
||||
| (new (...p: A7) => R7)
|
||||
: ConstructorType extends {
|
||||
new (...args: infer A1): infer R1;
|
||||
new (...args: infer A2): infer R2;
|
||||
new (...args: infer A3): infer R3;
|
||||
new (...args: infer A4): infer R4;
|
||||
new (...args: infer A5): infer R5;
|
||||
new (...args: infer A6): infer R6;
|
||||
}
|
||||
?
|
||||
| (new (...p: A1) => R1)
|
||||
| (new (...p: A2) => R2)
|
||||
| (new (...p: A3) => R3)
|
||||
| (new (...p: A4) => R4)
|
||||
| (new (...p: A5) => R5)
|
||||
| (new (...p: A6) => R6)
|
||||
: ConstructorType extends {
|
||||
new (...args: infer A1): infer R1;
|
||||
new (...args: infer A2): infer R2;
|
||||
new (...args: infer A3): infer R3;
|
||||
new (...args: infer A4): infer R4;
|
||||
new (...args: infer A5): infer R5;
|
||||
}
|
||||
?
|
||||
| (new (...p: A1) => R1)
|
||||
| (new (...p: A2) => R2)
|
||||
| (new (...p: A3) => R3)
|
||||
| (new (...p: A4) => R4)
|
||||
| (new (...p: A5) => R5)
|
||||
: ConstructorType extends {
|
||||
new (...args: infer A1): infer R1;
|
||||
new (...args: infer A2): infer R2;
|
||||
new (...args: infer A3): infer R3;
|
||||
new (...args: infer A4): infer R4;
|
||||
}
|
||||
? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3) | (new (...p: A4) => R4)
|
||||
: ConstructorType extends {
|
||||
new (...args: infer A1): infer R1;
|
||||
new (...args: infer A2): infer R2;
|
||||
new (...args: infer A3): infer R3;
|
||||
}
|
||||
? (new (...p: A1) => R1) | (new (...p: A2) => R2) | (new (...p: A3) => R3)
|
||||
: ConstructorType extends {
|
||||
new (...args: infer A1): infer R1;
|
||||
new (...args: infer A2): infer R2;
|
||||
}
|
||||
? (new (...p: A1) => R1) | (new (...p: A2) => R2)
|
||||
: ConstructorType extends new (...args: infer A1) => infer R1
|
||||
? new (...p: A1) => R1
|
||||
: never;
|
||||
/**
|
||||
* Get a union of overload variants for a constructor
|
||||
* {@linkcode ConstructorType}. Does a check for whether we can do the
|
||||
* one-shot 10-overload matcher (which works for ts\>5.3), and if not,
|
||||
* falls back to the more complicated utility.
|
||||
*/
|
||||
export type ConstructorOverloadsUnion<ConstructorType> =
|
||||
IsNever<TSPost53ConstructorOverloadsInfoUnion<new (a: 1) => any>> extends true
|
||||
? TSPre53ConstructorOverloadsInfoUnion<ConstructorType>
|
||||
: TSPost53ConstructorOverloadsInfoUnion<ConstructorType>;
|
||||
/**
|
||||
* Allows inferring any constructor using the `infer` keyword.
|
||||
*/
|
||||
export type InferConstructor<ConstructorType extends new (...args: any) => any> = ConstructorType;
|
||||
/**
|
||||
* A union type of the parameters allowed for any overload
|
||||
* of constructor {@linkcode ConstructorType}.
|
||||
*/
|
||||
export type ConstructorOverloadParameters<ConstructorType> =
|
||||
ConstructorOverloadsUnion<ConstructorType> extends InferConstructor<infer Ctor> ? ConstructorParameters<Ctor> : never;
|
||||
/**
|
||||
* Calculates the number of overloads for a given function type.
|
||||
*/
|
||||
export type NumOverloads<FunctionType> = UnionToTuple<OverloadsInfoUnion<FunctionType>>["length"];
|
||||
431
node_modules/bun-types/vendor/expect-type/utils.d.ts
generated
vendored
Normal file
431
node_modules/bun-types/vendor/expect-type/utils.d.ts
generated
vendored
Normal file
|
|
@ -0,0 +1,431 @@
|
|||
/*
|
||||
Copyright 2024 Misha Kaletsky
|
||||
|
||||
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.
|
||||
|
||||
|
||||
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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Negates a boolean type.
|
||||
*/
|
||||
export type Not<T extends boolean> = T extends true ? false : true;
|
||||
/**
|
||||
* Returns `true` if at least one of the types in the
|
||||
* {@linkcode Types} array is `true`, otherwise returns `false`.
|
||||
*/
|
||||
export type Or<Types extends boolean[]> = Types[number] extends false ? false : true;
|
||||
/**
|
||||
* Checks if all the boolean types in the {@linkcode Types} array are `true`.
|
||||
*/
|
||||
export type And<Types extends boolean[]> = Types[number] extends true ? true : false;
|
||||
/**
|
||||
* Represents an equality type that returns {@linkcode Right} if
|
||||
* {@linkcode Left} is `true`,
|
||||
* otherwise returns the negation of {@linkcode Right}.
|
||||
*/
|
||||
export type Eq<Left extends boolean, Right extends boolean> = Left extends true ? Right : Not<Right>;
|
||||
/**
|
||||
* Represents the exclusive OR operation on a tuple of boolean types.
|
||||
* Returns `true` if exactly one of the boolean types is `true`,
|
||||
* otherwise returns `false`.
|
||||
*/
|
||||
export type Xor<Types extends [boolean, boolean]> = Not<Eq<Types[0], Types[1]>>;
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const secret: unique symbol;
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
type Secret = typeof secret;
|
||||
/**
|
||||
* Checks if the given type is `never`.
|
||||
*/
|
||||
export type IsNever<T> = [T] extends [never] ? true : false;
|
||||
/**
|
||||
* Checks if the given type is `any`.
|
||||
*/
|
||||
export type IsAny<T> = [T] extends [Secret] ? Not<IsNever<T>> : false;
|
||||
/**
|
||||
* Determines if the given type is `unknown`.
|
||||
*/
|
||||
export type IsUnknown<T> = [unknown] extends [T] ? Not<IsAny<T>> : false;
|
||||
/**
|
||||
* Determines if a type is either `never` or `any`.
|
||||
*/
|
||||
export type IsNeverOrAny<T> = Or<[IsNever<T>, IsAny<T>]>;
|
||||
/**
|
||||
* Subjective "useful" keys from a type. For objects it's just `keyof` but for
|
||||
* tuples/arrays it's the number keys.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* UsefulKeys<{ a: 1; b: 2 }> // 'a' | 'b'
|
||||
*
|
||||
* UsefulKeys<['a', 'b']> // '0' | '1'
|
||||
*
|
||||
* UsefulKeys<string[]> // number
|
||||
* ```
|
||||
*/
|
||||
export type UsefulKeys<T> = T extends any[]
|
||||
? {
|
||||
[K in keyof T]: K;
|
||||
}[number]
|
||||
: keyof T;
|
||||
/**
|
||||
* Extracts the keys from a type that are required (not optional).
|
||||
*/
|
||||
export type RequiredKeys<T> = Extract<
|
||||
{
|
||||
[K in keyof T]-?: {} extends Pick<T, K> ? never : K;
|
||||
}[keyof T],
|
||||
keyof T
|
||||
>;
|
||||
/**
|
||||
* Gets the keys of an object type that are optional.
|
||||
*/
|
||||
export type OptionalKeys<T> = Exclude<keyof T, RequiredKeys<T>>;
|
||||
/**
|
||||
* Extracts the keys from a type that are not `readonly`.
|
||||
*/
|
||||
export type ReadonlyKeys<T> = Extract<
|
||||
{
|
||||
[K in keyof T]-?: ReadonlyEquivalent<
|
||||
{
|
||||
[_K in K]: T[K];
|
||||
},
|
||||
{
|
||||
-readonly [_K in K]: T[K];
|
||||
}
|
||||
> extends true
|
||||
? never
|
||||
: K;
|
||||
}[keyof T],
|
||||
keyof T
|
||||
>;
|
||||
/**
|
||||
* Determines if two types, are equivalent in a `readonly` manner.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
type ReadonlyEquivalent<X, Y> = Extends<<T>() => T extends X ? true : false, <T>() => T extends Y ? true : false>;
|
||||
/**
|
||||
* Checks if one type extends another. Note: this is not quite the same as `Left extends Right` because:
|
||||
* 1. If either type is `never`, the result is `true` iff the other type is also `never`.
|
||||
* 2. Types are wrapped in a 1-tuple so that union types are not distributed - instead we consider `string | number` to _not_ extend `number`. If we used `Left extends Right` directly you would get `Extends<string | number, number>` => `false | true` => `boolean`.
|
||||
*/
|
||||
export type Extends<Left, Right> = IsNever<Left> extends true ? IsNever<Right> : [Left] extends [Right] ? true : false;
|
||||
/**
|
||||
* Checks if the {@linkcode Left} type extends the {@linkcode Right} type,
|
||||
* excluding `any` or `never`.
|
||||
*/
|
||||
export type ExtendsExcludingAnyOrNever<Left, Right> = IsAny<Left> extends true ? IsAny<Right> : Extends<Left, Right>;
|
||||
/**
|
||||
* Checks if two types are strictly equal using
|
||||
* the TypeScript internal identical-to operator.
|
||||
*
|
||||
* @see {@link https://github.com/microsoft/TypeScript/issues/55188#issuecomment-1656328122 | much history}
|
||||
*/
|
||||
export type StrictEqualUsingTSInternalIdenticalToOperator<L, R> =
|
||||
(<T>() => T extends (L & T) | T ? true : false) extends <T>() => T extends (R & T) | T ? true : false
|
||||
? IsNever<L> extends IsNever<R>
|
||||
? true
|
||||
: false
|
||||
: false;
|
||||
/**
|
||||
* Checks that {@linkcode Left} and {@linkcode Right} extend each other.
|
||||
* Not quite the same as an equality check since `any` can make it resolve
|
||||
* to `true`. So should only be used when {@linkcode Left} and
|
||||
* {@linkcode Right} are known to avoid `any`.
|
||||
*/
|
||||
export type MutuallyExtends<Left, Right> = And<[Extends<Left, Right>, Extends<Right, Left>]>;
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
declare const mismatch: unique symbol;
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
type Mismatch = {
|
||||
[mismatch]: "mismatch";
|
||||
};
|
||||
/**
|
||||
* A type which should match anything passed as a value but *doesn't*
|
||||
* match {@linkcode Mismatch}. It helps TypeScript select the right overload
|
||||
* for {@linkcode PositiveExpectTypeOf.toEqualTypeOf | .toEqualTypeOf()} and
|
||||
* {@linkcode PositiveExpectTypeOf.toMatchTypeOf | .toMatchTypeOf()}.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
declare const avalue: unique symbol;
|
||||
/**
|
||||
* Represents a value that can be of various types.
|
||||
*/
|
||||
export type AValue =
|
||||
| {
|
||||
[avalue]?: undefined;
|
||||
}
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| symbol
|
||||
| bigint
|
||||
| null
|
||||
| undefined
|
||||
| void;
|
||||
/**
|
||||
* Represents the type of mismatched arguments between
|
||||
* the actual result and the expected result.
|
||||
*
|
||||
* If {@linkcode ActualResult} and {@linkcode ExpectedResult} are equivalent,
|
||||
* the type resolves to an empty tuple `[]`, indicating no mismatch.
|
||||
* If they are not equivalent, it resolves to a tuple containing the element
|
||||
* {@linkcode Mismatch}, signifying a discrepancy between
|
||||
* the expected and actual results.
|
||||
*/
|
||||
export type MismatchArgs<ActualResult extends boolean, ExpectedResult extends boolean> =
|
||||
Eq<ActualResult, ExpectedResult> extends true ? [] : [Mismatch];
|
||||
/**
|
||||
* Represents the options for the {@linkcode ExpectTypeOf} function.
|
||||
*/
|
||||
export interface ExpectTypeOfOptions {
|
||||
positive: boolean;
|
||||
branded: boolean;
|
||||
}
|
||||
/**
|
||||
* Convert a union to an intersection.
|
||||
* `A | B | C` -\> `A & B & C`
|
||||
*/
|
||||
export type UnionToIntersection<Union> = (Union extends any ? (distributedUnion: Union) => void : never) extends (
|
||||
mergedIntersection: infer Intersection,
|
||||
) => void
|
||||
? Intersection
|
||||
: never;
|
||||
/**
|
||||
* Get the last element of a union.
|
||||
* First, converts to a union of `() => T` functions,
|
||||
* then uses {@linkcode UnionToIntersection} to get the last one.
|
||||
*/
|
||||
export type LastOf<Union> =
|
||||
UnionToIntersection<Union extends any ? () => Union : never> extends () => infer R ? R : never;
|
||||
/**
|
||||
* Intermediate type for {@linkcode UnionToTuple} which pushes the
|
||||
* "last" union member to the end of a tuple, and recursively prepends
|
||||
* the remainder of the union.
|
||||
*/
|
||||
export type TuplifyUnion<Union, LastElement = LastOf<Union>> =
|
||||
IsNever<Union> extends true ? [] : [...TuplifyUnion<Exclude<Union, LastElement>>, LastElement];
|
||||
/**
|
||||
* Convert a union like `1 | 2 | 3` to a tuple like `[1, 2, 3]`.
|
||||
*/
|
||||
export type UnionToTuple<Union> = TuplifyUnion<Union>;
|
||||
export type IsTuple<T> = Or<[Extends<T, []>, Extends<T, [any, ...any[]]>]>;
|
||||
export type IsUnion<T> = Not<Extends<UnionToTuple<T>["length"], 1>>;
|
||||
/**
|
||||
* A recursive version of `Pick` that selects properties from the left type that are present in the right type.
|
||||
* The "leaf" types from `Left` are used - only the keys of `Right` are considered.
|
||||
*
|
||||
* @example
|
||||
* ```ts
|
||||
* const user = {email: 'a@b.com', name: 'John Doe', address: {street: '123 2nd St', city: 'New York', zip: '10001', state: 'NY', country: 'USA'}}
|
||||
*
|
||||
* type Result = DeepPickMatchingProps<typeof user, {name: unknown; address: {city: unknown}}> // {name: string, address: {city: string}}
|
||||
* ```
|
||||
*/
|
||||
export type DeepPickMatchingProps<Left, Right> =
|
||||
Left extends Record<string, unknown>
|
||||
? Pick<
|
||||
{
|
||||
[K in keyof Left]: K extends keyof Right ? DeepPickMatchingProps<Left[K], Right[K]> : never;
|
||||
},
|
||||
Extract<keyof Left, keyof Right>
|
||||
>
|
||||
: Left;
|
||||
export {};
|
||||
Loading…
Add table
Add a link
Reference in a new issue