From a5eff395b462ae5cdff77895d668740f61bbb4cc Mon Sep 17 00:00:00 2001 From: Gani Georgiev Date: Fri, 15 Mar 2024 11:43:27 +0200 Subject: [PATCH] [#4566] fixed JSVM routerUse() example --- .../jsvm/internal/types/generated/types.d.ts | 11618 ++++++++-------- plugins/jsvm/internal/types/types.go | 2 +- 2 files changed, 5854 insertions(+), 5766 deletions(-) diff --git a/plugins/jsvm/internal/types/generated/types.d.ts b/plugins/jsvm/internal/types/generated/types.d.ts index 33349ad4d..7b513e7fa 100644 --- a/plugins/jsvm/internal/types/generated/types.d.ts +++ b/plugins/jsvm/internal/types/generated/types.d.ts @@ -1,4 +1,4 @@ -// 1710271905 +// 1710495869 // GENERATED CODE - DO NOT MODIFY BY HAND // ------------------------------------------------------------------- @@ -80,7 +80,7 @@ declare function routerAdd( * ```js * routerUse((next) => { * return (c) => { - * console.log(c.Path()) + * console.log(c.path()) * return next(c) * } * }) @@ -1662,18 +1662,25 @@ namespace os { readFrom(r: io.Reader): number } /** - * fileWithoutReadFrom implements all the methods of *File other - * than ReadFrom. This is used to permit ReadFrom to call io.Copy - * without leading to a recursive call to ReadFrom. + * noReadFrom can be embedded alongside another type to + * hide the ReadFrom method of that other type. */ - type _subRIcVQ = File - interface fileWithoutReadFrom extends _subRIcVQ { + interface noReadFrom { } - interface fileWithoutReadFrom { + interface noReadFrom { /** - * This ReadFrom method hides the *File ReadFrom method. + * ReadFrom hides another ReadFrom method. + * It should never be called. */ - readFrom(_arg0: fileWithoutReadFrom): void + readFrom(_arg0: io.Reader): number + } + /** + * fileWithoutReadFrom implements all the methods of *File other + * than ReadFrom. This is used to permit ReadFrom to call io.Copy + * without leading to a recursive call to ReadFrom. + */ + type _subDWinF = noReadFrom&File + interface fileWithoutReadFrom extends _subDWinF { } interface File { /** @@ -1693,6 +1700,33 @@ namespace os { */ writeAt(b: string|Array, off: number): number } + interface File { + /** + * WriteTo implements io.WriterTo. + */ + writeTo(w: io.Writer): number + } + /** + * noWriteTo can be embedded alongside another type to + * hide the WriteTo method of that other type. + */ + interface noWriteTo { + } + interface noWriteTo { + /** + * WriteTo hides another WriteTo method. + * It should never be called. + */ + writeTo(_arg0: io.Writer): number + } + /** + * fileWithoutWriteTo implements all the methods of *File other + * than WriteTo. This is used to permit WriteTo to call io.Copy + * without leading to a recursive call to WriteTo. + */ + type _subdqHeU = noWriteTo&File + interface fileWithoutWriteTo extends _subdqHeU { + } interface File { /** * Seek sets the offset for the next Read or Write on file to offset, interpreted @@ -1765,6 +1799,16 @@ namespace os { */ (oldpath: string, newpath: string): void } + interface readlink { + /** + * Readlink returns the destination of the named symbolic link. + * If there is an error, it will be of type *PathError. + * + * If the link destination is relative, Readlink returns the relative path + * without resolving it to an absolute one. + */ + (name: string): string + } interface tempDir { /** * TempDir returns the default directory to use for temporary files. @@ -2128,13 +2172,6 @@ namespace os { */ (oldname: string, newname: string): void } - interface readlink { - /** - * Readlink returns the destination of the named symbolic link. - * If there is an error, it will be of type *PathError. - */ - (name: string): string - } interface unixDirent { } interface unixDirent { @@ -2274,6 +2311,10 @@ namespace os { * If the file is a symbolic link, the returned FileInfo * describes the symbolic link. Lstat makes no attempt to follow the link. * If there is an error, it will be of type *PathError. + * + * On Windows, if the file is a reparse point that is a surrogate for another + * named entity (such as a symbolic link or mounted folder), the returned + * FileInfo describes the reparse point, and makes no attempt to resolve it. */ (name: string): FileInfo } @@ -2324,8 +2365,8 @@ namespace os { /** * File represents an open file descriptor. */ - type _subMfvEV = file - interface File extends _subMfvEV { + type _subxbGPe = file + interface File extends _subxbGPe { } /** * A FileInfo describes a file and is returned by Stat and Lstat. @@ -2408,7 +2449,7 @@ namespace filepath { * ``` * * Match requires pattern to match all of name, not just a substring. - * The only possible returned error is ErrBadPattern, when pattern + * The only possible returned error is [ErrBadPattern], when pattern * is malformed. * * On Windows, escaping is disabled. Instead, '\\' is treated as @@ -2420,11 +2461,11 @@ namespace filepath { /** * Glob returns the names of all files matching pattern or nil * if there is no matching file. The syntax of patterns is the same - * as in Match. The pattern may describe hierarchical names such as - * /usr/*\/bin/ed (assuming the Separator is '/'). + * as in [Match]. The pattern may describe hierarchical names such as + * /usr/*\/bin/ed (assuming the [Separator] is '/'). * * Glob ignores file system errors such as I/O errors reading directories. - * The only possible returned error is ErrBadPattern, when pattern + * The only possible returned error is [ErrBadPattern], when pattern * is malformed. */ (pattern: string): Array @@ -2443,7 +2484,7 @@ namespace filepath { * by purely lexical processing. It applies the following rules * iteratively until no further processing can be done: * - * 1. Replace multiple Separator elements with a single one. + * 1. Replace multiple [Separator] elements with a single one. * 2. Eliminate each . path name element (the current directory). * 3. Eliminate each inner .. path name element (the parent directory) * ``` @@ -2512,7 +2553,7 @@ namespace filepath { } interface splitList { /** - * SplitList splits a list of paths joined by the OS-specific ListSeparator, + * SplitList splits a list of paths joined by the OS-specific [ListSeparator], * usually found in PATH or GOPATH environment variables. * Unlike strings.Split, SplitList returns an empty slice when passed an empty * string. @@ -2521,7 +2562,7 @@ namespace filepath { } interface split { /** - * Split splits path immediately following the final Separator, + * Split splits path immediately following the final [Separator], * separating it into a directory and file name component. * If there is no Separator in path, Split returns an empty dir * and file set to path. @@ -2532,7 +2573,7 @@ namespace filepath { interface join { /** * Join joins any number of path elements into a single path, - * separating them with an OS specific Separator. Empty elements + * separating them with an OS specific [Separator]. Empty elements * are ignored. The result is Cleaned. However, if the argument * list is empty or all its elements are empty, Join returns * an empty string. @@ -2556,7 +2597,7 @@ namespace filepath { * links. * If path is relative the result will be relative to the current directory, * unless one of the components is an absolute symbolic link. - * EvalSymlinks calls Clean on the result. + * EvalSymlinks calls [Clean] on the result. */ (path: string): string } @@ -2566,7 +2607,7 @@ namespace filepath { * If the path is not absolute it will be joined with the current * working directory to turn it into an absolute path. The absolute * path name for a given file is not guaranteed to be unique. - * Abs calls Clean on the result. + * Abs calls [Clean] on the result. */ (path: string): string } @@ -2574,17 +2615,17 @@ namespace filepath { /** * Rel returns a relative path that is lexically equivalent to targpath when * joined to basepath with an intervening separator. That is, - * Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself. + * [Join](basepath, Rel(basepath, targpath)) is equivalent to targpath itself. * On success, the returned path will always be relative to basepath, * even if basepath and targpath share no elements. * An error is returned if targpath can't be made relative to basepath or if * knowing the current working directory would be necessary to compute it. - * Rel calls Clean on the result. + * Rel calls [Clean] on the result. */ (basepath: string, targpath: string): string } /** - * WalkFunc is the type of the function called by Walk to visit each + * WalkFunc is the type of the function called by [Walk] to visit each * file or directory. * * The path argument contains the argument to Walk as a prefix. @@ -2600,9 +2641,9 @@ namespace filepath { * The info argument is the fs.FileInfo for the named path. * * The error result returned by the function controls how Walk continues. - * If the function returns the special value SkipDir, Walk skips the + * If the function returns the special value [SkipDir], Walk skips the * current directory (path if info.IsDir() is true, otherwise path's - * parent directory). If the function returns the special value SkipAll, + * parent directory). If the function returns the special value [SkipAll], * Walk skips all remaining files and directories. Otherwise, if the function * returns a non-nil error, Walk stops entirely and returns that error. * @@ -2613,14 +2654,14 @@ namespace filepath { * * Walk calls the function with a non-nil err argument in two cases. * - * First, if an os.Lstat on the root directory or any directory or file + * First, if an [os.Lstat] on the root directory or any directory or file * in the tree fails, Walk calls the function with path set to that * directory or file's path, info set to nil, and err set to the error * from os.Lstat. * * Second, if a directory's Readdirnames method fails, Walk calls the * function with path set to the directory's path, info, set to an - * fs.FileInfo describing the directory, and err set to the error from + * [fs.FileInfo] describing the directory, and err set to the error from * Readdirnames. */ interface WalkFunc {(path: string, info: fs.FileInfo, err: Error): void } @@ -2630,7 +2671,7 @@ namespace filepath { * directory in the tree, including root. * * All errors that arise visiting files and directories are filtered by fn: - * see the fs.WalkDirFunc documentation for details. + * see the [fs.WalkDirFunc] documentation for details. * * The files are walked in lexical order, which makes the output deterministic * but requires WalkDir to read an entire directory into memory before proceeding @@ -2644,30 +2685,13 @@ namespace filepath { */ (root: string, fn: fs.WalkDirFunc): void } - interface statDirEntry { - } - interface statDirEntry { - name(): string - } - interface statDirEntry { - isDir(): boolean - } - interface statDirEntry { - type(): fs.FileMode - } - interface statDirEntry { - info(): fs.FileInfo - } - interface statDirEntry { - string(): string - } interface walk { /** * Walk walks the file tree rooted at root, calling fn for each file or * directory in the tree, including root. * * All errors that arise visiting files and directories are filtered by fn: - * see the WalkFunc documentation for details. + * see the [WalkFunc] documentation for details. * * The files are walked in lexical order, which makes the output deterministic * but requires Walk to read an entire directory into memory before proceeding @@ -2675,7 +2699,7 @@ namespace filepath { * * Walk does not follow symbolic links. * - * Walk is less efficient than WalkDir, introduced in Go 1.16, + * Walk is less efficient than [WalkDir], introduced in Go 1.16, * which avoids calling os.Lstat on every visited file or directory. */ (root: string, fn: WalkFunc): void @@ -2692,7 +2716,7 @@ namespace filepath { interface dir { /** * Dir returns all but the last element of path, typically the path's directory. - * After dropping the final element, Dir calls Clean on the path and trailing + * After dropping the final element, Dir calls [Clean] on the path and trailing * slashes are removed. * If the path is empty, Dir returns ".". * If the path consists entirely of separators, Dir returns a single separator. @@ -2726,441 +2750,60 @@ namespace filepath { } } -/** - * Package template is a thin wrapper around the standard html/template - * and text/template packages that implements a convenient registry to - * load and cache templates on the fly concurrently. - * - * It was created to assist the JSVM plugin HTML rendering, but could be used in other Go code. - * - * Example: - * - * ``` - * registry := template.NewRegistry() - * - * html1, err := registry.LoadFiles( - * // the files set wil be parsed only once and then cached - * "layout.html", - * "content.html", - * ).Render(map[string]any{"name": "John"}) - * - * html2, err := registry.LoadFiles( - * // reuse the already parsed and cached files set - * "layout.html", - * "content.html", - * ).Render(map[string]any{"name": "Jane"}) - * ``` - */ -namespace template { - interface newRegistry { +namespace middleware { + interface bodyLimit { /** - * NewRegistry creates and initializes a new templates registry with - * some defaults (eg. global "raw" template function for unescaped HTML). + * BodyLimit returns a BodyLimit middleware. * - * Use the Registry.Load* methods to load templates into the registry. + * BodyLimit middleware sets the maximum allowed size for a request body, if the size exceeds the configured limit, it + * sends "413 - Request Entity Too Large" response. The BodyLimit is determined based on both `Content-Length` request + * header and actual content read, which makes it super secure. */ - (): (Registry) + (limitBytes: number): echo.MiddlewareFunc + } + interface gzip { + /** + * Gzip returns a middleware which compresses HTTP response using gzip compression scheme. + */ + (): echo.MiddlewareFunc } +} + +/** + * Package dbx provides a set of DB-agnostic and easy-to-use query building methods for relational databases. + */ +namespace dbx { /** - * Registry defines a templates registry that is safe to be used by multiple goroutines. - * - * Use the Registry.Load* methods to load templates into the registry. + * Builder supports building SQL statements in a DB-agnostic way. + * Builder mainly provides two sets of query building methods: those building SELECT statements + * and those manipulating DB data or schema (e.g. INSERT statements, CREATE TABLE statements). */ - interface Registry { - } - interface Registry { + interface Builder { + [key:string]: any; /** - * AddFuncs registers new global template functions. - * - * The key of each map entry is the function name that will be used in the templates. - * If a function with the map entry name already exists it will be replaced with the new one. - * - * The value of each map entry is a function that must have either a - * single return value, or two return values of which the second has type error. - * - * Example: - * - * r.AddFuncs(map[string]any{ - * ``` - * "toUpper": func(str string) string { - * return strings.ToUppser(str) - * }, - * ... - * ``` - * }) + * NewQuery creates a new Query object with the given SQL statement. + * The SQL statement may contain parameter placeholders which can be bound with actual parameter + * values before the statement is executed. */ - addFuncs(funcs: _TygojaDict): (Registry) - } - interface Registry { + newQuery(_arg0: string): (Query) /** - * LoadFiles caches (if not already) the specified filenames set as a - * single template and returns a ready to use Renderer instance. - * - * There must be at least 1 filename specified. + * Select returns a new SelectQuery object that can be used to build a SELECT statement. + * The parameters to this method should be the list column names to be selected. + * A column name may have an optional alias name. For example, Select("id", "my_name AS name"). */ - loadFiles(...filenames: string[]): (Renderer) - } - interface Registry { + select(..._arg0: string[]): (SelectQuery) /** - * LoadString caches (if not already) the specified inline string as a - * single template and returns a ready to use Renderer instance. + * ModelQuery returns a new ModelQuery object that can be used to perform model insertion, update, and deletion. + * The parameter to this method should be a pointer to the model struct that needs to be inserted, updated, or deleted. */ - loadString(text: string): (Renderer) - } - interface Registry { + model(_arg0: { + }): (ModelQuery) /** - * LoadFS caches (if not already) the specified fs and globPatterns - * pair as single template and returns a ready to use Renderer instance. - * - * There must be at least 1 file matching the provided globPattern(s) - * (note that most file names serves as glob patterns matching themselves). + * GeneratePlaceholder generates an anonymous parameter placeholder with the given parameter ID. */ - loadFS(fsys: fs.FS, ...globPatterns: string[]): (Renderer) - } - /** - * Renderer defines a single parsed template. - */ - interface Renderer { - } - interface Renderer { + generatePlaceholder(_arg0: number): string /** - * Render executes the template with the specified data as the dot object - * and returns the result as plain string. - */ - render(data: any): string - } -} - -/** - * Package exec runs external commands. It wraps os.StartProcess to make it - * easier to remap stdin and stdout, connect I/O with pipes, and do other - * adjustments. - * - * Unlike the "system" library call from C and other languages, the - * os/exec package intentionally does not invoke the system shell and - * does not expand any glob patterns or handle other expansions, - * pipelines, or redirections typically done by shells. The package - * behaves more like C's "exec" family of functions. To expand glob - * patterns, either call the shell directly, taking care to escape any - * dangerous input, or use the path/filepath package's Glob function. - * To expand environment variables, use package os's ExpandEnv. - * - * Note that the examples in this package assume a Unix system. - * They may not run on Windows, and they do not run in the Go Playground - * used by golang.org and godoc.org. - * - * # Executables in the current directory - * - * The functions Command and LookPath look for a program - * in the directories listed in the current path, following the - * conventions of the host operating system. - * Operating systems have for decades included the current - * directory in this search, sometimes implicitly and sometimes - * configured explicitly that way by default. - * Modern practice is that including the current directory - * is usually unexpected and often leads to security problems. - * - * To avoid those security problems, as of Go 1.19, this package will not resolve a program - * using an implicit or explicit path entry relative to the current directory. - * That is, if you run exec.LookPath("go"), it will not successfully return - * ./go on Unix nor .\go.exe on Windows, no matter how the path is configured. - * Instead, if the usual path algorithms would result in that answer, - * these functions return an error err satisfying errors.Is(err, ErrDot). - * - * For example, consider these two program snippets: - * - * ``` - * path, err := exec.LookPath("prog") - * if err != nil { - * log.Fatal(err) - * } - * use(path) - * ``` - * - * and - * - * ``` - * cmd := exec.Command("prog") - * if err := cmd.Run(); err != nil { - * log.Fatal(err) - * } - * ``` - * - * These will not find and run ./prog or .\prog.exe, - * no matter how the current path is configured. - * - * Code that always wants to run a program from the current directory - * can be rewritten to say "./prog" instead of "prog". - * - * Code that insists on including results from relative path entries - * can instead override the error using an errors.Is check: - * - * ``` - * path, err := exec.LookPath("prog") - * if errors.Is(err, exec.ErrDot) { - * err = nil - * } - * if err != nil { - * log.Fatal(err) - * } - * use(path) - * ``` - * - * and - * - * ``` - * cmd := exec.Command("prog") - * if errors.Is(cmd.Err, exec.ErrDot) { - * cmd.Err = nil - * } - * if err := cmd.Run(); err != nil { - * log.Fatal(err) - * } - * ``` - * - * Setting the environment variable GODEBUG=execerrdot=0 - * disables generation of ErrDot entirely, temporarily restoring the pre-Go 1.19 - * behavior for programs that are unable to apply more targeted fixes. - * A future version of Go may remove support for this variable. - * - * Before adding such overrides, make sure you understand the - * security implications of doing so. - * See https://go.dev/blog/path-security for more information. - */ -namespace exec { - interface command { - /** - * Command returns the Cmd struct to execute the named program with - * the given arguments. - * - * It sets only the Path and Args in the returned structure. - * - * If name contains no path separators, Command uses LookPath to - * resolve name to a complete path if possible. Otherwise it uses name - * directly as Path. - * - * The returned Cmd's Args field is constructed from the command name - * followed by the elements of arg, so arg should not include the - * command name itself. For example, Command("echo", "hello"). - * Args[0] is always name, not the possibly resolved Path. - * - * On Windows, processes receive the whole command line as a single string - * and do their own parsing. Command combines and quotes Args into a command - * line string with an algorithm compatible with applications using - * CommandLineToArgvW (which is the most common way). Notable exceptions are - * msiexec.exe and cmd.exe (and thus, all batch files), which have a different - * unquoting algorithm. In these or other similar cases, you can do the - * quoting yourself and provide the full command line in SysProcAttr.CmdLine, - * leaving Args empty. - */ - (name: string, ...arg: string[]): (Cmd) - } -} - -namespace security { - interface s256Challenge { - /** - * S256Challenge creates base64 encoded sha256 challenge string derived from code. - * The padding of the result base64 string is stripped per [RFC 7636]. - * - * [RFC 7636]: https://datatracker.ietf.org/doc/html/rfc7636#section-4.2 - */ - (code: string): string - } - interface md5 { - /** - * MD5 creates md5 hash from the provided plain text. - */ - (text: string): string - } - interface sha256 { - /** - * SHA256 creates sha256 hash as defined in FIPS 180-4 from the provided text. - */ - (text: string): string - } - interface sha512 { - /** - * SHA512 creates sha512 hash as defined in FIPS 180-4 from the provided text. - */ - (text: string): string - } - interface hs256 { - /** - * HS256 creates a HMAC hash with sha256 digest algorithm. - */ - (text: string, secret: string): string - } - interface hs512 { - /** - * HS512 creates a HMAC hash with sha512 digest algorithm. - */ - (text: string, secret: string): string - } - interface equal { - /** - * Equal compares two hash strings for equality without leaking timing information. - */ - (hash1: string, hash2: string): boolean - } - // @ts-ignore - import crand = rand - interface encrypt { - /** - * Encrypt encrypts data with key (must be valid 32 char aes key). - */ - (data: string|Array, key: string): string - } - interface decrypt { - /** - * Decrypt decrypts encrypted text with key (must be valid 32 chars aes key). - */ - (cipherText: string, key: string): string|Array - } - interface parseUnverifiedJWT { - /** - * ParseUnverifiedJWT parses JWT and returns its claims - * but DOES NOT verify the signature. - * - * It verifies only the exp, iat and nbf claims. - */ - (token: string): jwt.MapClaims - } - interface parseJWT { - /** - * ParseJWT verifies and parses JWT and returns its claims. - */ - (token: string, verificationKey: string): jwt.MapClaims - } - interface newJWT { - /** - * NewJWT generates and returns new HS256 signed JWT. - */ - (payload: jwt.MapClaims, signingKey: string, secondsDuration: number): string - } - interface newToken { - /** - * Deprecated: - * Consider replacing with NewJWT(). - * - * NewToken is a legacy alias for NewJWT that generates a HS256 signed JWT. - */ - (payload: jwt.MapClaims, signingKey: string, secondsDuration: number): string - } - // @ts-ignore - import cryptoRand = rand - // @ts-ignore - import mathRand = rand - interface randomString { - /** - * RandomString generates a cryptographically random string with the specified length. - * - * The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding. - */ - (length: number): string - } - interface randomStringWithAlphabet { - /** - * RandomStringWithAlphabet generates a cryptographically random string - * with the specified length and characters set. - * - * It panics if for some reason rand.Int returns a non-nil error. - */ - (length: number, alphabet: string): string - } - interface pseudorandomString { - /** - * PseudorandomString generates a pseudorandom string with the specified length. - * - * The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding. - * - * For a cryptographically random string (but a little bit slower) use RandomString instead. - */ - (length: number): string - } - interface pseudorandomStringWithAlphabet { - /** - * PseudorandomStringWithAlphabet generates a pseudorandom string - * with the specified length and characters set. - * - * For a cryptographically random (but a little bit slower) use RandomStringWithAlphabet instead. - */ - (length: number, alphabet: string): string - } -} - -/** - * Package validation provides configurable and extensible rules for validating data of various types. - */ -namespace ozzo_validation { - /** - * Error interface represents an validation error - */ - interface Error { - [key:string]: any; - error(): string - code(): string - message(): string - setMessage(_arg0: string): Error - params(): _TygojaDict - setParams(_arg0: _TygojaDict): Error - } -} - -namespace middleware { - interface bodyLimit { - /** - * BodyLimit returns a BodyLimit middleware. - * - * BodyLimit middleware sets the maximum allowed size for a request body, if the size exceeds the configured limit, it - * sends "413 - Request Entity Too Large" response. The BodyLimit is determined based on both `Content-Length` request - * header and actual content read, which makes it super secure. - */ - (limitBytes: number): echo.MiddlewareFunc - } - interface gzip { - /** - * Gzip returns a middleware which compresses HTTP response using gzip compression scheme. - */ - (): echo.MiddlewareFunc - } -} - -/** - * Package dbx provides a set of DB-agnostic and easy-to-use query building methods for relational databases. - */ -namespace dbx { - /** - * Builder supports building SQL statements in a DB-agnostic way. - * Builder mainly provides two sets of query building methods: those building SELECT statements - * and those manipulating DB data or schema (e.g. INSERT statements, CREATE TABLE statements). - */ - interface Builder { - [key:string]: any; - /** - * NewQuery creates a new Query object with the given SQL statement. - * The SQL statement may contain parameter placeholders which can be bound with actual parameter - * values before the statement is executed. - */ - newQuery(_arg0: string): (Query) - /** - * Select returns a new SelectQuery object that can be used to build a SELECT statement. - * The parameters to this method should be the list column names to be selected. - * A column name may have an optional alias name. For example, Select("id", "my_name AS name"). - */ - select(..._arg0: string[]): (SelectQuery) - /** - * ModelQuery returns a new ModelQuery object that can be used to perform model insertion, update, and deletion. - * The parameter to this method should be a pointer to the model struct that needs to be inserted, updated, or deleted. - */ - model(_arg0: { - }): (ModelQuery) - /** - * GeneratePlaceholder generates an anonymous parameter placeholder with the given parameter ID. - */ - generatePlaceholder(_arg0: number): string - /** - * Quote quotes a string so that it can be embedded in a SQL statement as a string value. + * Quote quotes a string so that it can be embedded in a SQL statement as a string value. */ quote(_arg0: string): string /** @@ -3462,14 +3105,14 @@ namespace dbx { /** * MssqlBuilder is the builder for SQL Server databases. */ - type _subcdPqR = BaseBuilder - interface MssqlBuilder extends _subcdPqR { + type _subLWXoY = BaseBuilder + interface MssqlBuilder extends _subLWXoY { } /** * MssqlQueryBuilder is the query builder for SQL Server databases. */ - type _subTZheC = BaseQueryBuilder - interface MssqlQueryBuilder extends _subTZheC { + type _subjRdIJ = BaseQueryBuilder + interface MssqlQueryBuilder extends _subjRdIJ { } interface newMssqlBuilder { /** @@ -3540,8 +3183,8 @@ namespace dbx { /** * MysqlBuilder is the builder for MySQL databases. */ - type _subcXwFY = BaseBuilder - interface MysqlBuilder extends _subcXwFY { + type _subiPFWn = BaseBuilder + interface MysqlBuilder extends _subiPFWn { } interface newMysqlBuilder { /** @@ -3616,14 +3259,14 @@ namespace dbx { /** * OciBuilder is the builder for Oracle databases. */ - type _subGfnXq = BaseBuilder - interface OciBuilder extends _subGfnXq { + type _subRrPnq = BaseBuilder + interface OciBuilder extends _subRrPnq { } /** * OciQueryBuilder is the query builder for Oracle databases. */ - type _subHrbWO = BaseQueryBuilder - interface OciQueryBuilder extends _subHrbWO { + type _subyswTX = BaseQueryBuilder + interface OciQueryBuilder extends _subyswTX { } interface newOciBuilder { /** @@ -3686,8 +3329,8 @@ namespace dbx { /** * PgsqlBuilder is the builder for PostgreSQL databases. */ - type _subBwXSI = BaseBuilder - interface PgsqlBuilder extends _subBwXSI { + type _subpnZgm = BaseBuilder + interface PgsqlBuilder extends _subpnZgm { } interface newPgsqlBuilder { /** @@ -3754,8 +3397,8 @@ namespace dbx { /** * SqliteBuilder is the builder for SQLite databases. */ - type _subwDEmW = BaseBuilder - interface SqliteBuilder extends _subwDEmW { + type _subtEyFP = BaseBuilder + interface SqliteBuilder extends _subtEyFP { } interface newSqliteBuilder { /** @@ -3854,8 +3497,8 @@ namespace dbx { /** * StandardBuilder is the builder that is used by DB for an unknown driver. */ - type _subMUMar = BaseBuilder - interface StandardBuilder extends _subMUMar { + type _subzzdCK = BaseBuilder + interface StandardBuilder extends _subzzdCK { } interface newStandardBuilder { /** @@ -3921,8 +3564,8 @@ namespace dbx { * DB enhances sql.DB by providing a set of DB-agnostic query building methods. * DB allows easier query building and population of data into Go variables. */ - type _subiYWlA = Builder - interface DB extends _subiYWlA { + type _subAiGqM = Builder + interface DB extends _subAiGqM { /** * FieldMapper maps struct fields to DB columns. Defaults to DefaultFieldMapFunc. */ @@ -4726,8 +4369,8 @@ namespace dbx { * Rows enhances sql.Rows by providing additional data query methods. * Rows can be obtained by calling Query.Rows(). It is mainly used to populate data row by row. */ - type _subblrDB = sql.Rows - interface Rows extends _subblrDB { + type _subsAYPm = sql.Rows + interface Rows extends _subsAYPm { } interface Rows { /** @@ -5085,8 +4728,8 @@ namespace dbx { }): string } interface structInfo { } - type _subSwKZu = structInfo - interface structValue extends _subSwKZu { + type _subNLgjm = structInfo + interface structValue extends _subNLgjm { } interface fieldInfo { } @@ -5125,8 +4768,8 @@ namespace dbx { /** * Tx enhances sql.Tx with additional querying methods. */ - type _subhYOwK = Builder - interface Tx extends _subhYOwK { + type _subNcvbx = Builder + interface Tx extends _subNcvbx { } interface Tx { /** @@ -5142,125 +4785,401 @@ namespace dbx { } } -namespace filesystem { - /** - * FileReader defines an interface for a file resource reader. - */ - interface FileReader { - [key:string]: any; - open(): io.ReadSeekCloser - } +/** + * Package validation provides configurable and extensible rules for validating data of various types. + */ +namespace ozzo_validation { /** - * File defines a single file [io.ReadSeekCloser] resource. - * - * The file could be from a local path, multipart/form-data header, etc. + * Error interface represents an validation error */ - interface File { - reader: FileReader - name: string - originalName: string - size: number + interface Error { + [key:string]: any; + error(): string + code(): string + message(): string + setMessage(_arg0: string): Error + params(): _TygojaDict + setParams(_arg0: _TygojaDict): Error } - interface newFileFromPath { +} + +/** + * Package exec runs external commands. It wraps os.StartProcess to make it + * easier to remap stdin and stdout, connect I/O with pipes, and do other + * adjustments. + * + * Unlike the "system" library call from C and other languages, the + * os/exec package intentionally does not invoke the system shell and + * does not expand any glob patterns or handle other expansions, + * pipelines, or redirections typically done by shells. The package + * behaves more like C's "exec" family of functions. To expand glob + * patterns, either call the shell directly, taking care to escape any + * dangerous input, or use the path/filepath package's Glob function. + * To expand environment variables, use package os's ExpandEnv. + * + * Note that the examples in this package assume a Unix system. + * They may not run on Windows, and they do not run in the Go Playground + * used by golang.org and godoc.org. + * + * # Executables in the current directory + * + * The functions Command and LookPath look for a program + * in the directories listed in the current path, following the + * conventions of the host operating system. + * Operating systems have for decades included the current + * directory in this search, sometimes implicitly and sometimes + * configured explicitly that way by default. + * Modern practice is that including the current directory + * is usually unexpected and often leads to security problems. + * + * To avoid those security problems, as of Go 1.19, this package will not resolve a program + * using an implicit or explicit path entry relative to the current directory. + * That is, if you run exec.LookPath("go"), it will not successfully return + * ./go on Unix nor .\go.exe on Windows, no matter how the path is configured. + * Instead, if the usual path algorithms would result in that answer, + * these functions return an error err satisfying errors.Is(err, ErrDot). + * + * For example, consider these two program snippets: + * + * ``` + * path, err := exec.LookPath("prog") + * if err != nil { + * log.Fatal(err) + * } + * use(path) + * ``` + * + * and + * + * ``` + * cmd := exec.Command("prog") + * if err := cmd.Run(); err != nil { + * log.Fatal(err) + * } + * ``` + * + * These will not find and run ./prog or .\prog.exe, + * no matter how the current path is configured. + * + * Code that always wants to run a program from the current directory + * can be rewritten to say "./prog" instead of "prog". + * + * Code that insists on including results from relative path entries + * can instead override the error using an errors.Is check: + * + * ``` + * path, err := exec.LookPath("prog") + * if errors.Is(err, exec.ErrDot) { + * err = nil + * } + * if err != nil { + * log.Fatal(err) + * } + * use(path) + * ``` + * + * and + * + * ``` + * cmd := exec.Command("prog") + * if errors.Is(cmd.Err, exec.ErrDot) { + * cmd.Err = nil + * } + * if err := cmd.Run(); err != nil { + * log.Fatal(err) + * } + * ``` + * + * Setting the environment variable GODEBUG=execerrdot=0 + * disables generation of ErrDot entirely, temporarily restoring the pre-Go 1.19 + * behavior for programs that are unable to apply more targeted fixes. + * A future version of Go may remove support for this variable. + * + * Before adding such overrides, make sure you understand the + * security implications of doing so. + * See https://go.dev/blog/path-security for more information. + */ +namespace exec { + interface command { /** - * NewFileFromPath creates a new File instance from the provided local file path. + * Command returns the Cmd struct to execute the named program with + * the given arguments. + * + * It sets only the Path and Args in the returned structure. + * + * If name contains no path separators, Command uses LookPath to + * resolve name to a complete path if possible. Otherwise it uses name + * directly as Path. + * + * The returned Cmd's Args field is constructed from the command name + * followed by the elements of arg, so arg should not include the + * command name itself. For example, Command("echo", "hello"). + * Args[0] is always name, not the possibly resolved Path. + * + * On Windows, processes receive the whole command line as a single string + * and do their own parsing. Command combines and quotes Args into a command + * line string with an algorithm compatible with applications using + * CommandLineToArgvW (which is the most common way). Notable exceptions are + * msiexec.exe and cmd.exe (and thus, all batch files), which have a different + * unquoting algorithm. In these or other similar cases, you can do the + * quoting yourself and provide the full command line in SysProcAttr.CmdLine, + * leaving Args empty. */ - (path: string): (File) + (name: string, ...arg: string[]): (Cmd) } - interface newFileFromBytes { +} + +namespace security { + interface s256Challenge { /** - * NewFileFromBytes creates a new File instance from the provided byte slice. + * S256Challenge creates base64 encoded sha256 challenge string derived from code. + * The padding of the result base64 string is stripped per [RFC 7636]. + * + * [RFC 7636]: https://datatracker.ietf.org/doc/html/rfc7636#section-4.2 */ - (b: string|Array, name: string): (File) + (code: string): string } - interface newFileFromMultipart { + interface md5 { /** - * NewFileFromMultipart creates a new File from the provided multipart header. + * MD5 creates md5 hash from the provided plain text. */ - (mh: multipart.FileHeader): (File) + (text: string): string } - interface newFileFromUrl { + interface sha256 { /** - * NewFileFromUrl creates a new File from the provided url by - * downloading the resource and load it as BytesReader. - * - * Example - * - * ``` - * ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - * defer cancel() - * - * file, err := filesystem.NewFileFromUrl(ctx, "https://example.com/image.png") - * ``` + * SHA256 creates sha256 hash as defined in FIPS 180-4 from the provided text. */ - (ctx: context.Context, url: string): (File) - } - /** - * MultipartReader defines a FileReader from [multipart.FileHeader]. - */ - interface MultipartReader { - header?: multipart.FileHeader + (text: string): string } - interface MultipartReader { + interface sha512 { /** - * Open implements the [filesystem.FileReader] interface. + * SHA512 creates sha512 hash as defined in FIPS 180-4 from the provided text. */ - open(): io.ReadSeekCloser - } - /** - * PathReader defines a FileReader from a local file path. - */ - interface PathReader { - path: string + (text: string): string } - interface PathReader { + interface hs256 { /** - * Open implements the [filesystem.FileReader] interface. + * HS256 creates a HMAC hash with sha256 digest algorithm. */ - open(): io.ReadSeekCloser - } - /** - * BytesReader defines a FileReader from bytes content. - */ - interface BytesReader { - bytes: string|Array + (text: string, secret: string): string } - interface BytesReader { + interface hs512 { /** - * Open implements the [filesystem.FileReader] interface. + * HS512 creates a HMAC hash with sha512 digest algorithm. */ - open(): io.ReadSeekCloser - } - type _subPtagO = bytes.Reader - interface bytesReadSeekCloser extends _subPtagO { + (text: string, secret: string): string } - interface bytesReadSeekCloser { + interface equal { /** - * Close implements the [io.ReadSeekCloser] interface. + * Equal compares two hash strings for equality without leaking timing information. */ - close(): void + (hash1: string, hash2: string): boolean } - interface System { + // @ts-ignore + import crand = rand + interface encrypt { + /** + * Encrypt encrypts data with key (must be valid 32 char aes key). + */ + (data: string|Array, key: string): string } - interface newS3 { + interface decrypt { /** - * NewS3 initializes an S3 filesystem instance. - * - * NB! Make sure to call `Close()` after you are done working with it. + * Decrypt decrypts encrypted text with key (must be valid 32 chars aes key). */ - (bucketName: string, region: string, endpoint: string, accessKey: string, secretKey: string, s3ForcePathStyle: boolean): (System) + (cipherText: string, key: string): string|Array } - interface newLocal { + interface parseUnverifiedJWT { /** - * NewLocal initializes a new local filesystem instance. + * ParseUnverifiedJWT parses JWT and returns its claims + * but DOES NOT verify the signature. * - * NB! Make sure to call `Close()` after you are done working with it. + * It verifies only the exp, iat and nbf claims. */ - (dirPath: string): (System) + (token: string): jwt.MapClaims } - interface System { + interface parseJWT { /** - * SetContext assigns the specified context to the current filesystem. + * ParseJWT verifies and parses JWT and returns its claims. + */ + (token: string, verificationKey: string): jwt.MapClaims + } + interface newJWT { + /** + * NewJWT generates and returns new HS256 signed JWT. + */ + (payload: jwt.MapClaims, signingKey: string, secondsDuration: number): string + } + interface newToken { + /** + * Deprecated: + * Consider replacing with NewJWT(). + * + * NewToken is a legacy alias for NewJWT that generates a HS256 signed JWT. + */ + (payload: jwt.MapClaims, signingKey: string, secondsDuration: number): string + } + // @ts-ignore + import cryptoRand = rand + // @ts-ignore + import mathRand = rand + interface randomString { + /** + * RandomString generates a cryptographically random string with the specified length. + * + * The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding. + */ + (length: number): string + } + interface randomStringWithAlphabet { + /** + * RandomStringWithAlphabet generates a cryptographically random string + * with the specified length and characters set. + * + * It panics if for some reason rand.Int returns a non-nil error. + */ + (length: number, alphabet: string): string + } + interface pseudorandomString { + /** + * PseudorandomString generates a pseudorandom string with the specified length. + * + * The generated string matches [A-Za-z0-9]+ and it's transparent to URL-encoding. + * + * For a cryptographically random string (but a little bit slower) use RandomString instead. + */ + (length: number): string + } + interface pseudorandomStringWithAlphabet { + /** + * PseudorandomStringWithAlphabet generates a pseudorandom string + * with the specified length and characters set. + * + * For a cryptographically random (but a little bit slower) use RandomStringWithAlphabet instead. + */ + (length: number, alphabet: string): string + } +} + +namespace filesystem { + /** + * FileReader defines an interface for a file resource reader. + */ + interface FileReader { + [key:string]: any; + open(): io.ReadSeekCloser + } + /** + * File defines a single file [io.ReadSeekCloser] resource. + * + * The file could be from a local path, multipart/form-data header, etc. + */ + interface File { + reader: FileReader + name: string + originalName: string + size: number + } + interface newFileFromPath { + /** + * NewFileFromPath creates a new File instance from the provided local file path. + */ + (path: string): (File) + } + interface newFileFromBytes { + /** + * NewFileFromBytes creates a new File instance from the provided byte slice. + */ + (b: string|Array, name: string): (File) + } + interface newFileFromMultipart { + /** + * NewFileFromMultipart creates a new File from the provided multipart header. + */ + (mh: multipart.FileHeader): (File) + } + interface newFileFromUrl { + /** + * NewFileFromUrl creates a new File from the provided url by + * downloading the resource and load it as BytesReader. + * + * Example + * + * ``` + * ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + * defer cancel() + * + * file, err := filesystem.NewFileFromUrl(ctx, "https://example.com/image.png") + * ``` + */ + (ctx: context.Context, url: string): (File) + } + /** + * MultipartReader defines a FileReader from [multipart.FileHeader]. + */ + interface MultipartReader { + header?: multipart.FileHeader + } + interface MultipartReader { + /** + * Open implements the [filesystem.FileReader] interface. + */ + open(): io.ReadSeekCloser + } + /** + * PathReader defines a FileReader from a local file path. + */ + interface PathReader { + path: string + } + interface PathReader { + /** + * Open implements the [filesystem.FileReader] interface. + */ + open(): io.ReadSeekCloser + } + /** + * BytesReader defines a FileReader from bytes content. + */ + interface BytesReader { + bytes: string|Array + } + interface BytesReader { + /** + * Open implements the [filesystem.FileReader] interface. + */ + open(): io.ReadSeekCloser + } + type _subJhswA = bytes.Reader + interface bytesReadSeekCloser extends _subJhswA { + } + interface bytesReadSeekCloser { + /** + * Close implements the [io.ReadSeekCloser] interface. + */ + close(): void + } + interface System { + } + interface newS3 { + /** + * NewS3 initializes an S3 filesystem instance. + * + * NB! Make sure to call `Close()` after you are done working with it. + */ + (bucketName: string, region: string, endpoint: string, accessKey: string, secretKey: string, s3ForcePathStyle: boolean): (System) + } + interface newLocal { + /** + * NewLocal initializes a new local filesystem instance. + * + * NB! Make sure to call `Close()` after you are done working with it. + */ + (dirPath: string): (System) + } + interface System { + /** + * SetContext assigns the specified context to the current filesystem. */ setContext(ctx: context.Context): void } @@ -6368,8 +6287,8 @@ namespace forms { /** * SettingsUpsert is a [settings.Settings] upsert (create/update) form. */ - type _subkcDwH = settings.Settings - interface SettingsUpsert extends _subkcDwH { + type _subthFwf = settings.Settings + interface SettingsUpsert extends _subthFwf { } interface newSettingsUpsert { /** @@ -6800,8 +6719,8 @@ namespace pocketbase { /** * appWrapper serves as a private CoreApp instance wrapper. */ - type _subYCAQy = CoreApp - interface appWrapper extends _subYCAQy { + type _subYtFzn = CoreApp + interface appWrapper extends _subYtFzn { } /** * PocketBase defines a PocketBase app launcher. @@ -6809,8 +6728,8 @@ namespace pocketbase { * It implements [CoreApp] via embedding and all of the app interface methods * could be accessed directly through the instance (eg. PocketBase.DataDir()). */ - type _subLQYMv = appWrapper - interface PocketBase extends _subLQYMv { + type _subPmgzu = appWrapper + interface PocketBase extends _subPmgzu { /** * RootCmd is the main console command */ @@ -6894,55 +6813,175 @@ namespace pocketbase { } /** - * Package io provides basic interfaces to I/O primitives. - * Its primary job is to wrap existing implementations of such primitives, - * such as those in package os, into shared public interfaces that - * abstract the functionality, plus some other related primitives. + * Package template is a thin wrapper around the standard html/template + * and text/template packages that implements a convenient registry to + * load and cache templates on the fly concurrently. * - * Because these interfaces and primitives wrap lower-level operations with - * various implementations, unless otherwise informed clients should not - * assume they are safe for parallel execution. + * It was created to assist the JSVM plugin HTML rendering, but could be used in other Go code. + * + * Example: + * + * ``` + * registry := template.NewRegistry() + * + * html1, err := registry.LoadFiles( + * // the files set wil be parsed only once and then cached + * "layout.html", + * "content.html", + * ).Render(map[string]any{"name": "John"}) + * + * html2, err := registry.LoadFiles( + * // reuse the already parsed and cached files set + * "layout.html", + * "content.html", + * ).Render(map[string]any{"name": "Jane"}) + * ``` */ -namespace io { +namespace template { + interface newRegistry { + /** + * NewRegistry creates and initializes a new templates registry with + * some defaults (eg. global "raw" template function for unescaped HTML). + * + * Use the Registry.Load* methods to load templates into the registry. + */ + (): (Registry) + } /** - * Reader is the interface that wraps the basic Read method. - * - * Read reads up to len(p) bytes into p. It returns the number of bytes - * read (0 <= n <= len(p)) and any error encountered. Even if Read - * returns n < len(p), it may use all of p as scratch space during the call. - * If some data is available but not len(p) bytes, Read conventionally - * returns what is available instead of waiting for more. - * - * When Read encounters an error or end-of-file condition after - * successfully reading n > 0 bytes, it returns the number of - * bytes read. It may return the (non-nil) error from the same call - * or return the error (and n == 0) from a subsequent call. - * An instance of this general case is that a Reader returning - * a non-zero number of bytes at the end of the input stream may - * return either err == EOF or err == nil. The next Read should - * return 0, EOF. - * - * Callers should always process the n > 0 bytes returned before - * considering the error err. Doing so correctly handles I/O errors - * that happen after reading some bytes and also both of the - * allowed EOF behaviors. - * - * If len(p) == 0, Read should always return n == 0. It may return a - * non-nil error if some error condition is known, such as EOF. - * - * Implementations of Read are discouraged from returning a - * zero byte count with a nil error, except when len(p) == 0. - * Callers should treat a return of 0 and nil as indicating that - * nothing happened; in particular it does not indicate EOF. + * Registry defines a templates registry that is safe to be used by multiple goroutines. * - * Implementations must not retain p. + * Use the Registry.Load* methods to load templates into the registry. */ - interface Reader { - [key:string]: any; - read(p: string|Array): number + interface Registry { } - /** - * ReadSeekCloser is the interface that groups the basic Read, Seek and Close + interface Registry { + /** + * AddFuncs registers new global template functions. + * + * The key of each map entry is the function name that will be used in the templates. + * If a function with the map entry name already exists it will be replaced with the new one. + * + * The value of each map entry is a function that must have either a + * single return value, or two return values of which the second has type error. + * + * Example: + * + * r.AddFuncs(map[string]any{ + * ``` + * "toUpper": func(str string) string { + * return strings.ToUppser(str) + * }, + * ... + * ``` + * }) + */ + addFuncs(funcs: _TygojaDict): (Registry) + } + interface Registry { + /** + * LoadFiles caches (if not already) the specified filenames set as a + * single template and returns a ready to use Renderer instance. + * + * There must be at least 1 filename specified. + */ + loadFiles(...filenames: string[]): (Renderer) + } + interface Registry { + /** + * LoadString caches (if not already) the specified inline string as a + * single template and returns a ready to use Renderer instance. + */ + loadString(text: string): (Renderer) + } + interface Registry { + /** + * LoadFS caches (if not already) the specified fs and globPatterns + * pair as single template and returns a ready to use Renderer instance. + * + * There must be at least 1 file matching the provided globPattern(s) + * (note that most file names serves as glob patterns matching themselves). + */ + loadFS(fsys: fs.FS, ...globPatterns: string[]): (Renderer) + } + /** + * Renderer defines a single parsed template. + */ + interface Renderer { + } + interface Renderer { + /** + * Render executes the template with the specified data as the dot object + * and returns the result as plain string. + */ + render(data: any): string + } +} + +/** + * Package io provides basic interfaces to I/O primitives. + * Its primary job is to wrap existing implementations of such primitives, + * such as those in package os, into shared public interfaces that + * abstract the functionality, plus some other related primitives. + * + * Because these interfaces and primitives wrap lower-level operations with + * various implementations, unless otherwise informed clients should not + * assume they are safe for parallel execution. + */ +namespace io { + /** + * Reader is the interface that wraps the basic Read method. + * + * Read reads up to len(p) bytes into p. It returns the number of bytes + * read (0 <= n <= len(p)) and any error encountered. Even if Read + * returns n < len(p), it may use all of p as scratch space during the call. + * If some data is available but not len(p) bytes, Read conventionally + * returns what is available instead of waiting for more. + * + * When Read encounters an error or end-of-file condition after + * successfully reading n > 0 bytes, it returns the number of + * bytes read. It may return the (non-nil) error from the same call + * or return the error (and n == 0) from a subsequent call. + * An instance of this general case is that a Reader returning + * a non-zero number of bytes at the end of the input stream may + * return either err == EOF or err == nil. The next Read should + * return 0, EOF. + * + * Callers should always process the n > 0 bytes returned before + * considering the error err. Doing so correctly handles I/O errors + * that happen after reading some bytes and also both of the + * allowed EOF behaviors. + * + * If len(p) == 0, Read should always return n == 0. It may return a + * non-nil error if some error condition is known, such as EOF. + * + * Implementations of Read are discouraged from returning a + * zero byte count with a nil error, except when len(p) == 0. + * Callers should treat a return of 0 and nil as indicating that + * nothing happened; in particular it does not indicate EOF. + * + * Implementations must not retain p. + */ + interface Reader { + [key:string]: any; + read(p: string|Array): number + } + /** + * Writer is the interface that wraps the basic Write method. + * + * Write writes len(p) bytes from p to the underlying data stream. + * It returns the number of bytes written from p (0 <= n <= len(p)) + * and any error encountered that caused the write to stop early. + * Write must return a non-nil error if it returns n < len(p). + * Write must not modify the slice data, even temporarily. + * + * Implementations must not retain p. + */ + interface Writer { + [key:string]: any; + write(p: string|Array): number + } + /** + * ReadSeekCloser is the interface that groups the basic Read, Seek and Close * methods. */ interface ReadSeekCloser { @@ -6959,7 +6998,7 @@ namespace bytes { * A Reader implements the io.Reader, io.ReaderAt, io.WriterTo, io.Seeker, * io.ByteScanner, and io.RuneScanner interfaces by reading from * a byte slice. - * Unlike a Buffer, a Reader is read-only and supports seeking. + * Unlike a [Buffer], a Reader is read-only and supports seeking. * The zero value for Reader operates like a Reader of an empty slice. */ interface Reader { @@ -6974,62 +7013,62 @@ namespace bytes { interface Reader { /** * Size returns the original length of the underlying byte slice. - * Size is the number of bytes available for reading via ReadAt. - * The result is unaffected by any method calls except Reset. + * Size is the number of bytes available for reading via [Reader.ReadAt]. + * The result is unaffected by any method calls except [Reader.Reset]. */ size(): number } interface Reader { /** - * Read implements the io.Reader interface. + * Read implements the [io.Reader] interface. */ read(b: string|Array): number } interface Reader { /** - * ReadAt implements the io.ReaderAt interface. + * ReadAt implements the [io.ReaderAt] interface. */ readAt(b: string|Array, off: number): number } interface Reader { /** - * ReadByte implements the io.ByteReader interface. + * ReadByte implements the [io.ByteReader] interface. */ readByte(): number } interface Reader { /** - * UnreadByte complements ReadByte in implementing the io.ByteScanner interface. + * UnreadByte complements [Reader.ReadByte] in implementing the [io.ByteScanner] interface. */ unreadByte(): void } interface Reader { /** - * ReadRune implements the io.RuneReader interface. + * ReadRune implements the [io.RuneReader] interface. */ readRune(): [number, number] } interface Reader { /** - * UnreadRune complements ReadRune in implementing the io.RuneScanner interface. + * UnreadRune complements [Reader.ReadRune] in implementing the [io.RuneScanner] interface. */ unreadRune(): void } interface Reader { /** - * Seek implements the io.Seeker interface. + * Seek implements the [io.Seeker] interface. */ seek(offset: number, whence: number): number } interface Reader { /** - * WriteTo implements the io.WriterTo interface. + * WriteTo implements the [io.WriterTo] interface. */ writeTo(w: io.Writer): number } interface Reader { /** - * Reset resets the Reader to be reading from b. + * Reset resets the [Reader.Reader] to be reading from b. */ reset(b: string|Array): void } @@ -7052,11 +7091,11 @@ namespace bytes { * err is an operating system error describing the failure. * On most systems, that error has type syscall.Errno. * - * Deprecated: this package is locked down. Callers should use the - * corresponding package in the golang.org/x/sys repository instead. - * That is also where updates required by new systems or versions - * should be applied. See https://golang.org/s/go1.4-syscall for more - * information. + * NOTE: Most of the functions, types, and constants defined in + * this package are also available in the [golang.org/x/sys] package. + * That package has more system call support than this one, + * and most new code should prefer that package where possible. + * See https://golang.org/s/go1.4-syscall for more information. */ namespace syscall { interface SysProcAttr { @@ -7081,8 +7120,8 @@ namespace syscall { * This is only meaningful if Setsid is true. */ setctty: boolean - noctty: boolean // Detach fd 0 from controlling terminal - ctty: number // Controlling TTY fd + noctty: boolean // Detach fd 0 from controlling terminal. + ctty: number // Controlling TTY fd. /** * Foreground places the child process group in the foreground. * This implies Setpgid. The Ctty field must be set to @@ -7099,8 +7138,8 @@ namespace syscall { * There are more details at https://go.dev/issue/27505. */ pdeathsig: Signal - cloneflags: number // Flags for clone calls (Linux only) - unshareflags: number // Flags for unshare calls (Linux only) + cloneflags: number // Flags for clone calls. + unshareflags: number // Flags for unshare calls. uidMappings: Array // User ID mappings for user namespaces. gidMappings: Array // Group ID mappings for user namespaces. /** @@ -7110,9 +7149,15 @@ namespace syscall { * users this should be set to false for mappings work. */ gidMappingsEnableSetgroups: boolean - ambientCaps: Array // Ambient capabilities (Linux only) + ambientCaps: Array // Ambient capabilities. useCgroupFD: boolean // Whether to make use of the CgroupFD field. cgroupFD: number // File descriptor of a cgroup to put the new process into. + /** + * PidFD, if not nil, is used to store the pidfd of a child, if the + * functionality is supported by the kernel, or -1. Note *PidFD is + * changed only if the process starts successfully. + */ + pidFD?: number } // @ts-ignore import errorspkg = errors @@ -7256,6 +7301,14 @@ namespace syscall { * For debugging, the result of t.String does include the monotonic * clock reading if present. If t != u because of different monotonic clock readings, * that difference will be visible when printing t.String() and u.String(). + * + * # Timer Resolution + * + * Timer resolution varies depending on the Go runtime, the operating system + * and the underlying hardware. + * On Unix, the resolution is approximately 1ms. + * On Windows, the default resolution is approximately 16ms, but + * a higher resolution may be requested using [golang.org/x/sys/windows.TimeBeginPeriod]. */ namespace time { interface Time { @@ -7320,12 +7373,10 @@ namespace time { * As this time is unlikely to come up in practice, the IsZero method gives * a simple way of detecting a time that has not been initialized explicitly. * - * Each Time has associated with it a Location, consulted when computing the - * presentation form of the time, such as in the Format, Hour, and Year methods. - * The methods Local, UTC, and In return a Time with a specific location. - * Changing the location in this way changes only the presentation; it does not - * change the instant in time being denoted and therefore does not affect the - * computations described in earlier paragraphs. + * Each time has an associated Location. The methods Local, UTC, and In return a + * Time with a specific Location. Changing the Location of a Time value with + * these methods does not change the actual instant it represents, only the time + * zone in which to interpret it. * * Representations of a Time value saved by the GobEncode, MarshalBinary, * MarshalJSON, and MarshalText methods store the Time.Location's offset, but not @@ -7559,6 +7610,15 @@ namespace time { * For example, AddDate(-1, 2, 3) applied to January 1, 2011 * returns March 4, 2010. * + * Note that dates are fundamentally coupled to timezones, and calendrical + * periods like days don't have fixed durations. AddDate uses the Location of + * the Time value to determine these durations. That means that the same + * AddDate arguments can produce a different shift in absolute time depending on + * the base Time value and its Location. For example, AddDate(0, 0, 1) applied + * to 12:00 on March 27 always returns 12:00 on March 28. At some locations and + * in some years this is a 24 hour shift. In others it's a 23 hour shift due to + * daylight savings time transitions. + * * AddDate normalizes its result in the same way that Date does, * so, for example, adding one month to October 31 yields * December 1, the normalized form for November 31. @@ -7742,51 +7802,220 @@ namespace time { } /** - * Package fs defines basic interfaces to a file system. - * A file system can be provided by the host operating system - * but also by other packages. + * Package context defines the Context type, which carries deadlines, + * cancellation signals, and other request-scoped values across API boundaries + * and between processes. + * + * Incoming requests to a server should create a [Context], and outgoing + * calls to servers should accept a Context. The chain of function + * calls between them must propagate the Context, optionally replacing + * it with a derived Context created using [WithCancel], [WithDeadline], + * [WithTimeout], or [WithValue]. When a Context is canceled, all + * Contexts derived from it are also canceled. + * + * The [WithCancel], [WithDeadline], and [WithTimeout] functions take a + * Context (the parent) and return a derived Context (the child) and a + * [CancelFunc]. Calling the CancelFunc cancels the child and its + * children, removes the parent's reference to the child, and stops + * any associated timers. Failing to call the CancelFunc leaks the + * child and its children until the parent is canceled or the timer + * fires. The go vet tool checks that CancelFuncs are used on all + * control-flow paths. + * + * The [WithCancelCause] function returns a [CancelCauseFunc], which + * takes an error and records it as the cancellation cause. Calling + * [Cause] on the canceled context or any of its children retrieves + * the cause. If no cause is specified, Cause(ctx) returns the same + * value as ctx.Err(). + * + * Programs that use Contexts should follow these rules to keep interfaces + * consistent across packages and enable static analysis tools to check context + * propagation: + * + * Do not store Contexts inside a struct type; instead, pass a Context + * explicitly to each function that needs it. The Context should be the first + * parameter, typically named ctx: + * + * ``` + * func DoSomething(ctx context.Context, arg Arg) error { + * // ... use ctx ... + * } + * ``` + * + * Do not pass a nil [Context], even if a function permits it. Pass [context.TODO] + * if you are unsure about which Context to use. + * + * Use context Values only for request-scoped data that transits processes and + * APIs, not for passing optional parameters to functions. + * + * The same Context may be passed to functions running in different goroutines; + * Contexts are safe for simultaneous use by multiple goroutines. + * + * See https://blog.golang.org/context for example code for a server that uses + * Contexts. */ -namespace fs { +namespace context { /** - * An FS provides access to a hierarchical file system. + * A Context carries a deadline, a cancellation signal, and other values across + * API boundaries. * - * The FS interface is the minimum implementation required of the file system. - * A file system may implement additional interfaces, - * such as ReadFileFS, to provide additional or optimized functionality. + * Context's methods may be called by multiple goroutines simultaneously. */ - interface FS { + interface Context { [key:string]: any; /** - * Open opens the named file. + * Deadline returns the time when work done on behalf of this context + * should be canceled. Deadline returns ok==false when no deadline is + * set. Successive calls to Deadline return the same results. + */ + deadline(): [time.Time, boolean] + /** + * Done returns a channel that's closed when work done on behalf of this + * context should be canceled. Done may return nil if this context can + * never be canceled. Successive calls to Done return the same value. + * The close of the Done channel may happen asynchronously, + * after the cancel function returns. * - * When Open returns an error, it should be of type *PathError - * with the Op field set to "open", the Path field set to name, - * and the Err field describing the problem. + * WithCancel arranges for Done to be closed when cancel is called; + * WithDeadline arranges for Done to be closed when the deadline + * expires; WithTimeout arranges for Done to be closed when the timeout + * elapses. * - * Open should reject attempts to open names that do not satisfy - * ValidPath(name), returning a *PathError with Err set to - * ErrInvalid or ErrNotExist. + * Done is provided for use in select statements: + * + * // Stream generates values with DoSomething and sends them to out + * // until DoSomething returns an error or ctx.Done is closed. + * func Stream(ctx context.Context, out chan<- Value) error { + * for { + * v, err := DoSomething(ctx) + * if err != nil { + * return err + * } + * select { + * case <-ctx.Done(): + * return ctx.Err() + * case out <- v: + * } + * } + * } + * + * See https://blog.golang.org/pipelines for more examples of how to use + * a Done channel for cancellation. */ - open(name: string): File - } - /** - * A File provides access to a single file. - * The File interface is the minimum implementation required of the file. - * Directory files should also implement ReadDirFile. - * A file may implement io.ReaderAt or io.Seeker as optimizations. - */ - interface File { - [key:string]: any; - stat(): FileInfo - read(_arg0: string|Array): number - close(): void - } - /** - * A DirEntry is an entry read from a directory - * (using the ReadDir function or a ReadDirFile's ReadDir method). - */ - interface DirEntry { - [key:string]: any; + done(): undefined + /** + * If Done is not yet closed, Err returns nil. + * If Done is closed, Err returns a non-nil error explaining why: + * Canceled if the context was canceled + * or DeadlineExceeded if the context's deadline passed. + * After Err returns a non-nil error, successive calls to Err return the same error. + */ + err(): void + /** + * Value returns the value associated with this context for key, or nil + * if no value is associated with key. Successive calls to Value with + * the same key returns the same result. + * + * Use context values only for request-scoped data that transits + * processes and API boundaries, not for passing optional parameters to + * functions. + * + * A key identifies a specific value in a Context. Functions that wish + * to store values in Context typically allocate a key in a global + * variable then use that key as the argument to context.WithValue and + * Context.Value. A key can be any type that supports equality; + * packages should define keys as an unexported type to avoid + * collisions. + * + * Packages that define a Context key should provide type-safe accessors + * for the values stored using that key: + * + * ``` + * // Package user defines a User type that's stored in Contexts. + * package user + * + * import "context" + * + * // User is the type of value stored in the Contexts. + * type User struct {...} + * + * // key is an unexported type for keys defined in this package. + * // This prevents collisions with keys defined in other packages. + * type key int + * + * // userKey is the key for user.User values in Contexts. It is + * // unexported; clients use user.NewContext and user.FromContext + * // instead of using this key directly. + * var userKey key + * + * // NewContext returns a new Context that carries value u. + * func NewContext(ctx context.Context, u *User) context.Context { + * return context.WithValue(ctx, userKey, u) + * } + * + * // FromContext returns the User value stored in ctx, if any. + * func FromContext(ctx context.Context) (*User, bool) { + * u, ok := ctx.Value(userKey).(*User) + * return u, ok + * } + * ``` + */ + value(key: any): any + } +} + +/** + * Package fs defines basic interfaces to a file system. + * A file system can be provided by the host operating system + * but also by other packages. + * + * See the [testing/fstest] package for support with testing + * implementations of file systems. + */ +namespace fs { + /** + * An FS provides access to a hierarchical file system. + * + * The FS interface is the minimum implementation required of the file system. + * A file system may implement additional interfaces, + * such as [ReadFileFS], to provide additional or optimized functionality. + * + * [testing/fstest.TestFS] may be used to test implementations of an FS for + * correctness. + */ + interface FS { + [key:string]: any; + /** + * Open opens the named file. + * + * When Open returns an error, it should be of type *PathError + * with the Op field set to "open", the Path field set to name, + * and the Err field describing the problem. + * + * Open should reject attempts to open names that do not satisfy + * ValidPath(name), returning a *PathError with Err set to + * ErrInvalid or ErrNotExist. + */ + open(name: string): File + } + /** + * A File provides access to a single file. + * The File interface is the minimum implementation required of the file. + * Directory files should also implement [ReadDirFile]. + * A file may implement [io.ReaderAt] or [io.Seeker] as optimizations. + */ + interface File { + [key:string]: any; + stat(): FileInfo + read(_arg0: string|Array): number + close(): void + } + /** + * A DirEntry is an entry read from a directory + * (using the [ReadDir] function or a [ReadDirFile]'s ReadDir method). + */ + interface DirEntry { + [key:string]: any; /** * Name returns the name of the file (or subdirectory) described by the entry. * This name is only the final element of the path (the base name), not the entire path. @@ -7813,7 +8042,7 @@ namespace fs { info(): FileInfo } /** - * A FileInfo describes a file and is returned by Stat. + * A FileInfo describes a file and is returned by [Stat]. */ interface FileInfo { [key:string]: any; @@ -7829,7 +8058,7 @@ namespace fs { * The bits have the same definition on all systems, so that * information about files can be moved from one system * to another portably. Not all bits apply to all systems. - * The only required bit is ModeDir for directories. + * The only required bit is [ModeDir] for directories. */ interface FileMode extends Number{} interface FileMode { @@ -7838,7 +8067,7 @@ namespace fs { interface FileMode { /** * IsDir reports whether m describes a directory. - * That is, it tests for the ModeDir bit being set in m. + * That is, it tests for the [ModeDir] bit being set in m. */ isDir(): boolean } @@ -7851,13 +8080,13 @@ namespace fs { } interface FileMode { /** - * Perm returns the Unix permission bits in m (m & ModePerm). + * Perm returns the Unix permission bits in m (m & [ModePerm]). */ perm(): FileMode } interface FileMode { /** - * Type returns type bits in m (m & ModeType). + * Type returns type bits in m (m & [ModeType]). */ type(): FileMode } @@ -7882,51 +8111,51 @@ namespace fs { timeout(): boolean } /** - * WalkDirFunc is the type of the function called by WalkDir to visit + * WalkDirFunc is the type of the function called by [WalkDir] to visit * each file or directory. * - * The path argument contains the argument to WalkDir as a prefix. + * The path argument contains the argument to [WalkDir] as a prefix. * That is, if WalkDir is called with root argument "dir" and finds a file * named "a" in that directory, the walk function will be called with * argument "dir/a". * - * The d argument is the fs.DirEntry for the named path. + * The d argument is the [DirEntry] for the named path. * - * The error result returned by the function controls how WalkDir - * continues. If the function returns the special value SkipDir, WalkDir + * The error result returned by the function controls how [WalkDir] + * continues. If the function returns the special value [SkipDir], WalkDir * skips the current directory (path if d.IsDir() is true, otherwise * path's parent directory). If the function returns the special value - * SkipAll, WalkDir skips all remaining files and directories. Otherwise, + * [SkipAll], WalkDir skips all remaining files and directories. Otherwise, * if the function returns a non-nil error, WalkDir stops entirely and * returns that error. * * The err argument reports an error related to path, signaling that - * WalkDir will not walk into that directory. The function can decide how + * [WalkDir] will not walk into that directory. The function can decide how * to handle that error; as described earlier, returning the error will * cause WalkDir to stop walking the entire tree. * - * WalkDir calls the function with a non-nil err argument in two cases. + * [WalkDir] calls the function with a non-nil err argument in two cases. * - * First, if the initial fs.Stat on the root directory fails, WalkDir + * First, if the initial [Stat] on the root directory fails, WalkDir * calls the function with path set to root, d set to nil, and err set to - * the error from fs.Stat. + * the error from [fs.Stat]. * - * Second, if a directory's ReadDir method fails, WalkDir calls the + * Second, if a directory's ReadDir method (see [ReadDirFile]) fails, WalkDir calls the * function with path set to the directory's path, d set to an - * fs.DirEntry describing the directory, and err set to the error from + * [DirEntry] describing the directory, and err set to the error from * ReadDir. In this second case, the function is called twice with the * path of the directory: the first call is before the directory read is * attempted and has err set to nil, giving the function a chance to - * return SkipDir or SkipAll and avoid the ReadDir entirely. The second call + * return [SkipDir] or [SkipAll] and avoid the ReadDir entirely. The second call * is after a failed ReadDir and reports the error from ReadDir. * (If ReadDir succeeds, there is no second call.) * - * The differences between WalkDirFunc compared to filepath.WalkFunc are: + * The differences between WalkDirFunc compared to [path/filepath.WalkFunc] are: * * ``` - * - The second argument has type fs.DirEntry instead of fs.FileInfo. - * - The function is called before reading a directory, to allow SkipDir - * or SkipAll to bypass the directory read entirely or skip all remaining + * - The second argument has type [DirEntry] instead of [FileInfo]. + * - The function is called before reading a directory, to allow [SkipDir] + * or [SkipAll] to bypass the directory read entirely or skip all remaining * files and directories respectively. * - If a directory read fails, the function is called a second time * for that directory to report the error. @@ -7936,3851 +8165,3703 @@ namespace fs { } /** - * Package context defines the Context type, which carries deadlines, - * cancellation signals, and other request-scoped values across API boundaries - * and between processes. - * - * Incoming requests to a server should create a [Context], and outgoing - * calls to servers should accept a Context. The chain of function - * calls between them must propagate the Context, optionally replacing - * it with a derived Context created using [WithCancel], [WithDeadline], - * [WithTimeout], or [WithValue]. When a Context is canceled, all - * Contexts derived from it are also canceled. - * - * The [WithCancel], [WithDeadline], and [WithTimeout] functions take a - * Context (the parent) and return a derived Context (the child) and a - * [CancelFunc]. Calling the CancelFunc cancels the child and its - * children, removes the parent's reference to the child, and stops - * any associated timers. Failing to call the CancelFunc leaks the - * child and its children until the parent is canceled or the timer - * fires. The go vet tool checks that CancelFuncs are used on all - * control-flow paths. - * - * The [WithCancelCause] function returns a [CancelCauseFunc], which - * takes an error and records it as the cancellation cause. Calling - * [Cause] on the canceled context or any of its children retrieves - * the cause. If no cause is specified, Cause(ctx) returns the same - * value as ctx.Err(). - * - * Programs that use Contexts should follow these rules to keep interfaces - * consistent across packages and enable static analysis tools to check context - * propagation: - * - * Do not store Contexts inside a struct type; instead, pass a Context - * explicitly to each function that needs it. The Context should be the first - * parameter, typically named ctx: - * - * ``` - * func DoSomething(ctx context.Context, arg Arg) error { - * // ... use ctx ... - * } - * ``` - * - * Do not pass a nil [Context], even if a function permits it. Pass [context.TODO] - * if you are unsure about which Context to use. + * Package sql provides a generic interface around SQL (or SQL-like) + * databases. * - * Use context Values only for request-scoped data that transits processes and - * APIs, not for passing optional parameters to functions. + * The sql package must be used in conjunction with a database driver. + * See https://golang.org/s/sqldrivers for a list of drivers. * - * The same Context may be passed to functions running in different goroutines; - * Contexts are safe for simultaneous use by multiple goroutines. + * Drivers that do not support context cancellation will not return until + * after the query is completed. * - * See https://blog.golang.org/context for example code for a server that uses - * Contexts. + * For usage examples, see the wiki page at + * https://golang.org/s/sqlwiki. */ -namespace context { +namespace sql { /** - * A Context carries a deadline, a cancellation signal, and other values across - * API boundaries. + * TxOptions holds the transaction options to be used in [DB.BeginTx]. + */ + interface TxOptions { + /** + * Isolation is the transaction isolation level. + * If zero, the driver or database's default level is used. + */ + isolation: IsolationLevel + readOnly: boolean + } + /** + * DB is a database handle representing a pool of zero or more + * underlying connections. It's safe for concurrent use by multiple + * goroutines. * - * Context's methods may be called by multiple goroutines simultaneously. + * The sql package creates and frees connections automatically; it + * also maintains a free pool of idle connections. If the database has + * a concept of per-connection state, such state can be reliably observed + * within a transaction ([Tx]) or connection ([Conn]). Once [DB.Begin] is called, the + * returned [Tx] is bound to a single connection. Once [Tx.Commit] or + * [Tx.Rollback] is called on the transaction, that transaction's + * connection is returned to [DB]'s idle connection pool. The pool size + * can be controlled with [DB.SetMaxIdleConns]. */ - interface Context { - [key:string]: any; + interface DB { + } + interface DB { /** - * Deadline returns the time when work done on behalf of this context - * should be canceled. Deadline returns ok==false when no deadline is - * set. Successive calls to Deadline return the same results. + * PingContext verifies a connection to the database is still alive, + * establishing a connection if necessary. */ - deadline(): [time.Time, boolean] + pingContext(ctx: context.Context): void + } + interface DB { /** - * Done returns a channel that's closed when work done on behalf of this - * context should be canceled. Done may return nil if this context can - * never be canceled. Successive calls to Done return the same value. - * The close of the Done channel may happen asynchronously, - * after the cancel function returns. - * - * WithCancel arranges for Done to be closed when cancel is called; - * WithDeadline arranges for Done to be closed when the deadline - * expires; WithTimeout arranges for Done to be closed when the timeout - * elapses. - * - * Done is provided for use in select statements: - * - * // Stream generates values with DoSomething and sends them to out - * // until DoSomething returns an error or ctx.Done is closed. - * func Stream(ctx context.Context, out chan<- Value) error { - * for { - * v, err := DoSomething(ctx) - * if err != nil { - * return err - * } - * select { - * case <-ctx.Done(): - * return ctx.Err() - * case out <- v: - * } - * } - * } + * Ping verifies a connection to the database is still alive, + * establishing a connection if necessary. * - * See https://blog.golang.org/pipelines for more examples of how to use - * a Done channel for cancellation. + * Ping uses [context.Background] internally; to specify the context, use + * [DB.PingContext]. */ - done(): undefined + ping(): void + } + interface DB { /** - * If Done is not yet closed, Err returns nil. - * If Done is closed, Err returns a non-nil error explaining why: - * Canceled if the context was canceled - * or DeadlineExceeded if the context's deadline passed. - * After Err returns a non-nil error, successive calls to Err return the same error. + * Close closes the database and prevents new queries from starting. + * Close then waits for all queries that have started processing on the server + * to finish. + * + * It is rare to Close a [DB], as the [DB] handle is meant to be + * long-lived and shared between many goroutines. */ - err(): void + close(): void + } + interface DB { /** - * Value returns the value associated with this context for key, or nil - * if no value is associated with key. Successive calls to Value with - * the same key returns the same result. + * SetMaxIdleConns sets the maximum number of connections in the idle + * connection pool. * - * Use context values only for request-scoped data that transits - * processes and API boundaries, not for passing optional parameters to - * functions. - * - * A key identifies a specific value in a Context. Functions that wish - * to store values in Context typically allocate a key in a global - * variable then use that key as the argument to context.WithValue and - * Context.Value. A key can be any type that supports equality; - * packages should define keys as an unexported type to avoid - * collisions. + * If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, + * then the new MaxIdleConns will be reduced to match the MaxOpenConns limit. * - * Packages that define a Context key should provide type-safe accessors - * for the values stored using that key: + * If n <= 0, no idle connections are retained. * - * ``` - * // Package user defines a User type that's stored in Contexts. - * package user + * The default max idle connections is currently 2. This may change in + * a future release. + */ + setMaxIdleConns(n: number): void + } + interface DB { + /** + * SetMaxOpenConns sets the maximum number of open connections to the database. * - * import "context" + * If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than + * MaxIdleConns, then MaxIdleConns will be reduced to match the new + * MaxOpenConns limit. * - * // User is the type of value stored in the Contexts. - * type User struct {...} + * If n <= 0, then there is no limit on the number of open connections. + * The default is 0 (unlimited). + */ + setMaxOpenConns(n: number): void + } + interface DB { + /** + * SetConnMaxLifetime sets the maximum amount of time a connection may be reused. * - * // key is an unexported type for keys defined in this package. - * // This prevents collisions with keys defined in other packages. - * type key int + * Expired connections may be closed lazily before reuse. * - * // userKey is the key for user.User values in Contexts. It is - * // unexported; clients use user.NewContext and user.FromContext - * // instead of using this key directly. - * var userKey key + * If d <= 0, connections are not closed due to a connection's age. + */ + setConnMaxLifetime(d: time.Duration): void + } + interface DB { + /** + * SetConnMaxIdleTime sets the maximum amount of time a connection may be idle. * - * // NewContext returns a new Context that carries value u. - * func NewContext(ctx context.Context, u *User) context.Context { - * return context.WithValue(ctx, userKey, u) - * } + * Expired connections may be closed lazily before reuse. * - * // FromContext returns the User value stored in ctx, if any. - * func FromContext(ctx context.Context) (*User, bool) { - * u, ok := ctx.Value(userKey).(*User) - * return u, ok - * } - * ``` + * If d <= 0, connections are not closed due to a connection's idle time. */ - value(key: any): any - } -} - -/** - * Package multipart implements MIME multipart parsing, as defined in RFC - * 2046. - * - * The implementation is sufficient for HTTP (RFC 2388) and the multipart - * bodies generated by popular browsers. - * - * # Limits - * - * To protect against malicious inputs, this package sets limits on the size - * of the MIME data it processes. - * - * Reader.NextPart and Reader.NextRawPart limit the number of headers in a - * part to 10000 and Reader.ReadForm limits the total number of headers in all - * FileHeaders to 10000. - * These limits may be adjusted with the GODEBUG=multipartmaxheaders= - * setting. - * - * Reader.ReadForm further limits the number of parts in a form to 1000. - * This limit may be adjusted with the GODEBUG=multipartmaxparts= - * setting. - */ -/** - * Copyright 2023 The Go Authors. All rights reserved. - * Use of this source code is governed by a BSD-style - * license that can be found in the LICENSE file. - */ -namespace multipart { - /** - * A FileHeader describes a file part of a multipart request. - */ - interface FileHeader { - filename: string - header: textproto.MIMEHeader - size: number + setConnMaxIdleTime(d: time.Duration): void } - interface FileHeader { + interface DB { /** - * Open opens and returns the FileHeader's associated File. + * Stats returns database statistics. */ - open(): File + stats(): DBStats } -} - -/** - * Package http provides HTTP client and server implementations. - * - * Get, Head, Post, and PostForm make HTTP (or HTTPS) requests: - * - * ``` - * resp, err := http.Get("http://example.com/") - * ... - * resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) - * ... - * resp, err := http.PostForm("http://example.com/form", - * url.Values{"key": {"Value"}, "id": {"123"}}) - * ``` - * - * The caller must close the response body when finished with it: - * - * ``` - * resp, err := http.Get("http://example.com/") - * if err != nil { - * // handle error - * } - * defer resp.Body.Close() - * body, err := io.ReadAll(resp.Body) - * // ... - * ``` - * - * # Clients and Transports - * - * For control over HTTP client headers, redirect policy, and other - * settings, create a Client: - * - * ``` - * client := &http.Client{ - * CheckRedirect: redirectPolicyFunc, - * } - * - * resp, err := client.Get("http://example.com") - * // ... - * - * req, err := http.NewRequest("GET", "http://example.com", nil) - * // ... - * req.Header.Add("If-None-Match", `W/"wyzzy"`) - * resp, err := client.Do(req) - * // ... - * ``` - * - * For control over proxies, TLS configuration, keep-alives, - * compression, and other settings, create a Transport: - * - * ``` - * tr := &http.Transport{ - * MaxIdleConns: 10, - * IdleConnTimeout: 30 * time.Second, - * DisableCompression: true, - * } - * client := &http.Client{Transport: tr} - * resp, err := client.Get("https://example.com") - * ``` - * - * Clients and Transports are safe for concurrent use by multiple - * goroutines and for efficiency should only be created once and re-used. - * - * # Servers - * - * ListenAndServe starts an HTTP server with a given address and handler. - * The handler is usually nil, which means to use DefaultServeMux. - * Handle and HandleFunc add handlers to DefaultServeMux: - * - * ``` - * http.Handle("/foo", fooHandler) - * - * http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { - * fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) - * }) - * - * log.Fatal(http.ListenAndServe(":8080", nil)) - * ``` - * - * More control over the server's behavior is available by creating a - * custom Server: - * - * ``` - * s := &http.Server{ - * Addr: ":8080", - * Handler: myHandler, - * ReadTimeout: 10 * time.Second, - * WriteTimeout: 10 * time.Second, - * MaxHeaderBytes: 1 << 20, - * } - * log.Fatal(s.ListenAndServe()) - * ``` - * - * # HTTP/2 - * - * Starting with Go 1.6, the http package has transparent support for the - * HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 - * can do so by setting Transport.TLSNextProto (for clients) or - * Server.TLSNextProto (for servers) to a non-nil, empty - * map. Alternatively, the following GODEBUG settings are - * currently supported: - * - * ``` - * GODEBUG=http2client=0 # disable HTTP/2 client support - * GODEBUG=http2server=0 # disable HTTP/2 server support - * GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs - * GODEBUG=http2debug=2 # ... even more verbose, with frame dumps - * ``` - * - * Please report any issues before disabling HTTP/2 support: https://golang.org/s/http2bug - * - * The http package's Transport and Server both automatically enable - * HTTP/2 support for simple configurations. To enable HTTP/2 for more - * complex configurations, to use lower-level HTTP/2 features, or to use - * a newer version of Go's http2 package, import "golang.org/x/net/http2" - * directly and use its ConfigureTransport and/or ConfigureServer - * functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 - * package takes precedence over the net/http package's built-in HTTP/2 - * support. - */ -namespace http { - // @ts-ignore - import mathrand = rand - // @ts-ignore - import urlpkg = url - /** - * A Request represents an HTTP request received by a server - * or to be sent by a client. - * - * The field semantics differ slightly between client and server - * usage. In addition to the notes on the fields below, see the - * documentation for Request.Write and RoundTripper. - */ - interface Request { + interface DB { /** - * Method specifies the HTTP method (GET, POST, PUT, etc.). - * For client requests, an empty string means GET. + * PrepareContext creates a prepared statement for later queries or executions. + * Multiple queries or executions may be run concurrently from the + * returned statement. + * The caller must call the statement's [*Stmt.Close] method + * when the statement is no longer needed. * - * Go's HTTP client does not support sending a request with - * the CONNECT method. See the documentation on Transport for - * details. + * The provided context is used for the preparation of the statement, not for the + * execution of the statement. */ - method: string + prepareContext(ctx: context.Context, query: string): (Stmt) + } + interface DB { /** - * URL specifies either the URI being requested (for server - * requests) or the URL to access (for client requests). + * Prepare creates a prepared statement for later queries or executions. + * Multiple queries or executions may be run concurrently from the + * returned statement. + * The caller must call the statement's [*Stmt.Close] method + * when the statement is no longer needed. * - * For server requests, the URL is parsed from the URI - * supplied on the Request-Line as stored in RequestURI. For - * most requests, fields other than Path and RawQuery will be - * empty. (See RFC 7230, Section 5.3) - * - * For client requests, the URL's Host specifies the server to - * connect to, while the Request's Host field optionally - * specifies the Host header value to send in the HTTP - * request. + * Prepare uses [context.Background] internally; to specify the context, use + * [DB.PrepareContext]. */ - url?: url.URL + prepare(query: string): (Stmt) + } + interface DB { /** - * The protocol version for incoming server requests. - * - * For client requests, these fields are ignored. The HTTP - * client code always uses either HTTP/1.1 or HTTP/2. - * See the docs on Transport for details. + * ExecContext executes a query without returning any rows. + * The args are for any placeholder parameters in the query. */ - proto: string // "HTTP/1.0" - protoMajor: number // 1 - protoMinor: number // 0 + execContext(ctx: context.Context, query: string, ...args: any[]): Result + } + interface DB { /** - * Header contains the request header fields either received - * by the server or to be sent by the client. - * - * If a server received a request with header lines, - * - * ``` - * Host: example.com - * accept-encoding: gzip, deflate - * Accept-Language: en-us - * fOO: Bar - * foo: two - * ``` - * - * then - * - * ``` - * Header = map[string][]string{ - * "Accept-Encoding": {"gzip, deflate"}, - * "Accept-Language": {"en-us"}, - * "Foo": {"Bar", "two"}, - * } - * ``` - * - * For incoming requests, the Host header is promoted to the - * Request.Host field and removed from the Header map. - * - * HTTP defines that header names are case-insensitive. The - * request parser implements this by using CanonicalHeaderKey, - * making the first character and any characters following a - * hyphen uppercase and the rest lowercase. + * Exec executes a query without returning any rows. + * The args are for any placeholder parameters in the query. * - * For client requests, certain headers such as Content-Length - * and Connection are automatically written when needed and - * values in Header may be ignored. See the documentation - * for the Request.Write method. + * Exec uses [context.Background] internally; to specify the context, use + * [DB.ExecContext]. */ - header: Header + exec(query: string, ...args: any[]): Result + } + interface DB { /** - * Body is the request's body. - * - * For client requests, a nil body means the request has no - * body, such as a GET request. The HTTP Client's Transport - * is responsible for calling the Close method. - * - * For server requests, the Request Body is always non-nil - * but will return EOF immediately when no body is present. - * The Server will close the request body. The ServeHTTP - * Handler does not need to. - * - * Body must allow Read to be called concurrently with Close. - * In particular, calling Close should unblock a Read waiting - * for input. + * QueryContext executes a query that returns rows, typically a SELECT. + * The args are for any placeholder parameters in the query. */ - body: io.ReadCloser + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) + } + interface DB { /** - * GetBody defines an optional func to return a new copy of - * Body. It is used for client requests when a redirect requires - * reading the body more than once. Use of GetBody still - * requires setting Body. + * Query executes a query that returns rows, typically a SELECT. + * The args are for any placeholder parameters in the query. * - * For server requests, it is unused. + * Query uses [context.Background] internally; to specify the context, use + * [DB.QueryContext]. */ - getBody: () => io.ReadCloser + query(query: string, ...args: any[]): (Rows) + } + interface DB { /** - * ContentLength records the length of the associated content. - * The value -1 indicates that the length is unknown. - * Values >= 0 indicate that the given number of bytes may - * be read from Body. - * - * For client requests, a value of 0 with a non-nil Body is - * also treated as unknown. + * QueryRowContext executes a query that is expected to return at most one row. + * QueryRowContext always returns a non-nil value. Errors are deferred until + * [Row]'s Scan method is called. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, [*Row.Scan] scans the first selected row and discards + * the rest. */ - contentLength: number + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) + } + interface DB { /** - * TransferEncoding lists the transfer encodings from outermost to - * innermost. An empty list denotes the "identity" encoding. - * TransferEncoding can usually be ignored; chunked encoding is - * automatically added and removed as necessary when sending and - * receiving requests. + * QueryRow executes a query that is expected to return at most one row. + * QueryRow always returns a non-nil value. Errors are deferred until + * [Row]'s Scan method is called. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, [*Row.Scan] scans the first selected row and discards + * the rest. + * + * QueryRow uses [context.Background] internally; to specify the context, use + * [DB.QueryRowContext]. */ - transferEncoding: Array + queryRow(query: string, ...args: any[]): (Row) + } + interface DB { /** - * Close indicates whether to close the connection after - * replying to this request (for servers) or after sending this - * request and reading its response (for clients). + * BeginTx starts a transaction. * - * For server requests, the HTTP server handles this automatically - * and this field is not needed by Handlers. + * The provided context is used until the transaction is committed or rolled back. + * If the context is canceled, the sql package will roll back + * the transaction. [Tx.Commit] will return an error if the context provided to + * BeginTx is canceled. * - * For client requests, setting this field prevents re-use of - * TCP connections between requests to the same hosts, as if - * Transport.DisableKeepAlives were set. + * The provided [TxOptions] is optional and may be nil if defaults should be used. + * If a non-default isolation level is used that the driver doesn't support, + * an error will be returned. */ - close: boolean + beginTx(ctx: context.Context, opts: TxOptions): (Tx) + } + interface DB { /** - * For server requests, Host specifies the host on which the - * URL is sought. For HTTP/1 (per RFC 7230, section 5.4), this - * is either the value of the "Host" header or the host name - * given in the URL itself. For HTTP/2, it is the value of the - * ":authority" pseudo-header field. - * It may be of the form "host:port". For international domain - * names, Host may be in Punycode or Unicode form. Use - * golang.org/x/net/idna to convert it to either format if - * needed. - * To prevent DNS rebinding attacks, server Handlers should - * validate that the Host header has a value for which the - * Handler considers itself authoritative. The included - * ServeMux supports patterns registered to particular host - * names and thus protects its registered Handlers. + * Begin starts a transaction. The default isolation level is dependent on + * the driver. * - * For client requests, Host optionally overrides the Host - * header to send. If empty, the Request.Write method uses - * the value of URL.Host. Host may contain an international - * domain name. + * Begin uses [context.Background] internally; to specify the context, use + * [DB.BeginTx]. */ - host: string + begin(): (Tx) + } + interface DB { /** - * Form contains the parsed form data, including both the URL - * field's query parameters and the PATCH, POST, or PUT form data. - * This field is only available after ParseForm is called. - * The HTTP client ignores Form and uses Body instead. + * Driver returns the database's underlying driver. */ - form: url.Values + driver(): any + } + interface DB { /** - * PostForm contains the parsed form data from PATCH, POST - * or PUT body parameters. + * Conn returns a single connection by either opening a new connection + * or returning an existing connection from the connection pool. Conn will + * block until either a connection is returned or ctx is canceled. + * Queries run on the same Conn will be run in the same database session. * - * This field is only available after ParseForm is called. - * The HTTP client ignores PostForm and uses Body instead. + * Every Conn must be returned to the database pool after use by + * calling [Conn.Close]. */ - postForm: url.Values + conn(ctx: context.Context): (Conn) + } + /** + * Tx is an in-progress database transaction. + * + * A transaction must end with a call to [Tx.Commit] or [Tx.Rollback]. + * + * After a call to [Tx.Commit] or [Tx.Rollback], all operations on the + * transaction fail with [ErrTxDone]. + * + * The statements prepared for a transaction by calling + * the transaction's [Tx.Prepare] or [Tx.Stmt] methods are closed + * by the call to [Tx.Commit] or [Tx.Rollback]. + */ + interface Tx { + } + interface Tx { /** - * MultipartForm is the parsed multipart form, including file uploads. - * This field is only available after ParseMultipartForm is called. - * The HTTP client ignores MultipartForm and uses Body instead. + * Commit commits the transaction. */ - multipartForm?: multipart.Form + commit(): void + } + interface Tx { /** - * Trailer specifies additional headers that are sent after the request - * body. + * Rollback aborts the transaction. + */ + rollback(): void + } + interface Tx { + /** + * PrepareContext creates a prepared statement for use within a transaction. * - * For server requests, the Trailer map initially contains only the - * trailer keys, with nil values. (The client declares which trailers it - * will later send.) While the handler is reading from Body, it must - * not reference Trailer. After reading from Body returns EOF, Trailer - * can be read again and will contain non-nil values, if they were sent - * by the client. + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. * - * For client requests, Trailer must be initialized to a map containing - * the trailer keys to later send. The values may be nil or their final - * values. The ContentLength must be 0 or -1, to send a chunked request. - * After the HTTP request is sent the map values can be updated while - * the request body is read. Once the body returns EOF, the caller must - * not mutate Trailer. + * To use an existing prepared statement on this transaction, see [Tx.Stmt]. * - * Few HTTP clients, servers, or proxies support HTTP trailers. + * The provided context will be used for the preparation of the context, not + * for the execution of the returned statement. The returned statement + * will run in the transaction context. */ - trailer: Header + prepareContext(ctx: context.Context, query: string): (Stmt) + } + interface Tx { /** - * RemoteAddr allows HTTP servers and other software to record - * the network address that sent the request, usually for - * logging. This field is not filled in by ReadRequest and - * has no defined format. The HTTP server in this package - * sets RemoteAddr to an "IP:port" address before invoking a - * handler. - * This field is ignored by the HTTP client. + * Prepare creates a prepared statement for use within a transaction. + * + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. + * + * To use an existing prepared statement on this transaction, see [Tx.Stmt]. + * + * Prepare uses [context.Background] internally; to specify the context, use + * [Tx.PrepareContext]. */ - remoteAddr: string + prepare(query: string): (Stmt) + } + interface Tx { /** - * RequestURI is the unmodified request-target of the - * Request-Line (RFC 7230, Section 3.1.1) as sent by the client - * to a server. Usually the URL field should be used instead. - * It is an error to set this field in an HTTP client request. - */ - requestURI: string - /** - * TLS allows HTTP servers and other software to record - * information about the TLS connection on which the request - * was received. This field is not filled in by ReadRequest. - * The HTTP server in this package sets the field for - * TLS-enabled connections before invoking a handler; - * otherwise it leaves the field nil. - * This field is ignored by the HTTP client. + * StmtContext returns a transaction-specific prepared statement from + * an existing statement. + * + * Example: + * + * ``` + * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") + * ... + * tx, err := db.Begin() + * ... + * res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203) + * ``` + * + * The provided context is used for the preparation of the statement, not for the + * execution of the statement. + * + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. */ - tls?: any + stmtContext(ctx: context.Context, stmt: Stmt): (Stmt) + } + interface Tx { /** - * Cancel is an optional channel whose closure indicates that the client - * request should be regarded as canceled. Not all implementations of - * RoundTripper may support Cancel. + * Stmt returns a transaction-specific prepared statement from + * an existing statement. * - * For server requests, this field is not applicable. + * Example: * - * Deprecated: Set the Request's context with NewRequestWithContext - * instead. If a Request's Cancel field and context are both - * set, it is undefined whether Cancel is respected. + * ``` + * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") + * ... + * tx, err := db.Begin() + * ... + * res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203) + * ``` + * + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. + * + * Stmt uses [context.Background] internally; to specify the context, use + * [Tx.StmtContext]. */ - cancel: undefined + stmt(stmt: Stmt): (Stmt) + } + interface Tx { /** - * Response is the redirect response which caused this request - * to be created. This field is only populated during client - * redirects. + * ExecContext executes a query that doesn't return rows. + * For example: an INSERT and UPDATE. */ - response?: Response + execContext(ctx: context.Context, query: string, ...args: any[]): Result } - interface Request { + interface Tx { /** - * Context returns the request's context. To change the context, use - * Clone or WithContext. - * - * The returned context is always non-nil; it defaults to the - * background context. - * - * For outgoing client requests, the context controls cancellation. + * Exec executes a query that doesn't return rows. + * For example: an INSERT and UPDATE. * - * For incoming server requests, the context is canceled when the - * client's connection closes, the request is canceled (with HTTP/2), - * or when the ServeHTTP method returns. + * Exec uses [context.Background] internally; to specify the context, use + * [Tx.ExecContext]. */ - context(): context.Context + exec(query: string, ...args: any[]): Result } - interface Request { + interface Tx { /** - * WithContext returns a shallow copy of r with its context changed - * to ctx. The provided ctx must be non-nil. - * - * For outgoing client request, the context controls the entire - * lifetime of a request and its response: obtaining a connection, - * sending the request, and reading the response headers and body. - * - * To create a new request with a context, use NewRequestWithContext. - * To make a deep copy of a request with a new context, use Request.Clone. + * QueryContext executes a query that returns rows, typically a SELECT. */ - withContext(ctx: context.Context): (Request) + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) } - interface Request { + interface Tx { /** - * Clone returns a deep copy of r with its context changed to ctx. - * The provided ctx must be non-nil. + * Query executes a query that returns rows, typically a SELECT. * - * For an outgoing client request, the context controls the entire - * lifetime of a request and its response: obtaining a connection, - * sending the request, and reading the response headers and body. + * Query uses [context.Background] internally; to specify the context, use + * [Tx.QueryContext]. */ - clone(ctx: context.Context): (Request) + query(query: string, ...args: any[]): (Rows) } - interface Request { + interface Tx { /** - * ProtoAtLeast reports whether the HTTP protocol used - * in the request is at least major.minor. + * QueryRowContext executes a query that is expected to return at most one row. + * QueryRowContext always returns a non-nil value. Errors are deferred until + * [Row]'s Scan method is called. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, the [*Row.Scan] scans the first selected row and discards + * the rest. */ - protoAtLeast(major: number, minor: number): boolean + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) } - interface Request { + interface Tx { /** - * UserAgent returns the client's User-Agent, if sent in the request. + * QueryRow executes a query that is expected to return at most one row. + * QueryRow always returns a non-nil value. Errors are deferred until + * [Row]'s Scan method is called. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, the [*Row.Scan] scans the first selected row and discards + * the rest. + * + * QueryRow uses [context.Background] internally; to specify the context, use + * [Tx.QueryRowContext]. */ - userAgent(): string + queryRow(query: string, ...args: any[]): (Row) } - interface Request { + /** + * Stmt is a prepared statement. + * A Stmt is safe for concurrent use by multiple goroutines. + * + * If a Stmt is prepared on a [Tx] or [Conn], it will be bound to a single + * underlying connection forever. If the [Tx] or [Conn] closes, the Stmt will + * become unusable and all operations will return an error. + * If a Stmt is prepared on a [DB], it will remain usable for the lifetime of the + * [DB]. When the Stmt needs to execute on a new underlying connection, it will + * prepare itself on the new connection automatically. + */ + interface Stmt { + } + interface Stmt { /** - * Cookies parses and returns the HTTP cookies sent with the request. + * ExecContext executes a prepared statement with the given arguments and + * returns a [Result] summarizing the effect of the statement. */ - cookies(): Array<(Cookie | undefined)> + execContext(ctx: context.Context, ...args: any[]): Result } - interface Request { + interface Stmt { /** - * Cookie returns the named cookie provided in the request or - * ErrNoCookie if not found. - * If multiple cookies match the given name, only one cookie will - * be returned. + * Exec executes a prepared statement with the given arguments and + * returns a [Result] summarizing the effect of the statement. + * + * Exec uses [context.Background] internally; to specify the context, use + * [Stmt.ExecContext]. */ - cookie(name: string): (Cookie) + exec(...args: any[]): Result } - interface Request { + interface Stmt { /** - * AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, - * AddCookie does not attach more than one Cookie header field. That - * means all cookies, if any, are written into the same line, - * separated by semicolon. - * AddCookie only sanitizes c's name and value, and does not sanitize - * a Cookie header already present in the request. + * QueryContext executes a prepared query statement with the given arguments + * and returns the query results as a [*Rows]. */ - addCookie(c: Cookie): void + queryContext(ctx: context.Context, ...args: any[]): (Rows) } - interface Request { + interface Stmt { /** - * Referer returns the referring URL, if sent in the request. + * Query executes a prepared query statement with the given arguments + * and returns the query results as a *Rows. * - * Referer is misspelled as in the request itself, a mistake from the - * earliest days of HTTP. This value can also be fetched from the - * Header map as Header["Referer"]; the benefit of making it available - * as a method is that the compiler can diagnose programs that use the - * alternate (correct English) spelling req.Referrer() but cannot - * diagnose programs that use Header["Referrer"]. + * Query uses [context.Background] internally; to specify the context, use + * [Stmt.QueryContext]. */ - referer(): string + query(...args: any[]): (Rows) } - interface Request { + interface Stmt { /** - * MultipartReader returns a MIME multipart reader if this is a - * multipart/form-data or a multipart/mixed POST request, else returns nil and an error. - * Use this function instead of ParseMultipartForm to - * process the request body as a stream. + * QueryRowContext executes a prepared query statement with the given arguments. + * If an error occurs during the execution of the statement, that error will + * be returned by a call to Scan on the returned [*Row], which is always non-nil. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, the [*Row.Scan] scans the first selected row and discards + * the rest. */ - multipartReader(): (multipart.Reader) + queryRowContext(ctx: context.Context, ...args: any[]): (Row) } - interface Request { + interface Stmt { /** - * Write writes an HTTP/1.1 request, which is the header and body, in wire format. - * This method consults the following fields of the request: + * QueryRow executes a prepared query statement with the given arguments. + * If an error occurs during the execution of the statement, that error will + * be returned by a call to Scan on the returned [*Row], which is always non-nil. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, the [*Row.Scan] scans the first selected row and discards + * the rest. + * + * Example usage: * * ``` - * Host - * URL - * Method (defaults to "GET") - * Header - * ContentLength - * TransferEncoding - * Body + * var name string + * err := nameByUseridStmt.QueryRow(id).Scan(&name) * ``` * - * If Body is present, Content-Length is <= 0 and TransferEncoding - * hasn't been set to "identity", Write adds "Transfer-Encoding: - * chunked" to the header. Body is closed after it is sent. + * QueryRow uses [context.Background] internally; to specify the context, use + * [Stmt.QueryRowContext]. */ - write(w: io.Writer): void + queryRow(...args: any[]): (Row) } - interface Request { + interface Stmt { /** - * WriteProxy is like Write but writes the request in the form - * expected by an HTTP proxy. In particular, WriteProxy writes the - * initial Request-URI line of the request with an absolute URI, per - * section 5.3 of RFC 7230, including the scheme and host. - * In either case, WriteProxy also writes a Host header, using - * either r.Host or r.URL.Host. + * Close closes the statement. */ - writeProxy(w: io.Writer): void + close(): void } - interface Request { - /** - * BasicAuth returns the username and password provided in the request's - * Authorization header, if the request uses HTTP Basic Authentication. - * See RFC 2617, Section 2. - */ - basicAuth(): [string, boolean] + /** + * Rows is the result of a query. Its cursor starts before the first row + * of the result set. Use [Rows.Next] to advance from row to row. + */ + interface Rows { } - interface Request { + interface Rows { /** - * SetBasicAuth sets the request's Authorization header to use HTTP - * Basic Authentication with the provided username and password. - * - * With HTTP Basic Authentication the provided username and password - * are not encrypted. It should generally only be used in an HTTPS - * request. + * Next prepares the next result row for reading with the [Rows.Scan] method. It + * returns true on success, or false if there is no next result row or an error + * happened while preparing it. [Rows.Err] should be consulted to distinguish between + * the two cases. * - * The username may not contain a colon. Some protocols may impose - * additional requirements on pre-escaping the username and - * password. For instance, when used with OAuth2, both arguments must - * be URL encoded first with url.QueryEscape. + * Every call to [Rows.Scan], even the first one, must be preceded by a call to [Rows.Next]. */ - setBasicAuth(username: string, password: string): void + next(): boolean } - interface Request { + interface Rows { /** - * ParseForm populates r.Form and r.PostForm. - * - * For all requests, ParseForm parses the raw query from the URL and updates - * r.Form. - * - * For POST, PUT, and PATCH requests, it also reads the request body, parses it - * as a form and puts the results into both r.PostForm and r.Form. Request body - * parameters take precedence over URL query string values in r.Form. - * - * If the request Body's size has not already been limited by MaxBytesReader, - * the size is capped at 10MB. - * - * For other HTTP methods, or when the Content-Type is not - * application/x-www-form-urlencoded, the request Body is not read, and - * r.PostForm is initialized to a non-nil, empty value. + * NextResultSet prepares the next result set for reading. It reports whether + * there is further result sets, or false if there is no further result set + * or if there is an error advancing to it. The [Rows.Err] method should be consulted + * to distinguish between the two cases. * - * ParseMultipartForm calls ParseForm automatically. - * ParseForm is idempotent. + * After calling NextResultSet, the [Rows.Next] method should always be called before + * scanning. If there are further result sets they may not have rows in the result + * set. */ - parseForm(): void + nextResultSet(): boolean } - interface Request { - /** - * ParseMultipartForm parses a request body as multipart/form-data. - * The whole request body is parsed and up to a total of maxMemory bytes of - * its file parts are stored in memory, with the remainder stored on - * disk in temporary files. - * ParseMultipartForm calls ParseForm if necessary. - * If ParseForm returns an error, ParseMultipartForm returns it but also - * continues parsing the request body. - * After one call to ParseMultipartForm, subsequent calls have no effect. - */ - parseMultipartForm(maxMemory: number): void - } - interface Request { + interface Rows { /** - * FormValue returns the first value for the named component of the query. - * POST and PUT body parameters take precedence over URL query string values. - * FormValue calls ParseMultipartForm and ParseForm if necessary and ignores - * any errors returned by these functions. - * If key is not present, FormValue returns the empty string. - * To access multiple values of the same key, call ParseForm and - * then inspect Request.Form directly. + * Err returns the error, if any, that was encountered during iteration. + * Err may be called after an explicit or implicit [Rows.Close]. */ - formValue(key: string): string + err(): void } - interface Request { + interface Rows { /** - * PostFormValue returns the first value for the named component of the POST, - * PATCH, or PUT request body. URL query parameters are ignored. - * PostFormValue calls ParseMultipartForm and ParseForm if necessary and ignores - * any errors returned by these functions. - * If key is not present, PostFormValue returns the empty string. + * Columns returns the column names. + * Columns returns an error if the rows are closed. */ - postFormValue(key: string): string + columns(): Array } - interface Request { + interface Rows { /** - * FormFile returns the first file for the provided form key. - * FormFile calls ParseMultipartForm and ParseForm if necessary. + * ColumnTypes returns column information such as column type, length, + * and nullable. Some information may not be available from some drivers. */ - formFile(key: string): [multipart.File, (multipart.FileHeader)] + columnTypes(): Array<(ColumnType | undefined)> } - /** - * A ResponseWriter interface is used by an HTTP handler to - * construct an HTTP response. - * - * A ResponseWriter may not be used after the Handler.ServeHTTP method - * has returned. - */ - interface ResponseWriter { - [key:string]: any; + interface Rows { /** - * Header returns the header map that will be sent by - * WriteHeader. The Header map also is the mechanism with which - * Handlers can set HTTP trailers. + * Scan copies the columns in the current row into the values pointed + * at by dest. The number of values in dest must be the same as the + * number of columns in [Rows]. * - * Changing the header map after a call to WriteHeader (or - * Write) has no effect unless the HTTP status code was of the - * 1xx class or the modified headers are trailers. + * Scan converts columns read from the database into the following + * common Go types and special types provided by the sql package: * - * There are two ways to set Trailers. The preferred way is to - * predeclare in the headers which trailers you will later - * send by setting the "Trailer" header to the names of the - * trailer keys which will come later. In this case, those - * keys of the Header map are treated as if they were - * trailers. See the example. The second way, for trailer - * keys not known to the Handler until after the first Write, - * is to prefix the Header map keys with the TrailerPrefix - * constant value. See TrailerPrefix. + * ``` + * *string + * *[]byte + * *int, *int8, *int16, *int32, *int64 + * *uint, *uint8, *uint16, *uint32, *uint64 + * *bool + * *float32, *float64 + * *interface{} + * *RawBytes + * *Rows (cursor value) + * any type implementing Scanner (see Scanner docs) + * ``` * - * To suppress automatic response headers (such as "Date"), set - * their value to nil. - */ - header(): Header - /** - * Write writes the data to the connection as part of an HTTP reply. + * In the most simple case, if the type of the value from the source + * column is an integer, bool or string type T and dest is of type *T, + * Scan simply assigns the value through the pointer. * - * If WriteHeader has not yet been called, Write calls - * WriteHeader(http.StatusOK) before writing the data. If the Header - * does not contain a Content-Type line, Write adds a Content-Type set - * to the result of passing the initial 512 bytes of written data to - * DetectContentType. Additionally, if the total size of all written - * data is under a few KB and there are no Flush calls, the - * Content-Length header is added automatically. + * Scan also converts between string and numeric types, as long as no + * information would be lost. While Scan stringifies all numbers + * scanned from numeric database columns into *string, scans into + * numeric types are checked for overflow. For example, a float64 with + * value 300 or a string with value "300" can scan into a uint16, but + * not into a uint8, though float64(255) or "255" can scan into a + * uint8. One exception is that scans of some float64 numbers to + * strings may lose information when stringifying. In general, scan + * floating point columns into *float64. * - * Depending on the HTTP protocol version and the client, calling - * Write or WriteHeader may prevent future reads on the - * Request.Body. For HTTP/1.x requests, handlers should read any - * needed request body data before writing the response. Once the - * headers have been flushed (due to either an explicit Flusher.Flush - * call or writing enough data to trigger a flush), the request body - * may be unavailable. For HTTP/2 requests, the Go HTTP server permits - * handlers to continue to read the request body while concurrently - * writing the response. However, such behavior may not be supported - * by all HTTP/2 clients. Handlers should read before writing if - * possible to maximize compatibility. - */ - write(_arg0: string|Array): number - /** - * WriteHeader sends an HTTP response header with the provided - * status code. + * If a dest argument has type *[]byte, Scan saves in that argument a + * copy of the corresponding data. The copy is owned by the caller and + * can be modified and held indefinitely. The copy can be avoided by + * using an argument of type [*RawBytes] instead; see the documentation + * for [RawBytes] for restrictions on its use. * - * If WriteHeader is not called explicitly, the first call to Write - * will trigger an implicit WriteHeader(http.StatusOK). - * Thus explicit calls to WriteHeader are mainly used to - * send error codes or 1xx informational responses. + * If an argument has type *interface{}, Scan copies the value + * provided by the underlying driver without conversion. When scanning + * from a source value of type []byte to *interface{}, a copy of the + * slice is made and the caller owns the result. * - * The provided code must be a valid HTTP 1xx-5xx status code. - * Any number of 1xx headers may be written, followed by at most - * one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx - * headers may be buffered. Use the Flusher interface to send - * buffered data. The header map is cleared when 2xx-5xx headers are - * sent, but not with 1xx headers. + * Source values of type [time.Time] may be scanned into values of type + * *time.Time, *interface{}, *string, or *[]byte. When converting to + * the latter two, [time.RFC3339Nano] is used. * - * The server will automatically send a 100 (Continue) header - * on the first read from the request body if the request has - * an "Expect: 100-continue" header. - */ - writeHeader(statusCode: number): void - } - /** - * A Server defines parameters for running an HTTP server. - * The zero value for Server is a valid configuration. - */ - interface Server { - /** - * Addr optionally specifies the TCP address for the server to listen on, - * in the form "host:port". If empty, ":http" (port 80) is used. - * The service names are defined in RFC 6335 and assigned by IANA. - * See net.Dial for details of the address format. - */ - addr: string - handler: Handler // handler to invoke, http.DefaultServeMux if nil - /** - * DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler, - * otherwise responds with 200 OK and Content-Length: 0. - */ - disableGeneralOptionsHandler: boolean - /** - * TLSConfig optionally provides a TLS configuration for use - * by ServeTLS and ListenAndServeTLS. Note that this value is - * cloned by ServeTLS and ListenAndServeTLS, so it's not - * possible to modify the configuration with methods like - * tls.Config.SetSessionTicketKeys. To use - * SetSessionTicketKeys, use Server.Serve with a TLS Listener - * instead. - */ - tlsConfig?: any - /** - * ReadTimeout is the maximum duration for reading the entire - * request, including the body. A zero or negative value means - * there will be no timeout. + * Source values of type bool may be scanned into types *bool, + * *interface{}, *string, *[]byte, or [*RawBytes]. * - * Because ReadTimeout does not let Handlers make per-request - * decisions on each request body's acceptable deadline or - * upload rate, most users will prefer to use - * ReadHeaderTimeout. It is valid to use them both. - */ - readTimeout: time.Duration - /** - * ReadHeaderTimeout is the amount of time allowed to read - * request headers. The connection's read deadline is reset - * after reading the headers and the Handler can decide what - * is considered too slow for the body. If ReadHeaderTimeout - * is zero, the value of ReadTimeout is used. If both are - * zero, there is no timeout. - */ - readHeaderTimeout: time.Duration - /** - * WriteTimeout is the maximum duration before timing out - * writes of the response. It is reset whenever a new - * request's header is read. Like ReadTimeout, it does not - * let Handlers make decisions on a per-request basis. - * A zero or negative value means there will be no timeout. - */ - writeTimeout: time.Duration - /** - * IdleTimeout is the maximum amount of time to wait for the - * next request when keep-alives are enabled. If IdleTimeout - * is zero, the value of ReadTimeout is used. If both are - * zero, there is no timeout. - */ - idleTimeout: time.Duration - /** - * MaxHeaderBytes controls the maximum number of bytes the - * server will read parsing the request header's keys and - * values, including the request line. It does not limit the - * size of the request body. - * If zero, DefaultMaxHeaderBytes is used. - */ - maxHeaderBytes: number - /** - * TLSNextProto optionally specifies a function to take over - * ownership of the provided TLS connection when an ALPN - * protocol upgrade has occurred. The map key is the protocol - * name negotiated. The Handler argument should be used to - * handle HTTP requests and will initialize the Request's TLS - * and RemoteAddr if not already set. The connection is - * automatically closed when the function returns. - * If TLSNextProto is not nil, HTTP/2 support is not enabled - * automatically. + * For scanning into *bool, the source may be true, false, 1, 0, or + * string inputs parseable by [strconv.ParseBool]. + * + * Scan can also convert a cursor returned from a query, such as + * "select cursor(select * from my_table) from dual", into a + * [*Rows] value that can itself be scanned from. The parent + * select query will close any cursor [*Rows] if the parent [*Rows] is closed. + * + * If any of the first arguments implementing [Scanner] returns an error, + * that error will be wrapped in the returned error. */ - tlsNextProto: _TygojaDict + scan(...dest: any[]): void + } + interface Rows { /** - * ConnState specifies an optional callback function that is - * called when a client connection changes state. See the - * ConnState type and associated constants for details. + * Close closes the [Rows], preventing further enumeration. If [Rows.Next] is called + * and returns false and there are no further result sets, + * the [Rows] are closed automatically and it will suffice to check the + * result of [Rows.Err]. Close is idempotent and does not affect the result of [Rows.Err]. */ - connState: (_arg0: net.Conn, _arg1: ConnState) => void + close(): void + } + /** + * A Result summarizes an executed SQL command. + */ + interface Result { + [key:string]: any; /** - * ErrorLog specifies an optional logger for errors accepting - * connections, unexpected behavior from handlers, and - * underlying FileSystem errors. - * If nil, logging is done via the log package's standard logger. + * LastInsertId returns the integer generated by the database + * in response to a command. Typically this will be from an + * "auto increment" column when inserting a new row. Not all + * databases support this feature, and the syntax of such + * statements varies. */ - errorLog?: any + lastInsertId(): number /** - * BaseContext optionally specifies a function that returns - * the base context for incoming requests on this server. - * The provided Listener is the specific Listener that's - * about to start accepting requests. - * If BaseContext is nil, the default is context.Background(). - * If non-nil, it must return a non-nil context. + * RowsAffected returns the number of rows affected by an + * update, insert, or delete. Not every database or database + * driver may support this. */ - baseContext: (_arg0: net.Listener) => context.Context - /** - * ConnContext optionally specifies a function that modifies - * the context used for a new connection c. The provided ctx - * is derived from the base context and has a ServerContextKey - * value. - */ - connContext: (ctx: context.Context, c: net.Conn) => context.Context + rowsAffected(): number } - interface Server { +} + +/** + * Package exec runs external commands. It wraps os.StartProcess to make it + * easier to remap stdin and stdout, connect I/O with pipes, and do other + * adjustments. + * + * Unlike the "system" library call from C and other languages, the + * os/exec package intentionally does not invoke the system shell and + * does not expand any glob patterns or handle other expansions, + * pipelines, or redirections typically done by shells. The package + * behaves more like C's "exec" family of functions. To expand glob + * patterns, either call the shell directly, taking care to escape any + * dangerous input, or use the path/filepath package's Glob function. + * To expand environment variables, use package os's ExpandEnv. + * + * Note that the examples in this package assume a Unix system. + * They may not run on Windows, and they do not run in the Go Playground + * used by golang.org and godoc.org. + * + * # Executables in the current directory + * + * The functions Command and LookPath look for a program + * in the directories listed in the current path, following the + * conventions of the host operating system. + * Operating systems have for decades included the current + * directory in this search, sometimes implicitly and sometimes + * configured explicitly that way by default. + * Modern practice is that including the current directory + * is usually unexpected and often leads to security problems. + * + * To avoid those security problems, as of Go 1.19, this package will not resolve a program + * using an implicit or explicit path entry relative to the current directory. + * That is, if you run exec.LookPath("go"), it will not successfully return + * ./go on Unix nor .\go.exe on Windows, no matter how the path is configured. + * Instead, if the usual path algorithms would result in that answer, + * these functions return an error err satisfying errors.Is(err, ErrDot). + * + * For example, consider these two program snippets: + * + * ``` + * path, err := exec.LookPath("prog") + * if err != nil { + * log.Fatal(err) + * } + * use(path) + * ``` + * + * and + * + * ``` + * cmd := exec.Command("prog") + * if err := cmd.Run(); err != nil { + * log.Fatal(err) + * } + * ``` + * + * These will not find and run ./prog or .\prog.exe, + * no matter how the current path is configured. + * + * Code that always wants to run a program from the current directory + * can be rewritten to say "./prog" instead of "prog". + * + * Code that insists on including results from relative path entries + * can instead override the error using an errors.Is check: + * + * ``` + * path, err := exec.LookPath("prog") + * if errors.Is(err, exec.ErrDot) { + * err = nil + * } + * if err != nil { + * log.Fatal(err) + * } + * use(path) + * ``` + * + * and + * + * ``` + * cmd := exec.Command("prog") + * if errors.Is(cmd.Err, exec.ErrDot) { + * cmd.Err = nil + * } + * if err := cmd.Run(); err != nil { + * log.Fatal(err) + * } + * ``` + * + * Setting the environment variable GODEBUG=execerrdot=0 + * disables generation of ErrDot entirely, temporarily restoring the pre-Go 1.19 + * behavior for programs that are unable to apply more targeted fixes. + * A future version of Go may remove support for this variable. + * + * Before adding such overrides, make sure you understand the + * security implications of doing so. + * See https://go.dev/blog/path-security for more information. + */ +namespace exec { + /** + * Cmd represents an external command being prepared or run. + * + * A Cmd cannot be reused after calling its Run, Output or CombinedOutput + * methods. + */ + interface Cmd { /** - * Close immediately closes all active net.Listeners and any - * connections in state StateNew, StateActive, or StateIdle. For a - * graceful shutdown, use Shutdown. - * - * Close does not attempt to close (and does not even know about) - * any hijacked connections, such as WebSockets. + * Path is the path of the command to run. * - * Close returns any error returned from closing the Server's - * underlying Listener(s). + * This is the only field that must be set to a non-zero + * value. If Path is relative, it is evaluated relative + * to Dir. */ - close(): void - } - interface Server { + path: string /** - * Shutdown gracefully shuts down the server without interrupting any - * active connections. Shutdown works by first closing all open - * listeners, then closing all idle connections, and then waiting - * indefinitely for connections to return to idle and then shut down. - * If the provided context expires before the shutdown is complete, - * Shutdown returns the context's error, otherwise it returns any - * error returned from closing the Server's underlying Listener(s). - * - * When Shutdown is called, Serve, ListenAndServe, and - * ListenAndServeTLS immediately return ErrServerClosed. Make sure the - * program doesn't exit and waits instead for Shutdown to return. - * - * Shutdown does not attempt to close nor wait for hijacked - * connections such as WebSockets. The caller of Shutdown should - * separately notify such long-lived connections of shutdown and wait - * for them to close, if desired. See RegisterOnShutdown for a way to - * register shutdown notification functions. + * Args holds command line arguments, including the command as Args[0]. + * If the Args field is empty or nil, Run uses {Path}. * - * Once Shutdown has been called on a server, it may not be reused; - * future calls to methods such as Serve will return ErrServerClosed. + * In typical use, both Path and Args are set by calling Command. */ - shutdown(ctx: context.Context): void - } - interface Server { + args: Array /** - * RegisterOnShutdown registers a function to call on Shutdown. - * This can be used to gracefully shutdown connections that have - * undergone ALPN protocol upgrade or that have been hijacked. - * This function should start protocol-specific graceful shutdown, - * but should not wait for shutdown to complete. + * Env specifies the environment of the process. + * Each entry is of the form "key=value". + * If Env is nil, the new process uses the current process's + * environment. + * If Env contains duplicate environment keys, only the last + * value in the slice for each duplicate key is used. + * As a special case on Windows, SYSTEMROOT is always added if + * missing and not explicitly set to the empty string. */ - registerOnShutdown(f: () => void): void - } - interface Server { + env: Array /** - * ListenAndServe listens on the TCP network address srv.Addr and then - * calls Serve to handle requests on incoming connections. - * Accepted connections are configured to enable TCP keep-alives. + * Dir specifies the working directory of the command. + * If Dir is the empty string, Run runs the command in the + * calling process's current directory. + */ + dir: string + /** + * Stdin specifies the process's standard input. * - * If srv.Addr is blank, ":http" is used. + * If Stdin is nil, the process reads from the null device (os.DevNull). + * + * If Stdin is an *os.File, the process's standard input is connected + * directly to that file. * - * ListenAndServe always returns a non-nil error. After Shutdown or Close, - * the returned error is ErrServerClosed. + * Otherwise, during the execution of the command a separate + * goroutine reads from Stdin and delivers that data to the command + * over a pipe. In this case, Wait does not complete until the goroutine + * stops copying, either because it has reached the end of Stdin + * (EOF or a read error), or because writing to the pipe returned an error, + * or because a nonzero WaitDelay was set and expired. */ - listenAndServe(): void - } - interface Server { + stdin: io.Reader /** - * Serve accepts incoming connections on the Listener l, creating a - * new service goroutine for each. The service goroutines read requests and - * then call srv.Handler to reply to them. + * Stdout and Stderr specify the process's standard output and error. * - * HTTP/2 support is only enabled if the Listener returns *tls.Conn - * connections and they were configured with "h2" in the TLS - * Config.NextProtos. + * If either is nil, Run connects the corresponding file descriptor + * to the null device (os.DevNull). * - * Serve always returns a non-nil error and closes l. - * After Shutdown or Close, the returned error is ErrServerClosed. + * If either is an *os.File, the corresponding output from the process + * is connected directly to that file. + * + * Otherwise, during the execution of the command a separate goroutine + * reads from the process over a pipe and delivers that data to the + * corresponding Writer. In this case, Wait does not complete until the + * goroutine reaches EOF or encounters an error or a nonzero WaitDelay + * expires. + * + * If Stdout and Stderr are the same writer, and have a type that can + * be compared with ==, at most one goroutine at a time will call Write. */ - serve(l: net.Listener): void - } - interface Server { + stdout: io.Writer + stderr: io.Writer /** - * ServeTLS accepts incoming connections on the Listener l, creating a - * new service goroutine for each. The service goroutines perform TLS - * setup and then read requests, calling srv.Handler to reply to them. - * - * Files containing a certificate and matching private key for the - * server must be provided if neither the Server's - * TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. - * If the certificate is signed by a certificate authority, the - * certFile should be the concatenation of the server's certificate, - * any intermediates, and the CA's certificate. + * ExtraFiles specifies additional open files to be inherited by the + * new process. It does not include standard input, standard output, or + * standard error. If non-nil, entry i becomes file descriptor 3+i. * - * ServeTLS always returns a non-nil error. After Shutdown or Close, the - * returned error is ErrServerClosed. + * ExtraFiles is not supported on Windows. */ - serveTLS(l: net.Listener, certFile: string, keyFile: string): void - } - interface Server { + extraFiles: Array<(os.File | undefined)> /** - * SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. - * By default, keep-alives are always enabled. Only very - * resource-constrained environments or servers in the process of - * shutting down should disable them. + * SysProcAttr holds optional, operating system-specific attributes. + * Run passes it to os.StartProcess as the os.ProcAttr's Sys field. */ - setKeepAlivesEnabled(v: boolean): void - } - interface Server { + sysProcAttr?: syscall.SysProcAttr /** - * ListenAndServeTLS listens on the TCP network address srv.Addr and - * then calls ServeTLS to handle requests on incoming TLS connections. - * Accepted connections are configured to enable TCP keep-alives. - * - * Filenames containing a certificate and matching private key for the - * server must be provided if neither the Server's TLSConfig.Certificates - * nor TLSConfig.GetCertificate are populated. If the certificate is - * signed by a certificate authority, the certFile should be the - * concatenation of the server's certificate, any intermediates, and - * the CA's certificate. - * - * If srv.Addr is blank, ":https" is used. - * - * ListenAndServeTLS always returns a non-nil error. After Shutdown or - * Close, the returned error is ErrServerClosed. + * Process is the underlying process, once started. */ - listenAndServeTLS(certFile: string, keyFile: string): void - } -} - -/** - * Package sql provides a generic interface around SQL (or SQL-like) - * databases. - * - * The sql package must be used in conjunction with a database driver. - * See https://golang.org/s/sqldrivers for a list of drivers. - * - * Drivers that do not support context cancellation will not return until - * after the query is completed. - * - * For usage examples, see the wiki page at - * https://golang.org/s/sqlwiki. - */ -namespace sql { - /** - * TxOptions holds the transaction options to be used in DB.BeginTx. - */ - interface TxOptions { + process?: os.Process /** - * Isolation is the transaction isolation level. - * If zero, the driver or database's default level is used. + * ProcessState contains information about an exited process. + * If the process was started successfully, Wait or Run will + * populate its ProcessState when the command completes. */ - isolation: IsolationLevel - readOnly: boolean - } - /** - * DB is a database handle representing a pool of zero or more - * underlying connections. It's safe for concurrent use by multiple - * goroutines. - * - * The sql package creates and frees connections automatically; it - * also maintains a free pool of idle connections. If the database has - * a concept of per-connection state, such state can be reliably observed - * within a transaction (Tx) or connection (Conn). Once DB.Begin is called, the - * returned Tx is bound to a single connection. Once Commit or - * Rollback is called on the transaction, that transaction's - * connection is returned to DB's idle connection pool. The pool size - * can be controlled with SetMaxIdleConns. - */ - interface DB { - } - interface DB { + processState?: os.ProcessState + err: Error // LookPath error, if any. /** - * PingContext verifies a connection to the database is still alive, - * establishing a connection if necessary. + * If Cancel is non-nil, the command must have been created with + * CommandContext and Cancel will be called when the command's + * Context is done. By default, CommandContext sets Cancel to + * call the Kill method on the command's Process. + * + * Typically a custom Cancel will send a signal to the command's + * Process, but it may instead take other actions to initiate cancellation, + * such as closing a stdin or stdout pipe or sending a shutdown request on a + * network socket. + * + * If the command exits with a success status after Cancel is + * called, and Cancel does not return an error equivalent to + * os.ErrProcessDone, then Wait and similar methods will return a non-nil + * error: either an error wrapping the one returned by Cancel, + * or the error from the Context. + * (If the command exits with a non-success status, or Cancel + * returns an error that wraps os.ErrProcessDone, Wait and similar methods + * continue to return the command's usual exit status.) + * + * If Cancel is set to nil, nothing will happen immediately when the command's + * Context is done, but a nonzero WaitDelay will still take effect. That may + * be useful, for example, to work around deadlocks in commands that do not + * support shutdown signals but are expected to always finish quickly. + * + * Cancel will not be called if Start returns a non-nil error. */ - pingContext(ctx: context.Context): void - } - interface DB { + cancel: () => void /** - * Ping verifies a connection to the database is still alive, - * establishing a connection if necessary. + * If WaitDelay is non-zero, it bounds the time spent waiting on two sources + * of unexpected delay in Wait: a child process that fails to exit after the + * associated Context is canceled, and a child process that exits but leaves + * its I/O pipes unclosed. + * + * The WaitDelay timer starts when either the associated Context is done or a + * call to Wait observes that the child process has exited, whichever occurs + * first. When the delay has elapsed, the command shuts down the child process + * and/or its I/O pipes. + * + * If the child process has failed to exit — perhaps because it ignored or + * failed to receive a shutdown signal from a Cancel function, or because no + * Cancel function was set — then it will be terminated using os.Process.Kill. + * + * Then, if the I/O pipes communicating with the child process are still open, + * those pipes are closed in order to unblock any goroutines currently blocked + * on Read or Write calls. + * + * If pipes are closed due to WaitDelay, no Cancel call has occurred, + * and the command has otherwise exited with a successful status, Wait and + * similar methods will return ErrWaitDelay instead of nil. * - * Ping uses context.Background internally; to specify the context, use - * PingContext. + * If WaitDelay is zero (the default), I/O pipes will be read until EOF, + * which might not occur until orphaned subprocesses of the command have + * also closed their descriptors for the pipes. */ - ping(): void + waitDelay: time.Duration } - interface DB { + interface Cmd { /** - * Close closes the database and prevents new queries from starting. - * Close then waits for all queries that have started processing on the server - * to finish. - * - * It is rare to Close a DB, as the DB handle is meant to be - * long-lived and shared between many goroutines. + * String returns a human-readable description of c. + * It is intended only for debugging. + * In particular, it is not suitable for use as input to a shell. + * The output of String may vary across Go releases. */ - close(): void + string(): string } - interface DB { + interface Cmd { /** - * SetMaxIdleConns sets the maximum number of connections in the idle - * connection pool. + * Run starts the specified command and waits for it to complete. * - * If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, - * then the new MaxIdleConns will be reduced to match the MaxOpenConns limit. + * The returned error is nil if the command runs, has no problems + * copying stdin, stdout, and stderr, and exits with a zero exit + * status. * - * If n <= 0, no idle connections are retained. + * If the command starts but does not complete successfully, the error is of + * type *ExitError. Other error types may be returned for other situations. * - * The default max idle connections is currently 2. This may change in - * a future release. + * If the calling goroutine has locked the operating system thread + * with runtime.LockOSThread and modified any inheritable OS-level + * thread state (for example, Linux or Plan 9 name spaces), the new + * process will inherit the caller's thread state. */ - setMaxIdleConns(n: number): void + run(): void } - interface DB { + interface Cmd { /** - * SetMaxOpenConns sets the maximum number of open connections to the database. + * Start starts the specified command but does not wait for it to complete. * - * If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than - * MaxIdleConns, then MaxIdleConns will be reduced to match the new - * MaxOpenConns limit. + * If Start returns successfully, the c.Process field will be set. * - * If n <= 0, then there is no limit on the number of open connections. - * The default is 0 (unlimited). + * After a successful call to Start the Wait method must be called in + * order to release associated system resources. */ - setMaxOpenConns(n: number): void + start(): void } - interface DB { + interface Cmd { /** - * SetConnMaxLifetime sets the maximum amount of time a connection may be reused. + * Wait waits for the command to exit and waits for any copying to + * stdin or copying from stdout or stderr to complete. * - * Expired connections may be closed lazily before reuse. + * The command must have been started by Start. * - * If d <= 0, connections are not closed due to a connection's age. - */ - setConnMaxLifetime(d: time.Duration): void - } - interface DB { - /** - * SetConnMaxIdleTime sets the maximum amount of time a connection may be idle. + * The returned error is nil if the command runs, has no problems + * copying stdin, stdout, and stderr, and exits with a zero exit + * status. * - * Expired connections may be closed lazily before reuse. + * If the command fails to run or doesn't complete successfully, the + * error is of type *ExitError. Other error types may be + * returned for I/O problems. * - * If d <= 0, connections are not closed due to a connection's idle time. + * If any of c.Stdin, c.Stdout or c.Stderr are not an *os.File, Wait also waits + * for the respective I/O loop copying to or from the process to complete. + * + * Wait releases any resources associated with the Cmd. */ - setConnMaxIdleTime(d: time.Duration): void + wait(): void } - interface DB { + interface Cmd { /** - * Stats returns database statistics. + * Output runs the command and returns its standard output. + * Any returned error will usually be of type *ExitError. + * If c.Stderr was nil, Output populates ExitError.Stderr. */ - stats(): DBStats + output(): string|Array } - interface DB { + interface Cmd { /** - * PrepareContext creates a prepared statement for later queries or executions. - * Multiple queries or executions may be run concurrently from the - * returned statement. - * The caller must call the statement's Close method - * when the statement is no longer needed. - * - * The provided context is used for the preparation of the statement, not for the - * execution of the statement. + * CombinedOutput runs the command and returns its combined standard + * output and standard error. */ - prepareContext(ctx: context.Context, query: string): (Stmt) + combinedOutput(): string|Array } - interface DB { + interface Cmd { /** - * Prepare creates a prepared statement for later queries or executions. - * Multiple queries or executions may be run concurrently from the - * returned statement. - * The caller must call the statement's Close method - * when the statement is no longer needed. - * - * Prepare uses context.Background internally; to specify the context, use - * PrepareContext. + * StdinPipe returns a pipe that will be connected to the command's + * standard input when the command starts. + * The pipe will be closed automatically after Wait sees the command exit. + * A caller need only call Close to force the pipe to close sooner. + * For example, if the command being run will not exit until standard input + * is closed, the caller must close the pipe. */ - prepare(query: string): (Stmt) + stdinPipe(): io.WriteCloser } - interface DB { + interface Cmd { /** - * ExecContext executes a query without returning any rows. - * The args are for any placeholder parameters in the query. + * StdoutPipe returns a pipe that will be connected to the command's + * standard output when the command starts. + * + * Wait will close the pipe after seeing the command exit, so most callers + * need not close the pipe themselves. It is thus incorrect to call Wait + * before all reads from the pipe have completed. + * For the same reason, it is incorrect to call Run when using StdoutPipe. + * See the example for idiomatic usage. */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result + stdoutPipe(): io.ReadCloser } - interface DB { + interface Cmd { /** - * Exec executes a query without returning any rows. - * The args are for any placeholder parameters in the query. + * StderrPipe returns a pipe that will be connected to the command's + * standard error when the command starts. * - * Exec uses context.Background internally; to specify the context, use - * ExecContext. + * Wait will close the pipe after seeing the command exit, so most callers + * need not close the pipe themselves. It is thus incorrect to call Wait + * before all reads from the pipe have completed. + * For the same reason, it is incorrect to use Run when using StderrPipe. + * See the StdoutPipe example for idiomatic usage. */ - exec(query: string, ...args: any[]): Result + stderrPipe(): io.ReadCloser } - interface DB { + interface Cmd { /** - * QueryContext executes a query that returns rows, typically a SELECT. - * The args are for any placeholder parameters in the query. + * Environ returns a copy of the environment in which the command would be run + * as it is currently configured. */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) - } - interface DB { - /** - * Query executes a query that returns rows, typically a SELECT. - * The args are for any placeholder parameters in the query. - * - * Query uses context.Background internally; to specify the context, use - * QueryContext. - */ - query(query: string, ...args: any[]): (Rows) - } - interface DB { - /** - * QueryRowContext executes a query that is expected to return at most one row. - * QueryRowContext always returns a non-nil value. Errors are deferred until - * Row's Scan method is called. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. - */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) - } - interface DB { - /** - * QueryRow executes a query that is expected to return at most one row. - * QueryRow always returns a non-nil value. Errors are deferred until - * Row's Scan method is called. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. - * - * QueryRow uses context.Background internally; to specify the context, use - * QueryRowContext. - */ - queryRow(query: string, ...args: any[]): (Row) - } - interface DB { - /** - * BeginTx starts a transaction. - * - * The provided context is used until the transaction is committed or rolled back. - * If the context is canceled, the sql package will roll back - * the transaction. Tx.Commit will return an error if the context provided to - * BeginTx is canceled. - * - * The provided TxOptions is optional and may be nil if defaults should be used. - * If a non-default isolation level is used that the driver doesn't support, - * an error will be returned. - */ - beginTx(ctx: context.Context, opts: TxOptions): (Tx) - } - interface DB { - /** - * Begin starts a transaction. The default isolation level is dependent on - * the driver. - * - * Begin uses context.Background internally; to specify the context, use - * BeginTx. - */ - begin(): (Tx) - } - interface DB { - /** - * Driver returns the database's underlying driver. - */ - driver(): any - } - interface DB { - /** - * Conn returns a single connection by either opening a new connection - * or returning an existing connection from the connection pool. Conn will - * block until either a connection is returned or ctx is canceled. - * Queries run on the same Conn will be run in the same database session. - * - * Every Conn must be returned to the database pool after use by - * calling Conn.Close. - */ - conn(ctx: context.Context): (Conn) + environ(): Array } +} + +/** + * Package types implements some commonly used db serializable types + * like datetime, json, etc. + */ +namespace types { /** - * Tx is an in-progress database transaction. - * - * A transaction must end with a call to Commit or Rollback. - * - * After a call to Commit or Rollback, all operations on the - * transaction fail with ErrTxDone. - * - * The statements prepared for a transaction by calling - * the transaction's Prepare or Stmt methods are closed - * by the call to Commit or Rollback. + * JsonArray defines a slice that is safe for json and db read/write. */ - interface Tx { - } - interface Tx { - /** - * Commit commits the transaction. - */ - commit(): void - } - interface Tx { - /** - * Rollback aborts the transaction. - */ - rollback(): void - } - interface Tx { - /** - * PrepareContext creates a prepared statement for use within a transaction. - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. - * - * To use an existing prepared statement on this transaction, see Tx.Stmt. - * - * The provided context will be used for the preparation of the context, not - * for the execution of the returned statement. The returned statement - * will run in the transaction context. - */ - prepareContext(ctx: context.Context, query: string): (Stmt) - } - interface Tx { + interface JsonArray extends Array{} + interface JsonArray { /** - * Prepare creates a prepared statement for use within a transaction. - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. - * - * To use an existing prepared statement on this transaction, see Tx.Stmt. - * - * Prepare uses context.Background internally; to specify the context, use - * PrepareContext. + * MarshalJSON implements the [json.Marshaler] interface. */ - prepare(query: string): (Stmt) + marshalJSON(): string|Array } - interface Tx { + interface JsonArray { /** - * StmtContext returns a transaction-specific prepared statement from - * an existing statement. - * - * Example: - * - * ``` - * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") - * ... - * tx, err := db.Begin() - * ... - * res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203) - * ``` - * - * The provided context is used for the preparation of the statement, not for the - * execution of the statement. - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. + * Value implements the [driver.Valuer] interface. */ - stmtContext(ctx: context.Context, stmt: Stmt): (Stmt) + value(): any } - interface Tx { + interface JsonArray { /** - * Stmt returns a transaction-specific prepared statement from - * an existing statement. - * - * Example: - * - * ``` - * updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") - * ... - * tx, err := db.Begin() - * ... - * res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203) - * ``` - * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. - * - * Stmt uses context.Background internally; to specify the context, use - * StmtContext. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JsonArray[T] instance. */ - stmt(stmt: Stmt): (Stmt) + scan(value: any): void } - interface Tx { + /** + * JsonMap defines a map that is safe for json and db read/write. + */ + interface JsonMap extends _TygojaDict{} + interface JsonMap { /** - * ExecContext executes a query that doesn't return rows. - * For example: an INSERT and UPDATE. + * MarshalJSON implements the [json.Marshaler] interface. */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result + marshalJSON(): string|Array } - interface Tx { + interface JsonMap { /** - * Exec executes a query that doesn't return rows. - * For example: an INSERT and UPDATE. + * Get retrieves a single value from the current JsonMap. * - * Exec uses context.Background internally; to specify the context, use - * ExecContext. - */ - exec(query: string, ...args: any[]): Result - } - interface Tx { - /** - * QueryContext executes a query that returns rows, typically a SELECT. + * This helper was added primarily to assist the goja integration since custom map types + * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows) + get(key: string): any } - interface Tx { + interface JsonMap { /** - * Query executes a query that returns rows, typically a SELECT. + * Set sets a single value in the current JsonMap. * - * Query uses context.Background internally; to specify the context, use - * QueryContext. + * This helper was added primarily to assist the goja integration since custom map types + * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). */ - query(query: string, ...args: any[]): (Rows) + set(key: string, value: any): void } - interface Tx { + interface JsonMap { /** - * QueryRowContext executes a query that is expected to return at most one row. - * QueryRowContext always returns a non-nil value. Errors are deferred until - * Row's Scan method is called. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. + * Value implements the [driver.Valuer] interface. */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) + value(): any } - interface Tx { + interface JsonMap { /** - * QueryRow executes a query that is expected to return at most one row. - * QueryRow always returns a non-nil value. Errors are deferred until - * Row's Scan method is called. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. - * - * QueryRow uses context.Background internally; to specify the context, use - * QueryRowContext. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current `JsonMap` instance. */ - queryRow(query: string, ...args: any[]): (Row) + scan(value: any): void } +} + +/** + * Package multipart implements MIME multipart parsing, as defined in RFC + * 2046. + * + * The implementation is sufficient for HTTP (RFC 2388) and the multipart + * bodies generated by popular browsers. + * + * # Limits + * + * To protect against malicious inputs, this package sets limits on the size + * of the MIME data it processes. + * + * Reader.NextPart and Reader.NextRawPart limit the number of headers in a + * part to 10000 and Reader.ReadForm limits the total number of headers in all + * FileHeaders to 10000. + * These limits may be adjusted with the GODEBUG=multipartmaxheaders= + * setting. + * + * Reader.ReadForm further limits the number of parts in a form to 1000. + * This limit may be adjusted with the GODEBUG=multipartmaxparts= + * setting. + */ +/** + * Copyright 2023 The Go Authors. All rights reserved. + * Use of this source code is governed by a BSD-style + * license that can be found in the LICENSE file. + */ +namespace multipart { /** - * Stmt is a prepared statement. - * A Stmt is safe for concurrent use by multiple goroutines. - * - * If a Stmt is prepared on a Tx or Conn, it will be bound to a single - * underlying connection forever. If the Tx or Conn closes, the Stmt will - * become unusable and all operations will return an error. - * If a Stmt is prepared on a DB, it will remain usable for the lifetime of the - * DB. When the Stmt needs to execute on a new underlying connection, it will - * prepare itself on the new connection automatically. + * A FileHeader describes a file part of a multipart request. */ - interface Stmt { + interface FileHeader { + filename: string + header: textproto.MIMEHeader + size: number } - interface Stmt { + interface FileHeader { /** - * ExecContext executes a prepared statement with the given arguments and - * returns a Result summarizing the effect of the statement. + * Open opens and returns the FileHeader's associated File. */ - execContext(ctx: context.Context, ...args: any[]): Result + open(): File } - interface Stmt { - /** - * Exec executes a prepared statement with the given arguments and - * returns a Result summarizing the effect of the statement. - * - * Exec uses context.Background internally; to specify the context, use - * ExecContext. - */ - exec(...args: any[]): Result - } - interface Stmt { +} + +/** + * Package http provides HTTP client and server implementations. + * + * [Get], [Head], [Post], and [PostForm] make HTTP (or HTTPS) requests: + * + * ``` + * resp, err := http.Get("http://example.com/") + * ... + * resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) + * ... + * resp, err := http.PostForm("http://example.com/form", + * url.Values{"key": {"Value"}, "id": {"123"}}) + * ``` + * + * The caller must close the response body when finished with it: + * + * ``` + * resp, err := http.Get("http://example.com/") + * if err != nil { + * // handle error + * } + * defer resp.Body.Close() + * body, err := io.ReadAll(resp.Body) + * // ... + * ``` + * + * # Clients and Transports + * + * For control over HTTP client headers, redirect policy, and other + * settings, create a [Client]: + * + * ``` + * client := &http.Client{ + * CheckRedirect: redirectPolicyFunc, + * } + * + * resp, err := client.Get("http://example.com") + * // ... + * + * req, err := http.NewRequest("GET", "http://example.com", nil) + * // ... + * req.Header.Add("If-None-Match", `W/"wyzzy"`) + * resp, err := client.Do(req) + * // ... + * ``` + * + * For control over proxies, TLS configuration, keep-alives, + * compression, and other settings, create a [Transport]: + * + * ``` + * tr := &http.Transport{ + * MaxIdleConns: 10, + * IdleConnTimeout: 30 * time.Second, + * DisableCompression: true, + * } + * client := &http.Client{Transport: tr} + * resp, err := client.Get("https://example.com") + * ``` + * + * Clients and Transports are safe for concurrent use by multiple + * goroutines and for efficiency should only be created once and re-used. + * + * # Servers + * + * ListenAndServe starts an HTTP server with a given address and handler. + * The handler is usually nil, which means to use [DefaultServeMux]. + * [Handle] and [HandleFunc] add handlers to [DefaultServeMux]: + * + * ``` + * http.Handle("/foo", fooHandler) + * + * http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { + * fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) + * }) + * + * log.Fatal(http.ListenAndServe(":8080", nil)) + * ``` + * + * More control over the server's behavior is available by creating a + * custom Server: + * + * ``` + * s := &http.Server{ + * Addr: ":8080", + * Handler: myHandler, + * ReadTimeout: 10 * time.Second, + * WriteTimeout: 10 * time.Second, + * MaxHeaderBytes: 1 << 20, + * } + * log.Fatal(s.ListenAndServe()) + * ``` + * + * # HTTP/2 + * + * Starting with Go 1.6, the http package has transparent support for the + * HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 + * can do so by setting [Transport.TLSNextProto] (for clients) or + * [Server.TLSNextProto] (for servers) to a non-nil, empty + * map. Alternatively, the following GODEBUG settings are + * currently supported: + * + * ``` + * GODEBUG=http2client=0 # disable HTTP/2 client support + * GODEBUG=http2server=0 # disable HTTP/2 server support + * GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs + * GODEBUG=http2debug=2 # ... even more verbose, with frame dumps + * ``` + * + * Please report any issues before disabling HTTP/2 support: https://golang.org/s/http2bug + * + * The http package's [Transport] and [Server] both automatically enable + * HTTP/2 support for simple configurations. To enable HTTP/2 for more + * complex configurations, to use lower-level HTTP/2 features, or to use + * a newer version of Go's http2 package, import "golang.org/x/net/http2" + * directly and use its ConfigureTransport and/or ConfigureServer + * functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 + * package takes precedence over the net/http package's built-in HTTP/2 + * support. + */ +namespace http { + // @ts-ignore + import mathrand = rand + // @ts-ignore + import urlpkg = url + /** + * A Request represents an HTTP request received by a server + * or to be sent by a client. + * + * The field semantics differ slightly between client and server + * usage. In addition to the notes on the fields below, see the + * documentation for [Request.Write] and [RoundTripper]. + */ + interface Request { /** - * QueryContext executes a prepared query statement with the given arguments - * and returns the query results as a *Rows. + * Method specifies the HTTP method (GET, POST, PUT, etc.). + * For client requests, an empty string means GET. */ - queryContext(ctx: context.Context, ...args: any[]): (Rows) - } - interface Stmt { + method: string /** - * Query executes a prepared query statement with the given arguments - * and returns the query results as a *Rows. + * URL specifies either the URI being requested (for server + * requests) or the URL to access (for client requests). + * + * For server requests, the URL is parsed from the URI + * supplied on the Request-Line as stored in RequestURI. For + * most requests, fields other than Path and RawQuery will be + * empty. (See RFC 7230, Section 5.3) * - * Query uses context.Background internally; to specify the context, use - * QueryContext. + * For client requests, the URL's Host specifies the server to + * connect to, while the Request's Host field optionally + * specifies the Host header value to send in the HTTP + * request. */ - query(...args: any[]): (Rows) - } - interface Stmt { + url?: url.URL /** - * QueryRowContext executes a prepared query statement with the given arguments. - * If an error occurs during the execution of the statement, that error will - * be returned by a call to Scan on the returned *Row, which is always non-nil. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. + * The protocol version for incoming server requests. + * + * For client requests, these fields are ignored. The HTTP + * client code always uses either HTTP/1.1 or HTTP/2. + * See the docs on Transport for details. */ - queryRowContext(ctx: context.Context, ...args: any[]): (Row) - } - interface Stmt { + proto: string // "HTTP/1.0" + protoMajor: number // 1 + protoMinor: number // 0 /** - * QueryRow executes a prepared query statement with the given arguments. - * If an error occurs during the execution of the statement, that error will - * be returned by a call to Scan on the returned *Row, which is always non-nil. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards - * the rest. + * Header contains the request header fields either received + * by the server or to be sent by the client. * - * Example usage: + * If a server received a request with header lines, * * ``` - * var name string - * err := nameByUseridStmt.QueryRow(id).Scan(&name) + * Host: example.com + * accept-encoding: gzip, deflate + * Accept-Language: en-us + * fOO: Bar + * foo: two + * ``` + * + * then + * + * ``` + * Header = map[string][]string{ + * "Accept-Encoding": {"gzip, deflate"}, + * "Accept-Language": {"en-us"}, + * "Foo": {"Bar", "two"}, + * } * ``` * - * QueryRow uses context.Background internally; to specify the context, use - * QueryRowContext. + * For incoming requests, the Host header is promoted to the + * Request.Host field and removed from the Header map. + * + * HTTP defines that header names are case-insensitive. The + * request parser implements this by using CanonicalHeaderKey, + * making the first character and any characters following a + * hyphen uppercase and the rest lowercase. + * + * For client requests, certain headers such as Content-Length + * and Connection are automatically written when needed and + * values in Header may be ignored. See the documentation + * for the Request.Write method. */ - queryRow(...args: any[]): (Row) - } - interface Stmt { + header: Header /** - * Close closes the statement. + * Body is the request's body. + * + * For client requests, a nil body means the request has no + * body, such as a GET request. The HTTP Client's Transport + * is responsible for calling the Close method. + * + * For server requests, the Request Body is always non-nil + * but will return EOF immediately when no body is present. + * The Server will close the request body. The ServeHTTP + * Handler does not need to. + * + * Body must allow Read to be called concurrently with Close. + * In particular, calling Close should unblock a Read waiting + * for input. */ - close(): void - } - /** - * Rows is the result of a query. Its cursor starts before the first row - * of the result set. Use Next to advance from row to row. - */ - interface Rows { - } - interface Rows { + body: io.ReadCloser /** - * Next prepares the next result row for reading with the Scan method. It - * returns true on success, or false if there is no next result row or an error - * happened while preparing it. Err should be consulted to distinguish between - * the two cases. + * GetBody defines an optional func to return a new copy of + * Body. It is used for client requests when a redirect requires + * reading the body more than once. Use of GetBody still + * requires setting Body. * - * Every call to Scan, even the first one, must be preceded by a call to Next. + * For server requests, it is unused. */ - next(): boolean - } - interface Rows { + getBody: () => io.ReadCloser /** - * NextResultSet prepares the next result set for reading. It reports whether - * there is further result sets, or false if there is no further result set - * or if there is an error advancing to it. The Err method should be consulted - * to distinguish between the two cases. + * ContentLength records the length of the associated content. + * The value -1 indicates that the length is unknown. + * Values >= 0 indicate that the given number of bytes may + * be read from Body. * - * After calling NextResultSet, the Next method should always be called before - * scanning. If there are further result sets they may not have rows in the result - * set. + * For client requests, a value of 0 with a non-nil Body is + * also treated as unknown. */ - nextResultSet(): boolean - } - interface Rows { + contentLength: number /** - * Err returns the error, if any, that was encountered during iteration. - * Err may be called after an explicit or implicit Close. + * TransferEncoding lists the transfer encodings from outermost to + * innermost. An empty list denotes the "identity" encoding. + * TransferEncoding can usually be ignored; chunked encoding is + * automatically added and removed as necessary when sending and + * receiving requests. */ - err(): void - } - interface Rows { + transferEncoding: Array /** - * Columns returns the column names. - * Columns returns an error if the rows are closed. + * Close indicates whether to close the connection after + * replying to this request (for servers) or after sending this + * request and reading its response (for clients). + * + * For server requests, the HTTP server handles this automatically + * and this field is not needed by Handlers. + * + * For client requests, setting this field prevents re-use of + * TCP connections between requests to the same hosts, as if + * Transport.DisableKeepAlives were set. */ - columns(): Array - } - interface Rows { + close: boolean /** - * ColumnTypes returns column information such as column type, length, - * and nullable. Some information may not be available from some drivers. + * For server requests, Host specifies the host on which the + * URL is sought. For HTTP/1 (per RFC 7230, section 5.4), this + * is either the value of the "Host" header or the host name + * given in the URL itself. For HTTP/2, it is the value of the + * ":authority" pseudo-header field. + * It may be of the form "host:port". For international domain + * names, Host may be in Punycode or Unicode form. Use + * golang.org/x/net/idna to convert it to either format if + * needed. + * To prevent DNS rebinding attacks, server Handlers should + * validate that the Host header has a value for which the + * Handler considers itself authoritative. The included + * ServeMux supports patterns registered to particular host + * names and thus protects its registered Handlers. + * + * For client requests, Host optionally overrides the Host + * header to send. If empty, the Request.Write method uses + * the value of URL.Host. Host may contain an international + * domain name. */ - columnTypes(): Array<(ColumnType | undefined)> - } - interface Rows { + host: string /** - * Scan copies the columns in the current row into the values pointed - * at by dest. The number of values in dest must be the same as the - * number of columns in Rows. + * Form contains the parsed form data, including both the URL + * field's query parameters and the PATCH, POST, or PUT form data. + * This field is only available after ParseForm is called. + * The HTTP client ignores Form and uses Body instead. + */ + form: url.Values + /** + * PostForm contains the parsed form data from PATCH, POST + * or PUT body parameters. * - * Scan converts columns read from the database into the following - * common Go types and special types provided by the sql package: + * This field is only available after ParseForm is called. + * The HTTP client ignores PostForm and uses Body instead. + */ + postForm: url.Values + /** + * MultipartForm is the parsed multipart form, including file uploads. + * This field is only available after ParseMultipartForm is called. + * The HTTP client ignores MultipartForm and uses Body instead. + */ + multipartForm?: multipart.Form + /** + * Trailer specifies additional headers that are sent after the request + * body. * - * ``` - * *string - * *[]byte - * *int, *int8, *int16, *int32, *int64 - * *uint, *uint8, *uint16, *uint32, *uint64 - * *bool - * *float32, *float64 - * *interface{} - * *RawBytes - * *Rows (cursor value) - * any type implementing Scanner (see Scanner docs) - * ``` + * For server requests, the Trailer map initially contains only the + * trailer keys, with nil values. (The client declares which trailers it + * will later send.) While the handler is reading from Body, it must + * not reference Trailer. After reading from Body returns EOF, Trailer + * can be read again and will contain non-nil values, if they were sent + * by the client. * - * In the most simple case, if the type of the value from the source - * column is an integer, bool or string type T and dest is of type *T, - * Scan simply assigns the value through the pointer. + * For client requests, Trailer must be initialized to a map containing + * the trailer keys to later send. The values may be nil or their final + * values. The ContentLength must be 0 or -1, to send a chunked request. + * After the HTTP request is sent the map values can be updated while + * the request body is read. Once the body returns EOF, the caller must + * not mutate Trailer. * - * Scan also converts between string and numeric types, as long as no - * information would be lost. While Scan stringifies all numbers - * scanned from numeric database columns into *string, scans into - * numeric types are checked for overflow. For example, a float64 with - * value 300 or a string with value "300" can scan into a uint16, but - * not into a uint8, though float64(255) or "255" can scan into a - * uint8. One exception is that scans of some float64 numbers to - * strings may lose information when stringifying. In general, scan - * floating point columns into *float64. + * Few HTTP clients, servers, or proxies support HTTP trailers. + */ + trailer: Header + /** + * RemoteAddr allows HTTP servers and other software to record + * the network address that sent the request, usually for + * logging. This field is not filled in by ReadRequest and + * has no defined format. The HTTP server in this package + * sets RemoteAddr to an "IP:port" address before invoking a + * handler. + * This field is ignored by the HTTP client. + */ + remoteAddr: string + /** + * RequestURI is the unmodified request-target of the + * Request-Line (RFC 7230, Section 3.1.1) as sent by the client + * to a server. Usually the URL field should be used instead. + * It is an error to set this field in an HTTP client request. + */ + requestURI: string + /** + * TLS allows HTTP servers and other software to record + * information about the TLS connection on which the request + * was received. This field is not filled in by ReadRequest. + * The HTTP server in this package sets the field for + * TLS-enabled connections before invoking a handler; + * otherwise it leaves the field nil. + * This field is ignored by the HTTP client. + */ + tls?: any + /** + * Cancel is an optional channel whose closure indicates that the client + * request should be regarded as canceled. Not all implementations of + * RoundTripper may support Cancel. * - * If a dest argument has type *[]byte, Scan saves in that argument a - * copy of the corresponding data. The copy is owned by the caller and - * can be modified and held indefinitely. The copy can be avoided by - * using an argument of type *RawBytes instead; see the documentation - * for RawBytes for restrictions on its use. + * For server requests, this field is not applicable. * - * If an argument has type *interface{}, Scan copies the value - * provided by the underlying driver without conversion. When scanning - * from a source value of type []byte to *interface{}, a copy of the - * slice is made and the caller owns the result. + * Deprecated: Set the Request's context with NewRequestWithContext + * instead. If a Request's Cancel field and context are both + * set, it is undefined whether Cancel is respected. + */ + cancel: undefined + /** + * Response is the redirect response which caused this request + * to be created. This field is only populated during client + * redirects. + */ + response?: Response + } + interface Request { + /** + * Context returns the request's context. To change the context, use + * [Request.Clone] or [Request.WithContext]. * - * Source values of type time.Time may be scanned into values of type - * *time.Time, *interface{}, *string, or *[]byte. When converting to - * the latter two, time.RFC3339Nano is used. + * The returned context is always non-nil; it defaults to the + * background context. * - * Source values of type bool may be scanned into types *bool, - * *interface{}, *string, *[]byte, or *RawBytes. + * For outgoing client requests, the context controls cancellation. * - * For scanning into *bool, the source may be true, false, 1, 0, or - * string inputs parseable by strconv.ParseBool. + * For incoming server requests, the context is canceled when the + * client's connection closes, the request is canceled (with HTTP/2), + * or when the ServeHTTP method returns. + */ + context(): context.Context + } + interface Request { + /** + * WithContext returns a shallow copy of r with its context changed + * to ctx. The provided ctx must be non-nil. * - * Scan can also convert a cursor returned from a query, such as - * "select cursor(select * from my_table) from dual", into a - * *Rows value that can itself be scanned from. The parent - * select query will close any cursor *Rows if the parent *Rows is closed. + * For outgoing client request, the context controls the entire + * lifetime of a request and its response: obtaining a connection, + * sending the request, and reading the response headers and body. * - * If any of the first arguments implementing Scanner returns an error, - * that error will be wrapped in the returned error. + * To create a new request with a context, use [NewRequestWithContext]. + * To make a deep copy of a request with a new context, use [Request.Clone]. */ - scan(...dest: any[]): void + withContext(ctx: context.Context): (Request) } - interface Rows { + interface Request { /** - * Close closes the Rows, preventing further enumeration. If Next is called - * and returns false and there are no further result sets, - * the Rows are closed automatically and it will suffice to check the - * result of Err. Close is idempotent and does not affect the result of Err. + * Clone returns a deep copy of r with its context changed to ctx. + * The provided ctx must be non-nil. + * + * For an outgoing client request, the context controls the entire + * lifetime of a request and its response: obtaining a connection, + * sending the request, and reading the response headers and body. */ - close(): void + clone(ctx: context.Context): (Request) } - /** - * A Result summarizes an executed SQL command. - */ - interface Result { - [key:string]: any; + interface Request { /** - * LastInsertId returns the integer generated by the database - * in response to a command. Typically this will be from an - * "auto increment" column when inserting a new row. Not all - * databases support this feature, and the syntax of such - * statements varies. + * ProtoAtLeast reports whether the HTTP protocol used + * in the request is at least major.minor. */ - lastInsertId(): number + protoAtLeast(major: number, minor: number): boolean + } + interface Request { /** - * RowsAffected returns the number of rows affected by an - * update, insert, or delete. Not every database or database - * driver may support this. + * UserAgent returns the client's User-Agent, if sent in the request. */ - rowsAffected(): number + userAgent(): string } -} - -/** - * Package exec runs external commands. It wraps os.StartProcess to make it - * easier to remap stdin and stdout, connect I/O with pipes, and do other - * adjustments. - * - * Unlike the "system" library call from C and other languages, the - * os/exec package intentionally does not invoke the system shell and - * does not expand any glob patterns or handle other expansions, - * pipelines, or redirections typically done by shells. The package - * behaves more like C's "exec" family of functions. To expand glob - * patterns, either call the shell directly, taking care to escape any - * dangerous input, or use the path/filepath package's Glob function. - * To expand environment variables, use package os's ExpandEnv. - * - * Note that the examples in this package assume a Unix system. - * They may not run on Windows, and they do not run in the Go Playground - * used by golang.org and godoc.org. - * - * # Executables in the current directory - * - * The functions Command and LookPath look for a program - * in the directories listed in the current path, following the - * conventions of the host operating system. - * Operating systems have for decades included the current - * directory in this search, sometimes implicitly and sometimes - * configured explicitly that way by default. - * Modern practice is that including the current directory - * is usually unexpected and often leads to security problems. - * - * To avoid those security problems, as of Go 1.19, this package will not resolve a program - * using an implicit or explicit path entry relative to the current directory. - * That is, if you run exec.LookPath("go"), it will not successfully return - * ./go on Unix nor .\go.exe on Windows, no matter how the path is configured. - * Instead, if the usual path algorithms would result in that answer, - * these functions return an error err satisfying errors.Is(err, ErrDot). - * - * For example, consider these two program snippets: - * - * ``` - * path, err := exec.LookPath("prog") - * if err != nil { - * log.Fatal(err) - * } - * use(path) - * ``` - * - * and - * - * ``` - * cmd := exec.Command("prog") - * if err := cmd.Run(); err != nil { - * log.Fatal(err) - * } - * ``` - * - * These will not find and run ./prog or .\prog.exe, - * no matter how the current path is configured. - * - * Code that always wants to run a program from the current directory - * can be rewritten to say "./prog" instead of "prog". - * - * Code that insists on including results from relative path entries - * can instead override the error using an errors.Is check: - * - * ``` - * path, err := exec.LookPath("prog") - * if errors.Is(err, exec.ErrDot) { - * err = nil - * } - * if err != nil { - * log.Fatal(err) - * } - * use(path) - * ``` - * - * and - * - * ``` - * cmd := exec.Command("prog") - * if errors.Is(cmd.Err, exec.ErrDot) { - * cmd.Err = nil - * } - * if err := cmd.Run(); err != nil { - * log.Fatal(err) - * } - * ``` - * - * Setting the environment variable GODEBUG=execerrdot=0 - * disables generation of ErrDot entirely, temporarily restoring the pre-Go 1.19 - * behavior for programs that are unable to apply more targeted fixes. - * A future version of Go may remove support for this variable. - * - * Before adding such overrides, make sure you understand the - * security implications of doing so. - * See https://go.dev/blog/path-security for more information. - */ -namespace exec { - /** - * Cmd represents an external command being prepared or run. - * - * A Cmd cannot be reused after calling its Run, Output or CombinedOutput - * methods. - */ - interface Cmd { + interface Request { /** - * Path is the path of the command to run. + * Cookies parses and returns the HTTP cookies sent with the request. + */ + cookies(): Array<(Cookie | undefined)> + } + interface Request { + /** + * Cookie returns the named cookie provided in the request or + * [ErrNoCookie] if not found. + * If multiple cookies match the given name, only one cookie will + * be returned. + */ + cookie(name: string): (Cookie) + } + interface Request { + /** + * AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, + * AddCookie does not attach more than one [Cookie] header field. That + * means all cookies, if any, are written into the same line, + * separated by semicolon. + * AddCookie only sanitizes c's name and value, and does not sanitize + * a Cookie header already present in the request. + */ + addCookie(c: Cookie): void + } + interface Request { + /** + * Referer returns the referring URL, if sent in the request. * - * This is the only field that must be set to a non-zero - * value. If Path is relative, it is evaluated relative - * to Dir. + * Referer is misspelled as in the request itself, a mistake from the + * earliest days of HTTP. This value can also be fetched from the + * [Header] map as Header["Referer"]; the benefit of making it available + * as a method is that the compiler can diagnose programs that use the + * alternate (correct English) spelling req.Referrer() but cannot + * diagnose programs that use Header["Referrer"]. */ - path: string + referer(): string + } + interface Request { /** - * Args holds command line arguments, including the command as Args[0]. - * If the Args field is empty or nil, Run uses {Path}. + * MultipartReader returns a MIME multipart reader if this is a + * multipart/form-data or a multipart/mixed POST request, else returns nil and an error. + * Use this function instead of [Request.ParseMultipartForm] to + * process the request body as a stream. + */ + multipartReader(): (multipart.Reader) + } + interface Request { + /** + * Write writes an HTTP/1.1 request, which is the header and body, in wire format. + * This method consults the following fields of the request: * - * In typical use, both Path and Args are set by calling Command. + * ``` + * Host + * URL + * Method (defaults to "GET") + * Header + * ContentLength + * TransferEncoding + * Body + * ``` + * + * If Body is present, Content-Length is <= 0 and [Request.TransferEncoding] + * hasn't been set to "identity", Write adds "Transfer-Encoding: + * chunked" to the header. Body is closed after it is sent. */ - args: Array + write(w: io.Writer): void + } + interface Request { /** - * Env specifies the environment of the process. - * Each entry is of the form "key=value". - * If Env is nil, the new process uses the current process's - * environment. - * If Env contains duplicate environment keys, only the last - * value in the slice for each duplicate key is used. - * As a special case on Windows, SYSTEMROOT is always added if - * missing and not explicitly set to the empty string. + * WriteProxy is like [Request.Write] but writes the request in the form + * expected by an HTTP proxy. In particular, [Request.WriteProxy] writes the + * initial Request-URI line of the request with an absolute URI, per + * section 5.3 of RFC 7230, including the scheme and host. + * In either case, WriteProxy also writes a Host header, using + * either r.Host or r.URL.Host. */ - env: Array + writeProxy(w: io.Writer): void + } + interface Request { /** - * Dir specifies the working directory of the command. - * If Dir is the empty string, Run runs the command in the - * calling process's current directory. + * BasicAuth returns the username and password provided in the request's + * Authorization header, if the request uses HTTP Basic Authentication. + * See RFC 2617, Section 2. */ - dir: string + basicAuth(): [string, boolean] + } + interface Request { /** - * Stdin specifies the process's standard input. - * - * If Stdin is nil, the process reads from the null device (os.DevNull). + * SetBasicAuth sets the request's Authorization header to use HTTP + * Basic Authentication with the provided username and password. * - * If Stdin is an *os.File, the process's standard input is connected - * directly to that file. + * With HTTP Basic Authentication the provided username and password + * are not encrypted. It should generally only be used in an HTTPS + * request. * - * Otherwise, during the execution of the command a separate - * goroutine reads from Stdin and delivers that data to the command - * over a pipe. In this case, Wait does not complete until the goroutine - * stops copying, either because it has reached the end of Stdin - * (EOF or a read error), or because writing to the pipe returned an error, - * or because a nonzero WaitDelay was set and expired. + * The username may not contain a colon. Some protocols may impose + * additional requirements on pre-escaping the username and + * password. For instance, when used with OAuth2, both arguments must + * be URL encoded first with [url.QueryEscape]. */ - stdin: io.Reader + setBasicAuth(username: string, password: string): void + } + interface Request { /** - * Stdout and Stderr specify the process's standard output and error. + * ParseForm populates r.Form and r.PostForm. * - * If either is nil, Run connects the corresponding file descriptor - * to the null device (os.DevNull). + * For all requests, ParseForm parses the raw query from the URL and updates + * r.Form. * - * If either is an *os.File, the corresponding output from the process - * is connected directly to that file. + * For POST, PUT, and PATCH requests, it also reads the request body, parses it + * as a form and puts the results into both r.PostForm and r.Form. Request body + * parameters take precedence over URL query string values in r.Form. * - * Otherwise, during the execution of the command a separate goroutine - * reads from the process over a pipe and delivers that data to the - * corresponding Writer. In this case, Wait does not complete until the - * goroutine reaches EOF or encounters an error or a nonzero WaitDelay - * expires. + * If the request Body's size has not already been limited by [MaxBytesReader], + * the size is capped at 10MB. * - * If Stdout and Stderr are the same writer, and have a type that can - * be compared with ==, at most one goroutine at a time will call Write. - */ - stdout: io.Writer - stderr: io.Writer - /** - * ExtraFiles specifies additional open files to be inherited by the - * new process. It does not include standard input, standard output, or - * standard error. If non-nil, entry i becomes file descriptor 3+i. + * For other HTTP methods, or when the Content-Type is not + * application/x-www-form-urlencoded, the request Body is not read, and + * r.PostForm is initialized to a non-nil, empty value. * - * ExtraFiles is not supported on Windows. + * [Request.ParseMultipartForm] calls ParseForm automatically. + * ParseForm is idempotent. */ - extraFiles: Array<(os.File | undefined)> + parseForm(): void + } + interface Request { /** - * SysProcAttr holds optional, operating system-specific attributes. - * Run passes it to os.StartProcess as the os.ProcAttr's Sys field. + * ParseMultipartForm parses a request body as multipart/form-data. + * The whole request body is parsed and up to a total of maxMemory bytes of + * its file parts are stored in memory, with the remainder stored on + * disk in temporary files. + * ParseMultipartForm calls [Request.ParseForm] if necessary. + * If ParseForm returns an error, ParseMultipartForm returns it but also + * continues parsing the request body. + * After one call to ParseMultipartForm, subsequent calls have no effect. */ - sysProcAttr?: syscall.SysProcAttr + parseMultipartForm(maxMemory: number): void + } + interface Request { /** - * Process is the underlying process, once started. + * FormValue returns the first value for the named component of the query. + * The precedence order: + * 1. application/x-www-form-urlencoded form body (POST, PUT, PATCH only) + * 2. query parameters (always) + * 3. multipart/form-data form body (always) + * + * FormValue calls [Request.ParseMultipartForm] and [Request.ParseForm] + * if necessary and ignores any errors returned by these functions. + * If key is not present, FormValue returns the empty string. + * To access multiple values of the same key, call ParseForm and + * then inspect [Request.Form] directly. */ - process?: os.Process + formValue(key: string): string + } + interface Request { /** - * ProcessState contains information about an exited process. - * If the process was started successfully, Wait or Run will - * populate its ProcessState when the command completes. + * PostFormValue returns the first value for the named component of the POST, + * PUT, or PATCH request body. URL query parameters are ignored. + * PostFormValue calls [Request.ParseMultipartForm] and [Request.ParseForm] if necessary and ignores + * any errors returned by these functions. + * If key is not present, PostFormValue returns the empty string. */ - processState?: os.ProcessState - err: Error // LookPath error, if any. + postFormValue(key: string): string + } + interface Request { /** - * If Cancel is non-nil, the command must have been created with - * CommandContext and Cancel will be called when the command's - * Context is done. By default, CommandContext sets Cancel to - * call the Kill method on the command's Process. - * - * Typically a custom Cancel will send a signal to the command's - * Process, but it may instead take other actions to initiate cancellation, - * such as closing a stdin or stdout pipe or sending a shutdown request on a - * network socket. - * - * If the command exits with a success status after Cancel is - * called, and Cancel does not return an error equivalent to - * os.ErrProcessDone, then Wait and similar methods will return a non-nil - * error: either an error wrapping the one returned by Cancel, - * or the error from the Context. - * (If the command exits with a non-success status, or Cancel - * returns an error that wraps os.ErrProcessDone, Wait and similar methods - * continue to return the command's usual exit status.) - * - * If Cancel is set to nil, nothing will happen immediately when the command's - * Context is done, but a nonzero WaitDelay will still take effect. That may - * be useful, for example, to work around deadlocks in commands that do not - * support shutdown signals but are expected to always finish quickly. - * - * Cancel will not be called if Start returns a non-nil error. + * FormFile returns the first file for the provided form key. + * FormFile calls [Request.ParseMultipartForm] and [Request.ParseForm] if necessary. */ - cancel: () => void + formFile(key: string): [multipart.File, (multipart.FileHeader)] + } + interface Request { /** - * If WaitDelay is non-zero, it bounds the time spent waiting on two sources - * of unexpected delay in Wait: a child process that fails to exit after the - * associated Context is canceled, and a child process that exits but leaves - * its I/O pipes unclosed. - * - * The WaitDelay timer starts when either the associated Context is done or a - * call to Wait observes that the child process has exited, whichever occurs - * first. When the delay has elapsed, the command shuts down the child process - * and/or its I/O pipes. - * - * If the child process has failed to exit — perhaps because it ignored or - * failed to receive a shutdown signal from a Cancel function, or because no - * Cancel function was set — then it will be terminated using os.Process.Kill. - * - * Then, if the I/O pipes communicating with the child process are still open, - * those pipes are closed in order to unblock any goroutines currently blocked - * on Read or Write calls. - * - * If pipes are closed due to WaitDelay, no Cancel call has occurred, - * and the command has otherwise exited with a successful status, Wait and - * similar methods will return ErrWaitDelay instead of nil. - * - * If WaitDelay is zero (the default), I/O pipes will be read until EOF, - * which might not occur until orphaned subprocesses of the command have - * also closed their descriptors for the pipes. + * PathValue returns the value for the named path wildcard in the [ServeMux] pattern + * that matched the request. + * It returns the empty string if the request was not matched against a pattern + * or there is no such wildcard in the pattern. */ - waitDelay: time.Duration + pathValue(name: string): string } - interface Cmd { + interface Request { /** - * String returns a human-readable description of c. - * It is intended only for debugging. - * In particular, it is not suitable for use as input to a shell. - * The output of String may vary across Go releases. + * SetPathValue sets name to value, so that subsequent calls to r.PathValue(name) + * return value. */ - string(): string + setPathValue(name: string, value: string): void } - interface Cmd { + /** + * A ResponseWriter interface is used by an HTTP handler to + * construct an HTTP response. + * + * A ResponseWriter may not be used after [Handler.ServeHTTP] has returned. + */ + interface ResponseWriter { + [key:string]: any; /** - * Run starts the specified command and waits for it to complete. + * Header returns the header map that will be sent by + * [ResponseWriter.WriteHeader]. The [Header] map also is the mechanism with which + * [Handler] implementations can set HTTP trailers. * - * The returned error is nil if the command runs, has no problems - * copying stdin, stdout, and stderr, and exits with a zero exit - * status. + * Changing the header map after a call to [ResponseWriter.WriteHeader] (or + * [ResponseWriter.Write]) has no effect unless the HTTP status code was of the + * 1xx class or the modified headers are trailers. * - * If the command starts but does not complete successfully, the error is of - * type *ExitError. Other error types may be returned for other situations. + * There are two ways to set Trailers. The preferred way is to + * predeclare in the headers which trailers you will later + * send by setting the "Trailer" header to the names of the + * trailer keys which will come later. In this case, those + * keys of the Header map are treated as if they were + * trailers. See the example. The second way, for trailer + * keys not known to the [Handler] until after the first [ResponseWriter.Write], + * is to prefix the [Header] map keys with the [TrailerPrefix] + * constant value. * - * If the calling goroutine has locked the operating system thread - * with runtime.LockOSThread and modified any inheritable OS-level - * thread state (for example, Linux or Plan 9 name spaces), the new - * process will inherit the caller's thread state. + * To suppress automatic response headers (such as "Date"), set + * their value to nil. */ - run(): void - } - interface Cmd { + header(): Header /** - * Start starts the specified command but does not wait for it to complete. + * Write writes the data to the connection as part of an HTTP reply. * - * If Start returns successfully, the c.Process field will be set. + * If [ResponseWriter.WriteHeader] has not yet been called, Write calls + * WriteHeader(http.StatusOK) before writing the data. If the Header + * does not contain a Content-Type line, Write adds a Content-Type set + * to the result of passing the initial 512 bytes of written data to + * [DetectContentType]. Additionally, if the total size of all written + * data is under a few KB and there are no Flush calls, the + * Content-Length header is added automatically. * - * After a successful call to Start the Wait method must be called in - * order to release associated system resources. + * Depending on the HTTP protocol version and the client, calling + * Write or WriteHeader may prevent future reads on the + * Request.Body. For HTTP/1.x requests, handlers should read any + * needed request body data before writing the response. Once the + * headers have been flushed (due to either an explicit Flusher.Flush + * call or writing enough data to trigger a flush), the request body + * may be unavailable. For HTTP/2 requests, the Go HTTP server permits + * handlers to continue to read the request body while concurrently + * writing the response. However, such behavior may not be supported + * by all HTTP/2 clients. Handlers should read before writing if + * possible to maximize compatibility. */ - start(): void - } - interface Cmd { + write(_arg0: string|Array): number /** - * Wait waits for the command to exit and waits for any copying to - * stdin or copying from stdout or stderr to complete. - * - * The command must have been started by Start. - * - * The returned error is nil if the command runs, has no problems - * copying stdin, stdout, and stderr, and exits with a zero exit - * status. + * WriteHeader sends an HTTP response header with the provided + * status code. * - * If the command fails to run or doesn't complete successfully, the - * error is of type *ExitError. Other error types may be - * returned for I/O problems. + * If WriteHeader is not called explicitly, the first call to Write + * will trigger an implicit WriteHeader(http.StatusOK). + * Thus explicit calls to WriteHeader are mainly used to + * send error codes or 1xx informational responses. * - * If any of c.Stdin, c.Stdout or c.Stderr are not an *os.File, Wait also waits - * for the respective I/O loop copying to or from the process to complete. + * The provided code must be a valid HTTP 1xx-5xx status code. + * Any number of 1xx headers may be written, followed by at most + * one 2xx-5xx header. 1xx headers are sent immediately, but 2xx-5xx + * headers may be buffered. Use the Flusher interface to send + * buffered data. The header map is cleared when 2xx-5xx headers are + * sent, but not with 1xx headers. * - * Wait releases any resources associated with the Cmd. + * The server will automatically send a 100 (Continue) header + * on the first read from the request body if the request has + * an "Expect: 100-continue" header. */ - wait(): void + writeHeader(statusCode: number): void } - interface Cmd { + /** + * A Server defines parameters for running an HTTP server. + * The zero value for Server is a valid configuration. + */ + interface Server { /** - * Output runs the command and returns its standard output. - * Any returned error will usually be of type *ExitError. - * If c.Stderr was nil, Output populates ExitError.Stderr. + * Addr optionally specifies the TCP address for the server to listen on, + * in the form "host:port". If empty, ":http" (port 80) is used. + * The service names are defined in RFC 6335 and assigned by IANA. + * See net.Dial for details of the address format. */ - output(): string|Array - } - interface Cmd { + addr: string + handler: Handler // handler to invoke, http.DefaultServeMux if nil /** - * CombinedOutput runs the command and returns its combined standard - * output and standard error. + * DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler, + * otherwise responds with 200 OK and Content-Length: 0. */ - combinedOutput(): string|Array - } - interface Cmd { + disableGeneralOptionsHandler: boolean /** - * StdinPipe returns a pipe that will be connected to the command's - * standard input when the command starts. - * The pipe will be closed automatically after Wait sees the command exit. - * A caller need only call Close to force the pipe to close sooner. - * For example, if the command being run will not exit until standard input - * is closed, the caller must close the pipe. + * TLSConfig optionally provides a TLS configuration for use + * by ServeTLS and ListenAndServeTLS. Note that this value is + * cloned by ServeTLS and ListenAndServeTLS, so it's not + * possible to modify the configuration with methods like + * tls.Config.SetSessionTicketKeys. To use + * SetSessionTicketKeys, use Server.Serve with a TLS Listener + * instead. */ - stdinPipe(): io.WriteCloser - } - interface Cmd { + tlsConfig?: any /** - * StdoutPipe returns a pipe that will be connected to the command's - * standard output when the command starts. + * ReadTimeout is the maximum duration for reading the entire + * request, including the body. A zero or negative value means + * there will be no timeout. * - * Wait will close the pipe after seeing the command exit, so most callers - * need not close the pipe themselves. It is thus incorrect to call Wait - * before all reads from the pipe have completed. - * For the same reason, it is incorrect to call Run when using StdoutPipe. - * See the example for idiomatic usage. + * Because ReadTimeout does not let Handlers make per-request + * decisions on each request body's acceptable deadline or + * upload rate, most users will prefer to use + * ReadHeaderTimeout. It is valid to use them both. */ - stdoutPipe(): io.ReadCloser - } - interface Cmd { + readTimeout: time.Duration /** - * StderrPipe returns a pipe that will be connected to the command's - * standard error when the command starts. - * - * Wait will close the pipe after seeing the command exit, so most callers - * need not close the pipe themselves. It is thus incorrect to call Wait - * before all reads from the pipe have completed. - * For the same reason, it is incorrect to use Run when using StderrPipe. - * See the StdoutPipe example for idiomatic usage. + * ReadHeaderTimeout is the amount of time allowed to read + * request headers. The connection's read deadline is reset + * after reading the headers and the Handler can decide what + * is considered too slow for the body. If ReadHeaderTimeout + * is zero, the value of ReadTimeout is used. If both are + * zero, there is no timeout. */ - stderrPipe(): io.ReadCloser - } - interface Cmd { + readHeaderTimeout: time.Duration /** - * Environ returns a copy of the environment in which the command would be run - * as it is currently configured. + * WriteTimeout is the maximum duration before timing out + * writes of the response. It is reset whenever a new + * request's header is read. Like ReadTimeout, it does not + * let Handlers make decisions on a per-request basis. + * A zero or negative value means there will be no timeout. */ - environ(): Array - } -} - -/** - * Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html - * - * See README.md for more info. - */ -namespace jwt { - /** - * MapClaims is a claims type that uses the map[string]interface{} for JSON decoding. - * This is the default claims type if you don't supply one - */ - interface MapClaims extends _TygojaDict{} - interface MapClaims { - /** - * VerifyAudience Compares the aud claim against cmp. - * If required is false, this method will return true if the value matches or is unset - */ - verifyAudience(cmp: string, req: boolean): boolean - } - interface MapClaims { + writeTimeout: time.Duration /** - * VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). - * If req is false, it will return true, if exp is unset. + * IdleTimeout is the maximum amount of time to wait for the + * next request when keep-alives are enabled. If IdleTimeout + * is zero, the value of ReadTimeout is used. If both are + * zero, there is no timeout. */ - verifyExpiresAt(cmp: number, req: boolean): boolean - } - interface MapClaims { + idleTimeout: time.Duration /** - * VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). - * If req is false, it will return true, if iat is unset. + * MaxHeaderBytes controls the maximum number of bytes the + * server will read parsing the request header's keys and + * values, including the request line. It does not limit the + * size of the request body. + * If zero, DefaultMaxHeaderBytes is used. */ - verifyIssuedAt(cmp: number, req: boolean): boolean - } - interface MapClaims { + maxHeaderBytes: number /** - * VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). - * If req is false, it will return true, if nbf is unset. + * TLSNextProto optionally specifies a function to take over + * ownership of the provided TLS connection when an ALPN + * protocol upgrade has occurred. The map key is the protocol + * name negotiated. The Handler argument should be used to + * handle HTTP requests and will initialize the Request's TLS + * and RemoteAddr if not already set. The connection is + * automatically closed when the function returns. + * If TLSNextProto is not nil, HTTP/2 support is not enabled + * automatically. */ - verifyNotBefore(cmp: number, req: boolean): boolean - } - interface MapClaims { + tlsNextProto: _TygojaDict /** - * VerifyIssuer compares the iss claim against cmp. - * If required is false, this method will return true if the value matches or is unset + * ConnState specifies an optional callback function that is + * called when a client connection changes state. See the + * ConnState type and associated constants for details. */ - verifyIssuer(cmp: string, req: boolean): boolean - } - interface MapClaims { + connState: (_arg0: net.Conn, _arg1: ConnState) => void /** - * Valid validates time based claims "exp, iat, nbf". - * There is no accounting for clock skew. - * As well, if any of the above claims are not in the token, it will still - * be considered a valid claim. + * ErrorLog specifies an optional logger for errors accepting + * connections, unexpected behavior from handlers, and + * underlying FileSystem errors. + * If nil, logging is done via the log package's standard logger. */ - valid(): void - } -} - -/** - * Package blob provides an easy and portable way to interact with blobs - * within a storage location. Subpackages contain driver implementations of - * blob for supported services. - * - * See https://gocloud.dev/howto/blob/ for a detailed how-to guide. - * - * *blob.Bucket implements io/fs.FS and io/fs.SubFS, so it can be used with - * functions in that package. - * - * # Errors - * - * The errors returned from this package can be inspected in several ways: - * - * The Code function from gocloud.dev/gcerrors will return an error code, also - * defined in that package, when invoked on an error. - * - * The Bucket.ErrorAs method can retrieve the driver error underlying the returned - * error. - * - * # OpenCensus Integration - * - * OpenCensus supports tracing and metric collection for multiple languages and - * backend providers. See https://opencensus.io. - * - * This API collects OpenCensus traces and metrics for the following methods: - * ``` - * - Attributes - * - Copy - * - Delete - * - ListPage - * - NewRangeReader, from creation until the call to Close. (NewReader and ReadAll - * are included because they call NewRangeReader.) - * - NewWriter, from creation until the call to Close. - * ``` - * - * All trace and metric names begin with the package import path. - * The traces add the method name. - * For example, "gocloud.dev/blob/Attributes". - * The metrics are "completed_calls", a count of completed method calls by driver, - * method and status (error code); and "latency", a distribution of method latency - * by driver and method. - * For example, "gocloud.dev/blob/latency". - * - * It also collects the following metrics: - * ``` - * - gocloud.dev/blob/bytes_read: the total number of bytes read, by driver. - * - gocloud.dev/blob/bytes_written: the total number of bytes written, by driver. - * ``` - * - * To enable trace collection in your application, see "Configure Exporter" at - * https://opencensus.io/quickstart/go/tracing. - * To enable metric collection in your application, see "Exporting stats" at - * https://opencensus.io/quickstart/go/metrics. - */ -namespace blob { - /** - * Reader reads bytes from a blob. - * It implements io.ReadSeekCloser, and must be closed after - * reads are finished. - */ - interface Reader { - } - interface Reader { + errorLog?: any /** - * Read implements io.Reader (https://golang.org/pkg/io/#Reader). + * BaseContext optionally specifies a function that returns + * the base context for incoming requests on this server. + * The provided Listener is the specific Listener that's + * about to start accepting requests. + * If BaseContext is nil, the default is context.Background(). + * If non-nil, it must return a non-nil context. */ - read(p: string|Array): number - } - interface Reader { + baseContext: (_arg0: net.Listener) => context.Context /** - * Seek implements io.Seeker (https://golang.org/pkg/io/#Seeker). + * ConnContext optionally specifies a function that modifies + * the context used for a new connection c. The provided ctx + * is derived from the base context and has a ServerContextKey + * value. */ - seek(offset: number, whence: number): number + connContext: (ctx: context.Context, c: net.Conn) => context.Context } - interface Reader { + interface Server { /** - * Close implements io.Closer (https://golang.org/pkg/io/#Closer). + * Close immediately closes all active net.Listeners and any + * connections in state [StateNew], [StateActive], or [StateIdle]. For a + * graceful shutdown, use [Server.Shutdown]. + * + * Close does not attempt to close (and does not even know about) + * any hijacked connections, such as WebSockets. + * + * Close returns any error returned from closing the [Server]'s + * underlying Listener(s). */ close(): void } - interface Reader { + interface Server { /** - * ContentType returns the MIME type of the blob. + * Shutdown gracefully shuts down the server without interrupting any + * active connections. Shutdown works by first closing all open + * listeners, then closing all idle connections, and then waiting + * indefinitely for connections to return to idle and then shut down. + * If the provided context expires before the shutdown is complete, + * Shutdown returns the context's error, otherwise it returns any + * error returned from closing the [Server]'s underlying Listener(s). + * + * When Shutdown is called, [Serve], [ListenAndServe], and + * [ListenAndServeTLS] immediately return [ErrServerClosed]. Make sure the + * program doesn't exit and waits instead for Shutdown to return. + * + * Shutdown does not attempt to close nor wait for hijacked + * connections such as WebSockets. The caller of Shutdown should + * separately notify such long-lived connections of shutdown and wait + * for them to close, if desired. See [Server.RegisterOnShutdown] for a way to + * register shutdown notification functions. + * + * Once Shutdown has been called on a server, it may not be reused; + * future calls to methods such as Serve will return ErrServerClosed. */ - contentType(): string + shutdown(ctx: context.Context): void } - interface Reader { + interface Server { /** - * ModTime returns the time the blob was last modified. + * RegisterOnShutdown registers a function to call on [Server.Shutdown]. + * This can be used to gracefully shutdown connections that have + * undergone ALPN protocol upgrade or that have been hijacked. + * This function should start protocol-specific graceful shutdown, + * but should not wait for shutdown to complete. */ - modTime(): time.Time + registerOnShutdown(f: () => void): void } - interface Reader { + interface Server { /** - * Size returns the size of the blob content in bytes. + * ListenAndServe listens on the TCP network address srv.Addr and then + * calls [Serve] to handle requests on incoming connections. + * Accepted connections are configured to enable TCP keep-alives. + * + * If srv.Addr is blank, ":http" is used. + * + * ListenAndServe always returns a non-nil error. After [Server.Shutdown] or [Server.Close], + * the returned error is [ErrServerClosed]. */ - size(): number + listenAndServe(): void } - interface Reader { + interface Server { /** - * As converts i to driver-specific types. - * See https://gocloud.dev/concepts/as/ for background information, the "As" - * examples in this package for examples, and the driver package - * documentation for the specific types supported for that driver. + * Serve accepts incoming connections on the Listener l, creating a + * new service goroutine for each. The service goroutines read requests and + * then call srv.Handler to reply to them. + * + * HTTP/2 support is only enabled if the Listener returns [*tls.Conn] + * connections and they were configured with "h2" in the TLS + * Config.NextProtos. + * + * Serve always returns a non-nil error and closes l. + * After [Server.Shutdown] or [Server.Close], the returned error is [ErrServerClosed]. */ - as(i: { - }): boolean + serve(l: net.Listener): void } - interface Reader { + interface Server { /** - * WriteTo reads from r and writes to w until there's no more data or - * an error occurs. - * The return value is the number of bytes written to w. + * ServeTLS accepts incoming connections on the Listener l, creating a + * new service goroutine for each. The service goroutines perform TLS + * setup and then read requests, calling srv.Handler to reply to them. * - * It implements the io.WriterTo interface. + * Files containing a certificate and matching private key for the + * server must be provided if neither the [Server]'s + * TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. + * If the certificate is signed by a certificate authority, the + * certFile should be the concatenation of the server's certificate, + * any intermediates, and the CA's certificate. + * + * ServeTLS always returns a non-nil error. After [Server.Shutdown] or [Server.Close], the + * returned error is [ErrServerClosed]. */ - writeTo(w: io.Writer): number + serveTLS(l: net.Listener, certFile: string, keyFile: string): void } - /** - * Attributes contains attributes about a blob. - */ - interface Attributes { + interface Server { /** - * CacheControl specifies caching attributes that services may use - * when serving the blob. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control + * SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. + * By default, keep-alives are always enabled. Only very + * resource-constrained environments or servers in the process of + * shutting down should disable them. */ - cacheControl: string + setKeepAlivesEnabled(v: boolean): void + } + interface Server { /** - * ContentDisposition specifies whether the blob content is expected to be - * displayed inline or as an attachment. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition + * ListenAndServeTLS listens on the TCP network address srv.Addr and + * then calls [ServeTLS] to handle requests on incoming TLS connections. + * Accepted connections are configured to enable TCP keep-alives. + * + * Filenames containing a certificate and matching private key for the + * server must be provided if neither the [Server]'s TLSConfig.Certificates + * nor TLSConfig.GetCertificate are populated. If the certificate is + * signed by a certificate authority, the certFile should be the + * concatenation of the server's certificate, any intermediates, and + * the CA's certificate. + * + * If srv.Addr is blank, ":https" is used. + * + * ListenAndServeTLS always returns a non-nil error. After [Server.Shutdown] or + * [Server.Close], the returned error is [ErrServerClosed]. */ - contentDisposition: string + listenAndServeTLS(certFile: string, keyFile: string): void + } +} + +/** + * Package echo implements high performance, minimalist Go web framework. + * + * Example: + * + * ``` + * package main + * + * import ( + * "github.com/labstack/echo/v5" + * "github.com/labstack/echo/v5/middleware" + * "log" + * "net/http" + * ) + * + * // Handler + * func hello(c echo.Context) error { + * return c.String(http.StatusOK, "Hello, World!") + * } + * + * func main() { + * // Echo instance + * e := echo.New() + * + * // Middleware + * e.Use(middleware.Logger()) + * e.Use(middleware.Recover()) + * + * // Routes + * e.GET("/", hello) + * + * // Start server + * if err := e.Start(":8080"); err != http.ErrServerClosed { + * log.Fatal(err) + * } + * } + * ``` + * + * Learn more at https://echo.labstack.com + */ +namespace echo { + /** + * Context represents the context of the current HTTP request. It holds request and + * response objects, path, path parameters, data and registered handler. + */ + interface Context { + [key:string]: any; /** - * ContentEncoding specifies the encoding used for the blob's content, if any. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + * Request returns `*http.Request`. */ - contentEncoding: string + request(): (http.Request) /** - * ContentLanguage specifies the language used in the blob's content, if any. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language + * SetRequest sets `*http.Request`. */ - contentLanguage: string + setRequest(r: http.Request): void /** - * ContentType is the MIME type of the blob. It will not be empty. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type + * SetResponse sets `*Response`. */ - contentType: string + setResponse(r: Response): void /** - * Metadata holds key/value pairs associated with the blob. - * Keys are guaranteed to be in lowercase, even if the backend service - * has case-sensitive keys (although note that Metadata written via - * this package will always be lowercased). If there are duplicate - * case-insensitive keys (e.g., "foo" and "FOO"), only one value - * will be kept, and it is undefined which one. + * Response returns `*Response`. */ - metadata: _TygojaDict + response(): (Response) /** - * CreateTime is the time the blob was created, if available. If not available, - * CreateTime will be the zero time. + * IsTLS returns true if HTTP connection is TLS otherwise false. */ - createTime: time.Time + isTLS(): boolean /** - * ModTime is the time the blob was last modified. + * IsWebSocket returns true if HTTP connection is WebSocket otherwise false. */ - modTime: time.Time + isWebSocket(): boolean /** - * Size is the size of the blob's content in bytes. + * Scheme returns the HTTP protocol scheme, `http` or `https`. */ - size: number + scheme(): string /** - * MD5 is an MD5 hash of the blob contents or nil if not available. + * RealIP returns the client's network address based on `X-Forwarded-For` + * or `X-Real-IP` request header. + * The behavior can be configured using `Echo#IPExtractor`. */ - md5: string|Array + realIP(): string /** - * ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag. + * RouteInfo returns current request route information. Method, Path, Name and params if they exist for matched route. + * In case of 404 (route not found) and 405 (method not allowed) RouteInfo returns generic struct for these cases. */ - eTag: string - } - interface Attributes { + routeInfo(): RouteInfo /** - * As converts i to driver-specific types. - * See https://gocloud.dev/concepts/as/ for background information, the "As" - * examples in this package for examples, and the driver package - * documentation for the specific types supported for that driver. + * Path returns the registered path for the handler. */ - as(i: { - }): boolean - } - /** - * ListObject represents a single blob returned from List. - */ - interface ListObject { + path(): string /** - * Key is the key for this blob. + * PathParam returns path parameter by name. */ - key: string + pathParam(name: string): string /** - * ModTime is the time the blob was last modified. + * PathParamDefault returns the path parameter or default value for the provided name. + * + * Notes for DefaultRouter implementation: + * Path parameter could be empty for cases like that: + * * route `/release-:version/bin` and request URL is `/release-/bin` + * * route `/api/:version/image.jpg` and request URL is `/api//image.jpg` + * but not when path parameter is last part of route path + * * route `/download/file.:ext` will not match request `/download/file.` */ - modTime: time.Time + pathParamDefault(name: string, defaultValue: string): string /** - * Size is the size of the blob's content in bytes. + * PathParams returns path parameter values. */ - size: number + pathParams(): PathParams /** - * MD5 is an MD5 hash of the blob contents or nil if not available. + * SetPathParams sets path parameters for current request. */ - md5: string|Array + setPathParams(params: PathParams): void /** - * IsDir indicates that this result represents a "directory" in the - * hierarchical namespace, ending in ListOptions.Delimiter. Key can be - * passed as ListOptions.Prefix to list items in the "directory". - * Fields other than Key and IsDir will not be set if IsDir is true. + * QueryParam returns the query param for the provided name. */ - isDir: boolean - } - interface ListObject { + queryParam(name: string): string /** - * As converts i to driver-specific types. - * See https://gocloud.dev/concepts/as/ for background information, the "As" - * examples in this package for examples, and the driver package - * documentation for the specific types supported for that driver. + * QueryParamDefault returns the query param or default value for the provided name. */ - as(i: { - }): boolean - } -} - -/** - * Package types implements some commonly used db serializable types - * like datetime, json, etc. - */ -namespace types { - /** - * JsonArray defines a slice that is safe for json and db read/write. - */ - interface JsonArray extends Array{} - interface JsonArray { + queryParamDefault(name: string, defaultValue: string): string /** - * MarshalJSON implements the [json.Marshaler] interface. + * QueryParams returns the query parameters as `url.Values`. */ - marshalJSON(): string|Array - } - interface JsonArray { + queryParams(): url.Values /** - * Value implements the [driver.Valuer] interface. + * QueryString returns the URL query string. */ - value(): any - } - interface JsonArray { + queryString(): string /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JsonArray[T] instance. + * FormValue returns the form field value for the provided name. */ - scan(value: any): void - } - /** - * JsonMap defines a map that is safe for json and db read/write. - */ - interface JsonMap extends _TygojaDict{} - interface JsonMap { + formValue(name: string): string /** - * MarshalJSON implements the [json.Marshaler] interface. + * FormValueDefault returns the form field value or default value for the provided name. */ - marshalJSON(): string|Array - } - interface JsonMap { + formValueDefault(name: string, defaultValue: string): string /** - * Get retrieves a single value from the current JsonMap. - * - * This helper was added primarily to assist the goja integration since custom map types - * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). + * FormValues returns the form field values as `url.Values`. */ - get(key: string): any - } - interface JsonMap { + formValues(): url.Values /** - * Set sets a single value in the current JsonMap. - * - * This helper was added primarily to assist the goja integration since custom map types - * don't have direct access to the map keys (https://pkg.go.dev/github.com/dop251/goja#hdr-Maps_with_methods). + * FormFile returns the multipart form file for the provided name. */ - set(key: string, value: any): void - } - interface JsonMap { + formFile(name: string): (multipart.FileHeader) /** - * Value implements the [driver.Valuer] interface. + * MultipartForm returns the multipart form. */ - value(): any - } - interface JsonMap { + multipartForm(): (multipart.Form) /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current `JsonMap` instance. + * Cookie returns the named cookie provided in the request. */ - scan(value: any): void - } -} - -/** - * Package schema implements custom Schema and SchemaField datatypes - * for handling the Collection schema definitions. - */ -namespace schema { - // @ts-ignore - import validation = ozzo_validation - /** - * Schema defines a dynamic db schema as a slice of `SchemaField`s. - */ - interface Schema { - } - interface Schema { + cookie(name: string): (http.Cookie) /** - * Fields returns the registered schema fields. + * SetCookie adds a `Set-Cookie` header in HTTP response. */ - fields(): Array<(SchemaField | undefined)> - } - interface Schema { + setCookie(cookie: http.Cookie): void /** - * InitFieldsOptions calls `InitOptions()` for all schema fields. + * Cookies returns the HTTP cookies sent with the request. */ - initFieldsOptions(): void - } - interface Schema { + cookies(): Array<(http.Cookie | undefined)> /** - * Clone creates a deep clone of the current schema. + * Get retrieves data from the context. */ - clone(): (Schema) + get(key: string): { } - interface Schema { /** - * AsMap returns a map with all registered schema field. - * The returned map is indexed with each field name. + * Set saves data in the context. */ - asMap(): _TygojaDict - } - interface Schema { + set(key: string, val: { + }): void /** - * GetFieldById returns a single field by its id. + * Bind binds path params, query params and the request body into provided type `i`. The default binder + * binds body based on Content-Type header. */ - getFieldById(id: string): (SchemaField) - } - interface Schema { + bind(i: { + }): void /** - * GetFieldByName returns a single field by its name. + * Validate validates provided `i`. It is usually called after `Context#Bind()`. + * Validator must be registered using `Echo#Validator`. */ - getFieldByName(name: string): (SchemaField) - } - interface Schema { + validate(i: { + }): void /** - * RemoveField removes a single schema field by its id. - * - * This method does nothing if field with `id` doesn't exist. + * Render renders a template with data and sends a text/html response with status + * code. Renderer must be registered using `Echo.Renderer`. */ - removeField(id: string): void - } - interface Schema { + render(code: number, name: string, data: { + }): void /** - * AddField registers the provided newField to the current schema. - * - * If field with `newField.Id` already exist, the existing field is - * replaced with the new one. - * - * Otherwise the new field is appended to the other schema fields. + * HTML sends an HTTP response with status code. */ - addField(newField: SchemaField): void - } - interface Schema { + html(code: number, html: string): void /** - * Validate makes Schema validatable by implementing [validation.Validatable] interface. - * - * Internally calls each individual field's validator and additionally - * checks for invalid renamed fields and field name duplications. + * HTMLBlob sends an HTTP blob response with status code. */ - validate(): void - } - interface Schema { + htmlBlob(code: number, b: string|Array): void /** - * MarshalJSON implements the [json.Marshaler] interface. + * String sends a string response with status code. */ - marshalJSON(): string|Array - } - interface Schema { + string(code: number, s: string): void /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. - * - * On success, all schema field options are auto initialized. + * JSON sends a JSON response with status code. */ - unmarshalJSON(data: string|Array): void - } - interface Schema { + json(code: number, i: { + }): void /** - * Value implements the [driver.Valuer] interface. + * JSONPretty sends a pretty-print JSON with status code. */ - value(): any - } - interface Schema { + jsonPretty(code: number, i: { + }, indent: string): void /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current Schema instance. + * JSONBlob sends a JSON blob response with status code. */ - scan(value: any): void - } -} - -/** - * Package models implements all PocketBase DB models and DTOs. - */ -namespace models { - type _subZMvJa = BaseModel - interface Admin extends _subZMvJa { - avatar: number - email: string - tokenKey: string - passwordHash: string - lastResetSentAt: types.DateTime - } - interface Admin { + jsonBlob(code: number, b: string|Array): void /** - * TableName returns the Admin model SQL table name. + * JSONP sends a JSONP response with status code. It uses `callback` to construct + * the JSONP payload. */ - tableName(): string - } - interface Admin { + jsonp(code: number, callback: string, i: { + }): void /** - * ValidatePassword validates a plain password against the model's password. + * JSONPBlob sends a JSONP blob response with status code. It uses `callback` + * to construct the JSONP payload. */ - validatePassword(password: string): boolean - } - interface Admin { + jsonpBlob(code: number, callback: string, b: string|Array): void /** - * SetPassword sets cryptographically secure string to `model.Password`. - * - * Additionally this method also resets the LastResetSentAt and the TokenKey fields. + * XML sends an XML response with status code. */ - setPassword(password: string): void - } - interface Admin { + xml(code: number, i: { + }): void /** - * RefreshTokenKey generates and sets new random token key. + * XMLPretty sends a pretty-print XML with status code. */ - refreshTokenKey(): void - } - // @ts-ignore - import validation = ozzo_validation - type _subnGPQT = BaseModel - interface Collection extends _subnGPQT { - name: string - type: string - system: boolean - schema: schema.Schema - indexes: types.JsonArray + xmlPretty(code: number, i: { + }, indent: string): void /** - * rules + * XMLBlob sends an XML blob response with status code. */ - listRule?: string - viewRule?: string - createRule?: string - updateRule?: string - deleteRule?: string - options: types.JsonMap - } - interface Collection { + xmlBlob(code: number, b: string|Array): void /** - * TableName returns the Collection model SQL table name. + * Blob sends a blob response with status code and content type. */ - tableName(): string - } - interface Collection { + blob(code: number, contentType: string, b: string|Array): void /** - * BaseFilesPath returns the storage dir path used by the collection. + * Stream sends a streaming response with status code and content type. */ - baseFilesPath(): string - } - interface Collection { + stream(code: number, contentType: string, r: io.Reader): void /** - * IsBase checks if the current collection has "base" type. + * File sends a response with the content of the file. */ - isBase(): boolean - } - interface Collection { + file(file: string): void /** - * IsAuth checks if the current collection has "auth" type. + * FileFS sends a response with the content of the file from given filesystem. */ - isAuth(): boolean - } - interface Collection { + fileFS(file: string, filesystem: fs.FS): void /** - * IsView checks if the current collection has "view" type. + * Attachment sends a response as attachment, prompting client to save the + * file. */ - isView(): boolean - } - interface Collection { + attachment(file: string, name: string): void /** - * MarshalJSON implements the [json.Marshaler] interface. + * Inline sends a response as inline, opening the file in the browser. */ - marshalJSON(): string|Array - } - interface Collection { + inline(file: string, name: string): void /** - * BaseOptions decodes the current collection options and returns them - * as new [CollectionBaseOptions] instance. + * NoContent sends a response with no body and a status code. */ - baseOptions(): CollectionBaseOptions - } - interface Collection { + noContent(code: number): void /** - * AuthOptions decodes the current collection options and returns them - * as new [CollectionAuthOptions] instance. + * Redirect redirects the request to a provided URL with status code. */ - authOptions(): CollectionAuthOptions - } - interface Collection { + redirect(code: number, url: string): void /** - * ViewOptions decodes the current collection options and returns them - * as new [CollectionViewOptions] instance. + * Error invokes the registered global HTTP error handler. Generally used by middleware. + * A side-effect of calling global error handler is that now Response has been committed (sent to the client) and + * middlewares up in chain can not change Response status code or Response body anymore. + * + * Avoid using this method in handlers as no middleware will be able to effectively handle errors after that. + * Instead of calling this method in handler return your error and let it be handled by middlewares or global error handler. */ - viewOptions(): CollectionViewOptions - } - interface Collection { + error(err: Error): void /** - * NormalizeOptions updates the current collection options with a - * new normalized state based on the collection type. + * Echo returns the `Echo` instance. + * + * WARNING: Remember that Echo public fields and methods are coroutine safe ONLY when you are NOT mutating them + * anywhere in your code after Echo server has started. */ - normalizeOptions(): void + echo(): (Echo) } - interface Collection { + // @ts-ignore + import stdContext = context + /** + * Echo is the top-level framework instance. + * + * Goroutine safety: Do not mutate Echo instance fields after server has started. Accessing these + * fields from handlers/middlewares and changing field values at the same time leads to data-races. + * Same rule applies to adding new routes after server has been started - Adding a route is not Goroutine safe action. + */ + interface Echo { /** - * DecodeOptions decodes the current collection options into the - * provided "result" (must be a pointer). + * NewContextFunc allows using custom context implementations, instead of default *echo.context */ - decodeOptions(result: any): void - } - interface Collection { + newContextFunc: (e: Echo, pathParamAllocSize: number) => ServableContext + debug: boolean + httpErrorHandler: HTTPErrorHandler + binder: Binder + jsonSerializer: JSONSerializer + validator: Validator + renderer: Renderer + logger: Logger + ipExtractor: IPExtractor /** - * SetOptions normalizes and unmarshals the specified options into m.Options. + * Filesystem is file system used by Static and File handlers to access files. + * Defaults to os.DirFS(".") + * + * When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary + * prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths + * including `assets/images` as their prefix. */ - setOptions(typedOptions: any): void - } - type _subFrtBQ = BaseModel - interface ExternalAuth extends _subFrtBQ { - collectionId: string - recordId: string - provider: string - providerId: string - } - interface ExternalAuth { - tableName(): string - } - type _subHFvmX = BaseModel - interface Record extends _subHFvmX { - } - interface Record { + filesystem: fs.FS /** - * TableName returns the table name associated to the current Record model. + * OnAddRoute is called when Echo adds new route to specific host router. Handler is called for every router + * and before route is added to the host router. */ - tableName(): string + onAddRoute: (host: string, route: Routable) => void } - interface Record { + /** + * HandlerFunc defines a function to serve HTTP requests. + */ + interface HandlerFunc {(c: Context): void } + /** + * MiddlewareFunc defines a function to process middleware. + */ + interface MiddlewareFunc {(next: HandlerFunc): HandlerFunc } + interface Echo { /** - * Collection returns the Collection model associated to the current Record model. + * NewContext returns a new Context instance. + * + * Note: both request and response can be left to nil as Echo.ServeHTTP will call c.Reset(req,resp) anyway + * these arguments are useful when creating context for tests and cases like that. */ - collection(): (Collection) + newContext(r: http.Request, w: http.ResponseWriter): Context } - interface Record { + interface Echo { /** - * OriginalCopy returns a copy of the current record model populated - * with its ORIGINAL data state (aka. the initially loaded) and - * everything else reset to the defaults. + * Router returns the default router. */ - originalCopy(): (Record) + router(): Router } - interface Record { + interface Echo { /** - * CleanCopy returns a copy of the current record model populated only - * with its LATEST data state and everything else reset to the defaults. + * Routers returns the new map of host => router. */ - cleanCopy(): (Record) + routers(): _TygojaDict } - interface Record { + interface Echo { /** - * Expand returns a shallow copy of the current Record model expand data. + * RouterFor returns Router for given host. When host is left empty the default router is returned. */ - expand(): _TygojaDict + routerFor(host: string): [Router, boolean] } - interface Record { + interface Echo { /** - * SetExpand shallow copies the provided data to the current Record model's expand. + * ResetRouterCreator resets callback for creating new router instances. + * Note: current (default) router is immediately replaced with router created with creator func and vhost routers are cleared. */ - setExpand(expand: _TygojaDict): void + resetRouterCreator(creator: (e: Echo) => Router): void } - interface Record { + interface Echo { /** - * MergeExpand merges recursively the provided expand data into - * the current model's expand (if any). - * - * Note that if an expanded prop with the same key is a slice (old or new expand) - * then both old and new records will be merged into a new slice (aka. a :merge: [b,c] => [a,b,c]). - * Otherwise the "old" expanded record will be replace with the "new" one (aka. a :merge: aNew => aNew). + * Pre adds middleware to the chain which is run before router tries to find matching route. + * Meaning middleware is executed even for 404 (not found) cases. */ - mergeExpand(expand: _TygojaDict): void + pre(...middleware: MiddlewareFunc[]): void } - interface Record { + interface Echo { /** - * SchemaData returns a shallow copy ONLY of the defined record schema fields data. + * Use adds middleware to the chain which is run after router has found matching route and before route/request handler method is executed. */ - schemaData(): _TygojaDict + use(...middleware: MiddlewareFunc[]): void } - interface Record { + interface Echo { /** - * UnknownData returns a shallow copy ONLY of the unknown record fields data, - * aka. fields that are neither one of the base and special system ones, - * nor defined by the collection schema. + * CONNECT registers a new CONNECT route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - unknownData(): _TygojaDict + connect(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * IgnoreEmailVisibility toggles the flag to ignore the auth record email visibility check. + * DELETE registers a new DELETE route for a path with matching handler in the router + * with optional route-level middleware. Panics on error. */ - ignoreEmailVisibility(state: boolean): void + delete(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * WithUnknownData toggles the export/serialization of unknown data fields - * (false by default). + * GET registers a new GET route for a path with matching handler in the router + * with optional route-level middleware. Panics on error. */ - withUnknownData(state: boolean): void + get(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * Set sets the provided key-value data pair for the current Record model. - * - * If the record collection has field with name matching the provided "key", - * the value will be further normalized according to the field rules. + * HEAD registers a new HEAD route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - set(key: string, value: any): void + head(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * Get returns a normalized single record model data value for "key". + * OPTIONS registers a new OPTIONS route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - get(key: string): any + options(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * GetBool returns the data value for "key" as a bool. + * PATCH registers a new PATCH route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - getBool(key: string): boolean + patch(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * GetString returns the data value for "key" as a string. + * POST registers a new POST route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - getString(key: string): string + post(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * GetInt returns the data value for "key" as an int. + * PUT registers a new PUT route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - getInt(key: string): number + put(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * GetFloat returns the data value for "key" as a float64. + * TRACE registers a new TRACE route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - getFloat(key: string): number + trace(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * GetTime returns the data value for "key" as a [time.Time] instance. + * RouteNotFound registers a special-case route which is executed when no other route is found (i.e. HTTP 404 cases) + * for current request URL. + * Path supports static and named/any parameters just like other http method is defined. Generally path is ended with + * wildcard/match-any character (`/*`, `/download/*` etc). + * + * Example: `e.RouteNotFound("/*", func(c echo.Context) error { return c.NoContent(http.StatusNotFound) })` */ - getTime(key: string): time.Time + routeNotFound(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * GetDateTime returns the data value for "key" as a DateTime instance. + * Any registers a new route for all HTTP methods (supported by Echo) and path with matching handler + * in the router with optional route-level middleware. + * + * Note: this method only adds specific set of supported HTTP methods as handler and is not true + * "catch-any-arbitrary-method" way of matching requests. */ - getDateTime(key: string): types.DateTime + any(path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes } - interface Record { + interface Echo { /** - * GetStringSlice returns the data value for "key" as a slice of unique strings. + * Match registers a new route for multiple HTTP methods and path with matching + * handler in the router with optional route-level middleware. Panics on error. */ - getStringSlice(key: string): Array + match(methods: Array, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes } - interface Record { + interface Echo { /** - * ExpandedOne retrieves a single relation Record from the already - * loaded expand data of the current model. - * - * If the requested expand relation is multiple, this method returns - * only first available Record from the expanded relation. - * - * Returns nil if there is no such expand relation loaded. + * Static registers a new route with path prefix to serve static files from the provided root directory. */ - expandedOne(relField: string): (Record) + static(pathPrefix: string, fsRoot: string): RouteInfo } - interface Record { + interface Echo { /** - * ExpandedAll retrieves a slice of relation Records from the already - * loaded expand data of the current model. - * - * If the requested expand relation is single, this method normalizes - * the return result and will wrap the single model as a slice. + * StaticFS registers a new route with path prefix to serve static files from the provided file system. * - * Returns nil slice if there is no such expand relation loaded. + * When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary + * prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths + * including `assets/images` as their prefix. */ - expandedAll(relField: string): Array<(Record | undefined)> + staticFS(pathPrefix: string, filesystem: fs.FS): RouteInfo } - interface Record { + interface Echo { /** - * Retrieves the "key" json field value and unmarshals it into "result". - * - * Example - * - * ``` - * result := struct { - * FirstName string `json:"first_name"` - * }{} - * err := m.UnmarshalJSONField("my_field_name", &result) - * ``` + * FileFS registers a new route with path to serve file from the provided file system. */ - unmarshalJSONField(key: string, result: any): void + fileFS(path: string, file: string, filesystem: fs.FS, ...m: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * BaseFilesPath returns the storage dir path used by the record. + * File registers a new route with path to serve a static file with optional route-level middleware. Panics on error. */ - baseFilesPath(): string + file(path: string, file: string, ...middleware: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * FindFileFieldByFile returns the first file type field for which - * any of the record's data contains the provided filename. + * AddRoute registers a new Route with default host Router */ - findFileFieldByFile(filename: string): (schema.SchemaField) + addRoute(route: Routable): RouteInfo } - interface Record { + interface Echo { /** - * Load bulk loads the provided data into the current Record model. + * Add registers a new route for an HTTP method and path with matching handler + * in the router with optional route-level middleware. */ - load(data: _TygojaDict): void + add(method: string, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): RouteInfo } - interface Record { + interface Echo { /** - * ColumnValueMap implements [ColumnValueMapper] interface. + * Host creates a new router group for the provided host and optional host-level middleware. */ - columnValueMap(): _TygojaDict + host(name: string, ...m: MiddlewareFunc[]): (Group) } - interface Record { + interface Echo { /** - * PublicExport exports only the record fields that are safe to be public. - * - * For auth records, to force the export of the email field you need to set - * `m.IgnoreEmailVisibility(true)`. + * Group creates a new router group with prefix and optional group-level middleware. */ - publicExport(): _TygojaDict + group(prefix: string, ...m: MiddlewareFunc[]): (Group) } - interface Record { + interface Echo { /** - * MarshalJSON implements the [json.Marshaler] interface. - * - * Only the data exported by `PublicExport()` will be serialized. + * AcquireContext returns an empty `Context` instance from the pool. + * You must return the context by calling `ReleaseContext()`. */ - marshalJSON(): string|Array + acquireContext(): Context } - interface Record { + interface Echo { /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. + * ReleaseContext returns the `Context` instance back to the pool. + * You must call it after `AcquireContext()`. */ - unmarshalJSON(data: string|Array): void + releaseContext(c: Context): void } - interface Record { + interface Echo { /** - * ReplaceModifers returns a new map with applied modifier - * values based on the current record and the specified data. + * ServeHTTP implements `http.Handler` interface, which serves HTTP requests. + */ + serveHTTP(w: http.ResponseWriter, r: http.Request): void + } + interface Echo { + /** + * Start stars HTTP server on given address with Echo as a handler serving requests. The server can be shutdown by + * sending os.Interrupt signal with `ctrl+c`. * - * The resolved modifier keys will be removed. + * Note: this method is created for use in examples/demos and is deliberately simple without providing configuration + * options. * - * Multiple modifiers will be applied one after another, - * while reusing the previous base key value result (eg. 1; -5; +2 => -2). + * In need of customization use: * - * Example usage: + * ``` + * sc := echo.StartConfig{Address: ":8080"} + * if err := sc.Start(e); err != http.ErrServerClosed { + * log.Fatal(err) + * } + * ``` + * + * // or standard library `http.Server` * * ``` - * newData := record.ReplaceModifers(data) - * // record: {"field": 10} - * // data: {"field+": 5} - * // newData: {"field": 15} + * s := http.Server{Addr: ":8080", Handler: e} + * if err := s.ListenAndServe(); err != http.ErrServerClosed { + * log.Fatal(err) + * } * ``` */ - replaceModifers(data: _TygojaDict): _TygojaDict + start(address: string): void } - interface Record { +} + +/** + * Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html + * + * See README.md for more info. + */ +namespace jwt { + /** + * MapClaims is a claims type that uses the map[string]interface{} for JSON decoding. + * This is the default claims type if you don't supply one + */ + interface MapClaims extends _TygojaDict{} + interface MapClaims { /** - * Username returns the "username" auth record data value. + * VerifyAudience Compares the aud claim against cmp. + * If required is false, this method will return true if the value matches or is unset */ - username(): string + verifyAudience(cmp: string, req: boolean): boolean } - interface Record { + interface MapClaims { /** - * SetUsername sets the "username" auth record data value. - * - * This method doesn't check whether the provided value is a valid username. - * - * Returns an error if the record is not from an auth collection. + * VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). + * If req is false, it will return true, if exp is unset. */ - setUsername(username: string): void + verifyExpiresAt(cmp: number, req: boolean): boolean } - interface Record { + interface MapClaims { /** - * Email returns the "email" auth record data value. + * VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). + * If req is false, it will return true, if iat is unset. */ - email(): string + verifyIssuedAt(cmp: number, req: boolean): boolean } - interface Record { + interface MapClaims { /** - * SetEmail sets the "email" auth record data value. - * - * This method doesn't check whether the provided value is a valid email. - * - * Returns an error if the record is not from an auth collection. + * VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). + * If req is false, it will return true, if nbf is unset. */ - setEmail(email: string): void + verifyNotBefore(cmp: number, req: boolean): boolean } - interface Record { + interface MapClaims { /** - * Verified returns the "emailVisibility" auth record data value. + * VerifyIssuer compares the iss claim against cmp. + * If required is false, this method will return true if the value matches or is unset */ - emailVisibility(): boolean + verifyIssuer(cmp: string, req: boolean): boolean } - interface Record { + interface MapClaims { /** - * SetEmailVisibility sets the "emailVisibility" auth record data value. - * - * Returns an error if the record is not from an auth collection. + * Valid validates time based claims "exp, iat, nbf". + * There is no accounting for clock skew. + * As well, if any of the above claims are not in the token, it will still + * be considered a valid claim. */ - setEmailVisibility(visible: boolean): void + valid(): void } - interface Record { - /** - * Verified returns the "verified" auth record data value. - */ - verified(): boolean +} + +/** + * Package blob provides an easy and portable way to interact with blobs + * within a storage location. Subpackages contain driver implementations of + * blob for supported services. + * + * See https://gocloud.dev/howto/blob/ for a detailed how-to guide. + * + * *blob.Bucket implements io/fs.FS and io/fs.SubFS, so it can be used with + * functions in that package. + * + * # Errors + * + * The errors returned from this package can be inspected in several ways: + * + * The Code function from gocloud.dev/gcerrors will return an error code, also + * defined in that package, when invoked on an error. + * + * The Bucket.ErrorAs method can retrieve the driver error underlying the returned + * error. + * + * # OpenCensus Integration + * + * OpenCensus supports tracing and metric collection for multiple languages and + * backend providers. See https://opencensus.io. + * + * This API collects OpenCensus traces and metrics for the following methods: + * ``` + * - Attributes + * - Copy + * - Delete + * - ListPage + * - NewRangeReader, from creation until the call to Close. (NewReader and ReadAll + * are included because they call NewRangeReader.) + * - NewWriter, from creation until the call to Close. + * ``` + * + * All trace and metric names begin with the package import path. + * The traces add the method name. + * For example, "gocloud.dev/blob/Attributes". + * The metrics are "completed_calls", a count of completed method calls by driver, + * method and status (error code); and "latency", a distribution of method latency + * by driver and method. + * For example, "gocloud.dev/blob/latency". + * + * It also collects the following metrics: + * ``` + * - gocloud.dev/blob/bytes_read: the total number of bytes read, by driver. + * - gocloud.dev/blob/bytes_written: the total number of bytes written, by driver. + * ``` + * + * To enable trace collection in your application, see "Configure Exporter" at + * https://opencensus.io/quickstart/go/tracing. + * To enable metric collection in your application, see "Exporting stats" at + * https://opencensus.io/quickstart/go/metrics. + */ +namespace blob { + /** + * Reader reads bytes from a blob. + * It implements io.ReadSeekCloser, and must be closed after + * reads are finished. + */ + interface Reader { } - interface Record { + interface Reader { /** - * SetVerified sets the "verified" auth record data value. - * - * Returns an error if the record is not from an auth collection. + * Read implements io.Reader (https://golang.org/pkg/io/#Reader). */ - setVerified(verified: boolean): void + read(p: string|Array): number } - interface Record { + interface Reader { /** - * TokenKey returns the "tokenKey" auth record data value. + * Seek implements io.Seeker (https://golang.org/pkg/io/#Seeker). */ - tokenKey(): string + seek(offset: number, whence: number): number } - interface Record { + interface Reader { /** - * SetTokenKey sets the "tokenKey" auth record data value. - * - * Returns an error if the record is not from an auth collection. + * Close implements io.Closer (https://golang.org/pkg/io/#Closer). */ - setTokenKey(key: string): void + close(): void } - interface Record { + interface Reader { /** - * RefreshTokenKey generates and sets new random auth record "tokenKey". - * - * Returns an error if the record is not from an auth collection. + * ContentType returns the MIME type of the blob. */ - refreshTokenKey(): void + contentType(): string } - interface Record { + interface Reader { /** - * LastResetSentAt returns the "lastResentSentAt" auth record data value. + * ModTime returns the time the blob was last modified. */ - lastResetSentAt(): types.DateTime + modTime(): time.Time } - interface Record { + interface Reader { /** - * SetLastResetSentAt sets the "lastResentSentAt" auth record data value. - * - * Returns an error if the record is not from an auth collection. + * Size returns the size of the blob content in bytes. */ - setLastResetSentAt(dateTime: types.DateTime): void + size(): number } - interface Record { + interface Reader { /** - * LastVerificationSentAt returns the "lastVerificationSentAt" auth record data value. + * As converts i to driver-specific types. + * See https://gocloud.dev/concepts/as/ for background information, the "As" + * examples in this package for examples, and the driver package + * documentation for the specific types supported for that driver. */ - lastVerificationSentAt(): types.DateTime + as(i: { + }): boolean } - interface Record { + interface Reader { /** - * SetLastVerificationSentAt sets an "lastVerificationSentAt" auth record data value. + * WriteTo reads from r and writes to w until there's no more data or + * an error occurs. + * The return value is the number of bytes written to w. * - * Returns an error if the record is not from an auth collection. + * It implements the io.WriterTo interface. */ - setLastVerificationSentAt(dateTime: types.DateTime): void + writeTo(w: io.Writer): number } - interface Record { + /** + * Attributes contains attributes about a blob. + */ + interface Attributes { /** - * PasswordHash returns the "passwordHash" auth record data value. + * CacheControl specifies caching attributes that services may use + * when serving the blob. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control */ - passwordHash(): string - } - interface Record { + cacheControl: string /** - * ValidatePassword validates a plain password against the auth record password. - * - * Returns false if the password is incorrect or record is not from an auth collection. + * ContentDisposition specifies whether the blob content is expected to be + * displayed inline or as an attachment. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition */ - validatePassword(password: string): boolean - } - interface Record { + contentDisposition: string /** - * SetPassword sets cryptographically secure string to the auth record "password" field. - * This method also resets the "lastResetSentAt" and the "tokenKey" fields. - * - * Returns an error if the record is not from an auth collection or - * an empty password is provided. + * ContentEncoding specifies the encoding used for the blob's content, if any. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding */ - setPassword(password: string): void - } - /** - * RequestInfo defines a HTTP request data struct, usually used - * as part of the `@request.*` filter resolver. - */ - interface RequestInfo { - context: string - query: _TygojaDict - data: _TygojaDict - headers: _TygojaDict - authRecord?: Record - admin?: Admin - method: string - } - interface RequestInfo { + contentEncoding: string /** - * HasModifierDataKeys loosely checks if the current struct has any modifier Data keys. + * ContentLanguage specifies the language used in the blob's content, if any. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language */ - hasModifierDataKeys(): boolean - } -} - -namespace auth { - /** - * AuthUser defines a standardized oauth2 user data structure. - */ - interface AuthUser { - id: string - name: string - username: string - email: string - avatarUrl: string - accessToken: string - refreshToken: string - expiry: types.DateTime - rawUser: _TygojaDict - } - /** - * Provider defines a common interface for an OAuth2 client. - */ - interface Provider { - [key:string]: any; + contentLanguage: string /** - * Context returns the context associated with the provider (if any). + * ContentType is the MIME type of the blob. It will not be empty. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type */ - context(): context.Context + contentType: string /** - * SetContext assigns the specified context to the current provider. + * Metadata holds key/value pairs associated with the blob. + * Keys are guaranteed to be in lowercase, even if the backend service + * has case-sensitive keys (although note that Metadata written via + * this package will always be lowercased). If there are duplicate + * case-insensitive keys (e.g., "foo" and "FOO"), only one value + * will be kept, and it is undefined which one. */ - setContext(ctx: context.Context): void + metadata: _TygojaDict /** - * PKCE indicates whether the provider can use the PKCE flow. + * CreateTime is the time the blob was created, if available. If not available, + * CreateTime will be the zero time. */ - pkce(): boolean + createTime: time.Time /** - * SetPKCE toggles the state whether the provider can use the PKCE flow or not. + * ModTime is the time the blob was last modified. */ - setPKCE(enable: boolean): void + modTime: time.Time /** - * DisplayName usually returns provider name as it is officially written - * and it could be used directly in the UI. + * Size is the size of the blob's content in bytes. */ - displayName(): string + size: number /** - * SetDisplayName sets the provider's display name. + * MD5 is an MD5 hash of the blob contents or nil if not available. */ - setDisplayName(displayName: string): void + md5: string|Array /** - * Scopes returns the provider access permissions that will be requested. + * ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag. */ - scopes(): Array + eTag: string + } + interface Attributes { /** - * SetScopes sets the provider access permissions that will be requested later. + * As converts i to driver-specific types. + * See https://gocloud.dev/concepts/as/ for background information, the "As" + * examples in this package for examples, and the driver package + * documentation for the specific types supported for that driver. */ - setScopes(scopes: Array): void + as(i: { + }): boolean + } + /** + * ListObject represents a single blob returned from List. + */ + interface ListObject { /** - * ClientId returns the provider client's app ID. + * Key is the key for this blob. */ - clientId(): string + key: string /** - * SetClientId sets the provider client's ID. + * ModTime is the time the blob was last modified. */ - setClientId(clientId: string): void + modTime: time.Time /** - * ClientSecret returns the provider client's app secret. + * Size is the size of the blob's content in bytes. */ - clientSecret(): string + size: number /** - * SetClientSecret sets the provider client's app secret. + * MD5 is an MD5 hash of the blob contents or nil if not available. */ - setClientSecret(secret: string): void + md5: string|Array /** - * RedirectUrl returns the end address to redirect the user - * going through the OAuth flow. + * IsDir indicates that this result represents a "directory" in the + * hierarchical namespace, ending in ListOptions.Delimiter. Key can be + * passed as ListOptions.Prefix to list items in the "directory". + * Fields other than Key and IsDir will not be set if IsDir is true. */ - redirectUrl(): string + isDir: boolean + } + interface ListObject { /** - * SetRedirectUrl sets the provider's RedirectUrl. + * As converts i to driver-specific types. + * See https://gocloud.dev/concepts/as/ for background information, the "As" + * examples in this package for examples, and the driver package + * documentation for the specific types supported for that driver. */ - setRedirectUrl(url: string): void + as(i: { + }): boolean + } +} + +/** + * Package schema implements custom Schema and SchemaField datatypes + * for handling the Collection schema definitions. + */ +namespace schema { + // @ts-ignore + import validation = ozzo_validation + /** + * Schema defines a dynamic db schema as a slice of `SchemaField`s. + */ + interface Schema { + } + interface Schema { /** - * AuthUrl returns the provider's authorization service url. + * Fields returns the registered schema fields. */ - authUrl(): string + fields(): Array<(SchemaField | undefined)> + } + interface Schema { /** - * SetAuthUrl sets the provider's AuthUrl. + * InitFieldsOptions calls `InitOptions()` for all schema fields. */ - setAuthUrl(url: string): void + initFieldsOptions(): void + } + interface Schema { /** - * TokenUrl returns the provider's token exchange service url. + * Clone creates a deep clone of the current schema. */ - tokenUrl(): string + clone(): (Schema) + } + interface Schema { /** - * SetTokenUrl sets the provider's TokenUrl. + * AsMap returns a map with all registered schema field. + * The returned map is indexed with each field name. */ - setTokenUrl(url: string): void + asMap(): _TygojaDict + } + interface Schema { /** - * UserApiUrl returns the provider's user info api url. + * GetFieldById returns a single field by its id. */ - userApiUrl(): string + getFieldById(id: string): (SchemaField) + } + interface Schema { /** - * SetUserApiUrl sets the provider's UserApiUrl. + * GetFieldByName returns a single field by its name. */ - setUserApiUrl(url: string): void + getFieldByName(name: string): (SchemaField) + } + interface Schema { /** - * Client returns an http client using the provided token. + * RemoveField removes a single schema field by its id. + * + * This method does nothing if field with `id` doesn't exist. */ - client(token: oauth2.Token): (any) + removeField(id: string): void + } + interface Schema { /** - * BuildAuthUrl returns a URL to the provider's consent page - * that asks for permissions for the required scopes explicitly. + * AddField registers the provided newField to the current schema. + * + * If field with `newField.Id` already exist, the existing field is + * replaced with the new one. + * + * Otherwise the new field is appended to the other schema fields. */ - buildAuthUrl(state: string, ...opts: oauth2.AuthCodeOption[]): string + addField(newField: SchemaField): void + } + interface Schema { /** - * FetchToken converts an authorization code to token. + * Validate makes Schema validatable by implementing [validation.Validatable] interface. + * + * Internally calls each individual field's validator and additionally + * checks for invalid renamed fields and field name duplications. */ - fetchToken(code: string, ...opts: oauth2.AuthCodeOption[]): (oauth2.Token) + validate(): void + } + interface Schema { /** - * FetchRawUserData requests and marshalizes into `result` the - * the OAuth user api response. + * MarshalJSON implements the [json.Marshaler] interface. */ - fetchRawUserData(token: oauth2.Token): string|Array + marshalJSON(): string|Array + } + interface Schema { /** - * FetchAuthUser is similar to FetchRawUserData, but normalizes and - * marshalizes the user api response into a standardized AuthUser struct. + * UnmarshalJSON implements the [json.Unmarshaler] interface. + * + * On success, all schema field options are auto initialized. */ - fetchAuthUser(token: oauth2.Token): (AuthUser) + unmarshalJSON(data: string|Array): void + } + interface Schema { + /** + * Value implements the [driver.Valuer] interface. + */ + value(): any + } + interface Schema { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current Schema instance. + */ + scan(value: any): void } } /** - * Package echo implements high performance, minimalist Go web framework. - * - * Example: - * - * ``` - * package main - * - * import ( - * "github.com/labstack/echo/v5" - * "github.com/labstack/echo/v5/middleware" - * "log" - * "net/http" - * ) - * - * // Handler - * func hello(c echo.Context) error { - * return c.String(http.StatusOK, "Hello, World!") - * } - * - * func main() { - * // Echo instance - * e := echo.New() - * - * // Middleware - * e.Use(middleware.Logger()) - * e.Use(middleware.Recover()) - * - * // Routes - * e.GET("/", hello) - * - * // Start server - * if err := e.Start(":8080"); err != http.ErrServerClosed { - * log.Fatal(err) - * } - * } - * ``` - * - * Learn more at https://echo.labstack.com + * Package models implements all PocketBase DB models and DTOs. */ -namespace echo { - /** - * Context represents the context of the current HTTP request. It holds request and - * response objects, path, path parameters, data and registered handler. - */ - interface Context { - [key:string]: any; +namespace models { + type _subKFBeq = BaseModel + interface Admin extends _subKFBeq { + avatar: number + email: string + tokenKey: string + passwordHash: string + lastResetSentAt: types.DateTime + } + interface Admin { /** - * Request returns `*http.Request`. + * TableName returns the Admin model SQL table name. */ - request(): (http.Request) + tableName(): string + } + interface Admin { /** - * SetRequest sets `*http.Request`. + * ValidatePassword validates a plain password against the model's password. */ - setRequest(r: http.Request): void + validatePassword(password: string): boolean + } + interface Admin { /** - * SetResponse sets `*Response`. + * SetPassword sets cryptographically secure string to `model.Password`. + * + * Additionally this method also resets the LastResetSentAt and the TokenKey fields. */ - setResponse(r: Response): void + setPassword(password: string): void + } + interface Admin { /** - * Response returns `*Response`. + * RefreshTokenKey generates and sets new random token key. */ - response(): (Response) + refreshTokenKey(): void + } + // @ts-ignore + import validation = ozzo_validation + type _subnEoHe = BaseModel + interface Collection extends _subnEoHe { + name: string + type: string + system: boolean + schema: schema.Schema + indexes: types.JsonArray /** - * IsTLS returns true if HTTP connection is TLS otherwise false. + * rules */ - isTLS(): boolean + listRule?: string + viewRule?: string + createRule?: string + updateRule?: string + deleteRule?: string + options: types.JsonMap + } + interface Collection { /** - * IsWebSocket returns true if HTTP connection is WebSocket otherwise false. + * TableName returns the Collection model SQL table name. */ - isWebSocket(): boolean + tableName(): string + } + interface Collection { /** - * Scheme returns the HTTP protocol scheme, `http` or `https`. + * BaseFilesPath returns the storage dir path used by the collection. */ - scheme(): string + baseFilesPath(): string + } + interface Collection { /** - * RealIP returns the client's network address based on `X-Forwarded-For` - * or `X-Real-IP` request header. - * The behavior can be configured using `Echo#IPExtractor`. + * IsBase checks if the current collection has "base" type. */ - realIP(): string + isBase(): boolean + } + interface Collection { /** - * RouteInfo returns current request route information. Method, Path, Name and params if they exist for matched route. - * In case of 404 (route not found) and 405 (method not allowed) RouteInfo returns generic struct for these cases. + * IsAuth checks if the current collection has "auth" type. */ - routeInfo(): RouteInfo + isAuth(): boolean + } + interface Collection { /** - * Path returns the registered path for the handler. + * IsView checks if the current collection has "view" type. */ - path(): string + isView(): boolean + } + interface Collection { /** - * PathParam returns path parameter by name. + * MarshalJSON implements the [json.Marshaler] interface. */ - pathParam(name: string): string + marshalJSON(): string|Array + } + interface Collection { /** - * PathParamDefault returns the path parameter or default value for the provided name. - * - * Notes for DefaultRouter implementation: - * Path parameter could be empty for cases like that: - * * route `/release-:version/bin` and request URL is `/release-/bin` - * * route `/api/:version/image.jpg` and request URL is `/api//image.jpg` - * but not when path parameter is last part of route path - * * route `/download/file.:ext` will not match request `/download/file.` + * BaseOptions decodes the current collection options and returns them + * as new [CollectionBaseOptions] instance. */ - pathParamDefault(name: string, defaultValue: string): string + baseOptions(): CollectionBaseOptions + } + interface Collection { /** - * PathParams returns path parameter values. + * AuthOptions decodes the current collection options and returns them + * as new [CollectionAuthOptions] instance. */ - pathParams(): PathParams + authOptions(): CollectionAuthOptions + } + interface Collection { /** - * SetPathParams sets path parameters for current request. + * ViewOptions decodes the current collection options and returns them + * as new [CollectionViewOptions] instance. */ - setPathParams(params: PathParams): void + viewOptions(): CollectionViewOptions + } + interface Collection { /** - * QueryParam returns the query param for the provided name. + * NormalizeOptions updates the current collection options with a + * new normalized state based on the collection type. */ - queryParam(name: string): string + normalizeOptions(): void + } + interface Collection { /** - * QueryParamDefault returns the query param or default value for the provided name. + * DecodeOptions decodes the current collection options into the + * provided "result" (must be a pointer). */ - queryParamDefault(name: string, defaultValue: string): string + decodeOptions(result: any): void + } + interface Collection { /** - * QueryParams returns the query parameters as `url.Values`. + * SetOptions normalizes and unmarshals the specified options into m.Options. */ - queryParams(): url.Values + setOptions(typedOptions: any): void + } + type _submpsOP = BaseModel + interface ExternalAuth extends _submpsOP { + collectionId: string + recordId: string + provider: string + providerId: string + } + interface ExternalAuth { + tableName(): string + } + type _subMeygg = BaseModel + interface Record extends _subMeygg { + } + interface Record { /** - * QueryString returns the URL query string. + * TableName returns the table name associated to the current Record model. */ - queryString(): string + tableName(): string + } + interface Record { /** - * FormValue returns the form field value for the provided name. + * Collection returns the Collection model associated to the current Record model. */ - formValue(name: string): string + collection(): (Collection) + } + interface Record { /** - * FormValueDefault returns the form field value or default value for the provided name. + * OriginalCopy returns a copy of the current record model populated + * with its ORIGINAL data state (aka. the initially loaded) and + * everything else reset to the defaults. */ - formValueDefault(name: string, defaultValue: string): string + originalCopy(): (Record) + } + interface Record { /** - * FormValues returns the form field values as `url.Values`. + * CleanCopy returns a copy of the current record model populated only + * with its LATEST data state and everything else reset to the defaults. */ - formValues(): url.Values + cleanCopy(): (Record) + } + interface Record { /** - * FormFile returns the multipart form file for the provided name. + * Expand returns a shallow copy of the current Record model expand data. */ - formFile(name: string): (multipart.FileHeader) + expand(): _TygojaDict + } + interface Record { /** - * MultipartForm returns the multipart form. + * SetExpand shallow copies the provided data to the current Record model's expand. */ - multipartForm(): (multipart.Form) + setExpand(expand: _TygojaDict): void + } + interface Record { /** - * Cookie returns the named cookie provided in the request. + * MergeExpand merges recursively the provided expand data into + * the current model's expand (if any). + * + * Note that if an expanded prop with the same key is a slice (old or new expand) + * then both old and new records will be merged into a new slice (aka. a :merge: [b,c] => [a,b,c]). + * Otherwise the "old" expanded record will be replace with the "new" one (aka. a :merge: aNew => aNew). */ - cookie(name: string): (http.Cookie) - /** - * SetCookie adds a `Set-Cookie` header in HTTP response. - */ - setCookie(cookie: http.Cookie): void + mergeExpand(expand: _TygojaDict): void + } + interface Record { /** - * Cookies returns the HTTP cookies sent with the request. + * SchemaData returns a shallow copy ONLY of the defined record schema fields data. */ - cookies(): Array<(http.Cookie | undefined)> + schemaData(): _TygojaDict + } + interface Record { /** - * Get retrieves data from the context. + * UnknownData returns a shallow copy ONLY of the unknown record fields data, + * aka. fields that are neither one of the base and special system ones, + * nor defined by the collection schema. */ - get(key: string): { + unknownData(): _TygojaDict } + interface Record { /** - * Set saves data in the context. + * IgnoreEmailVisibility toggles the flag to ignore the auth record email visibility check. */ - set(key: string, val: { - }): void + ignoreEmailVisibility(state: boolean): void + } + interface Record { /** - * Bind binds path params, query params and the request body into provided type `i`. The default binder - * binds body based on Content-Type header. + * WithUnknownData toggles the export/serialization of unknown data fields + * (false by default). */ - bind(i: { - }): void + withUnknownData(state: boolean): void + } + interface Record { /** - * Validate validates provided `i`. It is usually called after `Context#Bind()`. - * Validator must be registered using `Echo#Validator`. + * Set sets the provided key-value data pair for the current Record model. + * + * If the record collection has field with name matching the provided "key", + * the value will be further normalized according to the field rules. */ - validate(i: { - }): void + set(key: string, value: any): void + } + interface Record { /** - * Render renders a template with data and sends a text/html response with status - * code. Renderer must be registered using `Echo.Renderer`. + * Get returns a normalized single record model data value for "key". */ - render(code: number, name: string, data: { - }): void + get(key: string): any + } + interface Record { /** - * HTML sends an HTTP response with status code. + * GetBool returns the data value for "key" as a bool. */ - html(code: number, html: string): void + getBool(key: string): boolean + } + interface Record { /** - * HTMLBlob sends an HTTP blob response with status code. + * GetString returns the data value for "key" as a string. */ - htmlBlob(code: number, b: string|Array): void + getString(key: string): string + } + interface Record { /** - * String sends a string response with status code. + * GetInt returns the data value for "key" as an int. */ - string(code: number, s: string): void + getInt(key: string): number + } + interface Record { /** - * JSON sends a JSON response with status code. + * GetFloat returns the data value for "key" as a float64. */ - json(code: number, i: { - }): void + getFloat(key: string): number + } + interface Record { /** - * JSONPretty sends a pretty-print JSON with status code. + * GetTime returns the data value for "key" as a [time.Time] instance. */ - jsonPretty(code: number, i: { - }, indent: string): void + getTime(key: string): time.Time + } + interface Record { /** - * JSONBlob sends a JSON blob response with status code. + * GetDateTime returns the data value for "key" as a DateTime instance. */ - jsonBlob(code: number, b: string|Array): void + getDateTime(key: string): types.DateTime + } + interface Record { /** - * JSONP sends a JSONP response with status code. It uses `callback` to construct - * the JSONP payload. + * GetStringSlice returns the data value for "key" as a slice of unique strings. */ - jsonp(code: number, callback: string, i: { - }): void + getStringSlice(key: string): Array + } + interface Record { /** - * JSONPBlob sends a JSONP blob response with status code. It uses `callback` - * to construct the JSONP payload. + * ExpandedOne retrieves a single relation Record from the already + * loaded expand data of the current model. + * + * If the requested expand relation is multiple, this method returns + * only first available Record from the expanded relation. + * + * Returns nil if there is no such expand relation loaded. */ - jsonpBlob(code: number, callback: string, b: string|Array): void + expandedOne(relField: string): (Record) + } + interface Record { /** - * XML sends an XML response with status code. + * ExpandedAll retrieves a slice of relation Records from the already + * loaded expand data of the current model. + * + * If the requested expand relation is single, this method normalizes + * the return result and will wrap the single model as a slice. + * + * Returns nil slice if there is no such expand relation loaded. */ - xml(code: number, i: { - }): void + expandedAll(relField: string): Array<(Record | undefined)> + } + interface Record { /** - * XMLPretty sends a pretty-print XML with status code. + * Retrieves the "key" json field value and unmarshals it into "result". + * + * Example + * + * ``` + * result := struct { + * FirstName string `json:"first_name"` + * }{} + * err := m.UnmarshalJSONField("my_field_name", &result) + * ``` */ - xmlPretty(code: number, i: { - }, indent: string): void + unmarshalJSONField(key: string, result: any): void + } + interface Record { /** - * XMLBlob sends an XML blob response with status code. + * BaseFilesPath returns the storage dir path used by the record. */ - xmlBlob(code: number, b: string|Array): void + baseFilesPath(): string + } + interface Record { /** - * Blob sends a blob response with status code and content type. + * FindFileFieldByFile returns the first file type field for which + * any of the record's data contains the provided filename. */ - blob(code: number, contentType: string, b: string|Array): void + findFileFieldByFile(filename: string): (schema.SchemaField) + } + interface Record { /** - * Stream sends a streaming response with status code and content type. + * Load bulk loads the provided data into the current Record model. */ - stream(code: number, contentType: string, r: io.Reader): void + load(data: _TygojaDict): void + } + interface Record { /** - * File sends a response with the content of the file. + * ColumnValueMap implements [ColumnValueMapper] interface. */ - file(file: string): void + columnValueMap(): _TygojaDict + } + interface Record { /** - * FileFS sends a response with the content of the file from given filesystem. + * PublicExport exports only the record fields that are safe to be public. + * + * For auth records, to force the export of the email field you need to set + * `m.IgnoreEmailVisibility(true)`. */ - fileFS(file: string, filesystem: fs.FS): void + publicExport(): _TygojaDict + } + interface Record { /** - * Attachment sends a response as attachment, prompting client to save the - * file. + * MarshalJSON implements the [json.Marshaler] interface. + * + * Only the data exported by `PublicExport()` will be serialized. */ - attachment(file: string, name: string): void + marshalJSON(): string|Array + } + interface Record { /** - * Inline sends a response as inline, opening the file in the browser. + * UnmarshalJSON implements the [json.Unmarshaler] interface. */ - inline(file: string, name: string): void + unmarshalJSON(data: string|Array): void + } + interface Record { /** - * NoContent sends a response with no body and a status code. + * ReplaceModifers returns a new map with applied modifier + * values based on the current record and the specified data. + * + * The resolved modifier keys will be removed. + * + * Multiple modifiers will be applied one after another, + * while reusing the previous base key value result (eg. 1; -5; +2 => -2). + * + * Example usage: + * + * ``` + * newData := record.ReplaceModifers(data) + * // record: {"field": 10} + * // data: {"field+": 5} + * // newData: {"field": 15} + * ``` */ - noContent(code: number): void + replaceModifers(data: _TygojaDict): _TygojaDict + } + interface Record { /** - * Redirect redirects the request to a provided URL with status code. + * Username returns the "username" auth record data value. */ - redirect(code: number, url: string): void + username(): string + } + interface Record { /** - * Error invokes the registered global HTTP error handler. Generally used by middleware. - * A side-effect of calling global error handler is that now Response has been committed (sent to the client) and - * middlewares up in chain can not change Response status code or Response body anymore. + * SetUsername sets the "username" auth record data value. * - * Avoid using this method in handlers as no middleware will be able to effectively handle errors after that. - * Instead of calling this method in handler return your error and let it be handled by middlewares or global error handler. + * This method doesn't check whether the provided value is a valid username. + * + * Returns an error if the record is not from an auth collection. */ - error(err: Error): void + setUsername(username: string): void + } + interface Record { /** - * Echo returns the `Echo` instance. - * - * WARNING: Remember that Echo public fields and methods are coroutine safe ONLY when you are NOT mutating them - * anywhere in your code after Echo server has started. + * Email returns the "email" auth record data value. */ - echo(): (Echo) + email(): string } - // @ts-ignore - import stdContext = context - /** - * Echo is the top-level framework instance. - * - * Goroutine safety: Do not mutate Echo instance fields after server has started. Accessing these - * fields from handlers/middlewares and changing field values at the same time leads to data-races. - * Same rule applies to adding new routes after server has been started - Adding a route is not Goroutine safe action. - */ - interface Echo { + interface Record { /** - * NewContextFunc allows using custom context implementations, instead of default *echo.context + * SetEmail sets the "email" auth record data value. + * + * This method doesn't check whether the provided value is a valid email. + * + * Returns an error if the record is not from an auth collection. */ - newContextFunc: (e: Echo, pathParamAllocSize: number) => ServableContext - debug: boolean - httpErrorHandler: HTTPErrorHandler - binder: Binder - jsonSerializer: JSONSerializer - validator: Validator - renderer: Renderer - logger: Logger - ipExtractor: IPExtractor - /** - * Filesystem is file system used by Static and File handlers to access files. - * Defaults to os.DirFS(".") - * - * When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary - * prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths - * including `assets/images` as their prefix. - */ - filesystem: fs.FS + setEmail(email: string): void + } + interface Record { /** - * OnAddRoute is called when Echo adds new route to specific host router. Handler is called for every router - * and before route is added to the host router. + * Verified returns the "emailVisibility" auth record data value. */ - onAddRoute: (host: string, route: Routable) => void + emailVisibility(): boolean } - /** - * HandlerFunc defines a function to serve HTTP requests. - */ - interface HandlerFunc {(c: Context): void } - /** - * MiddlewareFunc defines a function to process middleware. - */ - interface MiddlewareFunc {(next: HandlerFunc): HandlerFunc } - interface Echo { + interface Record { /** - * NewContext returns a new Context instance. + * SetEmailVisibility sets the "emailVisibility" auth record data value. * - * Note: both request and response can be left to nil as Echo.ServeHTTP will call c.Reset(req,resp) anyway - * these arguments are useful when creating context for tests and cases like that. + * Returns an error if the record is not from an auth collection. */ - newContext(r: http.Request, w: http.ResponseWriter): Context + setEmailVisibility(visible: boolean): void } - interface Echo { + interface Record { /** - * Router returns the default router. + * Verified returns the "verified" auth record data value. */ - router(): Router + verified(): boolean } - interface Echo { + interface Record { /** - * Routers returns the new map of host => router. + * SetVerified sets the "verified" auth record data value. + * + * Returns an error if the record is not from an auth collection. */ - routers(): _TygojaDict + setVerified(verified: boolean): void } - interface Echo { + interface Record { /** - * RouterFor returns Router for given host. When host is left empty the default router is returned. + * TokenKey returns the "tokenKey" auth record data value. */ - routerFor(host: string): [Router, boolean] + tokenKey(): string } - interface Echo { + interface Record { /** - * ResetRouterCreator resets callback for creating new router instances. - * Note: current (default) router is immediately replaced with router created with creator func and vhost routers are cleared. + * SetTokenKey sets the "tokenKey" auth record data value. + * + * Returns an error if the record is not from an auth collection. */ - resetRouterCreator(creator: (e: Echo) => Router): void + setTokenKey(key: string): void } - interface Echo { + interface Record { /** - * Pre adds middleware to the chain which is run before router tries to find matching route. - * Meaning middleware is executed even for 404 (not found) cases. + * RefreshTokenKey generates and sets new random auth record "tokenKey". + * + * Returns an error if the record is not from an auth collection. */ - pre(...middleware: MiddlewareFunc[]): void + refreshTokenKey(): void } - interface Echo { + interface Record { /** - * Use adds middleware to the chain which is run after router has found matching route and before route/request handler method is executed. + * LastResetSentAt returns the "lastResentSentAt" auth record data value. */ - use(...middleware: MiddlewareFunc[]): void + lastResetSentAt(): types.DateTime } - interface Echo { + interface Record { /** - * CONNECT registers a new CONNECT route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * SetLastResetSentAt sets the "lastResentSentAt" auth record data value. + * + * Returns an error if the record is not from an auth collection. */ - connect(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + setLastResetSentAt(dateTime: types.DateTime): void } - interface Echo { + interface Record { /** - * DELETE registers a new DELETE route for a path with matching handler in the router - * with optional route-level middleware. Panics on error. + * LastVerificationSentAt returns the "lastVerificationSentAt" auth record data value. */ - delete(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + lastVerificationSentAt(): types.DateTime } - interface Echo { + interface Record { /** - * GET registers a new GET route for a path with matching handler in the router - * with optional route-level middleware. Panics on error. + * SetLastVerificationSentAt sets an "lastVerificationSentAt" auth record data value. + * + * Returns an error if the record is not from an auth collection. */ - get(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + setLastVerificationSentAt(dateTime: types.DateTime): void } - interface Echo { + interface Record { /** - * HEAD registers a new HEAD route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * PasswordHash returns the "passwordHash" auth record data value. */ - head(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + passwordHash(): string } - interface Echo { + interface Record { /** - * OPTIONS registers a new OPTIONS route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * ValidatePassword validates a plain password against the auth record password. + * + * Returns false if the password is incorrect or record is not from an auth collection. */ - options(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + validatePassword(password: string): boolean } - interface Echo { + interface Record { /** - * PATCH registers a new PATCH route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * SetPassword sets cryptographically secure string to the auth record "password" field. + * This method also resets the "lastResetSentAt" and the "tokenKey" fields. + * + * Returns an error if the record is not from an auth collection or + * an empty password is provided. */ - patch(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + setPassword(password: string): void } - interface Echo { - /** - * POST registers a new POST route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. - */ - post(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + /** + * RequestInfo defines a HTTP request data struct, usually used + * as part of the `@request.*` filter resolver. + */ + interface RequestInfo { + context: string + query: _TygojaDict + data: _TygojaDict + headers: _TygojaDict + authRecord?: Record + admin?: Admin + method: string } - interface Echo { + interface RequestInfo { /** - * PUT registers a new PUT route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * HasModifierDataKeys loosely checks if the current struct has any modifier Data keys. */ - put(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + hasModifierDataKeys(): boolean } - interface Echo { +} + +namespace auth { + /** + * AuthUser defines a standardized oauth2 user data structure. + */ + interface AuthUser { + id: string + name: string + username: string + email: string + avatarUrl: string + accessToken: string + refreshToken: string + expiry: types.DateTime + rawUser: _TygojaDict + } + /** + * Provider defines a common interface for an OAuth2 client. + */ + interface Provider { + [key:string]: any; /** - * TRACE registers a new TRACE route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * Context returns the context associated with the provider (if any). */ - trace(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { + context(): context.Context /** - * RouteNotFound registers a special-case route which is executed when no other route is found (i.e. HTTP 404 cases) - * for current request URL. - * Path supports static and named/any parameters just like other http method is defined. Generally path is ended with - * wildcard/match-any character (`/*`, `/download/*` etc). - * - * Example: `e.RouteNotFound("/*", func(c echo.Context) error { return c.NoContent(http.StatusNotFound) })` + * SetContext assigns the specified context to the current provider. */ - routeNotFound(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { + setContext(ctx: context.Context): void /** - * Any registers a new route for all HTTP methods (supported by Echo) and path with matching handler - * in the router with optional route-level middleware. - * - * Note: this method only adds specific set of supported HTTP methods as handler and is not true - * "catch-any-arbitrary-method" way of matching requests. + * PKCE indicates whether the provider can use the PKCE flow. */ - any(path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes - } - interface Echo { + pkce(): boolean /** - * Match registers a new route for multiple HTTP methods and path with matching - * handler in the router with optional route-level middleware. Panics on error. + * SetPKCE toggles the state whether the provider can use the PKCE flow or not. */ - match(methods: Array, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes - } - interface Echo { + setPKCE(enable: boolean): void /** - * Static registers a new route with path prefix to serve static files from the provided root directory. + * DisplayName usually returns provider name as it is officially written + * and it could be used directly in the UI. */ - static(pathPrefix: string, fsRoot: string): RouteInfo - } - interface Echo { + displayName(): string /** - * StaticFS registers a new route with path prefix to serve static files from the provided file system. - * - * When dealing with `embed.FS` use `fs := echo.MustSubFS(fs, "rootDirectory") to create sub fs which uses necessary - * prefix for directory path. This is necessary as `//go:embed assets/images` embeds files with paths - * including `assets/images` as their prefix. + * SetDisplayName sets the provider's display name. */ - staticFS(pathPrefix: string, filesystem: fs.FS): RouteInfo - } - interface Echo { + setDisplayName(displayName: string): void /** - * FileFS registers a new route with path to serve file from the provided file system. + * Scopes returns the provider access permissions that will be requested. */ - fileFS(path: string, file: string, filesystem: fs.FS, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { + scopes(): Array /** - * File registers a new route with path to serve a static file with optional route-level middleware. Panics on error. + * SetScopes sets the provider access permissions that will be requested later. */ - file(path: string, file: string, ...middleware: MiddlewareFunc[]): RouteInfo - } - interface Echo { + setScopes(scopes: Array): void /** - * AddRoute registers a new Route with default host Router + * ClientId returns the provider client's app ID. */ - addRoute(route: Routable): RouteInfo - } - interface Echo { + clientId(): string /** - * Add registers a new route for an HTTP method and path with matching handler - * in the router with optional route-level middleware. + * SetClientId sets the provider client's ID. */ - add(method: string, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): RouteInfo - } - interface Echo { + setClientId(clientId: string): void /** - * Host creates a new router group for the provided host and optional host-level middleware. + * ClientSecret returns the provider client's app secret. */ - host(name: string, ...m: MiddlewareFunc[]): (Group) - } - interface Echo { + clientSecret(): string /** - * Group creates a new router group with prefix and optional group-level middleware. + * SetClientSecret sets the provider client's app secret. */ - group(prefix: string, ...m: MiddlewareFunc[]): (Group) - } - interface Echo { + setClientSecret(secret: string): void /** - * AcquireContext returns an empty `Context` instance from the pool. - * You must return the context by calling `ReleaseContext()`. + * RedirectUrl returns the end address to redirect the user + * going through the OAuth flow. */ - acquireContext(): Context - } - interface Echo { + redirectUrl(): string /** - * ReleaseContext returns the `Context` instance back to the pool. - * You must call it after `AcquireContext()`. + * SetRedirectUrl sets the provider's RedirectUrl. */ - releaseContext(c: Context): void - } - interface Echo { + setRedirectUrl(url: string): void /** - * ServeHTTP implements `http.Handler` interface, which serves HTTP requests. + * AuthUrl returns the provider's authorization service url. */ - serveHTTP(w: http.ResponseWriter, r: http.Request): void - } - interface Echo { + authUrl(): string /** - * Start stars HTTP server on given address with Echo as a handler serving requests. The server can be shutdown by - * sending os.Interrupt signal with `ctrl+c`. - * - * Note: this method is created for use in examples/demos and is deliberately simple without providing configuration - * options. - * - * In need of customization use: - * - * ``` - * sc := echo.StartConfig{Address: ":8080"} - * if err := sc.Start(e); err != http.ErrServerClosed { - * log.Fatal(err) - * } - * ``` - * - * // or standard library `http.Server` - * - * ``` - * s := http.Server{Addr: ":8080", Handler: e} - * if err := s.ListenAndServe(); err != http.ErrServerClosed { - * log.Fatal(err) - * } - * ``` + * SetAuthUrl sets the provider's AuthUrl. */ - start(address: string): void + setAuthUrl(url: string): void + /** + * TokenUrl returns the provider's token exchange service url. + */ + tokenUrl(): string + /** + * SetTokenUrl sets the provider's TokenUrl. + */ + setTokenUrl(url: string): void + /** + * UserApiUrl returns the provider's user info api url. + */ + userApiUrl(): string + /** + * SetUserApiUrl sets the provider's UserApiUrl. + */ + setUserApiUrl(url: string): void + /** + * Client returns an http client using the provided token. + */ + client(token: oauth2.Token): (any) + /** + * BuildAuthUrl returns a URL to the provider's consent page + * that asks for permissions for the required scopes explicitly. + */ + buildAuthUrl(state: string, ...opts: oauth2.AuthCodeOption[]): string + /** + * FetchToken converts an authorization code to token. + */ + fetchToken(code: string, ...opts: oauth2.AuthCodeOption[]): (oauth2.Token) + /** + * FetchRawUserData requests and marshalizes into `result` the + * the OAuth user api response. + */ + fetchRawUserData(token: oauth2.Token): string|Array + /** + * FetchAuthUser is similar to FetchRawUserData, but normalizes and + * marshalizes the user api response into a standardized AuthUser struct. + */ + fetchAuthUser(token: oauth2.Token): (AuthUser) } } @@ -11868,36 +11949,6 @@ namespace settings { } } -namespace migrate { - /** - * MigrationsList defines a list with migration definitions - */ - interface MigrationsList { - } - interface MigrationsList { - /** - * Item returns a single migration from the list by its index. - */ - item(index: number): (Migration) - } - interface MigrationsList { - /** - * Items returns the internal migrations list slice. - */ - items(): Array<(Migration | undefined)> - } - interface MigrationsList { - /** - * Register adds new migration definition to the list. - * - * If `optFilename` is not provided, it will try to get the name from its .go file. - * - * The list will be sorted automatically based on the migrations file name. - */ - register(up: (db: dbx.Builder) => void, down: (db: dbx.Builder) => void, ...optFilename: string[]): void - } -} - /** * Package daos handles common PocketBase DB model manipulations. * @@ -13426,6 +13477,36 @@ namespace core { } } +namespace migrate { + /** + * MigrationsList defines a list with migration definitions + */ + interface MigrationsList { + } + interface MigrationsList { + /** + * Item returns a single migration from the list by its index. + */ + item(index: number): (Migration) + } + interface MigrationsList { + /** + * Items returns the internal migrations list slice. + */ + items(): Array<(Migration | undefined)> + } + interface MigrationsList { + /** + * Register adds new migration definition to the list. + * + * If `optFilename` is not provided, it will try to get the name from its .go file. + * + * The list will be sorted automatically based on the migrations file name. + */ + register(up: (db: dbx.Builder) => void, down: (db: dbx.Builder) => void, ...optFilename: string[]): void + } +} + /** * Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. * In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. @@ -14491,6 +14572,31 @@ namespace cobra { } } +/** + * Package io provides basic interfaces to I/O primitives. + * Its primary job is to wrap existing implementations of such primitives, + * such as those in package os, into shared public interfaces that + * abstract the functionality, plus some other related primitives. + * + * Because these interfaces and primitives wrap lower-level operations with + * various implementations, unless otherwise informed clients should not + * assume they are safe for parallel execution. + */ +namespace io { + /** + * ReadCloser is the interface that groups the basic Read and Close methods. + */ + interface ReadCloser { + [key:string]: any; + } + /** + * WriteCloser is the interface that groups the basic Write and Close methods. + */ + interface WriteCloser { + [key:string]: any; + } +} + /** * Package syscall contains an interface to the low-level operating system * primitives. The details vary depending on the underlying system, and @@ -14508,11 +14614,11 @@ namespace cobra { * err is an operating system error describing the failure. * On most systems, that error has type syscall.Errno. * - * Deprecated: this package is locked down. Callers should use the - * corresponding package in the golang.org/x/sys repository instead. - * That is also where updates required by new systems or versions - * should be applied. See https://golang.org/s/go1.4-syscall for more - * information. + * NOTE: Most of the functions, types, and constants defined in + * this package are also available in the [golang.org/x/sys] package. + * That package has more system call support than this one, + * and most new code should prefer that package where possible. + * See https://golang.org/s/go1.4-syscall for more information. */ namespace syscall { /** @@ -14626,6 +14732,14 @@ namespace syscall { * For debugging, the result of t.String does include the monotonic * clock reading if present. If t != u because of different monotonic clock readings, * that difference will be visible when printing t.String() and u.String(). + * + * # Timer Resolution + * + * Timer resolution varies depending on the Go runtime, the operating system + * and the underlying hardware. + * On Unix, the resolution is approximately 1ms. + * On Windows, the default resolution is approximately 16ms, but + * a higher resolution may be requested using [golang.org/x/sys/windows.TimeBeginPeriod]. */ namespace time { /** @@ -14653,6 +14767,10 @@ namespace time { * Typically, the Location represents the collection of time offsets * in use in a geographical area. For many Locations the time offset varies * depending on whether daylight savings time is in use at the time instant. + * + * Location is used to provide a time zone in a printed Time value and for + * calculations involving intervals that may cross daylight savings time + * boundaries. */ interface Location { } @@ -14665,6 +14783,17 @@ namespace time { } } +/** + * Package fs defines basic interfaces to a file system. + * A file system can be provided by the host operating system + * but also by other packages. + * + * See the [testing/fstest] package for support with testing + * implementations of file systems. + */ +namespace fs { +} + /** * Package context defines the Context type, which carries deadlines, * cancellation signals, and other request-scoped values across API boundaries @@ -14721,62 +14850,14 @@ namespace time { namespace context { } -/** - * Package io provides basic interfaces to I/O primitives. - * Its primary job is to wrap existing implementations of such primitives, - * such as those in package os, into shared public interfaces that - * abstract the functionality, plus some other related primitives. - * - * Because these interfaces and primitives wrap lower-level operations with - * various implementations, unless otherwise informed clients should not - * assume they are safe for parallel execution. - */ -namespace io { - /** - * Writer is the interface that wraps the basic Write method. - * - * Write writes len(p) bytes from p to the underlying data stream. - * It returns the number of bytes written from p (0 <= n <= len(p)) - * and any error encountered that caused the write to stop early. - * Write must return a non-nil error if it returns n < len(p). - * Write must not modify the slice data, even temporarily. - * - * Implementations must not retain p. - */ - interface Writer { - [key:string]: any; - write(p: string|Array): number - } - /** - * ReadCloser is the interface that groups the basic Read and Close methods. - */ - interface ReadCloser { - [key:string]: any; - } - /** - * WriteCloser is the interface that groups the basic Write and Close methods. - */ - interface WriteCloser { - [key:string]: any; - } -} - -/** - * Package fs defines basic interfaces to a file system. - * A file system can be provided by the host operating system - * but also by other packages. - */ -namespace fs { -} - /** * Package net provides a portable interface for network I/O, including * TCP/IP, UDP, domain name resolution, and Unix domain sockets. * * Although the package provides access to low-level networking * primitives, most clients will need only the basic interface provided - * by the Dial, Listen, and Accept functions and the associated - * Conn and Listener interfaces. The crypto/tls package uses + * by the [Dial], [Listen], and Accept functions and the associated + * [Conn] and [Listener] interfaces. The crypto/tls package uses * the same interfaces and similar Dial and Listen functions. * * The Dial function connects to a server: @@ -14810,7 +14891,7 @@ namespace fs { * # Name Resolution * * The method for resolving domain names, whether indirectly with functions like Dial - * or directly with functions like LookupHost and LookupAddr, varies by operating system. + * or directly with functions like [LookupHost] and [LookupAddr], varies by operating system. * * On Unix systems, the resolver has two options for resolving names. * It can use a pure Go resolver that sends DNS requests directly to the servers @@ -14948,81 +15029,10 @@ namespace net { } } -namespace store { - /** - * Store defines a concurrent safe in memory key-value data store. - */ - interface Store { - } - interface Store { - /** - * Reset clears the store and replaces the store data with a - * shallow copy of the provided newData. - */ - reset(newData: _TygojaDict): void - } - interface Store { - /** - * Length returns the current number of elements in the store. - */ - length(): number - } - interface Store { - /** - * RemoveAll removes all the existing store entries. - */ - removeAll(): void - } - interface Store { - /** - * Remove removes a single entry from the store. - * - * Remove does nothing if key doesn't exist in the store. - */ - remove(key: string): void - } - interface Store { - /** - * Has checks if element with the specified key exist or not. - */ - has(key: string): boolean - } - interface Store { - /** - * Get returns a single element value from the store. - * - * If key is not set, the zero T value is returned. - */ - get(key: string): T - } - interface Store { - /** - * GetAll returns a shallow copy of the current store data. - */ - getAll(): _TygojaDict - } - interface Store { - /** - * Set sets (or overwrite if already exist) a new value for key. - */ - set(key: string, value: T): void - } - interface Store { - /** - * SetIfLessThanLimit sets (or overwrite if already exist) a new value for key. - * - * This method is similar to Set() but **it will skip adding new elements** - * to the store if the store length has reached the specified limit. - * false is returned if maxAllowedElements limit is reached. - */ - setIfLessThanLimit(key: string, value: T, maxAllowedElements: number): boolean - } -} - -/** - * Package url parses URLs and implements query escaping. - */ -namespace url { +/** + * Package url parses URLs and implements query escaping. + */ +namespace url { /** * A URL represents a parsed URL (technically, a URI reference). * @@ -15038,10 +15048,17 @@ namespace url { * scheme:opaque[?query][#fragment] * ``` * + * The Host field contains the host and port subcomponents of the URL. + * When the port is present, it is separated from the host with a colon. + * When the host is an IPv6 address, it must be enclosed in square brackets: + * "[fe80::1]:80". The [net.JoinHostPort] function combines a host and port + * into a string suitable for the Host field, adding square brackets to + * the host when necessary. + * * Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. * A consequence is that it is impossible to tell which slashes in the Path were * slashes in the raw URL and which were %2f. This distinction is rarely important, - * but when it is, the code should use the EscapedPath method, which preserves + * but when it is, the code should use the [URL.EscapedPath] method, which preserves * the original encoding of Path. * * The RawPath field is an optional field which is only set when the default @@ -15054,7 +15071,7 @@ namespace url { scheme: string opaque: string // encoded opaque data user?: Userinfo // username and password information - host: string // host or host:port + host: string // host or host:port (see Hostname and Port methods) path: string // path (relative paths may omit leading slash) rawPath: string // encoded path hint (see EscapedPath method) omitHost: boolean // do not emit empty host (authority) @@ -15070,7 +15087,7 @@ namespace url { * EscapedPath returns u.RawPath when it is a valid escaping of u.Path. * Otherwise EscapedPath ignores u.RawPath and computes an escaped * form on its own. - * The String and RequestURI methods use EscapedPath to construct + * The [URL.String] and [URL.RequestURI] methods use EscapedPath to construct * their results. * In general, code should call EscapedPath instead of * reading u.RawPath directly. @@ -15084,7 +15101,7 @@ namespace url { * EscapedFragment returns u.RawFragment when it is a valid escaping of u.Fragment. * Otherwise EscapedFragment ignores u.RawFragment and computes an escaped * form on its own. - * The String method uses EscapedFragment to construct its result. + * The [URL.String] method uses EscapedFragment to construct its result. * In general, code should call EscapedFragment instead of * reading u.RawFragment directly. */ @@ -15092,7 +15109,7 @@ namespace url { } interface URL { /** - * String reassembles the URL into a valid URL string. + * String reassembles the [URL] into a valid URL string. * The general form of the result is one of: * * ``` @@ -15122,7 +15139,7 @@ namespace url { } interface URL { /** - * Redacted is like String but replaces any password with "xxxxx". + * Redacted is like [URL.String] but replaces any password with "xxxxx". * Only the password in u.User is redacted. */ redacted(): string @@ -15178,16 +15195,16 @@ namespace url { } interface URL { /** - * IsAbs reports whether the URL is absolute. + * IsAbs reports whether the [URL] is absolute. * Absolute means that it has a non-empty scheme. */ isAbs(): boolean } interface URL { /** - * Parse parses a URL in the context of the receiver. The provided URL + * Parse parses a [URL] in the context of the receiver. The provided URL * may be relative or absolute. Parse returns nil, err on parse - * failure, otherwise its return value is the same as ResolveReference. + * failure, otherwise its return value is the same as [URL.ResolveReference]. */ parse(ref: string): (URL) } @@ -15196,7 +15213,7 @@ namespace url { * ResolveReference resolves a URI reference to an absolute URI from * an absolute base URI u, per RFC 3986 Section 5.2. The URI reference * may be relative or absolute. ResolveReference always returns a new - * URL instance, even if the returned URL is identical to either the + * [URL] instance, even if the returned URL is identical to either the * base or reference. If ref is an absolute URL, then ResolveReference * ignores base and returns a copy of ref. */ @@ -15206,7 +15223,7 @@ namespace url { /** * Query parses RawQuery and returns the corresponding values. * It silently discards malformed value pairs. - * To check errors use ParseQuery. + * To check errors use [ParseQuery]. */ query(): Values } @@ -15242,7 +15259,7 @@ namespace url { } interface URL { /** - * JoinPath returns a new URL with the provided path elements joined to + * JoinPath returns a new [URL] with the provided path elements joined to * any existing path and the resulting path cleaned of any ./ or ../ elements. * Any sequences of multiple / characters will be reduced to a single /. */ @@ -15250,107 +15267,26 @@ namespace url { } } -namespace hook { - /** - * Hook defines a concurrent safe structure for handling event hooks - * (aka. callbacks propagation). - */ - interface Hook { - } - interface Hook { - /** - * PreAdd registers a new handler to the hook by prepending it to the existing queue. - * - * Returns an autogenerated hook id that could be used later to remove the hook with Hook.Remove(id). - */ - preAdd(fn: Handler): string - } - interface Hook { - /** - * Add registers a new handler to the hook by appending it to the existing queue. - * - * Returns an autogenerated hook id that could be used later to remove the hook with Hook.Remove(id). - */ - add(fn: Handler): string - } - interface Hook { - /** - * Remove removes a single hook handler by its id. - */ - remove(id: string): void - } - interface Hook { - /** - * RemoveAll removes all registered handlers. - */ - removeAll(): void - } - interface Hook { - /** - * Trigger executes all registered hook handlers one by one - * with the specified `data` as an argument. - * - * Optionally, this method allows also to register additional one off - * handlers that will be temporary appended to the handlers queue. - * - * The execution stops when: - * - hook.StopPropagation is returned in one of the handlers - * - any non-nil error is returned in one of the handlers - */ - trigger(data: T, ...oneOffHandlers: Handler[]): void - } - /** - * TaggedHook defines a proxy hook which register handlers that are triggered only - * if the TaggedHook.tags are empty or includes at least one of the event data tag(s). - */ - type _subGPLeg = mainHook - interface TaggedHook extends _subGPLeg { - } - interface TaggedHook { - /** - * CanTriggerOn checks if the current TaggedHook can be triggered with - * the provided event data tags. - */ - canTriggerOn(tags: Array): boolean - } - interface TaggedHook { - /** - * PreAdd registers a new handler to the hook by prepending it to the existing queue. - * - * The fn handler will be called only if the event data tags satisfy h.CanTriggerOn. - */ - preAdd(fn: Handler): string - } - interface TaggedHook { - /** - * Add registers a new handler to the hook by appending it to the existing queue. - * - * The fn handler will be called only if the event data tags satisfy h.CanTriggerOn. - */ - add(fn: Handler): string - } -} - /** * Package textproto implements generic support for text-based request/response * protocols in the style of HTTP, NNTP, and SMTP. * * The package provides: * - * Error, which represents a numeric error response from + * [Error], which represents a numeric error response from * a server. * - * Pipeline, to manage pipelined requests and responses + * [Pipeline], to manage pipelined requests and responses * in a client. * - * Reader, to read numeric response code lines, + * [Reader], to read numeric response code lines, * key: value headers, lines wrapped with leading spaces * on continuation lines, and whole text blocks ending * with a dot on a line by itself. * - * Writer, to write dot-encoded text blocks. + * [Writer], to write dot-encoded text blocks. * - * Conn, a convenient packaging of Reader, Writer, and Pipeline for use + * [Conn], a convenient packaging of [Reader], [Writer], and [Pipeline] for use * with a single network connection. */ namespace textproto { @@ -15377,7 +15313,7 @@ namespace textproto { interface MIMEHeader { /** * Get gets the first value associated with the given key. - * It is case insensitive; CanonicalMIMEHeaderKey is used + * It is case insensitive; [CanonicalMIMEHeaderKey] is used * to canonicalize the provided key. * If there are no values associated with the key, Get returns "". * To use non-canonical keys, access the map directly. @@ -15387,7 +15323,7 @@ namespace textproto { interface MIMEHeader { /** * Values returns all values associated with the given key. - * It is case insensitive; CanonicalMIMEHeaderKey is + * It is case insensitive; [CanonicalMIMEHeaderKey] is * used to canonicalize the provided key. To use non-canonical * keys, access the map directly. * The returned slice is not a copy. @@ -15500,7 +15436,7 @@ namespace multipart { /** * Package http provides HTTP client and server implementations. * - * Get, Head, Post, and PostForm make HTTP (or HTTPS) requests: + * [Get], [Head], [Post], and [PostForm] make HTTP (or HTTPS) requests: * * ``` * resp, err := http.Get("http://example.com/") @@ -15526,7 +15462,7 @@ namespace multipart { * # Clients and Transports * * For control over HTTP client headers, redirect policy, and other - * settings, create a Client: + * settings, create a [Client]: * * ``` * client := &http.Client{ @@ -15544,7 +15480,7 @@ namespace multipart { * ``` * * For control over proxies, TLS configuration, keep-alives, - * compression, and other settings, create a Transport: + * compression, and other settings, create a [Transport]: * * ``` * tr := &http.Transport{ @@ -15562,8 +15498,8 @@ namespace multipart { * # Servers * * ListenAndServe starts an HTTP server with a given address and handler. - * The handler is usually nil, which means to use DefaultServeMux. - * Handle and HandleFunc add handlers to DefaultServeMux: + * The handler is usually nil, which means to use [DefaultServeMux]. + * [Handle] and [HandleFunc] add handlers to [DefaultServeMux]: * * ``` * http.Handle("/foo", fooHandler) @@ -15593,8 +15529,8 @@ namespace multipart { * * Starting with Go 1.6, the http package has transparent support for the * HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 - * can do so by setting Transport.TLSNextProto (for clients) or - * Server.TLSNextProto (for servers) to a non-nil, empty + * can do so by setting [Transport.TLSNextProto] (for clients) or + * [Server.TLSNextProto] (for servers) to a non-nil, empty * map. Alternatively, the following GODEBUG settings are * currently supported: * @@ -15607,7 +15543,7 @@ namespace multipart { * * Please report any issues before disabling HTTP/2 support: https://golang.org/s/http2bug * - * The http package's Transport and Server both automatically enable + * The http package's [Transport] and [Server] both automatically enable * HTTP/2 support for simple configurations. To enable HTTP/2 for more * complex configurations, to use lower-level HTTP/2 features, or to use * a newer version of Go's http2 package, import "golang.org/x/net/http2" @@ -15644,7 +15580,7 @@ namespace http { } interface Cookie { /** - * String returns the serialization of the cookie for use in a Cookie + * String returns the serialization of the cookie for use in a [Cookie] * header (if only Name and Value are set) or a Set-Cookie response * header (if other fields are set). * If c is nil or c.Name is invalid, the empty string is returned. @@ -15663,7 +15599,7 @@ namespace http { * A Header represents the key-value pairs in an HTTP header. * * The keys should be in canonical form, as returned by - * CanonicalHeaderKey. + * [CanonicalHeaderKey]. */ interface Header extends _TygojaDict{} interface Header { @@ -15671,7 +15607,7 @@ namespace http { * Add adds the key, value pair to the header. * It appends to any existing values associated with key. * The key is case insensitive; it is canonicalized by - * CanonicalHeaderKey. + * [CanonicalHeaderKey]. */ add(key: string, value: string): void } @@ -15680,7 +15616,7 @@ namespace http { * Set sets the header entries associated with key to the * single element value. It replaces any existing values * associated with key. The key is case insensitive; it is - * canonicalized by textproto.CanonicalMIMEHeaderKey. + * canonicalized by [textproto.CanonicalMIMEHeaderKey]. * To use non-canonical keys, assign to the map directly. */ set(key: string, value: string): void @@ -15689,7 +15625,7 @@ namespace http { /** * Get gets the first value associated with the given key. If * there are no values associated with the key, Get returns "". - * It is case insensitive; textproto.CanonicalMIMEHeaderKey is + * It is case insensitive; [textproto.CanonicalMIMEHeaderKey] is * used to canonicalize the provided key. Get assumes that all * keys are stored in canonical form. To use non-canonical keys, * access the map directly. @@ -15699,7 +15635,7 @@ namespace http { interface Header { /** * Values returns all values associated with the given key. - * It is case insensitive; textproto.CanonicalMIMEHeaderKey is + * It is case insensitive; [textproto.CanonicalMIMEHeaderKey] is * used to canonicalize the provided key. To use non-canonical * keys, access the map directly. * The returned slice is not a copy. @@ -15710,7 +15646,7 @@ namespace http { /** * Del deletes the values associated with key. * The key is case insensitive; it is canonicalized by - * CanonicalHeaderKey. + * [CanonicalHeaderKey]. */ del(key: string): void } @@ -15739,7 +15675,7 @@ namespace http { /** * Response represents the response from an HTTP request. * - * The Client and Transport return Responses from servers once + * The [Client] and [Transport] return Responses from servers once * the response headers have been received. The response body * is streamed on demand as the Body field is read. */ @@ -15850,7 +15786,7 @@ namespace http { /** * Location returns the URL of the response's "Location" header, * if present. Relative redirects are resolved relative to - * the Response's Request. ErrNoLocation is returned if no + * [Response.Request]. [ErrNoLocation] is returned if no * Location header is present. */ location(): (url.URL) @@ -15888,16 +15824,16 @@ namespace http { /** * A Handler responds to an HTTP request. * - * ServeHTTP should write reply headers and data to the ResponseWriter + * [Handler.ServeHTTP] should write reply headers and data to the [ResponseWriter] * and then return. Returning signals that the request is finished; it - * is not valid to use the ResponseWriter or read from the - * Request.Body after or concurrently with the completion of the + * is not valid to use the [ResponseWriter] or read from the + * [Request.Body] after or concurrently with the completion of the * ServeHTTP call. * * Depending on the HTTP client software, HTTP protocol version, and * any intermediaries between the client and the Go server, it may not - * be possible to read from the Request.Body after writing to the - * ResponseWriter. Cautious handlers should read the Request.Body + * be possible to read from the [Request.Body] after writing to the + * [ResponseWriter]. Cautious handlers should read the [Request.Body] * first, and then reply. * * Except for reading the body, handlers should not modify the @@ -15909,7 +15845,7 @@ namespace http { * and either closes the network connection or sends an HTTP/2 * RST_STREAM, depending on the HTTP protocol. To abort a handler so * the client sees an interrupted response but the server doesn't log - * an error, panic with the value ErrAbortHandler. + * an error, panic with the value [ErrAbortHandler]. */ interface Handler { [key:string]: any; @@ -15917,7 +15853,7 @@ namespace http { } /** * A ConnState represents the state of a client connection to a server. - * It's used by the optional Server.ConnState hook. + * It's used by the optional [Server.ConnState] hook. */ interface ConnState extends Number{} interface ConnState { @@ -15925,111 +15861,74 @@ namespace http { } } -namespace mailer { - /** - * Mailer defines a base mail client interface. - */ - interface Mailer { - [key:string]: any; - /** - * Send sends an email with the provided Message. - */ - send(message: Message): void - } -} - -/** - * Package oauth2 provides support for making - * OAuth2 authorized and authenticated HTTP requests, - * as specified in RFC 6749. - * It can additionally grant authorization with Bearer JWT. - */ -/** - * Copyright 2023 The Go Authors. All rights reserved. - * Use of this source code is governed by a BSD-style - * license that can be found in the LICENSE file. - */ -namespace oauth2 { +namespace store { /** - * An AuthCodeOption is passed to Config.AuthCodeURL. + * Store defines a concurrent safe in memory key-value data store. */ - interface AuthCodeOption { - [key:string]: any; + interface Store { } - /** - * Token represents the credentials used to authorize - * the requests to access protected resources on the OAuth 2.0 - * provider's backend. - * - * Most users of this package should not access fields of Token - * directly. They're exported mostly for use by related packages - * implementing derivative OAuth2 flows. - */ - interface Token { + interface Store { /** - * AccessToken is the token that authorizes and authenticates - * the requests. + * Reset clears the store and replaces the store data with a + * shallow copy of the provided newData. */ - accessToken: string + reset(newData: _TygojaDict): void + } + interface Store { /** - * TokenType is the type of token. - * The Type method returns either this or "Bearer", the default. + * Length returns the current number of elements in the store. */ - tokenType: string + length(): number + } + interface Store { /** - * RefreshToken is a token that's used by the application - * (as opposed to the user) to refresh the access token - * if it expires. + * RemoveAll removes all the existing store entries. */ - refreshToken: string + removeAll(): void + } + interface Store { /** - * Expiry is the optional expiration time of the access token. + * Remove removes a single entry from the store. * - * If zero, TokenSource implementations will reuse the same - * token forever and RefreshToken or equivalent - * mechanisms for that TokenSource will not be used. + * Remove does nothing if key doesn't exist in the store. */ - expiry: time.Time + remove(key: string): void } - interface Token { + interface Store { /** - * Type returns t.TokenType if non-empty, else "Bearer". + * Has checks if element with the specified key exist or not. */ - type(): string + has(key: string): boolean } - interface Token { + interface Store { /** - * SetAuthHeader sets the Authorization header to r using the access - * token in t. + * Get returns a single element value from the store. * - * This method is unnecessary when using Transport or an HTTP Client - * returned by this package. + * If key is not set, the zero T value is returned. */ - setAuthHeader(r: http.Request): void + get(key: string): T } - interface Token { + interface Store { /** - * WithExtra returns a new Token that's a clone of t, but using the - * provided raw extra map. This is only intended for use by packages - * implementing derivative OAuth2 flows. + * GetAll returns a shallow copy of the current store data. */ - withExtra(extra: { - }): (Token) + getAll(): _TygojaDict } - interface Token { + interface Store { /** - * Extra returns an extra field. - * Extra fields are key-value pairs returned by the server as a - * part of the token retrieval response. + * Set sets (or overwrite if already exist) a new value for key. */ - extra(key: string): { - } + set(key: string, value: T): void } - interface Token { + interface Store { /** - * Valid reports whether t is non-nil, has an AccessToken, and is not expired. + * SetIfLessThanLimit sets (or overwrite if already exist) a new value for key. + * + * This method is similar to Set() but **it will skip adding new elements** + * to the store if the store length has reached the specified limit. + * false is returned if maxAllowedElements limit is reached. */ - valid(): boolean + setIfLessThanLimit(key: string, value: T, maxAllowedElements: number): boolean } } @@ -16190,7 +16089,7 @@ namespace schema { */ namespace sql { /** - * IsolationLevel is the transaction isolation level used in TxOptions. + * IsolationLevel is the transaction isolation level used in [TxOptions]. */ interface IsolationLevel extends Number{} interface IsolationLevel { @@ -16221,14 +16120,14 @@ namespace sql { } /** * Conn represents a single database connection rather than a pool of database - * connections. Prefer running queries from DB unless there is a specific + * connections. Prefer running queries from [DB] unless there is a specific * need for a continuous single database connection. * - * A Conn must call Close to return the connection to the database pool + * A Conn must call [Conn.Close] to return the connection to the database pool * and may do so concurrently with a running query. * - * After a call to Close, all operations on the - * connection fail with ErrConnDone. + * After a call to [Conn.Close], all operations on the + * connection fail with [ErrConnDone]. */ interface Conn { } @@ -16256,9 +16155,9 @@ namespace sql { /** * QueryRowContext executes a query that is expected to return at most one row. * QueryRowContext always returns a non-nil value. Errors are deferred until - * Row's Scan method is called. - * If the query selects no rows, the *Row's Scan will return ErrNoRows. - * Otherwise, the *Row's Scan scans the first selected row and discards + * the [*Row.Scan] method is called. + * If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. + * Otherwise, the [*Row.Scan] scans the first selected row and discards * the rest. */ queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row) @@ -16268,7 +16167,7 @@ namespace sql { * PrepareContext creates a prepared statement for later queries or executions. * Multiple queries or executions may be run concurrently from the * returned statement. - * The caller must call the statement's Close method + * The caller must call the statement's [*Stmt.Close] method * when the statement is no longer needed. * * The provided context is used for the preparation of the statement, not for the @@ -16281,8 +16180,8 @@ namespace sql { * Raw executes f exposing the underlying driver connection for the * duration of f. The driverConn must not be used outside of f. * - * Once f returns and err is not driver.ErrBadConn, the Conn will continue to be usable - * until Conn.Close is called. + * Once f returns and err is not [driver.ErrBadConn], the [Conn] will continue to be usable + * until [Conn.Close] is called. */ raw(f: (driverConn: any) => void): void } @@ -16292,10 +16191,10 @@ namespace sql { * * The provided context is used until the transaction is committed or rolled back. * If the context is canceled, the sql package will roll back - * the transaction. Tx.Commit will return an error if the context provided to + * the transaction. [Tx.Commit] will return an error if the context provided to * BeginTx is canceled. * - * The provided TxOptions is optional and may be nil if defaults should be used. + * The provided [TxOptions] is optional and may be nil if defaults should be used. * If a non-default isolation level is used that the driver doesn't support, * an error will be returned. */ @@ -16304,7 +16203,7 @@ namespace sql { interface Conn { /** * Close returns the connection to the connection pool. - * All operations after a Close will return with ErrConnDone. + * All operations after a Close will return with [ErrConnDone]. * Close is safe to call concurrently with other operations and will * block until all other operations finish. It may be useful to first * cancel any used context and then call close directly after. @@ -16326,7 +16225,7 @@ namespace sql { /** * Length returns the column type length for variable length column types such * as text and binary field types. If the type length is unbounded the value will - * be math.MaxInt64 (any database limits will still apply). + * be [math.MaxInt64] (any database limits will still apply). * If the column type is not variable length, such as an int, or if not supported * by the driver ok is false. */ @@ -16341,7 +16240,7 @@ namespace sql { } interface ColumnType { /** - * ScanType returns a Go type suitable for scanning into using Rows.Scan. + * ScanType returns a Go type suitable for scanning into using [Rows.Scan]. * If a driver does not support this property ScanType will return * the type of an empty interface. */ @@ -16358,7 +16257,7 @@ namespace sql { /** * DatabaseTypeName returns the database system name of the column type. If an empty * string is returned, then the driver type name is not supported. - * Consult your driver documentation for a list of driver data types. Length specifiers + * Consult your driver documentation for a list of driver data types. [ColumnType.Length] specifiers * are not included. * Common type names include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", * "INT", and "BIGINT". @@ -16366,519 +16265,31 @@ namespace sql { databaseTypeName(): string } /** - * Row is the result of calling QueryRow to select a single row. + * Row is the result of calling [DB.QueryRow] to select a single row. */ interface Row { } interface Row { /** * Scan copies the columns from the matched row into the values - * pointed at by dest. See the documentation on Rows.Scan for details. + * pointed at by dest. See the documentation on [Rows.Scan] for details. * If more than one row matches the query, * Scan uses the first row and discards the rest. If no row matches - * the query, Scan returns ErrNoRows. + * the query, Scan returns [ErrNoRows]. */ scan(...dest: any[]): void } interface Row { /** * Err provides a way for wrapping packages to check for - * query errors without calling Scan. + * query errors without calling [Row.Scan]. * Err returns the error, if any, that was encountered while running the query. - * If this error is not nil, this error will also be returned from Scan. + * If this error is not nil, this error will also be returned from [Row.Scan]. */ err(): void } } -/** - * Package slog provides structured logging, - * in which log records include a message, - * a severity level, and various other attributes - * expressed as key-value pairs. - * - * It defines a type, [Logger], - * which provides several methods (such as [Logger.Info] and [Logger.Error]) - * for reporting events of interest. - * - * Each Logger is associated with a [Handler]. - * A Logger output method creates a [Record] from the method arguments - * and passes it to the Handler, which decides how to handle it. - * There is a default Logger accessible through top-level functions - * (such as [Info] and [Error]) that call the corresponding Logger methods. - * - * A log record consists of a time, a level, a message, and a set of key-value - * pairs, where the keys are strings and the values may be of any type. - * As an example, - * - * ``` - * slog.Info("hello", "count", 3) - * ``` - * - * creates a record containing the time of the call, - * a level of Info, the message "hello", and a single - * pair with key "count" and value 3. - * - * The [Info] top-level function calls the [Logger.Info] method on the default Logger. - * In addition to [Logger.Info], there are methods for Debug, Warn and Error levels. - * Besides these convenience methods for common levels, - * there is also a [Logger.Log] method which takes the level as an argument. - * Each of these methods has a corresponding top-level function that uses the - * default logger. - * - * The default handler formats the log record's message, time, level, and attributes - * as a string and passes it to the [log] package. - * - * ``` - * 2022/11/08 15:28:26 INFO hello count=3 - * ``` - * - * For more control over the output format, create a logger with a different handler. - * This statement uses [New] to create a new logger with a TextHandler - * that writes structured records in text form to standard error: - * - * ``` - * logger := slog.New(slog.NewTextHandler(os.Stderr, nil)) - * ``` - * - * [TextHandler] output is a sequence of key=value pairs, easily and unambiguously - * parsed by machine. This statement: - * - * ``` - * logger.Info("hello", "count", 3) - * ``` - * - * produces this output: - * - * ``` - * time=2022-11-08T15:28:26.000-05:00 level=INFO msg=hello count=3 - * ``` - * - * The package also provides [JSONHandler], whose output is line-delimited JSON: - * - * ``` - * logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) - * logger.Info("hello", "count", 3) - * ``` - * - * produces this output: - * - * ``` - * {"time":"2022-11-08T15:28:26.000000000-05:00","level":"INFO","msg":"hello","count":3} - * ``` - * - * Both [TextHandler] and [JSONHandler] can be configured with [HandlerOptions]. - * There are options for setting the minimum level (see Levels, below), - * displaying the source file and line of the log call, and - * modifying attributes before they are logged. - * - * Setting a logger as the default with - * - * ``` - * slog.SetDefault(logger) - * ``` - * - * will cause the top-level functions like [Info] to use it. - * [SetDefault] also updates the default logger used by the [log] package, - * so that existing applications that use [log.Printf] and related functions - * will send log records to the logger's handler without needing to be rewritten. - * - * Some attributes are common to many log calls. - * For example, you may wish to include the URL or trace identifier of a server request - * with all log events arising from the request. - * Rather than repeat the attribute with every log call, you can use [Logger.With] - * to construct a new Logger containing the attributes: - * - * ``` - * logger2 := logger.With("url", r.URL) - * ``` - * - * The arguments to With are the same key-value pairs used in [Logger.Info]. - * The result is a new Logger with the same handler as the original, but additional - * attributes that will appear in the output of every call. - * - * # Levels - * - * A [Level] is an integer representing the importance or severity of a log event. - * The higher the level, the more severe the event. - * This package defines constants for the most common levels, - * but any int can be used as a level. - * - * In an application, you may wish to log messages only at a certain level or greater. - * One common configuration is to log messages at Info or higher levels, - * suppressing debug logging until it is needed. - * The built-in handlers can be configured with the minimum level to output by - * setting [HandlerOptions.Level]. - * The program's `main` function typically does this. - * The default value is LevelInfo. - * - * Setting the [HandlerOptions.Level] field to a [Level] value - * fixes the handler's minimum level throughout its lifetime. - * Setting it to a [LevelVar] allows the level to be varied dynamically. - * A LevelVar holds a Level and is safe to read or write from multiple - * goroutines. - * To vary the level dynamically for an entire program, first initialize - * a global LevelVar: - * - * ``` - * var programLevel = new(slog.LevelVar) // Info by default - * ``` - * - * Then use the LevelVar to construct a handler, and make it the default: - * - * ``` - * h := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: programLevel}) - * slog.SetDefault(slog.New(h)) - * ``` - * - * Now the program can change its logging level with a single statement: - * - * ``` - * programLevel.Set(slog.LevelDebug) - * ``` - * - * # Groups - * - * Attributes can be collected into groups. - * A group has a name that is used to qualify the names of its attributes. - * How this qualification is displayed depends on the handler. - * [TextHandler] separates the group and attribute names with a dot. - * [JSONHandler] treats each group as a separate JSON object, with the group name as the key. - * - * Use [Group] to create a Group attribute from a name and a list of key-value pairs: - * - * ``` - * slog.Group("request", - * "method", r.Method, - * "url", r.URL) - * ``` - * - * TextHandler would display this group as - * - * ``` - * request.method=GET request.url=http://example.com - * ``` - * - * JSONHandler would display it as - * - * ``` - * "request":{"method":"GET","url":"http://example.com"} - * ``` - * - * Use [Logger.WithGroup] to qualify all of a Logger's output - * with a group name. Calling WithGroup on a Logger results in a - * new Logger with the same Handler as the original, but with all - * its attributes qualified by the group name. - * - * This can help prevent duplicate attribute keys in large systems, - * where subsystems might use the same keys. - * Pass each subsystem a different Logger with its own group name so that - * potential duplicates are qualified: - * - * ``` - * logger := slog.Default().With("id", systemID) - * parserLogger := logger.WithGroup("parser") - * parseInput(input, parserLogger) - * ``` - * - * When parseInput logs with parserLogger, its keys will be qualified with "parser", - * so even if it uses the common key "id", the log line will have distinct keys. - * - * # Contexts - * - * Some handlers may wish to include information from the [context.Context] that is - * available at the call site. One example of such information - * is the identifier for the current span when tracing is enabled. - * - * The [Logger.Log] and [Logger.LogAttrs] methods take a context as a first - * argument, as do their corresponding top-level functions. - * - * Although the convenience methods on Logger (Info and so on) and the - * corresponding top-level functions do not take a context, the alternatives ending - * in "Context" do. For example, - * - * ``` - * slog.InfoContext(ctx, "message") - * ``` - * - * It is recommended to pass a context to an output method if one is available. - * - * # Attrs and Values - * - * An [Attr] is a key-value pair. The Logger output methods accept Attrs as well as - * alternating keys and values. The statement - * - * ``` - * slog.Info("hello", slog.Int("count", 3)) - * ``` - * - * behaves the same as - * - * ``` - * slog.Info("hello", "count", 3) - * ``` - * - * There are convenience constructors for [Attr] such as [Int], [String], and [Bool] - * for common types, as well as the function [Any] for constructing Attrs of any - * type. - * - * The value part of an Attr is a type called [Value]. - * Like an [any], a Value can hold any Go value, - * but it can represent typical values, including all numbers and strings, - * without an allocation. - * - * For the most efficient log output, use [Logger.LogAttrs]. - * It is similar to [Logger.Log] but accepts only Attrs, not alternating - * keys and values; this allows it, too, to avoid allocation. - * - * The call - * - * ``` - * logger.LogAttrs(ctx, slog.LevelInfo, "hello", slog.Int("count", 3)) - * ``` - * - * is the most efficient way to achieve the same output as - * - * ``` - * slog.Info("hello", "count", 3) - * ``` - * - * # Customizing a type's logging behavior - * - * If a type implements the [LogValuer] interface, the [Value] returned from its LogValue - * method is used for logging. You can use this to control how values of the type - * appear in logs. For example, you can redact secret information like passwords, - * or gather a struct's fields in a Group. See the examples under [LogValuer] for - * details. - * - * A LogValue method may return a Value that itself implements [LogValuer]. The [Value.Resolve] - * method handles these cases carefully, avoiding infinite loops and unbounded recursion. - * Handler authors and others may wish to use Value.Resolve instead of calling LogValue directly. - * - * # Wrapping output methods - * - * The logger functions use reflection over the call stack to find the file name - * and line number of the logging call within the application. This can produce - * incorrect source information for functions that wrap slog. For instance, if you - * define this function in file mylog.go: - * - * ``` - * func Infof(format string, args ...any) { - * slog.Default().Info(fmt.Sprintf(format, args...)) - * } - * ``` - * - * and you call it like this in main.go: - * - * ``` - * Infof(slog.Default(), "hello, %s", "world") - * ``` - * - * then slog will report the source file as mylog.go, not main.go. - * - * A correct implementation of Infof will obtain the source location - * (pc) and pass it to NewRecord. - * The Infof function in the package-level example called "wrapping" - * demonstrates how to do this. - * - * # Working with Records - * - * Sometimes a Handler will need to modify a Record - * before passing it on to another Handler or backend. - * A Record contains a mixture of simple public fields (e.g. Time, Level, Message) - * and hidden fields that refer to state (such as attributes) indirectly. This - * means that modifying a simple copy of a Record (e.g. by calling - * [Record.Add] or [Record.AddAttrs] to add attributes) - * may have unexpected effects on the original. - * Before modifying a Record, use [Record.Clone] to - * create a copy that shares no state with the original, - * or create a new Record with [NewRecord] - * and build up its Attrs by traversing the old ones with [Record.Attrs]. - * - * # Performance considerations - * - * If profiling your application demonstrates that logging is taking significant time, - * the following suggestions may help. - * - * If many log lines have a common attribute, use [Logger.With] to create a Logger with - * that attribute. The built-in handlers will format that attribute only once, at the - * call to [Logger.With]. The [Handler] interface is designed to allow that optimization, - * and a well-written Handler should take advantage of it. - * - * The arguments to a log call are always evaluated, even if the log event is discarded. - * If possible, defer computation so that it happens only if the value is actually logged. - * For example, consider the call - * - * ``` - * slog.Info("starting request", "url", r.URL.String()) // may compute String unnecessarily - * ``` - * - * The URL.String method will be called even if the logger discards Info-level events. - * Instead, pass the URL directly: - * - * ``` - * slog.Info("starting request", "url", &r.URL) // calls URL.String only if needed - * ``` - * - * The built-in [TextHandler] will call its String method, but only - * if the log event is enabled. - * Avoiding the call to String also preserves the structure of the underlying value. - * For example [JSONHandler] emits the components of the parsed URL as a JSON object. - * If you want to avoid eagerly paying the cost of the String call - * without causing the handler to potentially inspect the structure of the value, - * wrap the value in a fmt.Stringer implementation that hides its Marshal methods. - * - * You can also use the [LogValuer] interface to avoid unnecessary work in disabled log - * calls. Say you need to log some expensive value: - * - * ``` - * slog.Debug("frobbing", "value", computeExpensiveValue(arg)) - * ``` - * - * Even if this line is disabled, computeExpensiveValue will be called. - * To avoid that, define a type implementing LogValuer: - * - * ``` - * type expensive struct { arg int } - * - * func (e expensive) LogValue() slog.Value { - * return slog.AnyValue(computeExpensiveValue(e.arg)) - * } - * ``` - * - * Then use a value of that type in log calls: - * - * ``` - * slog.Debug("frobbing", "value", expensive{arg}) - * ``` - * - * Now computeExpensiveValue will only be called when the line is enabled. - * - * The built-in handlers acquire a lock before calling [io.Writer.Write] - * to ensure that each record is written in one piece. User-defined - * handlers are responsible for their own locking. - * - * # Writing a handler - * - * For a guide to writing a custom handler, see https://golang.org/s/slog-handler-guide. - */ -namespace slog { - // @ts-ignore - import loginternal = internal - /** - * A Logger records structured information about each call to its - * Log, Debug, Info, Warn, and Error methods. - * For each call, it creates a Record and passes it to a Handler. - * - * To create a new Logger, call [New] or a Logger method - * that begins "With". - */ - interface Logger { - } - interface Logger { - /** - * Handler returns l's Handler. - */ - handler(): Handler - } - interface Logger { - /** - * With returns a Logger that includes the given attributes - * in each output operation. Arguments are converted to - * attributes as if by [Logger.Log]. - */ - with(...args: any[]): (Logger) - } - interface Logger { - /** - * WithGroup returns a Logger that starts a group, if name is non-empty. - * The keys of all attributes added to the Logger will be qualified by the given - * name. (How that qualification happens depends on the [Handler.WithGroup] - * method of the Logger's Handler.) - * - * If name is empty, WithGroup returns the receiver. - */ - withGroup(name: string): (Logger) - } - interface Logger { - /** - * Enabled reports whether l emits log records at the given context and level. - */ - enabled(ctx: context.Context, level: Level): boolean - } - interface Logger { - /** - * Log emits a log record with the current time and the given level and message. - * The Record's Attrs consist of the Logger's attributes followed by - * the Attrs specified by args. - * - * The attribute arguments are processed as follows: - * ``` - * - If an argument is an Attr, it is used as is. - * - If an argument is a string and this is not the last argument, - * the following argument is treated as the value and the two are combined - * into an Attr. - * - Otherwise, the argument is treated as a value with key "!BADKEY". - * ``` - */ - log(ctx: context.Context, level: Level, msg: string, ...args: any[]): void - } - interface Logger { - /** - * LogAttrs is a more efficient version of [Logger.Log] that accepts only Attrs. - */ - logAttrs(ctx: context.Context, level: Level, msg: string, ...attrs: Attr[]): void - } - interface Logger { - /** - * Debug logs at LevelDebug. - */ - debug(msg: string, ...args: any[]): void - } - interface Logger { - /** - * DebugContext logs at LevelDebug with the given context. - */ - debugContext(ctx: context.Context, msg: string, ...args: any[]): void - } - interface Logger { - /** - * Info logs at LevelInfo. - */ - info(msg: string, ...args: any[]): void - } - interface Logger { - /** - * InfoContext logs at LevelInfo with the given context. - */ - infoContext(ctx: context.Context, msg: string, ...args: any[]): void - } - interface Logger { - /** - * Warn logs at LevelWarn. - */ - warn(msg: string, ...args: any[]): void - } - interface Logger { - /** - * WarnContext logs at LevelWarn with the given context. - */ - warnContext(ctx: context.Context, msg: string, ...args: any[]): void - } - interface Logger { - /** - * Error logs at LevelError. - */ - error(msg: string, ...args: any[]): void - } - interface Logger { - /** - * ErrorContext logs at LevelError with the given context. - */ - errorContext(ctx: context.Context, msg: string, ...args: any[]): void - } -} - /** * Package models implements all PocketBase DB models and DTOs. */ @@ -17031,8 +16442,8 @@ namespace models { */ validate(): void } - type _subFEYMd = BaseModel - interface Log extends _subFEYMd { + type _subQqMea = BaseModel + interface Log extends _subQqMea { data: types.JsonMap message: string level: number @@ -17040,8 +16451,8 @@ namespace models { interface Log { tableName(): string } - type _subzhTmF = BaseModel - interface Param extends _subzhTmF { + type _subEWyne = BaseModel + interface Param extends _subEWyne { key: string value: types.JsonRaw } @@ -17063,51 +16474,110 @@ namespace models { } /** - * Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. - * In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. + * Package oauth2 provides support for making + * OAuth2 authorized and authenticated HTTP requests, + * as specified in RFC 6749. + * It can additionally grant authorization with Bearer JWT. */ -namespace cobra { - interface PositionalArgs {(cmd: Command, args: Array): void } - // @ts-ignore - import flag = pflag +/** + * Copyright 2023 The Go Authors. All rights reserved. + * Use of this source code is governed by a BSD-style + * license that can be found in the LICENSE file. + */ +namespace oauth2 { /** - * FParseErrWhitelist configures Flag parse errors to be ignored + * An AuthCodeOption is passed to Config.AuthCodeURL. */ - interface FParseErrWhitelist extends _TygojaAny{} + interface AuthCodeOption { + [key:string]: any; + } /** - * Group Structure to manage groups for commands + * Token represents the credentials used to authorize + * the requests to access protected resources on the OAuth 2.0 + * provider's backend. + * + * Most users of this package should not access fields of Token + * directly. They're exported mostly for use by related packages + * implementing derivative OAuth2 flows. */ - interface Group { - id: string - title: string + interface Token { + /** + * AccessToken is the token that authorizes and authenticates + * the requests. + */ + accessToken: string + /** + * TokenType is the type of token. + * The Type method returns either this or "Bearer", the default. + */ + tokenType: string + /** + * RefreshToken is a token that's used by the application + * (as opposed to the user) to refresh the access token + * if it expires. + */ + refreshToken: string + /** + * Expiry is the optional expiration time of the access token. + * + * If zero, TokenSource implementations will reuse the same + * token forever and RefreshToken or equivalent + * mechanisms for that TokenSource will not be used. + */ + expiry: time.Time } - /** - * ShellCompDirective is a bit map representing the different behaviors the shell - * can be instructed to have once completions have been provided. - */ - interface ShellCompDirective extends Number{} - /** - * CompletionOptions are the options to control shell completion - */ - interface CompletionOptions { + interface Token { /** - * DisableDefaultCmd prevents Cobra from creating a default 'completion' command + * Type returns t.TokenType if non-empty, else "Bearer". */ - disableDefaultCmd: boolean + type(): string + } + interface Token { /** - * DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag - * for shells that support completion descriptions + * SetAuthHeader sets the Authorization header to r using the access + * token in t. + * + * This method is unnecessary when using Transport or an HTTP Client + * returned by this package. */ - disableNoDescFlag: boolean + setAuthHeader(r: http.Request): void + } + interface Token { /** - * DisableDescriptions turns off all completion descriptions for shells - * that support them + * WithExtra returns a new Token that's a clone of t, but using the + * provided raw extra map. This is only intended for use by packages + * implementing derivative OAuth2 flows. */ - disableDescriptions: boolean + withExtra(extra: { + }): (Token) + } + interface Token { /** - * HiddenDefaultCmd makes the default 'completion' command hidden + * Extra returns an extra field. + * Extra fields are key-value pairs returned by the server as a + * part of the token retrieval response. */ - hiddenDefaultCmd: boolean + extra(key: string): { + } + } + interface Token { + /** + * Valid reports whether t is non-nil, has an AccessToken, and is not expired. + */ + valid(): boolean + } +} + +namespace mailer { + /** + * Mailer defines a base mail client interface. + */ + interface Mailer { + [key:string]: any; + /** + * Send sends an email with the provided Message. + */ + send(message: Message): void } } @@ -17717,24 +17187,6 @@ namespace settings { } } -/** - * Package daos handles common PocketBase DB model manipulations. - * - * Think of daos as DB repository and service layer in one. - */ -namespace daos { - interface LogsStatsItem { - total: number - date: types.DateTime - } - /** - * ExpandFetchFunc defines the function that is used to fetch the expanded relation records. - */ - interface ExpandFetchFunc {(relCollection: models.Collection, relIds: Array): Array<(models.Record | undefined)> } - // @ts-ignore - import validation = ozzo_validation -} - namespace subscriptions { /** * Broker defines a struct for managing subscriptions clients. @@ -17772,262 +17224,103 @@ namespace subscriptions { } } -/** - * Package core is the backbone of PocketBase. - * - * It defines the main PocketBase App interface and its base implementation. - */ -namespace core { - interface BootstrapEvent { - app: App - } - interface TerminateEvent { - app: App - isRestart: boolean - } - interface ServeEvent { - app: App - router?: echo.Echo - server?: http.Server - certManager?: any - } - interface ApiErrorEvent { - httpContext: echo.Context - error: Error - } - type _subHsNUU = BaseModelEvent - interface ModelEvent extends _subHsNUU { - dao?: daos.Dao +namespace hook { + /** + * Hook defines a concurrent safe structure for handling event hooks + * (aka. callbacks propagation). + */ + interface Hook { } - type _subXsXxs = BaseCollectionEvent - interface MailerRecordEvent extends _subXsXxs { - mailClient: mailer.Mailer - message?: mailer.Message - record?: models.Record - meta: _TygojaDict + interface Hook { + /** + * PreAdd registers a new handler to the hook by prepending it to the existing queue. + * + * Returns an autogenerated hook id that could be used later to remove the hook with Hook.Remove(id). + */ + preAdd(fn: Handler): string } - interface MailerAdminEvent { - mailClient: mailer.Mailer - message?: mailer.Message - admin?: models.Admin - meta: _TygojaDict + interface Hook { + /** + * Add registers a new handler to the hook by appending it to the existing queue. + * + * Returns an autogenerated hook id that could be used later to remove the hook with Hook.Remove(id). + */ + add(fn: Handler): string } - interface RealtimeConnectEvent { - httpContext: echo.Context - client: subscriptions.Client - idleTimeout: time.Duration + interface Hook { + /** + * Remove removes a single hook handler by its id. + */ + remove(id: string): void } - interface RealtimeDisconnectEvent { - httpContext: echo.Context - client: subscriptions.Client + interface Hook { + /** + * RemoveAll removes all registered handlers. + */ + removeAll(): void } - interface RealtimeMessageEvent { - httpContext: echo.Context - client: subscriptions.Client - message?: subscriptions.Message + interface Hook { + /** + * Trigger executes all registered hook handlers one by one + * with the specified `data` as an argument. + * + * Optionally, this method allows also to register additional one off + * handlers that will be temporary appended to the handlers queue. + * + * The execution stops when: + * - hook.StopPropagation is returned in one of the handlers + * - any non-nil error is returned in one of the handlers + */ + trigger(data: T, ...oneOffHandlers: Handler[]): void } - interface RealtimeSubscribeEvent { - httpContext: echo.Context - client: subscriptions.Client - subscriptions: Array + /** + * TaggedHook defines a proxy hook which register handlers that are triggered only + * if the TaggedHook.tags are empty or includes at least one of the event data tag(s). + */ + type _subRrEuI = mainHook + interface TaggedHook extends _subRrEuI { } - interface SettingsListEvent { - httpContext: echo.Context - redactedSettings?: settings.Settings + interface TaggedHook { + /** + * CanTriggerOn checks if the current TaggedHook can be triggered with + * the provided event data tags. + */ + canTriggerOn(tags: Array): boolean } - interface SettingsUpdateEvent { - httpContext: echo.Context - oldSettings?: settings.Settings - newSettings?: settings.Settings + interface TaggedHook { + /** + * PreAdd registers a new handler to the hook by prepending it to the existing queue. + * + * The fn handler will be called only if the event data tags satisfy h.CanTriggerOn. + */ + preAdd(fn: Handler): string } - type _subYJxmm = BaseCollectionEvent - interface RecordsListEvent extends _subYJxmm { - httpContext: echo.Context - records: Array<(models.Record | undefined)> - result?: search.Result + interface TaggedHook { + /** + * Add registers a new handler to the hook by appending it to the existing queue. + * + * The fn handler will be called only if the event data tags satisfy h.CanTriggerOn. + */ + add(fn: Handler): string } - type _subVyMvK = BaseCollectionEvent - interface RecordViewEvent extends _subVyMvK { - httpContext: echo.Context - record?: models.Record - } - type _subLqGWK = BaseCollectionEvent - interface RecordCreateEvent extends _subLqGWK { - httpContext: echo.Context - record?: models.Record - uploadedFiles: _TygojaDict - } - type _subyZWXO = BaseCollectionEvent - interface RecordUpdateEvent extends _subyZWXO { - httpContext: echo.Context - record?: models.Record - uploadedFiles: _TygojaDict - } - type _subkJZvl = BaseCollectionEvent - interface RecordDeleteEvent extends _subkJZvl { - httpContext: echo.Context - record?: models.Record - } - type _subBEQaE = BaseCollectionEvent - interface RecordAuthEvent extends _subBEQaE { - httpContext: echo.Context - record?: models.Record - token: string - meta: any - } - type _subfkUBE = BaseCollectionEvent - interface RecordAuthWithPasswordEvent extends _subfkUBE { - httpContext: echo.Context - record?: models.Record - identity: string - password: string - } - type _subvXlnW = BaseCollectionEvent - interface RecordAuthWithOAuth2Event extends _subvXlnW { - httpContext: echo.Context - providerName: string - providerClient: auth.Provider - record?: models.Record - oAuth2User?: auth.AuthUser - isNewRecord: boolean - } - type _subxjaJh = BaseCollectionEvent - interface RecordAuthRefreshEvent extends _subxjaJh { - httpContext: echo.Context - record?: models.Record - } - type _subAkeoH = BaseCollectionEvent - interface RecordRequestPasswordResetEvent extends _subAkeoH { - httpContext: echo.Context - record?: models.Record - } - type _subIGfZT = BaseCollectionEvent - interface RecordConfirmPasswordResetEvent extends _subIGfZT { - httpContext: echo.Context - record?: models.Record - } - type _subRszvO = BaseCollectionEvent - interface RecordRequestVerificationEvent extends _subRszvO { - httpContext: echo.Context - record?: models.Record - } - type _subAkqaR = BaseCollectionEvent - interface RecordConfirmVerificationEvent extends _subAkqaR { - httpContext: echo.Context - record?: models.Record - } - type _subCsCra = BaseCollectionEvent - interface RecordRequestEmailChangeEvent extends _subCsCra { - httpContext: echo.Context - record?: models.Record - } - type _subfZghW = BaseCollectionEvent - interface RecordConfirmEmailChangeEvent extends _subfZghW { - httpContext: echo.Context - record?: models.Record - } - type _subPgvLJ = BaseCollectionEvent - interface RecordListExternalAuthsEvent extends _subPgvLJ { - httpContext: echo.Context - record?: models.Record - externalAuths: Array<(models.ExternalAuth | undefined)> - } - type _subICsex = BaseCollectionEvent - interface RecordUnlinkExternalAuthEvent extends _subICsex { - httpContext: echo.Context - record?: models.Record - externalAuth?: models.ExternalAuth - } - interface AdminsListEvent { - httpContext: echo.Context - admins: Array<(models.Admin | undefined)> - result?: search.Result - } - interface AdminViewEvent { - httpContext: echo.Context - admin?: models.Admin - } - interface AdminCreateEvent { - httpContext: echo.Context - admin?: models.Admin - } - interface AdminUpdateEvent { - httpContext: echo.Context - admin?: models.Admin - } - interface AdminDeleteEvent { - httpContext: echo.Context - admin?: models.Admin - } - interface AdminAuthEvent { - httpContext: echo.Context - admin?: models.Admin - token: string - } - interface AdminAuthWithPasswordEvent { - httpContext: echo.Context - admin?: models.Admin - identity: string - password: string - } - interface AdminAuthRefreshEvent { - httpContext: echo.Context - admin?: models.Admin - } - interface AdminRequestPasswordResetEvent { - httpContext: echo.Context - admin?: models.Admin - } - interface AdminConfirmPasswordResetEvent { - httpContext: echo.Context - admin?: models.Admin - } - interface CollectionsListEvent { - httpContext: echo.Context - collections: Array<(models.Collection | undefined)> - result?: search.Result - } - type _subJEavf = BaseCollectionEvent - interface CollectionViewEvent extends _subJEavf { - httpContext: echo.Context - } - type _subeUhPm = BaseCollectionEvent - interface CollectionCreateEvent extends _subeUhPm { - httpContext: echo.Context - } - type _subAeQsW = BaseCollectionEvent - interface CollectionUpdateEvent extends _subAeQsW { - httpContext: echo.Context - } - type _subBUvQw = BaseCollectionEvent - interface CollectionDeleteEvent extends _subBUvQw { - httpContext: echo.Context - } - interface CollectionsImportEvent { - httpContext: echo.Context - collections: Array<(models.Collection | undefined)> - } - type _subhVrBM = BaseModelEvent - interface FileTokenEvent extends _subhVrBM { - httpContext: echo.Context - token: string - } - type _subKcLjU = BaseCollectionEvent - interface FileDownloadEvent extends _subKcLjU { - httpContext: echo.Context - record?: models.Record - fileField?: schema.SchemaField - servedPath: string - servedName: string - } -} - -namespace migrate { - interface Migration { - file: string - up: (db: dbx.Builder) => void - down: (db: dbx.Builder) => void +} + +/** + * Package daos handles common PocketBase DB model manipulations. + * + * Think of daos as DB repository and service layer in one. + */ +namespace daos { + interface LogsStatsItem { + total: number + date: types.DateTime } + /** + * ExpandFetchFunc defines the function that is used to fetch the expanded relation records. + */ + interface ExpandFetchFunc {(relCollection: models.Collection, relIds: Array): Array<(models.Record | undefined)> } + // @ts-ignore + import validation = ozzo_validation } /** @@ -18073,7 +17366,7 @@ namespace migrate { * ``` * * For more control over the output format, create a logger with a different handler. - * This statement uses [New] to create a new logger with a TextHandler + * This statement uses [New] to create a new logger with a [TextHandler] * that writes structured records in text form to standard error: * * ``` @@ -18279,7 +17572,7 @@ namespace migrate { * is the most efficient way to achieve the same output as * * ``` - * slog.Info("hello", "count", 3) + * slog.InfoContext(ctx, "hello", "count", 3) * ``` * * # Customizing a type's logging behavior @@ -18292,7 +17585,7 @@ namespace migrate { * * A LogValue method may return a Value that itself implements [LogValuer]. The [Value.Resolve] * method handles these cases carefully, avoiding infinite loops and unbounded recursion. - * Handler authors and others may wish to use Value.Resolve instead of calling LogValue directly. + * Handler authors and others may wish to use [Value.Resolve] instead of calling LogValue directly. * * # Wrapping output methods * @@ -18302,8 +17595,8 @@ namespace migrate { * define this function in file mylog.go: * * ``` - * func Infof(format string, args ...any) { - * slog.Default().Info(fmt.Sprintf(format, args...)) + * func Infof(logger *slog.Logger, format string, args ...any) { + * logger.Info(fmt.Sprintf(format, args...)) * } * ``` * @@ -18402,690 +17695,833 @@ namespace migrate { * For a guide to writing a custom handler, see https://golang.org/s/slog-handler-guide. */ namespace slog { + // @ts-ignore + import loginternal = internal /** - * An Attr is a key-value pair. + * A Logger records structured information about each call to its + * Log, Debug, Info, Warn, and Error methods. + * For each call, it creates a [Record] and passes it to a [Handler]. + * + * To create a new Logger, call [New] or a Logger method + * that begins "With". */ - interface Attr { - key: string - value: Value + interface Logger { } - interface Attr { + interface Logger { /** - * Equal reports whether a and b have equal keys and values. + * Handler returns l's Handler. */ - equal(b: Attr): boolean - } - interface Attr { - string(): string + handler(): Handler } - /** - * A Handler handles log records produced by a Logger.. - * - * A typical handler may print log records to standard error, - * or write them to a file or database, or perhaps augment them - * with additional attributes and pass them on to another handler. - * - * Any of the Handler's methods may be called concurrently with itself - * or with other methods. It is the responsibility of the Handler to - * manage this concurrency. - * - * Users of the slog package should not invoke Handler methods directly. - * They should use the methods of [Logger] instead. - */ - interface Handler { - [key:string]: any; + interface Logger { /** - * Enabled reports whether the handler handles records at the given level. - * The handler ignores records whose level is lower. - * It is called early, before any arguments are processed, - * to save effort if the log event should be discarded. - * If called from a Logger method, the first argument is the context - * passed to that method, or context.Background() if nil was passed - * or the method does not take a context. - * The context is passed so Enabled can use its values - * to make a decision. + * With returns a Logger that includes the given attributes + * in each output operation. Arguments are converted to + * attributes as if by [Logger.Log]. */ - enabled(_arg0: context.Context, _arg1: Level): boolean + with(...args: any[]): (Logger) + } + interface Logger { /** - * Handle handles the Record. - * It will only be called when Enabled returns true. - * The Context argument is as for Enabled. - * It is present solely to provide Handlers access to the context's values. - * Canceling the context should not affect record processing. - * (Among other things, log messages may be necessary to debug a - * cancellation-related problem.) + * WithGroup returns a Logger that starts a group, if name is non-empty. + * The keys of all attributes added to the Logger will be qualified by the given + * name. (How that qualification happens depends on the [Handler.WithGroup] + * method of the Logger's Handler.) * - * Handle methods that produce output should observe the following rules: - * ``` - * - If r.Time is the zero time, ignore the time. - * - If r.PC is zero, ignore it. - * - Attr's values should be resolved. - * - If an Attr's key and value are both the zero value, ignore the Attr. - * This can be tested with attr.Equal(Attr{}). - * - If a group's key is empty, inline the group's Attrs. - * - If a group has no Attrs (even if it has a non-empty key), - * ignore it. - * ``` + * If name is empty, WithGroup returns the receiver. */ - handle(_arg0: context.Context, _arg1: Record): void + withGroup(name: string): (Logger) + } + interface Logger { /** - * WithAttrs returns a new Handler whose attributes consist of - * both the receiver's attributes and the arguments. - * The Handler owns the slice: it may retain, modify or discard it. + * Enabled reports whether l emits log records at the given context and level. */ - withAttrs(attrs: Array): Handler + enabled(ctx: context.Context, level: Level): boolean + } + interface Logger { /** - * WithGroup returns a new Handler with the given group appended to - * the receiver's existing groups. - * The keys of all subsequent attributes, whether added by With or in a - * Record, should be qualified by the sequence of group names. - * - * How this qualification happens is up to the Handler, so long as - * this Handler's attribute keys differ from those of another Handler - * with a different sequence of group names. - * - * A Handler should treat WithGroup as starting a Group of Attrs that ends - * at the end of the log event. That is, - * - * ``` - * logger.WithGroup("s").LogAttrs(level, msg, slog.Int("a", 1), slog.Int("b", 2)) - * ``` - * - * should behave like + * Log emits a log record with the current time and the given level and message. + * The Record's Attrs consist of the Logger's attributes followed by + * the Attrs specified by args. * + * The attribute arguments are processed as follows: * ``` - * logger.LogAttrs(level, msg, slog.Group("s", slog.Int("a", 1), slog.Int("b", 2))) + * - If an argument is an Attr, it is used as is. + * - If an argument is a string and this is not the last argument, + * the following argument is treated as the value and the two are combined + * into an Attr. + * - Otherwise, the argument is treated as a value with key "!BADKEY". * ``` - * - * If the name is empty, WithGroup returns the receiver. */ - withGroup(name: string): Handler + log(ctx: context.Context, level: Level, msg: string, ...args: any[]): void } - /** - * A Level is the importance or severity of a log event. - * The higher the level, the more important or severe the event. - */ - interface Level extends Number{} - interface Level { + interface Logger { /** - * String returns a name for the level. - * If the level has a name, then that name - * in uppercase is returned. - * If the level is between named values, then - * an integer is appended to the uppercased name. - * Examples: - * - * ``` - * LevelWarn.String() => "WARN" - * (LevelInfo+2).String() => "INFO+2" - * ``` + * LogAttrs is a more efficient version of [Logger.Log] that accepts only Attrs. */ - string(): string + logAttrs(ctx: context.Context, level: Level, msg: string, ...attrs: Attr[]): void } - interface Level { + interface Logger { /** - * MarshalJSON implements [encoding/json.Marshaler] - * by quoting the output of [Level.String]. + * Debug logs at [LevelDebug]. */ - marshalJSON(): string|Array + debug(msg: string, ...args: any[]): void } - interface Level { + interface Logger { /** - * UnmarshalJSON implements [encoding/json.Unmarshaler] - * It accepts any string produced by [Level.MarshalJSON], - * ignoring case. - * It also accepts numeric offsets that would result in a different string on - * output. For example, "Error-8" would marshal as "INFO". + * DebugContext logs at [LevelDebug] with the given context. */ - unmarshalJSON(data: string|Array): void + debugContext(ctx: context.Context, msg: string, ...args: any[]): void } - interface Level { + interface Logger { /** - * MarshalText implements [encoding.TextMarshaler] - * by calling [Level.String]. + * Info logs at [LevelInfo]. */ - marshalText(): string|Array + info(msg: string, ...args: any[]): void } - interface Level { + interface Logger { /** - * UnmarshalText implements [encoding.TextUnmarshaler]. - * It accepts any string produced by [Level.MarshalText], - * ignoring case. - * It also accepts numeric offsets that would result in a different string on - * output. For example, "Error-8" would marshal as "INFO". + * InfoContext logs at [LevelInfo] with the given context. */ - unmarshalText(data: string|Array): void + infoContext(ctx: context.Context, msg: string, ...args: any[]): void } - interface Level { + interface Logger { /** - * Level returns the receiver. - * It implements Leveler. + * Warn logs at [LevelWarn]. */ - level(): Level - } - // @ts-ignore - import loginternal = internal -} - -/** - * Package url parses URLs and implements query escaping. - */ -namespace url { - /** - * The Userinfo type is an immutable encapsulation of username and - * password details for a URL. An existing Userinfo value is guaranteed - * to have a username set (potentially empty, as allowed by RFC 2396), - * and optionally a password. - */ - interface Userinfo { + warn(msg: string, ...args: any[]): void } - interface Userinfo { + interface Logger { /** - * Username returns the username. + * WarnContext logs at [LevelWarn] with the given context. */ - username(): string + warnContext(ctx: context.Context, msg: string, ...args: any[]): void } - interface Userinfo { + interface Logger { /** - * Password returns the password in case it is set, and whether it is set. + * Error logs at [LevelError]. */ - password(): [string, boolean] + error(msg: string, ...args: any[]): void } - interface Userinfo { + interface Logger { /** - * String returns the encoded userinfo information in the standard form - * of "username[:password]". + * ErrorContext logs at [LevelError] with the given context. */ - string(): string + errorContext(ctx: context.Context, msg: string, ...args: any[]): void } } /** - * Package types implements some commonly used db serializable types - * like datetime, json, etc. + * Package core is the backbone of PocketBase. + * + * It defines the main PocketBase App interface and its base implementation. */ -namespace types { - /** - * JsonRaw defines a json value type that is safe for db read/write. - */ - interface JsonRaw extends Array{} - interface JsonRaw { - /** - * String returns the current JsonRaw instance as a json encoded string. - */ - string(): string +namespace core { + interface BootstrapEvent { + app: App } - interface JsonRaw { - /** - * MarshalJSON implements the [json.Marshaler] interface. - */ - marshalJSON(): string|Array + interface TerminateEvent { + app: App + isRestart: boolean } - interface JsonRaw { - /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. - */ - unmarshalJSON(b: string|Array): void + interface ServeEvent { + app: App + router?: echo.Echo + server?: http.Server + certManager?: any } - interface JsonRaw { - /** - * Value implements the [driver.Valuer] interface. - */ - value(): any + interface ApiErrorEvent { + httpContext: echo.Context + error: Error } - interface JsonRaw { - /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JsonRaw instance. - */ - scan(value: any): void + type _subqJuQF = BaseModelEvent + interface ModelEvent extends _subqJuQF { + dao?: daos.Dao } -} - -/** - * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer - * object, creating another object (Reader or Writer) that also implements - * the interface but provides buffering and some help for textual I/O. - */ -namespace bufio { - /** - * ReadWriter stores pointers to a Reader and a Writer. - * It implements io.ReadWriter. - */ - type _subiylBZ = Reader&Writer - interface ReadWriter extends _subiylBZ { + type _subtFRsK = BaseCollectionEvent + interface MailerRecordEvent extends _subtFRsK { + mailClient: mailer.Mailer + message?: mailer.Message + record?: models.Record + meta: _TygojaDict } -} - -/** - * Package net provides a portable interface for network I/O, including - * TCP/IP, UDP, domain name resolution, and Unix domain sockets. - * - * Although the package provides access to low-level networking - * primitives, most clients will need only the basic interface provided - * by the Dial, Listen, and Accept functions and the associated - * Conn and Listener interfaces. The crypto/tls package uses - * the same interfaces and similar Dial and Listen functions. - * - * The Dial function connects to a server: - * - * ``` - * conn, err := net.Dial("tcp", "golang.org:80") - * if err != nil { - * // handle error - * } - * fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n") - * status, err := bufio.NewReader(conn).ReadString('\n') - * // ... - * ``` - * - * The Listen function creates servers: - * - * ``` - * ln, err := net.Listen("tcp", ":8080") - * if err != nil { - * // handle error - * } - * for { - * conn, err := ln.Accept() - * if err != nil { - * // handle error - * } - * go handleConnection(conn) - * } - * ``` - * - * # Name Resolution - * - * The method for resolving domain names, whether indirectly with functions like Dial - * or directly with functions like LookupHost and LookupAddr, varies by operating system. - * - * On Unix systems, the resolver has two options for resolving names. - * It can use a pure Go resolver that sends DNS requests directly to the servers - * listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C - * library routines such as getaddrinfo and getnameinfo. - * - * By default the pure Go resolver is used, because a blocked DNS request consumes - * only a goroutine, while a blocked C call consumes an operating system thread. - * When cgo is available, the cgo-based resolver is used instead under a variety of - * conditions: on systems that do not let programs make direct DNS requests (OS X), - * when the LOCALDOMAIN environment variable is present (even if empty), - * when the RES_OPTIONS or HOSTALIASES environment variable is non-empty, - * when the ASR_CONFIG environment variable is non-empty (OpenBSD only), - * when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the - * Go resolver does not implement, and when the name being looked up ends in .local - * or is an mDNS name. - * - * The resolver decision can be overridden by setting the netdns value of the - * GODEBUG environment variable (see package runtime) to go or cgo, as in: - * - * ``` - * export GODEBUG=netdns=go # force pure Go resolver - * export GODEBUG=netdns=cgo # force native resolver (cgo, win32) - * ``` - * - * The decision can also be forced while building the Go source tree - * by setting the netgo or netcgo build tag. - * - * A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver - * to print debugging information about its decisions. - * To force a particular resolver while also printing debugging information, - * join the two settings by a plus sign, as in GODEBUG=netdns=go+1. - * - * On macOS, if Go code that uses the net package is built with - * -buildmode=c-archive, linking the resulting archive into a C program - * requires passing -lresolv when linking the C code. - * - * On Plan 9, the resolver always accesses /net/cs and /net/dns. - * - * On Windows, in Go 1.18.x and earlier, the resolver always used C - * library functions, such as GetAddrInfo and DnsQuery. - */ -namespace net { - /** - * Addr represents a network end point address. - * - * The two methods Network and String conventionally return strings - * that can be passed as the arguments to Dial, but the exact form - * and meaning of the strings is up to the implementation. - */ - interface Addr { - [key:string]: any; - network(): string // name of the network (for example, "tcp", "udp") - string(): string // string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80") + interface MailerAdminEvent { + mailClient: mailer.Mailer + message?: mailer.Message + admin?: models.Admin + meta: _TygojaDict } -} - -/** - * Package multipart implements MIME multipart parsing, as defined in RFC - * 2046. - * - * The implementation is sufficient for HTTP (RFC 2388) and the multipart - * bodies generated by popular browsers. - * - * # Limits - * - * To protect against malicious inputs, this package sets limits on the size - * of the MIME data it processes. - * - * Reader.NextPart and Reader.NextRawPart limit the number of headers in a - * part to 10000 and Reader.ReadForm limits the total number of headers in all - * FileHeaders to 10000. - * These limits may be adjusted with the GODEBUG=multipartmaxheaders= - * setting. - * - * Reader.ReadForm further limits the number of parts in a form to 1000. - * This limit may be adjusted with the GODEBUG=multipartmaxparts= - * setting. - */ + interface RealtimeConnectEvent { + httpContext: echo.Context + client: subscriptions.Client + idleTimeout: time.Duration + } + interface RealtimeDisconnectEvent { + httpContext: echo.Context + client: subscriptions.Client + } + interface RealtimeMessageEvent { + httpContext: echo.Context + client: subscriptions.Client + message?: subscriptions.Message + } + interface RealtimeSubscribeEvent { + httpContext: echo.Context + client: subscriptions.Client + subscriptions: Array + } + interface SettingsListEvent { + httpContext: echo.Context + redactedSettings?: settings.Settings + } + interface SettingsUpdateEvent { + httpContext: echo.Context + oldSettings?: settings.Settings + newSettings?: settings.Settings + } + type _subMxETv = BaseCollectionEvent + interface RecordsListEvent extends _subMxETv { + httpContext: echo.Context + records: Array<(models.Record | undefined)> + result?: search.Result + } + type _submYpen = BaseCollectionEvent + interface RecordViewEvent extends _submYpen { + httpContext: echo.Context + record?: models.Record + } + type _subGzbTN = BaseCollectionEvent + interface RecordCreateEvent extends _subGzbTN { + httpContext: echo.Context + record?: models.Record + uploadedFiles: _TygojaDict + } + type _subJyOTV = BaseCollectionEvent + interface RecordUpdateEvent extends _subJyOTV { + httpContext: echo.Context + record?: models.Record + uploadedFiles: _TygojaDict + } + type _subZtgUj = BaseCollectionEvent + interface RecordDeleteEvent extends _subZtgUj { + httpContext: echo.Context + record?: models.Record + } + type _subkfrmL = BaseCollectionEvent + interface RecordAuthEvent extends _subkfrmL { + httpContext: echo.Context + record?: models.Record + token: string + meta: any + } + type _subdeIlh = BaseCollectionEvent + interface RecordAuthWithPasswordEvent extends _subdeIlh { + httpContext: echo.Context + record?: models.Record + identity: string + password: string + } + type _subVkswj = BaseCollectionEvent + interface RecordAuthWithOAuth2Event extends _subVkswj { + httpContext: echo.Context + providerName: string + providerClient: auth.Provider + record?: models.Record + oAuth2User?: auth.AuthUser + isNewRecord: boolean + } + type _subOjrpL = BaseCollectionEvent + interface RecordAuthRefreshEvent extends _subOjrpL { + httpContext: echo.Context + record?: models.Record + } + type _subEaoXh = BaseCollectionEvent + interface RecordRequestPasswordResetEvent extends _subEaoXh { + httpContext: echo.Context + record?: models.Record + } + type _subCozbd = BaseCollectionEvent + interface RecordConfirmPasswordResetEvent extends _subCozbd { + httpContext: echo.Context + record?: models.Record + } + type _subUyKYs = BaseCollectionEvent + interface RecordRequestVerificationEvent extends _subUyKYs { + httpContext: echo.Context + record?: models.Record + } + type _subGDKnx = BaseCollectionEvent + interface RecordConfirmVerificationEvent extends _subGDKnx { + httpContext: echo.Context + record?: models.Record + } + type _subAJiUh = BaseCollectionEvent + interface RecordRequestEmailChangeEvent extends _subAJiUh { + httpContext: echo.Context + record?: models.Record + } + type _subusdID = BaseCollectionEvent + interface RecordConfirmEmailChangeEvent extends _subusdID { + httpContext: echo.Context + record?: models.Record + } + type _subVbGrM = BaseCollectionEvent + interface RecordListExternalAuthsEvent extends _subVbGrM { + httpContext: echo.Context + record?: models.Record + externalAuths: Array<(models.ExternalAuth | undefined)> + } + type _subAUhXW = BaseCollectionEvent + interface RecordUnlinkExternalAuthEvent extends _subAUhXW { + httpContext: echo.Context + record?: models.Record + externalAuth?: models.ExternalAuth + } + interface AdminsListEvent { + httpContext: echo.Context + admins: Array<(models.Admin | undefined)> + result?: search.Result + } + interface AdminViewEvent { + httpContext: echo.Context + admin?: models.Admin + } + interface AdminCreateEvent { + httpContext: echo.Context + admin?: models.Admin + } + interface AdminUpdateEvent { + httpContext: echo.Context + admin?: models.Admin + } + interface AdminDeleteEvent { + httpContext: echo.Context + admin?: models.Admin + } + interface AdminAuthEvent { + httpContext: echo.Context + admin?: models.Admin + token: string + } + interface AdminAuthWithPasswordEvent { + httpContext: echo.Context + admin?: models.Admin + identity: string + password: string + } + interface AdminAuthRefreshEvent { + httpContext: echo.Context + admin?: models.Admin + } + interface AdminRequestPasswordResetEvent { + httpContext: echo.Context + admin?: models.Admin + } + interface AdminConfirmPasswordResetEvent { + httpContext: echo.Context + admin?: models.Admin + } + interface CollectionsListEvent { + httpContext: echo.Context + collections: Array<(models.Collection | undefined)> + result?: search.Result + } + type _subuBhod = BaseCollectionEvent + interface CollectionViewEvent extends _subuBhod { + httpContext: echo.Context + } + type _subPUQiz = BaseCollectionEvent + interface CollectionCreateEvent extends _subPUQiz { + httpContext: echo.Context + } + type _subwzIpk = BaseCollectionEvent + interface CollectionUpdateEvent extends _subwzIpk { + httpContext: echo.Context + } + type _subDnmPd = BaseCollectionEvent + interface CollectionDeleteEvent extends _subDnmPd { + httpContext: echo.Context + } + interface CollectionsImportEvent { + httpContext: echo.Context + collections: Array<(models.Collection | undefined)> + } + type _sublLbCA = BaseModelEvent + interface FileTokenEvent extends _sublLbCA { + httpContext: echo.Context + token: string + } + type _subirTIM = BaseCollectionEvent + interface FileDownloadEvent extends _subirTIM { + httpContext: echo.Context + record?: models.Record + fileField?: schema.SchemaField + servedPath: string + servedName: string + } +} + /** - * Copyright 2023 The Go Authors. All rights reserved. - * Use of this source code is governed by a BSD-style - * license that can be found in the LICENSE file. + * Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. + * In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. */ -namespace multipart { +namespace cobra { + interface PositionalArgs {(cmd: Command, args: Array): void } + // @ts-ignore + import flag = pflag /** - * A Part represents a single part in a multipart body. + * FParseErrWhitelist configures Flag parse errors to be ignored */ - interface Part { + interface FParseErrWhitelist extends _TygojaAny{} + /** + * Group Structure to manage groups for commands + */ + interface Group { + id: string + title: string + } + /** + * ShellCompDirective is a bit map representing the different behaviors the shell + * can be instructed to have once completions have been provided. + */ + interface ShellCompDirective extends Number{} + /** + * CompletionOptions are the options to control shell completion + */ + interface CompletionOptions { /** - * The headers of the body, if any, with the keys canonicalized - * in the same fashion that the Go http.Request headers are. - * For example, "foo-bar" changes case to "Foo-Bar" + * DisableDefaultCmd prevents Cobra from creating a default 'completion' command */ - header: textproto.MIMEHeader - } - interface Part { + disableDefaultCmd: boolean /** - * FormName returns the name parameter if p has a Content-Disposition - * of type "form-data". Otherwise it returns the empty string. + * DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag + * for shells that support completion descriptions */ - formName(): string - } - interface Part { + disableNoDescFlag: boolean /** - * FileName returns the filename parameter of the Part's Content-Disposition - * header. If not empty, the filename is passed through filepath.Base (which is - * platform dependent) before being returned. + * DisableDescriptions turns off all completion descriptions for shells + * that support them */ - fileName(): string - } - interface Part { + disableDescriptions: boolean /** - * Read reads the body of a part, after its headers and before the - * next part (if any) begins. + * HiddenDefaultCmd makes the default 'completion' command hidden */ - read(d: string|Array): number + hiddenDefaultCmd: boolean } - interface Part { - close(): void +} + +namespace migrate { + interface Migration { + file: string + up: (db: dbx.Builder) => void + down: (db: dbx.Builder) => void } } /** - * Package http provides HTTP client and server implementations. - * - * Get, Head, Post, and PostForm make HTTP (or HTTPS) requests: - * - * ``` - * resp, err := http.Get("http://example.com/") - * ... - * resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) - * ... - * resp, err := http.PostForm("http://example.com/form", - * url.Values{"key": {"Value"}, "id": {"123"}}) - * ``` + * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer + * object, creating another object (Reader or Writer) that also implements + * the interface but provides buffering and some help for textual I/O. + */ +namespace bufio { + /** + * ReadWriter stores pointers to a [Reader] and a [Writer]. + * It implements [io.ReadWriter]. + */ + type _subgPvbB = Reader&Writer + interface ReadWriter extends _subgPvbB { + } +} + +namespace store { +} + +/** + * Package url parses URLs and implements query escaping. + */ +namespace url { + /** + * The Userinfo type is an immutable encapsulation of username and + * password details for a [URL]. An existing Userinfo value is guaranteed + * to have a username set (potentially empty, as allowed by RFC 2396), + * and optionally a password. + */ + interface Userinfo { + } + interface Userinfo { + /** + * Username returns the username. + */ + username(): string + } + interface Userinfo { + /** + * Password returns the password in case it is set, and whether it is set. + */ + password(): [string, boolean] + } + interface Userinfo { + /** + * String returns the encoded userinfo information in the standard form + * of "username[:password]". + */ + string(): string + } +} + +/** + * Package net provides a portable interface for network I/O, including + * TCP/IP, UDP, domain name resolution, and Unix domain sockets. * - * The caller must close the response body when finished with it: + * Although the package provides access to low-level networking + * primitives, most clients will need only the basic interface provided + * by the [Dial], [Listen], and Accept functions and the associated + * [Conn] and [Listener] interfaces. The crypto/tls package uses + * the same interfaces and similar Dial and Listen functions. + * + * The Dial function connects to a server: * * ``` - * resp, err := http.Get("http://example.com/") + * conn, err := net.Dial("tcp", "golang.org:80") * if err != nil { * // handle error * } - * defer resp.Body.Close() - * body, err := io.ReadAll(resp.Body) + * fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n") + * status, err := bufio.NewReader(conn).ReadString('\n') * // ... * ``` * - * # Clients and Transports - * - * For control over HTTP client headers, redirect policy, and other - * settings, create a Client: + * The Listen function creates servers: * * ``` - * client := &http.Client{ - * CheckRedirect: redirectPolicyFunc, + * ln, err := net.Listen("tcp", ":8080") + * if err != nil { + * // handle error * } - * - * resp, err := client.Get("http://example.com") - * // ... - * - * req, err := http.NewRequest("GET", "http://example.com", nil) - * // ... - * req.Header.Add("If-None-Match", `W/"wyzzy"`) - * resp, err := client.Do(req) - * // ... - * ``` - * - * For control over proxies, TLS configuration, keep-alives, - * compression, and other settings, create a Transport: - * - * ``` - * tr := &http.Transport{ - * MaxIdleConns: 10, - * IdleConnTimeout: 30 * time.Second, - * DisableCompression: true, + * for { + * conn, err := ln.Accept() + * if err != nil { + * // handle error + * } + * go handleConnection(conn) * } - * client := &http.Client{Transport: tr} - * resp, err := client.Get("https://example.com") * ``` * - * Clients and Transports are safe for concurrent use by multiple - * goroutines and for efficiency should only be created once and re-used. - * - * # Servers - * - * ListenAndServe starts an HTTP server with a given address and handler. - * The handler is usually nil, which means to use DefaultServeMux. - * Handle and HandleFunc add handlers to DefaultServeMux: + * # Name Resolution * - * ``` - * http.Handle("/foo", fooHandler) + * The method for resolving domain names, whether indirectly with functions like Dial + * or directly with functions like [LookupHost] and [LookupAddr], varies by operating system. * - * http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { - * fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) - * }) + * On Unix systems, the resolver has two options for resolving names. + * It can use a pure Go resolver that sends DNS requests directly to the servers + * listed in /etc/resolv.conf, or it can use a cgo-based resolver that calls C + * library routines such as getaddrinfo and getnameinfo. * - * log.Fatal(http.ListenAndServe(":8080", nil)) - * ``` + * By default the pure Go resolver is used, because a blocked DNS request consumes + * only a goroutine, while a blocked C call consumes an operating system thread. + * When cgo is available, the cgo-based resolver is used instead under a variety of + * conditions: on systems that do not let programs make direct DNS requests (OS X), + * when the LOCALDOMAIN environment variable is present (even if empty), + * when the RES_OPTIONS or HOSTALIASES environment variable is non-empty, + * when the ASR_CONFIG environment variable is non-empty (OpenBSD only), + * when /etc/resolv.conf or /etc/nsswitch.conf specify the use of features that the + * Go resolver does not implement, and when the name being looked up ends in .local + * or is an mDNS name. * - * More control over the server's behavior is available by creating a - * custom Server: + * The resolver decision can be overridden by setting the netdns value of the + * GODEBUG environment variable (see package runtime) to go or cgo, as in: * * ``` - * s := &http.Server{ - * Addr: ":8080", - * Handler: myHandler, - * ReadTimeout: 10 * time.Second, - * WriteTimeout: 10 * time.Second, - * MaxHeaderBytes: 1 << 20, - * } - * log.Fatal(s.ListenAndServe()) + * export GODEBUG=netdns=go # force pure Go resolver + * export GODEBUG=netdns=cgo # force native resolver (cgo, win32) * ``` * - * # HTTP/2 + * The decision can also be forced while building the Go source tree + * by setting the netgo or netcgo build tag. * - * Starting with Go 1.6, the http package has transparent support for the - * HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 - * can do so by setting Transport.TLSNextProto (for clients) or - * Server.TLSNextProto (for servers) to a non-nil, empty - * map. Alternatively, the following GODEBUG settings are - * currently supported: + * A numeric netdns setting, as in GODEBUG=netdns=1, causes the resolver + * to print debugging information about its decisions. + * To force a particular resolver while also printing debugging information, + * join the two settings by a plus sign, as in GODEBUG=netdns=go+1. * - * ``` - * GODEBUG=http2client=0 # disable HTTP/2 client support - * GODEBUG=http2server=0 # disable HTTP/2 server support - * GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs - * GODEBUG=http2debug=2 # ... even more verbose, with frame dumps - * ``` + * On macOS, if Go code that uses the net package is built with + * -buildmode=c-archive, linking the resulting archive into a C program + * requires passing -lresolv when linking the C code. * - * Please report any issues before disabling HTTP/2 support: https://golang.org/s/http2bug + * On Plan 9, the resolver always accesses /net/cs and /net/dns. * - * The http package's Transport and Server both automatically enable - * HTTP/2 support for simple configurations. To enable HTTP/2 for more - * complex configurations, to use lower-level HTTP/2 features, or to use - * a newer version of Go's http2 package, import "golang.org/x/net/http2" - * directly and use its ConfigureTransport and/or ConfigureServer - * functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 - * package takes precedence over the net/http package's built-in HTTP/2 - * support. + * On Windows, in Go 1.18.x and earlier, the resolver always used C + * library functions, such as GetAddrInfo and DnsQuery. */ -namespace http { +namespace net { /** - * SameSite allows a server to define a cookie attribute making it impossible for - * the browser to send this cookie along with cross-site requests. The main - * goal is to mitigate the risk of cross-origin information leakage, and provide - * some protection against cross-site request forgery attacks. + * Addr represents a network end point address. * - * See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details. + * The two methods [Addr.Network] and [Addr.String] conventionally return strings + * that can be passed as the arguments to [Dial], but the exact form + * and meaning of the strings is up to the implementation. */ - interface SameSite extends Number{} - // @ts-ignore - import mathrand = rand - // @ts-ignore - import urlpkg = url + interface Addr { + [key:string]: any; + network(): string // name of the network (for example, "tcp", "udp") + string(): string // string form of address (for example, "192.0.2.1:25", "[2001:db8::1]:80") + } } /** - * Package echo implements high performance, minimalist Go web framework. - * - * Example: - * - * ``` - * package main - * - * import ( - * "github.com/labstack/echo/v5" - * "github.com/labstack/echo/v5/middleware" - * "log" - * "net/http" - * ) - * - * // Handler - * func hello(c echo.Context) error { - * return c.String(http.StatusOK, "Hello, World!") - * } - * - * func main() { - * // Echo instance - * e := echo.New() - * - * // Middleware - * e.Use(middleware.Logger()) - * e.Use(middleware.Recover()) - * - * // Routes - * e.GET("/", hello) - * - * // Start server - * if err := e.Start(":8080"); err != http.ErrServerClosed { - * log.Fatal(err) - * } - * } - * ``` - * - * Learn more at https://echo.labstack.com + * Package types implements some commonly used db serializable types + * like datetime, json, etc. */ -namespace echo { - // @ts-ignore - import stdContext = context +namespace types { /** - * Route contains information to adding/registering new route with the router. - * Method+Path pair uniquely identifies the Route. It is mandatory to provide Method+Path+Handler fields. + * JsonRaw defines a json value type that is safe for db read/write. */ - interface Route { - method: string - path: string - handler: HandlerFunc - middlewares: Array - name: string - } - interface Route { + interface JsonRaw extends Array{} + interface JsonRaw { /** - * ToRouteInfo converts Route to RouteInfo + * String returns the current JsonRaw instance as a json encoded string. */ - toRouteInfo(params: Array): RouteInfo + string(): string } - interface Route { + interface JsonRaw { /** - * ToRoute returns Route which Router uses to register the method handler for path. + * MarshalJSON implements the [json.Marshaler] interface. */ - toRoute(): Route + marshalJSON(): string|Array } - interface Route { + interface JsonRaw { /** - * ForGroup recreates Route with added group prefix and group middlewares it is grouped to. + * UnmarshalJSON implements the [json.Unmarshaler] interface. */ - forGroup(pathPrefix: string, middlewares: Array): Routable + unmarshalJSON(b: string|Array): void } - /** - * RoutableContext is additional interface that structures implementing Context must implement. Methods inside this - * interface are meant for request routing purposes and should not be used in middlewares. - */ - interface RoutableContext { - [key:string]: any; + interface JsonRaw { /** - * Request returns `*http.Request`. + * Value implements the [driver.Valuer] interface. */ - request(): (http.Request) + value(): any + } + interface JsonRaw { /** - * RawPathParams returns raw path pathParams value. Allocation of PathParams is handled by Context. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JsonRaw instance. */ - rawPathParams(): (PathParams) + scan(value: any): void + } +} + +namespace search { + /** + * Result defines the returned search result structure. + */ + interface Result { + page: number + perPage: number + totalItems: number + totalPages: number + items: any + } +} + +/** + * Package multipart implements MIME multipart parsing, as defined in RFC + * 2046. + * + * The implementation is sufficient for HTTP (RFC 2388) and the multipart + * bodies generated by popular browsers. + * + * # Limits + * + * To protect against malicious inputs, this package sets limits on the size + * of the MIME data it processes. + * + * Reader.NextPart and Reader.NextRawPart limit the number of headers in a + * part to 10000 and Reader.ReadForm limits the total number of headers in all + * FileHeaders to 10000. + * These limits may be adjusted with the GODEBUG=multipartmaxheaders= + * setting. + * + * Reader.ReadForm further limits the number of parts in a form to 1000. + * This limit may be adjusted with the GODEBUG=multipartmaxparts= + * setting. + */ +/** + * Copyright 2023 The Go Authors. All rights reserved. + * Use of this source code is governed by a BSD-style + * license that can be found in the LICENSE file. + */ +namespace multipart { + /** + * A Part represents a single part in a multipart body. + */ + interface Part { /** - * SetRawPathParams replaces any existing param values with new values for this context lifetime (request). - * Do not set any other value than what you got from RawPathParams as allocation of PathParams is handled by Context. + * The headers of the body, if any, with the keys canonicalized + * in the same fashion that the Go http.Request headers are. + * For example, "foo-bar" changes case to "Foo-Bar" */ - setRawPathParams(params: PathParams): void + header: textproto.MIMEHeader + } + interface Part { /** - * SetPath sets the registered path for the handler. + * FormName returns the name parameter if p has a Content-Disposition + * of type "form-data". Otherwise it returns the empty string. */ - setPath(p: string): void + formName(): string + } + interface Part { /** - * SetRouteInfo sets the route info of this request to the context. + * FileName returns the filename parameter of the Part's Content-Disposition + * header. If not empty, the filename is passed through filepath.Base (which is + * platform dependent) before being returned. */ - setRouteInfo(ri: RouteInfo): void + fileName(): string + } + interface Part { /** - * Set saves data in the context. Allows router to store arbitrary (that only router has access to) data in context - * for later use in middlewares/handler. + * Read reads the body of a part, after its headers and before the + * next part (if any) begins. */ - set(key: string, val: { - }): void + read(d: string|Array): number } - /** - * PathParam is tuple pf path parameter name and its value in request path - */ - interface PathParam { - name: string - value: string + interface Part { + close(): void } } -namespace store { -} - -namespace hook { - /** - * Handler defines a hook handler function. - */ - interface Handler {(e: T): void } +/** + * Package http provides HTTP client and server implementations. + * + * [Get], [Head], [Post], and [PostForm] make HTTP (or HTTPS) requests: + * + * ``` + * resp, err := http.Get("http://example.com/") + * ... + * resp, err := http.Post("http://example.com/upload", "image/jpeg", &buf) + * ... + * resp, err := http.PostForm("http://example.com/form", + * url.Values{"key": {"Value"}, "id": {"123"}}) + * ``` + * + * The caller must close the response body when finished with it: + * + * ``` + * resp, err := http.Get("http://example.com/") + * if err != nil { + * // handle error + * } + * defer resp.Body.Close() + * body, err := io.ReadAll(resp.Body) + * // ... + * ``` + * + * # Clients and Transports + * + * For control over HTTP client headers, redirect policy, and other + * settings, create a [Client]: + * + * ``` + * client := &http.Client{ + * CheckRedirect: redirectPolicyFunc, + * } + * + * resp, err := client.Get("http://example.com") + * // ... + * + * req, err := http.NewRequest("GET", "http://example.com", nil) + * // ... + * req.Header.Add("If-None-Match", `W/"wyzzy"`) + * resp, err := client.Do(req) + * // ... + * ``` + * + * For control over proxies, TLS configuration, keep-alives, + * compression, and other settings, create a [Transport]: + * + * ``` + * tr := &http.Transport{ + * MaxIdleConns: 10, + * IdleConnTimeout: 30 * time.Second, + * DisableCompression: true, + * } + * client := &http.Client{Transport: tr} + * resp, err := client.Get("https://example.com") + * ``` + * + * Clients and Transports are safe for concurrent use by multiple + * goroutines and for efficiency should only be created once and re-used. + * + * # Servers + * + * ListenAndServe starts an HTTP server with a given address and handler. + * The handler is usually nil, which means to use [DefaultServeMux]. + * [Handle] and [HandleFunc] add handlers to [DefaultServeMux]: + * + * ``` + * http.Handle("/foo", fooHandler) + * + * http.HandleFunc("/bar", func(w http.ResponseWriter, r *http.Request) { + * fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path)) + * }) + * + * log.Fatal(http.ListenAndServe(":8080", nil)) + * ``` + * + * More control over the server's behavior is available by creating a + * custom Server: + * + * ``` + * s := &http.Server{ + * Addr: ":8080", + * Handler: myHandler, + * ReadTimeout: 10 * time.Second, + * WriteTimeout: 10 * time.Second, + * MaxHeaderBytes: 1 << 20, + * } + * log.Fatal(s.ListenAndServe()) + * ``` + * + * # HTTP/2 + * + * Starting with Go 1.6, the http package has transparent support for the + * HTTP/2 protocol when using HTTPS. Programs that must disable HTTP/2 + * can do so by setting [Transport.TLSNextProto] (for clients) or + * [Server.TLSNextProto] (for servers) to a non-nil, empty + * map. Alternatively, the following GODEBUG settings are + * currently supported: + * + * ``` + * GODEBUG=http2client=0 # disable HTTP/2 client support + * GODEBUG=http2server=0 # disable HTTP/2 server support + * GODEBUG=http2debug=1 # enable verbose HTTP/2 debug logs + * GODEBUG=http2debug=2 # ... even more verbose, with frame dumps + * ``` + * + * Please report any issues before disabling HTTP/2 support: https://golang.org/s/http2bug + * + * The http package's [Transport] and [Server] both automatically enable + * HTTP/2 support for simple configurations. To enable HTTP/2 for more + * complex configurations, to use lower-level HTTP/2 features, or to use + * a newer version of Go's http2 package, import "golang.org/x/net/http2" + * directly and use its ConfigureTransport and/or ConfigureServer + * functions. Manually configuring HTTP/2 via the golang.org/x/net/http2 + * package takes precedence over the net/http package's built-in HTTP/2 + * support. + */ +namespace http { /** - * wrapped local Hook embedded struct to limit the public API surface. + * SameSite allows a server to define a cookie attribute making it impossible for + * the browser to send this cookie along with cross-site requests. The main + * goal is to mitigate the risk of cross-origin information leakage, and provide + * some protection against cross-site request forgery attacks. + * + * See https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site-00 for details. */ - type _subAvUey = Hook - interface mainHook extends _subAvUey { - } + interface SameSite extends Number{} + // @ts-ignore + import mathrand = rand + // @ts-ignore + import urlpkg = url } namespace mailer { @@ -19105,16 +18541,131 @@ namespace mailer { } } -namespace search { +namespace hook { /** - * Result defines the returned search result structure. + * Handler defines a hook handler function. */ - interface Result { - page: number - perPage: number - totalItems: number - totalPages: number - items: any + interface Handler {(e: T): void } + /** + * wrapped local Hook embedded struct to limit the public API surface. + */ + type _subgCDlS = Hook + interface mainHook extends _subgCDlS { + } +} + +/** + * Package echo implements high performance, minimalist Go web framework. + * + * Example: + * + * ``` + * package main + * + * import ( + * "github.com/labstack/echo/v5" + * "github.com/labstack/echo/v5/middleware" + * "log" + * "net/http" + * ) + * + * // Handler + * func hello(c echo.Context) error { + * return c.String(http.StatusOK, "Hello, World!") + * } + * + * func main() { + * // Echo instance + * e := echo.New() + * + * // Middleware + * e.Use(middleware.Logger()) + * e.Use(middleware.Recover()) + * + * // Routes + * e.GET("/", hello) + * + * // Start server + * if err := e.Start(":8080"); err != http.ErrServerClosed { + * log.Fatal(err) + * } + * } + * ``` + * + * Learn more at https://echo.labstack.com + */ +namespace echo { + // @ts-ignore + import stdContext = context + /** + * Route contains information to adding/registering new route with the router. + * Method+Path pair uniquely identifies the Route. It is mandatory to provide Method+Path+Handler fields. + */ + interface Route { + method: string + path: string + handler: HandlerFunc + middlewares: Array + name: string + } + interface Route { + /** + * ToRouteInfo converts Route to RouteInfo + */ + toRouteInfo(params: Array): RouteInfo + } + interface Route { + /** + * ToRoute returns Route which Router uses to register the method handler for path. + */ + toRoute(): Route + } + interface Route { + /** + * ForGroup recreates Route with added group prefix and group middlewares it is grouped to. + */ + forGroup(pathPrefix: string, middlewares: Array): Routable + } + /** + * RoutableContext is additional interface that structures implementing Context must implement. Methods inside this + * interface are meant for request routing purposes and should not be used in middlewares. + */ + interface RoutableContext { + [key:string]: any; + /** + * Request returns `*http.Request`. + */ + request(): (http.Request) + /** + * RawPathParams returns raw path pathParams value. Allocation of PathParams is handled by Context. + */ + rawPathParams(): (PathParams) + /** + * SetRawPathParams replaces any existing param values with new values for this context lifetime (request). + * Do not set any other value than what you got from RawPathParams as allocation of PathParams is handled by Context. + */ + setRawPathParams(params: PathParams): void + /** + * SetPath sets the registered path for the handler. + */ + setPath(p: string): void + /** + * SetRouteInfo sets the route info of this request to the context. + */ + setRouteInfo(ri: RouteInfo): void + /** + * Set saves data in the context. Allows router to store arbitrary (that only router has access to) data in context + * for later use in middlewares/handler. + */ + set(key: string, val: { + }): void + } + /** + * PathParam is tuple pf path parameter name and its value in request path + */ + interface PathParam { + name: string + value: string } } @@ -19223,334 +18774,560 @@ namespace subscriptions { } /** - * Package core is the backbone of PocketBase. + * Package slog provides structured logging, + * in which log records include a message, + * a severity level, and various other attributes + * expressed as key-value pairs. * - * It defines the main PocketBase App interface and its base implementation. - */ -namespace core { - interface BaseModelEvent { - model: models.Model - } - interface BaseModelEvent { - tags(): Array - } - interface BaseCollectionEvent { - collection?: models.Collection - } - interface BaseCollectionEvent { - tags(): Array - } -} - -/** - * Package types implements some commonly used db serializable types - * like datetime, json, etc. - */ -namespace types { -} - -/** - * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer - * object, creating another object (Reader or Writer) that also implements - * the interface but provides buffering and some help for textual I/O. - */ -namespace bufio { - /** - * Reader implements buffering for an io.Reader object. - */ - interface Reader { - } - interface Reader { - /** - * Size returns the size of the underlying buffer in bytes. - */ - size(): number - } - interface Reader { - /** - * Reset discards any buffered data, resets all state, and switches - * the buffered reader to read from r. - * Calling Reset on the zero value of Reader initializes the internal buffer - * to the default size. - * Calling b.Reset(b) (that is, resetting a Reader to itself) does nothing. - */ - reset(r: io.Reader): void - } - interface Reader { - /** - * Peek returns the next n bytes without advancing the reader. The bytes stop - * being valid at the next read call. If Peek returns fewer than n bytes, it - * also returns an error explaining why the read is short. The error is - * ErrBufferFull if n is larger than b's buffer size. - * - * Calling Peek prevents a UnreadByte or UnreadRune call from succeeding - * until the next read operation. - */ - peek(n: number): string|Array - } - interface Reader { - /** - * Discard skips the next n bytes, returning the number of bytes discarded. - * - * If Discard skips fewer than n bytes, it also returns an error. - * If 0 <= n <= b.Buffered(), Discard is guaranteed to succeed without - * reading from the underlying io.Reader. - */ - discard(n: number): number - } - interface Reader { - /** - * Read reads data into p. - * It returns the number of bytes read into p. - * The bytes are taken from at most one Read on the underlying Reader, - * hence n may be less than len(p). - * To read exactly len(p) bytes, use io.ReadFull(b, p). - * If the underlying Reader can return a non-zero count with io.EOF, - * then this Read method can do so as well; see the [io.Reader] docs. - */ - read(p: string|Array): number - } - interface Reader { - /** - * ReadByte reads and returns a single byte. - * If no byte is available, returns an error. - */ - readByte(): number + * It defines a type, [Logger], + * which provides several methods (such as [Logger.Info] and [Logger.Error]) + * for reporting events of interest. + * + * Each Logger is associated with a [Handler]. + * A Logger output method creates a [Record] from the method arguments + * and passes it to the Handler, which decides how to handle it. + * There is a default Logger accessible through top-level functions + * (such as [Info] and [Error]) that call the corresponding Logger methods. + * + * A log record consists of a time, a level, a message, and a set of key-value + * pairs, where the keys are strings and the values may be of any type. + * As an example, + * + * ``` + * slog.Info("hello", "count", 3) + * ``` + * + * creates a record containing the time of the call, + * a level of Info, the message "hello", and a single + * pair with key "count" and value 3. + * + * The [Info] top-level function calls the [Logger.Info] method on the default Logger. + * In addition to [Logger.Info], there are methods for Debug, Warn and Error levels. + * Besides these convenience methods for common levels, + * there is also a [Logger.Log] method which takes the level as an argument. + * Each of these methods has a corresponding top-level function that uses the + * default logger. + * + * The default handler formats the log record's message, time, level, and attributes + * as a string and passes it to the [log] package. + * + * ``` + * 2022/11/08 15:28:26 INFO hello count=3 + * ``` + * + * For more control over the output format, create a logger with a different handler. + * This statement uses [New] to create a new logger with a [TextHandler] + * that writes structured records in text form to standard error: + * + * ``` + * logger := slog.New(slog.NewTextHandler(os.Stderr, nil)) + * ``` + * + * [TextHandler] output is a sequence of key=value pairs, easily and unambiguously + * parsed by machine. This statement: + * + * ``` + * logger.Info("hello", "count", 3) + * ``` + * + * produces this output: + * + * ``` + * time=2022-11-08T15:28:26.000-05:00 level=INFO msg=hello count=3 + * ``` + * + * The package also provides [JSONHandler], whose output is line-delimited JSON: + * + * ``` + * logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)) + * logger.Info("hello", "count", 3) + * ``` + * + * produces this output: + * + * ``` + * {"time":"2022-11-08T15:28:26.000000000-05:00","level":"INFO","msg":"hello","count":3} + * ``` + * + * Both [TextHandler] and [JSONHandler] can be configured with [HandlerOptions]. + * There are options for setting the minimum level (see Levels, below), + * displaying the source file and line of the log call, and + * modifying attributes before they are logged. + * + * Setting a logger as the default with + * + * ``` + * slog.SetDefault(logger) + * ``` + * + * will cause the top-level functions like [Info] to use it. + * [SetDefault] also updates the default logger used by the [log] package, + * so that existing applications that use [log.Printf] and related functions + * will send log records to the logger's handler without needing to be rewritten. + * + * Some attributes are common to many log calls. + * For example, you may wish to include the URL or trace identifier of a server request + * with all log events arising from the request. + * Rather than repeat the attribute with every log call, you can use [Logger.With] + * to construct a new Logger containing the attributes: + * + * ``` + * logger2 := logger.With("url", r.URL) + * ``` + * + * The arguments to With are the same key-value pairs used in [Logger.Info]. + * The result is a new Logger with the same handler as the original, but additional + * attributes that will appear in the output of every call. + * + * # Levels + * + * A [Level] is an integer representing the importance or severity of a log event. + * The higher the level, the more severe the event. + * This package defines constants for the most common levels, + * but any int can be used as a level. + * + * In an application, you may wish to log messages only at a certain level or greater. + * One common configuration is to log messages at Info or higher levels, + * suppressing debug logging until it is needed. + * The built-in handlers can be configured with the minimum level to output by + * setting [HandlerOptions.Level]. + * The program's `main` function typically does this. + * The default value is LevelInfo. + * + * Setting the [HandlerOptions.Level] field to a [Level] value + * fixes the handler's minimum level throughout its lifetime. + * Setting it to a [LevelVar] allows the level to be varied dynamically. + * A LevelVar holds a Level and is safe to read or write from multiple + * goroutines. + * To vary the level dynamically for an entire program, first initialize + * a global LevelVar: + * + * ``` + * var programLevel = new(slog.LevelVar) // Info by default + * ``` + * + * Then use the LevelVar to construct a handler, and make it the default: + * + * ``` + * h := slog.NewJSONHandler(os.Stderr, &slog.HandlerOptions{Level: programLevel}) + * slog.SetDefault(slog.New(h)) + * ``` + * + * Now the program can change its logging level with a single statement: + * + * ``` + * programLevel.Set(slog.LevelDebug) + * ``` + * + * # Groups + * + * Attributes can be collected into groups. + * A group has a name that is used to qualify the names of its attributes. + * How this qualification is displayed depends on the handler. + * [TextHandler] separates the group and attribute names with a dot. + * [JSONHandler] treats each group as a separate JSON object, with the group name as the key. + * + * Use [Group] to create a Group attribute from a name and a list of key-value pairs: + * + * ``` + * slog.Group("request", + * "method", r.Method, + * "url", r.URL) + * ``` + * + * TextHandler would display this group as + * + * ``` + * request.method=GET request.url=http://example.com + * ``` + * + * JSONHandler would display it as + * + * ``` + * "request":{"method":"GET","url":"http://example.com"} + * ``` + * + * Use [Logger.WithGroup] to qualify all of a Logger's output + * with a group name. Calling WithGroup on a Logger results in a + * new Logger with the same Handler as the original, but with all + * its attributes qualified by the group name. + * + * This can help prevent duplicate attribute keys in large systems, + * where subsystems might use the same keys. + * Pass each subsystem a different Logger with its own group name so that + * potential duplicates are qualified: + * + * ``` + * logger := slog.Default().With("id", systemID) + * parserLogger := logger.WithGroup("parser") + * parseInput(input, parserLogger) + * ``` + * + * When parseInput logs with parserLogger, its keys will be qualified with "parser", + * so even if it uses the common key "id", the log line will have distinct keys. + * + * # Contexts + * + * Some handlers may wish to include information from the [context.Context] that is + * available at the call site. One example of such information + * is the identifier for the current span when tracing is enabled. + * + * The [Logger.Log] and [Logger.LogAttrs] methods take a context as a first + * argument, as do their corresponding top-level functions. + * + * Although the convenience methods on Logger (Info and so on) and the + * corresponding top-level functions do not take a context, the alternatives ending + * in "Context" do. For example, + * + * ``` + * slog.InfoContext(ctx, "message") + * ``` + * + * It is recommended to pass a context to an output method if one is available. + * + * # Attrs and Values + * + * An [Attr] is a key-value pair. The Logger output methods accept Attrs as well as + * alternating keys and values. The statement + * + * ``` + * slog.Info("hello", slog.Int("count", 3)) + * ``` + * + * behaves the same as + * + * ``` + * slog.Info("hello", "count", 3) + * ``` + * + * There are convenience constructors for [Attr] such as [Int], [String], and [Bool] + * for common types, as well as the function [Any] for constructing Attrs of any + * type. + * + * The value part of an Attr is a type called [Value]. + * Like an [any], a Value can hold any Go value, + * but it can represent typical values, including all numbers and strings, + * without an allocation. + * + * For the most efficient log output, use [Logger.LogAttrs]. + * It is similar to [Logger.Log] but accepts only Attrs, not alternating + * keys and values; this allows it, too, to avoid allocation. + * + * The call + * + * ``` + * logger.LogAttrs(ctx, slog.LevelInfo, "hello", slog.Int("count", 3)) + * ``` + * + * is the most efficient way to achieve the same output as + * + * ``` + * slog.InfoContext(ctx, "hello", "count", 3) + * ``` + * + * # Customizing a type's logging behavior + * + * If a type implements the [LogValuer] interface, the [Value] returned from its LogValue + * method is used for logging. You can use this to control how values of the type + * appear in logs. For example, you can redact secret information like passwords, + * or gather a struct's fields in a Group. See the examples under [LogValuer] for + * details. + * + * A LogValue method may return a Value that itself implements [LogValuer]. The [Value.Resolve] + * method handles these cases carefully, avoiding infinite loops and unbounded recursion. + * Handler authors and others may wish to use [Value.Resolve] instead of calling LogValue directly. + * + * # Wrapping output methods + * + * The logger functions use reflection over the call stack to find the file name + * and line number of the logging call within the application. This can produce + * incorrect source information for functions that wrap slog. For instance, if you + * define this function in file mylog.go: + * + * ``` + * func Infof(logger *slog.Logger, format string, args ...any) { + * logger.Info(fmt.Sprintf(format, args...)) + * } + * ``` + * + * and you call it like this in main.go: + * + * ``` + * Infof(slog.Default(), "hello, %s", "world") + * ``` + * + * then slog will report the source file as mylog.go, not main.go. + * + * A correct implementation of Infof will obtain the source location + * (pc) and pass it to NewRecord. + * The Infof function in the package-level example called "wrapping" + * demonstrates how to do this. + * + * # Working with Records + * + * Sometimes a Handler will need to modify a Record + * before passing it on to another Handler or backend. + * A Record contains a mixture of simple public fields (e.g. Time, Level, Message) + * and hidden fields that refer to state (such as attributes) indirectly. This + * means that modifying a simple copy of a Record (e.g. by calling + * [Record.Add] or [Record.AddAttrs] to add attributes) + * may have unexpected effects on the original. + * Before modifying a Record, use [Record.Clone] to + * create a copy that shares no state with the original, + * or create a new Record with [NewRecord] + * and build up its Attrs by traversing the old ones with [Record.Attrs]. + * + * # Performance considerations + * + * If profiling your application demonstrates that logging is taking significant time, + * the following suggestions may help. + * + * If many log lines have a common attribute, use [Logger.With] to create a Logger with + * that attribute. The built-in handlers will format that attribute only once, at the + * call to [Logger.With]. The [Handler] interface is designed to allow that optimization, + * and a well-written Handler should take advantage of it. + * + * The arguments to a log call are always evaluated, even if the log event is discarded. + * If possible, defer computation so that it happens only if the value is actually logged. + * For example, consider the call + * + * ``` + * slog.Info("starting request", "url", r.URL.String()) // may compute String unnecessarily + * ``` + * + * The URL.String method will be called even if the logger discards Info-level events. + * Instead, pass the URL directly: + * + * ``` + * slog.Info("starting request", "url", &r.URL) // calls URL.String only if needed + * ``` + * + * The built-in [TextHandler] will call its String method, but only + * if the log event is enabled. + * Avoiding the call to String also preserves the structure of the underlying value. + * For example [JSONHandler] emits the components of the parsed URL as a JSON object. + * If you want to avoid eagerly paying the cost of the String call + * without causing the handler to potentially inspect the structure of the value, + * wrap the value in a fmt.Stringer implementation that hides its Marshal methods. + * + * You can also use the [LogValuer] interface to avoid unnecessary work in disabled log + * calls. Say you need to log some expensive value: + * + * ``` + * slog.Debug("frobbing", "value", computeExpensiveValue(arg)) + * ``` + * + * Even if this line is disabled, computeExpensiveValue will be called. + * To avoid that, define a type implementing LogValuer: + * + * ``` + * type expensive struct { arg int } + * + * func (e expensive) LogValue() slog.Value { + * return slog.AnyValue(computeExpensiveValue(e.arg)) + * } + * ``` + * + * Then use a value of that type in log calls: + * + * ``` + * slog.Debug("frobbing", "value", expensive{arg}) + * ``` + * + * Now computeExpensiveValue will only be called when the line is enabled. + * + * The built-in handlers acquire a lock before calling [io.Writer.Write] + * to ensure that each record is written in one piece. User-defined + * handlers are responsible for their own locking. + * + * # Writing a handler + * + * For a guide to writing a custom handler, see https://golang.org/s/slog-handler-guide. + */ +namespace slog { + /** + * An Attr is a key-value pair. + */ + interface Attr { + key: string + value: Value } - interface Reader { + interface Attr { /** - * UnreadByte unreads the last byte. Only the most recently read byte can be unread. - * - * UnreadByte returns an error if the most recent method called on the - * Reader was not a read operation. Notably, Peek, Discard, and WriteTo are not - * considered read operations. + * Equal reports whether a and b have equal keys and values. */ - unreadByte(): void + equal(b: Attr): boolean } - interface Reader { - /** - * ReadRune reads a single UTF-8 encoded Unicode character and returns the - * rune and its size in bytes. If the encoded rune is invalid, it consumes one byte - * and returns unicode.ReplacementChar (U+FFFD) with a size of 1. - */ - readRune(): [number, number] + interface Attr { + string(): string } - interface Reader { + /** + * A Handler handles log records produced by a Logger. + * + * A typical handler may print log records to standard error, + * or write them to a file or database, or perhaps augment them + * with additional attributes and pass them on to another handler. + * + * Any of the Handler's methods may be called concurrently with itself + * or with other methods. It is the responsibility of the Handler to + * manage this concurrency. + * + * Users of the slog package should not invoke Handler methods directly. + * They should use the methods of [Logger] instead. + */ + interface Handler { + [key:string]: any; /** - * UnreadRune unreads the last rune. If the most recent method called on - * the Reader was not a ReadRune, UnreadRune returns an error. (In this - * regard it is stricter than UnreadByte, which will unread the last byte - * from any read operation.) + * Enabled reports whether the handler handles records at the given level. + * The handler ignores records whose level is lower. + * It is called early, before any arguments are processed, + * to save effort if the log event should be discarded. + * If called from a Logger method, the first argument is the context + * passed to that method, or context.Background() if nil was passed + * or the method does not take a context. + * The context is passed so Enabled can use its values + * to make a decision. */ - unreadRune(): void - } - interface Reader { + enabled(_arg0: context.Context, _arg1: Level): boolean /** - * Buffered returns the number of bytes that can be read from the current buffer. + * Handle handles the Record. + * It will only be called when Enabled returns true. + * The Context argument is as for Enabled. + * It is present solely to provide Handlers access to the context's values. + * Canceling the context should not affect record processing. + * (Among other things, log messages may be necessary to debug a + * cancellation-related problem.) + * + * Handle methods that produce output should observe the following rules: + * ``` + * - If r.Time is the zero time, ignore the time. + * - If r.PC is zero, ignore it. + * - Attr's values should be resolved. + * - If an Attr's key and value are both the zero value, ignore the Attr. + * This can be tested with attr.Equal(Attr{}). + * - If a group's key is empty, inline the group's Attrs. + * - If a group has no Attrs (even if it has a non-empty key), + * ignore it. + * ``` */ - buffered(): number - } - interface Reader { + handle(_arg0: context.Context, _arg1: Record): void /** - * ReadSlice reads until the first occurrence of delim in the input, - * returning a slice pointing at the bytes in the buffer. - * The bytes stop being valid at the next read. - * If ReadSlice encounters an error before finding a delimiter, - * it returns all the data in the buffer and the error itself (often io.EOF). - * ReadSlice fails with error ErrBufferFull if the buffer fills without a delim. - * Because the data returned from ReadSlice will be overwritten - * by the next I/O operation, most clients should use - * ReadBytes or ReadString instead. - * ReadSlice returns err != nil if and only if line does not end in delim. + * WithAttrs returns a new Handler whose attributes consist of + * both the receiver's attributes and the arguments. + * The Handler owns the slice: it may retain, modify or discard it. */ - readSlice(delim: number): string|Array - } - interface Reader { + withAttrs(attrs: Array): Handler /** - * ReadLine is a low-level line-reading primitive. Most callers should use - * ReadBytes('\n') or ReadString('\n') instead or use a Scanner. + * WithGroup returns a new Handler with the given group appended to + * the receiver's existing groups. + * The keys of all subsequent attributes, whether added by With or in a + * Record, should be qualified by the sequence of group names. * - * ReadLine tries to return a single line, not including the end-of-line bytes. - * If the line was too long for the buffer then isPrefix is set and the - * beginning of the line is returned. The rest of the line will be returned - * from future calls. isPrefix will be false when returning the last fragment - * of the line. The returned buffer is only valid until the next call to - * ReadLine. ReadLine either returns a non-nil line or it returns an error, - * never both. + * How this qualification happens is up to the Handler, so long as + * this Handler's attribute keys differ from those of another Handler + * with a different sequence of group names. * - * The text returned from ReadLine does not include the line end ("\r\n" or "\n"). - * No indication or error is given if the input ends without a final line end. - * Calling UnreadByte after ReadLine will always unread the last byte read - * (possibly a character belonging to the line end) even if that byte is not - * part of the line returned by ReadLine. - */ - readLine(): [string|Array, boolean] - } - interface Reader { - /** - * ReadBytes reads until the first occurrence of delim in the input, - * returning a slice containing the data up to and including the delimiter. - * If ReadBytes encounters an error before finding a delimiter, - * it returns the data read before the error and the error itself (often io.EOF). - * ReadBytes returns err != nil if and only if the returned data does not end in - * delim. - * For simple uses, a Scanner may be more convenient. - */ - readBytes(delim: number): string|Array - } - interface Reader { - /** - * ReadString reads until the first occurrence of delim in the input, - * returning a string containing the data up to and including the delimiter. - * If ReadString encounters an error before finding a delimiter, - * it returns the data read before the error and the error itself (often io.EOF). - * ReadString returns err != nil if and only if the returned data does not end in - * delim. - * For simple uses, a Scanner may be more convenient. - */ - readString(delim: number): string - } - interface Reader { - /** - * WriteTo implements io.WriterTo. - * This may make multiple calls to the Read method of the underlying Reader. - * If the underlying reader supports the WriteTo method, - * this calls the underlying WriteTo without buffering. + * A Handler should treat WithGroup as starting a Group of Attrs that ends + * at the end of the log event. That is, + * + * ``` + * logger.WithGroup("s").LogAttrs(ctx, level, msg, slog.Int("a", 1), slog.Int("b", 2)) + * ``` + * + * should behave like + * + * ``` + * logger.LogAttrs(ctx, level, msg, slog.Group("s", slog.Int("a", 1), slog.Int("b", 2))) + * ``` + * + * If the name is empty, WithGroup returns the receiver. */ - writeTo(w: io.Writer): number + withGroup(name: string): Handler } /** - * Writer implements buffering for an io.Writer object. - * If an error occurs writing to a Writer, no more data will be - * accepted and all subsequent writes, and Flush, will return the error. - * After all data has been written, the client should call the - * Flush method to guarantee all data has been forwarded to - * the underlying io.Writer. + * A Level is the importance or severity of a log event. + * The higher the level, the more important or severe the event. */ - interface Writer { - } - interface Writer { - /** - * Size returns the size of the underlying buffer in bytes. - */ - size(): number - } - interface Writer { - /** - * Reset discards any unflushed buffered data, clears any error, and - * resets b to write its output to w. - * Calling Reset on the zero value of Writer initializes the internal buffer - * to the default size. - * Calling w.Reset(w) (that is, resetting a Writer to itself) does nothing. - */ - reset(w: io.Writer): void - } - interface Writer { - /** - * Flush writes any buffered data to the underlying io.Writer. - */ - flush(): void - } - interface Writer { - /** - * Available returns how many bytes are unused in the buffer. - */ - available(): number - } - interface Writer { - /** - * AvailableBuffer returns an empty buffer with b.Available() capacity. - * This buffer is intended to be appended to and - * passed to an immediately succeeding Write call. - * The buffer is only valid until the next write operation on b. - */ - availableBuffer(): string|Array - } - interface Writer { + interface Level extends Number{} + interface Level { /** - * Buffered returns the number of bytes that have been written into the current buffer. + * String returns a name for the level. + * If the level has a name, then that name + * in uppercase is returned. + * If the level is between named values, then + * an integer is appended to the uppercased name. + * Examples: + * + * ``` + * LevelWarn.String() => "WARN" + * (LevelInfo+2).String() => "INFO+2" + * ``` */ - buffered(): number + string(): string } - interface Writer { + interface Level { /** - * Write writes the contents of p into the buffer. - * It returns the number of bytes written. - * If nn < len(p), it also returns an error explaining - * why the write is short. + * MarshalJSON implements [encoding/json.Marshaler] + * by quoting the output of [Level.String]. */ - write(p: string|Array): number + marshalJSON(): string|Array } - interface Writer { + interface Level { /** - * WriteByte writes a single byte. + * UnmarshalJSON implements [encoding/json.Unmarshaler] + * It accepts any string produced by [Level.MarshalJSON], + * ignoring case. + * It also accepts numeric offsets that would result in a different string on + * output. For example, "Error-8" would marshal as "INFO". */ - writeByte(c: number): void + unmarshalJSON(data: string|Array): void } - interface Writer { + interface Level { /** - * WriteRune writes a single Unicode code point, returning - * the number of bytes written and any error. + * MarshalText implements [encoding.TextMarshaler] + * by calling [Level.String]. */ - writeRune(r: number): number + marshalText(): string|Array } - interface Writer { + interface Level { /** - * WriteString writes a string. - * It returns the number of bytes written. - * If the count is less than len(s), it also returns an error explaining - * why the write is short. + * UnmarshalText implements [encoding.TextUnmarshaler]. + * It accepts any string produced by [Level.MarshalText], + * ignoring case. + * It also accepts numeric offsets that would result in a different string on + * output. For example, "Error-8" would marshal as "INFO". */ - writeString(s: string): number + unmarshalText(data: string|Array): void } - interface Writer { + interface Level { /** - * ReadFrom implements io.ReaderFrom. If the underlying writer - * supports the ReadFrom method, this calls the underlying ReadFrom. - * If there is buffered data and an underlying ReadFrom, this fills - * the buffer and writes it before calling ReadFrom. + * Level returns the receiver. + * It implements [Leveler]. */ - readFrom(r: io.Reader): number + level(): Level } + // @ts-ignore + import loginternal = internal } /** - * Package mail implements parsing of mail messages. + * Package core is the backbone of PocketBase. * - * For the most part, this package follows the syntax as specified by RFC 5322 and - * extended by RFC 6532. - * Notable divergences: - * ``` - * - Obsolete address formats are not parsed, including addresses with - * embedded route information. - * - The full range of spacing (the CFWS syntax element) is not supported, - * such as breaking addresses across lines. - * - No unicode normalization is performed. - * - The special characters ()[]:;@\, are allowed to appear unquoted in names. - * - A leading From line is permitted, as in mbox format (RFC 4155). - * ``` + * It defines the main PocketBase App interface and its base implementation. */ -namespace mail { - /** - * Address represents a single mail address. - * An address such as "Barry Gibbs " is represented - * as Address{Name: "Barry Gibbs", Address: "bg@example.com"}. - */ - interface Address { - name: string // Proper name; may be empty. - address: string // user@domain +namespace core { + interface BaseModelEvent { + model: models.Model } - interface Address { - /** - * String formats the address as a valid RFC 5322 address. - * If the address's name contains non-ASCII characters - * the name will be rendered according to RFC 2047. - */ - string(): string + interface BaseModelEvent { + tags(): Array + } + interface BaseCollectionEvent { + collection?: models.Collection + } + interface BaseCollectionEvent { + tags(): Array } -} - -namespace search { } namespace subscriptions { @@ -19599,7 +19376,7 @@ namespace subscriptions { * ``` * * For more control over the output format, create a logger with a different handler. - * This statement uses [New] to create a new logger with a TextHandler + * This statement uses [New] to create a new logger with a [TextHandler] * that writes structured records in text form to standard error: * * ``` @@ -19805,7 +19582,7 @@ namespace subscriptions { * is the most efficient way to achieve the same output as * * ``` - * slog.Info("hello", "count", 3) + * slog.InfoContext(ctx, "hello", "count", 3) * ``` * * # Customizing a type's logging behavior @@ -19818,7 +19595,7 @@ namespace subscriptions { * * A LogValue method may return a Value that itself implements [LogValuer]. The [Value.Resolve] * method handles these cases carefully, avoiding infinite loops and unbounded recursion. - * Handler authors and others may wish to use Value.Resolve instead of calling LogValue directly. + * Handler authors and others may wish to use [Value.Resolve] instead of calling LogValue directly. * * # Wrapping output methods * @@ -19828,8 +19605,8 @@ namespace subscriptions { * define this function in file mylog.go: * * ``` - * func Infof(format string, args ...any) { - * slog.Default().Info(fmt.Sprintf(format, args...)) + * func Infof(logger *slog.Logger, format string, args ...any) { + * logger.Info(fmt.Sprintf(format, args...)) * } * ``` * @@ -19939,163 +19716,474 @@ namespace slog { */ interface Record { /** - * The time at which the output method (Log, Info, etc.) was called. + * The time at which the output method (Log, Info, etc.) was called. + */ + time: time.Time + /** + * The log message. + */ + message: string + /** + * The level of the event. + */ + level: Level + /** + * The program counter at the time the record was constructed, as determined + * by runtime.Callers. If zero, no program counter is available. + * + * The only valid use for this value is as an argument to + * [runtime.CallersFrames]. In particular, it must not be passed to + * [runtime.FuncForPC]. + */ + pc: number + } + interface Record { + /** + * Clone returns a copy of the record with no shared state. + * The original record and the clone can both be modified + * without interfering with each other. + */ + clone(): Record + } + interface Record { + /** + * NumAttrs returns the number of attributes in the [Record]. + */ + numAttrs(): number + } + interface Record { + /** + * Attrs calls f on each Attr in the [Record]. + * Iteration stops if f returns false. + */ + attrs(f: (_arg0: Attr) => boolean): void + } + interface Record { + /** + * AddAttrs appends the given Attrs to the [Record]'s list of Attrs. + * It omits empty groups. + */ + addAttrs(...attrs: Attr[]): void + } + interface Record { + /** + * Add converts the args to Attrs as described in [Logger.Log], + * then appends the Attrs to the [Record]'s list of Attrs. + * It omits empty groups. + */ + add(...args: any[]): void + } + /** + * A Value can represent any Go value, but unlike type any, + * it can represent most small values without an allocation. + * The zero Value corresponds to nil. + */ + interface Value { + } + interface Value { + /** + * Kind returns v's Kind. + */ + kind(): Kind + } + interface Value { + /** + * Any returns v's value as an any. + */ + any(): any + } + interface Value { + /** + * String returns Value's value as a string, formatted like [fmt.Sprint]. Unlike + * the methods Int64, Float64, and so on, which panic if v is of the + * wrong kind, String never panics. + */ + string(): string + } + interface Value { + /** + * Int64 returns v's value as an int64. It panics + * if v is not a signed integer. + */ + int64(): number + } + interface Value { + /** + * Uint64 returns v's value as a uint64. It panics + * if v is not an unsigned integer. + */ + uint64(): number + } + interface Value { + /** + * Bool returns v's value as a bool. It panics + * if v is not a bool. + */ + bool(): boolean + } + interface Value { + /** + * Duration returns v's value as a [time.Duration]. It panics + * if v is not a time.Duration. + */ + duration(): time.Duration + } + interface Value { + /** + * Float64 returns v's value as a float64. It panics + * if v is not a float64. + */ + float64(): number + } + interface Value { + /** + * Time returns v's value as a [time.Time]. It panics + * if v is not a time.Time. + */ + time(): time.Time + } + interface Value { + /** + * LogValuer returns v's value as a LogValuer. It panics + * if v is not a LogValuer. + */ + logValuer(): LogValuer + } + interface Value { + /** + * Group returns v's value as a []Attr. + * It panics if v's [Kind] is not [KindGroup]. + */ + group(): Array + } + interface Value { + /** + * Equal reports whether v and w represent the same Go value. + */ + equal(w: Value): boolean + } + interface Value { + /** + * Resolve repeatedly calls LogValue on v while it implements [LogValuer], + * and returns the result. + * If v resolves to a group, the group's attributes' values are not recursively + * resolved. + * If the number of LogValue calls exceeds a threshold, a Value containing an + * error is returned. + * Resolve's return value is guaranteed not to be of Kind [KindLogValuer]. + */ + resolve(): Value + } +} + +/** + * Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer + * object, creating another object (Reader or Writer) that also implements + * the interface but provides buffering and some help for textual I/O. + */ +namespace bufio { + /** + * Reader implements buffering for an io.Reader object. + */ + interface Reader { + } + interface Reader { + /** + * Size returns the size of the underlying buffer in bytes. + */ + size(): number + } + interface Reader { + /** + * Reset discards any buffered data, resets all state, and switches + * the buffered reader to read from r. + * Calling Reset on the zero value of [Reader] initializes the internal buffer + * to the default size. + * Calling b.Reset(b) (that is, resetting a [Reader] to itself) does nothing. + */ + reset(r: io.Reader): void + } + interface Reader { + /** + * Peek returns the next n bytes without advancing the reader. The bytes stop + * being valid at the next read call. If Peek returns fewer than n bytes, it + * also returns an error explaining why the read is short. The error is + * [ErrBufferFull] if n is larger than b's buffer size. + * + * Calling Peek prevents a [Reader.UnreadByte] or [Reader.UnreadRune] call from succeeding + * until the next read operation. + */ + peek(n: number): string|Array + } + interface Reader { + /** + * Discard skips the next n bytes, returning the number of bytes discarded. + * + * If Discard skips fewer than n bytes, it also returns an error. + * If 0 <= n <= b.Buffered(), Discard is guaranteed to succeed without + * reading from the underlying io.Reader. + */ + discard(n: number): number + } + interface Reader { + /** + * Read reads data into p. + * It returns the number of bytes read into p. + * The bytes are taken from at most one Read on the underlying [Reader], + * hence n may be less than len(p). + * To read exactly len(p) bytes, use io.ReadFull(b, p). + * If the underlying [Reader] can return a non-zero count with io.EOF, + * then this Read method can do so as well; see the [io.Reader] docs. + */ + read(p: string|Array): number + } + interface Reader { + /** + * ReadByte reads and returns a single byte. + * If no byte is available, returns an error. */ - time: time.Time + readByte(): number + } + interface Reader { /** - * The log message. + * UnreadByte unreads the last byte. Only the most recently read byte can be unread. + * + * UnreadByte returns an error if the most recent method called on the + * [Reader] was not a read operation. Notably, [Reader.Peek], [Reader.Discard], and [Reader.WriteTo] are not + * considered read operations. */ - message: string + unreadByte(): void + } + interface Reader { /** - * The level of the event. + * ReadRune reads a single UTF-8 encoded Unicode character and returns the + * rune and its size in bytes. If the encoded rune is invalid, it consumes one byte + * and returns unicode.ReplacementChar (U+FFFD) with a size of 1. */ - level: Level + readRune(): [number, number] + } + interface Reader { /** - * The program counter at the time the record was constructed, as determined - * by runtime.Callers. If zero, no program counter is available. - * - * The only valid use for this value is as an argument to - * [runtime.CallersFrames]. In particular, it must not be passed to - * [runtime.FuncForPC]. + * UnreadRune unreads the last rune. If the most recent method called on + * the [Reader] was not a [Reader.ReadRune], [Reader.UnreadRune] returns an error. (In this + * regard it is stricter than [Reader.UnreadByte], which will unread the last byte + * from any read operation.) */ - pc: number + unreadRune(): void } - interface Record { + interface Reader { /** - * Clone returns a copy of the record with no shared state. - * The original record and the clone can both be modified - * without interfering with each other. + * Buffered returns the number of bytes that can be read from the current buffer. */ - clone(): Record + buffered(): number } - interface Record { + interface Reader { /** - * NumAttrs returns the number of attributes in the Record. + * ReadSlice reads until the first occurrence of delim in the input, + * returning a slice pointing at the bytes in the buffer. + * The bytes stop being valid at the next read. + * If ReadSlice encounters an error before finding a delimiter, + * it returns all the data in the buffer and the error itself (often io.EOF). + * ReadSlice fails with error [ErrBufferFull] if the buffer fills without a delim. + * Because the data returned from ReadSlice will be overwritten + * by the next I/O operation, most clients should use + * [Reader.ReadBytes] or ReadString instead. + * ReadSlice returns err != nil if and only if line does not end in delim. */ - numAttrs(): number + readSlice(delim: number): string|Array } - interface Record { + interface Reader { /** - * Attrs calls f on each Attr in the Record. - * Iteration stops if f returns false. + * ReadLine is a low-level line-reading primitive. Most callers should use + * [Reader.ReadBytes]('\n') or [Reader.ReadString]('\n') instead or use a [Scanner]. + * + * ReadLine tries to return a single line, not including the end-of-line bytes. + * If the line was too long for the buffer then isPrefix is set and the + * beginning of the line is returned. The rest of the line will be returned + * from future calls. isPrefix will be false when returning the last fragment + * of the line. The returned buffer is only valid until the next call to + * ReadLine. ReadLine either returns a non-nil line or it returns an error, + * never both. + * + * The text returned from ReadLine does not include the line end ("\r\n" or "\n"). + * No indication or error is given if the input ends without a final line end. + * Calling [Reader.UnreadByte] after ReadLine will always unread the last byte read + * (possibly a character belonging to the line end) even if that byte is not + * part of the line returned by ReadLine. */ - attrs(f: (_arg0: Attr) => boolean): void + readLine(): [string|Array, boolean] } - interface Record { + interface Reader { /** - * AddAttrs appends the given Attrs to the Record's list of Attrs. - * It omits empty groups. + * ReadBytes reads until the first occurrence of delim in the input, + * returning a slice containing the data up to and including the delimiter. + * If ReadBytes encounters an error before finding a delimiter, + * it returns the data read before the error and the error itself (often io.EOF). + * ReadBytes returns err != nil if and only if the returned data does not end in + * delim. + * For simple uses, a Scanner may be more convenient. */ - addAttrs(...attrs: Attr[]): void + readBytes(delim: number): string|Array } - interface Record { + interface Reader { /** - * Add converts the args to Attrs as described in [Logger.Log], - * then appends the Attrs to the Record's list of Attrs. - * It omits empty groups. + * ReadString reads until the first occurrence of delim in the input, + * returning a string containing the data up to and including the delimiter. + * If ReadString encounters an error before finding a delimiter, + * it returns the data read before the error and the error itself (often io.EOF). + * ReadString returns err != nil if and only if the returned data does not end in + * delim. + * For simple uses, a Scanner may be more convenient. */ - add(...args: any[]): void + readString(delim: number): string + } + interface Reader { + /** + * WriteTo implements io.WriterTo. + * This may make multiple calls to the [Reader.Read] method of the underlying [Reader]. + * If the underlying reader supports the [Reader.WriteTo] method, + * this calls the underlying [Reader.WriteTo] without buffering. + */ + writeTo(w: io.Writer): number } /** - * A Value can represent any Go value, but unlike type any, - * it can represent most small values without an allocation. - * The zero Value corresponds to nil. + * Writer implements buffering for an [io.Writer] object. + * If an error occurs writing to a [Writer], no more data will be + * accepted and all subsequent writes, and [Writer.Flush], will return the error. + * After all data has been written, the client should call the + * [Writer.Flush] method to guarantee all data has been forwarded to + * the underlying [io.Writer]. */ - interface Value { + interface Writer { } - interface Value { + interface Writer { /** - * Kind returns v's Kind. + * Size returns the size of the underlying buffer in bytes. */ - kind(): Kind + size(): number } - interface Value { + interface Writer { /** - * Any returns v's value as an any. + * Reset discards any unflushed buffered data, clears any error, and + * resets b to write its output to w. + * Calling Reset on the zero value of [Writer] initializes the internal buffer + * to the default size. + * Calling w.Reset(w) (that is, resetting a [Writer] to itself) does nothing. */ - any(): any + reset(w: io.Writer): void } - interface Value { + interface Writer { /** - * String returns Value's value as a string, formatted like fmt.Sprint. Unlike - * the methods Int64, Float64, and so on, which panic if v is of the - * wrong kind, String never panics. + * Flush writes any buffered data to the underlying [io.Writer]. */ - string(): string + flush(): void } - interface Value { + interface Writer { /** - * Int64 returns v's value as an int64. It panics - * if v is not a signed integer. + * Available returns how many bytes are unused in the buffer. */ - int64(): number + available(): number } - interface Value { + interface Writer { /** - * Uint64 returns v's value as a uint64. It panics - * if v is not an unsigned integer. + * AvailableBuffer returns an empty buffer with b.Available() capacity. + * This buffer is intended to be appended to and + * passed to an immediately succeeding [Writer.Write] call. + * The buffer is only valid until the next write operation on b. */ - uint64(): number + availableBuffer(): string|Array } - interface Value { + interface Writer { /** - * Bool returns v's value as a bool. It panics - * if v is not a bool. + * Buffered returns the number of bytes that have been written into the current buffer. */ - bool(): boolean + buffered(): number } - interface Value { + interface Writer { /** - * Duration returns v's value as a time.Duration. It panics - * if v is not a time.Duration. + * Write writes the contents of p into the buffer. + * It returns the number of bytes written. + * If nn < len(p), it also returns an error explaining + * why the write is short. */ - duration(): time.Duration + write(p: string|Array): number } - interface Value { + interface Writer { /** - * Float64 returns v's value as a float64. It panics - * if v is not a float64. + * WriteByte writes a single byte. */ - float64(): number + writeByte(c: number): void } - interface Value { + interface Writer { /** - * Time returns v's value as a time.Time. It panics - * if v is not a time.Time. + * WriteRune writes a single Unicode code point, returning + * the number of bytes written and any error. */ - time(): time.Time + writeRune(r: number): number } - interface Value { + interface Writer { /** - * LogValuer returns v's value as a LogValuer. It panics - * if v is not a LogValuer. + * WriteString writes a string. + * It returns the number of bytes written. + * If the count is less than len(s), it also returns an error explaining + * why the write is short. */ - logValuer(): LogValuer + writeString(s: string): number } - interface Value { + interface Writer { /** - * Group returns v's value as a []Attr. - * It panics if v's Kind is not KindGroup. + * ReadFrom implements [io.ReaderFrom]. If the underlying writer + * supports the ReadFrom method, this calls the underlying ReadFrom. + * If there is buffered data and an underlying ReadFrom, this fills + * the buffer and writes it before calling ReadFrom. */ - group(): Array + readFrom(r: io.Reader): number } - interface Value { - /** - * Equal reports whether v and w represent the same Go value. - */ - equal(w: Value): boolean +} + +/** + * Package types implements some commonly used db serializable types + * like datetime, json, etc. + */ +namespace types { +} + +namespace search { +} + +/** + * Package mail implements parsing of mail messages. + * + * For the most part, this package follows the syntax as specified by RFC 5322 and + * extended by RFC 6532. + * Notable divergences: + * ``` + * - Obsolete address formats are not parsed, including addresses with + * embedded route information. + * - The full range of spacing (the CFWS syntax element) is not supported, + * such as breaking addresses across lines. + * - No unicode normalization is performed. + * - The special characters ()[]:;@\, are allowed to appear unquoted in names. + * - A leading From line is permitted, as in mbox format (RFC 4155). + * ``` + */ +namespace mail { + /** + * Address represents a single mail address. + * An address such as "Barry Gibbs " is represented + * as Address{Name: "Barry Gibbs", Address: "bg@example.com"}. + */ + interface Address { + name: string // Proper name; may be empty. + address: string // user@domain } - interface Value { + interface Address { /** - * Resolve repeatedly calls LogValue on v while it implements LogValuer, - * and returns the result. - * If v resolves to a group, the group's attributes' values are not recursively - * resolved. - * If the number of LogValue calls exceeds a threshold, a Value containing an - * error is returned. - * Resolve's return value is guaranteed not to be of Kind KindLogValuer. + * String formats the address as a valid RFC 5322 address. + * If the address's name contains non-ASCII characters + * the name will be rendered according to RFC 2047. */ - resolve(): Value + string(): string } } @@ -20142,7 +20230,7 @@ namespace slog { * ``` * * For more control over the output format, create a logger with a different handler. - * This statement uses [New] to create a new logger with a TextHandler + * This statement uses [New] to create a new logger with a [TextHandler] * that writes structured records in text form to standard error: * * ``` @@ -20348,7 +20436,7 @@ namespace slog { * is the most efficient way to achieve the same output as * * ``` - * slog.Info("hello", "count", 3) + * slog.InfoContext(ctx, "hello", "count", 3) * ``` * * # Customizing a type's logging behavior @@ -20361,7 +20449,7 @@ namespace slog { * * A LogValue method may return a Value that itself implements [LogValuer]. The [Value.Resolve] * method handles these cases carefully, avoiding infinite loops and unbounded recursion. - * Handler authors and others may wish to use Value.Resolve instead of calling LogValue directly. + * Handler authors and others may wish to use [Value.Resolve] instead of calling LogValue directly. * * # Wrapping output methods * @@ -20371,8 +20459,8 @@ namespace slog { * define this function in file mylog.go: * * ``` - * func Infof(format string, args ...any) { - * slog.Default().Info(fmt.Sprintf(format, args...)) + * func Infof(logger *slog.Logger, format string, args ...any) { + * logger.Info(fmt.Sprintf(format, args...)) * } * ``` * @@ -20474,7 +20562,7 @@ namespace slog { // @ts-ignore import loginternal = internal /** - * Kind is the kind of a Value. + * Kind is the kind of a [Value]. */ interface Kind extends Number{} interface Kind { diff --git a/plugins/jsvm/internal/types/types.go b/plugins/jsvm/internal/types/types.go index b50809425..e4f772862 100644 --- a/plugins/jsvm/internal/types/types.go +++ b/plugins/jsvm/internal/types/types.go @@ -96,7 +96,7 @@ declare function routerAdd( * ` + "```" + `js * routerUse((next) => { * return (c) => { - * console.log(c.Path()) + * console.log(c.path()) * return next(c) * } * })