introduced structure backend packeges and frontend

This commit is contained in:
2024-12-28 16:30:48 +01:00
parent f0017a13e1
commit 48e0708dc9
3606 changed files with 1376938 additions and 341 deletions
@@ -1,35 +1,20 @@
package main
package character
import (
"bamort/database"
"bamort/models"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"log"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var DB *gorm.DB
func ConnectDatabase() {
dsn := "bamort:bG4)efozrc@tcp(192.168.0.5:3306)/bamort?charset=utf8mb4&parseTime=True&loc=Local"
database, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("Failed to connect to database:", err)
}
DB = database
}
/*
Replace user, password, and dbname with your MySQL credentials and database name.
*/
func saveCharacterToDB(character *Character) error {
func SaveCharacterToDB(character *models.Char) error {
// Use GORM transaction to ensure atomicity
return DB.Transaction(func(tx *gorm.DB) error {
return database.DB.Transaction(func(tx *gorm.DB) error {
// Save the main character record
if err := tx.Create(character).Error; err != nil {
return fmt.Errorf("failed to save character: %w", err)
@@ -1,11 +1,9 @@
/*
User Handlers
Add handlers for user registration and login:
*/
package main
package character
import (
"bamort/database"
"bamort/models"
"encoding/json"
"fmt"
"net/http"
@@ -14,68 +12,8 @@ import (
"strings"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
)
func RegisterUser(c *gin.Context) {
var user User
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(user.PasswordHash), bcrypt.DefaultCost)
user.PasswordHash = string(hashedPassword)
if err := DB.Create(&user).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create user"})
return
}
c.JSON(http.StatusCreated, gin.H{"message": "User registered successfully:"})
}
func LoginUser(c *gin.Context) {
var user User
var input struct {
Username string `json:"username"`
Password string `json:"password"`
}
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid username. or password"})
return
}
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(input.Password)); err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid username or password."})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Login successful"})
}
// Apply middleware to protected routes
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.GetHeader("Authorization")
if token == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
// Add token validation logic here
c.Next()
}
}
/*
Character Handlers
@@ -83,8 +21,8 @@ Add CRUD operations for characters:
*/
func GetCharacters(c *gin.Context) {
var characters []Character
if err := DB.Find(&characters).Error; err != nil {
var characters []models.Char
if err := database.DB.Find(&characters).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve characters"})
return
}
@@ -92,13 +30,13 @@ func GetCharacters(c *gin.Context) {
}
func CreateCharacter(c *gin.Context) {
var character Character
var character models.Char
if err := c.ShouldBindJSON(&character); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := DB.Create(&character).Error; err != nil {
if err := database.DB.Create(&character).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create character"})
return
}
@@ -114,13 +52,13 @@ Allows users to add new equipment items for a specific character.
*/
func CreateAusruestung(c *gin.Context) {
var ausruestung Ausruestung
var ausruestung models.Ausruestung
if err := c.ShouldBindJSON(&ausruestung); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := DB.Create(&ausruestung).Error; err != nil {
if err := database.DB.Create(&ausruestung).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create Ausruestung"})
return
}
@@ -131,8 +69,8 @@ func CreateAusruestung(c *gin.Context) {
func GetAusruestung(c *gin.Context) {
characterID := c.Param("character_id")
var ausruestung []Ausruestung
if err := DB.Where("character_id = ?", characterID).Find(&ausruestung).Error; err != nil {
var ausruestung []models.Ausruestung
if err := database.DB.Where("character_id = ?", characterID).Find(&ausruestung).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve Ausruestung"})
return
}
@@ -142,9 +80,9 @@ func GetAusruestung(c *gin.Context) {
func UpdateAusruestung(c *gin.Context) {
ausruestungID := c.Param("ausruestung_id")
var ausruestung Ausruestung
var ausruestung models.Ausruestung
if err := DB.First(&ausruestung, ausruestungID).Error; err != nil {
if err := database.DB.First(&ausruestung, ausruestungID).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Ausruestung not found"})
return
}
@@ -154,7 +92,7 @@ func UpdateAusruestung(c *gin.Context) {
return
}
if err := DB.Save(&ausruestung).Error; err != nil {
if err := database.DB.Save(&ausruestung).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update Ausruestung"})
return
}
@@ -164,7 +102,7 @@ func UpdateAusruestung(c *gin.Context) {
func DeleteAusruestung(c *gin.Context) {
ausruestungID := c.Param("ausruestung_id")
if err := DB.Delete(&Ausruestung{}, ausruestungID).Error; err != nil {
if err := database.DB.Delete(&models.Ausruestung{}, ausruestungID).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete Ausruestung"})
return
}
@@ -212,7 +150,7 @@ func UploadFiles(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "Files uploaded successfully"})
// Open and parse JSON
var character Character
var character models.Char
filePath := fmt.Sprintf("./uploads/%s", file_vtt.Filename)
fileContent, err := os.ReadFile(filePath)
if err != nil {
@@ -225,7 +163,7 @@ func UploadFiles(c *gin.Context) {
}
// Save character data to the database
if err := saveCharacterToDB(&character); err != nil {
if err := SaveCharacterToDB(&character); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save character to database"})
return
}
@@ -246,31 +184,3 @@ func isValidFileType(filename string) bool {
}
return false
}
func SetupCheck(c *gin.Context) {
ConnectDatabase()
err := DB.AutoMigrate(&Character{},
&Fertigkeit{}, &Zauber{}, &Lp{},
&Eigenschaft{}, &Merkmale{},
&Bennies{},
&Gestalt{},
&Ap{}, &B{},
&Erfahrungsschatz{},
&MagischTransport{},
&Transportation{},
&MagischAusruestung{},
&Ausruestung{},
&MagischBehaelter{},
&Behaeltniss{},
&MagischWaffe{},
&Waffe{},
&Waffenfertigkeit{},
&StammFertigkeit{},
)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to automigrate DataBase"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Setup Check OK"})
}
+54
View File
@@ -0,0 +1,54 @@
package database
import (
"database/sql/driver"
"encoding/json"
"errors"
"log"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var DB *gorm.DB
func ConnectDatabase() *gorm.DB {
dsn := "bamort:bG4)efozrc@tcp(192.168.0.5:3306)/bamort?charset=utf8mb4&parseTime=True&loc=Local"
database, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("Failed to connect to database:", err)
}
DB = database
return DB
}
func GetDB() *gorm.DB {
if DB == nil {
DB = ConnectDatabase()
}
return DB
}
// StringArray is a custom type for []string
type StringArray []string
// Value implements the driver.Valuer interface for database storage
func (s StringArray) Value() (driver.Value, error) {
return json.Marshal(s) // Serialize []string to JSON
}
// Scan implements the sql.Scanner interface for database retrieval
func (s *StringArray) Scan(value interface{}) error {
if value == nil {
*s = []string{}
return nil
}
bytes, ok := value.([]byte)
if !ok {
return errors.New("failed to convert database value to []byte")
}
return json.Unmarshal(bytes, s) // Deserialize JSON to []string
}
+35
View File
@@ -0,0 +1,35 @@
package database
import (
"github.com/gin-gonic/gin"
)
func SetupCheck(c *gin.Context) {
ConnectDatabase()
/*
err := DB.AutoMigrate(&Character{},
&Fertigkeit{}, &Zauber{}, &Lp{},
&Eigenschaft{}, &Merkmale{},
&Bennies{},
&Gestalt{},
&Ap{}, &B{},
&Erfahrungsschatz{},
&MagischTransport{},
&Transportation{},
&MagischAusruestung{},
&Ausruestung{},
&MagischBehaelter{},
&Behaeltniss{},
&MagischWaffe{},
&Waffe{},
&Waffenfertigkeit{},
&StammFertigkeit{},
)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to automigrate DataBase"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Setup Check OK"})
*/
}
+14 -8
View File
@@ -1,7 +1,18 @@
//replace github.com/Bardioc26/bamort => ./ // or the path to the local directory
module bamort
go 1.23.2
require (
github.com/gin-contrib/cors v1.7.2
github.com/gin-gonic/gin v1.10.0
github.com/stretchr/testify v1.10.0
golang.org/x/crypto v0.31.0
gorm.io/driver/mysql v1.5.7
gorm.io/driver/sqlite v1.5.7
gorm.io/gorm v1.25.12
)
require (
filippo.io/edwards25519 v1.1.0 // indirect
github.com/bytedance/sonic v1.12.6 // indirect
@@ -10,10 +21,7 @@ require (
github.com/cloudwego/iasm v0.2.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/gabriel-vasile/mimetype v1.4.7 // indirect
github.com/gin-contrib/cors v1.7.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-gonic/gin v1.10.0 // indirect
github.com/go-bindata/go-bindata v3.1.2+incompatible // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.23.0 // indirect
@@ -23,6 +31,7 @@ require (
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.9 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-sqlite3 v1.14.24 // indirect
@@ -30,17 +39,14 @@ require (
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.10.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect
golang.org/x/arch v0.12.0 // indirect
golang.org/x/crypto v0.31.0 // indirect
golang.org/x/net v0.33.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/text v0.21.0 // indirect
google.golang.org/protobuf v1.36.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gorm.io/driver/mysql v1.5.7 // indirect
gorm.io/driver/sqlite v1.5.7 // indirect
gorm.io/gorm v1.25.12 // indirect
)
//replace github.com/Bardioc26/bamort => ./ // or the path to the local directory
+113
View File
@@ -0,0 +1,113 @@
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/bytedance/sonic v1.12.6 h1:/isNmCUF2x3Sh8RAp/4mh4ZGkcFAX/hLrzrK3AvpRzk=
github.com/bytedance/sonic v1.12.6/go.mod h1:B8Gt/XvtZ3Fqj+iSKMypzymZxw/FVwgIGKzMzT9r/rk=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/bytedance/sonic/loader v0.2.1 h1:1GgorWTqf12TA8mma4DDSbaQigE2wOgQo7iCjjJv3+E=
github.com/bytedance/sonic/loader v0.2.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.7 h1:SKFKl7kD0RiPdbht0s7hFtjl489WcQ1VyPW8ZzUMYCA=
github.com/gabriel-vasile/mimetype v1.4.7/go.mod h1:GDlAgAyIRT27BhFl53XNAFtfjzOkLaF35JdEG0P7LtU=
github.com/gin-contrib/cors v1.7.2 h1:oLDHxdg8W/XDoN/8zamqk/Drgt4oVZDvaV0YmvVICQw=
github.com/gin-contrib/cors v1.7.2/go.mod h1:SUJVARKgQ40dmrzgXEVxj2m7Ig1v1qIboQkPDTQ9t2E=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.23.0 h1:/PwmTwZhS0dPkav3cdK9kV1FsAmrL8sThn8IHr/sO+o=
github.com/go-playground/validator/v10 v10.23.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
github.com/go-sql-driver/mysql v1.7.0/go.mod h1:OXbVy3sEdcQ2Doequ6Z5BW6fXNQTmx+9S1MCJN5yJMI=
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/goccy/go-json v0.10.4 h1:JSwxQzIqKfmFX1swYPpUThQZp/Ka4wzJdK0LWVytLPM=
github.com/goccy/go-json v0.10.4/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.9 h1:66ze0taIn2H33fBvCkXuv9BmCwDfafmiIVpKV9kKGuY=
github.com/klauspost/cpuid/v2 v2.2.9/go.mod h1:rqkxqrZ1EhYM9G+hXH7YdowN5R5RGN6NK4QwQ3WMXF8=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM=
github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
golang.org/x/arch v0.12.0 h1:UsYJhbzPYGsT0HbEdmYcqtCv8UNGvnaL561NnIUvaKg=
golang.org/x/arch v0.12.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.36.0 h1:mjIs9gYtt56AzC4ZaffQuh88TZurBGhIJMBZGSxNerQ=
google.golang.org/protobuf v1.36.0/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/mysql v1.5.7 h1:MndhOPYOfEp2rHKgkZIhJ16eVUIRf2HmzgoPmh7FCWo=
gorm.io/driver/mysql v1.5.7/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
gorm.io/driver/sqlite v1.5.7 h1:8NvsrhP0ifM7LX9G4zPB97NwovUakUxc+2V2uuf3Z1I=
gorm.io/driver/sqlite v1.5.7/go.mod h1:U+J8craQU6Fzkcvu8oLeAQmi50TkwPEhHDEjQZXDah4=
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
gorm.io/gorm v1.25.12 h1:I0u8i2hWQItBq1WfE0o2+WuL9+8L21K9e2HHSTE/0f8=
gorm.io/gorm v1.25.12/go.mod h1:xh7N7RHfYlNc5EmcI/El95gXusucDrQnHXe0+CgWcLQ=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
+43
View File
@@ -0,0 +1,43 @@
package main
import (
"bamort/character"
"bamort/database"
"bamort/user"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {
database.ConnectDatabase()
//database.DB.AutoMigrate(&models.User{}, &models.Character{}) // Add other models here
r := gin.Default()
// Add CORS middleware
r.Use(cors.New(cors.Config{
//AllowOrigins: []string{"http://localhost:3000"}, // Replace with your frontend's URL
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE"},
AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
}))
// Routes
r.POST("/register", user.RegisterUser)
r.POST("/login", user.LoginUser)
protected := r.Group("/api")
protected.Use(user.AuthMiddleware())
protected.GET("/characters", character.GetCharacters)
protected.POST("/characters", character.CreateCharacter)
protected.POST("/ausruestung", character.CreateAusruestung)
protected.GET("/ausruestung/:character_id", character.GetAusruestung)
protected.PUT("/ausruestung/:ausruestung_id", character.UpdateAusruestung)
protected.DELETE("/ausruestung/:ausruestung_id", character.DeleteAusruestung)
protected.POST("/upload", character.UploadFiles)
protected.GET("/setupcheck", database.SetupCheck)
r.Run(":8180") // Start server on port 8080
}
+175
View File
@@ -0,0 +1,175 @@
package models
type ImEigenschaft struct {
ID uint `json:"id"`
Name string `json:"name"`
Value int `json:"value"`
}
type ImAusruestung struct {
ID string `json:"id"`
Name string `json:"name"`
Beschreibung string `json:"beschreibung"`
Anzahl int `json:"anzahl"`
BeinhaltetIn *string `json:"beinhaltet_in"`
Bonus int `json:"bonus,omitempty"`
Gewicht float64 `json:"gewicht"`
Magisch ImMagisch `gorm:"foreignKey:ID" json:"magisch"`
Wert float64 `json:"wert"`
}
type ImFertigkeit struct {
ID string `json:"id"`
Name string `json:"name"`
Beschreibung string `json:"beschreibung"`
Fertigkeitswert int `json:"fertigkeitswert"`
Bonus int `json:"bonus,omitempty"`
Pp int `json:"pp,omitempty"`
Quelle string `json:"quelle"`
}
type ImZauber struct {
ID string `json:"id"`
Name string `json:"name"`
Beschreibung string `json:"beschreibung"`
Bonus int `json:"bonus"`
Quelle string `json:"quelle"`
}
type ImWaffenfertigkeit struct {
ID string `json:"id"`
Name string `json:"name"`
Beschreibung string `json:"beschreibung"`
Bonus int `json:"bonus"`
Fertigkeitswert int `json:"fertigkeitswert"`
Pp int `json:"pp"`
Quelle string `json:"quelle"`
}
type ImWaffe struct {
ID string `json:"id"`
Name string `json:"name"`
Beschreibung string `json:"beschreibung"`
Abwb int `json:"abwb"`
Anb int `json:"anb"`
Anzahl int `json:"anzahl"`
BeinhaltetIn *string `json:"beinhaltet_in"`
Gewicht float64 `json:"gewicht"`
Magisch ImMagisch `json:"magisch"`
NameFuerSpezialisierung string `json:"nameFuerSpezialisierung"`
Schb int `json:"schb"`
Wert float64 `json:"wert"`
}
type ImMerkmale struct {
Augenfarbe string `json:"augenfarbe"`
Haarfarbe string `json:"haarfarbe"`
Sonstige string `json:"sonstige"`
}
type ImLp struct {
Max int `json:"max"`
Value int `json:"value"`
}
type ImGestalt struct {
Breite string `json:"breite"`
Groesse string `json:"groesse"`
}
type ImErfahrungsschatz struct {
Value int `json:"value"`
}
type ImEigenschaften struct {
Au int `json:"au"`
Gs int `json:"gs"`
Gw int `json:"gw"`
In int `json:"in"`
Ko int `json:"ko"`
Pa int `json:"pa"`
St int `json:"st"`
Wk int `json:"wk"`
Zt int `json:"zt"`
}
type ImBennies struct {
Gg int `json:"gg"`
Gp int `json:"gp"`
Sg int `json:"sg"`
}
type ImBehaeltniss struct {
ID string `json:"id"`
Name string `json:"name"`
Beschreibung string `json:"beschreibung"`
BeinhaltetIn any `json:"beinhaltet_in"`
Gewicht float64 `json:"gewicht"`
Magisch ImMagisch `gorm:"foreignKey:ID" json:"magisch"`
Tragkraft float64 `json:"tragkraft"`
Volumen float64 `json:"volumen"`
Wert float64 `json:"wert"`
}
type ImAp struct {
Max int `json:"max"`
Value int `json:"value"`
}
type ImB struct {
Max int `json:"max"`
Value int `json:"value"`
}
type ImTransportation struct {
ID string `json:"id"`
Name string `json:"name"`
Beschreibung string `json:"beschreibung"`
BeinhaltetIn any `json:"beinhaltet_in"`
Gewicht int `json:"gewicht"`
Tragkraft float64 `json:"tragkraft"`
Wert float64 `json:"wert"`
Magisch ImMagisch `gorm:"foreignKey:ID" json:"magisch"`
//Magisch Magisch `gorm:"polymorphic:Item;polymorphicValue:Transportmittel" json:"magisch"`
}
type ImMagisch struct {
Abw int `json:"abw"`
Ausgebrannt bool `json:"ausgebrannt"`
IstMagisch bool `json:"ist_magisch"`
}
/*
Define models for each table
Add other models for Ausruestung, Fertigkeiten, etc., following the same pattern.
*/
type ImCharacterImport struct {
ID string `json:"id"`
Name string `json:"name"`
Rasse string `json:"rasse"`
Typ string `json:"typ"`
Alter int `json:"alter"`
Anrede string `json:"anrede"`
Grad int `json:"grad"`
Groesse int `json:"groesse"`
Gewicht int `json:"gewicht"`
Glaube string `json:"glaube"`
Hand string `json:"hand"`
Fertigkeiten []ImFertigkeit `json:"fertigkeiten"`
Zauber []ImZauber `json:"zauber"`
Lp ImLp `json:"lp"`
Eigenschaften ImEigenschaften `json:"eigenschaften"`
Merkmale ImMerkmale `json:"merkmale"`
Bennies ImBennies `json:"bennies"`
Gestalt ImGestalt `json:"gestalt"`
Ap ImAp `json:"ap"`
B ImB `json:"b"`
Erfahrungsschatz ImErfahrungsschatz `json:"erfahrungsschatz"`
Transportmittel []ImTransportation `json:"transportmittel"`
Ausruestung []ImAusruestung `json:"ausruestung"`
Behaeltnisse []ImBehaeltniss `json:"behaeltnisse"`
Waffen []ImWaffe `json:"waffen"`
Waffenfertigkeiten []ImWaffenfertigkeit `json:"waffenfertigkeiten"`
Spezialisierung []string `json:"spezialisierung"`
Image string `json:"image,omitempty"`
}
+33 -81
View File
@@ -1,4 +1,6 @@
package main
package models
import "bamort/database"
type User struct {
UserID uint `gorm:"primaryKey"`
@@ -7,38 +9,36 @@ type User struct {
Email string `gorm:"unique"`
}
type Character struct {
ID uint `gorm:"primaryKey" json:"dbid"`
ImportID string `json:"id"`
Name string `json:"name"`
Rasse string `json:"rasse"`
Typ string `json:"typ"`
Alter int `json:"alter"`
Anrede string `json:"anrede"`
Grad int `json:"grad"`
Groesse int `json:"groesse"`
Gewicht int `json:"gewicht"`
Glaube string `json:"glaube"`
Hand string `json:"hand"`
Fertigkeiten []Fertigkeit `gorm:"foreignKey:CharacterID" json:"fertigkeiten"`
Zauber []Zauber `gorm:"foreignKey:CharacterID" json:"zauber"`
Lp Lp `gorm:"foreignKey:CharacterID" json:"lp"`
Eigenschaften []Eigenschaft `gorm:"foreignKey:CharacterID" json:"eigenschaften"`
Merkmale Merkmale `gorm:"foreignKey:CharacterID" json:"merkmale"`
Bennies Bennies `gorm:"foreignKey:CharacterID" json:"bennies"`
Gestalt Gestalt `gorm:"foreignKey:CharacterID" json:"gestalt"`
Ap Ap `gorm:"foreignKey:CharacterID" json:"ap"`
B B `gorm:"foreignKey:CharacterID" json:"b"`
Erfahrungsschatz Erfahrungsschatz `gorm:"foreignKey:CharacterID" json:"erfahrungsschatz"`
Transportmittel []Transportation `gorm:"foreignKey:CharacterID" json:"transportmittel"`
Ausruestung []Ausruestung `gorm:"foreignKey:CharacterID" json:"ausruestung"`
Behaeltnisse []Behaeltniss `gorm:"foreignKey:CharacterID" json:"behaeltnisse"`
Waffen []Waffe `gorm:"foreignKey:CharacterID" json:"waffen"`
Waffenfertigkeiten []Waffenfertigkeit `gorm:"foreignKey:CharacterID" json:"waffenfertigkeiten"`
Spezialisierung StringArray `gorm:"type:TEXT" json:"spezialisierung"`
/*
Image string `json:"image,omitempty"`
*/
type Char struct {
ID uint `gorm:"primaryKey" json:"dbid"`
ImportID string `json:"id"`
Name string `json:"name"`
Rasse string `json:"rasse"`
Typ string `json:"typ"`
Alter int `json:"alter"`
Anrede string `json:"anrede"`
Grad int `json:"grad"`
Groesse int `json:"groesse"`
Gewicht int `json:"gewicht"`
Glaube string `json:"glaube"`
Hand string `json:"hand"`
Fertigkeiten []Fertigkeit `gorm:"foreignKey:CharacterID" json:"fertigkeiten"`
Zauber []Zauber `gorm:"foreignKey:CharacterID" json:"zauber"`
Lp Lp `gorm:"foreignKey:CharacterID" json:"lp"`
Eigenschaften []Eigenschaft `gorm:"foreignKey:CharacterID" json:"eigenschaften"`
Merkmale Merkmale `gorm:"foreignKey:CharacterID" json:"merkmale"`
Bennies Bennies `gorm:"foreignKey:CharacterID" json:"bennies"`
Gestalt Gestalt `gorm:"foreignKey:CharacterID" json:"gestalt"`
Ap Ap `gorm:"foreignKey:CharacterID" json:"ap"`
B B `gorm:"foreignKey:CharacterID" json:"b"`
Erfahrungsschatz Erfahrungsschatz `gorm:"foreignKey:CharacterID" json:"erfahrungsschatz"`
Transportmittel []Transportation `gorm:"foreignKey:CharacterID" json:"transportmittel"`
Ausruestung []Ausruestung `gorm:"foreignKey:CharacterID" json:"ausruestung"`
Behaeltnisse []Behaeltniss `gorm:"foreignKey:CharacterID" json:"behaeltnisse"`
Waffen []Waffe `gorm:"foreignKey:CharacterID" json:"waffen"`
Waffenfertigkeiten []Waffenfertigkeit `gorm:"foreignKey:CharacterID" json:"waffenfertigkeiten"`
Spezialisierung database.StringArray `gorm:"type:TEXT" json:"spezialisierung"`
Image string `json:"image,omitempty"`
}
type Eigenschaft struct {
@@ -242,51 +242,3 @@ type MagischTransport struct {
Ausgebrannt bool `json:"ausgebrannt"`
IstMagisch bool `json:"ist_magisch"`
}
/*
Define models for each table
Add other models for Ausruestung, Fertigkeiten, etc., following the same pattern.
*/
type CharacterImport struct {
ID uint `gorm:"primaryKey" json:"dbid"`
ImportID string `json:"id"`
Name string `json:"name"`
Rasse string `json:"rasse"`
Typ string `json:"typ"`
Alter int `json:"alter"`
Anrede string `json:"anrede"`
Grad int `json:"grad"`
Groesse int `json:"groesse"`
Gewicht int `json:"gewicht"`
Glaube string `json:"glaube"`
Hand string `json:"hand"`
Fertigkeiten []Fertigkeit `gorm:"foreignKey:CharacterID" json:"fertigkeiten"`
Zauber []Zauber `gorm:"foreignKey:CharacterID" json:"zauber"`
Lp Lp `gorm:"foreignKey:CharacterID" json:"lp"`
Eigenschaften Eigenschaften `gorm:"foreignKey:CharacterID" json:"eigenschaften"`
Merkmale Merkmale `gorm:"foreignKey:CharacterID" json:"merkmale"`
Bennies Bennies `gorm:"foreignKey:CharacterID" json:"bennies"`
Gestalt Gestalt `gorm:"foreignKey:CharacterID" json:"gestalt"`
Ap Ap `gorm:"foreignKey:CharacterID" json:"ap"`
B B `gorm:"foreignKey:CharacterID" json:"b"`
Erfahrungsschatz Erfahrungsschatz `gorm:"foreignKey:CharacterID" json:"erfahrungsschatz"`
Transportmittel []Transportation `gorm:"foreignKey:CharacterID" json:"transportmittel"`
Ausruestung []Ausruestung `gorm:"foreignKey:CharacterID" json:"ausruestung"`
Behaeltnisse []Behaeltniss `gorm:"foreignKey:CharacterID" json:"behaeltnisse"`
Waffen []Waffe `gorm:"foreignKey:CharacterID" json:"waffen"`
Waffenfertigkeiten []Waffenfertigkeit `gorm:"foreignKey:CharacterID" json:"waffenfertigkeiten"`
Spezialisierung StringArray `gorm:"type:TEXT" json:"spezialisierung"`
/*
Image string `json:"image,omitempty"`
*/
}
type StammFertigkeit struct {
ID uint `gorm:"primaryKey" json:"id"`
System string `gorm:"index" json:"system"`
Name string `json:"name"`
Beschreibung string `json:"beschreibung"`
Initialkeitswert int `json:"initialwert"`
Bonuseigenschaft string `json:"bonuseigenschaft,omitempty"`
Quelle string `json:"quelle"`
}
@@ -1,17 +1,18 @@
package main
package models
import (
"bamort/database"
"fmt"
"strings"
"gorm.io/gorm"
)
func CheckFertigkeit(fertigkeit *Fertigkeit, autocreate bool) (*StammFertigkeit, error) {
stammF := StammFertigkeit{}
func CheckFertigkeit(fertigkeit *ImFertigkeit, autocreate bool) (*ImStammFertigkeit, error) {
stammF := ImStammFertigkeit{}
if strings.HasPrefix(fertigkeit.ImportID, "moam") {
err := DB.First(&stammF, "system=? AND name = ?", "midgard", fertigkeit.Name).Error
if strings.HasPrefix(fertigkeit.ID, "moam") {
err := database.DB.First(&stammF, "system=? AND name = ?", "midgard", fertigkeit.Name).Error
if err == nil {
// Fertigkeit found
return &stammF, nil
@@ -30,7 +31,7 @@ func CheckFertigkeit(fertigkeit *Fertigkeit, autocreate bool) (*StammFertigkeit,
stammF.Bonuseigenschaft = "keine"
stammF.Quelle = fertigkeit.Quelle
//fmt.Println(stammF)
err = DB.Transaction(func(tx *gorm.DB) error {
err = database.DB.Transaction(func(tx *gorm.DB) error {
// Save the main character record
if err := tx.Create(&stammF).Error; err != nil {
return fmt.Errorf("failed to save Fertigkeit Stammdaten: %w", err)
@@ -43,10 +44,20 @@ func CheckFertigkeit(fertigkeit *Fertigkeit, autocreate bool) (*StammFertigkeit,
}
}
err := DB.First(&stammF, "system=? AND name = ?", "midgard", fertigkeit.Name).Error
err := database.DB.First(&stammF, "system=? AND name = ?", "midgard", fertigkeit.Name).Error
if err != nil {
// Fertigkeit found
return nil, err
}
return &stammF, nil
}
type ImStammFertigkeit struct {
ID uint `gorm:"primaryKey" json:"id"`
System string `gorm:"index" json:"system"`
Name string `json:"name"`
Beschreibung string `json:"beschreibung"`
Initialkeitswert int `json:"initialwert"`
Bonuseigenschaft string `json:"bonuseigenschaft,omitempty"`
Quelle string `json:"quelle"`
}
File diff suppressed because one or more lines are too long
@@ -1,6 +1,8 @@
package main
import (
"bamort/database"
"bamort/models"
"encoding/json"
"fmt"
"os"
@@ -15,21 +17,22 @@ func TestImportVTT(t *testing.T) {
//DB = testDB // Assign test DB to global DB
// loading file to Modell
fileName := fmt.Sprintf("./uploads/%s", "test.json")
fileName := fmt.Sprintf("../testdata/%s", "VTT_Import1.json")
assert.Equal(t, "../testdata/VTT_Import1.json", fileName)
fileContent, err := os.ReadFile(fileName)
assert.NoError(t, err, "Expected no error when reading file "+fileName)
character := CharacterImport{}
character := models.ImCharacterImport{}
err = json.Unmarshal(fileContent, &character)
assert.NoError(t, err, "Expected no error when Unmarshal filecontent")
assert.Equal(t, "Harsk Hammerhuter, Zen", character.Name)
assert.Equal(t, "Zwerg", character.Rasse)
assert.Equal(t, "Hören", character.Fertigkeiten[0].Name)
assert.Equal(t, 0, len(character.Zauber))
assert.Equal(t, 1, len(character.Zauber))
assert.Equal(t, 17, character.Lp.Value)
assert.Equal(t, 96, character.Eigenschaften.Gs)
assert.Equal(t, 74, character.Eigenschaften.Au)
assert.Equal(t, 21, len(character.Ausruestung))
assert.Equal(t, 1, len(character.Ausruestung))
assert.Equal(t, "Lederrüstung", character.Ausruestung[0].Name)
assert.Equal(t, "blau", character.Merkmale.Augenfarbe)
assert.Equal(t, "Lederrucksack", character.Behaeltnisse[0].Name)
@@ -46,12 +49,13 @@ func TestImportVTT(t *testing.T) {
func TestImportFertigkeitenStammdaten(t *testing.T) {
// Setup test database
testDB := SetupTestDB()
DB = testDB // Assign test DB to global DB
database.DB = testDB // Assign test DB to global DB
// loading file to Modell
fileName := fmt.Sprintf("./uploads/%s", "test.json")
fileName := fmt.Sprintf("../testdata/%s", "VTT_Import1.json")
assert.Equal(t, "../testdata/VTT_Import1.json", fileName)
fileContent, err := os.ReadFile(fileName)
assert.NoError(t, err, "Expected no error when reading file "+fileName)
character := CharacterImport{}
character := models.ImCharacterImport{}
err = json.Unmarshal(fileContent, &character)
assert.NoError(t, err, "Expected no error when Unmarshal filecontent")
@@ -86,10 +90,10 @@ func TestImportFertigkeitenStammdaten(t *testing.T) {
}
err = DB.First(&stammF, "system=? AND name = ?", "midgard", fertigkeit.Name).Error
fmt.Println(stammF) */
stammF, err := CheckFertigkeit(&fertigkeit, false)
stammF, err := models.CheckFertigkeit(&fertigkeit, false)
assert.Error(t, err, "expexted Error does not exist in Fertigkeit Stammdaten")
if stammF == nil && err != nil {
stammF, err = CheckFertigkeit(&fertigkeit, true)
stammF, err = models.CheckFertigkeit(&fertigkeit, true)
}
assert.NoError(t, err, "Expected to finds the Fertigkeit Stammdaten in the database")
assert.Equal(t, fertigkeit.Name, stammF.Name)
@@ -1,6 +1,9 @@
package main
import (
"bamort/character"
"bamort/database"
"bamort/models"
"testing"
"github.com/stretchr/testify/assert"
@@ -16,23 +19,23 @@ func SetupTestDB() *gorm.DB {
}
// Auto-migrate the schemas for all related models
db.AutoMigrate(&Character{},
&Fertigkeit{}, &Zauber{}, &Lp{},
&Eigenschaft{}, &Merkmale{},
&Bennies{},
&Gestalt{},
&Ap{}, &B{},
&Erfahrungsschatz{},
&MagischTransport{},
&Transportation{},
&MagischAusruestung{},
&Ausruestung{},
&MagischBehaelter{},
&Behaeltniss{},
&MagischWaffe{},
&Waffe{},
&Waffenfertigkeit{},
&StammFertigkeit{},
db.AutoMigrate(&models.Char{},
&models.Fertigkeit{}, &models.Zauber{}, &models.Lp{},
&models.Eigenschaft{}, &models.Merkmale{},
&models.Bennies{},
&models.Gestalt{},
&models.Ap{}, &models.B{},
&models.Erfahrungsschatz{},
&models.MagischTransport{},
&models.Transportation{},
&models.MagischAusruestung{},
&models.Ausruestung{},
&models.MagischBehaelter{},
&models.Behaeltniss{},
&models.MagischWaffe{},
&models.Waffe{},
&models.Waffenfertigkeit{},
&models.ImStammFertigkeit{},
)
return db
}
@@ -40,10 +43,10 @@ func SetupTestDB() *gorm.DB {
func TestSaveCharacterToDB(t *testing.T) {
// Setup test database
testDB := SetupTestDB()
DB = testDB // Assign test DB to global DB
database.DB = testDB // Assign test DB to global DB
// Define a sample character for testing
character := &Character{
char := &models.Char{
Name: "Test Character",
Rasse: "Elf",
Typ: "Mage",
@@ -54,71 +57,71 @@ func TestSaveCharacterToDB(t *testing.T) {
Gewicht: 70,
Glaube: "None",
Hand: "Right",
Eigenschaften: []Eigenschaft{
Eigenschaften: []models.Eigenschaft{
{Name: "Au", Value: 50},
{Name: "St", Value: 80},
{Name: "Zt", Value: 100},
},
Fertigkeiten: []Fertigkeit{
Fertigkeiten: []models.Fertigkeit{
{Name: "Stehlen", Beschreibung: "jemandem etwas wegnehmen ohne das der es merkt", Fertigkeitswert: 6},
{Name: "Geländelauf", Beschreibung: "Lauf um Hindernisse herum", Fertigkeitswert: 12},
},
Zauber: []Zauber{
Zauber: []models.Zauber{
{Name: "Fireball", Beschreibung: "Cast a fireball", Bonus: 0, Quelle: "Ark 20"},
},
Lp: Lp{
Lp: models.Lp{
Max: 100,
Value: 80,
},
Merkmale: Merkmale{
Merkmale: models.Merkmale{
Augenfarbe: "Blau",
Haarfarbe: "Blonde",
Sonstige: "Scar on the left cheek",
},
Bennies: Bennies{
Bennies: models.Bennies{
Gg: 1,
Gp: 0,
Sg: 2,
},
Gestalt: Gestalt{
Gestalt: models.Gestalt{
Breite: "schmal",
Groesse: "klein",
},
Ap: Ap{
Ap: models.Ap{
Max: 50,
Value: 40,
},
B: B{
B: models.B{
Max: 25,
Value: 20,
},
Erfahrungsschatz: Erfahrungsschatz{
Erfahrungsschatz: models.Erfahrungsschatz{
Value: 2768,
},
Transportmittel: []Transportation{
Transportmittel: []models.Transportation{
{Name: "Karren",
Beschreibung: "ein Karren",
Gewicht: 100, Tragkraft: 300, Wert: 55,
Magisch: MagischTransport{IstMagisch: true, Abw: 30, Ausgebrannt: false},
Magisch: models.MagischTransport{IstMagisch: true, Abw: 30, Ausgebrannt: false},
},
},
Ausruestung: []Ausruestung{
Ausruestung: []models.Ausruestung{
{Name: "Staff", Beschreibung: "Magic Staff", Anzahl: 1, Gewicht: 2.5, Wert: 500,
Magisch: MagischAusruestung{IstMagisch: true, Abw: 10, Ausgebrannt: false},
Magisch: models.MagischAusruestung{IstMagisch: true, Abw: 10, Ausgebrannt: false},
},
},
Behaeltnisse: []Behaeltniss{
Behaeltnisse: []models.Behaeltniss{
{Name: "Backpack", Beschreibung: "Leather backpack",
Gewicht: 1.5, Tragkraft: 10, Volumen: 20, Wert: 50,
//Magisch: MagischBehaelter{IstMagisch: false},
},
},
Waffen: []Waffe{
Waffen: []models.Waffe{
{Name: "Schwert", Beschreibung: "Ein schwert", Abwb: 0, Anb: 0, Gewicht: 1.5, NameFuerSpezialisierung: "Schwert", Schb: 0, Wert: 3,
Magisch: MagischWaffe{IstMagisch: false}},
Magisch: models.MagischWaffe{IstMagisch: false}},
},
Waffenfertigkeiten: []Waffenfertigkeit{
Waffenfertigkeiten: []models.Waffenfertigkeit{
{Name: "Einhandschlagwaffe", Beschreibung: "z.B. für Kurzschwerter", Bonus: 0,
Fertigkeitswert: 12, Pp: 1, Quelle: "Kod 256"},
},
@@ -127,18 +130,18 @@ func TestSaveCharacterToDB(t *testing.T) {
},
}
//fmt.Println(character)
//fmt.Println(char)
// Call the function being tested
err := saveCharacterToDB(character)
err := character.SaveCharacterToDB(char)
assert.NoError(t, err, "Expected no error when saving character to DB")
//fmt.Println(character)
//fmt.Println(char)
// Verify that the character was saved
var savedCharacter Character
var savedChar models.Char
//err = DB.Preload("Eigenschaften").Preload("Ausruestung").Preload("Behaeltnisse").
// Preload("Fertigkeiten").Preload("Merkmale").Preload("Lp").Preload("Ap").
err = DB.
err = database.DB.
Preload("Eigenschaften").
Preload("Fertigkeiten").
Preload("Zauber").
@@ -155,25 +158,25 @@ func TestSaveCharacterToDB(t *testing.T) {
Preload("Behaeltnisse").
Preload("Waffen").
Preload("Waffenfertigkeiten").
First(&savedCharacter, "name = ?", "Test Character").Error
First(&savedChar, "name = ?", "Test Character").Error
assert.NoError(t, err, "Expected to find the character in the database")
assert.Equal(t, "Test Character", savedCharacter.Name)
assert.Equal(t, "Elf", savedCharacter.Rasse)
assert.Equal(t, "Stehlen", savedCharacter.Fertigkeiten[0].Name)
assert.Equal(t, "Fireball", savedCharacter.Zauber[0].Name)
assert.Equal(t, 80, savedCharacter.Lp.Value)
assert.Equal(t, 3, len(savedCharacter.Eigenschaften))
assert.Equal(t, "Au", savedCharacter.Eigenschaften[0].Name)
assert.Equal(t, 50, savedCharacter.Eigenschaften[0].Value)
assert.Equal(t, "Blau", savedCharacter.Merkmale.Augenfarbe)
assert.Equal(t, 1, len(savedCharacter.Ausruestung))
assert.Equal(t, "Staff", savedCharacter.Ausruestung[0].Name)
assert.Equal(t, "Blau", savedCharacter.Merkmale.Augenfarbe)
assert.Equal(t, "Backpack", savedCharacter.Behaeltnisse[0].Name)
assert.Equal(t, "Schwert", savedCharacter.Waffen[0].Name)
assert.Equal(t, 40, savedCharacter.Ap.Value)
assert.Equal(t, "Einhandschlagwaffe", savedCharacter.Waffenfertigkeiten[0].Name)
assert.Equal(t, 2, len(savedCharacter.Spezialisierung))
assert.Equal(t, "Bogen", savedCharacter.Spezialisierung[0])
assert.Equal(t, "Streitaxt", savedCharacter.Spezialisierung[1])
assert.Equal(t, "Test Character", savedChar.Name)
assert.Equal(t, "Elf", savedChar.Rasse)
assert.Equal(t, "Stehlen", savedChar.Fertigkeiten[0].Name)
assert.Equal(t, "Fireball", savedChar.Zauber[0].Name)
assert.Equal(t, 80, savedChar.Lp.Value)
assert.Equal(t, 3, len(savedChar.Eigenschaften))
assert.Equal(t, "Au", savedChar.Eigenschaften[0].Name)
assert.Equal(t, 50, savedChar.Eigenschaften[0].Value)
assert.Equal(t, "Blau", savedChar.Merkmale.Augenfarbe)
assert.Equal(t, 1, len(savedChar.Ausruestung))
assert.Equal(t, "Staff", savedChar.Ausruestung[0].Name)
assert.Equal(t, "Blau", savedChar.Merkmale.Augenfarbe)
assert.Equal(t, "Backpack", savedChar.Behaeltnisse[0].Name)
assert.Equal(t, "Schwert", savedChar.Waffen[0].Name)
assert.Equal(t, 40, savedChar.Ap.Value)
assert.Equal(t, "Einhandschlagwaffe", savedChar.Waffenfertigkeiten[0].Name)
assert.Equal(t, 2, len(savedChar.Spezialisierung))
assert.Equal(t, "Bogen", savedChar.Spezialisierung[0])
assert.Equal(t, "Streitaxt", savedChar.Spezialisierung[1])
}
+75
View File
@@ -0,0 +1,75 @@
/*
User Handlers
Add handlers for user registration and login:
*/
package user
import (
"bamort/database"
"bamort/models"
"net/http"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/bcrypt"
)
func RegisterUser(c *gin.Context) {
var user models.User
if err := c.ShouldBindJSON(&user); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(user.PasswordHash), bcrypt.DefaultCost)
user.PasswordHash = string(hashedPassword)
if err := database.DB.Create(&user).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create user"})
return
}
c.JSON(http.StatusCreated, gin.H{"message": "User registered successfully:"})
}
func LoginUser(c *gin.Context) {
var user models.User
var input struct {
Username string `json:"username"`
Password string `json:"password"`
}
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := database.DB.Where("username = ?", input.Username).First(&user).Error; err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid username. or password"})
return
}
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(input.Password)); err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid username or password."})
return
}
c.JSON(http.StatusOK, gin.H{"message": "Login successful"})
}
// Apply middleware to protected routes
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.GetHeader("Authorization")
if token == "" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
c.Abort()
return
}
// Add token validation logic here
c.Next()
}
}
-37
View File
@@ -1,37 +0,0 @@
package main
import (
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func main() {
ConnectDatabase()
DB.AutoMigrate(&User{}, &Character{}, &Eigenschaft{}) // Add other models here
r := gin.Default()
// Add CORS middleware
r.Use(cors.New(cors.Config{
//AllowOrigins: []string{"http://localhost:3000"}, // Replace with your frontend's URL
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "DELETE"},
AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
}))
// Routes
r.POST("/register", RegisterUser)
r.POST("/login", LoginUser)
r.GET("/characters", AuthMiddleware(), GetCharacters)
r.POST("/characters", AuthMiddleware(), CreateCharacter)
r.POST("/ausruestung", AuthMiddleware(), CreateAusruestung)
r.GET("/ausruestung/:character_id", AuthMiddleware(), GetAusruestung)
r.PUT("/ausruestung/:ausruestung_id", AuthMiddleware(), UpdateAusruestung)
r.DELETE("/ausruestung/:ausruestung_id", AuthMiddleware(), DeleteAusruestung)
r.POST("/upload", AuthMiddleware(), UploadFiles)
r.GET("/setupcheck", AuthMiddleware(), SetupCheck)
r.Run(":8180") // Start server on port 8080
}
+2
View File
@@ -0,0 +1,2 @@
Moam_export
CharType.go
File diff suppressed because one or more lines are too long
+6
View File
@@ -0,0 +1,6 @@
FROM node:21.6-alpine
WORKDIR /vue_app
expose 8080
CMD ["npm", "run", "serve"]
+29
View File
@@ -0,0 +1,29 @@
# =========== 1) Build stage ===========
FROM golang:1.20-alpine AS builder
# Create and set working directory
WORKDIR /app
# Copy go.mod and go.sum first, then download dependencies
COPY go.mod go.sum ./
RUN go mod download
# Copy the rest of the backend code
COPY . .
# Build the Go binary
RUN go build -o server main.go
# =========== 2) Runtime stage ===========
FROM alpine:3.18
WORKDIR /app
# Copy the compiled binary from builder stage
COPY --from=builder /app/server /app
# Expose port 8080 (or your backend port)
EXPOSE 8080
# Run the Go server
CMD ["./server"]
+27
View File
@@ -0,0 +1,27 @@
# =========== 1) Build stage ===========
FROM node:18-alpine AS build
WORKDIR /usr/src/app
# Copy package manifests and install dependencies
COPY package*.json ./
RUN npm install
# Copy the rest of the frontend code
COPY . .
# Build the production bundle
RUN npm run build
# =========== 2) Serve stage ===========
FROM nginx:alpine
# Copy production build to Nginx html folder.
# Adjust /usr/src/app/build -> /usr/src/app/dist if youre using Angular/Vue
COPY --from=build /usr/src/app/build /usr/share/nginx/html
# Expose HTTP port
EXPOSE 80
# Run Nginx in foreground
CMD ["nginx", "-g", "daemon off;"]
+28
View File
@@ -0,0 +1,28 @@
#FROM node:14
FROM node:21.6-slim
RUN apt update; apt install -y curl
WORKDIR /vue-setup
RUN npm install -g @vue/cli
RUN npm install -g vite
# The following commands ensure access to our files
# If we left them out, changing files on our local setup
# would fail due to insufficient permissions.
RUN userdel -r node
ARG USER_ID
ARG GROUP_ID
RUN addgroup --gid $GROUP_ID user
RUN adduser --disabled-password --gecos '' --uid $USER_ID --gid $GROUP_ID user
# Set the active user and open the interactive terminal
USER user
ENTRYPOINT [ "bash" ]
+4
View File
@@ -0,0 +1,4 @@
# Build an image named vue_helper using the Setup.Dockerfile
# The build args manage permissions when executing commands from inside the container
#
docker build -f ./dockerfiles/Dev.Dockerfile -t vue_app:dev vue_app
+7
View File
@@ -0,0 +1,7 @@
# Build an image named vue_helper using the Setup.Dockerfile
# The build args manage permissions when executing commands from inside the container
#
docker build \
--build-arg USER_ID=$(id -u) \
--build-arg GROUP_ID=$(id -g) \
-t vue_helper:slim - < ./dockerfiles/Setup.Dockerfile
+49
View File
@@ -0,0 +1,49 @@
version: "3.8"
services:
mariadb:
image: mariadb:10.7
container_name: my_mariadb
environment:
- MYSQL_ROOT_PASSWORD=1234
- MYSQL_DATABASE=rollenspiel_db
ports:
- "3306:3306"
volumes:
- db_data:/var/lib/mysql
command: ['--character-set-server=utf8mb4', '--collation-server=utf8mb4_unicode_ci']
backend:
build:
context: ../backend
dockerfile: Dockerfile
container_name: backend
# environment:
# - YOUR_ENV=example
environment:
DB_HOST: mariadb
DB_USER: root
DB_PASS: 1234
DB_NAME: rollenspiel_db
ports:
- "8080:8080"
# volumes:
# - ./some-local-folder:/app/some-folder
# You can add more configuration as needed.
depends_on:
- mariadb
frontend:
build:
context: ../frontend
dockerfile: Dockerfile.frontend
container_name: frontend
ports:
- "3000:80"
depends_on:
- backend
# environment:
# - API_URL=http://backend:8080
# In your frontend code, you'd reference process.env.API_URL or similar
# if using environment variables at build time.
volumes:
db_data:
+3
View File
@@ -0,0 +1,3 @@
docker run -v /data/dev/bamort/bamort:/vue_app \
-p 8080:8080 \
-it vue_app:dev
+1
View File
@@ -0,0 +1 @@
docker run --rm -ti -v /data/dev/bamort:/vue-setup vue_helper:slim
View File
+1
View File
@@ -0,0 +1 @@
../browserslist/cli.js
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../esbuild/bin/esbuild
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../is-docker/cli.js
+1
View File
@@ -0,0 +1 @@
../is-inside-container/cli.js
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../jsesc/bin/jsesc
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../json5/lib/cli.js
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../nanoid/bin/nanoid.cjs
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../which/bin/node-which
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../@babel/parser/bin/babel-parser.js
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../rollup/dist/bin/rollup
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../typescript/bin/tsc
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../typescript/bin/tsserver
+1
View File
@@ -0,0 +1 @@
../update-browserslist-db/cli.js
Generated Vendored Symlink
+1
View File
@@ -0,0 +1 @@
../vite/bin/vite.js
+2108
View File
File diff suppressed because it is too large Load Diff
+34
View File
@@ -0,0 +1,34 @@
{
"hash": "74ee2b3b",
"configHash": "7ba34175",
"lockfileHash": "2df9fa13",
"browserHash": "5d25d1a0",
"optimized": {
"axios": {
"src": "../../axios/index.js",
"file": "axios.js",
"fileHash": "5760348d",
"needsInterop": false
},
"vue": {
"src": "../../vue/dist/vue.runtime.esm-bundler.js",
"file": "vue.js",
"fileHash": "668d3806",
"needsInterop": false
},
"vue-router": {
"src": "../../vue-router/dist/vue-router.mjs",
"file": "vue-router.js",
"fileHash": "bbe7f140",
"needsInterop": false
}
},
"chunks": {
"chunk-U3LI7FBV": {
"file": "chunk-U3LI7FBV.js"
},
"chunk-PZ5AY32C": {
"file": "chunk-PZ5AY32C.js"
}
}
}
+2519
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+9
View File
@@ -0,0 +1,9 @@
var __defProp = Object.defineProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
export {
__export
};
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": [],
"sourcesContent": [],
"mappings": "",
"names": []
}
+12542
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+3
View File
@@ -0,0 +1,3 @@
{
"type": "module"
}
+2932
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+343
View File
@@ -0,0 +1,343 @@
import {
BaseTransition,
BaseTransitionPropsValidators,
Comment,
DeprecationTypes,
EffectScope,
ErrorCodes,
ErrorTypeStrings,
Fragment,
KeepAlive,
ReactiveEffect,
Static,
Suspense,
Teleport,
Text,
TrackOpTypes,
Transition,
TransitionGroup,
TriggerOpTypes,
VueElement,
assertNumber,
callWithAsyncErrorHandling,
callWithErrorHandling,
camelize,
capitalize,
cloneVNode,
compatUtils,
compile,
computed,
createApp,
createBaseVNode,
createBlock,
createCommentVNode,
createElementBlock,
createHydrationRenderer,
createPropsRestProxy,
createRenderer,
createSSRApp,
createSlots,
createStaticVNode,
createTextVNode,
createVNode,
customRef,
defineAsyncComponent,
defineComponent,
defineCustomElement,
defineEmits,
defineExpose,
defineModel,
defineOptions,
defineProps,
defineSSRCustomElement,
defineSlots,
devtools,
effect,
effectScope,
getCurrentInstance,
getCurrentScope,
getCurrentWatcher,
getTransitionRawChildren,
guardReactiveProps,
h,
handleError,
hasInjectionContext,
hydrate,
hydrateOnIdle,
hydrateOnInteraction,
hydrateOnMediaQuery,
hydrateOnVisible,
initCustomFormatter,
initDirectivesForSSR,
inject,
isMemoSame,
isProxy,
isReactive,
isReadonly,
isRef,
isRuntimeOnly,
isShallow,
isVNode,
markRaw,
mergeDefaults,
mergeModels,
mergeProps,
nextTick,
normalizeClass,
normalizeProps,
normalizeStyle,
onActivated,
onBeforeMount,
onBeforeUnmount,
onBeforeUpdate,
onDeactivated,
onErrorCaptured,
onMounted,
onRenderTracked,
onRenderTriggered,
onScopeDispose,
onServerPrefetch,
onUnmounted,
onUpdated,
onWatcherCleanup,
openBlock,
popScopeId,
provide,
proxyRefs,
pushScopeId,
queuePostFlushCb,
reactive,
readonly,
ref,
registerRuntimeCompiler,
render,
renderList,
renderSlot,
resolveComponent,
resolveDirective,
resolveDynamicComponent,
resolveFilter,
resolveTransitionHooks,
setBlockTracking,
setDevtoolsHook,
setTransitionHooks,
shallowReactive,
shallowReadonly,
shallowRef,
ssrContextKey,
ssrUtils,
stop,
toDisplayString,
toHandlerKey,
toHandlers,
toRaw,
toRef,
toRefs,
toValue,
transformVNodeArgs,
triggerRef,
unref,
useAttrs,
useCssModule,
useCssVars,
useHost,
useId,
useModel,
useSSRContext,
useShadowRoot,
useSlots,
useTemplateRef,
useTransitionState,
vModelCheckbox,
vModelDynamic,
vModelRadio,
vModelSelect,
vModelText,
vShow,
version,
warn,
watch,
watchEffect,
watchPostEffect,
watchSyncEffect,
withAsyncContext,
withCtx,
withDefaults,
withDirectives,
withKeys,
withMemo,
withModifiers,
withScopeId
} from "./chunk-U3LI7FBV.js";
import "./chunk-PZ5AY32C.js";
export {
BaseTransition,
BaseTransitionPropsValidators,
Comment,
DeprecationTypes,
EffectScope,
ErrorCodes,
ErrorTypeStrings,
Fragment,
KeepAlive,
ReactiveEffect,
Static,
Suspense,
Teleport,
Text,
TrackOpTypes,
Transition,
TransitionGroup,
TriggerOpTypes,
VueElement,
assertNumber,
callWithAsyncErrorHandling,
callWithErrorHandling,
camelize,
capitalize,
cloneVNode,
compatUtils,
compile,
computed,
createApp,
createBlock,
createCommentVNode,
createElementBlock,
createBaseVNode as createElementVNode,
createHydrationRenderer,
createPropsRestProxy,
createRenderer,
createSSRApp,
createSlots,
createStaticVNode,
createTextVNode,
createVNode,
customRef,
defineAsyncComponent,
defineComponent,
defineCustomElement,
defineEmits,
defineExpose,
defineModel,
defineOptions,
defineProps,
defineSSRCustomElement,
defineSlots,
devtools,
effect,
effectScope,
getCurrentInstance,
getCurrentScope,
getCurrentWatcher,
getTransitionRawChildren,
guardReactiveProps,
h,
handleError,
hasInjectionContext,
hydrate,
hydrateOnIdle,
hydrateOnInteraction,
hydrateOnMediaQuery,
hydrateOnVisible,
initCustomFormatter,
initDirectivesForSSR,
inject,
isMemoSame,
isProxy,
isReactive,
isReadonly,
isRef,
isRuntimeOnly,
isShallow,
isVNode,
markRaw,
mergeDefaults,
mergeModels,
mergeProps,
nextTick,
normalizeClass,
normalizeProps,
normalizeStyle,
onActivated,
onBeforeMount,
onBeforeUnmount,
onBeforeUpdate,
onDeactivated,
onErrorCaptured,
onMounted,
onRenderTracked,
onRenderTriggered,
onScopeDispose,
onServerPrefetch,
onUnmounted,
onUpdated,
onWatcherCleanup,
openBlock,
popScopeId,
provide,
proxyRefs,
pushScopeId,
queuePostFlushCb,
reactive,
readonly,
ref,
registerRuntimeCompiler,
render,
renderList,
renderSlot,
resolveComponent,
resolveDirective,
resolveDynamicComponent,
resolveFilter,
resolveTransitionHooks,
setBlockTracking,
setDevtoolsHook,
setTransitionHooks,
shallowReactive,
shallowReadonly,
shallowRef,
ssrContextKey,
ssrUtils,
stop,
toDisplayString,
toHandlerKey,
toHandlers,
toRaw,
toRef,
toRefs,
toValue,
transformVNodeArgs,
triggerRef,
unref,
useAttrs,
useCssModule,
useCssVars,
useHost,
useId,
useModel,
useSSRContext,
useShadowRoot,
useSlots,
useTemplateRef,
useTransitionState,
vModelCheckbox,
vModelDynamic,
vModelRadio,
vModelSelect,
vModelText,
vShow,
version,
warn,
watch,
watchEffect,
watchPostEffect,
watchSyncEffect,
withAsyncContext,
withCtx,
withDefaults,
withDirectives,
withKeys,
withMemo,
withModifiers,
withScopeId
};
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": [],
"sourcesContent": [],
"mappings": "",
"names": []
}
+123
View File
@@ -0,0 +1,123 @@
// @ts-nocheck
export {};
; declare module 'vue' {
export interface GlobalComponents { }
export interface GlobalDirectives { }
}
; declare global {
const __VLS_intrinsicElements: __VLS_IntrinsicElements;
const __VLS_directiveBindingRestFields: { instance: null, oldValue: null, modifiers: any, dir: any };
const __VLS_unref: typeof import('vue').unref;
const __VLS_nativeElements = {
...{} as SVGElementTagNameMap,
...{} as HTMLElementTagNameMap,
};
type __VLS_IntrinsicElements = import('vue/jsx-runtime').JSX.IntrinsicElements;
type __VLS_Element = import('vue/jsx-runtime').JSX.Element;
type __VLS_GlobalComponents = import('vue').GlobalComponents & Pick<typeof import('vue'), 'Transition' | 'TransitionGroup' | 'KeepAlive' | 'Suspense' | 'Teleport'>;
type __VLS_GlobalDirectives = import('vue').GlobalDirectives;
type __VLS_IsAny<T> = 0 extends 1 & T ? true : false;
type __VLS_PickNotAny<A, B> = __VLS_IsAny<A> extends true ? B : A;
type __VLS_unknownDirective = (arg1: unknown, arg2: unknown, arg3: unknown, arg4: unknown) => void;
type __VLS_WithComponent<N0 extends string, LocalComponents, N1 extends string, N2 extends string, N3 extends string> =
N1 extends keyof LocalComponents ? N1 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N1] } :
N2 extends keyof LocalComponents ? N2 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N2] } :
N3 extends keyof LocalComponents ? N3 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N3] } :
N1 extends keyof __VLS_GlobalComponents ? N1 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N1] } :
N2 extends keyof __VLS_GlobalComponents ? N2 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N2] } :
N3 extends keyof __VLS_GlobalComponents ? N3 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N3] } :
{ [K in N0]: unknown }
type __VLS_FunctionalComponentProps<T, K> =
'__ctx' extends keyof __VLS_PickNotAny<K, {}> ? K extends { __ctx?: { props?: infer P } } ? NonNullable<P> : never
: T extends (props: infer P, ...args: any) => any ? P :
{};
type __VLS_IsFunction<T, K> = K extends keyof T
? __VLS_IsAny<T[K]> extends false
? unknown extends T[K]
? false
: true
: false
: false;
// fix https://github.com/vuejs/language-tools/issues/926
type __VLS_UnionToIntersection<U> = (U extends unknown ? (arg: U) => unknown : never) extends ((arg: infer P) => unknown) ? P : never;
type __VLS_OverloadUnionInner<T, U = unknown> = U & T extends (...args: infer A) => infer R
? U extends T
? never
: __VLS_OverloadUnionInner<T, Pick<T, keyof T> & U & ((...args: A) => R)> | ((...args: A) => R)
: never;
type __VLS_OverloadUnion<T> = Exclude<
__VLS_OverloadUnionInner<(() => never) & T>,
T extends () => never ? never : () => never
>;
type __VLS_ConstructorOverloads<T> = __VLS_OverloadUnion<T> extends infer F
? F extends (event: infer E, ...args: infer A) => any
? { [K in E & string]: (...args: A) => void; }
: never
: never;
type __VLS_NormalizeEmits<T> = __VLS_PrettifyGlobal<
__VLS_UnionToIntersection<
__VLS_ConstructorOverloads<T> & {
[K in keyof T]: T[K] extends any[] ? { (...args: T[K]): void } : never
}
>
>;
type __VLS_PrettifyGlobal<T> = { [K in keyof T]: T[K]; } & {};
type __VLS_PickFunctionalComponentCtx<T, K> = NonNullable<__VLS_PickNotAny<
'__ctx' extends keyof __VLS_PickNotAny<K, {}> ? K extends { __ctx?: infer Ctx } ? Ctx : never : any
, T extends (props: any, ctx: infer Ctx) => any ? Ctx : any
>>;
type __VLS_UseTemplateRef<T> = Readonly<import('vue').ShallowRef<T | null>>;
function __VLS_getVForSourceType(source: number): [number, number, number][];
function __VLS_getVForSourceType(source: string): [string, number, number][];
function __VLS_getVForSourceType<T extends any[]>(source: T): [
item: T[number],
key: number,
index: number,
][];
function __VLS_getVForSourceType<T extends { [Symbol.iterator](): Iterator<any> }>(source: T): [
item: T extends { [Symbol.iterator](): Iterator<infer T1> } ? T1 : never,
key: number,
index: undefined,
][];
// #3845
function __VLS_getVForSourceType<T extends number | { [Symbol.iterator](): Iterator<any> }>(source: T): [
item: number | (Exclude<T, number> extends { [Symbol.iterator](): Iterator<infer T1> } ? T1 : never),
key: number,
index: undefined,
][];
function __VLS_getVForSourceType<T>(source: T): [
item: T[keyof T],
key: keyof T,
index: number,
][];
// @ts-ignore
function __VLS_getSlotParams<T>(slot: T): Parameters<__VLS_PickNotAny<NonNullable<T>, (...args: any[]) => any>>;
// @ts-ignore
function __VLS_getSlotParam<T>(slot: T): Parameters<__VLS_PickNotAny<NonNullable<T>, (...args: any[]) => any>>[0];
function __VLS_asFunctionalDirective<T>(dir: T): T extends import('vue').ObjectDirective
? NonNullable<T['created' | 'beforeMount' | 'mounted' | 'beforeUpdate' | 'updated' | 'beforeUnmount' | 'unmounted']>
: T extends (...args: any) => any
? T
: __VLS_unknownDirective;
function __VLS_withScope<T, K>(ctx: T, scope: K): ctx is T & K;
function __VLS_makeOptional<T>(t: T): { [K in keyof T]?: T[K] };
function __VLS_nonNullable<T>(t: T): T extends null | undefined ? never : T;
function __VLS_asFunctionalComponent<T, K = T extends new (...args: any) => any ? InstanceType<T> : unknown>(t: T, instance?: K):
T extends new (...args: any) => any
? (props: (K extends { $props: infer Props } ? Props : any) & Record<string, unknown>, ctx?: any) => __VLS_Element & { __ctx?: {
attrs?: any,
slots?: K extends { $slots: infer Slots } ? Slots : any,
emit?: K extends { $emit: infer Emit } ? Emit : any
} & { props?: (K extends { $props: infer Props } ? Props : any) & Record<string, unknown>; expose?(exposed: K): void; } }
: T extends () => any ? (props: {}, ctx?: any) => ReturnType<T>
: T extends (...args: any) => any ? T
: (_: {} & Record<string, unknown>, ctx?: any) => { __ctx?: { attrs?: any, expose?: any, slots?: any, emit?: any, props?: {} & Record<string, unknown> } };
function __VLS_elementAsFunction<T>(tag: T, endTag?: T): (_: T & Record<string, unknown>) => void;
function __VLS_functionalComponentArgsRest<T extends (...args: any) => any>(t: T): 2 extends Parameters<T>['length'] ? [any] : [];
function __VLS_normalizeSlot<S>(s: S): S extends () => infer R ? (props: {}) => R : S;
function __VLS_tryAsConstant<const T>(t: T): T;
}
+119
View File
@@ -0,0 +1,119 @@
// @ts-nocheck
export {};
; declare global {
const __VLS_intrinsicElements: __VLS_IntrinsicElements;
const __VLS_directiveBindingRestFields: { instance: null, oldValue: null, modifiers: any, dir: any };
const __VLS_unref: typeof import('vue').unref;
const __VLS_nativeElements = {
...{} as SVGElementTagNameMap,
...{} as HTMLElementTagNameMap,
};
type __VLS_IntrinsicElements = import('vue/jsx-runtime').JSX.IntrinsicElements;
type __VLS_Element = import('vue/jsx-runtime').JSX.Element;
type __VLS_GlobalComponents = import('vue').GlobalComponents;
type __VLS_GlobalDirectives = import('vue').GlobalDirectives;
type __VLS_IsAny<T> = 0 extends 1 & T ? true : false;
type __VLS_PickNotAny<A, B> = __VLS_IsAny<A> extends true ? B : A;
type __VLS_unknownDirective = (arg1: unknown, arg2: unknown, arg3: unknown, arg4: unknown) => void;
type __VLS_WithComponent<N0 extends string, LocalComponents, N1 extends string, N2 extends string, N3 extends string> =
N1 extends keyof LocalComponents ? N1 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N1] } :
N2 extends keyof LocalComponents ? N2 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N2] } :
N3 extends keyof LocalComponents ? N3 extends N0 ? Pick<LocalComponents, N0 extends keyof LocalComponents ? N0 : never> : { [K in N0]: LocalComponents[N3] } :
N1 extends keyof __VLS_GlobalComponents ? N1 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N1] } :
N2 extends keyof __VLS_GlobalComponents ? N2 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N2] } :
N3 extends keyof __VLS_GlobalComponents ? N3 extends N0 ? Pick<__VLS_GlobalComponents, N0 extends keyof __VLS_GlobalComponents ? N0 : never> : { [K in N0]: __VLS_GlobalComponents[N3] } :
{ [K in N0]: unknown }
type __VLS_FunctionalComponentProps<T, K> =
'__ctx' extends keyof __VLS_PickNotAny<K, {}> ? K extends { __ctx?: { props?: infer P } } ? NonNullable<P> : never
: T extends (props: infer P, ...args: any) => any ? P :
{};
type __VLS_IsFunction<T, K> = K extends keyof T
? __VLS_IsAny<T[K]> extends false
? unknown extends T[K]
? false
: true
: false
: false;
// fix https://github.com/vuejs/language-tools/issues/926
type __VLS_UnionToIntersection<U> = (U extends unknown ? (arg: U) => unknown : never) extends ((arg: infer P) => unknown) ? P : never;
type __VLS_OverloadUnionInner<T, U = unknown> = U & T extends (...args: infer A) => infer R
? U extends T
? never
: __VLS_OverloadUnionInner<T, Pick<T, keyof T> & U & ((...args: A) => R)> | ((...args: A) => R)
: never;
type __VLS_OverloadUnion<T> = Exclude<
__VLS_OverloadUnionInner<(() => never) & T>,
T extends () => never ? never : () => never
>;
type __VLS_ConstructorOverloads<T> = __VLS_OverloadUnion<T> extends infer F
? F extends (event: infer E, ...args: infer A) => any
? { [K in E & string]: (...args: A) => void; }
: never
: never;
type __VLS_NormalizeEmits<T> = __VLS_PrettifyGlobal<
__VLS_UnionToIntersection<
__VLS_ConstructorOverloads<T> & {
[K in keyof T]: T[K] extends any[] ? { (...args: T[K]): void } : never
}
>
>;
type __VLS_PrettifyGlobal<T> = { [K in keyof T]: T[K]; } & {};
type __VLS_PickFunctionalComponentCtx<T, K> = NonNullable<__VLS_PickNotAny<
'__ctx' extends keyof __VLS_PickNotAny<K, {}> ? K extends { __ctx?: infer Ctx } ? Ctx : never : any
, T extends (props: any, ctx: infer Ctx) => any ? Ctx : any
>>;
type __VLS_UseTemplateRef<T> = Readonly<import('vue').ShallowRef<T | null>>;
function __VLS_getVForSourceType(source: number): [number, number, number][];
function __VLS_getVForSourceType(source: string): [string, number, number][];
function __VLS_getVForSourceType<T extends any[]>(source: T): [
item: T[number],
key: number,
index: number,
][];
function __VLS_getVForSourceType<T extends { [Symbol.iterator](): Iterator<any> }>(source: T): [
item: T extends { [Symbol.iterator](): Iterator<infer T1> } ? T1 : never,
key: number,
index: undefined,
][];
// #3845
function __VLS_getVForSourceType<T extends number | { [Symbol.iterator](): Iterator<any> }>(source: T): [
item: number | (Exclude<T, number> extends { [Symbol.iterator](): Iterator<infer T1> } ? T1 : never),
key: number,
index: undefined,
][];
function __VLS_getVForSourceType<T>(source: T): [
item: T[keyof T],
key: keyof T,
index: number,
][];
// @ts-ignore
function __VLS_getSlotParams<T>(slot: T): Parameters<__VLS_PickNotAny<NonNullable<T>, (...args: any[]) => any>>;
// @ts-ignore
function __VLS_getSlotParam<T>(slot: T): Parameters<__VLS_PickNotAny<NonNullable<T>, (...args: any[]) => any>>[0];
function __VLS_asFunctionalDirective<T>(dir: T): T extends import('vue').ObjectDirective
? NonNullable<T['created' | 'beforeMount' | 'mounted' | 'beforeUpdate' | 'updated' | 'beforeUnmount' | 'unmounted']>
: T extends (...args: any) => any
? T
: __VLS_unknownDirective;
function __VLS_withScope<T, K>(ctx: T, scope: K): ctx is T & K;
function __VLS_makeOptional<T>(t: T): { [K in keyof T]?: T[K] };
function __VLS_nonNullable<T>(t: T): T extends null | undefined ? never : T;
function __VLS_asFunctionalComponent<T, K = T extends new (...args: any) => any ? InstanceType<T> : unknown>(t: T, instance?: K):
T extends new (...args: any) => any
? (props: (K extends { $props: infer Props } ? Props : any) & Record<string, unknown>, ctx?: any) => __VLS_Element & { __ctx?: {
attrs?: any,
slots?: K extends { $slots: infer Slots } ? Slots : any,
emit?: K extends { $emit: infer Emit } ? Emit : any
} & { props?: (K extends { $props: infer Props } ? Props : any) & Record<string, unknown>; expose?(exposed: K): void; } }
: T extends () => any ? (props: {}, ctx?: any) => ReturnType<T>
: T extends (...args: any) => any ? T
: (_: {} & Record<string, unknown>, ctx?: any) => { __ctx?: { attrs?: any, expose?: any, slots?: any, emit?: any, props?: {} & Record<string, unknown> } };
function __VLS_elementAsFunction<T>(tag: T, endTag?: T): (_: T & Record<string, unknown>) => void;
function __VLS_functionalComponentArgsRest<T extends (...args: any) => any>(t: T): 2 extends Parameters<T>['length'] ? [any] : [];
function __VLS_normalizeSlot<S>(s: S): S extends () => infer R ? (props: {}) => R : S;
function __VLS_tryAsConstant<const T>(t: T): T;
}
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+218
View File
@@ -0,0 +1,218 @@
# @ampproject/remapping
> Remap sequential sourcemaps through transformations to point at the original source code
Remapping allows you to take the sourcemaps generated through transforming your code and "remap"
them to the original source locations. Think "my minified code, transformed with babel and bundled
with webpack", all pointing to the correct location in your original source code.
With remapping, none of your source code transformations need to be aware of the input's sourcemap,
they only need to generate an output sourcemap. This greatly simplifies building custom
transformations (think a find-and-replace).
## Installation
```sh
npm install @ampproject/remapping
```
## Usage
```typescript
function remapping(
map: SourceMap | SourceMap[],
loader: (file: string, ctx: LoaderContext) => (SourceMap | null | undefined),
options?: { excludeContent: boolean, decodedMappings: boolean }
): SourceMap;
// LoaderContext gives the loader the importing sourcemap, tree depth, the ability to override the
// "source" location (where child sources are resolved relative to, or the location of original
// source), and the ability to override the "content" of an original source for inclusion in the
// output sourcemap.
type LoaderContext = {
readonly importer: string;
readonly depth: number;
source: string;
content: string | null | undefined;
}
```
`remapping` takes the final output sourcemap, and a `loader` function. For every source file pointer
in the sourcemap, the `loader` will be called with the resolved path. If the path itself represents
a transformed file (it has a sourcmap associated with it), then the `loader` should return that
sourcemap. If not, the path will be treated as an original, untransformed source code.
```js
// Babel transformed "helloworld.js" into "transformed.js"
const transformedMap = JSON.stringify({
file: 'transformed.js',
// 1st column of 2nd line of output file translates into the 1st source
// file, line 3, column 2
mappings: ';CAEE',
sources: ['helloworld.js'],
version: 3,
});
// Uglify minified "transformed.js" into "transformed.min.js"
const minifiedTransformedMap = JSON.stringify({
file: 'transformed.min.js',
// 0th column of 1st line of output file translates into the 1st source
// file, line 2, column 1.
mappings: 'AACC',
names: [],
sources: ['transformed.js'],
version: 3,
});
const remapped = remapping(
minifiedTransformedMap,
(file, ctx) => {
// The "transformed.js" file is an transformed file.
if (file === 'transformed.js') {
// The root importer is empty.
console.assert(ctx.importer === '');
// The depth in the sourcemap tree we're currently loading.
// The root `minifiedTransformedMap` is depth 0, and its source children are depth 1, etc.
console.assert(ctx.depth === 1);
return transformedMap;
}
// Loader will be called to load transformedMap's source file pointers as well.
console.assert(file === 'helloworld.js');
// `transformed.js`'s sourcemap points into `helloworld.js`.
console.assert(ctx.importer === 'transformed.js');
// This is a source child of `transformed`, which is a source child of `minifiedTransformedMap`.
console.assert(ctx.depth === 2);
return null;
}
);
console.log(remapped);
// {
// file: 'transpiled.min.js',
// mappings: 'AAEE',
// sources: ['helloworld.js'],
// version: 3,
// };
```
In this example, `loader` will be called twice:
1. `"transformed.js"`, the first source file pointer in the `minifiedTransformedMap`. We return the
associated sourcemap for it (its a transformed file, after all) so that sourcemap locations can
be traced through it into the source files it represents.
2. `"helloworld.js"`, our original, unmodified source code. This file does not have a sourcemap, so
we return `null`.
The `remapped` sourcemap now points from `transformed.min.js` into locations in `helloworld.js`. If
you were to read the `mappings`, it says "0th column of the first line output line points to the 1st
column of the 2nd line of the file `helloworld.js`".
### Multiple transformations of a file
As a convenience, if you have multiple single-source transformations of a file, you may pass an
array of sourcemap files in the order of most-recent transformation sourcemap first. Note that this
changes the `importer` and `depth` of each call to our loader. So our above example could have been
written as:
```js
const remapped = remapping(
[minifiedTransformedMap, transformedMap],
() => null
);
console.log(remapped);
// {
// file: 'transpiled.min.js',
// mappings: 'AAEE',
// sources: ['helloworld.js'],
// version: 3,
// };
```
### Advanced control of the loading graph
#### `source`
The `source` property can overridden to any value to change the location of the current load. Eg,
for an original source file, it allows us to change the location to the original source regardless
of what the sourcemap source entry says. And for transformed files, it allows us to change the
relative resolving location for child sources of the loaded sourcemap.
```js
const remapped = remapping(
minifiedTransformedMap,
(file, ctx) => {
if (file === 'transformed.js') {
// We pretend the transformed.js file actually exists in the 'src/' directory. When the nested
// source files are loaded, they will now be relative to `src/`.
ctx.source = 'src/transformed.js';
return transformedMap;
}
console.assert(file === 'src/helloworld.js');
// We could futher change the source of this original file, eg, to be inside a nested directory
// itself. This will be reflected in the remapped sourcemap.
ctx.source = 'src/nested/transformed.js';
return null;
}
);
console.log(remapped);
// {
// …,
// sources: ['src/nested/helloworld.js'],
// };
```
#### `content`
The `content` property can be overridden when we encounter an original source file. Eg, this allows
you to manually provide the source content of the original file regardless of whether the
`sourcesContent` field is present in the parent sourcemap. It can also be set to `null` to remove
the source content.
```js
const remapped = remapping(
minifiedTransformedMap,
(file, ctx) => {
if (file === 'transformed.js') {
// transformedMap does not include a `sourcesContent` field, so usually the remapped sourcemap
// would not include any `sourcesContent` values.
return transformedMap;
}
console.assert(file === 'helloworld.js');
// We can read the file to provide the source content.
ctx.content = fs.readFileSync(file, 'utf8');
return null;
}
);
console.log(remapped);
// {
// …,
// sourcesContent: [
// 'console.log("Hello world!")',
// ],
// };
```
### Options
#### excludeContent
By default, `excludeContent` is `false`. Passing `{ excludeContent: true }` will exclude the
`sourcesContent` field from the returned sourcemap. This is mainly useful when you want to reduce
the size out the sourcemap.
#### decodedMappings
By default, `decodedMappings` is `false`. Passing `{ decodedMappings: true }` will leave the
`mappings` field in a [decoded state](https://github.com/rich-harris/sourcemap-codec) instead of
encoding into a VLQ string.
+197
View File
@@ -0,0 +1,197 @@
import { decodedMappings, traceSegment, TraceMap } from '@jridgewell/trace-mapping';
import { GenMapping, maybeAddSegment, setSourceContent, setIgnore, toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping';
const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null, false);
const EMPTY_SOURCES = [];
function SegmentObject(source, line, column, name, content, ignore) {
return { source, line, column, name, content, ignore };
}
function Source(map, sources, source, content, ignore) {
return {
map,
sources,
source,
content,
ignore,
};
}
/**
* MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes
* (which may themselves be SourceMapTrees).
*/
function MapSource(map, sources) {
return Source(map, sources, '', null, false);
}
/**
* A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive
* segment tracing ends at the `OriginalSource`.
*/
function OriginalSource(source, content, ignore) {
return Source(null, EMPTY_SOURCES, source, content, ignore);
}
/**
* traceMappings is only called on the root level SourceMapTree, and begins the process of
* resolving each mapping in terms of the original source files.
*/
function traceMappings(tree) {
// TODO: Eventually support sourceRoot, which has to be removed because the sources are already
// fully resolved. We'll need to make sources relative to the sourceRoot before adding them.
const gen = new GenMapping({ file: tree.map.file });
const { sources: rootSources, map } = tree;
const rootNames = map.names;
const rootMappings = decodedMappings(map);
for (let i = 0; i < rootMappings.length; i++) {
const segments = rootMappings[i];
for (let j = 0; j < segments.length; j++) {
const segment = segments[j];
const genCol = segment[0];
let traced = SOURCELESS_MAPPING;
// 1-length segments only move the current generated column, there's no source information
// to gather from it.
if (segment.length !== 1) {
const source = rootSources[segment[1]];
traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : '');
// If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a
// respective segment into an original source.
if (traced == null)
continue;
}
const { column, line, name, content, source, ignore } = traced;
maybeAddSegment(gen, i, genCol, source, line, column, name);
if (source && content != null)
setSourceContent(gen, source, content);
if (ignore)
setIgnore(gen, source, true);
}
}
return gen;
}
/**
* originalPositionFor is only called on children SourceMapTrees. It recurses down into its own
* child SourceMapTrees, until we find the original source map.
*/
function originalPositionFor(source, line, column, name) {
if (!source.map) {
return SegmentObject(source.source, line, column, name, source.content, source.ignore);
}
const segment = traceSegment(source.map, line, column);
// If we couldn't find a segment, then this doesn't exist in the sourcemap.
if (segment == null)
return null;
// 1-length segments only move the current generated column, there's no source information
// to gather from it.
if (segment.length === 1)
return SOURCELESS_MAPPING;
return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
}
function asArray(value) {
if (Array.isArray(value))
return value;
return [value];
}
/**
* Recursively builds a tree structure out of sourcemap files, with each node
* being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of
* `OriginalSource`s and `SourceMapTree`s.
*
* Every sourcemap is composed of a collection of source files and mappings
* into locations of those source files. When we generate a `SourceMapTree` for
* the sourcemap, we attempt to load each source file's own sourcemap. If it
* does not have an associated sourcemap, it is considered an original,
* unmodified source file.
*/
function buildSourceMapTree(input, loader) {
const maps = asArray(input).map((m) => new TraceMap(m, ''));
const map = maps.pop();
for (let i = 0; i < maps.length; i++) {
if (maps[i].sources.length > 1) {
throw new Error(`Transformation map ${i} must have exactly one source file.\n` +
'Did you specify these with the most recent transformation maps first?');
}
}
let tree = build(map, loader, '', 0);
for (let i = maps.length - 1; i >= 0; i--) {
tree = MapSource(maps[i], [tree]);
}
return tree;
}
function build(map, loader, importer, importerDepth) {
const { resolvedSources, sourcesContent, ignoreList } = map;
const depth = importerDepth + 1;
const children = resolvedSources.map((sourceFile, i) => {
// The loading context gives the loader more information about why this file is being loaded
// (eg, from which importer). It also allows the loader to override the location of the loaded
// sourcemap/original source, or to override the content in the sourcesContent field if it's
// an unmodified source file.
const ctx = {
importer,
depth,
source: sourceFile || '',
content: undefined,
ignore: undefined,
};
// Use the provided loader callback to retrieve the file's sourcemap.
// TODO: We should eventually support async loading of sourcemap files.
const sourceMap = loader(ctx.source, ctx);
const { source, content, ignore } = ctx;
// If there is a sourcemap, then we need to recurse into it to load its source files.
if (sourceMap)
return build(new TraceMap(sourceMap, source), loader, source, depth);
// Else, it's an unmodified source file.
// The contents of this unmodified source file can be overridden via the loader context,
// allowing it to be explicitly null or a string. If it remains undefined, we fall back to
// the importing sourcemap's `sourcesContent` field.
const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;
const ignored = ignore !== undefined ? ignore : ignoreList ? ignoreList.includes(i) : false;
return OriginalSource(source, sourceContent, ignored);
});
return MapSource(map, children);
}
/**
* A SourceMap v3 compatible sourcemap, which only includes fields that were
* provided to it.
*/
class SourceMap {
constructor(map, options) {
const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map);
this.version = out.version; // SourceMap spec says this should be first.
this.file = out.file;
this.mappings = out.mappings;
this.names = out.names;
this.ignoreList = out.ignoreList;
this.sourceRoot = out.sourceRoot;
this.sources = out.sources;
if (!options.excludeContent) {
this.sourcesContent = out.sourcesContent;
}
}
toString() {
return JSON.stringify(this);
}
}
/**
* Traces through all the mappings in the root sourcemap, through the sources
* (and their sourcemaps), all the way back to the original source location.
*
* `loader` will be called every time we encounter a source file. If it returns
* a sourcemap, we will recurse into that sourcemap to continue the trace. If
* it returns a falsey value, that source file is treated as an original,
* unmodified source file.
*
* Pass `excludeContent` to exclude any self-containing source file content
* from the output sourcemap.
*
* Pass `decodedMappings` to receive a SourceMap with decoded (instead of
* VLQ encoded) mappings.
*/
function remapping(input, loader, options) {
const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };
const tree = buildSourceMapTree(input, loader);
return new SourceMap(traceMappings(tree), opts);
}
export { remapping as default };
//# sourceMappingURL=remapping.mjs.map
File diff suppressed because one or more lines are too long
+202
View File
@@ -0,0 +1,202 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('@jridgewell/trace-mapping'), require('@jridgewell/gen-mapping')) :
typeof define === 'function' && define.amd ? define(['@jridgewell/trace-mapping', '@jridgewell/gen-mapping'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.remapping = factory(global.traceMapping, global.genMapping));
})(this, (function (traceMapping, genMapping) { 'use strict';
const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null, false);
const EMPTY_SOURCES = [];
function SegmentObject(source, line, column, name, content, ignore) {
return { source, line, column, name, content, ignore };
}
function Source(map, sources, source, content, ignore) {
return {
map,
sources,
source,
content,
ignore,
};
}
/**
* MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes
* (which may themselves be SourceMapTrees).
*/
function MapSource(map, sources) {
return Source(map, sources, '', null, false);
}
/**
* A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive
* segment tracing ends at the `OriginalSource`.
*/
function OriginalSource(source, content, ignore) {
return Source(null, EMPTY_SOURCES, source, content, ignore);
}
/**
* traceMappings is only called on the root level SourceMapTree, and begins the process of
* resolving each mapping in terms of the original source files.
*/
function traceMappings(tree) {
// TODO: Eventually support sourceRoot, which has to be removed because the sources are already
// fully resolved. We'll need to make sources relative to the sourceRoot before adding them.
const gen = new genMapping.GenMapping({ file: tree.map.file });
const { sources: rootSources, map } = tree;
const rootNames = map.names;
const rootMappings = traceMapping.decodedMappings(map);
for (let i = 0; i < rootMappings.length; i++) {
const segments = rootMappings[i];
for (let j = 0; j < segments.length; j++) {
const segment = segments[j];
const genCol = segment[0];
let traced = SOURCELESS_MAPPING;
// 1-length segments only move the current generated column, there's no source information
// to gather from it.
if (segment.length !== 1) {
const source = rootSources[segment[1]];
traced = originalPositionFor(source, segment[2], segment[3], segment.length === 5 ? rootNames[segment[4]] : '');
// If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a
// respective segment into an original source.
if (traced == null)
continue;
}
const { column, line, name, content, source, ignore } = traced;
genMapping.maybeAddSegment(gen, i, genCol, source, line, column, name);
if (source && content != null)
genMapping.setSourceContent(gen, source, content);
if (ignore)
genMapping.setIgnore(gen, source, true);
}
}
return gen;
}
/**
* originalPositionFor is only called on children SourceMapTrees. It recurses down into its own
* child SourceMapTrees, until we find the original source map.
*/
function originalPositionFor(source, line, column, name) {
if (!source.map) {
return SegmentObject(source.source, line, column, name, source.content, source.ignore);
}
const segment = traceMapping.traceSegment(source.map, line, column);
// If we couldn't find a segment, then this doesn't exist in the sourcemap.
if (segment == null)
return null;
// 1-length segments only move the current generated column, there's no source information
// to gather from it.
if (segment.length === 1)
return SOURCELESS_MAPPING;
return originalPositionFor(source.sources[segment[1]], segment[2], segment[3], segment.length === 5 ? source.map.names[segment[4]] : name);
}
function asArray(value) {
if (Array.isArray(value))
return value;
return [value];
}
/**
* Recursively builds a tree structure out of sourcemap files, with each node
* being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of
* `OriginalSource`s and `SourceMapTree`s.
*
* Every sourcemap is composed of a collection of source files and mappings
* into locations of those source files. When we generate a `SourceMapTree` for
* the sourcemap, we attempt to load each source file's own sourcemap. If it
* does not have an associated sourcemap, it is considered an original,
* unmodified source file.
*/
function buildSourceMapTree(input, loader) {
const maps = asArray(input).map((m) => new traceMapping.TraceMap(m, ''));
const map = maps.pop();
for (let i = 0; i < maps.length; i++) {
if (maps[i].sources.length > 1) {
throw new Error(`Transformation map ${i} must have exactly one source file.\n` +
'Did you specify these with the most recent transformation maps first?');
}
}
let tree = build(map, loader, '', 0);
for (let i = maps.length - 1; i >= 0; i--) {
tree = MapSource(maps[i], [tree]);
}
return tree;
}
function build(map, loader, importer, importerDepth) {
const { resolvedSources, sourcesContent, ignoreList } = map;
const depth = importerDepth + 1;
const children = resolvedSources.map((sourceFile, i) => {
// The loading context gives the loader more information about why this file is being loaded
// (eg, from which importer). It also allows the loader to override the location of the loaded
// sourcemap/original source, or to override the content in the sourcesContent field if it's
// an unmodified source file.
const ctx = {
importer,
depth,
source: sourceFile || '',
content: undefined,
ignore: undefined,
};
// Use the provided loader callback to retrieve the file's sourcemap.
// TODO: We should eventually support async loading of sourcemap files.
const sourceMap = loader(ctx.source, ctx);
const { source, content, ignore } = ctx;
// If there is a sourcemap, then we need to recurse into it to load its source files.
if (sourceMap)
return build(new traceMapping.TraceMap(sourceMap, source), loader, source, depth);
// Else, it's an unmodified source file.
// The contents of this unmodified source file can be overridden via the loader context,
// allowing it to be explicitly null or a string. If it remains undefined, we fall back to
// the importing sourcemap's `sourcesContent` field.
const sourceContent = content !== undefined ? content : sourcesContent ? sourcesContent[i] : null;
const ignored = ignore !== undefined ? ignore : ignoreList ? ignoreList.includes(i) : false;
return OriginalSource(source, sourceContent, ignored);
});
return MapSource(map, children);
}
/**
* A SourceMap v3 compatible sourcemap, which only includes fields that were
* provided to it.
*/
class SourceMap {
constructor(map, options) {
const out = options.decodedMappings ? genMapping.toDecodedMap(map) : genMapping.toEncodedMap(map);
this.version = out.version; // SourceMap spec says this should be first.
this.file = out.file;
this.mappings = out.mappings;
this.names = out.names;
this.ignoreList = out.ignoreList;
this.sourceRoot = out.sourceRoot;
this.sources = out.sources;
if (!options.excludeContent) {
this.sourcesContent = out.sourcesContent;
}
}
toString() {
return JSON.stringify(this);
}
}
/**
* Traces through all the mappings in the root sourcemap, through the sources
* (and their sourcemaps), all the way back to the original source location.
*
* `loader` will be called every time we encounter a source file. If it returns
* a sourcemap, we will recurse into that sourcemap to continue the trace. If
* it returns a falsey value, that source file is treated as an original,
* unmodified source file.
*
* Pass `excludeContent` to exclude any self-containing source file content
* from the output sourcemap.
*
* Pass `decodedMappings` to receive a SourceMap with decoded (instead of
* VLQ encoded) mappings.
*/
function remapping(input, loader, options) {
const opts = typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false };
const tree = buildSourceMapTree(input, loader);
return new SourceMap(traceMappings(tree), opts);
}
return remapping;
}));
//# sourceMappingURL=remapping.umd.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,14 @@
import type { MapSource as MapSourceType } from './source-map-tree';
import type { SourceMapInput, SourceMapLoader } from './types';
/**
* Recursively builds a tree structure out of sourcemap files, with each node
* being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of
* `OriginalSource`s and `SourceMapTree`s.
*
* Every sourcemap is composed of a collection of source files and mappings
* into locations of those source files. When we generate a `SourceMapTree` for
* the sourcemap, we attempt to load each source file's own sourcemap. If it
* does not have an associated sourcemap, it is considered an original,
* unmodified source file.
*/
export default function buildSourceMapTree(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader): MapSourceType;
+20
View File
@@ -0,0 +1,20 @@
import SourceMap from './source-map';
import type { SourceMapInput, SourceMapLoader, Options } from './types';
export type { SourceMapSegment, EncodedSourceMap, EncodedSourceMap as RawSourceMap, DecodedSourceMap, SourceMapInput, SourceMapLoader, LoaderContext, Options, } from './types';
export type { SourceMap };
/**
* Traces through all the mappings in the root sourcemap, through the sources
* (and their sourcemaps), all the way back to the original source location.
*
* `loader` will be called every time we encounter a source file. If it returns
* a sourcemap, we will recurse into that sourcemap to continue the trace. If
* it returns a falsey value, that source file is treated as an original,
* unmodified source file.
*
* Pass `excludeContent` to exclude any self-containing source file content
* from the output sourcemap.
*
* Pass `decodedMappings` to receive a SourceMap with decoded (instead of
* VLQ encoded) mappings.
*/
export default function remapping(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader, options?: boolean | Options): SourceMap;
@@ -0,0 +1,45 @@
import { GenMapping } from '@jridgewell/gen-mapping';
import type { TraceMap } from '@jridgewell/trace-mapping';
export declare type SourceMapSegmentObject = {
column: number;
line: number;
name: string;
source: string;
content: string | null;
ignore: boolean;
};
export declare type OriginalSource = {
map: null;
sources: Sources[];
source: string;
content: string | null;
ignore: boolean;
};
export declare type MapSource = {
map: TraceMap;
sources: Sources[];
source: string;
content: null;
ignore: false;
};
export declare type Sources = OriginalSource | MapSource;
/**
* MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes
* (which may themselves be SourceMapTrees).
*/
export declare function MapSource(map: TraceMap, sources: Sources[]): MapSource;
/**
* A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive
* segment tracing ends at the `OriginalSource`.
*/
export declare function OriginalSource(source: string, content: string | null, ignore: boolean): OriginalSource;
/**
* traceMappings is only called on the root level SourceMapTree, and begins the process of
* resolving each mapping in terms of the original source files.
*/
export declare function traceMappings(tree: MapSource): GenMapping;
/**
* originalPositionFor is only called on children SourceMapTrees. It recurses down into its own
* child SourceMapTrees, until we find the original source map.
*/
export declare function originalPositionFor(source: Sources, line: number, column: number, name: string): SourceMapSegmentObject | null;
+18
View File
@@ -0,0 +1,18 @@
import type { GenMapping } from '@jridgewell/gen-mapping';
import type { DecodedSourceMap, EncodedSourceMap, Options } from './types';
/**
* A SourceMap v3 compatible sourcemap, which only includes fields that were
* provided to it.
*/
export default class SourceMap {
file?: string | null;
mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings'];
sourceRoot?: string;
names: string[];
sources: (string | null)[];
sourcesContent?: (string | null)[];
version: 3;
ignoreList: number[] | undefined;
constructor(map: GenMapping, options: Options);
toString(): string;
}
+15
View File
@@ -0,0 +1,15 @@
import type { SourceMapInput } from '@jridgewell/trace-mapping';
export type { SourceMapSegment, DecodedSourceMap, EncodedSourceMap, } from '@jridgewell/trace-mapping';
export type { SourceMapInput };
export declare type LoaderContext = {
readonly importer: string;
readonly depth: number;
source: string;
content: string | null | undefined;
ignore: boolean | undefined;
};
export declare type SourceMapLoader = (file: string, ctx: LoaderContext) => SourceMapInput | null | undefined | void;
export declare type Options = {
excludeContent?: boolean;
decodedMappings?: boolean;
};
+75
View File
@@ -0,0 +1,75 @@
{
"name": "@ampproject/remapping",
"version": "2.3.0",
"description": "Remap sequential sourcemaps through transformations to point at the original source code",
"keywords": [
"source",
"map",
"remap"
],
"main": "dist/remapping.umd.js",
"module": "dist/remapping.mjs",
"types": "dist/types/remapping.d.ts",
"exports": {
".": [
{
"types": "./dist/types/remapping.d.ts",
"browser": "./dist/remapping.umd.js",
"require": "./dist/remapping.umd.js",
"import": "./dist/remapping.mjs"
},
"./dist/remapping.umd.js"
],
"./package.json": "./package.json"
},
"files": [
"dist"
],
"author": "Justin Ridgewell <jridgewell@google.com>",
"repository": {
"type": "git",
"url": "git+https://github.com/ampproject/remapping.git"
},
"license": "Apache-2.0",
"engines": {
"node": ">=6.0.0"
},
"scripts": {
"build": "run-s -n build:*",
"build:rollup": "rollup -c rollup.config.js",
"build:ts": "tsc --project tsconfig.build.json",
"lint": "run-s -n lint:*",
"lint:prettier": "npm run test:lint:prettier -- --write",
"lint:ts": "npm run test:lint:ts -- --fix",
"prebuild": "rm -rf dist",
"prepublishOnly": "npm run preversion",
"preversion": "run-s test build",
"test": "run-s -n test:lint test:only",
"test:debug": "node --inspect-brk node_modules/.bin/jest --runInBand",
"test:lint": "run-s -n test:lint:*",
"test:lint:prettier": "prettier --check '{src,test}/**/*.ts'",
"test:lint:ts": "eslint '{src,test}/**/*.ts'",
"test:only": "jest --coverage",
"test:watch": "jest --coverage --watch"
},
"devDependencies": {
"@rollup/plugin-typescript": "8.3.2",
"@types/jest": "27.4.1",
"@typescript-eslint/eslint-plugin": "5.20.0",
"@typescript-eslint/parser": "5.20.0",
"eslint": "8.14.0",
"eslint-config-prettier": "8.5.0",
"jest": "27.5.1",
"jest-config": "27.5.1",
"npm-run-all": "4.1.5",
"prettier": "2.6.2",
"rollup": "2.70.2",
"ts-jest": "27.1.4",
"tslib": "2.4.0",
"typescript": "4.6.3"
},
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.5",
"@jridgewell/trace-mapping": "^0.3.24"
}
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021 Anthony Fu <https://github.com/antfu>
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.
+24
View File
@@ -0,0 +1,24 @@
# @antfu/utils
[![NPM version](https://img.shields.io/npm/v/@antfu/utils?color=a1b858&label=)](https://www.npmjs.com/package/@antfu/utils)
[![Docs](https://img.shields.io/badge/docs-green)](https://www.jsdocs.io/package/@antfu/utils)
Opinionated collection of common JavaScript / TypeScript utils by [@antfu](https://github.com/antfu).
- Tree-shakable ESM
- Fully typed - with TSDocs
- Type utilities - `Arrayable<T>`, `ElementOf<T>`, etc.
> This package is designed to be used as `devDependencies` and bundled into your dist.
## Sponsors
<p align="center">
<a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
<img src='https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg'/>
</a>
</p>
## License
[MIT](./LICENSE) License © 2021-PRESENT [Anthony Fu](https://github.com/antfu)
+844
View File
@@ -0,0 +1,844 @@
'use strict';
function clamp(n, min, max) {
return Math.min(max, Math.max(min, n));
}
function sum(...args) {
return flattenArrayable(args).reduce((a, b) => a + b, 0);
}
function lerp(min, max, t) {
const interpolation = clamp(t, 0, 1);
return min + (max - min) * interpolation;
}
function remap(n, inMin, inMax, outMin, outMax) {
const interpolation = (n - inMin) / (inMax - inMin);
return lerp(outMin, outMax, interpolation);
}
function toArray(array) {
array = array ?? [];
return Array.isArray(array) ? array : [array];
}
function flattenArrayable(array) {
return toArray(array).flat(1);
}
function mergeArrayable(...args) {
return args.flatMap((i) => toArray(i));
}
function partition(array, ...filters) {
const result = Array.from({ length: filters.length + 1 }).fill(null).map(() => []);
array.forEach((e, idx, arr) => {
let i = 0;
for (const filter of filters) {
if (filter(e, idx, arr)) {
result[i].push(e);
return;
}
i += 1;
}
result[i].push(e);
});
return result;
}
function uniq(array) {
return Array.from(new Set(array));
}
function uniqueBy(array, equalFn) {
return array.reduce((acc, cur) => {
const index = acc.findIndex((item) => equalFn(cur, item));
if (index === -1)
acc.push(cur);
return acc;
}, []);
}
function last(array) {
return at(array, -1);
}
function remove(array, value) {
if (!array)
return false;
const index = array.indexOf(value);
if (index >= 0) {
array.splice(index, 1);
return true;
}
return false;
}
function at(array, index) {
const len = array.length;
if (!len)
return void 0;
if (index < 0)
index += len;
return array[index];
}
function range(...args) {
let start, stop, step;
if (args.length === 1) {
start = 0;
step = 1;
[stop] = args;
} else {
[start, stop, step = 1] = args;
}
const arr = [];
let current = start;
while (current < stop) {
arr.push(current);
current += step || 1;
}
return arr;
}
function move(arr, from, to) {
arr.splice(to, 0, arr.splice(from, 1)[0]);
return arr;
}
function clampArrayRange(n, arr) {
return clamp(n, 0, arr.length - 1);
}
function sample(arr, quantity) {
return Array.from({ length: quantity }, (_) => arr[Math.round(Math.random() * (arr.length - 1))]);
}
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
function assert(condition, message) {
if (!condition)
throw new Error(message);
}
const toString = (v) => Object.prototype.toString.call(v);
function getTypeName(v) {
if (v === null)
return "null";
const type = toString(v).slice(8, -1).toLowerCase();
return typeof v === "object" || typeof v === "function" ? type : typeof v;
}
function noop() {
}
function isDeepEqual(value1, value2) {
const type1 = getTypeName(value1);
const type2 = getTypeName(value2);
if (type1 !== type2)
return false;
if (type1 === "array") {
if (value1.length !== value2.length)
return false;
return value1.every((item, i) => {
return isDeepEqual(item, value2[i]);
});
}
if (type1 === "object") {
const keyArr = Object.keys(value1);
if (keyArr.length !== Object.keys(value2).length)
return false;
return keyArr.every((key) => {
return isDeepEqual(value1[key], value2[key]);
});
}
return Object.is(value1, value2);
}
function notNullish(v) {
return v != null;
}
function noNull(v) {
return v !== null;
}
function notUndefined(v) {
return v !== void 0;
}
function isTruthy(v) {
return Boolean(v);
}
const isDef = (val) => typeof val !== "undefined";
const isBoolean = (val) => typeof val === "boolean";
const isFunction = (val) => typeof val === "function";
const isNumber = (val) => typeof val === "number";
const isString = (val) => typeof val === "string";
const isObject = (val) => toString(val) === "[object Object]";
const isUndefined = (val) => toString(val) === "[object Undefined]";
const isNull = (val) => toString(val) === "[object Null]";
const isRegExp = (val) => toString(val) === "[object RegExp]";
const isDate = (val) => toString(val) === "[object Date]";
const isWindow = (val) => typeof window !== "undefined" && toString(val) === "[object Window]";
const isBrowser = typeof window !== "undefined";
function slash(str) {
return str.replace(/\\/g, "/");
}
function ensurePrefix(prefix, str) {
if (!str.startsWith(prefix))
return prefix + str;
return str;
}
function ensureSuffix(suffix, str) {
if (!str.endsWith(suffix))
return str + suffix;
return str;
}
function template(str, ...args) {
const [firstArg, fallback] = args;
if (isObject(firstArg)) {
const vars = firstArg;
return str.replace(/{([\w\d]+)}/g, (_, key) => vars[key] || ((typeof fallback === "function" ? fallback(key) : fallback) ?? key));
} else {
return str.replace(/{(\d+)}/g, (_, key) => {
const index = Number(key);
if (Number.isNaN(index))
return key;
return args[index];
});
}
}
const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
function randomStr(size = 16, dict = urlAlphabet) {
let id = "";
let i = size;
const len = dict.length;
while (i--)
id += dict[Math.random() * len | 0];
return id;
}
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1).toLowerCase();
}
const _reFullWs = /^\s*$/;
function unindent(str) {
const lines = (typeof str === "string" ? str : str[0]).split("\n");
const whitespaceLines = lines.map((line) => _reFullWs.test(line));
const commonIndent = lines.reduce((min, line, idx) => {
var _a;
if (whitespaceLines[idx])
return min;
const indent = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0].length;
return indent === void 0 ? min : Math.min(min, indent);
}, Number.POSITIVE_INFINITY);
let emptyLinesHead = 0;
while (emptyLinesHead < lines.length && whitespaceLines[emptyLinesHead])
emptyLinesHead++;
let emptyLinesTail = 0;
while (emptyLinesTail < lines.length && whitespaceLines[lines.length - emptyLinesTail - 1])
emptyLinesTail++;
return lines.slice(emptyLinesHead, lines.length - emptyLinesTail).map((line) => line.slice(commonIndent)).join("\n");
}
const timestamp = () => +Date.now();
function batchInvoke(functions) {
functions.forEach((fn) => fn && fn());
}
function invoke(fn) {
return fn();
}
function tap(value, callback) {
callback(value);
return value;
}
function objectMap(obj, fn) {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) => fn(k, v)).filter(notNullish)
);
}
function isKeyOf(obj, k) {
return k in obj;
}
function objectKeys(obj) {
return Object.keys(obj);
}
function objectEntries(obj) {
return Object.entries(obj);
}
function deepMerge(target, ...sources) {
if (!sources.length)
return target;
const source = sources.shift();
if (source === void 0)
return target;
if (isMergableObject(target) && isMergableObject(source)) {
objectKeys(source).forEach((key) => {
if (key === "__proto__" || key === "constructor" || key === "prototype")
return;
if (isMergableObject(source[key])) {
if (!target[key])
target[key] = {};
if (isMergableObject(target[key])) {
deepMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
} else {
target[key] = source[key];
}
});
}
return deepMerge(target, ...sources);
}
function deepMergeWithArray(target, ...sources) {
if (!sources.length)
return target;
const source = sources.shift();
if (source === void 0)
return target;
if (Array.isArray(target) && Array.isArray(source))
target.push(...source);
if (isMergableObject(target) && isMergableObject(source)) {
objectKeys(source).forEach((key) => {
if (key === "__proto__" || key === "constructor" || key === "prototype")
return;
if (Array.isArray(source[key])) {
if (!target[key])
target[key] = [];
deepMergeWithArray(target[key], source[key]);
} else if (isMergableObject(source[key])) {
if (!target[key])
target[key] = {};
deepMergeWithArray(target[key], source[key]);
} else {
target[key] = source[key];
}
});
}
return deepMergeWithArray(target, ...sources);
}
function isMergableObject(item) {
return isObject(item) && !Array.isArray(item);
}
function objectPick(obj, keys, omitUndefined = false) {
return keys.reduce((n, k) => {
if (k in obj) {
if (!omitUndefined || obj[k] !== void 0)
n[k] = obj[k];
}
return n;
}, {});
}
function clearUndefined(obj) {
Object.keys(obj).forEach((key) => obj[key] === void 0 ? delete obj[key] : {});
return obj;
}
function hasOwnProperty(obj, v) {
if (obj == null)
return false;
return Object.prototype.hasOwnProperty.call(obj, v);
}
function createSingletonPromise(fn) {
let _promise;
function wrapper() {
if (!_promise)
_promise = fn();
return _promise;
}
wrapper.reset = async () => {
const _prev = _promise;
_promise = void 0;
if (_prev)
await _prev;
};
return wrapper;
}
function sleep(ms, callback) {
return new Promise(
(resolve) => setTimeout(async () => {
await (callback == null ? void 0 : callback());
resolve();
}, ms)
);
}
function createPromiseLock() {
const locks = [];
return {
async run(fn) {
const p = fn();
locks.push(p);
try {
return await p;
} finally {
remove(locks, p);
}
},
async wait() {
await Promise.allSettled(locks);
},
isWaiting() {
return Boolean(locks.length);
},
clear() {
locks.length = 0;
}
};
}
function createControlledPromise() {
let resolve, reject;
const promise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
promise.resolve = resolve;
promise.reject = reject;
return promise;
}
/* eslint-disable no-undefined,no-param-reassign,no-shadow */
/**
* Throttle execution of a function. Especially useful for rate limiting
* execution of handlers on events like resize and scroll.
*
* @param {number} delay - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher)
* are most useful.
* @param {Function} callback - A function to be executed after delay milliseconds. The `this` context and all arguments are passed through,
* as-is, to `callback` when the throttled-function is executed.
* @param {object} [options] - An object to configure options.
* @param {boolean} [options.noTrailing] - Optional, defaults to false. If noTrailing is true, callback will only execute every `delay` milliseconds
* while the throttled-function is being called. If noTrailing is false or unspecified, callback will be executed
* one final time after the last throttled-function call. (After the throttled-function has not been called for
* `delay` milliseconds, the internal counter is reset).
* @param {boolean} [options.noLeading] - Optional, defaults to false. If noLeading is false, the first throttled-function call will execute callback
* immediately. If noLeading is true, the first the callback execution will be skipped. It should be noted that
* callback will never executed if both noLeading = true and noTrailing = true.
* @param {boolean} [options.debounceMode] - If `debounceMode` is true (at begin), schedule `clear` to execute after `delay` ms. If `debounceMode` is
* false (at end), schedule `callback` to execute after `delay` ms.
*
* @returns {Function} A new, throttled, function.
*/
function throttle (delay, callback, options) {
var _ref = options || {},
_ref$noTrailing = _ref.noTrailing,
noTrailing = _ref$noTrailing === void 0 ? false : _ref$noTrailing,
_ref$noLeading = _ref.noLeading,
noLeading = _ref$noLeading === void 0 ? false : _ref$noLeading,
_ref$debounceMode = _ref.debounceMode,
debounceMode = _ref$debounceMode === void 0 ? undefined : _ref$debounceMode;
/*
* After wrapper has stopped being called, this timeout ensures that
* `callback` is executed at the proper times in `throttle` and `end`
* debounce modes.
*/
var timeoutID;
var cancelled = false; // Keep track of the last time `callback` was executed.
var lastExec = 0; // Function to clear existing timeout
function clearExistingTimeout() {
if (timeoutID) {
clearTimeout(timeoutID);
}
} // Function to cancel next exec
function cancel(options) {
var _ref2 = options || {},
_ref2$upcomingOnly = _ref2.upcomingOnly,
upcomingOnly = _ref2$upcomingOnly === void 0 ? false : _ref2$upcomingOnly;
clearExistingTimeout();
cancelled = !upcomingOnly;
}
/*
* The `wrapper` function encapsulates all of the throttling / debouncing
* functionality and when executed will limit the rate at which `callback`
* is executed.
*/
function wrapper() {
for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) {
arguments_[_key] = arguments[_key];
}
var self = this;
var elapsed = Date.now() - lastExec;
if (cancelled) {
return;
} // Execute `callback` and update the `lastExec` timestamp.
function exec() {
lastExec = Date.now();
callback.apply(self, arguments_);
}
/*
* If `debounceMode` is true (at begin) this is used to clear the flag
* to allow future `callback` executions.
*/
function clear() {
timeoutID = undefined;
}
if (!noLeading && debounceMode && !timeoutID) {
/*
* Since `wrapper` is being called for the first time and
* `debounceMode` is true (at begin), execute `callback`
* and noLeading != true.
*/
exec();
}
clearExistingTimeout();
if (debounceMode === undefined && elapsed > delay) {
if (noLeading) {
/*
* In throttle mode with noLeading, if `delay` time has
* been exceeded, update `lastExec` and schedule `callback`
* to execute after `delay` ms.
*/
lastExec = Date.now();
if (!noTrailing) {
timeoutID = setTimeout(debounceMode ? clear : exec, delay);
}
} else {
/*
* In throttle mode without noLeading, if `delay` time has been exceeded, execute
* `callback`.
*/
exec();
}
} else if (noTrailing !== true) {
/*
* In trailing throttle mode, since `delay` time has not been
* exceeded, schedule `callback` to execute `delay` ms after most
* recent execution.
*
* If `debounceMode` is true (at begin), schedule `clear` to execute
* after `delay` ms.
*
* If `debounceMode` is false (at end), schedule `callback` to
* execute after `delay` ms.
*/
timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === undefined ? delay - elapsed : delay);
}
}
wrapper.cancel = cancel; // Return the wrapper function.
return wrapper;
}
/* eslint-disable no-undefined */
/**
* Debounce execution of a function. Debouncing, unlike throttling,
* guarantees that a function is only executed a single time, either at the
* very beginning of a series of calls, or at the very end.
*
* @param {number} delay - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
* @param {Function} callback - A function to be executed after delay milliseconds. The `this` context and all arguments are passed through, as-is,
* to `callback` when the debounced-function is executed.
* @param {object} [options] - An object to configure options.
* @param {boolean} [options.atBegin] - Optional, defaults to false. If atBegin is false or unspecified, callback will only be executed `delay` milliseconds
* after the last debounced-function call. If atBegin is true, callback will be executed only at the first debounced-function call.
* (After the throttled-function has not been called for `delay` milliseconds, the internal counter is reset).
*
* @returns {Function} A new, debounced function.
*/
function debounce (delay, callback, options) {
var _ref = options || {},
_ref$atBegin = _ref.atBegin,
atBegin = _ref$atBegin === void 0 ? false : _ref$atBegin;
return throttle(delay, callback, {
debounceMode: atBegin !== false
});
}
/*
How it works:
`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.
*/
class Node {
value;
next;
constructor(value) {
this.value = value;
}
}
class Queue {
#head;
#tail;
#size;
constructor() {
this.clear();
}
enqueue(value) {
const node = new Node(value);
if (this.#head) {
this.#tail.next = node;
this.#tail = node;
} else {
this.#head = node;
this.#tail = node;
}
this.#size++;
}
dequeue() {
const current = this.#head;
if (!current) {
return;
}
this.#head = this.#head.next;
this.#size--;
return current.value;
}
clear() {
this.#head = undefined;
this.#tail = undefined;
this.#size = 0;
}
get size() {
return this.#size;
}
* [Symbol.iterator]() {
let current = this.#head;
while (current) {
yield current.value;
current = current.next;
}
}
}
const AsyncResource = {
bind(fn, _type, thisArg) {
return fn.bind(thisArg);
},
};
function pLimit(concurrency) {
if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
throw new TypeError('Expected `concurrency` to be a number from 1 and up');
}
const queue = new Queue();
let activeCount = 0;
const next = () => {
activeCount--;
if (queue.size > 0) {
queue.dequeue()();
}
};
const run = async (function_, resolve, arguments_) => {
activeCount++;
const result = (async () => function_(...arguments_))();
resolve(result);
try {
await result;
} catch {}
next();
};
const enqueue = (function_, resolve, arguments_) => {
queue.enqueue(
AsyncResource.bind(run.bind(undefined, function_, resolve, arguments_)),
);
(async () => {
// This function needs to wait until the next microtask before comparing
// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
// when the run function is dequeued and called. The comparison in the if-statement
// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
await Promise.resolve();
if (activeCount < concurrency && queue.size > 0) {
queue.dequeue()();
}
})();
};
const generator = (function_, ...arguments_) => new Promise(resolve => {
enqueue(function_, resolve, arguments_);
});
Object.defineProperties(generator, {
activeCount: {
get: () => activeCount,
},
pendingCount: {
get: () => queue.size,
},
clearQueue: {
value() {
queue.clear();
},
},
});
return generator;
}
const VOID = Symbol("p-void");
class PInstance extends Promise {
constructor(items = [], options) {
super(() => {
});
this.items = items;
this.options = options;
this.promises = /* @__PURE__ */ new Set();
}
get promise() {
var _a;
let batch;
const items = [...Array.from(this.items), ...Array.from(this.promises)];
if ((_a = this.options) == null ? void 0 : _a.concurrency) {
const limit = pLimit(this.options.concurrency);
batch = Promise.all(items.map((p2) => limit(() => p2)));
} else {
batch = Promise.all(items);
}
return batch.then((l) => l.filter((i) => i !== VOID));
}
add(...args) {
args.forEach((i) => {
this.promises.add(i);
});
}
map(fn) {
return new PInstance(
Array.from(this.items).map(async (i, idx) => {
const v = await i;
if (v === VOID)
return VOID;
return fn(v, idx);
}),
this.options
);
}
filter(fn) {
return new PInstance(
Array.from(this.items).map(async (i, idx) => {
const v = await i;
const r = await fn(v, idx);
if (!r)
return VOID;
return v;
}),
this.options
);
}
forEach(fn) {
return this.map(fn).then();
}
reduce(fn, initialValue) {
return this.promise.then((array) => array.reduce(fn, initialValue));
}
clear() {
this.promises.clear();
}
then(fn) {
const p2 = this.promise;
if (fn)
return p2.then(fn);
else
return p2;
}
catch(fn) {
return this.promise.catch(fn);
}
finally(fn) {
return this.promise.finally(fn);
}
}
function p(items, options) {
return new PInstance(items, options);
}
exports.assert = assert;
exports.at = at;
exports.batchInvoke = batchInvoke;
exports.capitalize = capitalize;
exports.clamp = clamp;
exports.clampArrayRange = clampArrayRange;
exports.clearUndefined = clearUndefined;
exports.createControlledPromise = createControlledPromise;
exports.createPromiseLock = createPromiseLock;
exports.createSingletonPromise = createSingletonPromise;
exports.debounce = debounce;
exports.deepMerge = deepMerge;
exports.deepMergeWithArray = deepMergeWithArray;
exports.ensurePrefix = ensurePrefix;
exports.ensureSuffix = ensureSuffix;
exports.flattenArrayable = flattenArrayable;
exports.getTypeName = getTypeName;
exports.hasOwnProperty = hasOwnProperty;
exports.invoke = invoke;
exports.isBoolean = isBoolean;
exports.isBrowser = isBrowser;
exports.isDate = isDate;
exports.isDeepEqual = isDeepEqual;
exports.isDef = isDef;
exports.isFunction = isFunction;
exports.isKeyOf = isKeyOf;
exports.isNull = isNull;
exports.isNumber = isNumber;
exports.isObject = isObject;
exports.isRegExp = isRegExp;
exports.isString = isString;
exports.isTruthy = isTruthy;
exports.isUndefined = isUndefined;
exports.isWindow = isWindow;
exports.last = last;
exports.lerp = lerp;
exports.mergeArrayable = mergeArrayable;
exports.move = move;
exports.noNull = noNull;
exports.noop = noop;
exports.notNullish = notNullish;
exports.notUndefined = notUndefined;
exports.objectEntries = objectEntries;
exports.objectKeys = objectKeys;
exports.objectMap = objectMap;
exports.objectPick = objectPick;
exports.p = p;
exports.partition = partition;
exports.randomStr = randomStr;
exports.range = range;
exports.remap = remap;
exports.remove = remove;
exports.sample = sample;
exports.shuffle = shuffle;
exports.slash = slash;
exports.sleep = sleep;
exports.sum = sum;
exports.tap = tap;
exports.template = template;
exports.throttle = throttle;
exports.timestamp = timestamp;
exports.toArray = toArray;
exports.toString = toString;
exports.unindent = unindent;
exports.uniq = uniq;
exports.uniqueBy = uniqueBy;
+614
View File
@@ -0,0 +1,614 @@
/**
* Promise, or maybe not
*/
type Awaitable<T> = T | PromiseLike<T>;
/**
* Null or whatever
*/
type Nullable<T> = T | null | undefined;
/**
* Array, or not yet
*/
type Arrayable<T> = T | Array<T>;
/**
* Function
*/
type Fn<T = void> = () => T;
/**
* Constructor
*/
type Constructor<T = void> = new (...args: any[]) => T;
/**
* Infers the element type of an array
*/
type ElementOf<T> = T extends (infer E)[] ? E : never;
/**
* Defines an intersection type of all union items.
*
* @param U Union of any types that will be intersected.
* @returns U items intersected
* @see https://stackoverflow.com/a/50375286/9259330
*/
type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
/**
* Infers the arguments type of a function
*/
type ArgumentsType<T> = T extends ((...args: infer A) => any) ? A : never;
type MergeInsertions<T> = T extends object ? {
[K in keyof T]: MergeInsertions<T[K]>;
} : T;
type DeepMerge<F, S> = MergeInsertions<{
[K in keyof F | keyof S]: K extends keyof S & keyof F ? DeepMerge<F[K], S[K]> : K extends keyof S ? S[K] : K extends keyof F ? F[K] : never;
}>;
/**
* Convert `Arrayable<T>` to `Array<T>`
*
* @category Array
*/
declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
/**
* Convert `Arrayable<T>` to `Array<T>` and flatten it
*
* @category Array
*/
declare function flattenArrayable<T>(array?: Nullable<Arrayable<T | Array<T>>>): Array<T>;
/**
* Use rest arguments to merge arrays
*
* @category Array
*/
declare function mergeArrayable<T>(...args: Nullable<Arrayable<T>>[]): Array<T>;
type PartitionFilter<T> = (i: T, idx: number, arr: readonly T[]) => any;
/**
* Divide an array into two parts by a filter function
*
* @category Array
* @example const [odd, even] = partition([1, 2, 3, 4], i => i % 2 != 0)
*/
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>): [T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>): [T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>): [T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>): [T[], T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>, f5: PartitionFilter<T>): [T[], T[], T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>, f5: PartitionFilter<T>, f6: PartitionFilter<T>): [T[], T[], T[], T[], T[], T[], T[]];
/**
* Unique an Array
*
* @category Array
*/
declare function uniq<T>(array: readonly T[]): T[];
/**
* Unique an Array by a custom equality function
*
* @category Array
*/
declare function uniqueBy<T>(array: readonly T[], equalFn: (a: any, b: any) => boolean): T[];
/**
* Get last item
*
* @category Array
*/
declare function last(array: readonly []): undefined;
declare function last<T>(array: readonly T[]): T;
/**
* Remove an item from Array
*
* @category Array
*/
declare function remove<T>(array: T[], value: T): boolean;
/**
* Get nth item of Array. Negative for backward
*
* @category Array
*/
declare function at(array: readonly [], index: number): undefined;
declare function at<T>(array: readonly T[], index: number): T;
/**
* Genrate a range array of numbers. The `stop` is exclusive.
*
* @category Array
*/
declare function range(stop: number): number[];
declare function range(start: number, stop: number, step?: number): number[];
/**
* Move element in an Array
*
* @category Array
* @param arr
* @param from
* @param to
*/
declare function move<T>(arr: T[], from: number, to: number): T[];
/**
* Clamp a number to the index range of an array
*
* @category Array
*/
declare function clampArrayRange(n: number, arr: readonly unknown[]): number;
/**
* Get random item(s) from an array
*
* @param arr
* @param quantity - quantity of random items which will be returned
*/
declare function sample<T>(arr: T[], quantity: number): T[];
/**
* Shuffle an array. This function mutates the array.
*
* @category Array
*/
declare function shuffle<T>(array: T[]): T[];
declare function assert(condition: boolean, message: string): asserts condition;
declare const toString: (v: any) => string;
declare function getTypeName(v: any): string;
declare function noop(): void;
declare function isDeepEqual(value1: any, value2: any): boolean;
/**
* Type guard to filter out null-ish values
*
* @category Guards
* @example array.filter(notNullish)
*/
declare function notNullish<T>(v: T | null | undefined): v is NonNullable<T>;
/**
* Type guard to filter out null values
*
* @category Guards
* @example array.filter(noNull)
*/
declare function noNull<T>(v: T | null): v is Exclude<T, null>;
/**
* Type guard to filter out null-ish values
*
* @category Guards
* @example array.filter(notUndefined)
*/
declare function notUndefined<T>(v: T): v is Exclude<T, undefined>;
/**
* Type guard to filter out falsy values
*
* @category Guards
* @example array.filter(isTruthy)
*/
declare function isTruthy<T>(v: T): v is NonNullable<T>;
declare const isDef: <T = any>(val?: T) => val is T;
declare const isBoolean: (val: any) => val is boolean;
declare const isFunction: <T extends Function>(val: any) => val is T;
declare const isNumber: (val: any) => val is number;
declare const isString: (val: unknown) => val is string;
declare const isObject: (val: any) => val is object;
declare const isUndefined: (val: any) => val is undefined;
declare const isNull: (val: any) => val is null;
declare const isRegExp: (val: any) => val is RegExp;
declare const isDate: (val: any) => val is Date;
declare const isWindow: (val: any) => boolean;
declare const isBrowser: boolean;
declare function clamp(n: number, min: number, max: number): number;
declare function sum(...args: number[] | number[][]): number;
/**
* Linearly interpolates between `min` and `max` based on `t`
*
* @category Math
* @param min The minimum value
* @param max The maximum value
* @param t The interpolation value clamped between 0 and 1
* @example
* ```
* const value = lerp(0, 2, 0.5) // value will be 1
* ```
*/
declare function lerp(min: number, max: number, t: number): number;
/**
* Linearly remaps a clamped value from its source range [`inMin`, `inMax`] to the destination range [`outMin`, `outMax`]
*
* @category Math
* @example
* ```
* const value = remap(0.5, 0, 1, 200, 400) // value will be 300
* ```
*/
declare function remap(n: number, inMin: number, inMax: number, outMin: number, outMax: number): number;
/**
* Replace backslash to slash
*
* @category String
*/
declare function slash(str: string): string;
/**
* Ensure prefix of a string
*
* @category String
*/
declare function ensurePrefix(prefix: string, str: string): string;
/**
* Ensure suffix of a string
*
* @category String
*/
declare function ensureSuffix(suffix: string, str: string): string;
/**
* Dead simple template engine, just like Python's `.format()`
* Support passing variables as either in index based or object/name based approach
* While using object/name based approach, you can pass a fallback value as the third argument
*
* @category String
* @example
* ```
* const result = template(
* 'Hello {0}! My name is {1}.',
* 'Inès',
* 'Anthony'
* ) // Hello Inès! My name is Anthony.
* ```
*
* ```
* const result = namedTemplate(
* '{greet}! My name is {name}.',
* { greet: 'Hello', name: 'Anthony' }
* ) // Hello! My name is Anthony.
* ```
*
* const result = namedTemplate(
* '{greet}! My name is {name}.',
* { greet: 'Hello' }, // name isn't passed hence fallback will be used for name
* 'placeholder'
* ) // Hello! My name is placeholder.
* ```
*/
declare function template(str: string, object: Record<string | number, any>, fallback?: string | ((key: string) => string)): string;
declare function template(str: string, ...args: (string | number | bigint | undefined | null)[]): string;
/**
* Generate a random string
* @category String
*/
declare function randomStr(size?: number, dict?: string): string;
/**
* First letter uppercase, other lowercase
* @category string
* @example
* ```
* capitalize('hello') => 'Hello'
* ```
*/
declare function capitalize(str: string): string;
/**
* Remove common leading whitespace from a template string.
* Will also remove empty lines at the beginning and end.
* @category string
* @example
* ```ts
* const str = unindent`
* if (a) {
* b()
* }
* `
*/
declare function unindent(str: TemplateStringsArray | string): string;
declare const timestamp: () => number;
/**
* Call every function in an array
*/
declare function batchInvoke(functions: Nullable<Fn>[]): void;
/**
* Call the function
*/
declare function invoke(fn: Fn): void;
/**
* Pass the value through the callback, and return the value
*
* @example
* ```
* function createUser(name: string): User {
* return tap(new User, user => {
* user.name = name
* })
* }
* ```
*/
declare function tap<T>(value: T, callback: (value: T) => void): T;
/**
* Map key/value pairs for an object, and construct a new one
*
*
* @category Object
*
* Transform:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => [k.toString().toUpperCase(), v.toString()])
* // { A: '1', B: '2' }
* ```
*
* Swap key/value:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => [v, k])
* // { 1: 'a', 2: 'b' }
* ```
*
* Filter keys:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => k === 'a' ? undefined : [k, v])
* // { b: 2 }
* ```
*/
declare function objectMap<K extends string, V, NK extends string | number | symbol = K, NV = V>(obj: Record<K, V>, fn: (key: K, value: V) => [NK, NV] | undefined): Record<NK, NV>;
/**
* Type guard for any key, `k`.
* Marks `k` as a key of `T` if `k` is in `obj`.
*
* @category Object
* @param obj object to query for key `k`
* @param k key to check existence in `obj`
*/
declare function isKeyOf<T extends object>(obj: T, k: keyof any): k is keyof T;
/**
* Strict typed `Object.keys`
*
* @category Object
*/
declare function objectKeys<T extends object>(obj: T): (`${keyof T & undefined}` | `${keyof T & null}` | `${keyof T & string}` | `${keyof T & number}` | `${keyof T & false}` | `${keyof T & true}`)[];
/**
* Strict typed `Object.entries`
*
* @category Object
*/
declare function objectEntries<T extends object>(obj: T): [keyof T, T[keyof T]][];
/**
* Deep merge
*
* The first argument is the target object, the rest are the sources.
* The target object will be mutated and returned.
*
* @category Object
*/
declare function deepMerge<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
/**
* Deep merge
*
* Differs from `deepMerge` in that it merges arrays instead of overriding them.
*
* The first argument is the target object, the rest are the sources.
* The target object will be mutated and returned.
*
* @category Object
*/
declare function deepMergeWithArray<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
/**
* Create a new subset object by giving keys
*
* @category Object
*/
declare function objectPick<O extends object, T extends keyof O>(obj: O, keys: T[], omitUndefined?: boolean): Pick<O, T>;
/**
* Clear undefined fields from an object. It mutates the object
*
* @category Object
*/
declare function clearUndefined<T extends object>(obj: T): T;
/**
* Determines whether an object has a property with the specified name
*
* @see https://eslint.org/docs/rules/no-prototype-builtins
* @category Object
*/
declare function hasOwnProperty<T>(obj: T, v: PropertyKey): boolean;
interface SingletonPromiseReturn<T> {
(): Promise<T>;
/**
* Reset current staled promise.
* Await it to have proper shutdown.
*/
reset: () => Promise<void>;
}
/**
* Create singleton promise function
*
* @category Promise
*/
declare function createSingletonPromise<T>(fn: () => Promise<T>): SingletonPromiseReturn<T>;
/**
* Promised `setTimeout`
*
* @category Promise
*/
declare function sleep(ms: number, callback?: Fn<any>): Promise<void>;
/**
* Create a promise lock
*
* @category Promise
* @example
* ```
* const lock = createPromiseLock()
*
* lock.run(async () => {
* await doSomething()
* })
*
* // in anther context:
* await lock.wait() // it will wait all tasking finished
* ```
*/
declare function createPromiseLock(): {
run<T = void>(fn: () => Promise<T>): Promise<T>;
wait(): Promise<void>;
isWaiting(): boolean;
clear(): void;
};
/**
* Promise with `resolve` and `reject` methods of itself
*/
interface ControlledPromise<T = void> extends Promise<T> {
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
}
/**
* Return a Promise with `resolve` and `reject` methods
*
* @category Promise
* @example
* ```
* const promise = createControlledPromise()
*
* await promise
*
* // in anther context:
* promise.resolve(data)
* ```
*/
declare function createControlledPromise<T>(): ControlledPromise<T>;
interface CancelOptions {
upcomingOnly?: boolean;
}
interface Cancel {
cancel: (options?: CancelOptions) => void;
}
interface NoReturn<T extends (...args: any[]) => any> {
(...args: Parameters<T>): void;
}
interface ThrottleOptions {
noTrailing?: boolean;
noLeading?: boolean;
debounceMode?: boolean;
}
interface DebounceOptions {
atBegin?: boolean;
}
type throttle<T extends (...args: any[]) => any> = NoReturn<T> & Cancel;
/**
* Throttle execution of a function. Especially useful for rate limiting
* execution of handlers on events like resize and scroll.
*
* @param delay
* A zero-or-greater delay in milliseconds. For event callbacks, values around
* 100 or 250 (or even higher) are most useful.
*
* @param callback
* A function to be executed after delay milliseconds. The `this` context and
* all arguments are passed through, as-is, to `callback` when the
* throttled-function is executed.
*
* @param options
* An object to configure options.
*
* @param options.noTrailing
* Optional, defaults to false. If noTrailing is true, callback will only execute
* every `delay` milliseconds while the throttled-function is being called. If
* noTrailing is false or unspecified, callback will be executed one final time
* after the last throttled-function call. (After the throttled-function has not
* been called for `delay` milliseconds, the internal counter is reset)
*
* @param options.noLeading
* Optional, defaults to false. If noLeading is false, the first throttled-function
* call will execute callback immediately. If noLeading is true, the first the
* callback execution will be skipped. It should be noted that callback will never
* executed if both noLeading = true and noTrailing = true.
*
* @param options.debounceMode If `debounceMode` is true (at begin), schedule
* `callback` to execute after `delay` ms. If `debounceMode` is false (at end),
* schedule `callback` to execute after `delay` ms.
*
* @return
* A new, throttled, function.
*/
declare function throttle<T extends (...args: any[]) => any>(
delay: number,
callback: T,
options?: ThrottleOptions,
): throttle<T>;
type debounce<T extends (...args: any[]) => any> = NoReturn<T> & Cancel;
/**
* Debounce execution of a function. Debouncing, unlike throttling,
* guarantees that a function is only executed a single time, either at the
* very beginning of a series of calls, or at the very end.
*
* @param delay
* A zero-or-greater delay in milliseconds. For event callbacks, values around
* 100 or 250 (or even higher) are most useful.
*
* @param callback
* A function to be executed after delay milliseconds. The `this` context and
* all arguments are passed through, as-is, to `callback` when the
* debounced-function is executed.
*
* @param options
* An object to configure options.
*
* @param options.atBegin
* If atBegin is false or unspecified, callback will only be executed `delay`
* milliseconds after the last debounced-function call. If atBegin is true,
* callback will be executed only at the first debounced-function call. (After
* the throttled-function has not been called for `delay` milliseconds, the
* internal counter is reset).
*
* @return
* A new, debounced function.
*/
declare function debounce<T extends (...args: any[]) => any>(
delay: number,
callback: T,
options?: DebounceOptions,
): debounce<T>;
interface POptions {
/**
* How many promises are resolved at the same time.
*/
concurrency?: number | undefined;
}
declare class PInstance<T = any> extends Promise<Awaited<T>[]> {
items: Iterable<T>;
options?: POptions | undefined;
private promises;
get promise(): Promise<Awaited<T>[]>;
constructor(items?: Iterable<T>, options?: POptions | undefined);
add(...args: (T | Promise<T>)[]): void;
map<U>(fn: (value: Awaited<T>, index: number) => U): PInstance<Promise<U>>;
filter(fn: (value: Awaited<T>, index: number) => boolean | Promise<boolean>): PInstance<Promise<T>>;
forEach(fn: (value: Awaited<T>, index: number) => void): Promise<void>;
reduce<U>(fn: (previousValue: U, currentValue: Awaited<T>, currentIndex: number, array: Awaited<T>[]) => U, initialValue: U): Promise<U>;
clear(): void;
then(fn?: () => PromiseLike<any>): Promise<any>;
catch(fn?: (err: unknown) => PromiseLike<any>): Promise<any>;
finally(fn?: () => void): Promise<Awaited<T>[]>;
}
/**
* Utility for managing multiple promises.
*
* @see https://github.com/antfu/utils/tree/main/docs/p.md
* @category Promise
* @example
* ```
* import { p } from '@antfu/utils'
*
* const items = [1, 2, 3, 4, 5]
*
* await p(items)
* .map(async i => await multiply(i, 3))
* .filter(async i => await isEven(i))
* // [6, 12]
* ```
*/
declare function p<T = any>(items?: Iterable<T>, options?: POptions): PInstance<T>;
export { type ArgumentsType, type Arrayable, type Awaitable, type Constructor, type ControlledPromise, type DeepMerge, type ElementOf, type Fn, type MergeInsertions, type Nullable, type PartitionFilter, type SingletonPromiseReturn, type UnionToIntersection, assert, at, batchInvoke, capitalize, clamp, clampArrayRange, clearUndefined, createControlledPromise, createPromiseLock, createSingletonPromise, debounce, deepMerge, deepMergeWithArray, ensurePrefix, ensureSuffix, flattenArrayable, getTypeName, hasOwnProperty, invoke, isBoolean, isBrowser, isDate, isDeepEqual, isDef, isFunction, isKeyOf, isNull, isNumber, isObject, isRegExp, isString, isTruthy, isUndefined, isWindow, last, lerp, mergeArrayable, move, noNull, noop, notNullish, notUndefined, objectEntries, objectKeys, objectMap, objectPick, p, partition, randomStr, range, remap, remove, sample, shuffle, slash, sleep, sum, tap, template, throttle, timestamp, toArray, toString, unindent, uniq, uniqueBy };
+614
View File
@@ -0,0 +1,614 @@
/**
* Promise, or maybe not
*/
type Awaitable<T> = T | PromiseLike<T>;
/**
* Null or whatever
*/
type Nullable<T> = T | null | undefined;
/**
* Array, or not yet
*/
type Arrayable<T> = T | Array<T>;
/**
* Function
*/
type Fn<T = void> = () => T;
/**
* Constructor
*/
type Constructor<T = void> = new (...args: any[]) => T;
/**
* Infers the element type of an array
*/
type ElementOf<T> = T extends (infer E)[] ? E : never;
/**
* Defines an intersection type of all union items.
*
* @param U Union of any types that will be intersected.
* @returns U items intersected
* @see https://stackoverflow.com/a/50375286/9259330
*/
type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
/**
* Infers the arguments type of a function
*/
type ArgumentsType<T> = T extends ((...args: infer A) => any) ? A : never;
type MergeInsertions<T> = T extends object ? {
[K in keyof T]: MergeInsertions<T[K]>;
} : T;
type DeepMerge<F, S> = MergeInsertions<{
[K in keyof F | keyof S]: K extends keyof S & keyof F ? DeepMerge<F[K], S[K]> : K extends keyof S ? S[K] : K extends keyof F ? F[K] : never;
}>;
/**
* Convert `Arrayable<T>` to `Array<T>`
*
* @category Array
*/
declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
/**
* Convert `Arrayable<T>` to `Array<T>` and flatten it
*
* @category Array
*/
declare function flattenArrayable<T>(array?: Nullable<Arrayable<T | Array<T>>>): Array<T>;
/**
* Use rest arguments to merge arrays
*
* @category Array
*/
declare function mergeArrayable<T>(...args: Nullable<Arrayable<T>>[]): Array<T>;
type PartitionFilter<T> = (i: T, idx: number, arr: readonly T[]) => any;
/**
* Divide an array into two parts by a filter function
*
* @category Array
* @example const [odd, even] = partition([1, 2, 3, 4], i => i % 2 != 0)
*/
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>): [T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>): [T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>): [T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>): [T[], T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>, f5: PartitionFilter<T>): [T[], T[], T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>, f5: PartitionFilter<T>, f6: PartitionFilter<T>): [T[], T[], T[], T[], T[], T[], T[]];
/**
* Unique an Array
*
* @category Array
*/
declare function uniq<T>(array: readonly T[]): T[];
/**
* Unique an Array by a custom equality function
*
* @category Array
*/
declare function uniqueBy<T>(array: readonly T[], equalFn: (a: any, b: any) => boolean): T[];
/**
* Get last item
*
* @category Array
*/
declare function last(array: readonly []): undefined;
declare function last<T>(array: readonly T[]): T;
/**
* Remove an item from Array
*
* @category Array
*/
declare function remove<T>(array: T[], value: T): boolean;
/**
* Get nth item of Array. Negative for backward
*
* @category Array
*/
declare function at(array: readonly [], index: number): undefined;
declare function at<T>(array: readonly T[], index: number): T;
/**
* Genrate a range array of numbers. The `stop` is exclusive.
*
* @category Array
*/
declare function range(stop: number): number[];
declare function range(start: number, stop: number, step?: number): number[];
/**
* Move element in an Array
*
* @category Array
* @param arr
* @param from
* @param to
*/
declare function move<T>(arr: T[], from: number, to: number): T[];
/**
* Clamp a number to the index range of an array
*
* @category Array
*/
declare function clampArrayRange(n: number, arr: readonly unknown[]): number;
/**
* Get random item(s) from an array
*
* @param arr
* @param quantity - quantity of random items which will be returned
*/
declare function sample<T>(arr: T[], quantity: number): T[];
/**
* Shuffle an array. This function mutates the array.
*
* @category Array
*/
declare function shuffle<T>(array: T[]): T[];
declare function assert(condition: boolean, message: string): asserts condition;
declare const toString: (v: any) => string;
declare function getTypeName(v: any): string;
declare function noop(): void;
declare function isDeepEqual(value1: any, value2: any): boolean;
/**
* Type guard to filter out null-ish values
*
* @category Guards
* @example array.filter(notNullish)
*/
declare function notNullish<T>(v: T | null | undefined): v is NonNullable<T>;
/**
* Type guard to filter out null values
*
* @category Guards
* @example array.filter(noNull)
*/
declare function noNull<T>(v: T | null): v is Exclude<T, null>;
/**
* Type guard to filter out null-ish values
*
* @category Guards
* @example array.filter(notUndefined)
*/
declare function notUndefined<T>(v: T): v is Exclude<T, undefined>;
/**
* Type guard to filter out falsy values
*
* @category Guards
* @example array.filter(isTruthy)
*/
declare function isTruthy<T>(v: T): v is NonNullable<T>;
declare const isDef: <T = any>(val?: T) => val is T;
declare const isBoolean: (val: any) => val is boolean;
declare const isFunction: <T extends Function>(val: any) => val is T;
declare const isNumber: (val: any) => val is number;
declare const isString: (val: unknown) => val is string;
declare const isObject: (val: any) => val is object;
declare const isUndefined: (val: any) => val is undefined;
declare const isNull: (val: any) => val is null;
declare const isRegExp: (val: any) => val is RegExp;
declare const isDate: (val: any) => val is Date;
declare const isWindow: (val: any) => boolean;
declare const isBrowser: boolean;
declare function clamp(n: number, min: number, max: number): number;
declare function sum(...args: number[] | number[][]): number;
/**
* Linearly interpolates between `min` and `max` based on `t`
*
* @category Math
* @param min The minimum value
* @param max The maximum value
* @param t The interpolation value clamped between 0 and 1
* @example
* ```
* const value = lerp(0, 2, 0.5) // value will be 1
* ```
*/
declare function lerp(min: number, max: number, t: number): number;
/**
* Linearly remaps a clamped value from its source range [`inMin`, `inMax`] to the destination range [`outMin`, `outMax`]
*
* @category Math
* @example
* ```
* const value = remap(0.5, 0, 1, 200, 400) // value will be 300
* ```
*/
declare function remap(n: number, inMin: number, inMax: number, outMin: number, outMax: number): number;
/**
* Replace backslash to slash
*
* @category String
*/
declare function slash(str: string): string;
/**
* Ensure prefix of a string
*
* @category String
*/
declare function ensurePrefix(prefix: string, str: string): string;
/**
* Ensure suffix of a string
*
* @category String
*/
declare function ensureSuffix(suffix: string, str: string): string;
/**
* Dead simple template engine, just like Python's `.format()`
* Support passing variables as either in index based or object/name based approach
* While using object/name based approach, you can pass a fallback value as the third argument
*
* @category String
* @example
* ```
* const result = template(
* 'Hello {0}! My name is {1}.',
* 'Inès',
* 'Anthony'
* ) // Hello Inès! My name is Anthony.
* ```
*
* ```
* const result = namedTemplate(
* '{greet}! My name is {name}.',
* { greet: 'Hello', name: 'Anthony' }
* ) // Hello! My name is Anthony.
* ```
*
* const result = namedTemplate(
* '{greet}! My name is {name}.',
* { greet: 'Hello' }, // name isn't passed hence fallback will be used for name
* 'placeholder'
* ) // Hello! My name is placeholder.
* ```
*/
declare function template(str: string, object: Record<string | number, any>, fallback?: string | ((key: string) => string)): string;
declare function template(str: string, ...args: (string | number | bigint | undefined | null)[]): string;
/**
* Generate a random string
* @category String
*/
declare function randomStr(size?: number, dict?: string): string;
/**
* First letter uppercase, other lowercase
* @category string
* @example
* ```
* capitalize('hello') => 'Hello'
* ```
*/
declare function capitalize(str: string): string;
/**
* Remove common leading whitespace from a template string.
* Will also remove empty lines at the beginning and end.
* @category string
* @example
* ```ts
* const str = unindent`
* if (a) {
* b()
* }
* `
*/
declare function unindent(str: TemplateStringsArray | string): string;
declare const timestamp: () => number;
/**
* Call every function in an array
*/
declare function batchInvoke(functions: Nullable<Fn>[]): void;
/**
* Call the function
*/
declare function invoke(fn: Fn): void;
/**
* Pass the value through the callback, and return the value
*
* @example
* ```
* function createUser(name: string): User {
* return tap(new User, user => {
* user.name = name
* })
* }
* ```
*/
declare function tap<T>(value: T, callback: (value: T) => void): T;
/**
* Map key/value pairs for an object, and construct a new one
*
*
* @category Object
*
* Transform:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => [k.toString().toUpperCase(), v.toString()])
* // { A: '1', B: '2' }
* ```
*
* Swap key/value:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => [v, k])
* // { 1: 'a', 2: 'b' }
* ```
*
* Filter keys:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => k === 'a' ? undefined : [k, v])
* // { b: 2 }
* ```
*/
declare function objectMap<K extends string, V, NK extends string | number | symbol = K, NV = V>(obj: Record<K, V>, fn: (key: K, value: V) => [NK, NV] | undefined): Record<NK, NV>;
/**
* Type guard for any key, `k`.
* Marks `k` as a key of `T` if `k` is in `obj`.
*
* @category Object
* @param obj object to query for key `k`
* @param k key to check existence in `obj`
*/
declare function isKeyOf<T extends object>(obj: T, k: keyof any): k is keyof T;
/**
* Strict typed `Object.keys`
*
* @category Object
*/
declare function objectKeys<T extends object>(obj: T): (`${keyof T & undefined}` | `${keyof T & null}` | `${keyof T & string}` | `${keyof T & number}` | `${keyof T & false}` | `${keyof T & true}`)[];
/**
* Strict typed `Object.entries`
*
* @category Object
*/
declare function objectEntries<T extends object>(obj: T): [keyof T, T[keyof T]][];
/**
* Deep merge
*
* The first argument is the target object, the rest are the sources.
* The target object will be mutated and returned.
*
* @category Object
*/
declare function deepMerge<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
/**
* Deep merge
*
* Differs from `deepMerge` in that it merges arrays instead of overriding them.
*
* The first argument is the target object, the rest are the sources.
* The target object will be mutated and returned.
*
* @category Object
*/
declare function deepMergeWithArray<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
/**
* Create a new subset object by giving keys
*
* @category Object
*/
declare function objectPick<O extends object, T extends keyof O>(obj: O, keys: T[], omitUndefined?: boolean): Pick<O, T>;
/**
* Clear undefined fields from an object. It mutates the object
*
* @category Object
*/
declare function clearUndefined<T extends object>(obj: T): T;
/**
* Determines whether an object has a property with the specified name
*
* @see https://eslint.org/docs/rules/no-prototype-builtins
* @category Object
*/
declare function hasOwnProperty<T>(obj: T, v: PropertyKey): boolean;
interface SingletonPromiseReturn<T> {
(): Promise<T>;
/**
* Reset current staled promise.
* Await it to have proper shutdown.
*/
reset: () => Promise<void>;
}
/**
* Create singleton promise function
*
* @category Promise
*/
declare function createSingletonPromise<T>(fn: () => Promise<T>): SingletonPromiseReturn<T>;
/**
* Promised `setTimeout`
*
* @category Promise
*/
declare function sleep(ms: number, callback?: Fn<any>): Promise<void>;
/**
* Create a promise lock
*
* @category Promise
* @example
* ```
* const lock = createPromiseLock()
*
* lock.run(async () => {
* await doSomething()
* })
*
* // in anther context:
* await lock.wait() // it will wait all tasking finished
* ```
*/
declare function createPromiseLock(): {
run<T = void>(fn: () => Promise<T>): Promise<T>;
wait(): Promise<void>;
isWaiting(): boolean;
clear(): void;
};
/**
* Promise with `resolve` and `reject` methods of itself
*/
interface ControlledPromise<T = void> extends Promise<T> {
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
}
/**
* Return a Promise with `resolve` and `reject` methods
*
* @category Promise
* @example
* ```
* const promise = createControlledPromise()
*
* await promise
*
* // in anther context:
* promise.resolve(data)
* ```
*/
declare function createControlledPromise<T>(): ControlledPromise<T>;
interface CancelOptions {
upcomingOnly?: boolean;
}
interface Cancel {
cancel: (options?: CancelOptions) => void;
}
interface NoReturn<T extends (...args: any[]) => any> {
(...args: Parameters<T>): void;
}
interface ThrottleOptions {
noTrailing?: boolean;
noLeading?: boolean;
debounceMode?: boolean;
}
interface DebounceOptions {
atBegin?: boolean;
}
type throttle<T extends (...args: any[]) => any> = NoReturn<T> & Cancel;
/**
* Throttle execution of a function. Especially useful for rate limiting
* execution of handlers on events like resize and scroll.
*
* @param delay
* A zero-or-greater delay in milliseconds. For event callbacks, values around
* 100 or 250 (or even higher) are most useful.
*
* @param callback
* A function to be executed after delay milliseconds. The `this` context and
* all arguments are passed through, as-is, to `callback` when the
* throttled-function is executed.
*
* @param options
* An object to configure options.
*
* @param options.noTrailing
* Optional, defaults to false. If noTrailing is true, callback will only execute
* every `delay` milliseconds while the throttled-function is being called. If
* noTrailing is false or unspecified, callback will be executed one final time
* after the last throttled-function call. (After the throttled-function has not
* been called for `delay` milliseconds, the internal counter is reset)
*
* @param options.noLeading
* Optional, defaults to false. If noLeading is false, the first throttled-function
* call will execute callback immediately. If noLeading is true, the first the
* callback execution will be skipped. It should be noted that callback will never
* executed if both noLeading = true and noTrailing = true.
*
* @param options.debounceMode If `debounceMode` is true (at begin), schedule
* `callback` to execute after `delay` ms. If `debounceMode` is false (at end),
* schedule `callback` to execute after `delay` ms.
*
* @return
* A new, throttled, function.
*/
declare function throttle<T extends (...args: any[]) => any>(
delay: number,
callback: T,
options?: ThrottleOptions,
): throttle<T>;
type debounce<T extends (...args: any[]) => any> = NoReturn<T> & Cancel;
/**
* Debounce execution of a function. Debouncing, unlike throttling,
* guarantees that a function is only executed a single time, either at the
* very beginning of a series of calls, or at the very end.
*
* @param delay
* A zero-or-greater delay in milliseconds. For event callbacks, values around
* 100 or 250 (or even higher) are most useful.
*
* @param callback
* A function to be executed after delay milliseconds. The `this` context and
* all arguments are passed through, as-is, to `callback` when the
* debounced-function is executed.
*
* @param options
* An object to configure options.
*
* @param options.atBegin
* If atBegin is false or unspecified, callback will only be executed `delay`
* milliseconds after the last debounced-function call. If atBegin is true,
* callback will be executed only at the first debounced-function call. (After
* the throttled-function has not been called for `delay` milliseconds, the
* internal counter is reset).
*
* @return
* A new, debounced function.
*/
declare function debounce<T extends (...args: any[]) => any>(
delay: number,
callback: T,
options?: DebounceOptions,
): debounce<T>;
interface POptions {
/**
* How many promises are resolved at the same time.
*/
concurrency?: number | undefined;
}
declare class PInstance<T = any> extends Promise<Awaited<T>[]> {
items: Iterable<T>;
options?: POptions | undefined;
private promises;
get promise(): Promise<Awaited<T>[]>;
constructor(items?: Iterable<T>, options?: POptions | undefined);
add(...args: (T | Promise<T>)[]): void;
map<U>(fn: (value: Awaited<T>, index: number) => U): PInstance<Promise<U>>;
filter(fn: (value: Awaited<T>, index: number) => boolean | Promise<boolean>): PInstance<Promise<T>>;
forEach(fn: (value: Awaited<T>, index: number) => void): Promise<void>;
reduce<U>(fn: (previousValue: U, currentValue: Awaited<T>, currentIndex: number, array: Awaited<T>[]) => U, initialValue: U): Promise<U>;
clear(): void;
then(fn?: () => PromiseLike<any>): Promise<any>;
catch(fn?: (err: unknown) => PromiseLike<any>): Promise<any>;
finally(fn?: () => void): Promise<Awaited<T>[]>;
}
/**
* Utility for managing multiple promises.
*
* @see https://github.com/antfu/utils/tree/main/docs/p.md
* @category Promise
* @example
* ```
* import { p } from '@antfu/utils'
*
* const items = [1, 2, 3, 4, 5]
*
* await p(items)
* .map(async i => await multiply(i, 3))
* .filter(async i => await isEven(i))
* // [6, 12]
* ```
*/
declare function p<T = any>(items?: Iterable<T>, options?: POptions): PInstance<T>;
export { type ArgumentsType, type Arrayable, type Awaitable, type Constructor, type ControlledPromise, type DeepMerge, type ElementOf, type Fn, type MergeInsertions, type Nullable, type PartitionFilter, type SingletonPromiseReturn, type UnionToIntersection, assert, at, batchInvoke, capitalize, clamp, clampArrayRange, clearUndefined, createControlledPromise, createPromiseLock, createSingletonPromise, debounce, deepMerge, deepMergeWithArray, ensurePrefix, ensureSuffix, flattenArrayable, getTypeName, hasOwnProperty, invoke, isBoolean, isBrowser, isDate, isDeepEqual, isDef, isFunction, isKeyOf, isNull, isNumber, isObject, isRegExp, isString, isTruthy, isUndefined, isWindow, last, lerp, mergeArrayable, move, noNull, noop, notNullish, notUndefined, objectEntries, objectKeys, objectMap, objectPick, p, partition, randomStr, range, remap, remove, sample, shuffle, slash, sleep, sum, tap, template, throttle, timestamp, toArray, toString, unindent, uniq, uniqueBy };
+614
View File
@@ -0,0 +1,614 @@
/**
* Promise, or maybe not
*/
type Awaitable<T> = T | PromiseLike<T>;
/**
* Null or whatever
*/
type Nullable<T> = T | null | undefined;
/**
* Array, or not yet
*/
type Arrayable<T> = T | Array<T>;
/**
* Function
*/
type Fn<T = void> = () => T;
/**
* Constructor
*/
type Constructor<T = void> = new (...args: any[]) => T;
/**
* Infers the element type of an array
*/
type ElementOf<T> = T extends (infer E)[] ? E : never;
/**
* Defines an intersection type of all union items.
*
* @param U Union of any types that will be intersected.
* @returns U items intersected
* @see https://stackoverflow.com/a/50375286/9259330
*/
type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
/**
* Infers the arguments type of a function
*/
type ArgumentsType<T> = T extends ((...args: infer A) => any) ? A : never;
type MergeInsertions<T> = T extends object ? {
[K in keyof T]: MergeInsertions<T[K]>;
} : T;
type DeepMerge<F, S> = MergeInsertions<{
[K in keyof F | keyof S]: K extends keyof S & keyof F ? DeepMerge<F[K], S[K]> : K extends keyof S ? S[K] : K extends keyof F ? F[K] : never;
}>;
/**
* Convert `Arrayable<T>` to `Array<T>`
*
* @category Array
*/
declare function toArray<T>(array?: Nullable<Arrayable<T>>): Array<T>;
/**
* Convert `Arrayable<T>` to `Array<T>` and flatten it
*
* @category Array
*/
declare function flattenArrayable<T>(array?: Nullable<Arrayable<T | Array<T>>>): Array<T>;
/**
* Use rest arguments to merge arrays
*
* @category Array
*/
declare function mergeArrayable<T>(...args: Nullable<Arrayable<T>>[]): Array<T>;
type PartitionFilter<T> = (i: T, idx: number, arr: readonly T[]) => any;
/**
* Divide an array into two parts by a filter function
*
* @category Array
* @example const [odd, even] = partition([1, 2, 3, 4], i => i % 2 != 0)
*/
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>): [T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>): [T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>): [T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>): [T[], T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>, f5: PartitionFilter<T>): [T[], T[], T[], T[], T[], T[]];
declare function partition<T>(array: readonly T[], f1: PartitionFilter<T>, f2: PartitionFilter<T>, f3: PartitionFilter<T>, f4: PartitionFilter<T>, f5: PartitionFilter<T>, f6: PartitionFilter<T>): [T[], T[], T[], T[], T[], T[], T[]];
/**
* Unique an Array
*
* @category Array
*/
declare function uniq<T>(array: readonly T[]): T[];
/**
* Unique an Array by a custom equality function
*
* @category Array
*/
declare function uniqueBy<T>(array: readonly T[], equalFn: (a: any, b: any) => boolean): T[];
/**
* Get last item
*
* @category Array
*/
declare function last(array: readonly []): undefined;
declare function last<T>(array: readonly T[]): T;
/**
* Remove an item from Array
*
* @category Array
*/
declare function remove<T>(array: T[], value: T): boolean;
/**
* Get nth item of Array. Negative for backward
*
* @category Array
*/
declare function at(array: readonly [], index: number): undefined;
declare function at<T>(array: readonly T[], index: number): T;
/**
* Genrate a range array of numbers. The `stop` is exclusive.
*
* @category Array
*/
declare function range(stop: number): number[];
declare function range(start: number, stop: number, step?: number): number[];
/**
* Move element in an Array
*
* @category Array
* @param arr
* @param from
* @param to
*/
declare function move<T>(arr: T[], from: number, to: number): T[];
/**
* Clamp a number to the index range of an array
*
* @category Array
*/
declare function clampArrayRange(n: number, arr: readonly unknown[]): number;
/**
* Get random item(s) from an array
*
* @param arr
* @param quantity - quantity of random items which will be returned
*/
declare function sample<T>(arr: T[], quantity: number): T[];
/**
* Shuffle an array. This function mutates the array.
*
* @category Array
*/
declare function shuffle<T>(array: T[]): T[];
declare function assert(condition: boolean, message: string): asserts condition;
declare const toString: (v: any) => string;
declare function getTypeName(v: any): string;
declare function noop(): void;
declare function isDeepEqual(value1: any, value2: any): boolean;
/**
* Type guard to filter out null-ish values
*
* @category Guards
* @example array.filter(notNullish)
*/
declare function notNullish<T>(v: T | null | undefined): v is NonNullable<T>;
/**
* Type guard to filter out null values
*
* @category Guards
* @example array.filter(noNull)
*/
declare function noNull<T>(v: T | null): v is Exclude<T, null>;
/**
* Type guard to filter out null-ish values
*
* @category Guards
* @example array.filter(notUndefined)
*/
declare function notUndefined<T>(v: T): v is Exclude<T, undefined>;
/**
* Type guard to filter out falsy values
*
* @category Guards
* @example array.filter(isTruthy)
*/
declare function isTruthy<T>(v: T): v is NonNullable<T>;
declare const isDef: <T = any>(val?: T) => val is T;
declare const isBoolean: (val: any) => val is boolean;
declare const isFunction: <T extends Function>(val: any) => val is T;
declare const isNumber: (val: any) => val is number;
declare const isString: (val: unknown) => val is string;
declare const isObject: (val: any) => val is object;
declare const isUndefined: (val: any) => val is undefined;
declare const isNull: (val: any) => val is null;
declare const isRegExp: (val: any) => val is RegExp;
declare const isDate: (val: any) => val is Date;
declare const isWindow: (val: any) => boolean;
declare const isBrowser: boolean;
declare function clamp(n: number, min: number, max: number): number;
declare function sum(...args: number[] | number[][]): number;
/**
* Linearly interpolates between `min` and `max` based on `t`
*
* @category Math
* @param min The minimum value
* @param max The maximum value
* @param t The interpolation value clamped between 0 and 1
* @example
* ```
* const value = lerp(0, 2, 0.5) // value will be 1
* ```
*/
declare function lerp(min: number, max: number, t: number): number;
/**
* Linearly remaps a clamped value from its source range [`inMin`, `inMax`] to the destination range [`outMin`, `outMax`]
*
* @category Math
* @example
* ```
* const value = remap(0.5, 0, 1, 200, 400) // value will be 300
* ```
*/
declare function remap(n: number, inMin: number, inMax: number, outMin: number, outMax: number): number;
/**
* Replace backslash to slash
*
* @category String
*/
declare function slash(str: string): string;
/**
* Ensure prefix of a string
*
* @category String
*/
declare function ensurePrefix(prefix: string, str: string): string;
/**
* Ensure suffix of a string
*
* @category String
*/
declare function ensureSuffix(suffix: string, str: string): string;
/**
* Dead simple template engine, just like Python's `.format()`
* Support passing variables as either in index based or object/name based approach
* While using object/name based approach, you can pass a fallback value as the third argument
*
* @category String
* @example
* ```
* const result = template(
* 'Hello {0}! My name is {1}.',
* 'Inès',
* 'Anthony'
* ) // Hello Inès! My name is Anthony.
* ```
*
* ```
* const result = namedTemplate(
* '{greet}! My name is {name}.',
* { greet: 'Hello', name: 'Anthony' }
* ) // Hello! My name is Anthony.
* ```
*
* const result = namedTemplate(
* '{greet}! My name is {name}.',
* { greet: 'Hello' }, // name isn't passed hence fallback will be used for name
* 'placeholder'
* ) // Hello! My name is placeholder.
* ```
*/
declare function template(str: string, object: Record<string | number, any>, fallback?: string | ((key: string) => string)): string;
declare function template(str: string, ...args: (string | number | bigint | undefined | null)[]): string;
/**
* Generate a random string
* @category String
*/
declare function randomStr(size?: number, dict?: string): string;
/**
* First letter uppercase, other lowercase
* @category string
* @example
* ```
* capitalize('hello') => 'Hello'
* ```
*/
declare function capitalize(str: string): string;
/**
* Remove common leading whitespace from a template string.
* Will also remove empty lines at the beginning and end.
* @category string
* @example
* ```ts
* const str = unindent`
* if (a) {
* b()
* }
* `
*/
declare function unindent(str: TemplateStringsArray | string): string;
declare const timestamp: () => number;
/**
* Call every function in an array
*/
declare function batchInvoke(functions: Nullable<Fn>[]): void;
/**
* Call the function
*/
declare function invoke(fn: Fn): void;
/**
* Pass the value through the callback, and return the value
*
* @example
* ```
* function createUser(name: string): User {
* return tap(new User, user => {
* user.name = name
* })
* }
* ```
*/
declare function tap<T>(value: T, callback: (value: T) => void): T;
/**
* Map key/value pairs for an object, and construct a new one
*
*
* @category Object
*
* Transform:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => [k.toString().toUpperCase(), v.toString()])
* // { A: '1', B: '2' }
* ```
*
* Swap key/value:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => [v, k])
* // { 1: 'a', 2: 'b' }
* ```
*
* Filter keys:
* @example
* ```
* objectMap({ a: 1, b: 2 }, (k, v) => k === 'a' ? undefined : [k, v])
* // { b: 2 }
* ```
*/
declare function objectMap<K extends string, V, NK extends string | number | symbol = K, NV = V>(obj: Record<K, V>, fn: (key: K, value: V) => [NK, NV] | undefined): Record<NK, NV>;
/**
* Type guard for any key, `k`.
* Marks `k` as a key of `T` if `k` is in `obj`.
*
* @category Object
* @param obj object to query for key `k`
* @param k key to check existence in `obj`
*/
declare function isKeyOf<T extends object>(obj: T, k: keyof any): k is keyof T;
/**
* Strict typed `Object.keys`
*
* @category Object
*/
declare function objectKeys<T extends object>(obj: T): (`${keyof T & undefined}` | `${keyof T & null}` | `${keyof T & string}` | `${keyof T & number}` | `${keyof T & false}` | `${keyof T & true}`)[];
/**
* Strict typed `Object.entries`
*
* @category Object
*/
declare function objectEntries<T extends object>(obj: T): [keyof T, T[keyof T]][];
/**
* Deep merge
*
* The first argument is the target object, the rest are the sources.
* The target object will be mutated and returned.
*
* @category Object
*/
declare function deepMerge<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
/**
* Deep merge
*
* Differs from `deepMerge` in that it merges arrays instead of overriding them.
*
* The first argument is the target object, the rest are the sources.
* The target object will be mutated and returned.
*
* @category Object
*/
declare function deepMergeWithArray<T extends object = object, S extends object = T>(target: T, ...sources: S[]): DeepMerge<T, S>;
/**
* Create a new subset object by giving keys
*
* @category Object
*/
declare function objectPick<O extends object, T extends keyof O>(obj: O, keys: T[], omitUndefined?: boolean): Pick<O, T>;
/**
* Clear undefined fields from an object. It mutates the object
*
* @category Object
*/
declare function clearUndefined<T extends object>(obj: T): T;
/**
* Determines whether an object has a property with the specified name
*
* @see https://eslint.org/docs/rules/no-prototype-builtins
* @category Object
*/
declare function hasOwnProperty<T>(obj: T, v: PropertyKey): boolean;
interface SingletonPromiseReturn<T> {
(): Promise<T>;
/**
* Reset current staled promise.
* Await it to have proper shutdown.
*/
reset: () => Promise<void>;
}
/**
* Create singleton promise function
*
* @category Promise
*/
declare function createSingletonPromise<T>(fn: () => Promise<T>): SingletonPromiseReturn<T>;
/**
* Promised `setTimeout`
*
* @category Promise
*/
declare function sleep(ms: number, callback?: Fn<any>): Promise<void>;
/**
* Create a promise lock
*
* @category Promise
* @example
* ```
* const lock = createPromiseLock()
*
* lock.run(async () => {
* await doSomething()
* })
*
* // in anther context:
* await lock.wait() // it will wait all tasking finished
* ```
*/
declare function createPromiseLock(): {
run<T = void>(fn: () => Promise<T>): Promise<T>;
wait(): Promise<void>;
isWaiting(): boolean;
clear(): void;
};
/**
* Promise with `resolve` and `reject` methods of itself
*/
interface ControlledPromise<T = void> extends Promise<T> {
resolve: (value: T | PromiseLike<T>) => void;
reject: (reason?: any) => void;
}
/**
* Return a Promise with `resolve` and `reject` methods
*
* @category Promise
* @example
* ```
* const promise = createControlledPromise()
*
* await promise
*
* // in anther context:
* promise.resolve(data)
* ```
*/
declare function createControlledPromise<T>(): ControlledPromise<T>;
interface CancelOptions {
upcomingOnly?: boolean;
}
interface Cancel {
cancel: (options?: CancelOptions) => void;
}
interface NoReturn<T extends (...args: any[]) => any> {
(...args: Parameters<T>): void;
}
interface ThrottleOptions {
noTrailing?: boolean;
noLeading?: boolean;
debounceMode?: boolean;
}
interface DebounceOptions {
atBegin?: boolean;
}
type throttle<T extends (...args: any[]) => any> = NoReturn<T> & Cancel;
/**
* Throttle execution of a function. Especially useful for rate limiting
* execution of handlers on events like resize and scroll.
*
* @param delay
* A zero-or-greater delay in milliseconds. For event callbacks, values around
* 100 or 250 (or even higher) are most useful.
*
* @param callback
* A function to be executed after delay milliseconds. The `this` context and
* all arguments are passed through, as-is, to `callback` when the
* throttled-function is executed.
*
* @param options
* An object to configure options.
*
* @param options.noTrailing
* Optional, defaults to false. If noTrailing is true, callback will only execute
* every `delay` milliseconds while the throttled-function is being called. If
* noTrailing is false or unspecified, callback will be executed one final time
* after the last throttled-function call. (After the throttled-function has not
* been called for `delay` milliseconds, the internal counter is reset)
*
* @param options.noLeading
* Optional, defaults to false. If noLeading is false, the first throttled-function
* call will execute callback immediately. If noLeading is true, the first the
* callback execution will be skipped. It should be noted that callback will never
* executed if both noLeading = true and noTrailing = true.
*
* @param options.debounceMode If `debounceMode` is true (at begin), schedule
* `callback` to execute after `delay` ms. If `debounceMode` is false (at end),
* schedule `callback` to execute after `delay` ms.
*
* @return
* A new, throttled, function.
*/
declare function throttle<T extends (...args: any[]) => any>(
delay: number,
callback: T,
options?: ThrottleOptions,
): throttle<T>;
type debounce<T extends (...args: any[]) => any> = NoReturn<T> & Cancel;
/**
* Debounce execution of a function. Debouncing, unlike throttling,
* guarantees that a function is only executed a single time, either at the
* very beginning of a series of calls, or at the very end.
*
* @param delay
* A zero-or-greater delay in milliseconds. For event callbacks, values around
* 100 or 250 (or even higher) are most useful.
*
* @param callback
* A function to be executed after delay milliseconds. The `this` context and
* all arguments are passed through, as-is, to `callback` when the
* debounced-function is executed.
*
* @param options
* An object to configure options.
*
* @param options.atBegin
* If atBegin is false or unspecified, callback will only be executed `delay`
* milliseconds after the last debounced-function call. If atBegin is true,
* callback will be executed only at the first debounced-function call. (After
* the throttled-function has not been called for `delay` milliseconds, the
* internal counter is reset).
*
* @return
* A new, debounced function.
*/
declare function debounce<T extends (...args: any[]) => any>(
delay: number,
callback: T,
options?: DebounceOptions,
): debounce<T>;
interface POptions {
/**
* How many promises are resolved at the same time.
*/
concurrency?: number | undefined;
}
declare class PInstance<T = any> extends Promise<Awaited<T>[]> {
items: Iterable<T>;
options?: POptions | undefined;
private promises;
get promise(): Promise<Awaited<T>[]>;
constructor(items?: Iterable<T>, options?: POptions | undefined);
add(...args: (T | Promise<T>)[]): void;
map<U>(fn: (value: Awaited<T>, index: number) => U): PInstance<Promise<U>>;
filter(fn: (value: Awaited<T>, index: number) => boolean | Promise<boolean>): PInstance<Promise<T>>;
forEach(fn: (value: Awaited<T>, index: number) => void): Promise<void>;
reduce<U>(fn: (previousValue: U, currentValue: Awaited<T>, currentIndex: number, array: Awaited<T>[]) => U, initialValue: U): Promise<U>;
clear(): void;
then(fn?: () => PromiseLike<any>): Promise<any>;
catch(fn?: (err: unknown) => PromiseLike<any>): Promise<any>;
finally(fn?: () => void): Promise<Awaited<T>[]>;
}
/**
* Utility for managing multiple promises.
*
* @see https://github.com/antfu/utils/tree/main/docs/p.md
* @category Promise
* @example
* ```
* import { p } from '@antfu/utils'
*
* const items = [1, 2, 3, 4, 5]
*
* await p(items)
* .map(async i => await multiply(i, 3))
* .filter(async i => await isEven(i))
* // [6, 12]
* ```
*/
declare function p<T = any>(items?: Iterable<T>, options?: POptions): PInstance<T>;
export { type ArgumentsType, type Arrayable, type Awaitable, type Constructor, type ControlledPromise, type DeepMerge, type ElementOf, type Fn, type MergeInsertions, type Nullable, type PartitionFilter, type SingletonPromiseReturn, type UnionToIntersection, assert, at, batchInvoke, capitalize, clamp, clampArrayRange, clearUndefined, createControlledPromise, createPromiseLock, createSingletonPromise, debounce, deepMerge, deepMergeWithArray, ensurePrefix, ensureSuffix, flattenArrayable, getTypeName, hasOwnProperty, invoke, isBoolean, isBrowser, isDate, isDeepEqual, isDef, isFunction, isKeyOf, isNull, isNumber, isObject, isRegExp, isString, isTruthy, isUndefined, isWindow, last, lerp, mergeArrayable, move, noNull, noop, notNullish, notUndefined, objectEntries, objectKeys, objectMap, objectPick, p, partition, randomStr, range, remap, remove, sample, shuffle, slash, sleep, sum, tap, template, throttle, timestamp, toArray, toString, unindent, uniq, uniqueBy };
+777
View File
@@ -0,0 +1,777 @@
function clamp(n, min, max) {
return Math.min(max, Math.max(min, n));
}
function sum(...args) {
return flattenArrayable(args).reduce((a, b) => a + b, 0);
}
function lerp(min, max, t) {
const interpolation = clamp(t, 0, 1);
return min + (max - min) * interpolation;
}
function remap(n, inMin, inMax, outMin, outMax) {
const interpolation = (n - inMin) / (inMax - inMin);
return lerp(outMin, outMax, interpolation);
}
function toArray(array) {
array = array ?? [];
return Array.isArray(array) ? array : [array];
}
function flattenArrayable(array) {
return toArray(array).flat(1);
}
function mergeArrayable(...args) {
return args.flatMap((i) => toArray(i));
}
function partition(array, ...filters) {
const result = Array.from({ length: filters.length + 1 }).fill(null).map(() => []);
array.forEach((e, idx, arr) => {
let i = 0;
for (const filter of filters) {
if (filter(e, idx, arr)) {
result[i].push(e);
return;
}
i += 1;
}
result[i].push(e);
});
return result;
}
function uniq(array) {
return Array.from(new Set(array));
}
function uniqueBy(array, equalFn) {
return array.reduce((acc, cur) => {
const index = acc.findIndex((item) => equalFn(cur, item));
if (index === -1)
acc.push(cur);
return acc;
}, []);
}
function last(array) {
return at(array, -1);
}
function remove(array, value) {
if (!array)
return false;
const index = array.indexOf(value);
if (index >= 0) {
array.splice(index, 1);
return true;
}
return false;
}
function at(array, index) {
const len = array.length;
if (!len)
return void 0;
if (index < 0)
index += len;
return array[index];
}
function range(...args) {
let start, stop, step;
if (args.length === 1) {
start = 0;
step = 1;
[stop] = args;
} else {
[start, stop, step = 1] = args;
}
const arr = [];
let current = start;
while (current < stop) {
arr.push(current);
current += step || 1;
}
return arr;
}
function move(arr, from, to) {
arr.splice(to, 0, arr.splice(from, 1)[0]);
return arr;
}
function clampArrayRange(n, arr) {
return clamp(n, 0, arr.length - 1);
}
function sample(arr, quantity) {
return Array.from({ length: quantity }, (_) => arr[Math.round(Math.random() * (arr.length - 1))]);
}
function shuffle(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
function assert(condition, message) {
if (!condition)
throw new Error(message);
}
const toString = (v) => Object.prototype.toString.call(v);
function getTypeName(v) {
if (v === null)
return "null";
const type = toString(v).slice(8, -1).toLowerCase();
return typeof v === "object" || typeof v === "function" ? type : typeof v;
}
function noop() {
}
function isDeepEqual(value1, value2) {
const type1 = getTypeName(value1);
const type2 = getTypeName(value2);
if (type1 !== type2)
return false;
if (type1 === "array") {
if (value1.length !== value2.length)
return false;
return value1.every((item, i) => {
return isDeepEqual(item, value2[i]);
});
}
if (type1 === "object") {
const keyArr = Object.keys(value1);
if (keyArr.length !== Object.keys(value2).length)
return false;
return keyArr.every((key) => {
return isDeepEqual(value1[key], value2[key]);
});
}
return Object.is(value1, value2);
}
function notNullish(v) {
return v != null;
}
function noNull(v) {
return v !== null;
}
function notUndefined(v) {
return v !== void 0;
}
function isTruthy(v) {
return Boolean(v);
}
const isDef = (val) => typeof val !== "undefined";
const isBoolean = (val) => typeof val === "boolean";
const isFunction = (val) => typeof val === "function";
const isNumber = (val) => typeof val === "number";
const isString = (val) => typeof val === "string";
const isObject = (val) => toString(val) === "[object Object]";
const isUndefined = (val) => toString(val) === "[object Undefined]";
const isNull = (val) => toString(val) === "[object Null]";
const isRegExp = (val) => toString(val) === "[object RegExp]";
const isDate = (val) => toString(val) === "[object Date]";
const isWindow = (val) => typeof window !== "undefined" && toString(val) === "[object Window]";
const isBrowser = typeof window !== "undefined";
function slash(str) {
return str.replace(/\\/g, "/");
}
function ensurePrefix(prefix, str) {
if (!str.startsWith(prefix))
return prefix + str;
return str;
}
function ensureSuffix(suffix, str) {
if (!str.endsWith(suffix))
return str + suffix;
return str;
}
function template(str, ...args) {
const [firstArg, fallback] = args;
if (isObject(firstArg)) {
const vars = firstArg;
return str.replace(/{([\w\d]+)}/g, (_, key) => vars[key] || ((typeof fallback === "function" ? fallback(key) : fallback) ?? key));
} else {
return str.replace(/{(\d+)}/g, (_, key) => {
const index = Number(key);
if (Number.isNaN(index))
return key;
return args[index];
});
}
}
const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
function randomStr(size = 16, dict = urlAlphabet) {
let id = "";
let i = size;
const len = dict.length;
while (i--)
id += dict[Math.random() * len | 0];
return id;
}
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1).toLowerCase();
}
const _reFullWs = /^\s*$/;
function unindent(str) {
const lines = (typeof str === "string" ? str : str[0]).split("\n");
const whitespaceLines = lines.map((line) => _reFullWs.test(line));
const commonIndent = lines.reduce((min, line, idx) => {
var _a;
if (whitespaceLines[idx])
return min;
const indent = (_a = line.match(/^\s*/)) == null ? void 0 : _a[0].length;
return indent === void 0 ? min : Math.min(min, indent);
}, Number.POSITIVE_INFINITY);
let emptyLinesHead = 0;
while (emptyLinesHead < lines.length && whitespaceLines[emptyLinesHead])
emptyLinesHead++;
let emptyLinesTail = 0;
while (emptyLinesTail < lines.length && whitespaceLines[lines.length - emptyLinesTail - 1])
emptyLinesTail++;
return lines.slice(emptyLinesHead, lines.length - emptyLinesTail).map((line) => line.slice(commonIndent)).join("\n");
}
const timestamp = () => +Date.now();
function batchInvoke(functions) {
functions.forEach((fn) => fn && fn());
}
function invoke(fn) {
return fn();
}
function tap(value, callback) {
callback(value);
return value;
}
function objectMap(obj, fn) {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) => fn(k, v)).filter(notNullish)
);
}
function isKeyOf(obj, k) {
return k in obj;
}
function objectKeys(obj) {
return Object.keys(obj);
}
function objectEntries(obj) {
return Object.entries(obj);
}
function deepMerge(target, ...sources) {
if (!sources.length)
return target;
const source = sources.shift();
if (source === void 0)
return target;
if (isMergableObject(target) && isMergableObject(source)) {
objectKeys(source).forEach((key) => {
if (key === "__proto__" || key === "constructor" || key === "prototype")
return;
if (isMergableObject(source[key])) {
if (!target[key])
target[key] = {};
if (isMergableObject(target[key])) {
deepMerge(target[key], source[key]);
} else {
target[key] = source[key];
}
} else {
target[key] = source[key];
}
});
}
return deepMerge(target, ...sources);
}
function deepMergeWithArray(target, ...sources) {
if (!sources.length)
return target;
const source = sources.shift();
if (source === void 0)
return target;
if (Array.isArray(target) && Array.isArray(source))
target.push(...source);
if (isMergableObject(target) && isMergableObject(source)) {
objectKeys(source).forEach((key) => {
if (key === "__proto__" || key === "constructor" || key === "prototype")
return;
if (Array.isArray(source[key])) {
if (!target[key])
target[key] = [];
deepMergeWithArray(target[key], source[key]);
} else if (isMergableObject(source[key])) {
if (!target[key])
target[key] = {};
deepMergeWithArray(target[key], source[key]);
} else {
target[key] = source[key];
}
});
}
return deepMergeWithArray(target, ...sources);
}
function isMergableObject(item) {
return isObject(item) && !Array.isArray(item);
}
function objectPick(obj, keys, omitUndefined = false) {
return keys.reduce((n, k) => {
if (k in obj) {
if (!omitUndefined || obj[k] !== void 0)
n[k] = obj[k];
}
return n;
}, {});
}
function clearUndefined(obj) {
Object.keys(obj).forEach((key) => obj[key] === void 0 ? delete obj[key] : {});
return obj;
}
function hasOwnProperty(obj, v) {
if (obj == null)
return false;
return Object.prototype.hasOwnProperty.call(obj, v);
}
function createSingletonPromise(fn) {
let _promise;
function wrapper() {
if (!_promise)
_promise = fn();
return _promise;
}
wrapper.reset = async () => {
const _prev = _promise;
_promise = void 0;
if (_prev)
await _prev;
};
return wrapper;
}
function sleep(ms, callback) {
return new Promise(
(resolve) => setTimeout(async () => {
await (callback == null ? void 0 : callback());
resolve();
}, ms)
);
}
function createPromiseLock() {
const locks = [];
return {
async run(fn) {
const p = fn();
locks.push(p);
try {
return await p;
} finally {
remove(locks, p);
}
},
async wait() {
await Promise.allSettled(locks);
},
isWaiting() {
return Boolean(locks.length);
},
clear() {
locks.length = 0;
}
};
}
function createControlledPromise() {
let resolve, reject;
const promise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
promise.resolve = resolve;
promise.reject = reject;
return promise;
}
/* eslint-disable no-undefined,no-param-reassign,no-shadow */
/**
* Throttle execution of a function. Especially useful for rate limiting
* execution of handlers on events like resize and scroll.
*
* @param {number} delay - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher)
* are most useful.
* @param {Function} callback - A function to be executed after delay milliseconds. The `this` context and all arguments are passed through,
* as-is, to `callback` when the throttled-function is executed.
* @param {object} [options] - An object to configure options.
* @param {boolean} [options.noTrailing] - Optional, defaults to false. If noTrailing is true, callback will only execute every `delay` milliseconds
* while the throttled-function is being called. If noTrailing is false or unspecified, callback will be executed
* one final time after the last throttled-function call. (After the throttled-function has not been called for
* `delay` milliseconds, the internal counter is reset).
* @param {boolean} [options.noLeading] - Optional, defaults to false. If noLeading is false, the first throttled-function call will execute callback
* immediately. If noLeading is true, the first the callback execution will be skipped. It should be noted that
* callback will never executed if both noLeading = true and noTrailing = true.
* @param {boolean} [options.debounceMode] - If `debounceMode` is true (at begin), schedule `clear` to execute after `delay` ms. If `debounceMode` is
* false (at end), schedule `callback` to execute after `delay` ms.
*
* @returns {Function} A new, throttled, function.
*/
function throttle (delay, callback, options) {
var _ref = options || {},
_ref$noTrailing = _ref.noTrailing,
noTrailing = _ref$noTrailing === void 0 ? false : _ref$noTrailing,
_ref$noLeading = _ref.noLeading,
noLeading = _ref$noLeading === void 0 ? false : _ref$noLeading,
_ref$debounceMode = _ref.debounceMode,
debounceMode = _ref$debounceMode === void 0 ? undefined : _ref$debounceMode;
/*
* After wrapper has stopped being called, this timeout ensures that
* `callback` is executed at the proper times in `throttle` and `end`
* debounce modes.
*/
var timeoutID;
var cancelled = false; // Keep track of the last time `callback` was executed.
var lastExec = 0; // Function to clear existing timeout
function clearExistingTimeout() {
if (timeoutID) {
clearTimeout(timeoutID);
}
} // Function to cancel next exec
function cancel(options) {
var _ref2 = options || {},
_ref2$upcomingOnly = _ref2.upcomingOnly,
upcomingOnly = _ref2$upcomingOnly === void 0 ? false : _ref2$upcomingOnly;
clearExistingTimeout();
cancelled = !upcomingOnly;
}
/*
* The `wrapper` function encapsulates all of the throttling / debouncing
* functionality and when executed will limit the rate at which `callback`
* is executed.
*/
function wrapper() {
for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) {
arguments_[_key] = arguments[_key];
}
var self = this;
var elapsed = Date.now() - lastExec;
if (cancelled) {
return;
} // Execute `callback` and update the `lastExec` timestamp.
function exec() {
lastExec = Date.now();
callback.apply(self, arguments_);
}
/*
* If `debounceMode` is true (at begin) this is used to clear the flag
* to allow future `callback` executions.
*/
function clear() {
timeoutID = undefined;
}
if (!noLeading && debounceMode && !timeoutID) {
/*
* Since `wrapper` is being called for the first time and
* `debounceMode` is true (at begin), execute `callback`
* and noLeading != true.
*/
exec();
}
clearExistingTimeout();
if (debounceMode === undefined && elapsed > delay) {
if (noLeading) {
/*
* In throttle mode with noLeading, if `delay` time has
* been exceeded, update `lastExec` and schedule `callback`
* to execute after `delay` ms.
*/
lastExec = Date.now();
if (!noTrailing) {
timeoutID = setTimeout(debounceMode ? clear : exec, delay);
}
} else {
/*
* In throttle mode without noLeading, if `delay` time has been exceeded, execute
* `callback`.
*/
exec();
}
} else if (noTrailing !== true) {
/*
* In trailing throttle mode, since `delay` time has not been
* exceeded, schedule `callback` to execute `delay` ms after most
* recent execution.
*
* If `debounceMode` is true (at begin), schedule `clear` to execute
* after `delay` ms.
*
* If `debounceMode` is false (at end), schedule `callback` to
* execute after `delay` ms.
*/
timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === undefined ? delay - elapsed : delay);
}
}
wrapper.cancel = cancel; // Return the wrapper function.
return wrapper;
}
/* eslint-disable no-undefined */
/**
* Debounce execution of a function. Debouncing, unlike throttling,
* guarantees that a function is only executed a single time, either at the
* very beginning of a series of calls, or at the very end.
*
* @param {number} delay - A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.
* @param {Function} callback - A function to be executed after delay milliseconds. The `this` context and all arguments are passed through, as-is,
* to `callback` when the debounced-function is executed.
* @param {object} [options] - An object to configure options.
* @param {boolean} [options.atBegin] - Optional, defaults to false. If atBegin is false or unspecified, callback will only be executed `delay` milliseconds
* after the last debounced-function call. If atBegin is true, callback will be executed only at the first debounced-function call.
* (After the throttled-function has not been called for `delay` milliseconds, the internal counter is reset).
*
* @returns {Function} A new, debounced function.
*/
function debounce (delay, callback, options) {
var _ref = options || {},
_ref$atBegin = _ref.atBegin,
atBegin = _ref$atBegin === void 0 ? false : _ref$atBegin;
return throttle(delay, callback, {
debounceMode: atBegin !== false
});
}
/*
How it works:
`this.#head` is an instance of `Node` which keeps track of its current value and nests another instance of `Node` that keeps the value that comes after it. When a value is provided to `.enqueue()`, the code needs to iterate through `this.#head`, going deeper and deeper to find the last value. However, iterating through every single item is slow. This problem is solved by saving a reference to the last value as `this.#tail` so that it can reference it to add a new value.
*/
class Node {
value;
next;
constructor(value) {
this.value = value;
}
}
class Queue {
#head;
#tail;
#size;
constructor() {
this.clear();
}
enqueue(value) {
const node = new Node(value);
if (this.#head) {
this.#tail.next = node;
this.#tail = node;
} else {
this.#head = node;
this.#tail = node;
}
this.#size++;
}
dequeue() {
const current = this.#head;
if (!current) {
return;
}
this.#head = this.#head.next;
this.#size--;
return current.value;
}
clear() {
this.#head = undefined;
this.#tail = undefined;
this.#size = 0;
}
get size() {
return this.#size;
}
* [Symbol.iterator]() {
let current = this.#head;
while (current) {
yield current.value;
current = current.next;
}
}
}
const AsyncResource = {
bind(fn, _type, thisArg) {
return fn.bind(thisArg);
},
};
function pLimit(concurrency) {
if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
throw new TypeError('Expected `concurrency` to be a number from 1 and up');
}
const queue = new Queue();
let activeCount = 0;
const next = () => {
activeCount--;
if (queue.size > 0) {
queue.dequeue()();
}
};
const run = async (function_, resolve, arguments_) => {
activeCount++;
const result = (async () => function_(...arguments_))();
resolve(result);
try {
await result;
} catch {}
next();
};
const enqueue = (function_, resolve, arguments_) => {
queue.enqueue(
AsyncResource.bind(run.bind(undefined, function_, resolve, arguments_)),
);
(async () => {
// This function needs to wait until the next microtask before comparing
// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
// when the run function is dequeued and called. The comparison in the if-statement
// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
await Promise.resolve();
if (activeCount < concurrency && queue.size > 0) {
queue.dequeue()();
}
})();
};
const generator = (function_, ...arguments_) => new Promise(resolve => {
enqueue(function_, resolve, arguments_);
});
Object.defineProperties(generator, {
activeCount: {
get: () => activeCount,
},
pendingCount: {
get: () => queue.size,
},
clearQueue: {
value() {
queue.clear();
},
},
});
return generator;
}
const VOID = Symbol("p-void");
class PInstance extends Promise {
constructor(items = [], options) {
super(() => {
});
this.items = items;
this.options = options;
this.promises = /* @__PURE__ */ new Set();
}
get promise() {
var _a;
let batch;
const items = [...Array.from(this.items), ...Array.from(this.promises)];
if ((_a = this.options) == null ? void 0 : _a.concurrency) {
const limit = pLimit(this.options.concurrency);
batch = Promise.all(items.map((p2) => limit(() => p2)));
} else {
batch = Promise.all(items);
}
return batch.then((l) => l.filter((i) => i !== VOID));
}
add(...args) {
args.forEach((i) => {
this.promises.add(i);
});
}
map(fn) {
return new PInstance(
Array.from(this.items).map(async (i, idx) => {
const v = await i;
if (v === VOID)
return VOID;
return fn(v, idx);
}),
this.options
);
}
filter(fn) {
return new PInstance(
Array.from(this.items).map(async (i, idx) => {
const v = await i;
const r = await fn(v, idx);
if (!r)
return VOID;
return v;
}),
this.options
);
}
forEach(fn) {
return this.map(fn).then();
}
reduce(fn, initialValue) {
return this.promise.then((array) => array.reduce(fn, initialValue));
}
clear() {
this.promises.clear();
}
then(fn) {
const p2 = this.promise;
if (fn)
return p2.then(fn);
else
return p2;
}
catch(fn) {
return this.promise.catch(fn);
}
finally(fn) {
return this.promise.finally(fn);
}
}
function p(items, options) {
return new PInstance(items, options);
}
export { assert, at, batchInvoke, capitalize, clamp, clampArrayRange, clearUndefined, createControlledPromise, createPromiseLock, createSingletonPromise, debounce, deepMerge, deepMergeWithArray, ensurePrefix, ensureSuffix, flattenArrayable, getTypeName, hasOwnProperty, invoke, isBoolean, isBrowser, isDate, isDeepEqual, isDef, isFunction, isKeyOf, isNull, isNumber, isObject, isRegExp, isString, isTruthy, isUndefined, isWindow, last, lerp, mergeArrayable, move, noNull, noop, notNullish, notUndefined, objectEntries, objectKeys, objectMap, objectPick, p, partition, randomStr, range, remap, remove, sample, shuffle, slash, sleep, sum, tap, template, throttle, timestamp, toArray, toString, unindent, uniq, uniqueBy };
+67
View File
@@ -0,0 +1,67 @@
{
"name": "@antfu/utils",
"type": "module",
"version": "0.7.10",
"packageManager": "pnpm@9.1.0",
"description": "Opinionated collection of common JavaScript / TypeScript utils by @antfu",
"author": "Anthony Fu <anthonyfu117@hotmail.com>",
"license": "MIT",
"funding": "https://github.com/sponsors/antfu",
"homepage": "https://github.com/antfu/utils#readme",
"repository": {
"type": "git",
"url": "git+https://github.com/antfu/utils.git"
},
"bugs": {
"url": "https://github.com/antfu/utils/issues"
},
"keywords": [
"utils"
],
"sideEffects": false,
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
}
},
"main": "dist/index.cjs",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "rollup -c",
"dev": "nr build --watch",
"lint": "eslint .",
"lint-fix": "nr lint --fix",
"prepublishOnly": "npm run build",
"release": "bumpp --commit --push --tag && npm publish",
"start": "esno src/index.ts",
"typecheck": "tsc --noEmit",
"test": "vitest"
},
"devDependencies": {
"@antfu/eslint-config": "^2.16.3",
"@antfu/ni": "^0.21.12",
"@rollup/plugin-alias": "^5.1.0",
"@rollup/plugin-commonjs": "^25.0.7",
"@rollup/plugin-json": "^6.1.0",
"@rollup/plugin-node-resolve": "^15.2.3",
"@types/node": "^20.12.10",
"@types/throttle-debounce": "^5.0.2",
"bumpp": "^9.4.1",
"eslint": "npm:eslint-ts-patch@8.55.0-1",
"eslint-ts-patch": "8.55.0-1",
"esno": "^4.7.0",
"p-limit": "^5.0.0",
"rollup": "^4.17.2",
"rollup-plugin-dts": "^6.1.0",
"rollup-plugin-esbuild": "^6.1.1",
"throttle-debounce": "5.0.0",
"typescript": "^5.4.5",
"vite": "^5.2.11",
"vitest": "^1.6.0"
}
}
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
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.
+19
View File
@@ -0,0 +1,19 @@
# @babel/code-frame
> Generate errors that contain a code frame that point to source locations.
See our website [@babel/code-frame](https://babeljs.io/docs/babel-code-frame) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/code-frame
```
or using yarn:
```sh
yarn add @babel/code-frame --dev
```
+216
View File
@@ -0,0 +1,216 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var picocolors = require('picocolors');
var jsTokens = require('js-tokens');
var helperValidatorIdentifier = require('@babel/helper-validator-identifier');
function isColorSupported() {
return (typeof process === "object" && (process.env.FORCE_COLOR === "0" || process.env.FORCE_COLOR === "false") ? false : picocolors.isColorSupported
);
}
const compose = (f, g) => v => f(g(v));
function buildDefs(colors) {
return {
keyword: colors.cyan,
capitalized: colors.yellow,
jsxIdentifier: colors.yellow,
punctuator: colors.yellow,
number: colors.magenta,
string: colors.green,
regex: colors.magenta,
comment: colors.gray,
invalid: compose(compose(colors.white, colors.bgRed), colors.bold),
gutter: colors.gray,
marker: compose(colors.red, colors.bold),
message: compose(colors.red, colors.bold),
reset: colors.reset
};
}
const defsOn = buildDefs(picocolors.createColors(true));
const defsOff = buildDefs(picocolors.createColors(false));
function getDefs(enabled) {
return enabled ? defsOn : defsOff;
}
const sometimesKeywords = new Set(["as", "async", "from", "get", "of", "set"]);
const NEWLINE$1 = /\r\n|[\n\r\u2028\u2029]/;
const BRACKET = /^[()[\]{}]$/;
let tokenize;
{
const JSX_TAG = /^[a-z][\w-]*$/i;
const getTokenType = function (token, offset, text) {
if (token.type === "name") {
if (helperValidatorIdentifier.isKeyword(token.value) || helperValidatorIdentifier.isStrictReservedWord(token.value, true) || sometimesKeywords.has(token.value)) {
return "keyword";
}
if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.slice(offset - 2, offset) === "</")) {
return "jsxIdentifier";
}
if (token.value[0] !== token.value[0].toLowerCase()) {
return "capitalized";
}
}
if (token.type === "punctuator" && BRACKET.test(token.value)) {
return "bracket";
}
if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
return "punctuator";
}
return token.type;
};
tokenize = function* (text) {
let match;
while (match = jsTokens.default.exec(text)) {
const token = jsTokens.matchToToken(match);
yield {
type: getTokenType(token, match.index, text),
value: token.value
};
}
};
}
function highlight(text) {
if (text === "") return "";
const defs = getDefs(true);
let highlighted = "";
for (const {
type,
value
} of tokenize(text)) {
if (type in defs) {
highlighted += value.split(NEWLINE$1).map(str => defs[type](str)).join("\n");
} else {
highlighted += value;
}
}
return highlighted;
}
let deprecationWarningShown = false;
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
function getMarkerLines(loc, source, opts) {
const startLoc = Object.assign({
column: 0,
line: -1
}, loc.start);
const endLoc = Object.assign({}, startLoc, loc.end);
const {
linesAbove = 2,
linesBelow = 3
} = opts || {};
const startLine = startLoc.line;
const startColumn = startLoc.column;
const endLine = endLoc.line;
const endColumn = endLoc.column;
let start = Math.max(startLine - (linesAbove + 1), 0);
let end = Math.min(source.length, endLine + linesBelow);
if (startLine === -1) {
start = 0;
}
if (endLine === -1) {
end = source.length;
}
const lineDiff = endLine - startLine;
const markerLines = {};
if (lineDiff) {
for (let i = 0; i <= lineDiff; i++) {
const lineNumber = i + startLine;
if (!startColumn) {
markerLines[lineNumber] = true;
} else if (i === 0) {
const sourceLength = source[lineNumber - 1].length;
markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
} else if (i === lineDiff) {
markerLines[lineNumber] = [0, endColumn];
} else {
const sourceLength = source[lineNumber - i].length;
markerLines[lineNumber] = [0, sourceLength];
}
}
} else {
if (startColumn === endColumn) {
if (startColumn) {
markerLines[startLine] = [startColumn, 0];
} else {
markerLines[startLine] = true;
}
} else {
markerLines[startLine] = [startColumn, endColumn - startColumn];
}
}
return {
start,
end,
markerLines
};
}
function codeFrameColumns(rawLines, loc, opts = {}) {
const shouldHighlight = opts.forceColor || isColorSupported() && opts.highlightCode;
const defs = getDefs(shouldHighlight);
const lines = rawLines.split(NEWLINE);
const {
start,
end,
markerLines
} = getMarkerLines(loc, lines, opts);
const hasColumns = loc.start && typeof loc.start.column === "number";
const numberMaxWidth = String(end).length;
const highlightedLines = shouldHighlight ? highlight(rawLines) : rawLines;
let frame = highlightedLines.split(NEWLINE, end).slice(start, end).map((line, index) => {
const number = start + 1 + index;
const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
const gutter = ` ${paddedNumber} |`;
const hasMarker = markerLines[number];
const lastMarkerLine = !markerLines[number + 1];
if (hasMarker) {
let markerLine = "";
if (Array.isArray(hasMarker)) {
const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
const numberOfMarkers = hasMarker[1] || 1;
markerLine = ["\n ", defs.gutter(gutter.replace(/\d/g, " ")), " ", markerSpacing, defs.marker("^").repeat(numberOfMarkers)].join("");
if (lastMarkerLine && opts.message) {
markerLine += " " + defs.message(opts.message);
}
}
return [defs.marker(">"), defs.gutter(gutter), line.length > 0 ? ` ${line}` : "", markerLine].join("");
} else {
return ` ${defs.gutter(gutter)}${line.length > 0 ? ` ${line}` : ""}`;
}
}).join("\n");
if (opts.message && !hasColumns) {
frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
}
if (shouldHighlight) {
return defs.reset(frame);
} else {
return frame;
}
}
function index (rawLines, lineNumber, colNumber, opts = {}) {
if (!deprecationWarningShown) {
deprecationWarningShown = true;
const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
if (process.emitWarning) {
process.emitWarning(message, "DeprecationWarning");
} else {
const deprecationError = new Error(message);
deprecationError.name = "DeprecationWarning";
console.warn(new Error(message));
}
}
colNumber = Math.max(colNumber, 0);
const location = {
start: {
column: colNumber,
line: lineNumber
}
};
return codeFrameColumns(rawLines, location, opts);
}
exports.codeFrameColumns = codeFrameColumns;
exports.default = index;
exports.highlight = highlight;
//# sourceMappingURL=index.js.map
File diff suppressed because one or more lines are too long
+31
View File
@@ -0,0 +1,31 @@
{
"name": "@babel/code-frame",
"version": "7.26.2",
"description": "Generate errors that contain a code frame that point to source locations.",
"author": "The Babel Team (https://babel.dev/team)",
"homepage": "https://babel.dev/docs/en/next/babel-code-frame",
"bugs": "https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel.git",
"directory": "packages/babel-code-frame"
},
"main": "./lib/index.js",
"dependencies": {
"@babel/helper-validator-identifier": "^7.25.9",
"js-tokens": "^4.0.0",
"picocolors": "^1.0.0"
},
"devDependencies": {
"import-meta-resolve": "^4.1.0",
"strip-ansi": "^4.0.0"
},
"engines": {
"node": ">=6.9.0"
},
"type": "commonjs"
}
+22
View File
@@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
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.
+19
View File
@@ -0,0 +1,19 @@
# @babel/compat-data
> The compat-data to determine required Babel plugins
See our website [@babel/compat-data](https://babeljs.io/docs/babel-compat-data) for more information.
## Install
Using npm:
```sh
npm install --save @babel/compat-data
```
or using yarn:
```sh
yarn add @babel/compat-data
```
+2
View File
@@ -0,0 +1,2 @@
// Todo (Babel 8): remove this file as Babel 8 drop support of core-js 2
module.exports = require("./data/corejs2-built-ins.json");
@@ -0,0 +1,2 @@
// Todo (Babel 8): remove this file now that it is included in babel-plugin-polyfill-corejs3
module.exports = require("./data/corejs3-shipped-proposals.json");
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,5 @@
[
"esnext.promise.all-settled",
"esnext.string.match-all",
"esnext.global-this"
]
+18
View File
@@ -0,0 +1,18 @@
{
"es6.module": {
"chrome": "61",
"and_chr": "61",
"edge": "16",
"firefox": "60",
"and_ff": "60",
"node": "13.2.0",
"opera": "48",
"op_mob": "45",
"safari": "10.1",
"ios": "10.3",
"samsung": "8.2",
"android": "61",
"electron": "2.0",
"ios_saf": "10.3"
}
}

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