Implement geo backend, TS client, frontend, and CI tests.

Add a Go HTTP API with Ed25519 auth and invitation onboarding, user-scoped GeoJSON Point management, a Bun-tested @noble/ed25519 TypeScript client, static Vue/Vuetify frontend integration, and a Gitea CI workflow running both Go and Bun test suites.

Made-with: Cursor
This commit is contained in:
2026-03-01 11:41:21 +00:00
parent 5c73295ce5
commit 6e2becb06a
164 changed files with 446560 additions and 0 deletions
+35
View File
@@ -0,0 +1,35 @@
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Go
uses: actions/setup-go@v5
with:
go-version: "1.22.x"
- name: Go tests
run: go test ./...
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version: latest
- name: Bun install
working-directory: libs/geo-api-client
run: bun install
- name: Bun tests
working-directory: libs/geo-api-client
run: bun test
+58
View File
@@ -0,0 +1,58 @@
# Momswap Geo Backend
Go backend service for user-owned GeoJSON feature collections with Ed25519 authentication and invitation-based onboarding.
## What is implemented
- Ed25519 challenge-response auth (`/v1/auth/challenge`, `/v1/auth/login`)
- Hybrid invitation onboarding (signed invite payload + inviter lineage)
- User registration with ownership proof (`/v1/auth/register`)
- Per-user collections and Point feature CRUD endpoints
- Static no-build frontend (`web/`) using Vue + Vuetify from CDN
- Reusable TypeScript API client (`libs/geo-api-client`) using `@noble/ed25519`
- Bun tests for the TS client and Go tests for API flows
- Gitea CI workflow running Go and Bun test suites
## Quick start
```bash
go test ./...
go run ./cmd/api
```
Server default: `http://localhost:8080`.
Optional environment variables:
- `ADDR` (default `:8080`)
- `ADMIN_PUBLIC_KEY` (bootstrap initial inviter/admin user)
## Frontend
Open `web/index.html` through a static server (recommended) or browser file URL.
Example:
```bash
python -m http.server 4173
```
Then visit `http://localhost:4173/web/`.
## API client library
Path: `libs/geo-api-client`
```bash
cd libs/geo-api-client
bun install
bun test
bun run build
```
## CI
Workflow: `.gitea/workflows/ci.yml`
- `go test ./...`
- `bun test` in `libs/geo-api-client`
+38
View File
@@ -0,0 +1,38 @@
package main
import (
"log"
"net/http"
"os"
"time"
"momswap/backend/internal/app"
httpapi "momswap/backend/internal/http"
"momswap/backend/internal/store"
)
func main() {
addr := getEnv("ADDR", ":8080")
adminPublicKey := os.Getenv("ADMIN_PUBLIC_KEY")
memory := store.NewMemoryStore()
service := app.NewService(memory, app.Config{
ChallengeTTL: 5 * time.Minute,
SessionTTL: 24 * time.Hour,
})
service.BootstrapAdmin(adminPublicKey)
api := httpapi.NewAPI(service)
log.Printf("listening on %s", addr)
if err := http.ListenAndServe(addr, api.Routes()); err != nil {
log.Fatalf("listen: %v", err)
}
}
func getEnv(key, fallback string) string {
v := os.Getenv(key)
if v == "" {
return fallback
}
return v
}
+3
View File
@@ -0,0 +1,3 @@
module momswap/backend
go 1.22.2
+300
View File
@@ -0,0 +1,300 @@
package app
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"time"
"momswap/backend/internal/auth"
"momswap/backend/internal/store"
)
var (
ErrUnauthorized = errors.New("unauthorized")
ErrForbidden = errors.New("forbidden")
ErrBadRequest = errors.New("bad request")
ErrInviteInvalid = errors.New("invite invalid")
ErrInviteExpired = errors.New("invite expired")
ErrInviteExhaust = errors.New("invite exhausted")
ErrAlreadyUser = errors.New("user already registered")
ErrCollectionMiss = errors.New("collection missing")
ErrFeatureMiss = errors.New("feature missing")
)
type Config struct {
ChallengeTTL time.Duration
SessionTTL time.Duration
}
type Service struct {
store *store.MemoryStore
config Config
}
func NewService(memoryStore *store.MemoryStore, cfg Config) *Service {
return &Service{store: memoryStore, config: cfg}
}
type InvitationPayload struct {
JTI string `json:"jti"`
InviterPublicKey string `json:"inviterPublicKey"`
InviteePublicKey string `json:"inviteePublicKey,omitempty"`
ExpiresAtUnix int64 `json:"expiresAtUnix"`
MaxUses int `json:"maxUses"`
}
func (s *Service) BootstrapAdmin(publicKey string) {
if publicKey == "" {
return
}
s.store.UpsertUser(store.User{
PublicKey: publicKey,
CreatedAt: time.Now().UTC(),
})
}
func (s *Service) CreateChallenge(publicKey string) (string, error) {
if publicKey == "" {
return "", fmt.Errorf("%w: missing public key", ErrBadRequest)
}
nonce, err := auth.NewRandomToken(24)
if err != nil {
return "", err
}
err = s.store.CreateChallenge(store.Challenge{
Nonce: nonce,
PublicKey: publicKey,
ExpiresAt: time.Now().UTC().Add(s.config.ChallengeTTL),
Used: false,
})
if err != nil {
return "", err
}
return nonce, nil
}
func (s *Service) Login(publicKey, nonce, signature string) (string, error) {
ch, err := s.store.GetChallenge(nonce)
if err != nil {
return "", fmt.Errorf("%w: challenge not found", ErrUnauthorized)
}
if ch.Used || time.Now().UTC().After(ch.ExpiresAt) {
return "", fmt.Errorf("%w: challenge expired", ErrUnauthorized)
}
if ch.PublicKey != publicKey {
return "", fmt.Errorf("%w: challenge key mismatch", ErrUnauthorized)
}
if _, err := s.store.GetUser(publicKey); err != nil {
return "", fmt.Errorf("%w: user not registered", ErrUnauthorized)
}
msg := "login:" + nonce
if err := auth.VerifySignature(publicKey, msg, signature); err != nil {
return "", fmt.Errorf("%w: %v", ErrUnauthorized, err)
}
_ = s.store.MarkChallengeUsed(nonce)
token, err := auth.NewRandomToken(32)
if err != nil {
return "", err
}
s.store.SaveSession(store.Session{
Token: token,
PublicKey: publicKey,
ExpiresAt: time.Now().UTC().Add(s.config.SessionTTL),
})
return token, nil
}
func (s *Service) AuthenticateSession(token string) (string, error) {
session, err := s.store.GetSession(token)
if err != nil || time.Now().UTC().After(session.ExpiresAt) {
return "", ErrUnauthorized
}
return session.PublicKey, nil
}
func (s *Service) CreateInvitation(authenticatedKey, invitePayloadB64, inviteSigB64 string) error {
payloadRaw, err := base64.RawURLEncoding.DecodeString(invitePayloadB64)
if err != nil {
return fmt.Errorf("%w: decode payload", ErrBadRequest)
}
var payload InvitationPayload
if err := json.Unmarshal(payloadRaw, &payload); err != nil {
return fmt.Errorf("%w: invalid payload json", ErrBadRequest)
}
if payload.InviterPublicKey != authenticatedKey {
return fmt.Errorf("%w: inviter mismatch", ErrForbidden)
}
if payload.JTI == "" || payload.MaxUses <= 0 || payload.ExpiresAtUnix <= 0 {
return fmt.Errorf("%w: invalid invite fields", ErrBadRequest)
}
if time.Now().UTC().After(time.Unix(payload.ExpiresAtUnix, 0).UTC()) {
return ErrInviteExpired
}
if _, err := s.store.GetUser(payload.InviterPublicKey); err != nil {
return fmt.Errorf("%w: inviter user missing", ErrForbidden)
}
if err := auth.VerifySignature(payload.InviterPublicKey, "invite:"+invitePayloadB64, inviteSigB64); err != nil {
return fmt.Errorf("%w: %v", ErrBadRequest, err)
}
return s.store.SaveInvitation(store.Invitation{
JTI: payload.JTI,
InviterPublicKey: payload.InviterPublicKey,
InviteePublicKey: payload.InviteePublicKey,
ExpiresAt: time.Unix(payload.ExpiresAtUnix, 0).UTC(),
MaxUses: payload.MaxUses,
UsedCount: 0,
})
}
func (s *Service) Register(newPublicKey, invitePayloadB64, inviteSigB64, proofSigB64 string) error {
if newPublicKey == "" {
return fmt.Errorf("%w: missing public key", ErrBadRequest)
}
if _, err := s.store.GetUser(newPublicKey); err == nil {
return ErrAlreadyUser
}
payloadRaw, err := base64.RawURLEncoding.DecodeString(invitePayloadB64)
if err != nil {
return fmt.Errorf("%w: decode payload", ErrBadRequest)
}
var payload InvitationPayload
if err := json.Unmarshal(payloadRaw, &payload); err != nil {
return fmt.Errorf("%w: invalid payload", ErrBadRequest)
}
if err := auth.VerifySignature(payload.InviterPublicKey, "invite:"+invitePayloadB64, inviteSigB64); err != nil {
return fmt.Errorf("%w: invite signature", ErrInviteInvalid)
}
if _, err := s.store.GetUser(payload.InviterPublicKey); err != nil {
return fmt.Errorf("%w: inviter missing", ErrInviteInvalid)
}
inv, err := s.store.GetInvitation(payload.JTI)
if err != nil {
return fmt.Errorf("%w: invite unknown", ErrInviteInvalid)
}
if inv.InviterPublicKey != payload.InviterPublicKey {
return fmt.Errorf("%w: inviter mismatch", ErrInviteInvalid)
}
if time.Now().UTC().After(inv.ExpiresAt) {
return ErrInviteExpired
}
if inv.UsedCount >= inv.MaxUses {
return ErrInviteExhaust
}
if inv.InviteePublicKey != "" && inv.InviteePublicKey != newPublicKey {
return fmt.Errorf("%w: invite bound to another key", ErrInviteInvalid)
}
proofMessage := "register:" + newPublicKey + ":" + payload.JTI
if err := auth.VerifySignature(newPublicKey, proofMessage, proofSigB64); err != nil {
return fmt.Errorf("%w: register proof", ErrInviteInvalid)
}
if err := s.store.IncrementInvitationUsage(payload.JTI); err != nil {
return err
}
s.store.UpsertUser(store.User{
PublicKey: newPublicKey,
Inviter: payload.InviterPublicKey,
CreatedAt: time.Now().UTC(),
})
return nil
}
func validatePoint(point store.Point) error {
if point.Type != "Point" {
return fmt.Errorf("%w: geometry type must be Point", ErrBadRequest)
}
if len(point.Coordinates) != 2 {
return fmt.Errorf("%w: coordinates must have lon/lat", ErrBadRequest)
}
lon, lat := point.Coordinates[0], point.Coordinates[1]
if lon < -180 || lon > 180 || lat < -90 || lat > 90 {
return fmt.Errorf("%w: invalid lon/lat bounds", ErrBadRequest)
}
return nil
}
func (s *Service) CreateCollection(ownerKey, name string) (store.Collection, error) {
if name == "" {
return store.Collection{}, fmt.Errorf("%w: collection name required", ErrBadRequest)
}
id, err := auth.NewRandomToken(12)
if err != nil {
return store.Collection{}, err
}
c := store.Collection{
ID: id,
OwnerKey: ownerKey,
Name: name,
CreatedAt: time.Now().UTC(),
}
s.store.SaveCollection(c)
return c, nil
}
func (s *Service) ListCollections(ownerKey string) []store.Collection {
return s.store.ListCollectionsByOwner(ownerKey)
}
func (s *Service) CreateFeature(ownerKey, collectionID string, geometry store.Point, properties map[string]interface{}) (store.Feature, error) {
collection, err := s.store.GetCollection(collectionID)
if err != nil {
return store.Feature{}, ErrCollectionMiss
}
if collection.OwnerKey != ownerKey {
return store.Feature{}, ErrForbidden
}
if err := validatePoint(geometry); err != nil {
return store.Feature{}, err
}
id, err := auth.NewRandomToken(12)
if err != nil {
return store.Feature{}, err
}
now := time.Now().UTC()
feature := store.Feature{
ID: id,
CollectionID: collectionID,
OwnerKey: ownerKey,
Type: "Feature",
Geometry: geometry,
Properties: properties,
CreatedAt: now,
UpdatedAt: now,
}
s.store.SaveFeature(feature)
return feature, nil
}
func (s *Service) ListFeatures(ownerKey, collectionID string) ([]store.Feature, error) {
collection, err := s.store.GetCollection(collectionID)
if err != nil {
return nil, ErrCollectionMiss
}
if collection.OwnerKey != ownerKey {
return nil, ErrForbidden
}
return s.store.ListFeaturesByCollection(collectionID), nil
}
func (s *Service) DeleteFeature(ownerKey, featureID string) error {
feature, err := s.store.GetFeature(featureID)
if err != nil {
return ErrFeatureMiss
}
if feature.OwnerKey != ownerKey {
return ErrForbidden
}
return s.store.DeleteFeature(featureID)
}
+44
View File
@@ -0,0 +1,44 @@
package auth
import (
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
)
func NewRandomToken(byteLen int) (string, error) {
if byteLen <= 0 {
return "", errors.New("byteLen must be greater than zero")
}
b := make([]byte, byteLen)
if _, err := rand.Read(b); err != nil {
return "", fmt.Errorf("read random bytes: %w", err)
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
func VerifySignature(publicKeyBase64, message, signatureBase64 string) error {
pubBytes, err := base64.RawURLEncoding.DecodeString(publicKeyBase64)
if err != nil {
return fmt.Errorf("decode public key: %w", err)
}
if len(pubBytes) != ed25519.PublicKeySize {
return errors.New("invalid public key length")
}
sigBytes, err := base64.RawURLEncoding.DecodeString(signatureBase64)
if err != nil {
return fmt.Errorf("decode signature: %w", err)
}
if len(sigBytes) != ed25519.SignatureSize {
return errors.New("invalid signature length")
}
if !ed25519.Verify(ed25519.PublicKey(pubBytes), []byte(message), sigBytes) {
return errors.New("signature verification failed")
}
return nil
}
+197
View File
@@ -0,0 +1,197 @@
package httpapi_test
import (
"bytes"
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"momswap/backend/internal/app"
httpapi "momswap/backend/internal/http"
"momswap/backend/internal/store"
)
func newTestServer(adminPublicKey string) *httptest.Server {
memory := store.NewMemoryStore()
svc := app.NewService(memory, app.Config{
ChallengeTTL: 5 * time.Minute,
SessionTTL: 24 * time.Hour,
})
svc.BootstrapAdmin(adminPublicKey)
api := httpapi.NewAPI(svc)
return httptest.NewServer(api.Routes())
}
func mustJSON(t *testing.T, value interface{}) []byte {
t.Helper()
b, err := json.Marshal(value)
if err != nil {
t.Fatalf("marshal json: %v", err)
}
return b
}
func postJSON(t *testing.T, client *http.Client, url string, body interface{}, token string) (*http.Response, map[string]interface{}) {
t.Helper()
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(mustJSON(t, body)))
if err != nil {
t.Fatalf("new request: %v", err)
}
req.Header.Set("Content-Type", "application/json")
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("do request: %v", err)
}
defer resp.Body.Close()
out := map[string]interface{}{}
_ = json.NewDecoder(resp.Body).Decode(&out)
return resp, out
}
func loginUser(t *testing.T, client *http.Client, baseURL, pubB64 string, priv ed25519.PrivateKey) string {
t.Helper()
chResp, chData := postJSON(t, client, baseURL+"/v1/auth/challenge", map[string]string{"publicKey": pubB64}, "")
if chResp.StatusCode != http.StatusOK {
t.Fatalf("create challenge status=%d body=%v", chResp.StatusCode, chData)
}
nonce := chData["nonce"].(string)
sig := ed25519.Sign(priv, []byte("login:"+nonce))
loginResp, loginData := postJSON(t, client, baseURL+"/v1/auth/login", map[string]string{
"publicKey": pubB64,
"nonce": nonce,
"signature": base64.RawURLEncoding.EncodeToString(sig),
}, "")
if loginResp.StatusCode != http.StatusOK {
t.Fatalf("login status=%d body=%v", loginResp.StatusCode, loginData)
}
return loginData["accessToken"].(string)
}
func registerUserViaAdmin(t *testing.T, client *http.Client, baseURL, adminPub string, adminPriv ed25519.PrivateKey, adminToken string, userPub string, userPriv ed25519.PrivateKey, jti string) {
t.Helper()
payload := app.InvitationPayload{
JTI: jti,
InviterPublicKey: adminPub,
ExpiresAtUnix: time.Now().Add(time.Hour).Unix(),
MaxUses: 1,
}
payloadRaw := mustJSON(t, payload)
payloadB64 := base64.RawURLEncoding.EncodeToString(payloadRaw)
inviteSig := base64.RawURLEncoding.EncodeToString(ed25519.Sign(adminPriv, []byte("invite:"+payloadB64)))
inviteResp, inviteData := postJSON(t, client, baseURL+"/v1/invitations", map[string]string{
"invitePayloadB64": payloadB64,
"inviteSignature": inviteSig,
}, adminToken)
if inviteResp.StatusCode != http.StatusCreated {
t.Fatalf("create invitation status=%d body=%v", inviteResp.StatusCode, inviteData)
}
proofSig := base64.RawURLEncoding.EncodeToString(ed25519.Sign(userPriv, []byte("register:"+userPub+":"+jti)))
registerResp, registerData := postJSON(t, client, baseURL+"/v1/auth/register", map[string]string{
"publicKey": userPub,
"invitePayloadB64": payloadB64,
"inviteSignature": inviteSig,
"proofSignature": proofSig,
}, "")
if registerResp.StatusCode != http.StatusCreated {
t.Fatalf("register status=%d body=%v", registerResp.StatusCode, registerData)
}
}
func TestRegisterLoginAndProfile(t *testing.T) {
adminPub, adminPriv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatalf("generate admin key: %v", err)
}
adminPubB64 := base64.RawURLEncoding.EncodeToString(adminPub)
server := newTestServer(adminPubB64)
defer server.Close()
client := server.Client()
adminToken := loginUser(t, client, server.URL, adminPubB64, adminPriv)
userPub, userPriv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatalf("generate user key: %v", err)
}
userPubB64 := base64.RawURLEncoding.EncodeToString(userPub)
registerUserViaAdmin(t, client, server.URL, adminPubB64, adminPriv, adminToken, userPubB64, userPriv, "invite-1")
userToken := loginUser(t, client, server.URL, userPubB64, userPriv)
req, _ := http.NewRequest(http.MethodGet, server.URL+"/v1/me/keys", nil)
req.Header.Set("Authorization", "Bearer "+userToken)
resp, err := client.Do(req)
if err != nil {
t.Fatalf("me request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("me status=%d", resp.StatusCode)
}
}
func TestCollectionOwnershipIsolation(t *testing.T) {
adminPub, adminPriv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatalf("generate admin key: %v", err)
}
adminPubB64 := base64.RawURLEncoding.EncodeToString(adminPub)
server := newTestServer(adminPubB64)
defer server.Close()
client := server.Client()
adminToken := loginUser(t, client, server.URL, adminPubB64, adminPriv)
user1Pub, user1Priv, _ := ed25519.GenerateKey(rand.Reader)
user1PubB64 := base64.RawURLEncoding.EncodeToString(user1Pub)
registerUserViaAdmin(t, client, server.URL, adminPubB64, adminPriv, adminToken, user1PubB64, user1Priv, "invite-u1")
user1Token := loginUser(t, client, server.URL, user1PubB64, user1Priv)
user2Pub, user2Priv, _ := ed25519.GenerateKey(rand.Reader)
user2PubB64 := base64.RawURLEncoding.EncodeToString(user2Pub)
registerUserViaAdmin(t, client, server.URL, adminPubB64, adminPriv, adminToken, user2PubB64, user2Priv, "invite-u2")
user2Token := loginUser(t, client, server.URL, user2PubB64, user2Priv)
createCollectionResp, createCollectionData := postJSON(t, client, server.URL+"/v1/collections", map[string]string{
"name": "my places",
}, user1Token)
if createCollectionResp.StatusCode != http.StatusCreated {
t.Fatalf("create collection status=%d body=%v", createCollectionResp.StatusCode, createCollectionData)
}
collectionID := createCollectionData["id"].(string)
createFeatureResp, createFeatureData := postJSON(t, client, server.URL+"/v1/collections/"+collectionID+"/features", map[string]interface{}{
"geometry": map[string]interface{}{
"type": "Point",
"coordinates": []float64{-16.6291, 28.4636},
},
"properties": map[string]interface{}{
"name": "Santa Cruz",
},
}, user1Token)
if createFeatureResp.StatusCode != http.StatusCreated {
t.Fatalf("create feature status=%d body=%v", createFeatureResp.StatusCode, createFeatureData)
}
req, _ := http.NewRequest(http.MethodGet, server.URL+"/v1/collections/"+collectionID+"/features", nil)
req.Header.Set("Authorization", "Bearer "+user2Token)
resp, err := client.Do(req)
if err != nil {
t.Fatalf("list features as user2: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("expected 403, got %d", resp.StatusCode)
}
}
+275
View File
@@ -0,0 +1,275 @@
package httpapi
import (
"encoding/json"
"errors"
"net/http"
"strings"
"time"
"momswap/backend/internal/app"
"momswap/backend/internal/store"
)
type API struct {
service *app.Service
}
func NewAPI(svc *app.Service) *API {
return &API{service: svc}
}
func (a *API) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", a.health)
mux.HandleFunc("POST /v1/auth/challenge", a.createChallenge)
mux.HandleFunc("POST /v1/auth/login", a.login)
mux.HandleFunc("POST /v1/auth/register", a.register)
mux.HandleFunc("POST /v1/invitations", a.createInvitation)
mux.HandleFunc("GET /v1/me/keys", a.me)
mux.HandleFunc("POST /v1/collections", a.createCollection)
mux.HandleFunc("GET /v1/collections", a.listCollections)
mux.HandleFunc("POST /v1/collections/{id}/features", a.createFeature)
mux.HandleFunc("GET /v1/collections/{id}/features", a.listFeatures)
mux.HandleFunc("DELETE /v1/features/{id}", a.deleteFeature)
return withCORS(mux)
}
func withCORS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func writeJSON(w http.ResponseWriter, status int, payload interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(payload)
}
func readJSON(r *http.Request, target interface{}) error {
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
return dec.Decode(target)
}
func statusFromErr(err error) int {
switch {
case errors.Is(err, app.ErrUnauthorized):
return http.StatusUnauthorized
case errors.Is(err, app.ErrForbidden):
return http.StatusForbidden
case errors.Is(err, app.ErrBadRequest):
return http.StatusBadRequest
case errors.Is(err, app.ErrInviteInvalid),
errors.Is(err, app.ErrInviteExpired),
errors.Is(err, app.ErrInviteExhaust):
return http.StatusBadRequest
case errors.Is(err, app.ErrCollectionMiss), errors.Is(err, app.ErrFeatureMiss),
errors.Is(err, store.ErrNotFound):
return http.StatusNotFound
default:
return http.StatusInternalServerError
}
}
func writeErr(w http.ResponseWriter, err error) {
writeJSON(w, statusFromErr(err), map[string]string{"error": err.Error()})
}
func bearerToken(r *http.Request) (string, error) {
h := r.Header.Get("Authorization")
if h == "" {
return "", app.ErrUnauthorized
}
parts := strings.SplitN(h, " ", 2)
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") || parts[1] == "" {
return "", app.ErrUnauthorized
}
return parts[1], nil
}
func (a *API) authUser(r *http.Request) (string, error) {
token, err := bearerToken(r)
if err != nil {
return "", err
}
return a.service.AuthenticateSession(token)
}
func (a *API) health(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok", "time": time.Now().UTC().Format(time.RFC3339)})
}
func (a *API) createChallenge(w http.ResponseWriter, r *http.Request) {
var req struct {
PublicKey string `json:"publicKey"`
}
if err := readJSON(r, &req); err != nil {
writeErr(w, app.ErrBadRequest)
return
}
nonce, err := a.service.CreateChallenge(req.PublicKey)
if err != nil {
writeErr(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]string{"nonce": nonce, "messageToSign": "login:" + nonce})
}
func (a *API) login(w http.ResponseWriter, r *http.Request) {
var req struct {
PublicKey string `json:"publicKey"`
Nonce string `json:"nonce"`
Signature string `json:"signature"`
}
if err := readJSON(r, &req); err != nil {
writeErr(w, app.ErrBadRequest)
return
}
token, err := a.service.Login(req.PublicKey, req.Nonce, req.Signature)
if err != nil {
writeErr(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]string{"accessToken": token})
}
func (a *API) register(w http.ResponseWriter, r *http.Request) {
var req struct {
PublicKey string `json:"publicKey"`
InvitePayloadB64 string `json:"invitePayloadB64"`
InviteSignature string `json:"inviteSignature"`
ProofSignature string `json:"proofSignature"`
}
if err := readJSON(r, &req); err != nil {
writeErr(w, app.ErrBadRequest)
return
}
if err := a.service.Register(req.PublicKey, req.InvitePayloadB64, req.InviteSignature, req.ProofSignature); err != nil {
writeErr(w, err)
return
}
writeJSON(w, http.StatusCreated, map[string]string{"status": "registered"})
}
func (a *API) createInvitation(w http.ResponseWriter, r *http.Request) {
user, err := a.authUser(r)
if err != nil {
writeErr(w, err)
return
}
var req struct {
InvitePayloadB64 string `json:"invitePayloadB64"`
InviteSignature string `json:"inviteSignature"`
}
if err := readJSON(r, &req); err != nil {
writeErr(w, app.ErrBadRequest)
return
}
if err := a.service.CreateInvitation(user, req.InvitePayloadB64, req.InviteSignature); err != nil {
writeErr(w, err)
return
}
writeJSON(w, http.StatusCreated, map[string]string{"status": "invitation stored"})
}
func (a *API) me(w http.ResponseWriter, r *http.Request) {
user, err := a.authUser(r)
if err != nil {
writeErr(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]string{"publicKey": user})
}
func (a *API) createCollection(w http.ResponseWriter, r *http.Request) {
user, err := a.authUser(r)
if err != nil {
writeErr(w, err)
return
}
var req struct {
Name string `json:"name"`
}
if err := readJSON(r, &req); err != nil {
writeErr(w, app.ErrBadRequest)
return
}
collection, err := a.service.CreateCollection(user, req.Name)
if err != nil {
writeErr(w, err)
return
}
writeJSON(w, http.StatusCreated, collection)
}
func (a *API) listCollections(w http.ResponseWriter, r *http.Request) {
user, err := a.authUser(r)
if err != nil {
writeErr(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]interface{}{"collections": a.service.ListCollections(user)})
}
func (a *API) createFeature(w http.ResponseWriter, r *http.Request) {
user, err := a.authUser(r)
if err != nil {
writeErr(w, err)
return
}
collectionID := r.PathValue("id")
var req struct {
Geometry store.Point `json:"geometry"`
Properties map[string]interface{} `json:"properties"`
}
if err := readJSON(r, &req); err != nil {
writeErr(w, app.ErrBadRequest)
return
}
feature, err := a.service.CreateFeature(user, collectionID, req.Geometry, req.Properties)
if err != nil {
writeErr(w, err)
return
}
writeJSON(w, http.StatusCreated, feature)
}
func (a *API) listFeatures(w http.ResponseWriter, r *http.Request) {
user, err := a.authUser(r)
if err != nil {
writeErr(w, err)
return
}
collectionID := r.PathValue("id")
features, err := a.service.ListFeatures(user, collectionID)
if err != nil {
writeErr(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]interface{}{"features": features})
}
func (a *API) deleteFeature(w http.ResponseWriter, r *http.Request) {
user, err := a.authUser(r)
if err != nil {
writeErr(w, err)
return
}
featureID := r.PathValue("id")
if err := a.service.DeleteFeature(user, featureID); err != nil {
writeErr(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
+217
View File
@@ -0,0 +1,217 @@
package store
import (
"errors"
"sync"
"time"
)
var (
ErrNotFound = errors.New("not found")
ErrAlreadyExists = errors.New("already exists")
)
type MemoryStore struct {
mu sync.RWMutex
users map[string]User
challenges map[string]Challenge
sessions map[string]Session
invitations map[string]Invitation
collections map[string]Collection
features map[string]Feature
}
func NewMemoryStore() *MemoryStore {
return &MemoryStore{
users: make(map[string]User),
challenges: make(map[string]Challenge),
sessions: make(map[string]Session),
invitations: make(map[string]Invitation),
collections: make(map[string]Collection),
features: make(map[string]Feature),
}
}
func (s *MemoryStore) UpsertUser(user User) {
s.mu.Lock()
defer s.mu.Unlock()
s.users[user.PublicKey] = user
}
func (s *MemoryStore) GetUser(publicKey string) (User, error) {
s.mu.RLock()
defer s.mu.RUnlock()
user, ok := s.users[publicKey]
if !ok {
return User{}, ErrNotFound
}
return user, nil
}
func (s *MemoryStore) CreateChallenge(ch Challenge) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, exists := s.challenges[ch.Nonce]; exists {
return ErrAlreadyExists
}
s.challenges[ch.Nonce] = ch
return nil
}
func (s *MemoryStore) GetChallenge(nonce string) (Challenge, error) {
s.mu.RLock()
defer s.mu.RUnlock()
ch, ok := s.challenges[nonce]
if !ok {
return Challenge{}, ErrNotFound
}
return ch, nil
}
func (s *MemoryStore) MarkChallengeUsed(nonce string) error {
s.mu.Lock()
defer s.mu.Unlock()
ch, ok := s.challenges[nonce]
if !ok {
return ErrNotFound
}
ch.Used = true
s.challenges[nonce] = ch
return nil
}
func (s *MemoryStore) SaveSession(session Session) {
s.mu.Lock()
defer s.mu.Unlock()
s.sessions[session.Token] = session
}
func (s *MemoryStore) GetSession(token string) (Session, error) {
s.mu.RLock()
defer s.mu.RUnlock()
session, ok := s.sessions[token]
if !ok {
return Session{}, ErrNotFound
}
return session, nil
}
func (s *MemoryStore) SaveInvitation(inv Invitation) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, exists := s.invitations[inv.JTI]; exists {
return ErrAlreadyExists
}
s.invitations[inv.JTI] = inv
return nil
}
func (s *MemoryStore) GetInvitation(jti string) (Invitation, error) {
s.mu.RLock()
defer s.mu.RUnlock()
inv, ok := s.invitations[jti]
if !ok {
return Invitation{}, ErrNotFound
}
return inv, nil
}
func (s *MemoryStore) IncrementInvitationUsage(jti string) error {
s.mu.Lock()
defer s.mu.Unlock()
inv, ok := s.invitations[jti]
if !ok {
return ErrNotFound
}
inv.UsedCount++
s.invitations[jti] = inv
return nil
}
func (s *MemoryStore) SaveCollection(c Collection) {
s.mu.Lock()
defer s.mu.Unlock()
s.collections[c.ID] = c
}
func (s *MemoryStore) ListCollectionsByOwner(owner string) []Collection {
s.mu.RLock()
defer s.mu.RUnlock()
result := make([]Collection, 0)
for _, c := range s.collections {
if c.OwnerKey == owner {
result = append(result, c)
}
}
return result
}
func (s *MemoryStore) GetCollection(id string) (Collection, error) {
s.mu.RLock()
defer s.mu.RUnlock()
c, ok := s.collections[id]
if !ok {
return Collection{}, ErrNotFound
}
return c, nil
}
func (s *MemoryStore) SaveFeature(f Feature) {
s.mu.Lock()
defer s.mu.Unlock()
s.features[f.ID] = f
}
func (s *MemoryStore) ListFeaturesByCollection(collectionID string) []Feature {
s.mu.RLock()
defer s.mu.RUnlock()
result := make([]Feature, 0)
for _, f := range s.features {
if f.CollectionID == collectionID {
result = append(result, f)
}
}
return result
}
func (s *MemoryStore) GetFeature(featureID string) (Feature, error) {
s.mu.RLock()
defer s.mu.RUnlock()
f, ok := s.features[featureID]
if !ok {
return Feature{}, ErrNotFound
}
return f, nil
}
func (s *MemoryStore) DeleteFeature(featureID string) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.features[featureID]; !ok {
return ErrNotFound
}
delete(s.features, featureID)
return nil
}
func (s *MemoryStore) PruneExpired(now time.Time) {
s.mu.Lock()
defer s.mu.Unlock()
for nonce, ch := range s.challenges {
if ch.ExpiresAt.Before(now) {
delete(s.challenges, nonce)
}
}
for token, sess := range s.sessions {
if sess.ExpiresAt.Before(now) {
delete(s.sessions, token)
}
}
for jti, inv := range s.invitations {
if inv.ExpiresAt.Before(now) {
delete(s.invitations, jti)
}
}
}
+54
View File
@@ -0,0 +1,54 @@
package store
import "time"
type User struct {
PublicKey string `json:"publicKey"`
Inviter string `json:"inviter,omitempty"`
CreatedAt time.Time `json:"createdAt"`
}
type Challenge struct {
Nonce string
PublicKey string
ExpiresAt time.Time
Used bool
}
type Session struct {
Token string
PublicKey string
ExpiresAt time.Time
}
type Invitation struct {
JTI string
InviterPublicKey string
InviteePublicKey string
ExpiresAt time.Time
MaxUses int
UsedCount int
}
type Collection struct {
ID string `json:"id"`
OwnerKey string `json:"ownerKey"`
Name string `json:"name"`
CreatedAt time.Time `json:"createdAt"`
}
type Point struct {
Type string `json:"type"`
Coordinates []float64 `json:"coordinates"`
}
type Feature struct {
ID string `json:"id"`
CollectionID string `json:"collectionId"`
OwnerKey string `json:"ownerKey"`
Type string `json:"type"`
Geometry Point `json:"geometry"`
Properties map[string]interface{} `json:"properties"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
+19
View File
@@ -0,0 +1,19 @@
{
"lockfileVersion": 1,
"workspaces": {
"": {
"name": "@momswap/geo-api-client",
"dependencies": {
"@noble/ed25519": "latest",
},
"devDependencies": {
"typescript": "latest",
},
},
},
"packages": {
"@noble/ed25519": ["@noble/ed25519@3.0.0", "", {}, "sha512-QyteqMNm0GLqfa5SoYbSC3+Pvykwpn95Zgth4MFVSMKBB75ELl9tX1LAVsN4c3HXOrakHsF2gL4zWDAYCcsnzg=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
}
}
+617
View File
@@ -0,0 +1,617 @@
// node_modules/@noble/ed25519/index.js
/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
var ed25519_CURVE = {
p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,
h: 8n,
a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,
d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,
Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,
Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n
};
var { p: P, n: N, Gx, Gy, a: _a, d: _d, h } = ed25519_CURVE;
var L = 32;
var L2 = 64;
var captureTrace = (...args) => {
if ("captureStackTrace" in Error && typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(...args);
}
};
var err = (message = "") => {
const e = new Error(message);
captureTrace(e, err);
throw e;
};
var isBig = (n) => typeof n === "bigint";
var isStr = (s) => typeof s === "string";
var isBytes = (a) => a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
var abytes = (value, length, title = "") => {
const bytes = isBytes(value);
const len = value?.length;
const needsLen = length !== undefined;
if (!bytes || needsLen && len !== length) {
const prefix = title && `"${title}" `;
const ofLen = needsLen ? ` of length ${length}` : "";
const got = bytes ? `length=${len}` : `type=${typeof value}`;
err(prefix + "expected Uint8Array" + ofLen + ", got " + got);
}
return value;
};
var u8n = (len) => new Uint8Array(len);
var u8fr = (buf) => Uint8Array.from(buf);
var padh = (n, pad) => n.toString(16).padStart(pad, "0");
var bytesToHex = (b) => Array.from(abytes(b)).map((e) => padh(e, 2)).join("");
var C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };
var _ch = (ch) => {
if (ch >= C._0 && ch <= C._9)
return ch - C._0;
if (ch >= C.A && ch <= C.F)
return ch - (C.A - 10);
if (ch >= C.a && ch <= C.f)
return ch - (C.a - 10);
return;
};
var hexToBytes = (hex) => {
const e = "hex invalid";
if (!isStr(hex))
return err(e);
const hl = hex.length;
const al = hl / 2;
if (hl % 2)
return err(e);
const array = u8n(al);
for (let ai = 0, hi = 0;ai < al; ai++, hi += 2) {
const n1 = _ch(hex.charCodeAt(hi));
const n2 = _ch(hex.charCodeAt(hi + 1));
if (n1 === undefined || n2 === undefined)
return err(e);
array[ai] = n1 * 16 + n2;
}
return array;
};
var cr = () => globalThis?.crypto;
var subtle = () => cr()?.subtle ?? err("crypto.subtle must be defined, consider polyfill");
var concatBytes = (...arrs) => {
const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0));
let pad = 0;
arrs.forEach((a) => {
r.set(a, pad);
pad += a.length;
});
return r;
};
var big = BigInt;
var assertRange = (n, min, max, msg = "bad number: out of range") => isBig(n) && min <= n && n < max ? n : err(msg);
var M = (a, b = P) => {
const r = a % b;
return r >= 0n ? r : b + r;
};
var modN = (a) => M(a, N);
var invert = (num, md) => {
if (num === 0n || md <= 0n)
err("no inverse n=" + num + " mod=" + md);
let a = M(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;
while (a !== 0n) {
const q = b / a, r = b % a;
const m = x - u * q, n = y - v * q;
b = a, a = r, x = u, y = v, u = m, v = n;
}
return b === 1n ? M(x, md) : err("no inverse");
};
var apoint = (p) => p instanceof Point ? p : err("Point expected");
var B256 = 2n ** 256n;
class Point {
static BASE;
static ZERO;
X;
Y;
Z;
T;
constructor(X, Y, Z, T) {
const max = B256;
this.X = assertRange(X, 0n, max);
this.Y = assertRange(Y, 0n, max);
this.Z = assertRange(Z, 1n, max);
this.T = assertRange(T, 0n, max);
Object.freeze(this);
}
static CURVE() {
return ed25519_CURVE;
}
static fromAffine(p) {
return new Point(p.x, p.y, 1n, M(p.x * p.y));
}
static fromBytes(hex, zip215 = false) {
const d = _d;
const normed = u8fr(abytes(hex, L));
const lastByte = hex[31];
normed[31] = lastByte & ~128;
const y = bytesToNumLE(normed);
const max = zip215 ? B256 : P;
assertRange(y, 0n, max);
const y2 = M(y * y);
const u = M(y2 - 1n);
const v = M(d * y2 + 1n);
let { isValid, value: x } = uvRatio(u, v);
if (!isValid)
err("bad point: y not sqrt");
const isXOdd = (x & 1n) === 1n;
const isLastByteOdd = (lastByte & 128) !== 0;
if (!zip215 && x === 0n && isLastByteOdd)
err("bad point: x==0, isLastByteOdd");
if (isLastByteOdd !== isXOdd)
x = M(-x);
return new Point(x, y, 1n, M(x * y));
}
static fromHex(hex, zip215) {
return Point.fromBytes(hexToBytes(hex), zip215);
}
get x() {
return this.toAffine().x;
}
get y() {
return this.toAffine().y;
}
assertValidity() {
const a = _a;
const d = _d;
const p = this;
if (p.is0())
return err("bad point: ZERO");
const { X, Y, Z, T } = p;
const X2 = M(X * X);
const Y2 = M(Y * Y);
const Z2 = M(Z * Z);
const Z4 = M(Z2 * Z2);
const aX2 = M(X2 * a);
const left = M(Z2 * M(aX2 + Y2));
const right = M(Z4 + M(d * M(X2 * Y2)));
if (left !== right)
return err("bad point: equation left != right (1)");
const XY = M(X * Y);
const ZT = M(Z * T);
if (XY !== ZT)
return err("bad point: equation left != right (2)");
return this;
}
equals(other) {
const { X: X1, Y: Y1, Z: Z1 } = this;
const { X: X2, Y: Y2, Z: Z2 } = apoint(other);
const X1Z2 = M(X1 * Z2);
const X2Z1 = M(X2 * Z1);
const Y1Z2 = M(Y1 * Z2);
const Y2Z1 = M(Y2 * Z1);
return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
}
is0() {
return this.equals(I);
}
negate() {
return new Point(M(-this.X), this.Y, this.Z, M(-this.T));
}
double() {
const { X: X1, Y: Y1, Z: Z1 } = this;
const a = _a;
const A = M(X1 * X1);
const B = M(Y1 * Y1);
const C2 = M(2n * M(Z1 * Z1));
const D = M(a * A);
const x1y1 = X1 + Y1;
const E = M(M(x1y1 * x1y1) - A - B);
const G = D + B;
const F = G - C2;
const H = D - B;
const X3 = M(E * F);
const Y3 = M(G * H);
const T3 = M(E * H);
const Z3 = M(F * G);
return new Point(X3, Y3, Z3, T3);
}
add(other) {
const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
const { X: X2, Y: Y2, Z: Z2, T: T2 } = apoint(other);
const a = _a;
const d = _d;
const A = M(X1 * X2);
const B = M(Y1 * Y2);
const C2 = M(T1 * d * T2);
const D = M(Z1 * Z2);
const E = M((X1 + Y1) * (X2 + Y2) - A - B);
const F = M(D - C2);
const G = M(D + C2);
const H = M(B - a * A);
const X3 = M(E * F);
const Y3 = M(G * H);
const T3 = M(E * H);
const Z3 = M(F * G);
return new Point(X3, Y3, Z3, T3);
}
subtract(other) {
return this.add(apoint(other).negate());
}
multiply(n, safe = true) {
if (!safe && (n === 0n || this.is0()))
return I;
assertRange(n, 1n, N);
if (n === 1n)
return this;
if (this.equals(G))
return wNAF(n).p;
let p = I;
let f = G;
for (let d = this;n > 0n; d = d.double(), n >>= 1n) {
if (n & 1n)
p = p.add(d);
else if (safe)
f = f.add(d);
}
return p;
}
multiplyUnsafe(scalar) {
return this.multiply(scalar, false);
}
toAffine() {
const { X, Y, Z } = this;
if (this.equals(I))
return { x: 0n, y: 1n };
const iz = invert(Z, P);
if (M(Z * iz) !== 1n)
err("invalid inverse");
const x = M(X * iz);
const y = M(Y * iz);
return { x, y };
}
toBytes() {
const { x, y } = this.assertValidity().toAffine();
const b = numTo32bLE(y);
b[31] |= x & 1n ? 128 : 0;
return b;
}
toHex() {
return bytesToHex(this.toBytes());
}
clearCofactor() {
return this.multiply(big(h), false);
}
isSmallOrder() {
return this.clearCofactor().is0();
}
isTorsionFree() {
let p = this.multiply(N / 2n, false).double();
if (N % 2n)
p = p.add(this);
return p.is0();
}
}
var G = new Point(Gx, Gy, 1n, M(Gx * Gy));
var I = new Point(0n, 1n, 1n, 0n);
Point.BASE = G;
Point.ZERO = I;
var numTo32bLE = (num) => hexToBytes(padh(assertRange(num, 0n, B256), L2)).reverse();
var bytesToNumLE = (b) => big("0x" + bytesToHex(u8fr(abytes(b)).reverse()));
var pow2 = (x, power) => {
let r = x;
while (power-- > 0n) {
r *= r;
r %= P;
}
return r;
};
var pow_2_252_3 = (x) => {
const x2 = x * x % P;
const b2 = x2 * x % P;
const b4 = pow2(b2, 2n) * b2 % P;
const b5 = pow2(b4, 1n) * x % P;
const b10 = pow2(b5, 5n) * b5 % P;
const b20 = pow2(b10, 10n) * b10 % P;
const b40 = pow2(b20, 20n) * b20 % P;
const b80 = pow2(b40, 40n) * b40 % P;
const b160 = pow2(b80, 80n) * b80 % P;
const b240 = pow2(b160, 80n) * b80 % P;
const b250 = pow2(b240, 10n) * b10 % P;
const pow_p_5_8 = pow2(b250, 2n) * x % P;
return { pow_p_5_8, b2 };
};
var RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n;
var uvRatio = (u, v) => {
const v3 = M(v * v * v);
const v7 = M(v3 * v3 * v);
const pow = pow_2_252_3(u * v7).pow_p_5_8;
let x = M(u * v3 * pow);
const vx2 = M(v * x * x);
const root1 = x;
const root2 = M(x * RM1);
const useRoot1 = vx2 === u;
const useRoot2 = vx2 === M(-u);
const noRoot = vx2 === M(-u * RM1);
if (useRoot1)
x = root1;
if (useRoot2 || noRoot)
x = root2;
if ((M(x) & 1n) === 1n)
x = M(-x);
return { isValid: useRoot1 || useRoot2, value: x };
};
var modL_LE = (hash) => modN(bytesToNumLE(hash));
var sha512a = (...m) => hashes.sha512Async(concatBytes(...m));
var hash2extK = (hashed) => {
const head = hashed.slice(0, L);
head[0] &= 248;
head[31] &= 127;
head[31] |= 64;
const prefix = hashed.slice(L, L2);
const scalar = modL_LE(head);
const point = G.multiply(scalar);
const pointBytes = point.toBytes();
return { head, prefix, scalar, point, pointBytes };
};
var getExtendedPublicKeyAsync = (secretKey) => sha512a(abytes(secretKey, L)).then(hash2extK);
var getPublicKeyAsync = (secretKey) => getExtendedPublicKeyAsync(secretKey).then((p) => p.pointBytes);
var hashFinishA = (res) => sha512a(res.hashable).then(res.finish);
var _sign = (e, rBytes, msg) => {
const { pointBytes: P2, scalar: s } = e;
const r = modL_LE(rBytes);
const R = G.multiply(r).toBytes();
const hashable = concatBytes(R, P2, msg);
const finish = (hashed) => {
const S = modN(r + modL_LE(hashed) * s);
return abytes(concatBytes(R, numTo32bLE(S)), L2);
};
return { hashable, finish };
};
var signAsync = async (message, secretKey) => {
const m = abytes(message);
const e = await getExtendedPublicKeyAsync(secretKey);
const rBytes = await sha512a(e.prefix, m);
return hashFinishA(_sign(e, rBytes, m));
};
var hashes = {
sha512Async: async (message) => {
const s = subtle();
const m = concatBytes(message);
return u8n(await s.digest("SHA-512", m.buffer));
},
sha512: undefined
};
var W = 8;
var scalarBits = 256;
var pwindows = Math.ceil(scalarBits / W) + 1;
var pwindowSize = 2 ** (W - 1);
var precompute = () => {
const points = [];
let p = G;
let b = p;
for (let w = 0;w < pwindows; w++) {
b = p;
points.push(b);
for (let i = 1;i < pwindowSize; i++) {
b = b.add(p);
points.push(b);
}
p = b.double();
}
return points;
};
var Gpows = undefined;
var ctneg = (cnd, p) => {
const n = p.negate();
return cnd ? n : p;
};
var wNAF = (n) => {
const comp = Gpows || (Gpows = precompute());
let p = I;
let f = G;
const pow_2_w = 2 ** W;
const maxNum = pow_2_w;
const mask = big(pow_2_w - 1);
const shiftBy = big(W);
for (let w = 0;w < pwindows; w++) {
let wbits = Number(n & mask);
n >>= shiftBy;
if (wbits > pwindowSize) {
wbits -= maxNum;
n += 1n;
}
const off = w * pwindowSize;
const offF = off;
const offP = off + Math.abs(wbits) - 1;
const isEven = w % 2 !== 0;
const isNeg = wbits < 0;
if (wbits === 0) {
f = f.add(ctneg(isEven, comp[offF]));
} else {
p = p.add(ctneg(isNeg, comp[offP]));
}
}
if (n !== 0n)
err("invalid wnaf");
return { p, f };
};
// src/encoding.ts
function bytesToBase64Url(bytes) {
const bin = Array.from(bytes).map((b) => String.fromCharCode(b)).join("");
if (typeof btoa !== "undefined") {
return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
}
const b64 = globalThis.Buffer.from(bytes).toString("base64");
return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
}
function base64UrlToBytes(input) {
const normalized = input.replace(/-/g, "+").replace(/_/g, "/");
const padLen = (4 - normalized.length % 4) % 4;
const b64 = normalized + "=".repeat(padLen);
if (typeof atob !== "undefined") {
const bin = atob(b64);
const out = new Uint8Array(bin.length);
for (let i = 0;i < bin.length; i++) {
out[i] = bin.charCodeAt(i);
}
return out;
}
return new Uint8Array(globalThis.Buffer.from(b64, "base64"));
}
function textToBytes(value) {
return new TextEncoder().encode(value);
}
// src/keys.ts
function randomPrivateKey() {
const out = new Uint8Array(32);
crypto.getRandomValues(out);
return out;
}
async function generateKeyPair() {
const privateKey = randomPrivateKey();
const publicKey = await getPublicKeyAsync(privateKey);
return {
publicKey: bytesToBase64Url(publicKey),
privateKey: bytesToBase64Url(privateKey)
};
}
async function signMessage(privateKeyBase64, message) {
const privateKey = base64UrlToBytes(privateKeyBase64);
const signature = await signAsync(textToBytes(message), privateKey);
return bytesToBase64Url(signature);
}
// src/storage.ts
var DEFAULT_KEYS_STORAGE_KEY = "geo_api_keys_v1";
function saveKeys(storage, keys, storageKey = DEFAULT_KEYS_STORAGE_KEY) {
storage.setItem(storageKey, JSON.stringify(keys));
}
function loadKeys(storage, storageKey = DEFAULT_KEYS_STORAGE_KEY) {
const raw = storage.getItem(storageKey);
if (!raw) {
return null;
}
const parsed = JSON.parse(raw);
if (!parsed.publicKey || !parsed.privateKey) {
return null;
}
return parsed;
}
function clearKeys(storage, storageKey = DEFAULT_KEYS_STORAGE_KEY) {
storage.removeItem(storageKey);
}
// src/GeoApiClient.ts
class GeoApiClient {
baseUrl;
storage;
storageKey;
accessToken = null;
constructor(baseUrl, storage, storageKey = DEFAULT_KEYS_STORAGE_KEY) {
this.baseUrl = baseUrl.replace(/\/+$/g, "");
this.storage = storage;
this.storageKey = storageKey;
}
async ensureKeysInStorage() {
const existing = loadKeys(this.storage, this.storageKey);
if (existing) {
return existing;
}
const generated = await generateKeyPair();
saveKeys(this.storage, generated, this.storageKey);
return generated;
}
getStoredKeys() {
return loadKeys(this.storage, this.storageKey);
}
importKeys(keys) {
saveKeys(this.storage, keys, this.storageKey);
}
exportKeys() {
return loadKeys(this.storage, this.storageKey);
}
setAccessToken(token) {
this.accessToken = token;
}
async request(path, init = {}) {
const headers = new Headers(init.headers ?? {});
headers.set("Content-Type", "application/json");
if (this.accessToken) {
headers.set("Authorization", `Bearer ${this.accessToken}`);
}
const body = init.body === undefined ? undefined : JSON.stringify(init.body);
const res = await fetch(`${this.baseUrl}${path}`, { ...init, headers, body });
if (!res.ok) {
const maybeJson = await res.json().catch(() => ({}));
const msg = maybeJson.error ?? `HTTP ${res.status}`;
throw new Error(msg);
}
if (res.status === 204) {
return;
}
return await res.json();
}
async createChallenge(publicKey) {
return this.request("/v1/auth/challenge", { method: "POST", body: { publicKey } });
}
async loginWithSignature(publicKey, privateKey) {
const challenge = await this.createChallenge(publicKey);
const signature = await signMessage(privateKey, challenge.messageToSign);
const response = await this.request("/v1/auth/login", {
method: "POST",
body: {
publicKey,
nonce: challenge.nonce,
signature
}
});
this.accessToken = response.accessToken;
return response.accessToken;
}
async createInvitation(payload, inviterPrivateKey) {
const payloadStr = JSON.stringify(payload);
const payloadB64 = bytesToBase64Url(textToBytes(payloadStr));
const inviteSignature = await signMessage(inviterPrivateKey, `invite:${payloadB64}`);
await this.request("/v1/invitations", {
method: "POST",
body: {
invitePayloadB64: payloadB64,
inviteSignature
}
});
}
async registerWithInvitation(input) {
const proofSignature = await signMessage(input.privateKey, `register:${input.publicKey}:${input.jti}`);
await this.request("/v1/auth/register", {
method: "POST",
body: {
publicKey: input.publicKey,
invitePayloadB64: input.invitePayloadB64,
inviteSignature: input.inviteSignature,
proofSignature
}
});
}
async listCollections() {
return this.request("/v1/collections", { method: "GET" });
}
async createCollection(name) {
return this.request("/v1/collections", { method: "POST", body: { name } });
}
async listFeatures(collectionId) {
return this.request(`/v1/collections/${collectionId}/features`, { method: "GET" });
}
async createPointFeature(collectionId, lon, lat, properties) {
return this.request(`/v1/collections/${collectionId}/features`, {
method: "POST",
body: {
geometry: { type: "Point", coordinates: [lon, lat] },
properties
}
});
}
}
export {
signMessage,
saveKeys,
loadKeys,
generateKeyPair,
clearKeys,
GeoApiClient,
DEFAULT_KEYS_STORAGE_KEY
};
+1
View File
@@ -0,0 +1 @@
../typescript/bin/tsc
+1
View File
@@ -0,0 +1 @@
../typescript/bin/tsserver
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2019 Paul Miller (https://paulmillr.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+346
View File
@@ -0,0 +1,346 @@
# noble-ed25519
Fastest 5KB JS implementation of ed25519 signatures.
- ✍️ [EDDSA](https://en.wikipedia.org/wiki/EdDSA) signatures compliant with
[RFC8032](https://tools.ietf.org/html/rfc8032), FIPS 186-5
- 🪢 Consensus-friendly, compliant with [ZIP215](https://zips.z.cash/zip-0215)
- 🔖 SUF-CMA (strong unforgeability under chosen message attacks) and
SBS (non-repudiation / exclusive ownership)
- 🪶 3.66KB (gzipped)
The module is a sister project of [noble-curves](https://github.com/paulmillr/noble-curves),
focusing on smaller attack surface & better auditability.
Curves are drop-in replacement and have more features: ristretto255, x25519 / curve25519, ed25519ph, hash-to-curve, oprf. To upgrade from v1 to v2, see [Upgrading](#upgrading).
### This library belongs to _noble_ cryptography
> **noble-cryptography** — high-security, easily auditable set of contained cryptographic libraries and tools.
- Zero or minimal dependencies
- Highly readable TypeScript / JS code
- PGP-signed releases and transparent NPM builds with provenance
- Check out [homepage](https://paulmillr.com/noble/) & all libraries:
[ciphers](https://github.com/paulmillr/noble-ciphers),
[curves](https://github.com/paulmillr/noble-curves),
[hashes](https://github.com/paulmillr/noble-hashes),
[post-quantum](https://github.com/paulmillr/noble-post-quantum),
5KB [secp256k1](https://github.com/paulmillr/noble-secp256k1) /
[ed25519](https://github.com/paulmillr/noble-ed25519)
## Usage
> `npm install @noble/ed25519`
> `deno add jsr:@noble/ed25519`
We support all major platforms and runtimes. For node.js <= 18 and React Native, additional polyfills are needed: see below.
```js
import * as ed from '@noble/ed25519';
(async () => {
const { secretKey, publicKey } = await ed.keygenAsync();
// const publicKey = await ed.getPublicKeyAsync(secretKey);
const message = new TextEncoder().encode('hello noble');
const signature = await ed.signAsync(message, secretKey);
const isValid = await ed.verifyAsync(signature, message, publicKey);
})();
```
### Enabling synchronous methods
Only async methods are available by default, to keep the library dependency-free.
To enable sync methods:
```ts
import { sha512 } from '@noble/hashes/sha2.js';
ed.hashes.sha512 = sha512;
// Sync methods can be used now:
const { secretKey, publicKey } = ed.keygen();
// const publicKey = ed.getPublicKey(secretKey);
const sig = ed.sign(msg, secretKey);
const isValid = ed.verify(sig, msg, publicKey);
```
### React Native: polyfill getRandomValues and sha512
```ts
import 'react-native-get-random-values';
import { sha512 } from '@noble/hashes/sha2.js';
ed.hashes.sha512 = sha512;
ed.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m));
```
## API
There are 4 main methods, which accept Uint8Array-s:
- `keygen()` and `keygenAsync()`
- `getPublicKey(secretKey)` and `getPublicKeyAsync(secretKey)`
- `sign(message, secretKey)` and `signAsync(message, secretKey)`
- `verify(signature, message, publicKey)` and `verifyAsync(signature, message, publicKey)`
### keygen
```typescript
import * as ed from '@noble/ed25519';
(async () => {
const keys = ed.keygen(); // needs ed.hashes.sha512
const { secretKey, publicKey } = keys
const keysA = await ed.keygenAsync();
})();
```
### getPublicKey
```typescript
import * as ed from '@noble/ed25519';
(async () => {
const pubKey = ed.getPublicKey(secretKeyA); // needs ed.hashes.sha512
const pubKeyA = await ed.getPublicKeyAsync(secretKeyA);
const pubKeyPoint = ed.Point.fromBytes(pubKeyB);
const pubKeyExtended = ed.utils.getExtendedPublicKey(secretKeyA);
})();
```
Generates 32-byte public key from 32-byte private key.
- Some libraries have 64-byte private keys - those are just priv+pub concatenated
- Use `ExtendedPoint.fromHex(publicKey)` if you want to convert hex / bytes into Point.
It will use decompression algorithm 5.1.3 of RFC 8032.
- Use `utils.getExtendedPublicKey` if you need full SHA512 hash of seed
### sign
```ts
import * as ed from '@noble/ed25519';
(async () => {
const { secretKey, publicKey } = ed.keygen();
const message = new TextEncoder().encode('hello noble');
const signature = ed.sign(message, secretKey);
const signatureA = await ed.signAsync(message, secretKey);
})();
```
Generates deterministic EdDSA signature. `message` would be hashed by ed25519 internally.
For prehashed ed25519ph, switch to noble-curves.
### verify
```ts
import * as ed from '@noble/ed25519';
(async () => {
const { secretKey, publicKey } = ed.keygen();
const message = new TextEncoder().encode('hello noble');
const signature = ed.sign(message, secretKey);
const isValid = ed.verify(signature, message, pubKey);
const isValidFips = ed.verify(signature, message, pubKey, { zip215: false });
const isValidA = await ed.verifyAsync(signature, message, pubKey);
})();
```
Verifies EdDSA signature. Has SUF-CMA (strong unforgeability under chosen message attacks).
By default, follows ZIP215 [^1] and can be used in consensus-critical apps [^2].
`zip215: false` option switches verification criteria to strict
RFC8032 / FIPS 186-5 and provides non-repudiation with SBS (Strongly Binding Signatures) [^3].
### utils
A bunch of useful **utilities** are also exposed:
```typescript
import * as ed from '@noble/ed25519';
const { bytesToHex, hexToBytes, concatBytes, mod, invert, randomBytes } = ed.etc;
const { getExtendedPublicKey, getExtendedPublicKeyAsync, randomSecretKey } = ed.utils;
const { Point } = ed;
console.log(Point.CURVE(), Point.BASE);
/*
class Point {
static BASE: Point;
static ZERO: Point;
readonly X: bigint;
readonly Y: bigint;
readonly Z: bigint;
readonly T: bigint;
constructor(X: bigint, Y: bigint, Z: bigint, T: bigint);
static CURVE(): EdwardsOpts;
static fromAffine(p: AffinePoint): Point;
static fromBytes(hex: Bytes, zip215?: boolean): Point;
static fromHex(hex: string, zip215?: boolean): Point;
get x(): bigint;
get y(): bigint;
assertValidity(): this;
equals(other: Point): boolean;
is0(): boolean;
negate(): Point;
double(): Point;
add(other: Point): Point;
subtract(other: Point): Point;
multiply(n: bigint, safe?: boolean): Point;
multiplyUnsafe(scalar: bigint): Point;
toAffine(): AffinePoint;
toBytes(): Bytes;
toHex(): string;
clearCofactor(): Point;
isSmallOrder(): boolean;
isTorsionFree(): boolean;
}
*/
```
## Security
The module is production-ready.
We cross-test against sister project [noble-curves](https://github.com/paulmillr/noble-curves), which was audited and provides improved security.
- The current version has not been independently audited. It is a rewrite of v1, which has been audited by cure53 in Feb 2022:
[PDF](https://cure53.de/pentest-report_ed25519.pdf).
- It's being fuzzed [in a separate repository](https://github.com/paulmillr/fuzzing)
If you see anything unusual: investigate and report.
### Constant-timeness
We're targetting algorithmic constant time. _JIT-compiler_ and _Garbage Collector_ make "constant time"
extremely hard to achieve [timing attack](https://en.wikipedia.org/wiki/Timing_attack) resistance
in a scripting language. Which means _any other JS library can't have
constant-timeness_. Even statically typed Rust, a language without GC,
[makes it harder to achieve constant-time](https://www.chosenplaintext.ca/open-source/rust-timing-shield/security)
for some cases. If your goal is absolute security, don't use any JS lib — including bindings to native ones.
Use low-level libraries & languages.
### Supply chain security
- **Commits** are signed with PGP keys, to prevent forgery. Make sure to verify commit signatures
- **Releases** are transparent and built on GitHub CI.
Check out [attested checksums of single-file builds](https://github.com/paulmillr/noble-ed25519/attestations)
and [provenance logs](https://github.com/paulmillr/noble-ed25519/actions/workflows/release.yml)
- **Rare releasing** is followed to ensure less re-audit need for end-users
- **Dependencies** are minimized and locked-down: any dependency could get hacked and users will be downloading malware with every install.
- We make sure to use as few dependencies as possible
- Automatic dep updates are prevented by locking-down version ranges; diffs are checked with `npm-diff`
- **Dev Dependencies** are disabled for end-users; they are only used to develop / build the source code
For this package, there are 0 dependencies; and a few dev dependencies:
- [noble-hashes](https://github.com/paulmillr/noble-hashes) provides cryptographic hashing functionality
- micro-bmark, micro-should and jsbt are used for benchmarking / testing / build tooling and developed by the same author
- prettier, fast-check and typescript are used for code quality / test generation / ts compilation. It's hard to audit their source code thoroughly and fully because of their size
### Randomness
We're deferring to built-in
[crypto.getRandomValues](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues)
which is considered cryptographically secure (CSPRNG).
In the past, browsers had bugs that made it weak: it may happen again.
Implementing a userspace CSPRNG to get resilient to the weakness
is even worse: there is no reliable userspace source of quality entropy.
### Quantum computers
Cryptographically relevant quantum computer, if built, will allow to
break elliptic curve cryptography (both ECDSA / EdDSA & ECDH) using Shor's algorithm.
Consider switching to newer / hybrid algorithms, such as SPHINCS+. They are available in
[noble-post-quantum](https://github.com/paulmillr/noble-post-quantum).
NIST prohibits classical cryptography (RSA, DSA, ECDSA, ECDH) [after 2035](https://nvlpubs.nist.gov/nistpubs/ir/2024/NIST.IR.8547.ipd.pdf). Australian ASD prohibits it [after 2030](https://www.cyber.gov.au/resources-business-and-government/essential-cyber-security/ism/cyber-security-guidelines/guidelines-cryptography).
## Speed
npm run bench
Benchmarks measured with Apple M4.
init 11ms
keygen x 11,253 ops/sec @ 88μs/op
sign x 5,891 ops/sec @ 169μs/op
verify x 1,281 ops/sec @ 780μs/op
keygenAsync x 10,205 ops/sec @ 97μs/op
signAsync x 4,985 ops/sec @ 200μs/op
verifyAsync x 1,286 ops/sec @ 777μs/op
Point.fromBytes x 22,811 ops/sec @ 43μs/op
Compare to alternative implementations:
tweetnacl@1.0.3 getPublicKey x 1,808 ops/sec @ 552μs/op ± 1.64%
tweetnacl@1.0.3 sign x 651 ops/sec @ 1ms/op
ristretto255@0.1.2 getPublicKey x 640 ops/sec @ 1ms/op ± 1.59%
sodium-native#sign x 83,654 ops/sec @ 11μs/op
## Upgrading
### v2 to v3
v3 brings the package closer to noble-curves v2.
- Most methods now expect Uint8Array, string hex inputs are prohibited
- Add `keygen`, `keygenAsync` method
- Node v20.19 is now the minimum required version
- Various small changes for types and Point class
- etc: hashes are now set in `hashes` object:
```js
// before
ed.etc.sha512 = sha512;
ed.etc.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m));
// after
ed.hashes.sha512 = sha512;
ed.hashes.sha512Async = (m: Uint8Array) => Promise.resolve(sha512(m));
```
### v1 to v2
v2 features improved security and smaller attack surface.
The goal of v2 is to provide minimum possible JS library which is safe and fast.
That means the library was reduced 4x, to just over 300 lines. In order to
achieve the goal, **some features were moved** to
[noble-curves](https://github.com/paulmillr/noble-curves), which is
even safer and faster drop-in replacement library with same API.
Switch to curves if you intend to keep using these features:
- x25519 / curve25519 / getSharedSecret
- ristretto255 / RistrettoPoint
- Using `utils.precompute()` for non-base point
- Support for environments which don't support bigint literals
- Common.js support
- Support for node.js 18 and older without [shim](#usage)
Other changes for upgrading from @noble/ed25519 1.7 to 2.0:
- Methods are now sync by default; use `getPublicKeyAsync`, `signAsync`, `verifyAsync` for async versions
- `bigint` is no longer allowed in `getPublicKey`, `sign`, `verify`. Reason: ed25519 is LE, can lead to bugs
- `Point` (2d xy) has been changed to `ExtendedPoint` (xyzt)
- `Signature` was removed: just use raw bytes or hex now
- `utils` were split into `utils` (same api as in noble-curves) and
`etc` (`sha512Sync` and others)
## Contributing & testing
- `npm install && npm run build && npm test` will build the code and run tests.
- `npm run bench` will run benchmarks
- `npm run build:release` will build single file
See [paulmillr.com/noble](https://paulmillr.com/noble/)
for useful resources, articles, documentation and demos
related to the library.
## License
The MIT License (MIT)
Copyright (c) 2019 Paul Miller [(https://paulmillr.com)](https://paulmillr.com)
See LICENSE file.
[^1]: https://zips.z.cash/zip-0215
[^2]: https://hdevalence.ca/blog/2020-10-04-its-25519am
[^3]: https://eprint.iacr.org/2020/1244
+131
View File
@@ -0,0 +1,131 @@
/** Alias to Uint8Array. */
export type Bytes = Uint8Array;
/** Hex-encoded string or Uint8Array. */
/** Edwards elliptic curve options. */
export type EdwardsOpts = Readonly<{
p: bigint;
n: bigint;
h: bigint;
a: bigint;
d: bigint;
Gx: bigint;
Gy: bigint;
}>;
declare const bytesToHex: (b: Bytes) => string;
declare const hexToBytes: (hex: string) => Bytes;
declare const concatBytes: (...arrs: Bytes[]) => Bytes;
/** WebCrypto OS-level CSPRNG (random number generator). Will throw when not available. */
declare const randomBytes: (len?: number) => Bytes;
/** modular division */
declare const M: (a: bigint, b?: bigint) => bigint;
/** Modular inversion using euclidean GCD (non-CT). No negative exponent for now. */
declare const invert: (num: bigint, md: bigint) => bigint;
declare const hash: (msg: Bytes) => Bytes;
/** Point in 2d xy affine coordinates. */
export type AffinePoint = {
x: bigint;
y: bigint;
};
/** Point in XYZT extended coordinates. */
declare class Point {
static BASE: Point;
static ZERO: Point;
readonly X: bigint;
readonly Y: bigint;
readonly Z: bigint;
readonly T: bigint;
constructor(X: bigint, Y: bigint, Z: bigint, T: bigint);
static CURVE(): EdwardsOpts;
static fromAffine(p: AffinePoint): Point;
/** RFC8032 5.1.3: Uint8Array to Point. */
static fromBytes(hex: Bytes, zip215?: boolean): Point;
static fromHex(hex: string, zip215?: boolean): Point;
get x(): bigint;
get y(): bigint;
/** Checks if the point is valid and on-curve. */
assertValidity(): this;
/** Equality check: compare points P&Q. */
equals(other: Point): boolean;
is0(): boolean;
/** Flip point over y coordinate. */
negate(): Point;
/** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */
double(): Point;
/** Point addition. Complete formula. Cost: `8M + 1*k + 8add + 1*2`. */
add(other: Point): Point;
subtract(other: Point): Point;
/**
* Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
* Uses {@link wNAF} for base point.
* Uses fake point to mitigate side-channel leakage.
* @param n scalar by which point is multiplied
* @param safe safe mode guards against timing attacks; unsafe mode is faster
*/
multiply(n: bigint, safe?: boolean): Point;
multiplyUnsafe(scalar: bigint): Point;
/** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */
toAffine(): AffinePoint;
toBytes(): Bytes;
toHex(): string;
clearCofactor(): Point;
isSmallOrder(): boolean;
isTorsionFree(): boolean;
}
type ExtK = {
head: Bytes;
prefix: Bytes;
scalar: bigint;
point: Point;
pointBytes: Bytes;
};
declare const getExtendedPublicKeyAsync: (secretKey: Bytes) => Promise<ExtK>;
declare const getExtendedPublicKey: (secretKey: Bytes) => ExtK;
/** Creates 32-byte ed25519 public key from 32-byte secret key. Async. */
declare const getPublicKeyAsync: (secretKey: Bytes) => Promise<Bytes>;
/** Creates 32-byte ed25519 public key from 32-byte secret key. To use, set `hashes.sha512` first. */
declare const getPublicKey: (priv: Bytes) => Bytes;
/**
* Signs message using secret key. Async.
* Follows RFC8032 5.1.6.
*/
declare const signAsync: (message: Bytes, secretKey: Bytes) => Promise<Bytes>;
/**
* Signs message using secret key. To use, set `hashes.sha512` first.
* Follows RFC8032 5.1.6.
*/
declare const sign: (message: Bytes, secretKey: Bytes) => Bytes;
/** Verification options. zip215: true (default) follows ZIP215 spec. false would follow RFC8032. */
export type EdDSAVerifyOpts = {
zip215?: boolean;
};
/** Verifies signature on message and public key. Async. Follows RFC8032 5.1.7. */
declare const verifyAsync: (signature: Bytes, message: Bytes, publicKey: Bytes, opts?: EdDSAVerifyOpts) => Promise<boolean>;
/** Verifies signature on message and public key. To use, set `hashes.sha512` first. Follows RFC8032 5.1.7. */
declare const verify: (signature: Bytes, message: Bytes, publicKey: Bytes, opts?: EdDSAVerifyOpts) => boolean;
/** Math, hex, byte helpers. Not in `utils` because utils share API with noble-curves. */
declare const etc: {
bytesToHex: typeof bytesToHex;
hexToBytes: typeof hexToBytes;
concatBytes: typeof concatBytes;
mod: typeof M;
invert: typeof invert;
randomBytes: typeof randomBytes;
};
declare const hashes: {
sha512Async: (message: Bytes) => Promise<Bytes>;
sha512: undefined | ((message: Bytes) => Bytes);
};
declare const randomSecretKey: (seed?: Bytes) => Bytes;
type KeysSecPub = {
secretKey: Bytes;
publicKey: Bytes;
};
declare const keygen: (seed?: Bytes) => KeysSecPub;
declare const keygenAsync: (seed?: Bytes) => Promise<KeysSecPub>;
/** ed25519-specific key utilities. */
declare const utils: {
getExtendedPublicKeyAsync: typeof getExtendedPublicKeyAsync;
getExtendedPublicKey: typeof getExtendedPublicKey;
randomSecretKey: typeof randomSecretKey;
};
export { etc, getPublicKey, getPublicKeyAsync, hash, hashes, keygen, keygenAsync, Point, sign, signAsync, utils, verify, verifyAsync, };
+630
View File
@@ -0,0 +1,630 @@
/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
/**
* 5KB JS implementation of ed25519 EdDSA signatures.
* Compliant with RFC8032, FIPS 186-5 & ZIP215.
* @module
* @example
* ```js
import * as ed from '@noble/ed25519';
(async () => {
const secretKey = ed.utils.randomSecretKey();
const message = Uint8Array.from([0xab, 0xbc, 0xcd, 0xde]);
const pubKey = await ed.getPublicKeyAsync(secretKey); // Sync methods are also present
const signature = await ed.signAsync(message, secretKey);
const isValid = await ed.verifyAsync(signature, message, pubKey);
})();
```
*/
/**
* Curve params. ed25519 is twisted edwards curve. Equation is x² + y² = -a + dx²y².
* * P = `2n**255n - 19n` // field over which calculations are done
* * N = `2n**252n + 27742317777372353535851937790883648493n` // group order, amount of curve points
* * h = 8 // cofactor
* * a = `Fp.create(BigInt(-1))` // equation param
* * d = -121665/121666 a.k.a. `Fp.neg(121665 * Fp.inv(121666))` // equation param
* * Gx, Gy are coordinates of Generator / base point
*/
const ed25519_CURVE = {
p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,
h: 8n,
a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,
d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,
Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,
Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n,
};
const { p: P, n: N, Gx, Gy, a: _a, d: _d, h } = ed25519_CURVE;
const L = 32; // field / group byte length
const L2 = 64;
// Helpers and Precomputes sections are reused between libraries
// ## Helpers
// ----------
const captureTrace = (...args) => {
if ('captureStackTrace' in Error && typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(...args);
}
};
const err = (message = '') => {
const e = new Error(message);
captureTrace(e, err);
throw e;
};
const isBig = (n) => typeof n === 'bigint'; // is big integer
const isStr = (s) => typeof s === 'string'; // is string
const isBytes = (a) => a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
/** Asserts something is Uint8Array. */
const abytes = (value, length, title = '') => {
const bytes = isBytes(value);
const len = value?.length;
const needsLen = length !== undefined;
if (!bytes || (needsLen && len !== length)) {
const prefix = title && `"${title}" `;
const ofLen = needsLen ? ` of length ${length}` : '';
const got = bytes ? `length=${len}` : `type=${typeof value}`;
err(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
}
return value;
};
/** create Uint8Array */
const u8n = (len) => new Uint8Array(len);
const u8fr = (buf) => Uint8Array.from(buf);
const padh = (n, pad) => n.toString(16).padStart(pad, '0');
const bytesToHex = (b) => Array.from(abytes(b))
.map((e) => padh(e, 2))
.join('');
const C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; // ASCII characters
const _ch = (ch) => {
if (ch >= C._0 && ch <= C._9)
return ch - C._0; // '2' => 50-48
if (ch >= C.A && ch <= C.F)
return ch - (C.A - 10); // 'B' => 66-(65-10)
if (ch >= C.a && ch <= C.f)
return ch - (C.a - 10); // 'b' => 98-(97-10)
return;
};
const hexToBytes = (hex) => {
const e = 'hex invalid';
if (!isStr(hex))
return err(e);
const hl = hex.length;
const al = hl / 2;
if (hl % 2)
return err(e);
const array = u8n(al);
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
// treat each char as ASCII
const n1 = _ch(hex.charCodeAt(hi)); // parse first char, multiply it by 16
const n2 = _ch(hex.charCodeAt(hi + 1)); // parse second char
if (n1 === undefined || n2 === undefined)
return err(e);
array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9
}
return array;
};
const cr = () => globalThis?.crypto; // WebCrypto is available in all modern environments
const subtle = () => cr()?.subtle ?? err('crypto.subtle must be defined, consider polyfill');
// prettier-ignore
const concatBytes = (...arrs) => {
const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0)); // create u8a of summed length
let pad = 0; // walk through each array,
arrs.forEach(a => { r.set(a, pad); pad += a.length; }); // ensure they have proper type
return r;
};
/** WebCrypto OS-level CSPRNG (random number generator). Will throw when not available. */
const randomBytes = (len = L) => {
const c = cr();
return c.getRandomValues(u8n(len));
};
const big = BigInt;
const assertRange = (n, min, max, msg = 'bad number: out of range') => (isBig(n) && min <= n && n < max ? n : err(msg));
/** modular division */
const M = (a, b = P) => {
const r = a % b;
return r >= 0n ? r : b + r;
};
const modN = (a) => M(a, N);
/** Modular inversion using euclidean GCD (non-CT). No negative exponent for now. */
// prettier-ignore
const invert = (num, md) => {
if (num === 0n || md <= 0n)
err('no inverse n=' + num + ' mod=' + md);
let a = M(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;
while (a !== 0n) {
const q = b / a, r = b % a;
const m = x - u * q, n = y - v * q;
b = a, a = r, x = u, y = v, u = m, v = n;
}
return b === 1n ? M(x, md) : err('no inverse'); // b is gcd at this point
};
const callHash = (name) => {
// @ts-ignore
const fn = hashes[name];
if (typeof fn !== 'function')
err('hashes.' + name + ' not set');
return fn;
};
const hash = (msg) => callHash('sha512')(msg);
const apoint = (p) => (p instanceof Point ? p : err('Point expected'));
// ## End of Helpers
// -----------------
const B256 = 2n ** 256n;
/** Point in XYZT extended coordinates. */
class Point {
static BASE;
static ZERO;
X;
Y;
Z;
T;
constructor(X, Y, Z, T) {
const max = B256;
this.X = assertRange(X, 0n, max);
this.Y = assertRange(Y, 0n, max);
this.Z = assertRange(Z, 1n, max);
this.T = assertRange(T, 0n, max);
Object.freeze(this);
}
static CURVE() {
return ed25519_CURVE;
}
static fromAffine(p) {
return new Point(p.x, p.y, 1n, M(p.x * p.y));
}
/** RFC8032 5.1.3: Uint8Array to Point. */
static fromBytes(hex, zip215 = false) {
const d = _d;
// Copy array to not mess it up.
const normed = u8fr(abytes(hex, L));
// adjust first LE byte = last BE byte
const lastByte = hex[31];
normed[31] = lastByte & ~0x80;
const y = bytesToNumLE(normed);
// zip215=true: 0 <= y < 2^256
// zip215=false, RFC8032: 0 <= y < 2^255-19
const max = zip215 ? B256 : P;
assertRange(y, 0n, max);
const y2 = M(y * y); // y²
const u = M(y2 - 1n); // u=y²-1
const v = M(d * y2 + 1n); // v=dy²+1
let { isValid, value: x } = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root
if (!isValid)
err('bad point: y not sqrt'); // not square root: bad point
const isXOdd = (x & 1n) === 1n; // adjust sign of x coordinate
const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit
if (!zip215 && x === 0n && isLastByteOdd)
err('bad point: x==0, isLastByteOdd'); // x=0, x_0=1
if (isLastByteOdd !== isXOdd)
x = M(-x);
return new Point(x, y, 1n, M(x * y)); // Z=1, T=xy
}
static fromHex(hex, zip215) {
return Point.fromBytes(hexToBytes(hex), zip215);
}
get x() {
return this.toAffine().x;
}
get y() {
return this.toAffine().y;
}
/** Checks if the point is valid and on-curve. */
assertValidity() {
const a = _a;
const d = _d;
const p = this;
if (p.is0())
return err('bad point: ZERO'); // TODO: optimize, with vars below?
// Equation in affine coordinates: ax² + y² = 1 + dx²y²
// Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²
const { X, Y, Z, T } = p;
const X2 = M(X * X); // X²
const Y2 = M(Y * Y); // Y²
const Z2 = M(Z * Z); // Z²
const Z4 = M(Z2 * Z2); // Z⁴
const aX2 = M(X2 * a); // aX²
const left = M(Z2 * M(aX2 + Y2)); // (aX² + Y²)Z²
const right = M(Z4 + M(d * M(X2 * Y2))); // Z⁴ + dX²Y²
if (left !== right)
return err('bad point: equation left != right (1)');
// In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T
const XY = M(X * Y);
const ZT = M(Z * T);
if (XY !== ZT)
return err('bad point: equation left != right (2)');
return this;
}
/** Equality check: compare points P&Q. */
equals(other) {
const { X: X1, Y: Y1, Z: Z1 } = this;
const { X: X2, Y: Y2, Z: Z2 } = apoint(other); // checks class equality
const X1Z2 = M(X1 * Z2);
const X2Z1 = M(X2 * Z1);
const Y1Z2 = M(Y1 * Z2);
const Y2Z1 = M(Y2 * Z1);
return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
}
is0() {
return this.equals(I);
}
/** Flip point over y coordinate. */
negate() {
return new Point(M(-this.X), this.Y, this.Z, M(-this.T));
}
/** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */
double() {
const { X: X1, Y: Y1, Z: Z1 } = this;
const a = _a;
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
const A = M(X1 * X1);
const B = M(Y1 * Y1);
const C = M(2n * M(Z1 * Z1));
const D = M(a * A);
const x1y1 = X1 + Y1;
const E = M(M(x1y1 * x1y1) - A - B);
const G = D + B;
const F = G - C;
const H = D - B;
const X3 = M(E * F);
const Y3 = M(G * H);
const T3 = M(E * H);
const Z3 = M(F * G);
return new Point(X3, Y3, Z3, T3);
}
/** Point addition. Complete formula. Cost: `8M + 1*k + 8add + 1*2`. */
add(other) {
const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
const { X: X2, Y: Y2, Z: Z2, T: T2 } = apoint(other); // doesn't check if other on-curve
const a = _a;
const d = _d;
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-3
const A = M(X1 * X2);
const B = M(Y1 * Y2);
const C = M(T1 * d * T2);
const D = M(Z1 * Z2);
const E = M((X1 + Y1) * (X2 + Y2) - A - B);
const F = M(D - C);
const G = M(D + C);
const H = M(B - a * A);
const X3 = M(E * F);
const Y3 = M(G * H);
const T3 = M(E * H);
const Z3 = M(F * G);
return new Point(X3, Y3, Z3, T3);
}
subtract(other) {
return this.add(apoint(other).negate());
}
/**
* Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
* Uses {@link wNAF} for base point.
* Uses fake point to mitigate side-channel leakage.
* @param n scalar by which point is multiplied
* @param safe safe mode guards against timing attacks; unsafe mode is faster
*/
multiply(n, safe = true) {
if (!safe && (n === 0n || this.is0()))
return I;
assertRange(n, 1n, N);
if (n === 1n)
return this;
if (this.equals(G))
return wNAF(n).p;
// init result point & fake point
let p = I;
let f = G;
for (let d = this; n > 0n; d = d.double(), n >>= 1n) {
// if bit is present, add to point
// if not present, add to fake, for timing safety
if (n & 1n)
p = p.add(d);
else if (safe)
f = f.add(d);
}
return p;
}
multiplyUnsafe(scalar) {
return this.multiply(scalar, false);
}
/** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */
toAffine() {
const { X, Y, Z } = this;
// fast-paths for ZERO point OR Z=1
if (this.equals(I))
return { x: 0n, y: 1n };
const iz = invert(Z, P);
// (Z * Z^-1) must be 1, otherwise bad math
if (M(Z * iz) !== 1n)
err('invalid inverse');
// x = X*Z^-1; y = Y*Z^-1
const x = M(X * iz);
const y = M(Y * iz);
return { x, y };
}
toBytes() {
const { x, y } = this.assertValidity().toAffine();
const b = numTo32bLE(y);
// store sign in first LE byte
b[31] |= x & 1n ? 0x80 : 0;
return b;
}
toHex() {
return bytesToHex(this.toBytes());
}
clearCofactor() {
return this.multiply(big(h), false);
}
isSmallOrder() {
return this.clearCofactor().is0();
}
isTorsionFree() {
// Multiply by big number N. We can't `mul(N)` because of checks. Instead, we `mul(N/2)*2+1`
let p = this.multiply(N / 2n, false).double();
if (N % 2n)
p = p.add(this);
return p.is0();
}
}
/** Generator / base point */
const G = new Point(Gx, Gy, 1n, M(Gx * Gy));
/** Identity / zero point */
const I = new Point(0n, 1n, 1n, 0n);
// Static aliases
Point.BASE = G;
Point.ZERO = I;
const numTo32bLE = (num) => hexToBytes(padh(assertRange(num, 0n, B256), L2)).reverse();
const bytesToNumLE = (b) => big('0x' + bytesToHex(u8fr(abytes(b)).reverse()));
const pow2 = (x, power) => {
// pow2(x, 4) == x^(2^4)
let r = x;
while (power-- > 0n) {
r *= r;
r %= P;
}
return r;
};
// prettier-ignore
const pow_2_252_3 = (x) => {
const x2 = (x * x) % P; // x^2, bits 1
const b2 = (x2 * x) % P; // x^3, bits 11
const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111
const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111
const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)
const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)
const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)
const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)
const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)
const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)
const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)
const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.
return { pow_p_5_8, b2 };
};
const RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n; // √-1
// for sqrt comp
// prettier-ignore
const uvRatio = (u, v) => {
const v3 = M(v * v * v); // v³
const v7 = M(v3 * v3 * v); // v⁷
const pow = pow_2_252_3(u * v7).pow_p_5_8; // (uv⁷)^(p-5)/8
let x = M(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8
const vx2 = M(v * x * x); // vx²
const root1 = x; // First root candidate
const root2 = M(x * RM1); // Second root candidate; RM1 is √-1
const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root
const useRoot2 = vx2 === M(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)
const noRoot = vx2 === M(-u * RM1); // There is no valid root, vx² = -u√-1
if (useRoot1)
x = root1;
if (useRoot2 || noRoot)
x = root2; // We return root2 anyway, for const-time
if ((M(x) & 1n) === 1n)
x = M(-x); // edIsNegative
return { isValid: useRoot1 || useRoot2, value: x };
};
// N == L, just weird naming
const modL_LE = (hash) => modN(bytesToNumLE(hash)); // modulo L; but little-endian
/** hashes.sha512 should conform to the interface. */
// TODO: rename
const sha512a = (...m) => hashes.sha512Async(concatBytes(...m)); // Async SHA512
const sha512s = (...m) => callHash('sha512')(concatBytes(...m));
// RFC8032 5.1.5
const hash2extK = (hashed) => {
// slice creates a copy, unlike subarray
const head = hashed.slice(0, L);
head[0] &= 248; // Clamp bits: 0b1111_1000
head[31] &= 127; // 0b0111_1111
head[31] |= 64; // 0b0100_0000
const prefix = hashed.slice(L, L2); // secret key "prefix"
const scalar = modL_LE(head); // modular division over curve order
const point = G.multiply(scalar); // public key point
const pointBytes = point.toBytes(); // point serialized to Uint8Array
return { head, prefix, scalar, point, pointBytes };
};
// RFC8032 5.1.5; getPublicKey async, sync. Hash priv key and extract point.
const getExtendedPublicKeyAsync = (secretKey) => sha512a(abytes(secretKey, L)).then(hash2extK);
const getExtendedPublicKey = (secretKey) => hash2extK(sha512s(abytes(secretKey, L)));
/** Creates 32-byte ed25519 public key from 32-byte secret key. Async. */
const getPublicKeyAsync = (secretKey) => getExtendedPublicKeyAsync(secretKey).then((p) => p.pointBytes);
/** Creates 32-byte ed25519 public key from 32-byte secret key. To use, set `hashes.sha512` first. */
const getPublicKey = (priv) => getExtendedPublicKey(priv).pointBytes;
const hashFinishA = (res) => sha512a(res.hashable).then(res.finish);
const hashFinishS = (res) => res.finish(sha512s(res.hashable));
// Code, shared between sync & async sign
const _sign = (e, rBytes, msg) => {
const { pointBytes: P, scalar: s } = e;
const r = modL_LE(rBytes); // r was created outside, reduce it modulo L
const R = G.multiply(r).toBytes(); // R = [r]B
const hashable = concatBytes(R, P, msg); // dom2(F, C) || R || A || PH(M)
const finish = (hashed) => {
// k = SHA512(dom2(F, C) || R || A || PH(M))
const S = modN(r + modL_LE(hashed) * s); // S = (r + k * s) mod L; 0 <= s < l
return abytes(concatBytes(R, numTo32bLE(S)), L2); // 64-byte sig: 32b R.x + 32b LE(S)
};
return { hashable, finish };
};
/**
* Signs message using secret key. Async.
* Follows RFC8032 5.1.6.
*/
const signAsync = async (message, secretKey) => {
const m = abytes(message);
const e = await getExtendedPublicKeyAsync(secretKey);
const rBytes = await sha512a(e.prefix, m); // r = SHA512(dom2(F, C) || prefix || PH(M))
return hashFinishA(_sign(e, rBytes, m)); // gen R, k, S, then 64-byte signature
};
/**
* Signs message using secret key. To use, set `hashes.sha512` first.
* Follows RFC8032 5.1.6.
*/
const sign = (message, secretKey) => {
const m = abytes(message);
const e = getExtendedPublicKey(secretKey);
const rBytes = sha512s(e.prefix, m); // r = SHA512(dom2(F, C) || prefix || PH(M))
return hashFinishS(_sign(e, rBytes, m)); // gen R, k, S, then 64-byte signature
};
const defaultVerifyOpts = { zip215: true };
const _verify = (sig, msg, pub, opts = defaultVerifyOpts) => {
sig = abytes(sig, L2); // Signature hex str/Bytes, must be 64 bytes
msg = abytes(msg); // Message hex str/Bytes
pub = abytes(pub, L);
const { zip215 } = opts; // switch between zip215 and rfc8032 verif
let A;
let R;
let s;
let SB;
let hashable = Uint8Array.of();
try {
A = Point.fromBytes(pub, zip215); // public key A decoded
R = Point.fromBytes(sig.slice(0, L), zip215); // 0 <= R < 2^256: ZIP215 R can be >= P
s = bytesToNumLE(sig.slice(L, L2)); // Decode second half as an integer S
SB = G.multiply(s, false); // in the range 0 <= s < L
hashable = concatBytes(R.toBytes(), A.toBytes(), msg); // dom2(F, C) || R || A || PH(M)
}
catch (error) { }
const finish = (hashed) => {
// k = SHA512(dom2(F, C) || R || A || PH(M))
if (SB == null)
return false; // false if try-catch catched an error
if (!zip215 && A.isSmallOrder())
return false; // false for SBS: Strongly Binding Signature
const k = modL_LE(hashed); // decode in little-endian, modulo L
const RkA = R.add(A.multiply(k, false)); // [8]R + [8][k]A'
return RkA.add(SB.negate()).clearCofactor().is0(); // [8][S]B = [8]R + [8][k]A'
};
return { hashable, finish };
};
/** Verifies signature on message and public key. Async. Follows RFC8032 5.1.7. */
const verifyAsync = async (signature, message, publicKey, opts = defaultVerifyOpts) => hashFinishA(_verify(signature, message, publicKey, opts));
/** Verifies signature on message and public key. To use, set `hashes.sha512` first. Follows RFC8032 5.1.7. */
const verify = (signature, message, publicKey, opts = defaultVerifyOpts) => hashFinishS(_verify(signature, message, publicKey, opts));
/** Math, hex, byte helpers. Not in `utils` because utils share API with noble-curves. */
const etc = {
bytesToHex: bytesToHex,
hexToBytes: hexToBytes,
concatBytes: concatBytes,
mod: M,
invert: invert,
randomBytes: randomBytes,
};
const hashes = {
sha512Async: async (message) => {
const s = subtle();
const m = concatBytes(message);
return u8n(await s.digest('SHA-512', m.buffer));
},
sha512: undefined,
};
// FIPS 186 B.4.1 compliant key generation produces private keys
// with modulo bias being neglible. takes >N+16 bytes, returns (hash mod n-1)+1
const randomSecretKey = (seed = randomBytes(L)) => seed;
const keygen = (seed) => {
const secretKey = randomSecretKey(seed);
const publicKey = getPublicKey(secretKey);
return { secretKey, publicKey };
};
const keygenAsync = async (seed) => {
const secretKey = randomSecretKey(seed);
const publicKey = await getPublicKeyAsync(secretKey);
return { secretKey, publicKey };
};
/** ed25519-specific key utilities. */
const utils = {
getExtendedPublicKeyAsync: getExtendedPublicKeyAsync,
getExtendedPublicKey: getExtendedPublicKey,
randomSecretKey: randomSecretKey,
};
// ## Precomputes
// --------------
const W = 8; // W is window size
const scalarBits = 256;
const pwindows = Math.ceil(scalarBits / W) + 1; // 33 for W=8, NOT 32 - see wNAF loop
const pwindowSize = 2 ** (W - 1); // 128 for W=8
const precompute = () => {
const points = [];
let p = G;
let b = p;
for (let w = 0; w < pwindows; w++) {
b = p;
points.push(b);
for (let i = 1; i < pwindowSize; i++) {
b = b.add(p);
points.push(b);
} // i=1, bc we skip 0
p = b.double();
}
return points;
};
let Gpows = undefined; // precomputes for base point G
// const-time negate
const ctneg = (cnd, p) => {
const n = p.negate();
return cnd ? n : p;
};
/**
* Precomputes give 12x faster getPublicKey(), 10x sign(), 2x verify() by
* caching multiples of G (base point). Cache is stored in 32MB of RAM.
* Any time `G.multiply` is done, precomputes are used.
* Not used for getSharedSecret, which instead multiplies random pubkey `P.multiply`.
*
* w-ary non-adjacent form (wNAF) precomputation method is 10% slower than windowed method,
* but takes 2x less RAM. RAM reduction is possible by utilizing `.subtract`.
*
* !! Precomputes can be disabled by commenting-out call of the wNAF() inside Point#multiply().
*/
const wNAF = (n) => {
const comp = Gpows || (Gpows = precompute());
let p = I;
let f = G; // f must be G, or could become I in the end
const pow_2_w = 2 ** W; // 256 for W=8
const maxNum = pow_2_w; // 256 for W=8
const mask = big(pow_2_w - 1); // 255 for W=8 == mask 0b11111111
const shiftBy = big(W); // 8 for W=8
for (let w = 0; w < pwindows; w++) {
let wbits = Number(n & mask); // extract W bits.
n >>= shiftBy; // shift number by W bits.
// We use negative indexes to reduce size of precomputed table by 2x.
// Instead of needing precomputes 0..256, we only calculate them for 0..128.
// If an index > 128 is found, we do (256-index) - where 256 is next window.
// Naive: index +127 => 127, +224 => 224
// Optimized: index +127 => 127, +224 => 256-32
if (wbits > pwindowSize) {
wbits -= maxNum;
n += 1n;
}
const off = w * pwindowSize;
const offF = off; // offsets, evaluate both
const offP = off + Math.abs(wbits) - 1;
const isEven = w % 2 !== 0; // conditions, evaluate both
const isNeg = wbits < 0;
if (wbits === 0) {
// off == I: can't add it. Adding random offF instead.
f = f.add(ctneg(isEven, comp[offF])); // bits are 0: add garbage to fake point
}
else {
p = p.add(ctneg(isNeg, comp[offP])); // bits are 1: add to result point
}
}
if (n !== 0n)
err('invalid wnaf');
return { p, f }; // return both real and fake points for JIT
};
// !! Remove the export to easily use in REPL / browser console
export { etc, getPublicKey, getPublicKeyAsync, hash, hashes, keygen, keygenAsync, Point, sign, signAsync, utils, verify, verifyAsync, };
+685
View File
@@ -0,0 +1,685 @@
/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */
/**
* 5KB JS implementation of ed25519 EdDSA signatures.
* Compliant with RFC8032, FIPS 186-5 & ZIP215.
* @module
* @example
* ```js
import * as ed from '@noble/ed25519';
(async () => {
const secretKey = ed.utils.randomSecretKey();
const message = Uint8Array.from([0xab, 0xbc, 0xcd, 0xde]);
const pubKey = await ed.getPublicKeyAsync(secretKey); // Sync methods are also present
const signature = await ed.signAsync(message, secretKey);
const isValid = await ed.verifyAsync(signature, message, pubKey);
})();
```
*/
/**
* Curve params. ed25519 is twisted edwards curve. Equation is x² + y² = -a + dx²y².
* * P = `2n**255n - 19n` // field over which calculations are done
* * N = `2n**252n + 27742317777372353535851937790883648493n` // group order, amount of curve points
* * h = 8 // cofactor
* * a = `Fp.create(BigInt(-1))` // equation param
* * d = -121665/121666 a.k.a. `Fp.neg(121665 * Fp.inv(121666))` // equation param
* * Gx, Gy are coordinates of Generator / base point
*/
const ed25519_CURVE: EdwardsOpts = {
p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,
n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,
h: 8n,
a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,
d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,
Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,
Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n,
};
const { p: P, n: N, Gx, Gy, a: _a, d: _d, h } = ed25519_CURVE;
const L = 32; // field / group byte length
const L2 = 64;
/** Alias to Uint8Array. */
export type Bytes = Uint8Array;
/** Hex-encoded string or Uint8Array. */
/** Edwards elliptic curve options. */
export type EdwardsOpts = Readonly<{
p: bigint;
n: bigint;
h: bigint;
a: bigint;
d: bigint;
Gx: bigint;
Gy: bigint;
}>;
// Helpers and Precomputes sections are reused between libraries
// ## Helpers
// ----------
const captureTrace = (...args: Parameters<typeof Error.captureStackTrace>): void => {
if ('captureStackTrace' in Error && typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(...args);
}
};
const err = (message = ''): never => {
const e = new Error(message);
captureTrace(e, err);
throw e;
};
const isBig = (n: unknown): n is bigint => typeof n === 'bigint'; // is big integer
const isStr = (s: unknown): s is string => typeof s === 'string'; // is string
const isBytes = (a: unknown): a is Bytes =>
a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
/** Asserts something is Uint8Array. */
const abytes = (value: Bytes, length?: number, title: string = ''): Bytes => {
const bytes = isBytes(value);
const len = value?.length;
const needsLen = length !== undefined;
if (!bytes || (needsLen && len !== length)) {
const prefix = title && `"${title}" `;
const ofLen = needsLen ? ` of length ${length}` : '';
const got = bytes ? `length=${len}` : `type=${typeof value}`;
err(prefix + 'expected Uint8Array' + ofLen + ', got ' + got);
}
return value;
};
/** create Uint8Array */
const u8n = (len: number) => new Uint8Array(len);
const u8fr = (buf: ArrayLike<number>) => Uint8Array.from(buf);
const padh = (n: number | bigint, pad: number) => n.toString(16).padStart(pad, '0');
const bytesToHex = (b: Bytes): string =>
Array.from(abytes(b))
.map((e) => padh(e, 2))
.join('');
const C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 } as const; // ASCII characters
const _ch = (ch: number): number | undefined => {
if (ch >= C._0 && ch <= C._9) return ch - C._0; // '2' => 50-48
if (ch >= C.A && ch <= C.F) return ch - (C.A - 10); // 'B' => 66-(65-10)
if (ch >= C.a && ch <= C.f) return ch - (C.a - 10); // 'b' => 98-(97-10)
return;
};
const hexToBytes = (hex: string): Bytes => {
const e = 'hex invalid';
if (!isStr(hex)) return err(e);
const hl = hex.length;
const al = hl / 2;
if (hl % 2) return err(e);
const array = u8n(al);
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
// treat each char as ASCII
const n1 = _ch(hex.charCodeAt(hi)); // parse first char, multiply it by 16
const n2 = _ch(hex.charCodeAt(hi + 1)); // parse second char
if (n1 === undefined || n2 === undefined) return err(e);
array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9
}
return array;
};
declare const globalThis: Record<string, any> | undefined; // Typescript symbol present in browsers
const cr = () => globalThis?.crypto; // WebCrypto is available in all modern environments
const subtle = () => cr()?.subtle ?? err('crypto.subtle must be defined, consider polyfill');
// prettier-ignore
const concatBytes = (...arrs: Bytes[]): Bytes => {
const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0)); // create u8a of summed length
let pad = 0; // walk through each array,
arrs.forEach(a => { r.set(a, pad); pad += a.length; }); // ensure they have proper type
return r;
};
/** WebCrypto OS-level CSPRNG (random number generator). Will throw when not available. */
const randomBytes = (len: number = L): Bytes => {
const c = cr();
return c.getRandomValues(u8n(len));
};
const big = BigInt;
const assertRange = (
n: bigint,
min: bigint,
max: bigint,
msg = 'bad number: out of range'
): bigint => (isBig(n) && min <= n && n < max ? n : err(msg));
/** modular division */
const M = (a: bigint, b: bigint = P): bigint => {
const r = a % b;
return r >= 0n ? r : b + r;
};
const modN = (a: bigint) => M(a, N);
/** Modular inversion using euclidean GCD (non-CT). No negative exponent for now. */
// prettier-ignore
const invert = (num: bigint, md: bigint): bigint => {
if (num === 0n || md <= 0n) err('no inverse n=' + num + ' mod=' + md);
let a = M(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;
while (a !== 0n) {
const q = b / a, r = b % a;
const m = x - u * q, n = y - v * q;
b = a, a = r, x = u, y = v, u = m, v = n;
}
return b === 1n ? M(x, md) : err('no inverse'); // b is gcd at this point
};
const callHash = (name: string) => {
// @ts-ignore
const fn = hashes[name];
if (typeof fn !== 'function') err('hashes.' + name + ' not set');
return fn;
};
const hash = (msg: Bytes): Bytes => callHash('sha512')(msg);
const apoint = (p: unknown) => (p instanceof Point ? p : err('Point expected'));
/** Point in 2d xy affine coordinates. */
export type AffinePoint = {
x: bigint;
y: bigint;
};
// ## End of Helpers
// -----------------
const B256 = 2n ** 256n;
/** Point in XYZT extended coordinates. */
class Point {
static BASE: Point;
static ZERO: Point;
readonly X: bigint;
readonly Y: bigint;
readonly Z: bigint;
readonly T: bigint;
constructor(X: bigint, Y: bigint, Z: bigint, T: bigint) {
const max = B256;
this.X = assertRange(X, 0n, max);
this.Y = assertRange(Y, 0n, max);
this.Z = assertRange(Z, 1n, max);
this.T = assertRange(T, 0n, max);
Object.freeze(this);
}
static CURVE(): EdwardsOpts {
return ed25519_CURVE;
}
static fromAffine(p: AffinePoint): Point {
return new Point(p.x, p.y, 1n, M(p.x * p.y));
}
/** RFC8032 5.1.3: Uint8Array to Point. */
static fromBytes(hex: Bytes, zip215 = false): Point {
const d = _d;
// Copy array to not mess it up.
const normed = u8fr(abytes(hex, L));
// adjust first LE byte = last BE byte
const lastByte = hex[31];
normed[31] = lastByte & ~0x80;
const y = bytesToNumLE(normed);
// zip215=true: 0 <= y < 2^256
// zip215=false, RFC8032: 0 <= y < 2^255-19
const max = zip215 ? B256 : P;
assertRange(y, 0n, max);
const y2 = M(y * y); // y²
const u = M(y2 - 1n); // u=y²-1
const v = M(d * y2 + 1n); // v=dy²+1
let { isValid, value: x } = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root
if (!isValid) err('bad point: y not sqrt'); // not square root: bad point
const isXOdd = (x & 1n) === 1n; // adjust sign of x coordinate
const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit
if (!zip215 && x === 0n && isLastByteOdd) err('bad point: x==0, isLastByteOdd'); // x=0, x_0=1
if (isLastByteOdd !== isXOdd) x = M(-x);
return new Point(x, y, 1n, M(x * y)); // Z=1, T=xy
}
static fromHex(hex: string, zip215?: boolean): Point {
return Point.fromBytes(hexToBytes(hex), zip215);
}
get x(): bigint {
return this.toAffine().x;
}
get y(): bigint {
return this.toAffine().y;
}
/** Checks if the point is valid and on-curve. */
assertValidity(): this {
const a = _a;
const d = _d;
const p = this;
if (p.is0()) return err('bad point: ZERO'); // TODO: optimize, with vars below?
// Equation in affine coordinates: ax² + y² = 1 + dx²y²
// Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²
const { X, Y, Z, T } = p;
const X2 = M(X * X); // X²
const Y2 = M(Y * Y); // Y²
const Z2 = M(Z * Z); // Z²
const Z4 = M(Z2 * Z2); // Z⁴
const aX2 = M(X2 * a); // aX²
const left = M(Z2 * M(aX2 + Y2)); // (aX² + Y²)Z²
const right = M(Z4 + M(d * M(X2 * Y2))); // Z⁴ + dX²Y²
if (left !== right) return err('bad point: equation left != right (1)');
// In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T
const XY = M(X * Y);
const ZT = M(Z * T);
if (XY !== ZT) return err('bad point: equation left != right (2)');
return this;
}
/** Equality check: compare points P&Q. */
equals(other: Point): boolean {
const { X: X1, Y: Y1, Z: Z1 } = this;
const { X: X2, Y: Y2, Z: Z2 } = apoint(other); // checks class equality
const X1Z2 = M(X1 * Z2);
const X2Z1 = M(X2 * Z1);
const Y1Z2 = M(Y1 * Z2);
const Y2Z1 = M(Y2 * Z1);
return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
}
is0(): boolean {
return this.equals(I);
}
/** Flip point over y coordinate. */
negate(): Point {
return new Point(M(-this.X), this.Y, this.Z, M(-this.T));
}
/** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */
double(): Point {
const { X: X1, Y: Y1, Z: Z1 } = this;
const a = _a;
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd
const A = M(X1 * X1);
const B = M(Y1 * Y1);
const C = M(2n * M(Z1 * Z1));
const D = M(a * A);
const x1y1 = X1 + Y1;
const E = M(M(x1y1 * x1y1) - A - B);
const G = D + B;
const F = G - C;
const H = D - B;
const X3 = M(E * F);
const Y3 = M(G * H);
const T3 = M(E * H);
const Z3 = M(F * G);
return new Point(X3, Y3, Z3, T3);
}
/** Point addition. Complete formula. Cost: `8M + 1*k + 8add + 1*2`. */
add(other: Point): Point {
const { X: X1, Y: Y1, Z: Z1, T: T1 } = this;
const { X: X2, Y: Y2, Z: Z2, T: T2 } = apoint(other); // doesn't check if other on-curve
const a = _a;
const d = _d;
// https://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-3
const A = M(X1 * X2);
const B = M(Y1 * Y2);
const C = M(T1 * d * T2);
const D = M(Z1 * Z2);
const E = M((X1 + Y1) * (X2 + Y2) - A - B);
const F = M(D - C);
const G = M(D + C);
const H = M(B - a * A);
const X3 = M(E * F);
const Y3 = M(G * H);
const T3 = M(E * H);
const Z3 = M(F * G);
return new Point(X3, Y3, Z3, T3);
}
subtract(other: Point): Point {
return this.add(apoint(other).negate());
}
/**
* Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.
* Uses {@link wNAF} for base point.
* Uses fake point to mitigate side-channel leakage.
* @param n scalar by which point is multiplied
* @param safe safe mode guards against timing attacks; unsafe mode is faster
*/
multiply(n: bigint, safe = true): Point {
if (!safe && (n === 0n || this.is0())) return I;
assertRange(n, 1n, N);
if (n === 1n) return this;
if (this.equals(G)) return wNAF(n).p;
// init result point & fake point
let p = I;
let f = G;
for (let d: Point = this; n > 0n; d = d.double(), n >>= 1n) {
// if bit is present, add to point
// if not present, add to fake, for timing safety
if (n & 1n) p = p.add(d);
else if (safe) f = f.add(d);
}
return p;
}
multiplyUnsafe(scalar: bigint): Point {
return this.multiply(scalar, false);
}
/** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */
toAffine(): AffinePoint {
const { X, Y, Z } = this;
// fast-paths for ZERO point OR Z=1
if (this.equals(I)) return { x: 0n, y: 1n };
const iz = invert(Z, P);
// (Z * Z^-1) must be 1, otherwise bad math
if (M(Z * iz) !== 1n) err('invalid inverse');
// x = X*Z^-1; y = Y*Z^-1
const x = M(X * iz);
const y = M(Y * iz);
return { x, y };
}
toBytes(): Bytes {
const { x, y } = this.assertValidity().toAffine();
const b = numTo32bLE(y);
// store sign in first LE byte
b[31] |= x & 1n ? 0x80 : 0;
return b;
}
toHex(): string {
return bytesToHex(this.toBytes());
}
clearCofactor(): Point {
return this.multiply(big(h), false);
}
isSmallOrder(): boolean {
return this.clearCofactor().is0();
}
isTorsionFree(): boolean {
// Multiply by big number N. We can't `mul(N)` because of checks. Instead, we `mul(N/2)*2+1`
let p = this.multiply(N / 2n, false).double();
if (N % 2n) p = p.add(this);
return p.is0();
}
}
/** Generator / base point */
const G: Point = new Point(Gx, Gy, 1n, M(Gx * Gy));
/** Identity / zero point */
const I: Point = new Point(0n, 1n, 1n, 0n);
// Static aliases
Point.BASE = G;
Point.ZERO = I;
const numTo32bLE = (num: bigint) => hexToBytes(padh(assertRange(num, 0n, B256), L2)).reverse();
const bytesToNumLE = (b: Bytes): bigint => big('0x' + bytesToHex(u8fr(abytes(b)).reverse()));
const pow2 = (x: bigint, power: bigint): bigint => {
// pow2(x, 4) == x^(2^4)
let r = x;
while (power-- > 0n) {
r *= r;
r %= P;
}
return r;
};
// prettier-ignore
const pow_2_252_3 = (x: bigint) => { // x^(2^252-3) unrolled util for square root
const x2 = (x * x) % P; // x^2, bits 1
const b2 = (x2 * x) % P; // x^3, bits 11
const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111
const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111
const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)
const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)
const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)
const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)
const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)
const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)
const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)
const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.
return { pow_p_5_8, b2 };
}
const RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n; // √-1
// for sqrt comp
// prettier-ignore
const uvRatio = (u: bigint, v: bigint): { isValid: boolean, value: bigint } => {
const v3 = M(v * v * v); // v³
const v7 = M(v3 * v3 * v); // v⁷
const pow = pow_2_252_3(u * v7).pow_p_5_8; // (uv⁷)^(p-5)/8
let x = M(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8
const vx2 = M(v * x * x); // vx²
const root1 = x; // First root candidate
const root2 = M(x * RM1); // Second root candidate; RM1 is √-1
const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root
const useRoot2 = vx2 === M(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)
const noRoot = vx2 === M(-u * RM1); // There is no valid root, vx² = -u√-1
if (useRoot1) x = root1;
if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time
if ((M(x) & 1n) === 1n) x = M(-x); // edIsNegative
return { isValid: useRoot1 || useRoot2, value: x };
}
// N == L, just weird naming
const modL_LE = (hash: Bytes): bigint => modN(bytesToNumLE(hash)); // modulo L; but little-endian
/** hashes.sha512 should conform to the interface. */
// TODO: rename
const sha512a = (...m: Bytes[]) => hashes.sha512Async(concatBytes(...m)); // Async SHA512
const sha512s = (...m: Bytes[]) => callHash('sha512')(concatBytes(...m));
type ExtK = { head: Bytes; prefix: Bytes; scalar: bigint; point: Point; pointBytes: Bytes };
// RFC8032 5.1.5
const hash2extK = (hashed: Bytes): ExtK => {
// slice creates a copy, unlike subarray
const head = hashed.slice(0, L);
head[0] &= 248; // Clamp bits: 0b1111_1000
head[31] &= 127; // 0b0111_1111
head[31] |= 64; // 0b0100_0000
const prefix = hashed.slice(L, L2); // secret key "prefix"
const scalar = modL_LE(head); // modular division over curve order
const point = G.multiply(scalar); // public key point
const pointBytes = point.toBytes(); // point serialized to Uint8Array
return { head, prefix, scalar, point, pointBytes };
};
// RFC8032 5.1.5; getPublicKey async, sync. Hash priv key and extract point.
const getExtendedPublicKeyAsync = (secretKey: Bytes): Promise<ExtK> =>
sha512a(abytes(secretKey, L)).then(hash2extK);
const getExtendedPublicKey = (secretKey: Bytes): ExtK => hash2extK(sha512s(abytes(secretKey, L)));
/** Creates 32-byte ed25519 public key from 32-byte secret key. Async. */
const getPublicKeyAsync = (secretKey: Bytes): Promise<Bytes> =>
getExtendedPublicKeyAsync(secretKey).then((p) => p.pointBytes);
/** Creates 32-byte ed25519 public key from 32-byte secret key. To use, set `hashes.sha512` first. */
const getPublicKey = (priv: Bytes): Bytes => getExtendedPublicKey(priv).pointBytes;
type Finishable<T> = {
// Reduces logic duplication between
hashable: Bytes;
finish: (hashed: Bytes) => T; // sync & async versions of sign(), verify()
};
const hashFinishA = <T>(res: Finishable<T>): Promise<T> => sha512a(res.hashable).then(res.finish);
const hashFinishS = <T>(res: Finishable<T>): T => res.finish(sha512s(res.hashable));
// Code, shared between sync & async sign
const _sign = (e: ExtK, rBytes: Bytes, msg: Bytes): Finishable<Bytes> => {
const { pointBytes: P, scalar: s } = e;
const r = modL_LE(rBytes); // r was created outside, reduce it modulo L
const R = G.multiply(r).toBytes(); // R = [r]B
const hashable = concatBytes(R, P, msg); // dom2(F, C) || R || A || PH(M)
const finish = (hashed: Bytes): Bytes => {
// k = SHA512(dom2(F, C) || R || A || PH(M))
const S = modN(r + modL_LE(hashed) * s); // S = (r + k * s) mod L; 0 <= s < l
return abytes(concatBytes(R, numTo32bLE(S)), L2); // 64-byte sig: 32b R.x + 32b LE(S)
};
return { hashable, finish };
};
/**
* Signs message using secret key. Async.
* Follows RFC8032 5.1.6.
*/
const signAsync = async (message: Bytes, secretKey: Bytes): Promise<Bytes> => {
const m = abytes(message);
const e = await getExtendedPublicKeyAsync(secretKey);
const rBytes = await sha512a(e.prefix, m); // r = SHA512(dom2(F, C) || prefix || PH(M))
return hashFinishA(_sign(e, rBytes, m)); // gen R, k, S, then 64-byte signature
};
/**
* Signs message using secret key. To use, set `hashes.sha512` first.
* Follows RFC8032 5.1.6.
*/
const sign = (message: Bytes, secretKey: Bytes): Bytes => {
const m = abytes(message);
const e = getExtendedPublicKey(secretKey);
const rBytes = sha512s(e.prefix, m); // r = SHA512(dom2(F, C) || prefix || PH(M))
return hashFinishS(_sign(e, rBytes, m)); // gen R, k, S, then 64-byte signature
};
/** Verification options. zip215: true (default) follows ZIP215 spec. false would follow RFC8032. */
export type EdDSAVerifyOpts = { zip215?: boolean };
const defaultVerifyOpts: EdDSAVerifyOpts = { zip215: true };
const _verify = (
sig: Bytes,
msg: Bytes,
pub: Bytes,
opts: EdDSAVerifyOpts = defaultVerifyOpts
): Finishable<boolean> => {
sig = abytes(sig, L2); // Signature hex str/Bytes, must be 64 bytes
msg = abytes(msg); // Message hex str/Bytes
pub = abytes(pub, L);
const { zip215 } = opts; // switch between zip215 and rfc8032 verif
let A: Point;
let R: Point;
let s: bigint;
let SB: Point;
let hashable: Bytes = Uint8Array.of();
try {
A = Point.fromBytes(pub, zip215); // public key A decoded
R = Point.fromBytes(sig.slice(0, L), zip215); // 0 <= R < 2^256: ZIP215 R can be >= P
s = bytesToNumLE(sig.slice(L, L2)); // Decode second half as an integer S
SB = G.multiply(s, false); // in the range 0 <= s < L
hashable = concatBytes(R.toBytes(), A.toBytes(), msg); // dom2(F, C) || R || A || PH(M)
} catch (error) {}
const finish = (hashed: Bytes): boolean => {
// k = SHA512(dom2(F, C) || R || A || PH(M))
if (SB == null) return false; // false if try-catch catched an error
if (!zip215 && A.isSmallOrder()) return false; // false for SBS: Strongly Binding Signature
const k = modL_LE(hashed); // decode in little-endian, modulo L
const RkA = R.add(A.multiply(k, false)); // [8]R + [8][k]A'
return RkA.add(SB.negate()).clearCofactor().is0(); // [8][S]B = [8]R + [8][k]A'
};
return { hashable, finish };
};
/** Verifies signature on message and public key. Async. Follows RFC8032 5.1.7. */
const verifyAsync = async (
signature: Bytes,
message: Bytes,
publicKey: Bytes,
opts: EdDSAVerifyOpts = defaultVerifyOpts
): Promise<boolean> => hashFinishA(_verify(signature, message, publicKey, opts));
/** Verifies signature on message and public key. To use, set `hashes.sha512` first. Follows RFC8032 5.1.7. */
const verify = (
signature: Bytes,
message: Bytes,
publicKey: Bytes,
opts: EdDSAVerifyOpts = defaultVerifyOpts
): boolean => hashFinishS(_verify(signature, message, publicKey, opts));
/** Math, hex, byte helpers. Not in `utils` because utils share API with noble-curves. */
const etc = {
bytesToHex: bytesToHex as typeof bytesToHex,
hexToBytes: hexToBytes as typeof hexToBytes,
concatBytes: concatBytes as typeof concatBytes,
mod: M as typeof M,
invert: invert as typeof invert,
randomBytes: randomBytes as typeof randomBytes,
};
const hashes = {
sha512Async: async (message: Bytes): Promise<Bytes> => {
const s = subtle();
const m = concatBytes(message);
return u8n(await s.digest('SHA-512', m.buffer));
},
sha512: undefined as undefined | ((message: Bytes) => Bytes),
};
// FIPS 186 B.4.1 compliant key generation produces private keys
// with modulo bias being neglible. takes >N+16 bytes, returns (hash mod n-1)+1
const randomSecretKey = (seed: Bytes = randomBytes(L)): Bytes => seed;
type KeysSecPub = { secretKey: Bytes; publicKey: Bytes };
const keygen = (seed?: Bytes): KeysSecPub => {
const secretKey = randomSecretKey(seed);
const publicKey = getPublicKey(secretKey);
return { secretKey, publicKey };
};
const keygenAsync = async (seed?: Bytes): Promise<KeysSecPub> => {
const secretKey = randomSecretKey(seed);
const publicKey = await getPublicKeyAsync(secretKey);
return { secretKey, publicKey };
};
/** ed25519-specific key utilities. */
const utils = {
getExtendedPublicKeyAsync: getExtendedPublicKeyAsync as typeof getExtendedPublicKeyAsync,
getExtendedPublicKey: getExtendedPublicKey as typeof getExtendedPublicKey,
randomSecretKey: randomSecretKey as typeof randomSecretKey,
};
// ## Precomputes
// --------------
const W = 8; // W is window size
const scalarBits = 256;
const pwindows = Math.ceil(scalarBits / W) + 1; // 33 for W=8, NOT 32 - see wNAF loop
const pwindowSize = 2 ** (W - 1); // 128 for W=8
const precompute = () => {
const points: Point[] = [];
let p = G;
let b = p;
for (let w = 0; w < pwindows; w++) {
b = p;
points.push(b);
for (let i = 1; i < pwindowSize; i++) {
b = b.add(p);
points.push(b);
} // i=1, bc we skip 0
p = b.double();
}
return points;
};
let Gpows: Point[] | undefined = undefined; // precomputes for base point G
// const-time negate
const ctneg = (cnd: boolean, p: Point) => {
const n = p.negate();
return cnd ? n : p;
};
/**
* Precomputes give 12x faster getPublicKey(), 10x sign(), 2x verify() by
* caching multiples of G (base point). Cache is stored in 32MB of RAM.
* Any time `G.multiply` is done, precomputes are used.
* Not used for getSharedSecret, which instead multiplies random pubkey `P.multiply`.
*
* w-ary non-adjacent form (wNAF) precomputation method is 10% slower than windowed method,
* but takes 2x less RAM. RAM reduction is possible by utilizing `.subtract`.
*
* !! Precomputes can be disabled by commenting-out call of the wNAF() inside Point#multiply().
*/
const wNAF = (n: bigint): { p: Point; f: Point } => {
const comp = Gpows || (Gpows = precompute());
let p = I;
let f = G; // f must be G, or could become I in the end
const pow_2_w = 2 ** W; // 256 for W=8
const maxNum = pow_2_w; // 256 for W=8
const mask = big(pow_2_w - 1); // 255 for W=8 == mask 0b11111111
const shiftBy = big(W); // 8 for W=8
for (let w = 0; w < pwindows; w++) {
let wbits = Number(n & mask); // extract W bits.
n >>= shiftBy; // shift number by W bits.
// We use negative indexes to reduce size of precomputed table by 2x.
// Instead of needing precomputes 0..256, we only calculate them for 0..128.
// If an index > 128 is found, we do (256-index) - where 256 is next window.
// Naive: index +127 => 127, +224 => 224
// Optimized: index +127 => 127, +224 => 256-32
if (wbits > pwindowSize) {
wbits -= maxNum;
n += 1n;
}
const off = w * pwindowSize;
const offF = off; // offsets, evaluate both
const offP = off + Math.abs(wbits) - 1;
const isEven = w % 2 !== 0; // conditions, evaluate both
const isNeg = wbits < 0;
if (wbits === 0) {
// off == I: can't add it. Adding random offF instead.
f = f.add(ctneg(isEven, comp[offF])); // bits are 0: add garbage to fake point
} else {
p = p.add(ctneg(isNeg, comp[offP])); // bits are 1: add to result point
}
}
if (n !== 0n) err('invalid wnaf');
return { p, f }; // return both real and fake points for JIT
};
// !! Remove the export to easily use in REPL / browser console
export {
etc,
getPublicKey,
getPublicKeyAsync,
hash,
hashes,
keygen,
keygenAsync,
Point,
sign,
signAsync,
utils,
verify,
verifyAsync,
};
+55
View File
@@ -0,0 +1,55 @@
{
"name": "@noble/ed25519",
"version": "3.0.0",
"description": "Fastest 5KB JS implementation of ed25519 EDDSA signatures compliant with RFC8032, FIPS 186-5 & ZIP215",
"files": [
"index.js",
"index.d.ts",
"index.ts"
],
"devDependencies": {
"@noble/hashes": "2.0.0",
"@paulmillr/jsbt": "0.4.4",
"@types/node": "24.2.1",
"fast-check": "4.2.0",
"prettier": "3.6.2",
"typescript": "5.9.2"
},
"scripts": {
"build": "tsc",
"build:release": "npx --no @paulmillr/jsbt esbuild test/build",
"bench": "node test/benchmark.ts",
"format": "prettier --write 'index.ts' 'test/**/*.{js,ts}'",
"test": "node --experimental-strip-types --disable-warning=ExperimentalWarning test/index.ts",
"test:bun": "bun test/index.ts",
"test:deno": "deno --allow-env --allow-read test/index.ts",
"test:node20": "cd test; npx tsc; node compiled/test/index.js"
},
"keywords": [
"ed25519",
"rfc8032",
"fips186",
"signature",
"eddsa",
"noble",
"cryptography",
"elliptic curve",
"rfc7748",
"zip215",
"x25519",
"curve25519"
],
"homepage": "https://paulmillr.com/noble/",
"funding": "https://paulmillr.com/funding/",
"repository": {
"type": "git",
"url": "git+https://github.com/paulmillr/noble-ed25519.git"
},
"type": "module",
"main": "index.js",
"module": "index.js",
"types": "index.d.ts",
"sideEffects": false,
"author": "Paul Miller (https://paulmillr.com)",
"license": "MIT"
}
+55
View File
@@ -0,0 +1,55 @@
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:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
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
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
+50
View File
@@ -0,0 +1,50 @@
# TypeScript
[![CI](https://github.com/microsoft/TypeScript/actions/workflows/ci.yml/badge.svg)](https://github.com/microsoft/TypeScript/actions/workflows/ci.yml)
[![npm version](https://badge.fury.io/js/typescript.svg)](https://www.npmjs.com/package/typescript)
[![Downloads](https://img.shields.io/npm/dm/typescript.svg)](https://www.npmjs.com/package/typescript)
[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/microsoft/TypeScript/badge)](https://securityscorecards.dev/viewer/?uri=github.com/microsoft/TypeScript)
[TypeScript](https://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types to JavaScript that support tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](https://www.typescriptlang.org/play/), and stay up to date via [our blog](https://blogs.msdn.microsoft.com/typescript) and [Twitter account](https://twitter.com/typescript).
Find others who are using TypeScript at [our community page](https://www.typescriptlang.org/community/).
## Installing
For the latest stable version:
```bash
npm install -D typescript
```
For our nightly builds:
```bash
npm install -D typescript@next
```
## Contribute
There are many ways to [contribute](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md) to TypeScript.
* [Submit bugs](https://github.com/microsoft/TypeScript/issues) and help us verify fixes as they are checked in.
* Review the [source code changes](https://github.com/microsoft/TypeScript/pulls).
* Engage with other TypeScript users and developers on [StackOverflow](https://stackoverflow.com/questions/tagged/typescript).
* Help each other in the [TypeScript Community Discord](https://discord.gg/typescript).
* Join the [#typescript](https://twitter.com/search?q=%23TypeScript) discussion on Twitter.
* [Contribute bug fixes](https://github.com/microsoft/TypeScript/blob/main/CONTRIBUTING.md).
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see
the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com)
with any additional questions or comments.
## Documentation
* [TypeScript in 5 minutes](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html)
* [Programming handbook](https://www.typescriptlang.org/docs/handbook/intro.html)
* [Homepage](https://www.typescriptlang.org/)
## Roadmap
For details on our planned features and future direction, please refer to our [roadmap](https://github.com/microsoft/TypeScript/wiki/Roadmap).
+41
View File
@@ -0,0 +1,41 @@
<!-- BEGIN MICROSOFT SECURITY.MD V0.0.9 BLOCK -->
## Security
Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet) and [Xamarin](https://github.com/xamarin).
If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/security.md/definition), please report it to us as described below.
## Reporting Security Issues
**Please do not report security vulnerabilities through public GitHub issues.**
Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report).
If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/security.md/msrc/pgp).
You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc).
Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
* Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
* Full paths of source file(s) related to the manifestation of the issue
* The location of the affected source code (tag/branch/commit or direct URL)
* Any special configuration required to reproduce the issue
* Step-by-step instructions to reproduce the issue
* Proof-of-concept or exploit code (if possible)
* Impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly.
If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/security.md/msrc/bounty) page for more details about our active programs.
## Preferred Languages
We prefer all communications to be in English.
## Policy
Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/security.md/cvd).
<!-- END MICROSOFT SECURITY.MD BLOCK -->
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env node
require('../lib/tsc.js')
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env node
require('../lib/tsserver.js')
File diff suppressed because one or more lines are too long
+659
View File
@@ -0,0 +1,659 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// src/tsserver/server.ts
var import_os2 = __toESM(require("os"));
// src/typescript/typescript.ts
var typescript_exports = {};
__reExport(typescript_exports, require("./typescript.js"));
// src/tsserver/nodeServer.ts
var import_child_process = __toESM(require("child_process"));
var import_fs = __toESM(require("fs"));
var import_net = __toESM(require("net"));
var import_os = __toESM(require("os"));
var import_readline = __toESM(require("readline"));
// src/tsserver/common.ts
function getLogLevel(level) {
if (level) {
const l = level.toLowerCase();
for (const name in typescript_exports.server.LogLevel) {
if (isNaN(+name) && l === name.toLowerCase()) {
return typescript_exports.server.LogLevel[name];
}
}
}
return void 0;
}
// src/tsserver/nodeServer.ts
function parseLoggingEnvironmentString(logEnvStr) {
if (!logEnvStr) {
return {};
}
const logEnv = { logToFile: true };
const args = logEnvStr.split(" ");
const len = args.length - 1;
for (let i = 0; i < len; i += 2) {
const option = args[i];
const { value, extraPartCounter } = getEntireValue(i + 1);
i += extraPartCounter;
if (option && value) {
switch (option) {
case "-file":
logEnv.file = value;
break;
case "-level":
const level = getLogLevel(value);
logEnv.detailLevel = level !== void 0 ? level : typescript_exports.server.LogLevel.normal;
break;
case "-traceToConsole":
logEnv.traceToConsole = value.toLowerCase() === "true";
break;
case "-logToFile":
logEnv.logToFile = value.toLowerCase() === "true";
break;
}
}
}
return logEnv;
function getEntireValue(initialIndex) {
let pathStart = args[initialIndex];
let extraPartCounter = 0;
if (pathStart.charCodeAt(0) === typescript_exports.CharacterCodes.doubleQuote && pathStart.charCodeAt(pathStart.length - 1) !== typescript_exports.CharacterCodes.doubleQuote) {
for (let i = initialIndex + 1; i < args.length; i++) {
pathStart += " ";
pathStart += args[i];
extraPartCounter++;
if (pathStart.charCodeAt(pathStart.length - 1) === typescript_exports.CharacterCodes.doubleQuote) break;
}
}
return { value: (0, typescript_exports.stripQuotes)(pathStart), extraPartCounter };
}
}
function parseServerMode() {
const mode = typescript_exports.server.findArgument("--serverMode");
if (!mode) return void 0;
switch (mode.toLowerCase()) {
case "semantic":
return typescript_exports.LanguageServiceMode.Semantic;
case "partialsemantic":
return typescript_exports.LanguageServiceMode.PartialSemantic;
case "syntactic":
return typescript_exports.LanguageServiceMode.Syntactic;
default:
return mode;
}
}
function initializeNodeSystem() {
const sys4 = typescript_exports.Debug.checkDefined(typescript_exports.sys);
class Logger {
constructor(logFilename, traceToConsole, level) {
this.logFilename = logFilename;
this.traceToConsole = traceToConsole;
this.level = level;
this.seq = 0;
this.inGroup = false;
this.firstInGroup = true;
this.fd = -1;
if (this.logFilename) {
try {
this.fd = import_fs.default.openSync(this.logFilename, "w");
} catch {
}
}
}
static padStringRight(str, padding) {
return (str + padding).slice(0, padding.length);
}
close() {
if (this.fd >= 0) {
import_fs.default.close(this.fd, typescript_exports.noop);
}
}
getLogFileName() {
return this.logFilename;
}
perftrc(s) {
this.msg(s, typescript_exports.server.Msg.Perf);
}
info(s) {
this.msg(s, typescript_exports.server.Msg.Info);
}
err(s) {
this.msg(s, typescript_exports.server.Msg.Err);
}
startGroup() {
this.inGroup = true;
this.firstInGroup = true;
}
endGroup() {
this.inGroup = false;
}
loggingEnabled() {
return !!this.logFilename || this.traceToConsole;
}
hasLevel(level) {
return this.loggingEnabled() && this.level >= level;
}
msg(s, type = typescript_exports.server.Msg.Err) {
if (!this.canWrite()) return;
s = `[${typescript_exports.server.nowString()}] ${s}
`;
if (!this.inGroup || this.firstInGroup) {
const prefix = Logger.padStringRight(type + " " + this.seq.toString(), " ");
s = prefix + s;
}
this.write(s, type);
if (!this.inGroup) {
this.seq++;
}
}
canWrite() {
return this.fd >= 0 || this.traceToConsole;
}
write(s, _type) {
if (this.fd >= 0) {
const buf = Buffer.from(s);
import_fs.default.writeSync(
this.fd,
buf,
0,
buf.length,
/*position*/
null
);
}
if (this.traceToConsole) {
console.warn(s);
}
}
}
const libDirectory = (0, typescript_exports.getDirectoryPath)((0, typescript_exports.normalizePath)(sys4.getExecutingFilePath()));
const useWatchGuard = process.platform === "win32";
const originalWatchDirectory = sys4.watchDirectory.bind(sys4);
const logger = createLogger();
typescript_exports.Debug.loggingHost = {
log(level, s) {
switch (level) {
case typescript_exports.LogLevel.Error:
case typescript_exports.LogLevel.Warning:
return logger.msg(s, typescript_exports.server.Msg.Err);
case typescript_exports.LogLevel.Info:
case typescript_exports.LogLevel.Verbose:
return logger.msg(s, typescript_exports.server.Msg.Info);
}
}
};
const pending = (0, typescript_exports.createQueue)();
let canWrite = true;
if (useWatchGuard) {
const currentDrive = extractWatchDirectoryCacheKey(
sys4.resolvePath(sys4.getCurrentDirectory()),
/*currentDriveKey*/
void 0
);
const statusCache = /* @__PURE__ */ new Map();
sys4.watchDirectory = (path, callback, recursive, options) => {
const cacheKey = extractWatchDirectoryCacheKey(path, currentDrive);
let status = cacheKey && statusCache.get(cacheKey);
if (status === void 0) {
if (logger.hasLevel(typescript_exports.server.LogLevel.verbose)) {
logger.info(`${cacheKey} for path ${path} not found in cache...`);
}
try {
const args = [(0, typescript_exports.combinePaths)(libDirectory, "watchGuard.js"), path];
if (logger.hasLevel(typescript_exports.server.LogLevel.verbose)) {
logger.info(`Starting ${process.execPath} with args:${typescript_exports.server.stringifyIndented(args)}`);
}
import_child_process.default.execFileSync(process.execPath, args, { stdio: "ignore", env: { ELECTRON_RUN_AS_NODE: "1" } });
status = true;
if (logger.hasLevel(typescript_exports.server.LogLevel.verbose)) {
logger.info(`WatchGuard for path ${path} returned: OK`);
}
} catch (e) {
status = false;
if (logger.hasLevel(typescript_exports.server.LogLevel.verbose)) {
logger.info(`WatchGuard for path ${path} returned: ${e.message}`);
}
}
if (cacheKey) {
statusCache.set(cacheKey, status);
}
} else if (logger.hasLevel(typescript_exports.server.LogLevel.verbose)) {
logger.info(`watchDirectory for ${path} uses cached drive information.`);
}
if (status) {
return watchDirectorySwallowingException(path, callback, recursive, options);
} else {
return typescript_exports.noopFileWatcher;
}
};
} else {
sys4.watchDirectory = watchDirectorySwallowingException;
}
sys4.write = (s) => writeMessage(Buffer.from(s, "utf8"));
sys4.setTimeout = setTimeout;
sys4.clearTimeout = clearTimeout;
sys4.setImmediate = setImmediate;
sys4.clearImmediate = clearImmediate;
if (typeof global !== "undefined" && global.gc) {
sys4.gc = () => {
var _a;
return (_a = global.gc) == null ? void 0 : _a.call(global);
};
}
const cancellationToken = createCancellationToken(sys4.args);
const localeStr = typescript_exports.server.findArgument("--locale");
if (localeStr) {
(0, typescript_exports.validateLocaleAndSetLanguage)(localeStr, sys4);
}
const modeOrUnknown = parseServerMode();
let serverMode;
let unknownServerMode;
if (modeOrUnknown !== void 0) {
if (typeof modeOrUnknown === "number") serverMode = modeOrUnknown;
else unknownServerMode = modeOrUnknown;
}
return {
args: process.argv,
logger,
cancellationToken,
serverMode,
unknownServerMode,
startSession: startNodeSession
};
function createLogger() {
const cmdLineLogFileName = typescript_exports.server.findArgument("--logFile");
const cmdLineVerbosity = getLogLevel(typescript_exports.server.findArgument("--logVerbosity"));
const envLogOptions = parseLoggingEnvironmentString(process.env.TSS_LOG);
const unsubstitutedLogFileName = cmdLineLogFileName ? (0, typescript_exports.stripQuotes)(cmdLineLogFileName) : envLogOptions.logToFile ? envLogOptions.file || libDirectory + "/.log" + process.pid.toString() : void 0;
const substitutedLogFileName = unsubstitutedLogFileName ? unsubstitutedLogFileName.replace("PID", process.pid.toString()) : void 0;
const logVerbosity = cmdLineVerbosity || envLogOptions.detailLevel;
return new Logger(substitutedLogFileName, envLogOptions.traceToConsole, logVerbosity);
}
function writeMessage(buf) {
if (!canWrite) {
pending.enqueue(buf);
} else {
canWrite = false;
process.stdout.write(buf, setCanWriteFlagAndWriteMessageIfNecessary);
}
}
function setCanWriteFlagAndWriteMessageIfNecessary() {
canWrite = true;
if (!pending.isEmpty()) {
writeMessage(pending.dequeue());
}
}
function extractWatchDirectoryCacheKey(path, currentDriveKey) {
path = (0, typescript_exports.normalizeSlashes)(path);
if (isUNCPath(path)) {
const firstSlash = path.indexOf(typescript_exports.directorySeparator, 2);
return firstSlash !== -1 ? (0, typescript_exports.toFileNameLowerCase)(path.substring(0, firstSlash)) : path;
}
const rootLength = (0, typescript_exports.getRootLength)(path);
if (rootLength === 0) {
return currentDriveKey;
}
if (path.charCodeAt(1) === typescript_exports.CharacterCodes.colon && path.charCodeAt(2) === typescript_exports.CharacterCodes.slash) {
return (0, typescript_exports.toFileNameLowerCase)(path.charAt(0));
}
if (path.charCodeAt(0) === typescript_exports.CharacterCodes.slash && path.charCodeAt(1) !== typescript_exports.CharacterCodes.slash) {
return currentDriveKey;
}
return void 0;
}
function isUNCPath(s) {
return s.length > 2 && s.charCodeAt(0) === typescript_exports.CharacterCodes.slash && s.charCodeAt(1) === typescript_exports.CharacterCodes.slash;
}
function watchDirectorySwallowingException(path, callback, recursive, options) {
try {
return originalWatchDirectory(path, callback, recursive, options);
} catch (e) {
logger.info(`Exception when creating directory watcher: ${e.message}`);
return typescript_exports.noopFileWatcher;
}
}
}
function parseEventPort(eventPortStr) {
const eventPort = eventPortStr === void 0 ? void 0 : parseInt(eventPortStr);
return eventPort !== void 0 && !isNaN(eventPort) ? eventPort : void 0;
}
function startNodeSession(options, logger, cancellationToken) {
const rl = import_readline.default.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
});
const _NodeTypingsInstallerAdapter = class _NodeTypingsInstallerAdapter extends typescript_exports.server.TypingsInstallerAdapter {
constructor(telemetryEnabled2, logger2, host, globalTypingsCacheLocation, typingSafeListLocation2, typesMapLocation2, npmLocation2, validateDefaultNpmLocation2, event) {
super(
telemetryEnabled2,
logger2,
host,
globalTypingsCacheLocation,
event,
_NodeTypingsInstallerAdapter.maxActiveRequestCount
);
this.typingSafeListLocation = typingSafeListLocation2;
this.typesMapLocation = typesMapLocation2;
this.npmLocation = npmLocation2;
this.validateDefaultNpmLocation = validateDefaultNpmLocation2;
}
createInstallerProcess() {
if (this.logger.hasLevel(typescript_exports.server.LogLevel.requestTime)) {
this.logger.info("Binding...");
}
const args = [typescript_exports.server.Arguments.GlobalCacheLocation, this.globalTypingsCacheLocation];
if (this.telemetryEnabled) {
args.push(typescript_exports.server.Arguments.EnableTelemetry);
}
if (this.logger.loggingEnabled() && this.logger.getLogFileName()) {
args.push(typescript_exports.server.Arguments.LogFile, (0, typescript_exports.combinePaths)((0, typescript_exports.getDirectoryPath)((0, typescript_exports.normalizeSlashes)(this.logger.getLogFileName())), `ti-${process.pid}.log`));
}
if (this.typingSafeListLocation) {
args.push(typescript_exports.server.Arguments.TypingSafeListLocation, this.typingSafeListLocation);
}
if (this.typesMapLocation) {
args.push(typescript_exports.server.Arguments.TypesMapLocation, this.typesMapLocation);
}
if (this.npmLocation) {
args.push(typescript_exports.server.Arguments.NpmLocation, this.npmLocation);
}
if (this.validateDefaultNpmLocation) {
args.push(typescript_exports.server.Arguments.ValidateDefaultNpmLocation);
}
const execArgv = [];
for (const arg of process.execArgv) {
const match = /^--((?:debug|inspect)(?:-brk)?)(?:=(\d+))?$/.exec(arg);
if (match) {
const currentPort = match[2] !== void 0 ? +match[2] : match[1].charAt(0) === "d" ? 5858 : 9229;
execArgv.push(`--${match[1]}=${currentPort + 1}`);
break;
}
}
const typingsInstaller = (0, typescript_exports.combinePaths)((0, typescript_exports.getDirectoryPath)(typescript_exports.sys.getExecutingFilePath()), "typingsInstaller.js");
this.installer = import_child_process.default.fork(typingsInstaller, args, { execArgv });
this.installer.on("message", (m) => this.handleMessage(m));
this.host.setImmediate(() => this.event({ pid: this.installer.pid }, "typingsInstallerPid"));
process.on("exit", () => {
this.installer.kill();
});
return this.installer;
}
};
// This number is essentially arbitrary. Processing more than one typings request
// at a time makes sense, but having too many in the pipe results in a hang
// (see https://github.com/nodejs/node/issues/7657).
// It would be preferable to base our limit on the amount of space left in the
// buffer, but we have yet to find a way to retrieve that value.
_NodeTypingsInstallerAdapter.maxActiveRequestCount = 10;
let NodeTypingsInstallerAdapter = _NodeTypingsInstallerAdapter;
class IOSession extends typescript_exports.server.Session {
constructor() {
const event = (body, eventName) => {
this.event(body, eventName);
};
const host = typescript_exports.sys;
const typingsInstaller = disableAutomaticTypingAcquisition ? void 0 : new NodeTypingsInstallerAdapter(telemetryEnabled, logger, host, getGlobalTypingsCacheLocation(), typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, event);
super({
host,
cancellationToken,
...options,
typingsInstaller,
byteLength: Buffer.byteLength,
hrtime: process.hrtime,
logger,
canUseEvents: true,
typesMapLocation
});
this.eventPort = eventPort;
if (this.canUseEvents && this.eventPort) {
const s = import_net.default.connect({ port: this.eventPort }, () => {
this.eventSocket = s;
if (this.socketEventQueue) {
for (const event2 of this.socketEventQueue) {
this.writeToEventSocket(event2.body, event2.eventName);
}
this.socketEventQueue = void 0;
}
});
}
this.constructed = true;
}
event(body, eventName) {
typescript_exports.Debug.assert(!!this.constructed, "Should only call `IOSession.prototype.event` on an initialized IOSession");
if (this.canUseEvents && this.eventPort) {
if (!this.eventSocket) {
if (this.logger.hasLevel(typescript_exports.server.LogLevel.verbose)) {
this.logger.info(`eventPort: event "${eventName}" queued, but socket not yet initialized`);
}
(this.socketEventQueue || (this.socketEventQueue = [])).push({ body, eventName });
return;
} else {
typescript_exports.Debug.assert(this.socketEventQueue === void 0);
this.writeToEventSocket(body, eventName);
}
} else {
super.event(body, eventName);
}
}
writeToEventSocket(body, eventName) {
this.eventSocket.write(typescript_exports.server.formatMessage(typescript_exports.server.toEvent(eventName, body), this.logger, this.byteLength, this.host.newLine), "utf8");
}
exit() {
var _a;
this.logger.info("Exiting...");
this.projectService.closeLog();
(_a = typescript_exports.tracing) == null ? void 0 : _a.stopTracing();
process.exit(0);
}
listen() {
rl.on("line", (input) => {
const message = input.trim();
this.onMessage(message);
});
rl.on("close", () => {
this.exit();
});
}
}
class IpcIOSession extends IOSession {
writeMessage(msg) {
const verboseLogging = logger.hasLevel(typescript_exports.server.LogLevel.verbose);
if (verboseLogging) {
const json = JSON.stringify(msg);
logger.info(`${msg.type}:${typescript_exports.server.indent(json)}`);
}
process.send(msg);
}
parseMessage(message) {
return message;
}
toStringMessage(message) {
return JSON.stringify(message, void 0, 2);
}
listen() {
process.on("message", (e) => {
this.onMessage(e);
});
process.on("disconnect", () => {
this.exit();
});
}
}
const eventPort = parseEventPort(typescript_exports.server.findArgument("--eventPort"));
const typingSafeListLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.TypingSafeListLocation);
const typesMapLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.TypesMapLocation) || (0, typescript_exports.combinePaths)((0, typescript_exports.getDirectoryPath)(typescript_exports.sys.getExecutingFilePath()), "typesMap.json");
const npmLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.NpmLocation);
const validateDefaultNpmLocation = typescript_exports.server.hasArgument(typescript_exports.server.Arguments.ValidateDefaultNpmLocation);
const disableAutomaticTypingAcquisition = typescript_exports.server.hasArgument("--disableAutomaticTypingAcquisition");
const useNodeIpc = typescript_exports.server.hasArgument("--useNodeIpc");
const telemetryEnabled = typescript_exports.server.hasArgument(typescript_exports.server.Arguments.EnableTelemetry);
const commandLineTraceDir = typescript_exports.server.findArgument("--traceDirectory");
const traceDir = commandLineTraceDir ? (0, typescript_exports.stripQuotes)(commandLineTraceDir) : process.env.TSS_TRACE;
if (traceDir) {
(0, typescript_exports.startTracing)("server", traceDir);
}
const ioSession = useNodeIpc ? new IpcIOSession() : new IOSession();
process.on("uncaughtException", (err) => {
ioSession.logError(err, "unknown");
});
process.noAsar = true;
ioSession.listen();
function getGlobalTypingsCacheLocation() {
switch (process.platform) {
case "win32": {
const basePath = process.env.LOCALAPPDATA || process.env.APPDATA || import_os.default.homedir && import_os.default.homedir() || process.env.USERPROFILE || process.env.HOMEDRIVE && process.env.HOMEPATH && (0, typescript_exports.normalizeSlashes)(process.env.HOMEDRIVE + process.env.HOMEPATH) || import_os.default.tmpdir();
return (0, typescript_exports.combinePaths)((0, typescript_exports.combinePaths)((0, typescript_exports.normalizeSlashes)(basePath), "Microsoft/TypeScript"), typescript_exports.versionMajorMinor);
}
case "openbsd":
case "freebsd":
case "netbsd":
case "darwin":
case "linux":
case "android": {
const cacheLocation = getNonWindowsCacheLocation(process.platform === "darwin");
return (0, typescript_exports.combinePaths)((0, typescript_exports.combinePaths)(cacheLocation, "typescript"), typescript_exports.versionMajorMinor);
}
default:
return typescript_exports.Debug.fail(`unsupported platform '${process.platform}'`);
}
}
function getNonWindowsCacheLocation(platformIsDarwin) {
if (process.env.XDG_CACHE_HOME) {
return process.env.XDG_CACHE_HOME;
}
const usersDir = platformIsDarwin ? "Users" : "home";
const homePath = import_os.default.homedir && import_os.default.homedir() || process.env.HOME || (process.env.LOGNAME || process.env.USER) && `/${usersDir}/${process.env.LOGNAME || process.env.USER}` || import_os.default.tmpdir();
const cacheFolder = platformIsDarwin ? "Library/Caches" : ".cache";
return (0, typescript_exports.combinePaths)((0, typescript_exports.normalizeSlashes)(homePath), cacheFolder);
}
}
function pipeExists(name) {
return import_fs.default.existsSync(name);
}
function createCancellationToken(args) {
let cancellationPipeName;
for (let i = 0; i < args.length - 1; i++) {
if (args[i] === "--cancellationPipeName") {
cancellationPipeName = args[i + 1];
break;
}
}
if (!cancellationPipeName) {
return typescript_exports.server.nullCancellationToken;
}
if (cancellationPipeName.charAt(cancellationPipeName.length - 1) === "*") {
const namePrefix = cancellationPipeName.slice(0, -1);
if (namePrefix.length === 0 || namePrefix.includes("*")) {
throw new Error("Invalid name for template cancellation pipe: it should have length greater than 2 characters and contain only one '*'.");
}
let perRequestPipeName;
let currentRequestId;
return {
isCancellationRequested: () => perRequestPipeName !== void 0 && pipeExists(perRequestPipeName),
setRequest(requestId) {
currentRequestId = requestId;
perRequestPipeName = namePrefix + requestId;
},
resetRequest(requestId) {
if (currentRequestId !== requestId) {
throw new Error(`Mismatched request id, expected ${currentRequestId}, actual ${requestId}`);
}
perRequestPipeName = void 0;
}
};
} else {
return {
isCancellationRequested: () => pipeExists(cancellationPipeName),
setRequest: (_requestId) => void 0,
resetRequest: (_requestId) => void 0
};
}
}
// src/tsserver/server.ts
function findArgumentStringArray(argName) {
const arg = typescript_exports.server.findArgument(argName);
if (arg === void 0) {
return typescript_exports.emptyArray;
}
return arg.split(",").filter((name) => name !== "");
}
function start({ args, logger, cancellationToken, serverMode, unknownServerMode, startSession: startServer }, platform) {
logger.info(`Starting TS Server`);
logger.info(`Version: ${typescript_exports.version}`);
logger.info(`Arguments: ${args.join(" ")}`);
logger.info(`Platform: ${platform} NodeVersion: ${process.version} CaseSensitive: ${typescript_exports.sys.useCaseSensitiveFileNames}`);
logger.info(`ServerMode: ${serverMode} hasUnknownServerMode: ${unknownServerMode}`);
typescript_exports.setStackTraceLimit();
if (typescript_exports.Debug.isDebugging) {
typescript_exports.Debug.enableDebugInfo();
}
if (typescript_exports.sys.tryEnableSourceMapsForHost && /^development$/i.test(typescript_exports.sys.getEnvironmentVariable("NODE_ENV"))) {
typescript_exports.sys.tryEnableSourceMapsForHost();
}
console.log = (...args2) => logger.msg(args2.length === 1 ? args2[0] : args2.join(", "), typescript_exports.server.Msg.Info);
console.warn = (...args2) => logger.msg(args2.length === 1 ? args2[0] : args2.join(", "), typescript_exports.server.Msg.Err);
console.error = (...args2) => logger.msg(args2.length === 1 ? args2[0] : args2.join(", "), typescript_exports.server.Msg.Err);
startServer(
{
globalPlugins: findArgumentStringArray("--globalPlugins"),
pluginProbeLocations: findArgumentStringArray("--pluginProbeLocations"),
allowLocalPluginLoads: typescript_exports.server.hasArgument("--allowLocalPluginLoads"),
useSingleInferredProject: typescript_exports.server.hasArgument("--useSingleInferredProject"),
useInferredProjectPerProjectRoot: typescript_exports.server.hasArgument("--useInferredProjectPerProjectRoot"),
suppressDiagnosticEvents: typescript_exports.server.hasArgument("--suppressDiagnosticEvents"),
noGetErrOnBackgroundUpdate: typescript_exports.server.hasArgument("--noGetErrOnBackgroundUpdate"),
canUseWatchEvents: typescript_exports.server.hasArgument("--canUseWatchEvents"),
serverMode
},
logger,
cancellationToken
);
}
typescript_exports.setStackTraceLimit();
start(initializeNodeSystem(), import_os2.default.platform());
//# sourceMappingURL=_tsserver.js.map
+222
View File
@@ -0,0 +1,222 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// src/typingsInstaller/nodeTypingsInstaller.ts
var import_child_process = require("child_process");
var fs = __toESM(require("fs"));
var path = __toESM(require("path"));
// src/typescript/typescript.ts
var typescript_exports = {};
__reExport(typescript_exports, require("./typescript.js"));
// src/typingsInstaller/nodeTypingsInstaller.ts
var FileLog = class {
constructor(logFile) {
this.logFile = logFile;
this.isEnabled = () => {
return typeof this.logFile === "string";
};
this.writeLine = (text) => {
if (typeof this.logFile !== "string") return;
try {
fs.appendFileSync(this.logFile, `[${typescript_exports.server.nowString()}] ${text}${typescript_exports.sys.newLine}`);
} catch {
this.logFile = void 0;
}
};
}
};
function getDefaultNPMLocation(processName, validateDefaultNpmLocation2, host) {
if (path.basename(processName).indexOf("node") === 0) {
const npmPath = path.join(path.dirname(process.argv[0]), "npm");
if (!validateDefaultNpmLocation2) {
return npmPath;
}
if (host.fileExists(npmPath)) {
return `"${npmPath}"`;
}
}
return "npm";
}
function loadTypesRegistryFile(typesRegistryFilePath, host, log2) {
if (!host.fileExists(typesRegistryFilePath)) {
if (log2.isEnabled()) {
log2.writeLine(`Types registry file '${typesRegistryFilePath}' does not exist`);
}
return /* @__PURE__ */ new Map();
}
try {
const content = JSON.parse(host.readFile(typesRegistryFilePath));
return new Map(Object.entries(content.entries));
} catch (e) {
if (log2.isEnabled()) {
log2.writeLine(`Error when loading types registry file '${typesRegistryFilePath}': ${e.message}, ${e.stack}`);
}
return /* @__PURE__ */ new Map();
}
}
var typesRegistryPackageName = "types-registry";
function getTypesRegistryFileLocation(globalTypingsCacheLocation2) {
return (0, typescript_exports.combinePaths)((0, typescript_exports.normalizeSlashes)(globalTypingsCacheLocation2), `node_modules/${typesRegistryPackageName}/index.json`);
}
var NodeTypingsInstaller = class extends typescript_exports.server.typingsInstaller.TypingsInstaller {
constructor(globalTypingsCacheLocation2, typingSafeListLocation2, typesMapLocation2, npmLocation2, validateDefaultNpmLocation2, throttleLimit, log2) {
const libDirectory = (0, typescript_exports.getDirectoryPath)((0, typescript_exports.normalizePath)(typescript_exports.sys.getExecutingFilePath()));
super(
typescript_exports.sys,
globalTypingsCacheLocation2,
typingSafeListLocation2 ? (0, typescript_exports.toPath)(typingSafeListLocation2, "", (0, typescript_exports.createGetCanonicalFileName)(typescript_exports.sys.useCaseSensitiveFileNames)) : (0, typescript_exports.toPath)("typingSafeList.json", libDirectory, (0, typescript_exports.createGetCanonicalFileName)(typescript_exports.sys.useCaseSensitiveFileNames)),
typesMapLocation2 ? (0, typescript_exports.toPath)(typesMapLocation2, "", (0, typescript_exports.createGetCanonicalFileName)(typescript_exports.sys.useCaseSensitiveFileNames)) : (0, typescript_exports.toPath)("typesMap.json", libDirectory, (0, typescript_exports.createGetCanonicalFileName)(typescript_exports.sys.useCaseSensitiveFileNames)),
throttleLimit,
log2
);
this.npmPath = npmLocation2 !== void 0 ? npmLocation2 : getDefaultNPMLocation(process.argv[0], validateDefaultNpmLocation2, this.installTypingHost);
if (this.npmPath.includes(" ") && this.npmPath[0] !== `"`) {
this.npmPath = `"${this.npmPath}"`;
}
if (this.log.isEnabled()) {
this.log.writeLine(`Process id: ${process.pid}`);
this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${typescript_exports.server.Arguments.NpmLocation}' ${npmLocation2 === void 0 ? "not " : ""} provided)`);
this.log.writeLine(`validateDefaultNpmLocation: ${validateDefaultNpmLocation2}`);
}
this.ensurePackageDirectoryExists(globalTypingsCacheLocation2);
try {
if (this.log.isEnabled()) {
this.log.writeLine(`Updating ${typesRegistryPackageName} npm package...`);
}
this.execSyncAndLog(`${this.npmPath} install --ignore-scripts ${typesRegistryPackageName}@${this.latestDistTag}`, { cwd: globalTypingsCacheLocation2 });
if (this.log.isEnabled()) {
this.log.writeLine(`Updated ${typesRegistryPackageName} npm package`);
}
} catch (e) {
if (this.log.isEnabled()) {
this.log.writeLine(`Error updating ${typesRegistryPackageName} package: ${e.message}`);
}
this.delayedInitializationError = {
kind: "event::initializationFailed",
message: e.message,
stack: e.stack
};
}
this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation2), this.installTypingHost, this.log);
}
handleRequest(req) {
if (this.delayedInitializationError) {
this.sendResponse(this.delayedInitializationError);
this.delayedInitializationError = void 0;
}
super.handleRequest(req);
}
sendResponse(response) {
if (this.log.isEnabled()) {
this.log.writeLine(`Sending response:${typescript_exports.server.stringifyIndented(response)}`);
}
process.send(response);
if (this.log.isEnabled()) {
this.log.writeLine(`Response has been sent.`);
}
}
installWorker(requestId, packageNames, cwd, onRequestCompleted) {
if (this.log.isEnabled()) {
this.log.writeLine(`#${requestId} with cwd: ${cwd} arguments: ${JSON.stringify(packageNames)}`);
}
const start = Date.now();
const hasError = typescript_exports.server.typingsInstaller.installNpmPackages(this.npmPath, typescript_exports.version, packageNames, (command) => this.execSyncAndLog(command, { cwd }));
if (this.log.isEnabled()) {
this.log.writeLine(`npm install #${requestId} took: ${Date.now() - start} ms`);
}
onRequestCompleted(!hasError);
}
/** Returns 'true' in case of error. */
execSyncAndLog(command, options) {
if (this.log.isEnabled()) {
this.log.writeLine(`Exec: ${command}`);
}
try {
const stdout = (0, import_child_process.execSync)(command, { ...options, encoding: "utf-8" });
if (this.log.isEnabled()) {
this.log.writeLine(` Succeeded. stdout:${indent(typescript_exports.sys.newLine, stdout)}`);
}
return false;
} catch (error) {
const { stdout, stderr } = error;
this.log.writeLine(` Failed. stdout:${indent(typescript_exports.sys.newLine, stdout)}${typescript_exports.sys.newLine} stderr:${indent(typescript_exports.sys.newLine, stderr)}`);
return true;
}
}
};
var logFilePath = typescript_exports.server.findArgument(typescript_exports.server.Arguments.LogFile);
var globalTypingsCacheLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.GlobalCacheLocation);
var typingSafeListLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.TypingSafeListLocation);
var typesMapLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.TypesMapLocation);
var npmLocation = typescript_exports.server.findArgument(typescript_exports.server.Arguments.NpmLocation);
var validateDefaultNpmLocation = typescript_exports.server.hasArgument(typescript_exports.server.Arguments.ValidateDefaultNpmLocation);
var log = new FileLog(logFilePath);
if (log.isEnabled()) {
process.on("uncaughtException", (e) => {
log.writeLine(`Unhandled exception: ${e} at ${e.stack}`);
});
}
process.on("disconnect", () => {
if (log.isEnabled()) {
log.writeLine(`Parent process has exited, shutting down...`);
}
process.exit(0);
});
var installer;
process.on("message", (req) => {
installer ?? (installer = new NodeTypingsInstaller(
globalTypingsCacheLocation,
typingSafeListLocation,
typesMapLocation,
npmLocation,
validateDefaultNpmLocation,
/*throttleLimit*/
5,
log
));
installer.handleRequest(req);
});
function indent(newline, str) {
return str && str.length ? `${newline} ` + str.replace(/\r?\n/, `${newline} `) : "";
}
//# sourceMappingURL=_typingsInstaller.js.map
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es5" />
/// <reference lib="dom" />
/// <reference lib="webworker.importscripts" />
/// <reference lib="scripthost" />
+384
View File
@@ -0,0 +1,384 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/**
* The decorator context types provided to class element decorators.
*/
type ClassMemberDecoratorContext =
| ClassMethodDecoratorContext
| ClassGetterDecoratorContext
| ClassSetterDecoratorContext
| ClassFieldDecoratorContext
| ClassAccessorDecoratorContext;
/**
* The decorator context types provided to any decorator.
*/
type DecoratorContext =
| ClassDecoratorContext
| ClassMemberDecoratorContext;
type DecoratorMetadataObject = Record<PropertyKey, unknown> & object;
type DecoratorMetadata = typeof globalThis extends { Symbol: { readonly metadata: symbol; }; } ? DecoratorMetadataObject : DecoratorMetadataObject | undefined;
/**
* Context provided to a class decorator.
* @template Class The type of the decorated class associated with this context.
*/
interface ClassDecoratorContext<
Class extends abstract new (...args: any) => any = abstract new (...args: any) => any,
> {
/** The kind of element that was decorated. */
readonly kind: "class";
/** The name of the decorated class. */
readonly name: string | undefined;
/**
* Adds a callback to be invoked after the class definition has been finalized.
*
* @example
* ```ts
* function customElement(name: string): ClassDecoratorFunction {
* return (target, context) => {
* context.addInitializer(function () {
* customElements.define(name, this);
* });
* }
* }
*
* @customElement("my-element")
* class MyElement {}
* ```
*/
addInitializer(initializer: (this: Class) => void): void;
readonly metadata: DecoratorMetadata;
}
/**
* Context provided to a class method decorator.
* @template This The type on which the class element will be defined. For a static class element, this will be
* the type of the constructor. For a non-static class element, this will be the type of the instance.
* @template Value The type of the decorated class method.
*/
interface ClassMethodDecoratorContext<
This = unknown,
Value extends (this: This, ...args: any) => any = (this: This, ...args: any) => any,
> {
/** The kind of class element that was decorated. */
readonly kind: "method";
/** The name of the decorated class element. */
readonly name: string | symbol;
/** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */
readonly static: boolean;
/** A value indicating whether the class element has a private name. */
readonly private: boolean;
/** An object that can be used to access the current value of the class element at runtime. */
readonly access: {
/**
* Determines whether an object has a property with the same name as the decorated element.
*/
has(object: This): boolean;
/**
* Gets the current value of the method from the provided object.
*
* @example
* let fn = context.access.get(instance);
*/
get(object: This): Value;
};
/**
* Adds a callback to be invoked either after static methods are defined but before
* static initializers are run (when decorating a `static` element), or before instance
* initializers are run (when decorating a non-`static` element).
*
* @example
* ```ts
* const bound: ClassMethodDecoratorFunction = (value, context) {
* if (context.private) throw new TypeError("Not supported on private methods.");
* context.addInitializer(function () {
* this[context.name] = this[context.name].bind(this);
* });
* }
*
* class C {
* message = "Hello";
*
* @bound
* m() {
* console.log(this.message);
* }
* }
* ```
*/
addInitializer(initializer: (this: This) => void): void;
readonly metadata: DecoratorMetadata;
}
/**
* Context provided to a class getter decorator.
* @template This The type on which the class element will be defined. For a static class element, this will be
* the type of the constructor. For a non-static class element, this will be the type of the instance.
* @template Value The property type of the decorated class getter.
*/
interface ClassGetterDecoratorContext<
This = unknown,
Value = unknown,
> {
/** The kind of class element that was decorated. */
readonly kind: "getter";
/** The name of the decorated class element. */
readonly name: string | symbol;
/** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */
readonly static: boolean;
/** A value indicating whether the class element has a private name. */
readonly private: boolean;
/** An object that can be used to access the current value of the class element at runtime. */
readonly access: {
/**
* Determines whether an object has a property with the same name as the decorated element.
*/
has(object: This): boolean;
/**
* Invokes the getter on the provided object.
*
* @example
* let value = context.access.get(instance);
*/
get(object: This): Value;
};
/**
* Adds a callback to be invoked either after static methods are defined but before
* static initializers are run (when decorating a `static` element), or before instance
* initializers are run (when decorating a non-`static` element).
*/
addInitializer(initializer: (this: This) => void): void;
readonly metadata: DecoratorMetadata;
}
/**
* Context provided to a class setter decorator.
* @template This The type on which the class element will be defined. For a static class element, this will be
* the type of the constructor. For a non-static class element, this will be the type of the instance.
* @template Value The type of the decorated class setter.
*/
interface ClassSetterDecoratorContext<
This = unknown,
Value = unknown,
> {
/** The kind of class element that was decorated. */
readonly kind: "setter";
/** The name of the decorated class element. */
readonly name: string | symbol;
/** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */
readonly static: boolean;
/** A value indicating whether the class element has a private name. */
readonly private: boolean;
/** An object that can be used to access the current value of the class element at runtime. */
readonly access: {
/**
* Determines whether an object has a property with the same name as the decorated element.
*/
has(object: This): boolean;
/**
* Invokes the setter on the provided object.
*
* @example
* context.access.set(instance, value);
*/
set(object: This, value: Value): void;
};
/**
* Adds a callback to be invoked either after static methods are defined but before
* static initializers are run (when decorating a `static` element), or before instance
* initializers are run (when decorating a non-`static` element).
*/
addInitializer(initializer: (this: This) => void): void;
readonly metadata: DecoratorMetadata;
}
/**
* Context provided to a class `accessor` field decorator.
* @template This The type on which the class element will be defined. For a static class element, this will be
* the type of the constructor. For a non-static class element, this will be the type of the instance.
* @template Value The type of decorated class field.
*/
interface ClassAccessorDecoratorContext<
This = unknown,
Value = unknown,
> {
/** The kind of class element that was decorated. */
readonly kind: "accessor";
/** The name of the decorated class element. */
readonly name: string | symbol;
/** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */
readonly static: boolean;
/** A value indicating whether the class element has a private name. */
readonly private: boolean;
/** An object that can be used to access the current value of the class element at runtime. */
readonly access: {
/**
* Determines whether an object has a property with the same name as the decorated element.
*/
has(object: This): boolean;
/**
* Invokes the getter on the provided object.
*
* @example
* let value = context.access.get(instance);
*/
get(object: This): Value;
/**
* Invokes the setter on the provided object.
*
* @example
* context.access.set(instance, value);
*/
set(object: This, value: Value): void;
};
/**
* Adds a callback to be invoked immediately after the auto `accessor` being
* decorated is initialized (regardless if the `accessor` is `static` or not).
*/
addInitializer(initializer: (this: This) => void): void;
readonly metadata: DecoratorMetadata;
}
/**
* Describes the target provided to class `accessor` field decorators.
* @template This The `this` type to which the target applies.
* @template Value The property type for the class `accessor` field.
*/
interface ClassAccessorDecoratorTarget<This, Value> {
/**
* Invokes the getter that was defined prior to decorator application.
*
* @example
* let value = target.get.call(instance);
*/
get(this: This): Value;
/**
* Invokes the setter that was defined prior to decorator application.
*
* @example
* target.set.call(instance, value);
*/
set(this: This, value: Value): void;
}
/**
* Describes the allowed return value from a class `accessor` field decorator.
* @template This The `this` type to which the target applies.
* @template Value The property type for the class `accessor` field.
*/
interface ClassAccessorDecoratorResult<This, Value> {
/**
* An optional replacement getter function. If not provided, the existing getter function is used instead.
*/
get?(this: This): Value;
/**
* An optional replacement setter function. If not provided, the existing setter function is used instead.
*/
set?(this: This, value: Value): void;
/**
* An optional initializer mutator that is invoked when the underlying field initializer is evaluated.
* @param value The incoming initializer value.
* @returns The replacement initializer value.
*/
init?(this: This, value: Value): Value;
}
/**
* Context provided to a class field decorator.
* @template This The type on which the class element will be defined. For a static class element, this will be
* the type of the constructor. For a non-static class element, this will be the type of the instance.
* @template Value The type of the decorated class field.
*/
interface ClassFieldDecoratorContext<
This = unknown,
Value = unknown,
> {
/** The kind of class element that was decorated. */
readonly kind: "field";
/** The name of the decorated class element. */
readonly name: string | symbol;
/** A value indicating whether the class element is a static (`true`) or instance (`false`) element. */
readonly static: boolean;
/** A value indicating whether the class element has a private name. */
readonly private: boolean;
/** An object that can be used to access the current value of the class element at runtime. */
readonly access: {
/**
* Determines whether an object has a property with the same name as the decorated element.
*/
has(object: This): boolean;
/**
* Gets the value of the field on the provided object.
*/
get(object: This): Value;
/**
* Sets the value of the field on the provided object.
*/
set(object: This, value: Value): void;
};
/**
* Adds a callback to be invoked immediately after the field being decorated
* is initialized (regardless if the field is `static` or not).
*/
addInitializer(initializer: (this: This) => void): void;
readonly metadata: DecoratorMetadata;
}
@@ -0,0 +1,22 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;
declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol | undefined, parameterIndex: number) => void;
@@ -0,0 +1,41 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/////////////////////////////
/// Window Async Iterable APIs
/////////////////////////////
interface FileSystemDirectoryHandleAsyncIterator<T> extends AsyncIteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.asyncIterator](): FileSystemDirectoryHandleAsyncIterator<T>;
}
interface FileSystemDirectoryHandle {
[Symbol.asyncIterator](): FileSystemDirectoryHandleAsyncIterator<[string, FileSystemHandle]>;
entries(): FileSystemDirectoryHandleAsyncIterator<[string, FileSystemHandle]>;
keys(): FileSystemDirectoryHandleAsyncIterator<string>;
values(): FileSystemDirectoryHandleAsyncIterator<FileSystemHandle>;
}
interface ReadableStreamAsyncIterator<T> extends AsyncIteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.asyncIterator](): ReadableStreamAsyncIterator<T>;
}
interface ReadableStream<R = any> {
[Symbol.asyncIterator](options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>;
values(options?: ReadableStreamIteratorOptions): ReadableStreamAsyncIterator<R>;
}
File diff suppressed because it is too large Load Diff
+571
View File
@@ -0,0 +1,571 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/////////////////////////////
/// Window Iterable APIs
/////////////////////////////
interface AudioParam {
/**
* The **`setValueCurveAtTime()`** method of the following a curve defined by a list of values.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AudioParam/setValueCurveAtTime)
*/
setValueCurveAtTime(values: Iterable<number>, startTime: number, duration: number): AudioParam;
}
interface AudioParamMap extends ReadonlyMap<string, AudioParam> {
}
interface BaseAudioContext {
/**
* The **`createIIRFilter()`** method of the BaseAudioContext interface creates an IIRFilterNode, which represents a general **infinite impulse response** (IIR) filter which can be configured to serve as various types of filter.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createIIRFilter)
*/
createIIRFilter(feedforward: Iterable<number>, feedback: Iterable<number>): IIRFilterNode;
/**
* The `createPeriodicWave()` method of the BaseAudioContext interface is used to create a PeriodicWave.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/BaseAudioContext/createPeriodicWave)
*/
createPeriodicWave(real: Iterable<number>, imag: Iterable<number>, constraints?: PeriodicWaveConstraints): PeriodicWave;
}
interface CSSKeyframesRule {
[Symbol.iterator](): ArrayIterator<CSSKeyframeRule>;
}
interface CSSNumericArray {
[Symbol.iterator](): ArrayIterator<CSSNumericValue>;
entries(): ArrayIterator<[number, CSSNumericValue]>;
keys(): ArrayIterator<number>;
values(): ArrayIterator<CSSNumericValue>;
}
interface CSSRuleList {
[Symbol.iterator](): ArrayIterator<CSSRule>;
}
interface CSSStyleDeclaration {
[Symbol.iterator](): ArrayIterator<string>;
}
interface CSSTransformValue {
[Symbol.iterator](): ArrayIterator<CSSTransformComponent>;
entries(): ArrayIterator<[number, CSSTransformComponent]>;
keys(): ArrayIterator<number>;
values(): ArrayIterator<CSSTransformComponent>;
}
interface CSSUnparsedValue {
[Symbol.iterator](): ArrayIterator<CSSUnparsedSegment>;
entries(): ArrayIterator<[number, CSSUnparsedSegment]>;
keys(): ArrayIterator<number>;
values(): ArrayIterator<CSSUnparsedSegment>;
}
interface Cache {
/**
* The **`addAll()`** method of the Cache interface takes an array of URLs, retrieves them, and adds the resulting response objects to the given cache.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Cache/addAll)
*/
addAll(requests: Iterable<RequestInfo>): Promise<void>;
}
interface CanvasPath {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/roundRect) */
roundRect(x: number, y: number, w: number, h: number, radii?: number | DOMPointInit | Iterable<number | DOMPointInit>): void;
}
interface CanvasPathDrawingStyles {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/CanvasRenderingContext2D/setLineDash) */
setLineDash(segments: Iterable<number>): void;
}
interface CookieStoreManager {
/**
* The **`subscribe()`** method of the CookieStoreManager interface subscribes a ServiceWorkerRegistration to cookie change events.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CookieStoreManager/subscribe)
*/
subscribe(subscriptions: Iterable<CookieStoreGetOptions>): Promise<void>;
/**
* The **`unsubscribe()`** method of the CookieStoreManager interface stops the ServiceWorkerRegistration from receiving previously subscribed events.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CookieStoreManager/unsubscribe)
*/
unsubscribe(subscriptions: Iterable<CookieStoreGetOptions>): Promise<void>;
}
interface CustomStateSet extends Set<string> {
}
interface DOMRectList {
[Symbol.iterator](): ArrayIterator<DOMRect>;
}
interface DOMStringList {
[Symbol.iterator](): ArrayIterator<string>;
}
interface DOMTokenList {
[Symbol.iterator](): ArrayIterator<string>;
entries(): ArrayIterator<[number, string]>;
keys(): ArrayIterator<number>;
values(): ArrayIterator<string>;
}
interface DataTransferItemList {
[Symbol.iterator](): ArrayIterator<DataTransferItem>;
}
interface EventCounts extends ReadonlyMap<string, number> {
}
interface FileList {
[Symbol.iterator](): ArrayIterator<File>;
}
interface FontFaceSet extends Set<FontFace> {
}
interface FormDataIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): FormDataIterator<T>;
}
interface FormData {
[Symbol.iterator](): FormDataIterator<[string, FormDataEntryValue]>;
/** Returns an array of key, value pairs for every entry in the list. */
entries(): FormDataIterator<[string, FormDataEntryValue]>;
/** Returns a list of keys in the list. */
keys(): FormDataIterator<string>;
/** Returns a list of values in the list. */
values(): FormDataIterator<FormDataEntryValue>;
}
interface HTMLAllCollection {
[Symbol.iterator](): ArrayIterator<Element>;
}
interface HTMLCollectionBase {
[Symbol.iterator](): ArrayIterator<Element>;
}
interface HTMLCollectionOf<T extends Element> {
[Symbol.iterator](): ArrayIterator<T>;
}
interface HTMLFormElement {
[Symbol.iterator](): ArrayIterator<Element>;
}
interface HTMLSelectElement {
[Symbol.iterator](): ArrayIterator<HTMLOptionElement>;
}
interface HeadersIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): HeadersIterator<T>;
}
interface Headers {
[Symbol.iterator](): HeadersIterator<[string, string]>;
/** Returns an iterator allowing to go through all key/value pairs contained in this object. */
entries(): HeadersIterator<[string, string]>;
/** Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */
keys(): HeadersIterator<string>;
/** Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */
values(): HeadersIterator<string>;
}
interface Highlight extends Set<AbstractRange> {
}
interface HighlightRegistry extends Map<string, Highlight> {
}
interface IDBDatabase {
/**
* The **`transaction`** method of the IDBDatabase interface immediately returns a transaction object (IDBTransaction) containing the IDBTransaction.objectStore method, which you can use to access your object store.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBDatabase/transaction)
*/
transaction(storeNames: string | Iterable<string>, mode?: IDBTransactionMode, options?: IDBTransactionOptions): IDBTransaction;
}
interface IDBObjectStore {
/**
* The **`createIndex()`** method of the field/column defining a new data point for each database record to contain.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/IDBObjectStore/createIndex)
*/
createIndex(name: string, keyPath: string | Iterable<string>, options?: IDBIndexParameters): IDBIndex;
}
interface ImageTrackList {
[Symbol.iterator](): ArrayIterator<ImageTrack>;
}
interface MIDIInputMap extends ReadonlyMap<string, MIDIInput> {
}
interface MIDIOutput {
/**
* The **`send()`** method of the MIDIOutput interface queues messages for the corresponding MIDI port.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/MIDIOutput/send)
*/
send(data: Iterable<number>, timestamp?: DOMHighResTimeStamp): void;
}
interface MIDIOutputMap extends ReadonlyMap<string, MIDIOutput> {
}
interface MediaKeyStatusMapIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): MediaKeyStatusMapIterator<T>;
}
interface MediaKeyStatusMap {
[Symbol.iterator](): MediaKeyStatusMapIterator<[BufferSource, MediaKeyStatus]>;
entries(): MediaKeyStatusMapIterator<[BufferSource, MediaKeyStatus]>;
keys(): MediaKeyStatusMapIterator<BufferSource>;
values(): MediaKeyStatusMapIterator<MediaKeyStatus>;
}
interface MediaList {
[Symbol.iterator](): ArrayIterator<string>;
}
interface MessageEvent<T = any> {
/** @deprecated */
initMessageEvent(type: string, bubbles?: boolean, cancelable?: boolean, data?: any, origin?: string, lastEventId?: string, source?: MessageEventSource | null, ports?: Iterable<MessagePort>): void;
}
interface MimeTypeArray {
[Symbol.iterator](): ArrayIterator<MimeType>;
}
interface NamedNodeMap {
[Symbol.iterator](): ArrayIterator<Attr>;
}
interface Navigator {
/**
* The **`requestMediaKeySystemAccess()`** method of the Navigator interface returns a Promise which delivers a MediaKeySystemAccess object that can be used to access a particular media key system, which can in turn be used to create keys for decrypting a media stream.
* Available only in secure contexts.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Navigator/requestMediaKeySystemAccess)
*/
requestMediaKeySystemAccess(keySystem: string, supportedConfigurations: Iterable<MediaKeySystemConfiguration>): Promise<MediaKeySystemAccess>;
/**
* The **`vibrate()`** method of the Navigator interface pulses the vibration hardware on the device, if such hardware exists.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Navigator/vibrate)
*/
vibrate(pattern: Iterable<number>): boolean;
}
interface NodeList {
[Symbol.iterator](): ArrayIterator<Node>;
/** Returns an array of key, value pairs for every entry in the list. */
entries(): ArrayIterator<[number, Node]>;
/** Returns an list of keys in the list. */
keys(): ArrayIterator<number>;
/** Returns an list of values in the list. */
values(): ArrayIterator<Node>;
}
interface NodeListOf<TNode extends Node> {
[Symbol.iterator](): ArrayIterator<TNode>;
/** Returns an array of key, value pairs for every entry in the list. */
entries(): ArrayIterator<[number, TNode]>;
/** Returns an list of keys in the list. */
keys(): ArrayIterator<number>;
/** Returns an list of values in the list. */
values(): ArrayIterator<TNode>;
}
interface Plugin {
[Symbol.iterator](): ArrayIterator<MimeType>;
}
interface PluginArray {
[Symbol.iterator](): ArrayIterator<Plugin>;
}
interface RTCRtpTransceiver {
/**
* The **`setCodecPreferences()`** method of the RTCRtpTransceiver interface is used to set the codecs that the transceiver allows for decoding _received_ data, in order of decreasing preference.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/RTCRtpTransceiver/setCodecPreferences)
*/
setCodecPreferences(codecs: Iterable<RTCRtpCodec>): void;
}
interface RTCStatsReport extends ReadonlyMap<string, any> {
}
interface SVGLengthList {
[Symbol.iterator](): ArrayIterator<SVGLength>;
}
interface SVGNumberList {
[Symbol.iterator](): ArrayIterator<SVGNumber>;
}
interface SVGPointList {
[Symbol.iterator](): ArrayIterator<DOMPoint>;
}
interface SVGStringList {
[Symbol.iterator](): ArrayIterator<string>;
}
interface SVGTransformList {
[Symbol.iterator](): ArrayIterator<SVGTransform>;
}
interface SourceBufferList {
[Symbol.iterator](): ArrayIterator<SourceBuffer>;
}
interface SpeechRecognitionResult {
[Symbol.iterator](): ArrayIterator<SpeechRecognitionAlternative>;
}
interface SpeechRecognitionResultList {
[Symbol.iterator](): ArrayIterator<SpeechRecognitionResult>;
}
interface StylePropertyMapReadOnlyIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): StylePropertyMapReadOnlyIterator<T>;
}
interface StylePropertyMapReadOnly {
[Symbol.iterator](): StylePropertyMapReadOnlyIterator<[string, Iterable<CSSStyleValue>]>;
entries(): StylePropertyMapReadOnlyIterator<[string, Iterable<CSSStyleValue>]>;
keys(): StylePropertyMapReadOnlyIterator<string>;
values(): StylePropertyMapReadOnlyIterator<Iterable<CSSStyleValue>>;
}
interface StyleSheetList {
[Symbol.iterator](): ArrayIterator<CSSStyleSheet>;
}
interface SubtleCrypto {
/**
* The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey)
*/
deriveKey(algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, derivedKeyType: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
/**
* The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms).
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey)
*/
generateKey(algorithm: "Ed25519" | { name: "Ed25519" }, extractable: boolean, keyUsages: ReadonlyArray<"sign" | "verify">): Promise<CryptoKeyPair>;
generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: ReadonlyArray<KeyUsage>): Promise<CryptoKeyPair>;
generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: ReadonlyArray<KeyUsage>): Promise<CryptoKey>;
generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKeyPair | CryptoKey>;
/**
* The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey)
*/
importKey(format: "jwk", keyData: JsonWebKey, algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: ReadonlyArray<KeyUsage>): Promise<CryptoKey>;
importKey(format: Exclude<KeyFormat, "jwk">, keyData: BufferSource, algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
/**
* The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey)
*/
unwrapKey(format: KeyFormat, wrappedKey: BufferSource, unwrappingKey: CryptoKey, unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, unwrappedKeyAlgorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: Iterable<KeyUsage>): Promise<CryptoKey>;
}
interface TextTrackCueList {
[Symbol.iterator](): ArrayIterator<TextTrackCue>;
}
interface TextTrackList {
[Symbol.iterator](): ArrayIterator<TextTrack>;
}
interface TouchList {
[Symbol.iterator](): ArrayIterator<Touch>;
}
interface URLSearchParamsIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): URLSearchParamsIterator<T>;
}
interface URLSearchParams {
[Symbol.iterator](): URLSearchParamsIterator<[string, string]>;
/** Returns an array of key, value pairs for every entry in the search params. */
entries(): URLSearchParamsIterator<[string, string]>;
/** Returns a list of keys in the search params. */
keys(): URLSearchParamsIterator<string>;
/** Returns a list of values in the search params. */
values(): URLSearchParamsIterator<string>;
}
interface ViewTransitionTypeSet extends Set<string> {
}
interface WEBGL_draw_buffers {
/**
* The **`WEBGL_draw_buffers.drawBuffersWEBGL()`** method is part of the WebGL API and allows you to define the draw buffers to which all fragment colors are written.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WEBGL_draw_buffers/drawBuffersWEBGL)
*/
drawBuffersWEBGL(buffers: Iterable<GLenum>): void;
}
interface WEBGL_multi_draw {
/**
* The **`WEBGL_multi_draw.multiDrawArraysInstancedWEBGL()`** method of the WebGL API renders multiple primitives from array data.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WEBGL_multi_draw/multiDrawArraysInstancedWEBGL)
*/
multiDrawArraysInstancedWEBGL(mode: GLenum, firstsList: Int32Array<ArrayBufferLike> | Iterable<GLint>, firstsOffset: number, countsList: Int32Array<ArrayBufferLike> | Iterable<GLsizei>, countsOffset: number, instanceCountsList: Int32Array<ArrayBufferLike> | Iterable<GLsizei>, instanceCountsOffset: number, drawcount: GLsizei): void;
/**
* The **`WEBGL_multi_draw.multiDrawArraysWEBGL()`** method of the WebGL API renders multiple primitives from array data.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WEBGL_multi_draw/multiDrawArraysWEBGL)
*/
multiDrawArraysWEBGL(mode: GLenum, firstsList: Int32Array<ArrayBufferLike> | Iterable<GLint>, firstsOffset: number, countsList: Int32Array<ArrayBufferLike> | Iterable<GLsizei>, countsOffset: number, drawcount: GLsizei): void;
/**
* The **`WEBGL_multi_draw.multiDrawElementsInstancedWEBGL()`** method of the WebGL API renders multiple primitives from array data.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WEBGL_multi_draw/multiDrawElementsInstancedWEBGL)
*/
multiDrawElementsInstancedWEBGL(mode: GLenum, countsList: Int32Array<ArrayBufferLike> | Iterable<GLsizei>, countsOffset: number, type: GLenum, offsetsList: Int32Array<ArrayBufferLike> | Iterable<GLsizei>, offsetsOffset: number, instanceCountsList: Int32Array<ArrayBufferLike> | Iterable<GLsizei>, instanceCountsOffset: number, drawcount: GLsizei): void;
/**
* The **`WEBGL_multi_draw.multiDrawElementsWEBGL()`** method of the WebGL API renders multiple primitives from array data.
*
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/WEBGL_multi_draw/multiDrawElementsWEBGL)
*/
multiDrawElementsWEBGL(mode: GLenum, countsList: Int32Array<ArrayBufferLike> | Iterable<GLsizei>, countsOffset: number, type: GLenum, offsetsList: Int32Array<ArrayBufferLike> | Iterable<GLsizei>, offsetsOffset: number, drawcount: GLsizei): void;
}
interface WebGL2RenderingContextBase {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/clearBuffer) */
clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLfloat>, srcOffset?: number): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/clearBuffer) */
clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLint>, srcOffset?: number): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/clearBuffer) */
clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Iterable<GLuint>, srcOffset?: number): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/drawBuffers) */
drawBuffers(buffers: Iterable<GLenum>): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/getActiveUniforms) */
getActiveUniforms(program: WebGLProgram, uniformIndices: Iterable<GLuint>, pname: GLenum): any;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/getUniformIndices) */
getUniformIndices(program: WebGLProgram, uniformNames: Iterable<string>): GLuint[] | null;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/invalidateFramebuffer) */
invalidateFramebuffer(target: GLenum, attachments: Iterable<GLenum>): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/invalidateSubFramebuffer) */
invalidateSubFramebuffer(target: GLenum, attachments: Iterable<GLenum>, x: GLint, y: GLint, width: GLsizei, height: GLsizei): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/transformFeedbackVaryings) */
transformFeedbackVaryings(program: WebGLProgram, varyings: Iterable<string>, bufferMode: GLenum): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniform) */
uniform1uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniform) */
uniform2uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniform) */
uniform3uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniform) */
uniform4uiv(location: WebGLUniformLocation | null, data: Iterable<GLuint>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniformMatrix) */
uniformMatrix2x3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniformMatrix) */
uniformMatrix2x4fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniformMatrix) */
uniformMatrix3x2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniformMatrix) */
uniformMatrix3x4fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniformMatrix) */
uniformMatrix4x2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniformMatrix) */
uniformMatrix4x3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/vertexAttribI) */
vertexAttribI4iv(index: GLuint, values: Iterable<GLint>): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/vertexAttribI) */
vertexAttribI4uiv(index: GLuint, values: Iterable<GLuint>): void;
}
interface WebGL2RenderingContextOverloads {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
uniform1fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
uniform1iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
uniform2fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
uniform2iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
uniform3fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
uniform3iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
uniform4fv(location: WebGLUniformLocation | null, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
uniform4iv(location: WebGLUniformLocation | null, data: Iterable<GLint>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGL2RenderingContext/uniformMatrix) */
uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniformMatrix) */
uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniformMatrix) */
uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, data: Iterable<GLfloat>, srcOffset?: number, srcLength?: GLuint): void;
}
interface WebGLRenderingContextBase {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/vertexAttrib) */
vertexAttrib1fv(index: GLuint, values: Iterable<GLfloat>): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/vertexAttrib) */
vertexAttrib2fv(index: GLuint, values: Iterable<GLfloat>): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/vertexAttrib) */
vertexAttrib3fv(index: GLuint, values: Iterable<GLfloat>): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/vertexAttrib) */
vertexAttrib4fv(index: GLuint, values: Iterable<GLfloat>): void;
}
interface WebGLRenderingContextOverloads {
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
uniform1fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
uniform1iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
uniform2fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
uniform2iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
uniform3fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
uniform3iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
uniform4fv(location: WebGLUniformLocation | null, v: Iterable<GLfloat>): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniform) */
uniform4iv(location: WebGLUniformLocation | null, v: Iterable<GLint>): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniformMatrix) */
uniformMatrix2fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Iterable<GLfloat>): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniformMatrix) */
uniformMatrix3fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Iterable<GLfloat>): void;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebGLRenderingContext/uniformMatrix) */
uniformMatrix4fv(location: WebGLUniformLocation | null, transpose: GLboolean, value: Iterable<GLfloat>): void;
}
@@ -0,0 +1,147 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Map<K, V> {
clear(): void;
/**
* @returns true if an element in the Map existed and has been removed, or false if the element does not exist.
*/
delete(key: K): boolean;
/**
* Executes a provided function once per each key/value pair in the Map, in insertion order.
*/
forEach(callbackfn: (value: V, key: K, map: Map<K, V>) => void, thisArg?: any): void;
/**
* Returns a specified element from the Map object. If the value that is associated to the provided key is an object, then you will get a reference to that object and any change made to that object will effectively modify it inside the Map.
* @returns Returns the element associated with the specified key. If no element is associated with the specified key, undefined is returned.
*/
get(key: K): V | undefined;
/**
* @returns boolean indicating whether an element with the specified key exists or not.
*/
has(key: K): boolean;
/**
* Adds a new element with a specified key and value to the Map. If an element with the same key already exists, the element will be updated.
*/
set(key: K, value: V): this;
/**
* @returns the number of elements in the Map.
*/
readonly size: number;
}
interface MapConstructor {
new (): Map<any, any>;
new <K, V>(entries?: readonly (readonly [K, V])[] | null): Map<K, V>;
readonly prototype: Map<any, any>;
}
declare var Map: MapConstructor;
interface ReadonlyMap<K, V> {
forEach(callbackfn: (value: V, key: K, map: ReadonlyMap<K, V>) => void, thisArg?: any): void;
get(key: K): V | undefined;
has(key: K): boolean;
readonly size: number;
}
interface WeakMap<K extends WeakKey, V> {
/**
* Removes the specified element from the WeakMap.
* @returns true if the element was successfully removed, or false if it was not present.
*/
delete(key: K): boolean;
/**
* @returns a specified element.
*/
get(key: K): V | undefined;
/**
* @returns a boolean indicating whether an element with the specified key exists or not.
*/
has(key: K): boolean;
/**
* Adds a new element with a specified key and value.
* @param key Must be an object or symbol.
*/
set(key: K, value: V): this;
}
interface WeakMapConstructor {
new <K extends WeakKey = WeakKey, V = any>(entries?: readonly (readonly [K, V])[] | null): WeakMap<K, V>;
readonly prototype: WeakMap<WeakKey, any>;
}
declare var WeakMap: WeakMapConstructor;
interface Set<T> {
/**
* Appends a new element with a specified value to the end of the Set.
*/
add(value: T): this;
clear(): void;
/**
* Removes a specified value from the Set.
* @returns Returns true if an element in the Set existed and has been removed, or false if the element does not exist.
*/
delete(value: T): boolean;
/**
* Executes a provided function once per each value in the Set object, in insertion order.
*/
forEach(callbackfn: (value: T, value2: T, set: Set<T>) => void, thisArg?: any): void;
/**
* @returns a boolean indicating whether an element with the specified value exists in the Set or not.
*/
has(value: T): boolean;
/**
* @returns the number of (unique) elements in Set.
*/
readonly size: number;
}
interface SetConstructor {
new <T = any>(values?: readonly T[] | null): Set<T>;
readonly prototype: Set<any>;
}
declare var Set: SetConstructor;
interface ReadonlySet<T> {
forEach(callbackfn: (value: T, value2: T, set: ReadonlySet<T>) => void, thisArg?: any): void;
has(value: T): boolean;
readonly size: number;
}
interface WeakSet<T extends WeakKey> {
/**
* Appends a new value to the end of the WeakSet.
*/
add(value: T): this;
/**
* Removes the specified element from the WeakSet.
* @returns Returns true if the element existed and has been removed, or false if the element does not exist.
*/
delete(value: T): boolean;
/**
* @returns a boolean indicating whether a value exists in the WeakSet or not.
*/
has(value: T): boolean;
}
interface WeakSetConstructor {
new <T extends WeakKey = WeakKey>(values?: readonly T[] | null): WeakSet<T>;
readonly prototype: WeakSet<WeakKey>;
}
declare var WeakSet: WeakSetConstructor;
+597
View File
@@ -0,0 +1,597 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Array<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find<S extends T>(predicate: (value: T, index: number, obj: T[]) => value is S, thisArg?: any): S | undefined;
find(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T, index: number, obj: T[]) => unknown, thisArg?: any): number;
/**
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: T, start?: number, end?: number): this;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions & Intl.DateTimeFormatOptions): string;
}
interface ArrayConstructor {
/**
* Creates an array from an array-like object.
* @param arrayLike An array-like object to convert to an array.
*/
from<T>(arrayLike: ArrayLike<T>): T[];
/**
* Creates an array from an iterable object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): U[];
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of<T>(...items: T[]): T[];
}
interface DateConstructor {
new (value: number | string | Date): Date;
}
interface Function {
/**
* Returns the name of the function. Function names are read-only and can not be changed.
*/
readonly name: string;
}
interface Math {
/**
* Returns the number of leading zero bits in the 32-bit binary representation of a number.
* @param x A numeric expression.
*/
clz32(x: number): number;
/**
* Returns the result of 32-bit multiplication of two numbers.
* @param x First number
* @param y Second number
*/
imul(x: number, y: number): number;
/**
* Returns the sign of the x, indicating whether x is positive, negative or zero.
* @param x The numeric expression to test
*/
sign(x: number): number;
/**
* Returns the base 10 logarithm of a number.
* @param x A numeric expression.
*/
log10(x: number): number;
/**
* Returns the base 2 logarithm of a number.
* @param x A numeric expression.
*/
log2(x: number): number;
/**
* Returns the natural logarithm of 1 + x.
* @param x A numeric expression.
*/
log1p(x: number): number;
/**
* Returns the result of (e^x - 1), which is an implementation-dependent approximation to
* subtracting 1 from the exponential function of x (e raised to the power of x, where e
* is the base of the natural logarithms).
* @param x A numeric expression.
*/
expm1(x: number): number;
/**
* Returns the hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
cosh(x: number): number;
/**
* Returns the hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
sinh(x: number): number;
/**
* Returns the hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
tanh(x: number): number;
/**
* Returns the inverse hyperbolic cosine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
acosh(x: number): number;
/**
* Returns the inverse hyperbolic sine of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
asinh(x: number): number;
/**
* Returns the inverse hyperbolic tangent of a number.
* @param x A numeric expression that contains an angle measured in radians.
*/
atanh(x: number): number;
/**
* Returns the square root of the sum of squares of its arguments.
* @param values Values to compute the square root for.
* If no arguments are passed, the result is +0.
* If there is only one argument, the result is the absolute value.
* If any argument is +Infinity or -Infinity, the result is +Infinity.
* If any argument is NaN, the result is NaN.
* If all arguments are either +0 or 0, the result is +0.
*/
hypot(...values: number[]): number;
/**
* Returns the integral part of the a numeric expression, x, removing any fractional digits.
* If x is already an integer, the result is x.
* @param x A numeric expression.
*/
trunc(x: number): number;
/**
* Returns the nearest single precision float representation of a number.
* @param x A numeric expression.
*/
fround(x: number): number;
/**
* Returns an implementation-dependent approximation to the cube root of number.
* @param x A numeric expression.
*/
cbrt(x: number): number;
}
interface NumberConstructor {
/**
* The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1
* that is representable as a Number value, which is approximately:
* 2.2204460492503130808472633361816 x 1016.
*/
readonly EPSILON: number;
/**
* Returns true if passed value is finite.
* Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
isFinite(number: unknown): boolean;
/**
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
isInteger(number: unknown): boolean;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
* number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
isNaN(number: unknown): boolean;
/**
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
isSafeInteger(number: unknown): boolean;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
* a Number value.
* The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 1.
*/
readonly MAX_SAFE_INTEGER: number;
/**
* The value of the smallest integer n such that n and n 1 are both exactly representable as
* a Number value.
* The value of Number.MIN_SAFE_INTEGER is 9007199254740991 ((2^53 1)).
*/
readonly MIN_SAFE_INTEGER: number;
/**
* Converts a string to a floating-point number.
* @param string A string that contains a floating-point number.
*/
parseFloat(string: string): number;
/**
* Converts A string to an integer.
* @param string A string to convert into a number.
* @param radix A value between 2 and 36 that specifies the base of the number in `string`.
* If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.
* All other strings are considered decimal.
*/
parseInt(string: string, radix?: number): number;
}
interface ObjectConstructor {
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source The source object from which to copy properties.
*/
assign<T extends {}, U>(target: T, source: U): T & U;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
*/
assign<T extends {}, U, V>(target: T, source1: U, source2: V): T & U & V;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param source1 The first source object from which to copy properties.
* @param source2 The second source object from which to copy properties.
* @param source3 The third source object from which to copy properties.
*/
assign<T extends {}, U, V, W>(target: T, source1: U, source2: V, source3: W): T & U & V & W;
/**
* Copy the values of all of the enumerable own properties from one or more source objects to a
* target object. Returns the target object.
* @param target The target object to copy to.
* @param sources One or more source objects from which to copy properties
*/
assign(target: object, ...sources: any[]): any;
/**
* Returns an array of all symbol properties found directly on object o.
* @param o Object to retrieve the symbols from.
*/
getOwnPropertySymbols(o: any): symbol[];
/**
* Returns the names of the enumerable string properties and methods of an object.
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
keys(o: {}): string[];
/**
* Returns true if the values are the same value, false otherwise.
* @param value1 The first value.
* @param value2 The second value.
*/
is(value1: any, value2: any): boolean;
/**
* Sets the prototype of a specified object o to object proto or null. Returns the object o.
* @param o The object to change its prototype.
* @param proto The value of the new prototype or null.
*/
setPrototypeOf(o: any, proto: object | null): any;
}
interface ReadonlyArray<T> {
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find<S extends T>(predicate: (value: T, index: number, obj: readonly T[]) => value is S, thisArg?: any): S | undefined;
find(predicate: (value: T, index: number, obj: readonly T[]) => unknown, thisArg?: any): T | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: T, index: number, obj: readonly T[]) => unknown, thisArg?: any): number;
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions & Intl.DateTimeFormatOptions): string;
}
interface RegExp {
/**
* Returns a string indicating the flags of the regular expression in question. This field is read-only.
* The characters in this string are sequenced and concatenated in the following order:
*
* - "g" for global
* - "i" for ignoreCase
* - "m" for multiline
* - "u" for unicode
* - "y" for sticky
*
* If no flags are set, the value is the empty string.
*/
readonly flags: string;
/**
* Returns a Boolean value indicating the state of the sticky flag (y) used with a regular
* expression. Default is false. Read-only.
*/
readonly sticky: boolean;
/**
* Returns a Boolean value indicating the state of the Unicode flag (u) used with a regular
* expression. Default is false. Read-only.
*/
readonly unicode: boolean;
}
interface RegExpConstructor {
new (pattern: RegExp | string, flags?: string): RegExp;
(pattern: RegExp | string, flags?: string): RegExp;
}
interface String {
/**
* Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point
* value of the UTF-16 encoded code point starting at the string element at position pos in
* the String resulting from converting this object to a String.
* If there is no element at that position, the result is undefined.
* If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.
*/
codePointAt(pos: number): number | undefined;
/**
* Returns true if searchString appears as a substring of the result of converting this
* object to a String, at one or more positions that are
* greater than or equal to position; otherwise, returns false.
* @param searchString search string
* @param position If position is undefined, 0 is assumed, so as to search all of the String.
*/
includes(searchString: string, position?: number): boolean;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* endPosition length(this). Otherwise returns false.
*/
endsWith(searchString: string, endPosition?: number): boolean;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form: "NFC" | "NFD" | "NFKC" | "NFKD"): string;
/**
* Returns the String value result of normalizing the string into the normalization form
* named by form as specified in Unicode Standard Annex #15, Unicode Normalization Forms.
* @param form Applicable values: "NFC", "NFD", "NFKC", or "NFKD", If not specified default
* is "NFC"
*/
normalize(form?: string): string;
/**
* Returns a String value that is made from count copies appended together. If count is 0,
* the empty string is returned.
* @param count number of copies to append
*/
repeat(count: number): string;
/**
* Returns true if the sequence of elements of searchString converted to a String is the
* same as the corresponding elements of this object (converted to a String) starting at
* position. Otherwise returns false.
*/
startsWith(searchString: string, position?: number): boolean;
/**
* Returns an `<a>` HTML anchor element and sets the name attribute to the text value
* @deprecated A legacy feature for browser compatibility
* @param name
*/
anchor(name: string): string;
/**
* Returns a `<big>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
big(): string;
/**
* Returns a `<blink>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
blink(): string;
/**
* Returns a `<b>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
bold(): string;
/**
* Returns a `<tt>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
fixed(): string;
/**
* Returns a `<font>` HTML element and sets the color attribute value
* @deprecated A legacy feature for browser compatibility
*/
fontcolor(color: string): string;
/**
* Returns a `<font>` HTML element and sets the size attribute value
* @deprecated A legacy feature for browser compatibility
*/
fontsize(size: number): string;
/**
* Returns a `<font>` HTML element and sets the size attribute value
* @deprecated A legacy feature for browser compatibility
*/
fontsize(size: string): string;
/**
* Returns an `<i>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
italics(): string;
/**
* Returns an `<a>` HTML element and sets the href attribute value
* @deprecated A legacy feature for browser compatibility
*/
link(url: string): string;
/**
* Returns a `<small>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
small(): string;
/**
* Returns a `<strike>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
strike(): string;
/**
* Returns a `<sub>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
sub(): string;
/**
* Returns a `<sup>` HTML element
* @deprecated A legacy feature for browser compatibility
*/
sup(): string;
}
interface StringConstructor {
/**
* Return the String value whose elements are, in order, the elements in the List elements.
* If length is 0, the empty string is returned.
*/
fromCodePoint(...codePoints: number[]): string;
/**
* String.raw is usually used as a tag function of a Tagged Template String. When called as
* such, the first argument will be a well formed template call site object and the rest
* parameter will contain the substitution values. It can also be called directly, for example,
* to interleave strings and values from your own tag function, and in this case the only thing
* it needs from the first argument is the raw property.
* @param template A well-formed template string call site representation.
* @param substitutions A set of substitution values.
*/
raw(template: { raw: readonly string[] | ArrayLike<string>; }, ...substitutions: any[]): string;
}
interface Int8Array<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Uint8Array<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Uint8ClampedArray<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Int16Array<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Uint16Array<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Int32Array<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Uint32Array<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Float32Array<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
interface Float64Array<TArrayBuffer extends ArrayBufferLike> {
toLocaleString(locales: string | string[], options?: Intl.NumberFormatOptions): string;
}
+28
View File
@@ -0,0 +1,28 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es5" />
/// <reference lib="es2015.core" />
/// <reference lib="es2015.collection" />
/// <reference lib="es2015.iterable" />
/// <reference lib="es2015.generator" />
/// <reference lib="es2015.promise" />
/// <reference lib="es2015.proxy" />
/// <reference lib="es2015.reflect" />
/// <reference lib="es2015.symbol" />
/// <reference lib="es2015.symbol.wellknown" />
@@ -0,0 +1,77 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2015.iterable" />
interface Generator<T = unknown, TReturn = any, TNext = any> extends IteratorObject<T, TReturn, TNext> {
// NOTE: 'next' is defined using a tuple to ensure we report the correct assignability errors in all places.
next(...[value]: [] | [TNext]): IteratorResult<T, TReturn>;
return(value: TReturn): IteratorResult<T, TReturn>;
throw(e: any): IteratorResult<T, TReturn>;
[Symbol.iterator](): Generator<T, TReturn, TNext>;
}
interface GeneratorFunction {
/**
* Creates a new Generator object.
* @param args A list of arguments the function accepts.
*/
new (...args: any[]): Generator;
/**
* Creates a new Generator object.
* @param args A list of arguments the function accepts.
*/
(...args: any[]): Generator;
/**
* The length of the arguments.
*/
readonly length: number;
/**
* Returns the name of the function.
*/
readonly name: string;
/**
* A reference to the prototype.
*/
readonly prototype: Generator;
}
interface GeneratorFunctionConstructor {
/**
* Creates a new Generator function.
* @param args A list of arguments the function accepts.
*/
new (...args: string[]): GeneratorFunction;
/**
* Creates a new Generator function.
* @param args A list of arguments the function accepts.
*/
(...args: string[]): GeneratorFunction;
/**
* The length of the arguments.
*/
readonly length: number;
/**
* Returns the name of the function.
*/
readonly name: string;
/**
* A reference to the prototype.
*/
readonly prototype: GeneratorFunction;
}
@@ -0,0 +1,605 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2015.symbol" />
interface SymbolConstructor {
/**
* A method that returns the default iterator for an object. Called by the semantics of the
* for-of statement.
*/
readonly iterator: unique symbol;
}
interface IteratorYieldResult<TYield> {
done?: false;
value: TYield;
}
interface IteratorReturnResult<TReturn> {
done: true;
value: TReturn;
}
type IteratorResult<T, TReturn = any> = IteratorYieldResult<T> | IteratorReturnResult<TReturn>;
interface Iterator<T, TReturn = any, TNext = any> {
// NOTE: 'next' is defined using a tuple to ensure we report the correct assignability errors in all places.
next(...[value]: [] | [TNext]): IteratorResult<T, TReturn>;
return?(value?: TReturn): IteratorResult<T, TReturn>;
throw?(e?: any): IteratorResult<T, TReturn>;
}
interface Iterable<T, TReturn = any, TNext = any> {
[Symbol.iterator](): Iterator<T, TReturn, TNext>;
}
/**
* Describes a user-defined {@link Iterator} that is also iterable.
*/
interface IterableIterator<T, TReturn = any, TNext = any> extends Iterator<T, TReturn, TNext> {
[Symbol.iterator](): IterableIterator<T, TReturn, TNext>;
}
/**
* Describes an {@link Iterator} produced by the runtime that inherits from the intrinsic `Iterator.prototype`.
*/
interface IteratorObject<T, TReturn = unknown, TNext = unknown> extends Iterator<T, TReturn, TNext> {
[Symbol.iterator](): IteratorObject<T, TReturn, TNext>;
}
/**
* Defines the `TReturn` type used for built-in iterators produced by `Array`, `Map`, `Set`, and others.
* This is `undefined` when `strictBuiltInIteratorReturn` is `true`; otherwise, this is `any`.
*/
type BuiltinIteratorReturn = intrinsic;
interface ArrayIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): ArrayIterator<T>;
}
interface Array<T> {
/** Iterator */
[Symbol.iterator](): ArrayIterator<T>;
/**
* Returns an iterable of key, value pairs for every entry in the array
*/
entries(): ArrayIterator<[number, T]>;
/**
* Returns an iterable of keys in the array
*/
keys(): ArrayIterator<number>;
/**
* Returns an iterable of values in the array
*/
values(): ArrayIterator<T>;
}
interface ArrayConstructor {
/**
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
*/
from<T>(iterable: Iterable<T> | ArrayLike<T>): T[];
/**
* Creates an array from an iterable object.
* @param iterable An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T, U>(iterable: Iterable<T> | ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): U[];
}
interface ReadonlyArray<T> {
/** Iterator of values in the array. */
[Symbol.iterator](): ArrayIterator<T>;
/**
* Returns an iterable of key, value pairs for every entry in the array
*/
entries(): ArrayIterator<[number, T]>;
/**
* Returns an iterable of keys in the array
*/
keys(): ArrayIterator<number>;
/**
* Returns an iterable of values in the array
*/
values(): ArrayIterator<T>;
}
interface IArguments {
/** Iterator */
[Symbol.iterator](): ArrayIterator<any>;
}
interface MapIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): MapIterator<T>;
}
interface Map<K, V> {
/** Returns an iterable of entries in the map. */
[Symbol.iterator](): MapIterator<[K, V]>;
/**
* Returns an iterable of key, value pairs for every entry in the map.
*/
entries(): MapIterator<[K, V]>;
/**
* Returns an iterable of keys in the map
*/
keys(): MapIterator<K>;
/**
* Returns an iterable of values in the map
*/
values(): MapIterator<V>;
}
interface ReadonlyMap<K, V> {
/** Returns an iterable of entries in the map. */
[Symbol.iterator](): MapIterator<[K, V]>;
/**
* Returns an iterable of key, value pairs for every entry in the map.
*/
entries(): MapIterator<[K, V]>;
/**
* Returns an iterable of keys in the map
*/
keys(): MapIterator<K>;
/**
* Returns an iterable of values in the map
*/
values(): MapIterator<V>;
}
interface MapConstructor {
new (): Map<any, any>;
new <K, V>(iterable?: Iterable<readonly [K, V]> | null): Map<K, V>;
}
interface WeakMap<K extends WeakKey, V> {}
interface WeakMapConstructor {
new <K extends WeakKey, V>(iterable: Iterable<readonly [K, V]>): WeakMap<K, V>;
}
interface SetIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): SetIterator<T>;
}
interface Set<T> {
/** Iterates over values in the set. */
[Symbol.iterator](): SetIterator<T>;
/**
* Returns an iterable of [v,v] pairs for every value `v` in the set.
*/
entries(): SetIterator<[T, T]>;
/**
* Despite its name, returns an iterable of the values in the set.
*/
keys(): SetIterator<T>;
/**
* Returns an iterable of values in the set.
*/
values(): SetIterator<T>;
}
interface ReadonlySet<T> {
/** Iterates over values in the set. */
[Symbol.iterator](): SetIterator<T>;
/**
* Returns an iterable of [v,v] pairs for every value `v` in the set.
*/
entries(): SetIterator<[T, T]>;
/**
* Despite its name, returns an iterable of the values in the set.
*/
keys(): SetIterator<T>;
/**
* Returns an iterable of values in the set.
*/
values(): SetIterator<T>;
}
interface SetConstructor {
new <T>(iterable?: Iterable<T> | null): Set<T>;
}
interface WeakSet<T extends WeakKey> {}
interface WeakSetConstructor {
new <T extends WeakKey = WeakKey>(iterable: Iterable<T>): WeakSet<T>;
}
interface Promise<T> {}
interface PromiseConstructor {
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An iterable of Promises.
* @returns A new Promise.
*/
all<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>[]>;
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
* or rejected.
* @param values An iterable of Promises.
* @returns A new Promise.
*/
race<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>>;
}
interface StringIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): StringIterator<T>;
}
interface String {
/** Iterator */
[Symbol.iterator](): StringIterator<string>;
}
interface Int8Array<TArrayBuffer extends ArrayBufferLike> {
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): ArrayIterator<number>;
}
interface Int8ArrayConstructor {
new (elements: Iterable<number>): Int8Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
*/
from(elements: Iterable<number>): Int8Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(elements: Iterable<T>, mapfn?: (v: T, k: number) => number, thisArg?: any): Int8Array<ArrayBuffer>;
}
interface Uint8Array<TArrayBuffer extends ArrayBufferLike> {
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): ArrayIterator<number>;
}
interface Uint8ArrayConstructor {
new (elements: Iterable<number>): Uint8Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
*/
from(elements: Iterable<number>): Uint8Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(elements: Iterable<T>, mapfn?: (v: T, k: number) => number, thisArg?: any): Uint8Array<ArrayBuffer>;
}
interface Uint8ClampedArray<TArrayBuffer extends ArrayBufferLike> {
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): ArrayIterator<number>;
}
interface Uint8ClampedArrayConstructor {
new (elements: Iterable<number>): Uint8ClampedArray<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
*/
from(elements: Iterable<number>): Uint8ClampedArray<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(elements: Iterable<T>, mapfn?: (v: T, k: number) => number, thisArg?: any): Uint8ClampedArray<ArrayBuffer>;
}
interface Int16Array<TArrayBuffer extends ArrayBufferLike> {
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): ArrayIterator<number>;
}
interface Int16ArrayConstructor {
new (elements: Iterable<number>): Int16Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
*/
from(elements: Iterable<number>): Int16Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(elements: Iterable<T>, mapfn?: (v: T, k: number) => number, thisArg?: any): Int16Array<ArrayBuffer>;
}
interface Uint16Array<TArrayBuffer extends ArrayBufferLike> {
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): ArrayIterator<number>;
}
interface Uint16ArrayConstructor {
new (elements: Iterable<number>): Uint16Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
*/
from(elements: Iterable<number>): Uint16Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(elements: Iterable<T>, mapfn?: (v: T, k: number) => number, thisArg?: any): Uint16Array<ArrayBuffer>;
}
interface Int32Array<TArrayBuffer extends ArrayBufferLike> {
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): ArrayIterator<number>;
}
interface Int32ArrayConstructor {
new (elements: Iterable<number>): Int32Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
*/
from(elements: Iterable<number>): Int32Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(elements: Iterable<T>, mapfn?: (v: T, k: number) => number, thisArg?: any): Int32Array<ArrayBuffer>;
}
interface Uint32Array<TArrayBuffer extends ArrayBufferLike> {
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): ArrayIterator<number>;
}
interface Uint32ArrayConstructor {
new (elements: Iterable<number>): Uint32Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
*/
from(elements: Iterable<number>): Uint32Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(elements: Iterable<T>, mapfn?: (v: T, k: number) => number, thisArg?: any): Uint32Array<ArrayBuffer>;
}
interface Float32Array<TArrayBuffer extends ArrayBufferLike> {
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): ArrayIterator<number>;
}
interface Float32ArrayConstructor {
new (elements: Iterable<number>): Float32Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
*/
from(elements: Iterable<number>): Float32Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(elements: Iterable<T>, mapfn?: (v: T, k: number) => number, thisArg?: any): Float32Array<ArrayBuffer>;
}
interface Float64Array<TArrayBuffer extends ArrayBufferLike> {
[Symbol.iterator](): ArrayIterator<number>;
/**
* Returns an array of key, value pairs for every entry in the array
*/
entries(): ArrayIterator<[number, number]>;
/**
* Returns an list of keys in the array
*/
keys(): ArrayIterator<number>;
/**
* Returns an list of values in the array
*/
values(): ArrayIterator<number>;
}
interface Float64ArrayConstructor {
new (elements: Iterable<number>): Float64Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
*/
from(elements: Iterable<number>): Float64Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(elements: Iterable<T>, mapfn?: (v: T, k: number) => number, thisArg?: any): Float64Array<ArrayBuffer>;
}
@@ -0,0 +1,81 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface PromiseConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Promise<any>;
/**
* Creates a new Promise.
* @param executor A callback used to initialize the promise. This callback is passed two arguments:
* a resolve callback used to resolve the promise with a value or the result of another promise,
* and a reject callback used to reject the promise with a provided reason or error.
*/
new <T>(executor: (resolve: (value: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
/**
* Creates a Promise that is resolved with an array of results when all of the provided Promises
* resolve, or rejected when any Promise is rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
all<T extends readonly unknown[] | []>(values: T): Promise<{ -readonly [P in keyof T]: Awaited<T[P]>; }>;
// see: lib.es2015.iterable.d.ts
// all<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>[]>;
/**
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
* or rejected.
* @param values An array of Promises.
* @returns A new Promise.
*/
race<T extends readonly unknown[] | []>(values: T): Promise<Awaited<T[number]>>;
// see: lib.es2015.iterable.d.ts
// race<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>>;
/**
* Creates a new rejected promise for the provided reason.
* @param reason The reason the promise was rejected.
* @returns A new rejected Promise.
*/
reject<T = never>(reason?: any): Promise<T>;
/**
* Creates a new resolved promise.
* @returns A resolved promise.
*/
resolve(): Promise<void>;
/**
* Creates a new resolved promise for the provided value.
* @param value A promise.
* @returns A promise whose internal state matches the provided promise.
*/
resolve<T>(value: T): Promise<Awaited<T>>;
/**
* Creates a new resolved promise for the provided value.
* @param value A promise.
* @returns A promise whose internal state matches the provided promise.
*/
resolve<T>(value: T | PromiseLike<T>): Promise<Awaited<T>>;
}
declare var Promise: PromiseConstructor;
+128
View File
@@ -0,0 +1,128 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface ProxyHandler<T extends object> {
/**
* A trap method for a function call.
* @param target The original callable object which is being proxied.
*/
apply?(target: T, thisArg: any, argArray: any[]): any;
/**
* A trap for the `new` operator.
* @param target The original object which is being proxied.
* @param newTarget The constructor that was originally called.
*/
construct?(target: T, argArray: any[], newTarget: Function): object;
/**
* A trap for `Object.defineProperty()`.
* @param target The original object which is being proxied.
* @returns A `Boolean` indicating whether or not the property has been defined.
*/
defineProperty?(target: T, property: string | symbol, attributes: PropertyDescriptor): boolean;
/**
* A trap for the `delete` operator.
* @param target The original object which is being proxied.
* @param p The name or `Symbol` of the property to delete.
* @returns A `Boolean` indicating whether or not the property was deleted.
*/
deleteProperty?(target: T, p: string | symbol): boolean;
/**
* A trap for getting a property value.
* @param target The original object which is being proxied.
* @param p The name or `Symbol` of the property to get.
* @param receiver The proxy or an object that inherits from the proxy.
*/
get?(target: T, p: string | symbol, receiver: any): any;
/**
* A trap for `Object.getOwnPropertyDescriptor()`.
* @param target The original object which is being proxied.
* @param p The name of the property whose description should be retrieved.
*/
getOwnPropertyDescriptor?(target: T, p: string | symbol): PropertyDescriptor | undefined;
/**
* A trap for the `[[GetPrototypeOf]]` internal method.
* @param target The original object which is being proxied.
*/
getPrototypeOf?(target: T): object | null;
/**
* A trap for the `in` operator.
* @param target The original object which is being proxied.
* @param p The name or `Symbol` of the property to check for existence.
*/
has?(target: T, p: string | symbol): boolean;
/**
* A trap for `Object.isExtensible()`.
* @param target The original object which is being proxied.
*/
isExtensible?(target: T): boolean;
/**
* A trap for `Reflect.ownKeys()`.
* @param target The original object which is being proxied.
*/
ownKeys?(target: T): ArrayLike<string | symbol>;
/**
* A trap for `Object.preventExtensions()`.
* @param target The original object which is being proxied.
*/
preventExtensions?(target: T): boolean;
/**
* A trap for setting a property value.
* @param target The original object which is being proxied.
* @param p The name or `Symbol` of the property to set.
* @param receiver The object to which the assignment was originally directed.
* @returns A `Boolean` indicating whether or not the property was set.
*/
set?(target: T, p: string | symbol, newValue: any, receiver: any): boolean;
/**
* A trap for `Object.setPrototypeOf()`.
* @param target The original object which is being proxied.
* @param newPrototype The object's new prototype or `null`.
*/
setPrototypeOf?(target: T, v: object | null): boolean;
}
interface ProxyConstructor {
/**
* Creates a revocable Proxy object.
* @param target A target object to wrap with Proxy.
* @param handler An object whose properties define the behavior of Proxy when an operation is attempted on it.
*/
revocable<T extends object>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
/**
* Creates a Proxy object. The Proxy object allows you to create an object that can be used in place of the
* original object, but which may redefine fundamental Object operations like getting, setting, and defining
* properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs.
* @param target A target object to wrap with Proxy.
* @param handler An object whose properties define the behavior of Proxy when an operation is attempted on it.
*/
new <T extends object>(target: T, handler: ProxyHandler<T>): T;
}
declare var Proxy: ProxyConstructor;
+144
View File
@@ -0,0 +1,144 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare namespace Reflect {
/**
* Calls the function with the specified object as the this value
* and the elements of specified array as the arguments.
* @param target The function to call.
* @param thisArgument The object to be used as the this object.
* @param argumentsList An array of argument values to be passed to the function.
*/
function apply<T, A extends readonly any[], R>(
target: (this: T, ...args: A) => R,
thisArgument: T,
argumentsList: Readonly<A>,
): R;
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
/**
* Constructs the target with the elements of specified array as the arguments
* and the specified constructor as the `new.target` value.
* @param target The constructor to invoke.
* @param argumentsList An array of argument values to be passed to the constructor.
* @param newTarget The constructor to be used as the `new.target` object.
*/
function construct<A extends readonly any[], R>(
target: new (...args: A) => R,
argumentsList: Readonly<A>,
newTarget?: new (...args: any) => any,
): R;
function construct(target: Function, argumentsList: ArrayLike<any>, newTarget?: Function): any;
/**
* Adds a property to an object, or modifies attributes of an existing property.
* @param target Object on which to add or modify the property. This can be a native JavaScript object
* (that is, a user-defined object or a built in object) or a DOM object.
* @param propertyKey The property name.
* @param attributes Descriptor for the property. It can be for a data property or an accessor property.
*/
function defineProperty(target: object, propertyKey: PropertyKey, attributes: PropertyDescriptor & ThisType<any>): boolean;
/**
* Removes a property from an object, equivalent to `delete target[propertyKey]`,
* except it won't throw if `target[propertyKey]` is non-configurable.
* @param target Object from which to remove the own property.
* @param propertyKey The property name.
*/
function deleteProperty(target: object, propertyKey: PropertyKey): boolean;
/**
* Gets the property of target, equivalent to `target[propertyKey]` when `receiver === target`.
* @param target Object that contains the property on itself or in its prototype chain.
* @param propertyKey The property name.
* @param receiver The reference to use as the `this` value in the getter function,
* if `target[propertyKey]` is an accessor property.
*/
function get<T extends object, P extends PropertyKey>(
target: T,
propertyKey: P,
receiver?: unknown,
): P extends keyof T ? T[P] : any;
/**
* Gets the own property descriptor of the specified object.
* An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype.
* @param target Object that contains the property.
* @param propertyKey The property name.
*/
function getOwnPropertyDescriptor<T extends object, P extends PropertyKey>(
target: T,
propertyKey: P,
): TypedPropertyDescriptor<P extends keyof T ? T[P] : any> | undefined;
/**
* Returns the prototype of an object.
* @param target The object that references the prototype.
*/
function getPrototypeOf(target: object): object | null;
/**
* Equivalent to `propertyKey in target`.
* @param target Object that contains the property on itself or in its prototype chain.
* @param propertyKey Name of the property.
*/
function has(target: object, propertyKey: PropertyKey): boolean;
/**
* Returns a value that indicates whether new properties can be added to an object.
* @param target Object to test.
*/
function isExtensible(target: object): boolean;
/**
* Returns the string and symbol keys of the own properties of an object. The own properties of an object
* are those that are defined directly on that object, and are not inherited from the object's prototype.
* @param target Object that contains the own properties.
*/
function ownKeys(target: object): (string | symbol)[];
/**
* Prevents the addition of new properties to an object.
* @param target Object to make non-extensible.
* @return Whether the object has been made non-extensible.
*/
function preventExtensions(target: object): boolean;
/**
* Sets the property of target, equivalent to `target[propertyKey] = value` when `receiver === target`.
* @param target Object that contains the property on itself or in its prototype chain.
* @param propertyKey Name of the property.
* @param receiver The reference to use as the `this` value in the setter function,
* if `target[propertyKey]` is an accessor property.
*/
function set<T extends object, P extends PropertyKey>(
target: T,
propertyKey: P,
value: P extends keyof T ? T[P] : any,
receiver?: any,
): boolean;
function set(target: object, propertyKey: PropertyKey, value: any, receiver?: any): boolean;
/**
* Sets the prototype of a specified object o to object proto or null.
* @param target The object to change its prototype.
* @param proto The value of the new prototype or null.
* @return Whether setting the prototype was successful.
*/
function setPrototypeOf(target: object, proto: object | null): boolean;
}
+46
View File
@@ -0,0 +1,46 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface SymbolConstructor {
/**
* A reference to the prototype.
*/
readonly prototype: Symbol;
/**
* Returns a new unique Symbol value.
* @param description Description of the new Symbol object.
*/
(description?: string | number): symbol;
/**
* Returns a Symbol object from the global symbol registry matching the given key if found.
* Otherwise, returns a new symbol with this key.
* @param key key to search for.
*/
for(key: string): symbol;
/**
* Returns a key from the global symbol registry matching the given Symbol if found.
* Otherwise, returns a undefined.
* @param sym Symbol to find the key for.
*/
keyFor(sym: symbol): string | undefined;
}
declare var Symbol: SymbolConstructor;
@@ -0,0 +1,326 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2015.symbol" />
interface SymbolConstructor {
/**
* A method that determines if a constructor object recognizes an object as one of the
* constructors instances. Called by the semantics of the instanceof operator.
*/
readonly hasInstance: unique symbol;
/**
* A Boolean value that if true indicates that an object should flatten to its array elements
* by Array.prototype.concat.
*/
readonly isConcatSpreadable: unique symbol;
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.match method.
*/
readonly match: unique symbol;
/**
* A regular expression method that replaces matched substrings of a string. Called by the
* String.prototype.replace method.
*/
readonly replace: unique symbol;
/**
* A regular expression method that returns the index within a string that matches the
* regular expression. Called by the String.prototype.search method.
*/
readonly search: unique symbol;
/**
* A function valued property that is the constructor function that is used to create
* derived objects.
*/
readonly species: unique symbol;
/**
* A regular expression method that splits a string at the indices that match the regular
* expression. Called by the String.prototype.split method.
*/
readonly split: unique symbol;
/**
* A method that converts an object to a corresponding primitive value.
* Called by the ToPrimitive abstract operation.
*/
readonly toPrimitive: unique symbol;
/**
* A String value that is used in the creation of the default string description of an object.
* Called by the built-in method Object.prototype.toString.
*/
readonly toStringTag: unique symbol;
/**
* An Object whose truthy properties are properties that are excluded from the 'with'
* environment bindings of the associated objects.
*/
readonly unscopables: unique symbol;
}
interface Symbol {
/**
* Converts a Symbol object to a symbol.
*/
[Symbol.toPrimitive](hint: string): symbol;
readonly [Symbol.toStringTag]: string;
}
interface Array<T> {
/**
* Is an object whose properties have the value 'true'
* when they will be absent when used in a 'with' statement.
*/
readonly [Symbol.unscopables]: {
[K in keyof any[]]?: boolean;
};
}
interface ReadonlyArray<T> {
/**
* Is an object whose properties have the value 'true'
* when they will be absent when used in a 'with' statement.
*/
readonly [Symbol.unscopables]: {
[K in keyof readonly any[]]?: boolean;
};
}
interface Date {
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "default"): string;
/**
* Converts a Date object to a string.
*/
[Symbol.toPrimitive](hint: "string"): string;
/**
* Converts a Date object to a number.
*/
[Symbol.toPrimitive](hint: "number"): number;
/**
* Converts a Date object to a string or number.
*
* @param hint The strings "number", "string", or "default" to specify what primitive to return.
*
* @throws {TypeError} If 'hint' was given something other than "number", "string", or "default".
* @returns A number if 'hint' was "number", a string if 'hint' was "string" or "default".
*/
[Symbol.toPrimitive](hint: string): string | number;
}
interface Map<K, V> {
readonly [Symbol.toStringTag]: string;
}
interface WeakMap<K extends WeakKey, V> {
readonly [Symbol.toStringTag]: string;
}
interface Set<T> {
readonly [Symbol.toStringTag]: string;
}
interface WeakSet<T extends WeakKey> {
readonly [Symbol.toStringTag]: string;
}
interface JSON {
readonly [Symbol.toStringTag]: string;
}
interface Function {
/**
* Determines whether the given value inherits from this function if this function was used
* as a constructor function.
*
* A constructor function can control which objects are recognized as its instances by
* 'instanceof' by overriding this method.
*/
[Symbol.hasInstance](value: any): boolean;
}
interface GeneratorFunction {
readonly [Symbol.toStringTag]: string;
}
interface Math {
readonly [Symbol.toStringTag]: string;
}
interface Promise<T> {
readonly [Symbol.toStringTag]: string;
}
interface PromiseConstructor {
readonly [Symbol.species]: PromiseConstructor;
}
interface RegExp {
/**
* Matches a string with this regular expression, and returns an array containing the results of
* that search.
* @param string A string to search within.
*/
[Symbol.match](string: string): RegExpMatchArray | null;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replaceValue A String object or string literal containing the text to replace for every
* successful match of this regular expression.
*/
[Symbol.replace](string: string, replaceValue: string): string;
/**
* Replaces text in a string, using this regular expression.
* @param string A String object or string literal whose contents matching against
* this regular expression will be replaced
* @param replacer A function that returns the replacement text.
*/
[Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the position beginning first substring match in a regular expression search
* using this regular expression.
*
* @param string The string to search within.
*/
[Symbol.search](string: string): number;
/**
* Returns an array of substrings that were delimited by strings in the original input that
* match against this regular expression.
*
* If the regular expression contains capturing parentheses, then each time this
* regular expression matches, the results (including any undefined results) of the
* capturing parentheses are spliced.
*
* @param string string value to split
* @param limit if not undefined, the output array is truncated so that it contains no more
* than 'limit' elements.
*/
[Symbol.split](string: string, limit?: number): string[];
}
interface RegExpConstructor {
readonly [Symbol.species]: RegExpConstructor;
}
interface String {
/**
* Matches a string or an object that supports being matched against, and returns an array
* containing the results of that search, or null if no matches are found.
* @param matcher An object that supports being matched against.
*/
match(matcher: { [Symbol.match](string: string): RegExpMatchArray | null; }): RegExpMatchArray | null;
/**
* Passes a string and {@linkcode replaceValue} to the `[Symbol.replace]` method on {@linkcode searchValue}. This method is expected to implement its own replacement algorithm.
* @param searchValue An object that supports searching for and replacing matches within a string.
* @param replaceValue The replacement text.
*/
replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string;
/**
* Replaces text in a string, using an object that supports replacement within a string.
* @param searchValue A object can search for and replace matches within a string.
* @param replacer A function that returns the replacement text.
*/
replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string;
/**
* Finds the first substring match in a regular expression search.
* @param searcher An object which supports searching within a string.
*/
search(searcher: { [Symbol.search](string: string): number; }): number;
/**
* Split a string into substrings using the specified separator and return them as an array.
* @param splitter An object that can split a string.
* @param limit A value used to limit the number of elements returned in the array.
*/
split(splitter: { [Symbol.split](string: string, limit?: number): string[]; }, limit?: number): string[];
}
interface ArrayBuffer {
readonly [Symbol.toStringTag]: "ArrayBuffer";
}
interface DataView<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: string;
}
interface Int8Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Int8Array";
}
interface Uint8Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Uint8Array";
}
interface Uint8ClampedArray<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Uint8ClampedArray";
}
interface Int16Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Int16Array";
}
interface Uint16Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Uint16Array";
}
interface Int32Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Int32Array";
}
interface Uint32Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Uint32Array";
}
interface Float32Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Float32Array";
}
interface Float64Array<TArrayBuffer extends ArrayBufferLike> {
readonly [Symbol.toStringTag]: "Float64Array";
}
interface ArrayConstructor {
readonly [Symbol.species]: ArrayConstructor;
}
interface MapConstructor {
readonly [Symbol.species]: MapConstructor;
}
interface SetConstructor {
readonly [Symbol.species]: SetConstructor;
}
interface ArrayBufferConstructor {
readonly [Symbol.species]: ArrayBufferConstructor;
}
@@ -0,0 +1,116 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Array<T> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: T, fromIndex?: number): boolean;
}
interface ReadonlyArray<T> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: T, fromIndex?: number): boolean;
}
interface Int8Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint8Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint8ClampedArray<TArrayBuffer extends ArrayBufferLike> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Int16Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint16Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Int32Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Uint32Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Float32Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
interface Float64Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: number, fromIndex?: number): boolean;
}
+21
View File
@@ -0,0 +1,21 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2015" />
/// <reference lib="es2016.array.include" />
/// <reference lib="es2016.intl" />
+23
View File
@@ -0,0 +1,23 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2016" />
/// <reference lib="dom" />
/// <reference lib="webworker.importscripts" />
/// <reference lib="scripthost" />
/// <reference lib="dom.iterable" />
+31
View File
@@ -0,0 +1,31 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare namespace Intl {
/**
* The `Intl.getCanonicalLocales()` method returns an array containing
* the canonical locale names. Duplicates will be omitted and elements
* will be validated as structurally valid language tags.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/getCanonicalLocales)
*
* @param locale A list of String values for which to get the canonical locale names
* @returns An array containing the canonical and validated locale names.
*/
function getCanonicalLocales(locale?: string | readonly string[]): string[];
}
@@ -0,0 +1,21 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface ArrayBufferConstructor {
new (): ArrayBuffer;
}
+26
View File
@@ -0,0 +1,26 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2016" />
/// <reference lib="es2017.arraybuffer" />
/// <reference lib="es2017.date" />
/// <reference lib="es2017.intl" />
/// <reference lib="es2017.object" />
/// <reference lib="es2017.sharedmemory" />
/// <reference lib="es2017.string" />
/// <reference lib="es2017.typedarrays" />
+31
View File
@@ -0,0 +1,31 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface DateConstructor {
/**
* Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date.
* @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year.
* @param monthIndex The month as a number between 0 and 11 (January to December).
* @param date The date as a number between 1 and 31.
* @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour.
* @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes.
* @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds.
* @param ms A number from 0 to 999 that specifies the milliseconds.
*/
UTC(year: number, monthIndex?: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number;
}
+23
View File
@@ -0,0 +1,23 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2017" />
/// <reference lib="dom" />
/// <reference lib="webworker.importscripts" />
/// <reference lib="scripthost" />
/// <reference lib="dom.iterable" />
+44
View File
@@ -0,0 +1,44 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare namespace Intl {
interface DateTimeFormatPartTypesRegistry {
day: any;
dayPeriod: any;
era: any;
hour: any;
literal: any;
minute: any;
month: any;
second: any;
timeZoneName: any;
weekday: any;
year: any;
}
type DateTimeFormatPartTypes = keyof DateTimeFormatPartTypesRegistry;
interface DateTimeFormatPart {
type: DateTimeFormatPartTypes;
value: string;
}
interface DateTimeFormat {
formatToParts(date?: Date | number): DateTimeFormatPart[];
}
}
+49
View File
@@ -0,0 +1,49 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface ObjectConstructor {
/**
* Returns an array of values of the enumerable own properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
values<T>(o: { [s: string]: T; } | ArrayLike<T>): T[];
/**
* Returns an array of values of the enumerable own properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
values(o: {}): any[];
/**
* Returns an array of key/values of the enumerable own properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries<T>(o: { [s: string]: T; } | ArrayLike<T>): [string, T][];
/**
* Returns an array of key/values of the enumerable own properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries(o: {}): [string, any][];
/**
* Returns an object containing all own property descriptors of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
getOwnPropertyDescriptors<T>(o: T): { [P in keyof T]: TypedPropertyDescriptor<T[P]>; } & { [x: string]: PropertyDescriptor; };
}
@@ -0,0 +1,135 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2015.symbol" />
/// <reference lib="es2015.symbol.wellknown" />
interface SharedArrayBuffer {
/**
* Read-only. The length of the ArrayBuffer (in bytes).
*/
readonly byteLength: number;
/**
* Returns a section of an SharedArrayBuffer.
*/
slice(begin?: number, end?: number): SharedArrayBuffer;
readonly [Symbol.toStringTag]: "SharedArrayBuffer";
}
interface SharedArrayBufferConstructor {
readonly prototype: SharedArrayBuffer;
new (byteLength?: number): SharedArrayBuffer;
readonly [Symbol.species]: SharedArrayBufferConstructor;
}
declare var SharedArrayBuffer: SharedArrayBufferConstructor;
interface ArrayBufferTypes {
SharedArrayBuffer: SharedArrayBuffer;
}
interface Atomics {
/**
* Adds a value to the value at the given position in the array, returning the original value.
* Until this atomic operation completes, any other read or write operation against the array
* will block.
*/
add(typedArray: Int8Array<ArrayBufferLike> | Uint8Array<ArrayBufferLike> | Int16Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Int32Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike>, index: number, value: number): number;
/**
* Stores the bitwise AND of a value with the value at the given position in the array,
* returning the original value. Until this atomic operation completes, any other read or
* write operation against the array will block.
*/
and(typedArray: Int8Array<ArrayBufferLike> | Uint8Array<ArrayBufferLike> | Int16Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Int32Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike>, index: number, value: number): number;
/**
* Replaces the value at the given position in the array if the original value equals the given
* expected value, returning the original value. Until this atomic operation completes, any
* other read or write operation against the array will block.
*/
compareExchange(typedArray: Int8Array<ArrayBufferLike> | Uint8Array<ArrayBufferLike> | Int16Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Int32Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike>, index: number, expectedValue: number, replacementValue: number): number;
/**
* Replaces the value at the given position in the array, returning the original value. Until
* this atomic operation completes, any other read or write operation against the array will
* block.
*/
exchange(typedArray: Int8Array<ArrayBufferLike> | Uint8Array<ArrayBufferLike> | Int16Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Int32Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike>, index: number, value: number): number;
/**
* Returns a value indicating whether high-performance algorithms can use atomic operations
* (`true`) or must use locks (`false`) for the given number of bytes-per-element of a typed
* array.
*/
isLockFree(size: number): boolean;
/**
* Returns the value at the given position in the array. Until this atomic operation completes,
* any other read or write operation against the array will block.
*/
load(typedArray: Int8Array<ArrayBufferLike> | Uint8Array<ArrayBufferLike> | Int16Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Int32Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike>, index: number): number;
/**
* Stores the bitwise OR of a value with the value at the given position in the array,
* returning the original value. Until this atomic operation completes, any other read or write
* operation against the array will block.
*/
or(typedArray: Int8Array<ArrayBufferLike> | Uint8Array<ArrayBufferLike> | Int16Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Int32Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike>, index: number, value: number): number;
/**
* Stores a value at the given position in the array, returning the new value. Until this
* atomic operation completes, any other read or write operation against the array will block.
*/
store(typedArray: Int8Array<ArrayBufferLike> | Uint8Array<ArrayBufferLike> | Int16Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Int32Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike>, index: number, value: number): number;
/**
* Subtracts a value from the value at the given position in the array, returning the original
* value. Until this atomic operation completes, any other read or write operation against the
* array will block.
*/
sub(typedArray: Int8Array<ArrayBufferLike> | Uint8Array<ArrayBufferLike> | Int16Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Int32Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike>, index: number, value: number): number;
/**
* If the value at the given position in the array is equal to the provided value, the current
* agent is put to sleep causing execution to suspend until the timeout expires (returning
* `"timed-out"`) or until the agent is awoken (returning `"ok"`); otherwise, returns
* `"not-equal"`.
*/
wait(typedArray: Int32Array<ArrayBufferLike>, index: number, value: number, timeout?: number): "ok" | "not-equal" | "timed-out";
/**
* Wakes up sleeping agents that are waiting on the given index of the array, returning the
* number of agents that were awoken.
* @param typedArray A shared Int32Array<ArrayBufferLike>.
* @param index The position in the typedArray to wake up on.
* @param count The number of sleeping agents to notify. Defaults to +Infinity.
*/
notify(typedArray: Int32Array<ArrayBufferLike>, index: number, count?: number): number;
/**
* Stores the bitwise XOR of a value with the value at the given position in the array,
* returning the original value. Until this atomic operation completes, any other read or write
* operation against the array will block.
*/
xor(typedArray: Int8Array<ArrayBufferLike> | Uint8Array<ArrayBufferLike> | Int16Array<ArrayBufferLike> | Uint16Array<ArrayBufferLike> | Int32Array<ArrayBufferLike> | Uint32Array<ArrayBufferLike>, index: number, value: number): number;
readonly [Symbol.toStringTag]: "Atomics";
}
declare var Atomics: Atomics;
+45
View File
@@ -0,0 +1,45 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface String {
/**
* Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length.
* The padding is applied from the start (left) of the current string.
*
* @param maxLength The length of the resulting string once the current string has been padded.
* If this parameter is smaller than the current string's length, the current string will be returned as it is.
*
* @param fillString The string to pad the current string with.
* If this string is too long, it will be truncated and the left-most part will be applied.
* The default value for this parameter is " " (U+0020).
*/
padStart(maxLength: number, fillString?: string): string;
/**
* Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length.
* The padding is applied from the end (right) of the current string.
*
* @param maxLength The length of the resulting string once the current string has been padded.
* If this parameter is smaller than the current string's length, the current string will be returned as it is.
*
* @param fillString The string to pad the current string with.
* If this string is too long, it will be truncated and the left-most part will be applied.
* The default value for this parameter is " " (U+0020).
*/
padEnd(maxLength: number, fillString?: string): string;
}
@@ -0,0 +1,53 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Int8ArrayConstructor {
new (): Int8Array<ArrayBuffer>;
}
interface Uint8ArrayConstructor {
new (): Uint8Array<ArrayBuffer>;
}
interface Uint8ClampedArrayConstructor {
new (): Uint8ClampedArray<ArrayBuffer>;
}
interface Int16ArrayConstructor {
new (): Int16Array<ArrayBuffer>;
}
interface Uint16ArrayConstructor {
new (): Uint16Array<ArrayBuffer>;
}
interface Int32ArrayConstructor {
new (): Int32Array<ArrayBuffer>;
}
interface Uint32ArrayConstructor {
new (): Uint32Array<ArrayBuffer>;
}
interface Float32ArrayConstructor {
new (): Float32Array<ArrayBuffer>;
}
interface Float64ArrayConstructor {
new (): Float64Array<ArrayBuffer>;
}
@@ -0,0 +1,77 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2018.asynciterable" />
interface AsyncGenerator<T = unknown, TReturn = any, TNext = any> extends AsyncIteratorObject<T, TReturn, TNext> {
// NOTE: 'next' is defined using a tuple to ensure we report the correct assignability errors in all places.
next(...[value]: [] | [TNext]): Promise<IteratorResult<T, TReturn>>;
return(value: TReturn | PromiseLike<TReturn>): Promise<IteratorResult<T, TReturn>>;
throw(e: any): Promise<IteratorResult<T, TReturn>>;
[Symbol.asyncIterator](): AsyncGenerator<T, TReturn, TNext>;
}
interface AsyncGeneratorFunction {
/**
* Creates a new AsyncGenerator object.
* @param args A list of arguments the function accepts.
*/
new (...args: any[]): AsyncGenerator;
/**
* Creates a new AsyncGenerator object.
* @param args A list of arguments the function accepts.
*/
(...args: any[]): AsyncGenerator;
/**
* The length of the arguments.
*/
readonly length: number;
/**
* Returns the name of the function.
*/
readonly name: string;
/**
* A reference to the prototype.
*/
readonly prototype: AsyncGenerator;
}
interface AsyncGeneratorFunctionConstructor {
/**
* Creates a new AsyncGenerator function.
* @param args A list of arguments the function accepts.
*/
new (...args: string[]): AsyncGeneratorFunction;
/**
* Creates a new AsyncGenerator function.
* @param args A list of arguments the function accepts.
*/
(...args: string[]): AsyncGeneratorFunction;
/**
* The length of the arguments.
*/
readonly length: number;
/**
* Returns the name of the function.
*/
readonly name: string;
/**
* A reference to the prototype.
*/
readonly prototype: AsyncGeneratorFunction;
}
@@ -0,0 +1,53 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2015.symbol" />
/// <reference lib="es2015.iterable" />
interface SymbolConstructor {
/**
* A method that returns the default async iterator for an object. Called by the semantics of
* the for-await-of statement.
*/
readonly asyncIterator: unique symbol;
}
interface AsyncIterator<T, TReturn = any, TNext = any> {
// NOTE: 'next' is defined using a tuple to ensure we report the correct assignability errors in all places.
next(...[value]: [] | [TNext]): Promise<IteratorResult<T, TReturn>>;
return?(value?: TReturn | PromiseLike<TReturn>): Promise<IteratorResult<T, TReturn>>;
throw?(e?: any): Promise<IteratorResult<T, TReturn>>;
}
interface AsyncIterable<T, TReturn = any, TNext = any> {
[Symbol.asyncIterator](): AsyncIterator<T, TReturn, TNext>;
}
/**
* Describes a user-defined {@link AsyncIterator} that is also async iterable.
*/
interface AsyncIterableIterator<T, TReturn = any, TNext = any> extends AsyncIterator<T, TReturn, TNext> {
[Symbol.asyncIterator](): AsyncIterableIterator<T, TReturn, TNext>;
}
/**
* Describes an {@link AsyncIterator} produced by the runtime that inherits from the intrinsic `AsyncIterator.prototype`.
*/
interface AsyncIteratorObject<T, TReturn = unknown, TNext = unknown> extends AsyncIterator<T, TReturn, TNext> {
[Symbol.asyncIterator](): AsyncIteratorObject<T, TReturn, TNext>;
}
+24
View File
@@ -0,0 +1,24 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2017" />
/// <reference lib="es2018.asynciterable" />
/// <reference lib="es2018.asyncgenerator" />
/// <reference lib="es2018.promise" />
/// <reference lib="es2018.regexp" />
/// <reference lib="es2018.intl" />
+24
View File
@@ -0,0 +1,24 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2018" />
/// <reference lib="dom" />
/// <reference lib="webworker.importscripts" />
/// <reference lib="scripthost" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />
+83
View File
@@ -0,0 +1,83 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare namespace Intl {
// http://cldr.unicode.org/index/cldr-spec/plural-rules#TOC-Determining-Plural-Categories
type LDMLPluralRule = "zero" | "one" | "two" | "few" | "many" | "other";
type PluralRuleType = "cardinal" | "ordinal";
interface PluralRulesOptions {
localeMatcher?: "lookup" | "best fit" | undefined;
type?: PluralRuleType | undefined;
minimumIntegerDigits?: number | undefined;
minimumFractionDigits?: number | undefined;
maximumFractionDigits?: number | undefined;
minimumSignificantDigits?: number | undefined;
maximumSignificantDigits?: number | undefined;
}
interface ResolvedPluralRulesOptions {
locale: string;
pluralCategories: LDMLPluralRule[];
type: PluralRuleType;
minimumIntegerDigits: number;
minimumFractionDigits: number;
maximumFractionDigits: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
}
interface PluralRules {
resolvedOptions(): ResolvedPluralRulesOptions;
select(n: number): LDMLPluralRule;
}
interface PluralRulesConstructor {
new (locales?: string | readonly string[], options?: PluralRulesOptions): PluralRules;
(locales?: string | readonly string[], options?: PluralRulesOptions): PluralRules;
supportedLocalesOf(locales: string | readonly string[], options?: { localeMatcher?: "lookup" | "best fit"; }): string[];
}
const PluralRules: PluralRulesConstructor;
interface NumberFormatPartTypeRegistry {
literal: never;
nan: never;
infinity: never;
percent: never;
integer: never;
group: never;
decimal: never;
fraction: never;
plusSign: never;
minusSign: never;
percentSign: never;
currency: never;
}
type NumberFormatPartTypes = keyof NumberFormatPartTypeRegistry;
interface NumberFormatPart {
type: NumberFormatPartTypes;
value: string;
}
interface NumberFormat {
formatToParts(number?: number | bigint): NumberFormatPart[];
}
}
@@ -0,0 +1,30 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/**
* Represents the completion of an asynchronous operation
*/
interface Promise<T> {
/**
* Attaches a callback that is invoked when the Promise is settled (fulfilled or rejected). The
* resolved value cannot be modified from the callback.
* @param onfinally The callback to execute when the Promise is settled (fulfilled or rejected).
* @returns A Promise for the completion of the callback.
*/
finally(onfinally?: (() => void) | undefined | null): Promise<T>;
}
+37
View File
@@ -0,0 +1,37 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface RegExpMatchArray {
groups?: {
[key: string]: string;
};
}
interface RegExpExecArray {
groups?: {
[key: string]: string;
};
}
interface RegExp {
/**
* Returns a Boolean value indicating the state of the dotAll flag (s) used with a regular expression.
* Default is false. Read-only.
*/
readonly dotAll: boolean;
}
+79
View File
@@ -0,0 +1,79 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
type FlatArray<Arr, Depth extends number> = {
done: Arr;
recur: Arr extends ReadonlyArray<infer InnerArr> ? FlatArray<InnerArr, [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20][Depth]>
: Arr;
}[Depth extends -1 ? "done" : "recur"];
interface ReadonlyArray<T> {
/**
* Calls a defined callback function on each element of an array. Then, flattens the result into
* a new array.
* This is identical to a map followed by flat with depth 1.
*
* @param callback A function that accepts up to three arguments. The flatMap method calls the
* callback function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callback function. If
* thisArg is omitted, undefined is used as the this value.
*/
flatMap<U, This = undefined>(
callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray<U>,
thisArg?: This,
): U[];
/**
* Returns a new array with all sub-array elements concatenated into it recursively up to the
* specified depth.
*
* @param depth The maximum recursion depth
*/
flat<A, D extends number = 1>(
this: A,
depth?: D,
): FlatArray<A, D>[];
}
interface Array<T> {
/**
* Calls a defined callback function on each element of an array. Then, flattens the result into
* a new array.
* This is identical to a map followed by flat with depth 1.
*
* @param callback A function that accepts up to three arguments. The flatMap method calls the
* callback function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callback function. If
* thisArg is omitted, undefined is used as the this value.
*/
flatMap<U, This = undefined>(
callback: (this: This, value: T, index: number, array: T[]) => U | ReadonlyArray<U>,
thisArg?: This,
): U[];
/**
* Returns a new array with all sub-array elements concatenated into it recursively up to the
* specified depth.
*
* @param depth The maximum recursion depth
*/
flat<A, D extends number = 1>(
this: A,
depth?: D,
): FlatArray<A, D>[];
}
+24
View File
@@ -0,0 +1,24 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2018" />
/// <reference lib="es2019.array" />
/// <reference lib="es2019.object" />
/// <reference lib="es2019.string" />
/// <reference lib="es2019.symbol" />
/// <reference lib="es2019.intl" />
+24
View File
@@ -0,0 +1,24 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2019" />
/// <reference lib="dom" />
/// <reference lib="webworker.importscripts" />
/// <reference lib="scripthost" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />
+23
View File
@@ -0,0 +1,23 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare namespace Intl {
interface DateTimeFormatPartTypesRegistry {
unknown: never;
}
}
+33
View File
@@ -0,0 +1,33 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2015.iterable" />
interface ObjectConstructor {
/**
* Returns an object created by key-value entries for properties and methods
* @param entries An iterable object that contains key-value entries for properties and methods.
*/
fromEntries<T = any>(entries: Iterable<readonly [PropertyKey, T]>): { [k: string]: T; };
/**
* Returns an object created by key-value entries for properties and methods
* @param entries An iterable object that contains key-value entries for properties and methods.
*/
fromEntries(entries: Iterable<readonly any[]>): any;
}
+37
View File
@@ -0,0 +1,37 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface String {
/** Removes the trailing white space and line terminator characters from a string. */
trimEnd(): string;
/** Removes the leading white space and line terminator characters from a string. */
trimStart(): string;
/**
* Removes the leading white space and line terminator characters from a string.
* @deprecated A legacy feature for browser compatibility. Use `trimStart` instead
*/
trimLeft(): string;
/**
* Removes the trailing white space and line terminator characters from a string.
* @deprecated A legacy feature for browser compatibility. Use `trimEnd` instead
*/
trimRight(): string;
}
+24
View File
@@ -0,0 +1,24 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Symbol {
/**
* Expose the [[Description]] internal slot of a symbol directly.
*/
readonly description: string | undefined;
}
+765
View File
@@ -0,0 +1,765 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2020.intl" />
interface BigIntToLocaleStringOptions {
/**
* The locale matching algorithm to use.The default is "best fit". For information about this option, see the {@link https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation Intl page}.
*/
localeMatcher?: string;
/**
* The formatting style to use , the default is "decimal".
*/
style?: string;
numberingSystem?: string;
/**
* The unit to use in unit formatting, Possible values are core unit identifiers, defined in UTS #35, Part 2, Section 6. A subset of units from the full list was selected for use in ECMAScript. Pairs of simple units can be concatenated with "-per-" to make a compound unit. There is no default value; if the style is "unit", the unit property must be provided.
*/
unit?: string;
/**
* The unit formatting style to use in unit formatting, the defaults is "short".
*/
unitDisplay?: string;
/**
* The currency to use in currency formatting. Possible values are the ISO 4217 currency codes, such as "USD" for the US dollar, "EUR" for the euro, or "CNY" for the Chinese RMB — see the Current currency & funds code list. There is no default value; if the style is "currency", the currency property must be provided. It is only used when [[Style]] has the value "currency".
*/
currency?: string;
/**
* How to display the currency in currency formatting. It is only used when [[Style]] has the value "currency". The default is "symbol".
*
* "symbol" to use a localized currency symbol such as €,
*
* "code" to use the ISO currency code,
*
* "name" to use a localized currency name such as "dollar"
*/
currencyDisplay?: string;
/**
* Whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators. The default is true.
*/
useGrouping?: boolean;
/**
* The minimum number of integer digits to use. Possible values are from 1 to 21; the default is 1.
*/
minimumIntegerDigits?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21;
/**
* The minimum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number and percent formatting is 0; the default for currency formatting is the number of minor unit digits provided by the {@link http://www.currency-iso.org/en/home/tables/table-a1.html ISO 4217 currency codes list} (2 if the list doesn't provide that information).
*/
minimumFractionDigits?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20;
/**
* The maximum number of fraction digits to use. Possible values are from 0 to 20; the default for plain number formatting is the larger of minimumFractionDigits and 3; the default for currency formatting is the larger of minimumFractionDigits and the number of minor unit digits provided by the {@link http://www.currency-iso.org/en/home/tables/table-a1.html ISO 4217 currency codes list} (2 if the list doesn't provide that information); the default for percent formatting is the larger of minimumFractionDigits and 0.
*/
maximumFractionDigits?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20;
/**
* The minimum number of significant digits to use. Possible values are from 1 to 21; the default is 1.
*/
minimumSignificantDigits?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21;
/**
* The maximum number of significant digits to use. Possible values are from 1 to 21; the default is 21.
*/
maximumSignificantDigits?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21;
/**
* The formatting that should be displayed for the number, the defaults is "standard"
*
* "standard" plain number formatting
*
* "scientific" return the order-of-magnitude for formatted number.
*
* "engineering" return the exponent of ten when divisible by three
*
* "compact" string representing exponent, defaults is using the "short" form
*/
notation?: string;
/**
* used only when notation is "compact"
*/
compactDisplay?: string;
}
interface BigInt {
/**
* Returns a string representation of an object.
* @param radix Specifies a radix for converting numeric values to strings.
*/
toString(radix?: number): string;
/** Returns a string representation appropriate to the host environment's current locale. */
toLocaleString(locales?: Intl.LocalesArgument, options?: BigIntToLocaleStringOptions): string;
/** Returns the primitive value of the specified object. */
valueOf(): bigint;
readonly [Symbol.toStringTag]: "BigInt";
}
interface BigIntConstructor {
(value: bigint | boolean | number | string): bigint;
readonly prototype: BigInt;
/**
* Interprets the low bits of a BigInt as a 2's-complement signed integer.
* All higher bits are discarded.
* @param bits The number of low bits to use
* @param int The BigInt whose bits to extract
*/
asIntN(bits: number, int: bigint): bigint;
/**
* Interprets the low bits of a BigInt as an unsigned integer.
* All higher bits are discarded.
* @param bits The number of low bits to use
* @param int The BigInt whose bits to extract
*/
asUintN(bits: number, int: bigint): bigint;
}
declare var BigInt: BigIntConstructor;
/**
* A typed array of 64-bit signed integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated, an exception is raised.
*/
interface BigInt64Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> {
/** The size in bytes of each element in the array. */
readonly BYTES_PER_ELEMENT: number;
/** The ArrayBuffer instance referenced by the array. */
readonly buffer: TArrayBuffer;
/** The length in bytes of the array. */
readonly byteLength: number;
/** The offset in bytes of the array. */
readonly byteOffset: number;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/** Yields index, value pairs for every entry in the array. */
entries(): ArrayIterator<[number, bigint]>;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param predicate A function that accepts up to three arguments. The every method calls
* the predicate function for each element in the array until the predicate returns false,
* or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(predicate: (value: bigint, index: number, array: BigInt64Array<TArrayBuffer>) => boolean, thisArg?: any): boolean;
/**
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: bigint, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param predicate A function that accepts up to three arguments. The filter method calls
* the predicate function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(predicate: (value: bigint, index: number, array: BigInt64Array<TArrayBuffer>) => any, thisArg?: any): BigInt64Array<ArrayBuffer>;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: bigint, index: number, array: BigInt64Array<TArrayBuffer>) => boolean, thisArg?: any): bigint | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: bigint, index: number, array: BigInt64Array<TArrayBuffer>) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: bigint, index: number, array: BigInt64Array<TArrayBuffer>) => void, thisArg?: any): void;
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: bigint, fromIndex?: number): boolean;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: bigint, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/** Yields each index in the array. */
keys(): ArrayIterator<number>;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: bigint, fromIndex?: number): number;
/** The length of the array. */
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (value: bigint, index: number, array: BigInt64Array<TArrayBuffer>) => bigint, thisArg?: any): BigInt64Array<ArrayBuffer>;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array<TArrayBuffer>) => bigint): bigint;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array<TArrayBuffer>) => U, initialValue: U): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigInt64Array<TArrayBuffer>) => bigint): bigint;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigInt64Array<TArrayBuffer>) => U, initialValue: U): U;
/** Reverses the elements in the array. */
reverse(): this;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: ArrayLike<bigint>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array.
*/
slice(start?: number, end?: number): BigInt64Array<ArrayBuffer>;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param predicate A function that accepts up to three arguments. The some method calls the
* predicate function for each element in the array until the predicate returns true, or until
* the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(predicate: (value: bigint, index: number, array: BigInt64Array<TArrayBuffer>) => boolean, thisArg?: any): boolean;
/**
* Sorts the array.
* @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order.
*/
sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this;
/**
* Gets a new BigInt64Array view of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin?: number, end?: number): BigInt64Array<TArrayBuffer>;
/** Converts the array to a string by using the current locale. */
toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string;
/** Returns a string representation of the array. */
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): BigInt64Array<TArrayBuffer>;
/** Yields each value in the array. */
values(): ArrayIterator<bigint>;
[Symbol.iterator](): ArrayIterator<bigint>;
readonly [Symbol.toStringTag]: "BigInt64Array";
[index: number]: bigint;
}
interface BigInt64ArrayConstructor {
readonly prototype: BigInt64Array<ArrayBufferLike>;
new (length?: number): BigInt64Array<ArrayBuffer>;
new (array: ArrayLike<bigint> | Iterable<bigint>): BigInt64Array<ArrayBuffer>;
new <TArrayBuffer extends ArrayBufferLike = ArrayBuffer>(buffer: TArrayBuffer, byteOffset?: number, length?: number): BigInt64Array<TArrayBuffer>;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): BigInt64Array<ArrayBuffer>;
new (array: ArrayLike<bigint> | ArrayBuffer): BigInt64Array<ArrayBuffer>;
/** The size in bytes of each element in the array. */
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: bigint[]): BigInt64Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like object to convert to an array.
*/
from(arrayLike: ArrayLike<bigint>): BigInt64Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<U>(arrayLike: ArrayLike<U>, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigInt64Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
*/
from(elements: Iterable<bigint>): BigInt64Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(elements: Iterable<T>, mapfn?: (v: T, k: number) => bigint, thisArg?: any): BigInt64Array<ArrayBuffer>;
}
declare var BigInt64Array: BigInt64ArrayConstructor;
/**
* A typed array of 64-bit unsigned integer values. The contents are initialized to 0. If the
* requested number of bytes could not be allocated, an exception is raised.
*/
interface BigUint64Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> {
/** The size in bytes of each element in the array. */
readonly BYTES_PER_ELEMENT: number;
/** The ArrayBuffer instance referenced by the array. */
readonly buffer: TArrayBuffer;
/** The length in bytes of the array. */
readonly byteLength: number;
/** The offset in bytes of the array. */
readonly byteOffset: number;
/**
* Returns the this object after copying a section of the array identified by start and end
* to the same array starting at position target
* @param target If target is negative, it is treated as length+target where length is the
* length of the array.
* @param start If start is negative, it is treated as length+start. If end is negative, it
* is treated as length+end.
* @param end If not specified, length of the this object is used as its default value.
*/
copyWithin(target: number, start: number, end?: number): this;
/** Yields index, value pairs for every entry in the array. */
entries(): ArrayIterator<[number, bigint]>;
/**
* Determines whether all the members of an array satisfy the specified test.
* @param predicate A function that accepts up to three arguments. The every method calls
* the predicate function for each element in the array until the predicate returns false,
* or until the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
every(predicate: (value: bigint, index: number, array: BigUint64Array<TArrayBuffer>) => boolean, thisArg?: any): boolean;
/**
* Changes all array elements from `start` to `end` index to a static `value` and returns the modified array
* @param value value to fill array section with
* @param start index to start filling the array at. If start is negative, it is treated as
* length+start where length is the length of the array.
* @param end index to stop filling the array at. If end is negative, it is treated as
* length+end.
*/
fill(value: bigint, start?: number, end?: number): this;
/**
* Returns the elements of an array that meet the condition specified in a callback function.
* @param predicate A function that accepts up to three arguments. The filter method calls
* the predicate function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
filter(predicate: (value: bigint, index: number, array: BigUint64Array<TArrayBuffer>) => any, thisArg?: any): BigUint64Array<ArrayBuffer>;
/**
* Returns the value of the first element in the array where predicate is true, and undefined
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found, find
* immediately returns that element value. Otherwise, find returns undefined.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
find(predicate: (value: bigint, index: number, array: BigUint64Array<TArrayBuffer>) => boolean, thisArg?: any): bigint | undefined;
/**
* Returns the index of the first element in the array where predicate is true, and -1
* otherwise.
* @param predicate find calls predicate once for each element of the array, in ascending
* order, until it finds one where predicate returns true. If such an element is found,
* findIndex immediately returns that element index. Otherwise, findIndex returns -1.
* @param thisArg If provided, it will be used as the this value for each invocation of
* predicate. If it is not provided, undefined is used instead.
*/
findIndex(predicate: (value: bigint, index: number, array: BigUint64Array<TArrayBuffer>) => boolean, thisArg?: any): number;
/**
* Performs the specified action for each element in an array.
* @param callbackfn A function that accepts up to three arguments. forEach calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
forEach(callbackfn: (value: bigint, index: number, array: BigUint64Array<TArrayBuffer>) => void, thisArg?: any): void;
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
* @param searchElement The element to search for.
* @param fromIndex The position in this array at which to begin searching for searchElement.
*/
includes(searchElement: bigint, fromIndex?: number): boolean;
/**
* Returns the index of the first occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
indexOf(searchElement: bigint, fromIndex?: number): number;
/**
* Adds all the elements of an array separated by the specified separator string.
* @param separator A string used to separate one element of an array from the next in the
* resulting String. If omitted, the array elements are separated with a comma.
*/
join(separator?: string): string;
/** Yields each index in the array. */
keys(): ArrayIterator<number>;
/**
* Returns the index of the last occurrence of a value in an array.
* @param searchElement The value to locate in the array.
* @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the
* search starts at index 0.
*/
lastIndexOf(searchElement: bigint, fromIndex?: number): number;
/** The length of the array. */
readonly length: number;
/**
* Calls a defined callback function on each element of an array, and returns an array that
* contains the results.
* @param callbackfn A function that accepts up to three arguments. The map method calls the
* callbackfn function one time for each element in the array.
* @param thisArg An object to which the this keyword can refer in the callbackfn function.
* If thisArg is omitted, undefined is used as the this value.
*/
map(callbackfn: (value: bigint, index: number, array: BigUint64Array<TArrayBuffer>) => bigint, thisArg?: any): BigUint64Array<ArrayBuffer>;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array<TArrayBuffer>) => bigint): bigint;
/**
* Calls the specified callback function for all the elements in an array. The return value of
* the callback function is the accumulated result, and is provided as an argument in the next
* call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduce method calls the
* callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduce<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array<TArrayBuffer>) => U, initialValue: U): U;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an
* argument instead of an array value.
*/
reduceRight(callbackfn: (previousValue: bigint, currentValue: bigint, currentIndex: number, array: BigUint64Array<TArrayBuffer>) => bigint): bigint;
/**
* Calls the specified callback function for all the elements in an array, in descending order.
* The return value of the callback function is the accumulated result, and is provided as an
* argument in the next call to the callback function.
* @param callbackfn A function that accepts up to four arguments. The reduceRight method calls
* the callbackfn function one time for each element in the array.
* @param initialValue If initialValue is specified, it is used as the initial value to start
* the accumulation. The first call to the callbackfn function provides this value as an argument
* instead of an array value.
*/
reduceRight<U>(callbackfn: (previousValue: U, currentValue: bigint, currentIndex: number, array: BigUint64Array<TArrayBuffer>) => U, initialValue: U): U;
/** Reverses the elements in the array. */
reverse(): this;
/**
* Sets a value or an array of values.
* @param array A typed or untyped array of values to set.
* @param offset The index in the current array at which the values are to be written.
*/
set(array: ArrayLike<bigint>, offset?: number): void;
/**
* Returns a section of an array.
* @param start The beginning of the specified portion of the array.
* @param end The end of the specified portion of the array.
*/
slice(start?: number, end?: number): BigUint64Array<ArrayBuffer>;
/**
* Determines whether the specified callback function returns true for any element of an array.
* @param predicate A function that accepts up to three arguments. The some method calls the
* predicate function for each element in the array until the predicate returns true, or until
* the end of the array.
* @param thisArg An object to which the this keyword can refer in the predicate function.
* If thisArg is omitted, undefined is used as the this value.
*/
some(predicate: (value: bigint, index: number, array: BigUint64Array<TArrayBuffer>) => boolean, thisArg?: any): boolean;
/**
* Sorts the array.
* @param compareFn The function used to determine the order of the elements. If omitted, the elements are sorted in ascending order.
*/
sort(compareFn?: (a: bigint, b: bigint) => number | bigint): this;
/**
* Gets a new BigUint64Array view of the ArrayBuffer store for this array, referencing the elements
* at begin, inclusive, up to end, exclusive.
* @param begin The index of the beginning of the array.
* @param end The index of the end of the array.
*/
subarray(begin?: number, end?: number): BigUint64Array<TArrayBuffer>;
/** Converts the array to a string by using the current locale. */
toLocaleString(locales?: string | string[], options?: Intl.NumberFormatOptions): string;
/** Returns a string representation of the array. */
toString(): string;
/** Returns the primitive value of the specified object. */
valueOf(): BigUint64Array<TArrayBuffer>;
/** Yields each value in the array. */
values(): ArrayIterator<bigint>;
[Symbol.iterator](): ArrayIterator<bigint>;
readonly [Symbol.toStringTag]: "BigUint64Array";
[index: number]: bigint;
}
interface BigUint64ArrayConstructor {
readonly prototype: BigUint64Array<ArrayBufferLike>;
new (length?: number): BigUint64Array<ArrayBuffer>;
new (array: ArrayLike<bigint> | Iterable<bigint>): BigUint64Array<ArrayBuffer>;
new <TArrayBuffer extends ArrayBufferLike = ArrayBuffer>(buffer: TArrayBuffer, byteOffset?: number, length?: number): BigUint64Array<TArrayBuffer>;
new (buffer: ArrayBuffer, byteOffset?: number, length?: number): BigUint64Array<ArrayBuffer>;
new (array: ArrayLike<bigint> | ArrayBuffer): BigUint64Array<ArrayBuffer>;
/** The size in bytes of each element in the array. */
readonly BYTES_PER_ELEMENT: number;
/**
* Returns a new array from a set of elements.
* @param items A set of elements to include in the new array object.
*/
of(...items: bigint[]): BigUint64Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like object to convert to an array.
*/
from(arrayLike: ArrayLike<bigint>): BigUint64Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param arrayLike An array-like object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<U>(arrayLike: ArrayLike<U>, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigUint64Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
*/
from(elements: Iterable<bigint>): BigUint64Array<ArrayBuffer>;
/**
* Creates an array from an array-like or iterable object.
* @param elements An iterable object to convert to an array.
* @param mapfn A mapping function to call on every element of the array.
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from<T>(elements: Iterable<T>, mapfn?: (v: T, k: number) => bigint, thisArg?: any): BigUint64Array<ArrayBuffer>;
}
declare var BigUint64Array: BigUint64ArrayConstructor;
interface DataView<TArrayBuffer extends ArrayBufferLike> {
/**
* Gets the BigInt64 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
* @param littleEndian If false or undefined, a big-endian value should be read.
*/
getBigInt64(byteOffset: number, littleEndian?: boolean): bigint;
/**
* Gets the BigUint64 value at the specified byte offset from the start of the view. There is
* no alignment constraint; multi-byte values may be fetched from any offset.
* @param byteOffset The place in the buffer at which the value should be retrieved.
* @param littleEndian If false or undefined, a big-endian value should be read.
*/
getBigUint64(byteOffset: number, littleEndian?: boolean): bigint;
/**
* Stores a BigInt64 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written.
*/
setBigInt64(byteOffset: number, value: bigint, littleEndian?: boolean): void;
/**
* Stores a BigUint64 value at the specified byte offset from the start of the view.
* @param byteOffset The place in the buffer at which the value should be set.
* @param value The value to set.
* @param littleEndian If false or undefined, a big-endian value should be written.
*/
setBigUint64(byteOffset: number, value: bigint, littleEndian?: boolean): void;
}
declare namespace Intl {
interface NumberFormat {
format(value: number | bigint): string;
}
}
+27
View File
@@ -0,0 +1,27 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2019" />
/// <reference lib="es2020.bigint" />
/// <reference lib="es2020.date" />
/// <reference lib="es2020.number" />
/// <reference lib="es2020.promise" />
/// <reference lib="es2020.sharedmemory" />
/// <reference lib="es2020.string" />
/// <reference lib="es2020.symbol.wellknown" />
/// <reference lib="es2020.intl" />
+42
View File
@@ -0,0 +1,42 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2020.intl" />
interface Date {
/**
* Converts a date and time to a string by using the current or specified locale.
* @param locales A locale string, array of locale strings, Intl.Locale object, or array of Intl.Locale objects that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a date to a string by using the current or specified locale.
* @param locales A locale string, array of locale strings, Intl.Locale object, or array of Intl.Locale objects that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleDateString(locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;
/**
* Converts a time to a string by using the current or specified locale.
* @param locales A locale string, array of locale strings, Intl.Locale object, or array of Intl.Locale objects that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleTimeString(locales?: Intl.LocalesArgument, options?: Intl.DateTimeFormatOptions): string;
}
+24
View File
@@ -0,0 +1,24 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2020" />
/// <reference lib="dom" />
/// <reference lib="webworker.importscripts" />
/// <reference lib="scripthost" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />
+474
View File
@@ -0,0 +1,474 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2018.intl" />
declare namespace Intl {
/**
* A string that is a valid [Unicode BCP 47 Locale Identifier](https://unicode.org/reports/tr35/#Unicode_locale_identifier).
*
* For example: "fa", "es-MX", "zh-Hant-TW".
*
* See [MDN - Intl - locales argument](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
*/
type UnicodeBCP47LocaleIdentifier = string;
/**
* Unit to use in the relative time internationalized message.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/format#Parameters).
*/
type RelativeTimeFormatUnit =
| "year"
| "years"
| "quarter"
| "quarters"
| "month"
| "months"
| "week"
| "weeks"
| "day"
| "days"
| "hour"
| "hours"
| "minute"
| "minutes"
| "second"
| "seconds";
/**
* Value of the `unit` property in objects returned by
* `Intl.RelativeTimeFormat.prototype.formatToParts()`. `formatToParts` and
* `format` methods accept either singular or plural unit names as input,
* but `formatToParts` only outputs singular (e.g. "day") not plural (e.g.
* "days").
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts#Using_formatToParts).
*/
type RelativeTimeFormatUnitSingular =
| "year"
| "quarter"
| "month"
| "week"
| "day"
| "hour"
| "minute"
| "second";
/**
* The locale matching algorithm to use.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation).
*/
type RelativeTimeFormatLocaleMatcher = "lookup" | "best fit";
/**
* The format of output message.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters).
*/
type RelativeTimeFormatNumeric = "always" | "auto";
/**
* The length of the internationalized message.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters).
*/
type RelativeTimeFormatStyle = "long" | "short" | "narrow";
/**
* The locale or locales to use
*
* See [MDN - Intl - locales argument](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
*/
type LocalesArgument = UnicodeBCP47LocaleIdentifier | Locale | readonly (UnicodeBCP47LocaleIdentifier | Locale)[] | undefined;
/**
* An object with some or all of properties of `options` parameter
* of `Intl.RelativeTimeFormat` constructor.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters).
*/
interface RelativeTimeFormatOptions {
/** The locale matching algorithm to use. For information about this option, see [Intl page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation). */
localeMatcher?: RelativeTimeFormatLocaleMatcher;
/** The format of output message. */
numeric?: RelativeTimeFormatNumeric;
/** The length of the internationalized message. */
style?: RelativeTimeFormatStyle;
}
/**
* An object with properties reflecting the locale
* and formatting options computed during initialization
* of the `Intl.RelativeTimeFormat` object
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/resolvedOptions#Description).
*/
interface ResolvedRelativeTimeFormatOptions {
locale: UnicodeBCP47LocaleIdentifier;
style: RelativeTimeFormatStyle;
numeric: RelativeTimeFormatNumeric;
numberingSystem: string;
}
/**
* An object representing the relative time format in parts
* that can be used for custom locale-aware formatting.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts#Using_formatToParts).
*/
type RelativeTimeFormatPart =
| {
type: "literal";
value: string;
}
| {
type: Exclude<NumberFormatPartTypes, "literal">;
value: string;
unit: RelativeTimeFormatUnitSingular;
};
interface RelativeTimeFormat {
/**
* Formats a value and a unit according to the locale
* and formatting options of the given
* [`Intl.RelativeTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat)
* object.
*
* While this method automatically provides the correct plural forms,
* the grammatical form is otherwise as neutral as possible.
*
* It is the caller's responsibility to handle cut-off logic
* such as deciding between displaying "in 7 days" or "in 1 week".
* This API does not support relative dates involving compound units.
* e.g "in 5 days and 4 hours".
*
* @param value - Numeric value to use in the internationalized relative time message
*
* @param unit - [Unit](https://tc39.es/ecma402/#sec-singularrelativetimeunit) to use in the relative time internationalized message.
*
* @throws `RangeError` if `unit` was given something other than `unit` possible values
*
* @returns {string} Internationalized relative time message as string
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/format).
*/
format(value: number, unit: RelativeTimeFormatUnit): string;
/**
* Returns an array of objects representing the relative time format in parts that can be used for custom locale-aware formatting.
*
* @param value - Numeric value to use in the internationalized relative time message
*
* @param unit - [Unit](https://tc39.es/ecma402/#sec-singularrelativetimeunit) to use in the relative time internationalized message.
*
* @throws `RangeError` if `unit` was given something other than `unit` possible values
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts).
*/
formatToParts(value: number, unit: RelativeTimeFormatUnit): RelativeTimeFormatPart[];
/**
* Provides access to the locale and options computed during initialization of this `Intl.RelativeTimeFormat` object.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/resolvedOptions).
*/
resolvedOptions(): ResolvedRelativeTimeFormatOptions;
}
/**
* The [`Intl.RelativeTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat)
* object is a constructor for objects that enable language-sensitive relative time formatting.
*
* [Compatibility](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat#Browser_compatibility).
*/
const RelativeTimeFormat: {
/**
* Creates [Intl.RelativeTimeFormat](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) objects
*
* @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.
* For the general form and interpretation of the locales argument,
* see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
*
* @param options - An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters)
* with some or all of options of `RelativeTimeFormatOptions`.
*
* @returns [Intl.RelativeTimeFormat](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) object.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat).
*/
new (
locales?: LocalesArgument,
options?: RelativeTimeFormatOptions,
): RelativeTimeFormat;
/**
* Returns an array containing those of the provided locales
* that are supported in date and time formatting
* without having to fall back to the runtime's default locale.
*
* @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.
* For the general form and interpretation of the locales argument,
* see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
*
* @param options - An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters)
* with some or all of options of the formatting.
*
* @returns An array containing those of the provided locales
* that are supported in date and time formatting
* without having to fall back to the runtime's default locale.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/supportedLocalesOf).
*/
supportedLocalesOf(
locales?: LocalesArgument,
options?: RelativeTimeFormatOptions,
): UnicodeBCP47LocaleIdentifier[];
};
interface NumberFormatOptionsStyleRegistry {
unit: never;
}
interface NumberFormatOptionsCurrencyDisplayRegistry {
narrowSymbol: never;
}
interface NumberFormatOptionsSignDisplayRegistry {
auto: never;
never: never;
always: never;
exceptZero: never;
}
type NumberFormatOptionsSignDisplay = keyof NumberFormatOptionsSignDisplayRegistry;
interface NumberFormatOptions {
numberingSystem?: string | undefined;
compactDisplay?: "short" | "long" | undefined;
notation?: "standard" | "scientific" | "engineering" | "compact" | undefined;
signDisplay?: NumberFormatOptionsSignDisplay | undefined;
unit?: string | undefined;
unitDisplay?: "short" | "long" | "narrow" | undefined;
currencySign?: "standard" | "accounting" | undefined;
}
interface ResolvedNumberFormatOptions {
compactDisplay?: "short" | "long";
notation: "standard" | "scientific" | "engineering" | "compact";
signDisplay: NumberFormatOptionsSignDisplay;
unit?: string;
unitDisplay?: "short" | "long" | "narrow";
currencySign?: "standard" | "accounting";
}
interface NumberFormatPartTypeRegistry {
compact: never;
exponentInteger: never;
exponentMinusSign: never;
exponentSeparator: never;
unit: never;
unknown: never;
}
interface DateTimeFormatOptions {
calendar?: string | undefined;
dayPeriod?: "narrow" | "short" | "long" | undefined;
numberingSystem?: string | undefined;
dateStyle?: "full" | "long" | "medium" | "short" | undefined;
timeStyle?: "full" | "long" | "medium" | "short" | undefined;
hourCycle?: "h11" | "h12" | "h23" | "h24" | undefined;
}
type LocaleHourCycleKey = "h12" | "h23" | "h11" | "h24";
type LocaleCollationCaseFirst = "upper" | "lower" | "false";
interface LocaleOptions {
/** A string containing the language, and the script and region if available. */
baseName?: string;
/** The part of the Locale that indicates the locale's calendar era. */
calendar?: string;
/** Flag that defines whether case is taken into account for the locale's collation rules. */
caseFirst?: LocaleCollationCaseFirst;
/** The collation type used for sorting */
collation?: string;
/** The time keeping format convention used by the locale. */
hourCycle?: LocaleHourCycleKey;
/** The primary language subtag associated with the locale. */
language?: string;
/** The numeral system used by the locale. */
numberingSystem?: string;
/** Flag that defines whether the locale has special collation handling for numeric characters. */
numeric?: boolean;
/** The region of the world (usually a country) associated with the locale. Possible values are region codes as defined by ISO 3166-1. */
region?: string;
/** The script used for writing the particular language used in the locale. Possible values are script codes as defined by ISO 15924. */
script?: string;
}
interface Locale extends LocaleOptions {
/** A string containing the language, and the script and region if available. */
baseName: string;
/** The primary language subtag associated with the locale. */
language: string;
/** Gets the most likely values for the language, script, and region of the locale based on existing values. */
maximize(): Locale;
/** Attempts to remove information about the locale that would be added by calling `Locale.maximize()`. */
minimize(): Locale;
/** Returns the locale's full locale identifier string. */
toString(): UnicodeBCP47LocaleIdentifier;
}
/**
* Constructor creates [Intl.Locale](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale)
* objects
*
* @param tag - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646).
* For the general form and interpretation of the locales argument,
* see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
*
* @param options - An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/Locale#Parameters) with some or all of options of the locale.
*
* @returns [Intl.Locale](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale) object.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale).
*/
const Locale: {
new (tag: UnicodeBCP47LocaleIdentifier | Locale, options?: LocaleOptions): Locale;
};
type DisplayNamesFallback =
| "code"
| "none";
type DisplayNamesType =
| "language"
| "region"
| "script"
| "calendar"
| "dateTimeField"
| "currency";
type DisplayNamesLanguageDisplay =
| "dialect"
| "standard";
interface DisplayNamesOptions {
localeMatcher?: RelativeTimeFormatLocaleMatcher;
style?: RelativeTimeFormatStyle;
type: DisplayNamesType;
languageDisplay?: DisplayNamesLanguageDisplay;
fallback?: DisplayNamesFallback;
}
interface ResolvedDisplayNamesOptions {
locale: UnicodeBCP47LocaleIdentifier;
style: RelativeTimeFormatStyle;
type: DisplayNamesType;
fallback: DisplayNamesFallback;
languageDisplay?: DisplayNamesLanguageDisplay;
}
interface DisplayNames {
/**
* Receives a code and returns a string based on the locale and options provided when instantiating
* [`Intl.DisplayNames()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames)
*
* @param code The `code` to provide depends on the `type` passed to display name during creation:
* - If the type is `"region"`, code should be either an [ISO-3166 two letters region code](https://www.iso.org/iso-3166-country-codes.html),
* or a [three digits UN M49 Geographic Regions](https://unstats.un.org/unsd/methodology/m49/).
* - If the type is `"script"`, code should be an [ISO-15924 four letters script code](https://unicode.org/iso15924/iso15924-codes.html).
* - If the type is `"language"`, code should be a `languageCode` ["-" `scriptCode`] ["-" `regionCode` ] *("-" `variant` )
* subsequence of the unicode_language_id grammar in [UTS 35's Unicode Language and Locale Identifiers grammar](https://unicode.org/reports/tr35/#Unicode_language_identifier).
* `languageCode` is either a two letters ISO 639-1 language code or a three letters ISO 639-2 language code.
* - If the type is `"currency"`, code should be a [3-letter ISO 4217 currency code](https://www.iso.org/iso-4217-currency-codes.html).
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/of).
*/
of(code: string): string | undefined;
/**
* Returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current
* [`Intl/DisplayNames`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames) object.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/resolvedOptions).
*/
resolvedOptions(): ResolvedDisplayNamesOptions;
}
/**
* The [`Intl.DisplayNames()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames)
* object enables the consistent translation of language, region and script display names.
*
* [Compatibility](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames#browser_compatibility).
*/
const DisplayNames: {
prototype: DisplayNames;
/**
* @param locales A string with a BCP 47 language tag, or an array of such strings.
* For the general form and interpretation of the `locales` argument, see the [Intl](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation)
* page.
*
* @param options An object for setting up a display name.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/DisplayNames).
*/
new (locales: LocalesArgument, options: DisplayNamesOptions): DisplayNames;
/**
* Returns an array containing those of the provided locales that are supported in display names without having to fall back to the runtime's default locale.
*
* @param locales A string with a BCP 47 language tag, or an array of such strings.
* For the general form and interpretation of the `locales` argument, see the [Intl](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation)
* page.
*
* @param options An object with a locale matcher.
*
* @returns An array of strings representing a subset of the given locale tags that are supported in display names without having to fall back to the runtime's default locale.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/supportedLocalesOf).
*/
supportedLocalesOf(locales?: LocalesArgument, options?: { localeMatcher?: RelativeTimeFormatLocaleMatcher; }): UnicodeBCP47LocaleIdentifier[];
};
interface CollatorConstructor {
new (locales?: LocalesArgument, options?: CollatorOptions): Collator;
(locales?: LocalesArgument, options?: CollatorOptions): Collator;
supportedLocalesOf(locales: LocalesArgument, options?: CollatorOptions): string[];
}
interface DateTimeFormatConstructor {
new (locales?: LocalesArgument, options?: DateTimeFormatOptions): DateTimeFormat;
(locales?: LocalesArgument, options?: DateTimeFormatOptions): DateTimeFormat;
supportedLocalesOf(locales: LocalesArgument, options?: DateTimeFormatOptions): string[];
}
interface NumberFormatConstructor {
new (locales?: LocalesArgument, options?: NumberFormatOptions): NumberFormat;
(locales?: LocalesArgument, options?: NumberFormatOptions): NumberFormat;
supportedLocalesOf(locales: LocalesArgument, options?: NumberFormatOptions): string[];
}
interface PluralRulesConstructor {
new (locales?: LocalesArgument, options?: PluralRulesOptions): PluralRules;
(locales?: LocalesArgument, options?: PluralRulesOptions): PluralRules;
supportedLocalesOf(locales: LocalesArgument, options?: { localeMatcher?: "lookup" | "best fit"; }): string[];
}
}
+28
View File
@@ -0,0 +1,28 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2020.intl" />
interface Number {
/**
* Converts a number to a string by using the current or specified locale.
* @param locales A locale string, array of locale strings, Intl.Locale object, or array of Intl.Locale objects that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used.
* @param options An object that contains one or more properties that specify comparison options.
*/
toLocaleString(locales?: Intl.LocalesArgument, options?: Intl.NumberFormatOptions): string;
}
@@ -0,0 +1,47 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface PromiseFulfilledResult<T> {
status: "fulfilled";
value: T;
}
interface PromiseRejectedResult {
status: "rejected";
reason: any;
}
type PromiseSettledResult<T> = PromiseFulfilledResult<T> | PromiseRejectedResult;
interface PromiseConstructor {
/**
* Creates a Promise that is resolved with an array of results when all
* of the provided Promises resolve or reject.
* @param values An array of Promises.
* @returns A new Promise.
*/
allSettled<T extends readonly unknown[] | []>(values: T): Promise<{ -readonly [P in keyof T]: PromiseSettledResult<Awaited<T[P]>>; }>;
/**
* Creates a Promise that is resolved with an array of results when all
* of the provided Promises resolve or reject.
* @param values An array of Promises.
* @returns A new Promise.
*/
allSettled<T>(values: Iterable<T | PromiseLike<T>>): Promise<PromiseSettledResult<Awaited<T>>[]>;
}
@@ -0,0 +1,99 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2020.bigint" />
interface Atomics {
/**
* Adds a value to the value at the given position in the array, returning the original value.
* Until this atomic operation completes, any other read or write operation against the array
* will block.
*/
add(typedArray: BigInt64Array<ArrayBufferLike> | BigUint64Array<ArrayBufferLike>, index: number, value: bigint): bigint;
/**
* Stores the bitwise AND of a value with the value at the given position in the array,
* returning the original value. Until this atomic operation completes, any other read or
* write operation against the array will block.
*/
and(typedArray: BigInt64Array<ArrayBufferLike> | BigUint64Array<ArrayBufferLike>, index: number, value: bigint): bigint;
/**
* Replaces the value at the given position in the array if the original value equals the given
* expected value, returning the original value. Until this atomic operation completes, any
* other read or write operation against the array will block.
*/
compareExchange(typedArray: BigInt64Array<ArrayBufferLike> | BigUint64Array<ArrayBufferLike>, index: number, expectedValue: bigint, replacementValue: bigint): bigint;
/**
* Replaces the value at the given position in the array, returning the original value. Until
* this atomic operation completes, any other read or write operation against the array will
* block.
*/
exchange(typedArray: BigInt64Array<ArrayBufferLike> | BigUint64Array<ArrayBufferLike>, index: number, value: bigint): bigint;
/**
* Returns the value at the given position in the array. Until this atomic operation completes,
* any other read or write operation against the array will block.
*/
load(typedArray: BigInt64Array<ArrayBufferLike> | BigUint64Array<ArrayBufferLike>, index: number): bigint;
/**
* Stores the bitwise OR of a value with the value at the given position in the array,
* returning the original value. Until this atomic operation completes, any other read or write
* operation against the array will block.
*/
or(typedArray: BigInt64Array<ArrayBufferLike> | BigUint64Array<ArrayBufferLike>, index: number, value: bigint): bigint;
/**
* Stores a value at the given position in the array, returning the new value. Until this
* atomic operation completes, any other read or write operation against the array will block.
*/
store(typedArray: BigInt64Array<ArrayBufferLike> | BigUint64Array<ArrayBufferLike>, index: number, value: bigint): bigint;
/**
* Subtracts a value from the value at the given position in the array, returning the original
* value. Until this atomic operation completes, any other read or write operation against the
* array will block.
*/
sub(typedArray: BigInt64Array<ArrayBufferLike> | BigUint64Array<ArrayBufferLike>, index: number, value: bigint): bigint;
/**
* If the value at the given position in the array is equal to the provided value, the current
* agent is put to sleep causing execution to suspend until the timeout expires (returning
* `"timed-out"`) or until the agent is awoken (returning `"ok"`); otherwise, returns
* `"not-equal"`.
*/
wait(typedArray: BigInt64Array<ArrayBufferLike>, index: number, value: bigint, timeout?: number): "ok" | "not-equal" | "timed-out";
/**
* Wakes up sleeping agents that are waiting on the given index of the array, returning the
* number of agents that were awoken.
* @param typedArray A shared BigInt64Array.
* @param index The position in the typedArray to wake up on.
* @param count The number of sleeping agents to notify. Defaults to +Infinity.
*/
notify(typedArray: BigInt64Array<ArrayBufferLike>, index: number, count?: number): number;
/**
* Stores the bitwise XOR of a value with the value at the given position in the array,
* returning the original value. Until this atomic operation completes, any other read or write
* operation against the array will block.
*/
xor(typedArray: BigInt64Array<ArrayBufferLike> | BigUint64Array<ArrayBufferLike>, index: number, value: bigint): bigint;
}
+44
View File
@@ -0,0 +1,44 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2015.iterable" />
/// <reference lib="es2020.intl" />
/// <reference lib="es2020.symbol.wellknown" />
interface String {
/**
* Matches a string with a regular expression, and returns an iterable of matches
* containing the results of that search.
* @param regexp A variable name or string literal containing the regular expression pattern and flags.
*/
matchAll(regexp: RegExp): RegExpStringIterator<RegExpExecArray>;
/** Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. */
toLocaleLowerCase(locales?: Intl.LocalesArgument): string;
/** Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. */
toLocaleUpperCase(locales?: Intl.LocalesArgument): string;
/**
* Determines whether two strings are equivalent in the current or specified locale.
* @param that String to compare to target string
* @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details.
* @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details.
*/
localeCompare(that: string, locales?: Intl.LocalesArgument, options?: Intl.CollatorOptions): number;
}
@@ -0,0 +1,41 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2015.iterable" />
/// <reference lib="es2015.symbol" />
interface SymbolConstructor {
/**
* A regular expression method that matches the regular expression against a string. Called
* by the String.prototype.matchAll method.
*/
readonly matchAll: unique symbol;
}
interface RegExpStringIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): RegExpStringIterator<T>;
}
interface RegExp {
/**
* Matches a string with this regular expression, and returns an iterable of matches
* containing the results of that search.
* @param string A string to search within.
*/
[Symbol.matchAll](str: string): RegExpStringIterator<RegExpMatchArray>;
}
+23
View File
@@ -0,0 +1,23 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2020" />
/// <reference lib="es2021.promise" />
/// <reference lib="es2021.string" />
/// <reference lib="es2021.weakref" />
/// <reference lib="es2021.intl" />
+24
View File
@@ -0,0 +1,24 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2021" />
/// <reference lib="dom" />
/// <reference lib="webworker.importscripts" />
/// <reference lib="scripthost" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />
+166
View File
@@ -0,0 +1,166 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare namespace Intl {
interface DateTimeFormatPartTypesRegistry {
fractionalSecond: any;
}
interface DateTimeFormatOptions {
formatMatcher?: "basic" | "best fit" | "best fit" | undefined;
dateStyle?: "full" | "long" | "medium" | "short" | undefined;
timeStyle?: "full" | "long" | "medium" | "short" | undefined;
dayPeriod?: "narrow" | "short" | "long" | undefined;
fractionalSecondDigits?: 1 | 2 | 3 | undefined;
}
interface DateTimeRangeFormatPart extends DateTimeFormatPart {
source: "startRange" | "endRange" | "shared";
}
interface DateTimeFormat {
formatRange(startDate: Date | number | bigint, endDate: Date | number | bigint): string;
formatRangeToParts(startDate: Date | number | bigint, endDate: Date | number | bigint): DateTimeRangeFormatPart[];
}
interface ResolvedDateTimeFormatOptions {
formatMatcher?: "basic" | "best fit" | "best fit";
dateStyle?: "full" | "long" | "medium" | "short";
timeStyle?: "full" | "long" | "medium" | "short";
hourCycle?: "h11" | "h12" | "h23" | "h24";
dayPeriod?: "narrow" | "short" | "long";
fractionalSecondDigits?: 1 | 2 | 3;
}
/**
* The locale matching algorithm to use.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).
*/
type ListFormatLocaleMatcher = "lookup" | "best fit";
/**
* The format of output message.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).
*/
type ListFormatType = "conjunction" | "disjunction" | "unit";
/**
* The length of the formatted message.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).
*/
type ListFormatStyle = "long" | "short" | "narrow";
/**
* An object with some or all properties of the `Intl.ListFormat` constructor `options` parameter.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).
*/
interface ListFormatOptions {
/** The locale matching algorithm to use. For information about this option, see [Intl page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation). */
localeMatcher?: ListFormatLocaleMatcher | undefined;
/** The format of output message. */
type?: ListFormatType | undefined;
/** The length of the internationalized message. */
style?: ListFormatStyle | undefined;
}
interface ResolvedListFormatOptions {
locale: string;
style: ListFormatStyle;
type: ListFormatType;
}
interface ListFormat {
/**
* Returns a string with a language-specific representation of the list.
*
* @param list - An iterable object, such as an [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array).
*
* @throws `TypeError` if `list` includes something other than the possible values.
*
* @returns {string} A language-specific formatted string representing the elements of the list.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/format).
*/
format(list: Iterable<string>): string;
/**
* Returns an Array of objects representing the different components that can be used to format a list of values in a locale-aware fashion.
*
* @param list - An iterable object, such as an [Array](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array), to be formatted according to a locale.
*
* @throws `TypeError` if `list` includes something other than the possible values.
*
* @returns {{ type: "element" | "literal", value: string; }[]} An Array of components which contains the formatted parts from the list.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/formatToParts).
*/
formatToParts(list: Iterable<string>): { type: "element" | "literal"; value: string; }[];
/**
* Returns a new object with properties reflecting the locale and style
* formatting options computed during the construction of the current
* `Intl.ListFormat` object.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/resolvedOptions).
*/
resolvedOptions(): ResolvedListFormatOptions;
}
const ListFormat: {
prototype: ListFormat;
/**
* Creates [Intl.ListFormat](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) objects that
* enable language-sensitive list formatting.
*
* @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.
* For the general form and interpretation of the `locales` argument,
* see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
*
* @param options - An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters)
* with some or all options of `ListFormatOptions`.
*
* @returns [Intl.ListFormatOptions](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) object.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat).
*/
new (locales?: LocalesArgument, options?: ListFormatOptions): ListFormat;
/**
* Returns an array containing those of the provided locales that are
* supported in list formatting without having to fall back to the runtime's default locale.
*
* @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.
* For the general form and interpretation of the `locales` argument,
* see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
*
* @param options - An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/supportedLocalesOf#parameters).
* with some or all possible options.
*
* @returns An array of strings representing a subset of the given locale tags that are supported in list
* formatting without having to fall back to the runtime's default locale.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/supportedLocalesOf).
*/
supportedLocalesOf(locales: LocalesArgument, options?: Pick<ListFormatOptions, "localeMatcher">): UnicodeBCP47LocaleIdentifier[];
};
}
@@ -0,0 +1,48 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface AggregateError extends Error {
errors: any[];
}
interface AggregateErrorConstructor {
new (errors: Iterable<any>, message?: string): AggregateError;
(errors: Iterable<any>, message?: string): AggregateError;
readonly prototype: AggregateError;
}
declare var AggregateError: AggregateErrorConstructor;
/**
* Represents the completion of an asynchronous operation
*/
interface PromiseConstructor {
/**
* The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError containing an array of rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm.
* @param values An array or iterable of Promises.
* @returns A new Promise.
*/
any<T extends readonly unknown[] | []>(values: T): Promise<Awaited<T[number]>>;
/**
* The any function returns a promise that is fulfilled by the first given promise to be fulfilled, or rejected with an AggregateError containing an array of rejection reasons if all of the given promises are rejected. It resolves all elements of the passed iterable to promises as it runs this algorithm.
* @param values An array or iterable of Promises.
* @returns A new Promise.
*/
any<T>(values: Iterable<T | PromiseLike<T>>): Promise<Awaited<T>>;
}
+33
View File
@@ -0,0 +1,33 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface String {
/**
* Replace all instances of a substring in a string, using a regular expression or search string.
* @param searchValue A string to search for.
* @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
*/
replaceAll(searchValue: string | RegExp, replaceValue: string): string;
/**
* Replace all instances of a substring in a string, using a regular expression or search string.
* @param searchValue A string to search for.
* @param replacer A function that returns the replacement text.
*/
replaceAll(searchValue: string | RegExp, replacer: (substring: string, ...args: any[]) => string): string;
}
@@ -0,0 +1,78 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2015.symbol.wellknown" />
interface WeakRef<T extends WeakKey> {
readonly [Symbol.toStringTag]: "WeakRef";
/**
* Returns the WeakRef instance's target value, or undefined if the target value has been
* reclaimed.
* In es2023 the value can be either a symbol or an object, in previous versions only object is permissible.
*/
deref(): T | undefined;
}
interface WeakRefConstructor {
readonly prototype: WeakRef<any>;
/**
* Creates a WeakRef instance for the given target value.
* In es2023 the value can be either a symbol or an object, in previous versions only object is permissible.
* @param target The target value for the WeakRef instance.
*/
new <T extends WeakKey>(target: T): WeakRef<T>;
}
declare var WeakRef: WeakRefConstructor;
interface FinalizationRegistry<T> {
readonly [Symbol.toStringTag]: "FinalizationRegistry";
/**
* Registers a value with the registry.
* In es2023 the value can be either a symbol or an object, in previous versions only object is permissible.
* @param target The target value to register.
* @param heldValue The value to pass to the finalizer for this value. This cannot be the
* target value.
* @param unregisterToken The token to pass to the unregister method to unregister the target
* value. If not provided, the target cannot be unregistered.
*/
register(target: WeakKey, heldValue: T, unregisterToken?: WeakKey): void;
/**
* Unregisters a value from the registry.
* In es2023 the value can be either a symbol or an object, in previous versions only object is permissible.
* @param unregisterToken The token that was used as the unregisterToken argument when calling
* register to register the target value.
*/
unregister(unregisterToken: WeakKey): boolean;
}
interface FinalizationRegistryConstructor {
readonly prototype: FinalizationRegistry<any>;
/**
* Creates a finalization registry with an associated cleanup callback
* @param cleanupCallback The callback to call after a value in the registry has been reclaimed.
*/
new <T>(cleanupCallback: (heldValue: T) => void): FinalizationRegistry<T>;
}
declare var FinalizationRegistry: FinalizationRegistryConstructor;
+121
View File
@@ -0,0 +1,121 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Array<T> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): T | undefined;
}
interface ReadonlyArray<T> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): T | undefined;
}
interface Int8Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Uint8Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Uint8ClampedArray<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Int16Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Uint16Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Int32Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Uint32Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Float32Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface Float64Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): number | undefined;
}
interface BigInt64Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): bigint | undefined;
}
interface BigUint64Array<TArrayBuffer extends ArrayBufferLike> {
/**
* Returns the item located at the specified index.
* @param index The zero-based index of the desired code unit. A negative index will count back from the last item.
*/
at(index: number): bigint | undefined;
}
+25
View File
@@ -0,0 +1,25 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2021" />
/// <reference lib="es2022.array" />
/// <reference lib="es2022.error" />
/// <reference lib="es2022.intl" />
/// <reference lib="es2022.object" />
/// <reference lib="es2022.regexp" />
/// <reference lib="es2022.string" />
+75
View File
@@ -0,0 +1,75 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2021.promise" />
interface ErrorOptions {
cause?: unknown;
}
interface Error {
cause?: unknown;
}
interface ErrorConstructor {
new (message?: string, options?: ErrorOptions): Error;
(message?: string, options?: ErrorOptions): Error;
}
interface EvalErrorConstructor {
new (message?: string, options?: ErrorOptions): EvalError;
(message?: string, options?: ErrorOptions): EvalError;
}
interface RangeErrorConstructor {
new (message?: string, options?: ErrorOptions): RangeError;
(message?: string, options?: ErrorOptions): RangeError;
}
interface ReferenceErrorConstructor {
new (message?: string, options?: ErrorOptions): ReferenceError;
(message?: string, options?: ErrorOptions): ReferenceError;
}
interface SyntaxErrorConstructor {
new (message?: string, options?: ErrorOptions): SyntaxError;
(message?: string, options?: ErrorOptions): SyntaxError;
}
interface TypeErrorConstructor {
new (message?: string, options?: ErrorOptions): TypeError;
(message?: string, options?: ErrorOptions): TypeError;
}
interface URIErrorConstructor {
new (message?: string, options?: ErrorOptions): URIError;
(message?: string, options?: ErrorOptions): URIError;
}
interface AggregateErrorConstructor {
new (
errors: Iterable<any>,
message?: string,
options?: ErrorOptions,
): AggregateError;
(
errors: Iterable<any>,
message?: string,
options?: ErrorOptions,
): AggregateError;
}
+24
View File
@@ -0,0 +1,24 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference lib="es2022" />
/// <reference lib="dom" />
/// <reference lib="webworker.importscripts" />
/// <reference lib="scripthost" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />
+145
View File
@@ -0,0 +1,145 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare namespace Intl {
/**
* An object with some or all properties of the `Intl.Segmenter` constructor `options` parameter.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/Segmenter#parameters)
*/
interface SegmenterOptions {
/** The locale matching algorithm to use. For information about this option, see [Intl page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation). */
localeMatcher?: "best fit" | "lookup" | undefined;
/** The type of input to be split */
granularity?: "grapheme" | "word" | "sentence" | undefined;
}
/**
* The `Intl.Segmenter` object enables locale-sensitive text segmentation, enabling you to get meaningful items (graphemes, words or sentences) from a string.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter)
*/
interface Segmenter {
/**
* Returns `Segments` object containing the segments of the input string, using the segmenter's locale and granularity.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment)
*
* @param input - The text to be segmented as a `string`.
*
* @returns A new iterable Segments object containing the segments of the input string, using the segmenter's locale and granularity.
*/
segment(input: string): Segments;
/**
* The `resolvedOptions()` method of `Intl.Segmenter` instances returns a new object with properties reflecting the options computed during initialization of this `Segmenter` object.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/resolvedOptions)
*/
resolvedOptions(): ResolvedSegmenterOptions;
}
interface ResolvedSegmenterOptions {
locale: string;
granularity: "grapheme" | "word" | "sentence";
}
interface SegmentIterator<T> extends IteratorObject<T, BuiltinIteratorReturn, unknown> {
[Symbol.iterator](): SegmentIterator<T>;
}
/**
* A `Segments` object is an iterable collection of the segments of a text string. It is returned by a call to the `segment()` method of an `Intl.Segmenter` object.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments)
*/
interface Segments {
/**
* Returns an object describing the segment in the original string that includes the code unit at a specified index.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments/containing)
*
* @param codeUnitIndex - A number specifying the index of the code unit in the original input string. If the value is omitted, it defaults to `0`.
*/
containing(codeUnitIndex?: number): SegmentData | undefined;
/** Returns an iterator to iterate over the segments. */
[Symbol.iterator](): SegmentIterator<SegmentData>;
}
interface SegmentData {
/** A string containing the segment extracted from the original input string. */
segment: string;
/** The code unit index in the original input string at which the segment begins. */
index: number;
/** The complete input string that was segmented. */
input: string;
/**
* A boolean value only if granularity is "word"; otherwise, undefined.
* If granularity is "word", then isWordLike is true when the segment is word-like (i.e., consists of letters/numbers/ideographs/etc.); otherwise, false.
*/
isWordLike?: boolean;
}
/**
* The `Intl.Segmenter` object enables locale-sensitive text segmentation, enabling you to get meaningful items (graphemes, words or sentences) from a string.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter)
*/
const Segmenter: {
prototype: Segmenter;
/**
* Creates a new `Intl.Segmenter` object.
*
* @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.
* For the general form and interpretation of the `locales` argument,
* see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
*
* @param options - An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/Segmenter#parameters)
* with some or all options of `SegmenterOptions`.
*
* @returns [Intl.Segmenter](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segments) object.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter).
*/
new (locales?: LocalesArgument, options?: SegmenterOptions): Segmenter;
/**
* Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
*
* @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.
* For the general form and interpretation of the `locales` argument,
* see the [`Intl` page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
*
* @param options An [object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/supportedLocalesOf#parameters).
* with some or all possible options.
*
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/supportedLocalesOf)
*/
supportedLocalesOf(locales: LocalesArgument, options?: Pick<SegmenterOptions, "localeMatcher">): UnicodeBCP47LocaleIdentifier[];
};
/**
* Returns a sorted array of the supported collation, calendar, currency, numbering system, timezones, and units by the implementation.
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/supportedValuesOf)
*
* @param key A string indicating the category of values to return.
* @returns A sorted array of the supported values.
*/
function supportedValuesOf(key: "calendar" | "collation" | "currency" | "numberingSystem" | "timeZone" | "unit"): string[];
}

Some files were not shown because too many files have changed in this diff Show More