diff --git a/plugins/jsvm/internal/types/generated/types.d.ts b/plugins/jsvm/internal/types/generated/types.d.ts index fb4004c69..baa45f280 100644 --- a/plugins/jsvm/internal/types/generated/types.d.ts +++ b/plugins/jsvm/internal/types/generated/types.d.ts @@ -1483,8 +1483,8 @@ namespace os { */ readFrom(r: io.Reader): number } - type _subNHxsD = io.Writer - interface onlyWriter extends _subNHxsD { + type _subQUdIN = io.Writer + interface onlyWriter extends _subQUdIN { } interface File { /** @@ -2108,8 +2108,8 @@ namespace os { /** * File represents an open file descriptor. */ - type _subGZlhQ = file - interface File extends _subGZlhQ { + type _subHRVqQ = file + interface File extends _subHRVqQ { } /** * A FileInfo describes a file and is returned by Stat and Lstat. @@ -2475,6 +2475,120 @@ namespace filepath { } } +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 + } + // @ts-ignore + import crand = rand + interface encrypt { + /** + * Encrypt encrypts data with key (must be valid 32 char aes key). + */ + (data: string, key: string): string + } + interface decrypt { + /** + * Decrypt decrypts encrypted text with key (must be valid 32 chars aes key). + */ + (cipherText: string, key: string): string + } + interface parseUnverifiedJWT { + /** + * ParseUnverifiedJWT parses JWT token 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 token and returns its claims. + */ + (token: string, verificationKey: string): jwt.MapClaims + } + interface newJWT { + /** + * NewJWT generates and returns new HS256 signed JWT token. + */ + (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 token. + */ + (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. */ @@ -2827,14 +2941,14 @@ namespace dbx { /** * MssqlBuilder is the builder for SQL Server databases. */ - type _subDmNxN = BaseBuilder - interface MssqlBuilder extends _subDmNxN { + type _subixyDT = BaseBuilder + interface MssqlBuilder extends _subixyDT { } /** * MssqlQueryBuilder is the query builder for SQL Server databases. */ - type _subFqKkY = BaseQueryBuilder - interface MssqlQueryBuilder extends _subFqKkY { + type _subanlhz = BaseQueryBuilder + interface MssqlQueryBuilder extends _subanlhz { } interface newMssqlBuilder { /** @@ -2905,8 +3019,8 @@ namespace dbx { /** * MysqlBuilder is the builder for MySQL databases. */ - type _subEbYzY = BaseBuilder - interface MysqlBuilder extends _subEbYzY { + type _subPCLkc = BaseBuilder + interface MysqlBuilder extends _subPCLkc { } interface newMysqlBuilder { /** @@ -2981,14 +3095,14 @@ namespace dbx { /** * OciBuilder is the builder for Oracle databases. */ - type _subyonyV = BaseBuilder - interface OciBuilder extends _subyonyV { + type _subweRjK = BaseBuilder + interface OciBuilder extends _subweRjK { } /** * OciQueryBuilder is the query builder for Oracle databases. */ - type _subCZSnX = BaseQueryBuilder - interface OciQueryBuilder extends _subCZSnX { + type _subRsUtM = BaseQueryBuilder + interface OciQueryBuilder extends _subRsUtM { } interface newOciBuilder { /** @@ -3051,8 +3165,8 @@ namespace dbx { /** * PgsqlBuilder is the builder for PostgreSQL databases. */ - type _subdOuzV = BaseBuilder - interface PgsqlBuilder extends _subdOuzV { + type _subkRFPw = BaseBuilder + interface PgsqlBuilder extends _subkRFPw { } interface newPgsqlBuilder { /** @@ -3119,8 +3233,8 @@ namespace dbx { /** * SqliteBuilder is the builder for SQLite databases. */ - type _subLppjc = BaseBuilder - interface SqliteBuilder extends _subLppjc { + type _subjiAVL = BaseBuilder + interface SqliteBuilder extends _subjiAVL { } interface newSqliteBuilder { /** @@ -3219,8 +3333,8 @@ namespace dbx { /** * StandardBuilder is the builder that is used by DB for an unknown driver. */ - type _subXNBER = BaseBuilder - interface StandardBuilder extends _subXNBER { + type _subfyKzL = BaseBuilder + interface StandardBuilder extends _subfyKzL { } interface newStandardBuilder { /** @@ -3286,8 +3400,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 _subPjHdG = Builder - interface DB extends _subPjHdG { + type _subHwwUD = Builder + interface DB extends _subHwwUD { /** * FieldMapper maps struct fields to DB columns. Defaults to DefaultFieldMapFunc. */ @@ -4085,8 +4199,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 _subSKgcS = sql.Rows - interface Rows extends _subSKgcS { + type _subcHIpi = sql.Rows + interface Rows extends _subcHIpi { } interface Rows { /** @@ -4443,8 +4557,8 @@ namespace dbx { }): string } interface structInfo { } - type _subpbknc = structInfo - interface structValue extends _subpbknc { + type _suboymSV = structInfo + interface structValue extends _suboymSV { } interface fieldInfo { } @@ -4482,8 +4596,8 @@ namespace dbx { /** * Tx enhances sql.Tx with additional querying methods. */ - type _subNyGRi = Builder - interface Tx extends _subNyGRi { + type _subeVXQm = Builder + interface Tx extends _subeVXQm { } interface Tx { /** @@ -4547,120 +4661,6 @@ namespace exec { } } -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 - } - // @ts-ignore - import crand = rand - interface encrypt { - /** - * Encrypt encrypts data with key (must be valid 32 char aes key). - */ - (data: string, key: string): string - } - interface decrypt { - /** - * Decrypt decrypts encrypted text with key (must be valid 32 chars aes key). - */ - (cipherText: string, key: string): string - } - interface parseUnverifiedJWT { - /** - * ParseUnverifiedJWT parses JWT token 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 token and returns its claims. - */ - (token: string, verificationKey: string): jwt.MapClaims - } - interface newJWT { - /** - * NewJWT generates and returns new HS256 signed JWT token. - */ - (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 token. - */ - (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. @@ -4733,8 +4733,8 @@ namespace filesystem { */ open(): io.ReadSeekCloser } - type _subrymRg = bytes.Reader - interface bytesReadSeekCloser extends _subrymRg { + type _subbuUaP = bytes.Reader + interface bytesReadSeekCloser extends _subbuUaP { } interface bytesReadSeekCloser { /** @@ -5162,6 +5162,39 @@ namespace forms { */ submit(...interceptors: InterceptorFunc[]): void } + /** + * BackupUpload is a request form for uploading a new app backup. + */ + interface BackupUpload { + file?: filesystem.File + } + interface newBackupUpload { + /** + * NewBackupUpload creates new BackupUpload request form. + */ + (app: core.App): (BackupUpload | undefined) + } + interface BackupUpload { + /** + * SetContext replaces the default form upload context with the provided one. + */ + setContext(ctx: context.Context): void + } + interface BackupUpload { + /** + * Validate makes the form validatable by implementing [validation.Validatable] interface. + */ + validate(): void + } + interface BackupUpload { + /** + * Submit validates the form and upload the backup file. + * + * You can optionally provide a list of InterceptorFunc to further + * modify the form behavior before uploading the backup. + */ + submit(...interceptors: InterceptorFunc[]): void + } /** * InterceptorNextFunc is a interceptor handler function. * Usually used in combination with InterceptorFunc. @@ -5792,8 +5825,8 @@ namespace forms { /** * SettingsUpsert is a [settings.Settings] upsert (create/update) form. */ - type _subCObHb = settings.Settings - interface SettingsUpsert extends _subCObHb { + type _subshHkJ = settings.Settings + interface SettingsUpsert extends _subshHkJ { } interface newSettingsUpsert { /** @@ -6206,93 +6239,12 @@ namespace apis { } } -/** - * 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 { - /** - * NewRegistry creates and initializes a new blank templates registry. - * - * Use the Registry.Load* methods to load templates into the registry. - */ - (): (Registry | undefined) - } - /** - * 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. - */ - interface 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 | undefined) - } - 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 | undefined) - } - interface Registry { - /** - * LoadString 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(fs: fs.FS, ...globPatterns: string[]): (Renderer | undefined) - } - /** - * 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 - } -} - namespace pocketbase { /** * appWrapper serves as a private core.App instance wrapper. */ - type _subMVLNB = core.App - interface appWrapper extends _subMVLNB { + type _subEzPvN = core.App + interface appWrapper extends _subEzPvN { } /** * PocketBase defines a PocketBase app launcher. @@ -6300,8 +6252,8 @@ namespace pocketbase { * It implements [core.App] via embedding and all of the app interface methods * could be accessed directly through the instance (eg. PocketBase.DataDir()). */ - type _subSHfve = appWrapper - interface PocketBase extends _subSHfve { + type _subMjNuF = appWrapper + interface PocketBase extends _subMjNuF { /** * RootCmd is the main console command */ @@ -6373,6 +6325,87 @@ namespace pocketbase { } } +/** + * 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 { + /** + * NewRegistry creates and initializes a new blank templates registry. + * + * Use the Registry.Load* methods to load templates into the registry. + */ + (): (Registry | undefined) + } + /** + * 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. + */ + interface 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 | undefined) + } + 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 | undefined) + } + interface Registry { + /** + * LoadString 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(fs: fs.FS, ...globPatterns: string[]): (Renderer | undefined) + } + /** + * 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 syscall contains an interface to the low-level operating system * primitives. The details vary depending on the underlying system, and @@ -7258,92 +7291,6 @@ namespace io { } } -/** - * Package bytes implements functions for the manipulation of byte slices. - * It is analogous to the facilities of the strings package. - */ -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. - * The zero value for Reader operates like a Reader of an empty slice. - */ - interface Reader { - } - interface Reader { - /** - * Len returns the number of bytes of the unread portion of the - * slice. - */ - len(): number - } - interface Reader { - /** - * Size returns the original length of the underlying byte slice. - * Size is the number of bytes available for reading via ReadAt. - * The returned value is always the same and is not affected by calls - * to any other method. - */ - size(): number - } - interface Reader { - /** - * Read implements the io.Reader interface. - */ - read(b: string): number - } - interface Reader { - /** - * ReadAt implements the io.ReaderAt interface. - */ - readAt(b: string, off: number): number - } - interface Reader { - /** - * ReadByte implements the io.ByteReader interface. - */ - readByte(): string - } - interface Reader { - /** - * UnreadByte complements ReadByte in implementing the io.ByteScanner interface. - */ - unreadByte(): void - } - interface Reader { - /** - * ReadRune implements the io.RuneReader interface. - */ - readRune(): [string, number] - } - interface Reader { - /** - * UnreadRune complements ReadRune in implementing the io.RuneScanner interface. - */ - unreadRune(): void - } - interface Reader { - /** - * Seek implements the io.Seeker interface. - */ - seek(offset: number, whence: number): number - } - interface Reader { - /** - * WriteTo implements the io.WriterTo interface. - */ - writeTo(w: io.Writer): number - } - interface Reader { - /** - * Reset resets the Reader to be reading from b. - */ - reset(b: string): void - } -} - /** * Package fs defines basic interfaces to a file system. * A file system can be provided by the host operating system @@ -7532,3477 +7479,3563 @@ namespace fs { } /** - * Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html + * Package sql provides a generic interface around SQL (or SQL-like) + * databases. * - * See README.md for more info. + * 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 jwt { +namespace sql { /** - * 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 + * TxOptions holds the transaction options to be used in DB.BeginTx. */ - 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 { - /** - * VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). - * If req is false, it will return true, if exp is unset. - */ - verifyExpiresAt(cmp: number, req: boolean): boolean - } - interface MapClaims { - /** - * VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). - * If req is false, it will return true, if iat is unset. - */ - verifyIssuedAt(cmp: number, req: boolean): boolean - } - interface MapClaims { - /** - * VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). - * If req is false, it will return true, if nbf is unset. - */ - verifyNotBefore(cmp: number, req: boolean): boolean - } - interface MapClaims { - /** - * VerifyIssuer compares the iss claim against cmp. - * If required is false, this method will return true if the value matches or is unset - */ - verifyIssuer(cmp: string, req: boolean): boolean - } - interface MapClaims { + interface TxOptions { /** - * 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. + * Isolation is the transaction isolation level. + * If zero, the driver or database's default level is used. */ - valid(): void + isolation: IsolationLevel + readOnly: boolean } -} - -/** - * 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. - */ -namespace multipart { /** - * A FileHeader describes a file part of a multipart request. + * 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 FileHeader { - filename: string - header: textproto.MIMEHeader - size: number + interface DB { } - interface FileHeader { + interface DB { /** - * Open opens and returns the FileHeader's associated File. + * PingContext verifies a connection to the database is still alive, + * establishing a connection if necessary. */ - open(): File + pingContext(ctx: context.Context): 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 client 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) - * // ... - * ``` - * - * 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. - * - * 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()) - * ``` - * - * 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 environment variables 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 - * ``` - * - * The GODEBUG variables are not covered by Go's API compatibility - * promise. 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 { - /** - * Method specifies the HTTP method (GET, POST, PUT, etc.). - * For client requests, an empty string means GET. - * - * Go's HTTP client does not support sending a request with - * the CONNECT method. See the documentation on Transport for - * details. - */ - method: string - /** - * 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) - * - * 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. - */ - url?: url.URL - /** - * 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. - */ - proto: string // "HTTP/1.0" - protoMajor: number // 1 - protoMinor: number // 0 - /** - * 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. - * - * 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. - */ - header: Header - /** - * 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. - */ - body: io.ReadCloser - /** - * 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. - * - * For server requests, it is unused. - */ - getBody: () => io.ReadCloser - /** - * 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. - */ - contentLength: number - /** - * 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. - */ - transferEncoding: Array - /** - * 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. - */ - close: boolean - /** - * 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. - */ - host: string - /** - * 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. - * - * 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 + interface DB { /** - * Trailer specifies additional headers that are sent after the request - * body. - * - * 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. - * - * 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. + * Ping verifies a connection to the database is still alive, + * establishing a connection if necessary. * - * 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. + * Ping uses context.Background internally; to specify the context, use + * PingContext. */ - tls?: any + ping(): void + } + interface DB { /** - * 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. - * - * For server requests, this field is not applicable. + * 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. * - * 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. + * It is rare to Close a DB, as the DB handle is meant to be + * long-lived and shared between many goroutines. */ - response?: Response + close(): void } - interface Request { + interface DB { /** - * Context returns the request's context. To change the context, use - * WithContext. + * SetMaxIdleConns sets the maximum number of connections in the idle + * connection pool. * - * The returned context is always non-nil; it defaults to the - * background context. + * If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, + * then the new MaxIdleConns will be reduced to match the MaxOpenConns limit. * - * For outgoing client requests, the context controls cancellation. + * If n <= 0, no idle connections are retained. * - * 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. + * The default max idle connections is currently 2. This may change in + * a future release. */ - context(): context.Context + setMaxIdleConns(n: number): void } - interface Request { + interface DB { /** - * WithContext returns a shallow copy of r with its context changed - * to ctx. The provided ctx must be non-nil. + * SetMaxOpenConns sets the maximum number of open connections to the database. * - * 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 MaxIdleConns is greater than 0 and the new MaxOpenConns is less than + * MaxIdleConns, then MaxIdleConns will be reduced to match the new + * MaxOpenConns limit. * - * To create a new request with a context, use NewRequestWithContext. - * To change the context of a request, such as an incoming request you - * want to modify before sending back out, use Request.Clone. Between - * those two uses, it's rare to need WithContext. + * If n <= 0, then there is no limit on the number of open connections. + * The default is 0 (unlimited). */ - withContext(ctx: context.Context): (Request | undefined) + setMaxOpenConns(n: number): void } - interface Request { + interface DB { /** - * Clone returns a deep copy of r with its context changed to ctx. - * The provided ctx must be non-nil. + * SetConnMaxLifetime sets the maximum amount of time a connection may be reused. * - * 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. + * Expired connections may be closed lazily before reuse. + * + * If d <= 0, connections are not closed due to a connection's age. */ - clone(ctx: context.Context): (Request | undefined) + setConnMaxLifetime(d: time.Duration): void } - interface Request { + interface DB { /** - * ProtoAtLeast reports whether the HTTP protocol used - * in the request is at least major.minor. + * SetConnMaxIdleTime sets the maximum amount of time a connection may be idle. + * + * Expired connections may be closed lazily before reuse. + * + * If d <= 0, connections are not closed due to a connection's idle time. */ - protoAtLeast(major: number): boolean + setConnMaxIdleTime(d: time.Duration): void } - interface Request { + interface DB { /** - * UserAgent returns the client's User-Agent, if sent in the request. + * Stats returns database statistics. */ - userAgent(): string + stats(): DBStats } - interface Request { + interface DB { /** - * Cookies parses and returns the HTTP cookies sent with the request. + * 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. */ - cookies(): Array<(Cookie | undefined)> + prepareContext(ctx: context.Context, query: string): (Stmt | undefined) } - interface Request { + interface DB { /** - * 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. + * 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. */ - cookie(name: string): (Cookie | undefined) + prepare(query: string): (Stmt | undefined) } - interface Request { + interface DB { /** - * 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. + * ExecContext executes a query without returning any rows. + * The args are for any placeholder parameters in the query. */ - addCookie(c: Cookie): void + execContext(ctx: context.Context, query: string, ...args: any[]): Result } - interface Request { + interface DB { /** - * Referer returns the referring URL, if sent in the request. + * Exec executes a query without returning any rows. + * The args are for any placeholder parameters in the query. * - * 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"]. + * Exec uses context.Background internally; to specify the context, use + * ExecContext. */ - referer(): string + exec(query: string, ...args: any[]): Result } - interface Request { + interface DB { /** - * 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. + * QueryContext executes a query that returns rows, typically a SELECT. + * The args are for any placeholder parameters in the query. */ - multipartReader(): (multipart.Reader | undefined) + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) } - interface Request { + interface DB { /** - * 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: - * ``` - * Host - * URL - * Method (defaults to "GET") - * Header - * ContentLength - * TransferEncoding - * Body - * ``` + * Query executes a query that returns rows, typically a SELECT. + * The args are for any placeholder parameters in the query. * - * 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. - */ - write(w: io.Writer): void - } - interface Request { - /** - * 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. + * Query uses context.Background internally; to specify the context, use + * QueryContext. */ - writeProxy(w: io.Writer): void + query(query: string, ...args: any[]): (Rows | undefined) } - interface Request { + interface DB { /** - * 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. + * 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. */ - basicAuth(): [string, boolean] + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) } - interface Request { + interface DB { /** - * 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. + * 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. * - * 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. + * QueryRow uses context.Background internally; to specify the context, use + * QueryRowContext. */ - setBasicAuth(username: string): void + queryRow(query: string, ...args: any[]): (Row | undefined) } - interface Request { + interface DB { /** - * 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. + * BeginTx starts a transaction. * - * 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. + * 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. * - * ParseMultipartForm calls ParseForm automatically. - * ParseForm is idempotent. - */ - parseForm(): void - } - 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. + * 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. */ - parseMultipartForm(maxMemory: number): void + beginTx(ctx: context.Context, opts: TxOptions): (Tx | undefined) } - interface Request { + interface DB { /** - * 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. + * Begin starts a transaction. The default isolation level is dependent on + * the driver. + * + * Begin uses context.Background internally; to specify the context, use + * BeginTx. */ - formValue(key: string): string + begin(): (Tx | undefined) } - interface Request { + interface DB { /** - * 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. + * Driver returns the database's underlying driver. */ - postFormValue(key: string): string + driver(): any } - interface Request { + interface DB { /** - * FormFile returns the first file for the provided form key. - * FormFile calls ParseMultipartForm and ParseForm if necessary. + * 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. */ - formFile(key: string): [multipart.File, (multipart.FileHeader | undefined)] + conn(ctx: context.Context): (Conn | undefined) } /** - * A ResponseWriter interface is used by an HTTP handler to - * construct an HTTP response. + * Tx is an in-progress database transaction. * - * A ResponseWriter may not be used after the Handler.ServeHTTP method - * has returned. + * 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. */ - interface ResponseWriter { + interface Tx { + } + interface Tx { /** - * 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. + * 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. * - * Changing the header map after a call to WriteHeader (or - * Write) has no effect unless the modified headers are - * trailers. + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. * - * 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. + * To use an existing prepared statement on this transaction, see Tx.Stmt. * - * To suppress automatic response headers (such as "Date"), set - * their value to nil. + * 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. */ - header(): Header + prepareContext(ctx: context.Context, query: string): (Stmt | undefined) + } + interface Tx { /** - * Write writes the data to the connection as part of an HTTP reply. + * Prepare creates a prepared statement for use within a transaction. * - * 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. + * The returned statement operates within the transaction and will be closed + * when the transaction has been committed or rolled back. * - * 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. + * To use an existing prepared statement on this transaction, see Tx.Stmt. + * + * Prepare uses context.Background internally; to specify the context, use + * PrepareContext. */ - write(_arg0: string): number + prepare(query: string): (Stmt | undefined) + } + interface Tx { /** - * WriteHeader sends an HTTP response header with the provided - * status code. + * StmtContext returns a transaction-specific prepared statement from + * an existing statement. * - * 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. + * 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 code must be a valid HTTP 1xx-5xx status code. - * Only one header may be written. Go does not currently - * support sending user-defined 1xx informational headers, - * with the exception of 100-continue response header that the - * Server sends automatically when the Request.Body is read. + * 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. */ - writeHeader(statusCode: number): void + stmtContext(ctx: context.Context, stmt: Stmt): (Stmt | undefined) } - /** - * A Server defines parameters for running an HTTP server. - * The zero value for Server is a valid configuration. - */ - interface Server { + interface Tx { /** - * 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. + * 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. */ - addr: string - handler: Handler // handler to invoke, http.DefaultServeMux if nil + stmt(stmt: Stmt): (Stmt | undefined) + } + interface Tx { /** - * 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. + * ExecContext executes a query that doesn't return rows. + * For example: an INSERT and UPDATE. */ - tlsConfig?: any + execContext(ctx: context.Context, query: string, ...args: any[]): Result + } + interface Tx { /** - * ReadTimeout is the maximum duration for reading the entire - * request, including the body. A zero or negative value means - * there will be no timeout. + * Exec executes a query that doesn't return rows. + * For example: an INSERT and UPDATE. * - * 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. + * Exec uses context.Background internally; to specify the context, use + * ExecContext. */ - readTimeout: time.Duration + exec(query: string, ...args: any[]): Result + } + interface Tx { /** - * 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. + * QueryContext executes a query that returns rows, typically a SELECT. */ - readHeaderTimeout: time.Duration + queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) + } + interface Tx { /** - * 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. + * Query executes a query that returns rows, typically a SELECT. + * + * Query uses context.Background internally; to specify the context, use + * QueryContext. */ - writeTimeout: time.Duration + query(query: string, ...args: any[]): (Rows | undefined) + } + interface Tx { /** - * 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. + * 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. */ - idleTimeout: time.Duration + queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) + } + interface Tx { /** - * 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. + * 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. */ - maxHeaderBytes: number + queryRow(query: string, ...args: any[]): (Row | undefined) + } + /** + * 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 { /** - * 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. + * ExecContext executes a prepared statement with the given arguments and + * returns a Result summarizing the effect of the statement. */ - tlsNextProto: _TygojaDict + execContext(ctx: context.Context, ...args: any[]): Result + } + interface Stmt { /** - * ConnState specifies an optional callback function that is - * called when a client connection changes state. See the - * ConnState type and associated constants for details. + * 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. */ - connState: (_arg0: net.Conn, _arg1: ConnState) => void + exec(...args: any[]): Result + } + interface Stmt { /** - * 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. + * QueryContext executes a prepared query statement with the given arguments + * and returns the query results as a *Rows. */ - errorLog?: any + queryContext(ctx: context.Context, ...args: any[]): (Rows | undefined) + } + interface Stmt { /** - * 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. + * Query executes a prepared query statement with the given arguments + * and returns the query results as a *Rows. + * + * Query uses context.Background internally; to specify the context, use + * QueryContext. */ - baseContext: (_arg0: net.Listener) => context.Context + query(...args: any[]): (Rows | undefined) + } + interface Stmt { /** - * 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. + * 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. */ - connContext: (ctx: context.Context, c: net.Conn) => context.Context + queryRowContext(ctx: context.Context, ...args: any[]): (Row | undefined) } - interface Server { + interface Stmt { /** - * Close immediately closes all active net.Listeners and any - * connections in state StateNew, StateActive, or StateIdle. For a - * graceful shutdown, use Shutdown. + * 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. * - * Close does not attempt to close (and does not even know about) - * any hijacked connections, such as WebSockets. + * Example usage: * - * Close returns any error returned from closing the Server's - * underlying Listener(s). + * var name string + * err := nameByUseridStmt.QueryRow(id).Scan(&name) + * + * QueryRow uses context.Background internally; to specify the context, use + * QueryRowContext. + */ + queryRow(...args: any[]): (Row | undefined) + } + interface Stmt { + /** + * Close closes the statement. */ close(): void } - interface Server { + /** + * 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 { /** - * 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. + * 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. * - * 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. + * Every call to Scan, even the first one, must be preceded by a call to Next. + */ + next(): boolean + } + interface Rows { + /** + * 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. * - * Once Shutdown has been called on a server, it may not be reused; - * future calls to methods such as Serve will return ErrServerClosed. + * 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. */ - shutdown(ctx: context.Context): void + nextResultSet(): boolean } - interface Server { + interface Rows { /** - * 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. + * Err returns the error, if any, that was encountered during iteration. + * Err may be called after an explicit or implicit Close. */ - registerOnShutdown(f: () => void): void + err(): void } - interface Server { + interface Rows { /** - * 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 Shutdown or Close, - * the returned error is ErrServerClosed. + * Columns returns the column names. + * Columns returns an error if the rows are closed. */ - listenAndServe(): void + columns(): Array } - interface Server { + interface Rows { /** - * 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 Shutdown or Close, the returned error is ErrServerClosed. + * ColumnTypes returns column information such as column type, length, + * and nullable. Some information may not be available from some drivers. */ - serve(l: net.Listener): void + columnTypes(): Array<(ColumnType | undefined)> } - interface Server { + interface Rows { /** - * 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. + * 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. * - * 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. + * Scan converts columns read from the database into the following + * common Go types and special types provided by the sql package: * - * ServeTLS always returns a non-nil error. After Shutdown or Close, the - * returned error is ErrServerClosed. + * ``` + * *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) + * ``` + * + * 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. + * + * 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. + * + * 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 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. + * + * 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. + * + * Source values of type bool may be scanned into types *bool, + * *interface{}, *string, *[]byte, or *RawBytes. + * + * 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 */ - serveTLS(l: net.Listener, certFile: string): void + scan(...dest: any[]): void } - interface Server { + interface Rows { /** - * 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. + * 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. */ - setKeepAlivesEnabled(v: boolean): void + close(): void } - interface Server { + /** + * A Result summarizes an executed SQL command. + */ + interface Result { /** - * 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. + * 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. */ - listenAndServeTLS(certFile: string): void + lastInsertId(): number + /** + * RowsAffected returns the number of rows affected by an + * update, insert, or delete. Not every database or database + * driver may support this. + */ + rowsAffected(): number } } -namespace auth { +/** + * Package bytes implements functions for the manipulation of byte slices. + * It is analogous to the facilities of the strings package. + */ +namespace bytes { /** - * AuthUser defines a standardized oauth2 user data structure. + * 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. + * The zero value for Reader operates like a Reader of an empty slice. */ - interface AuthUser { - id: string - name: string - username: string - email: string - avatarUrl: string - rawUser: _TygojaDict - accessToken: string - refreshToken: string + interface Reader { } - /** - * Provider defines a common interface for an OAuth2 client. - */ - interface Provider { + interface Reader { /** - * Scopes returns the context associated with the provider (if any). + * Len returns the number of bytes of the unread portion of the + * slice. */ - context(): context.Context + len(): number + } + interface Reader { /** - * SetContext assigns the specified context to the current provider. + * Size returns the original length of the underlying byte slice. + * Size is the number of bytes available for reading via ReadAt. + * The returned value is always the same and is not affected by calls + * to any other method. */ - setContext(ctx: context.Context): void + size(): number + } + interface Reader { /** - * Scopes returns the provider access permissions that will be requested. + * Read implements the io.Reader interface. */ - scopes(): Array + read(b: string): number + } + interface Reader { /** - * SetScopes sets the provider access permissions that will be requested later. + * ReadAt implements the io.ReaderAt interface. */ - setScopes(scopes: Array): void + readAt(b: string, off: number): number + } + interface Reader { /** - * ClientId returns the provider client's app ID. + * ReadByte implements the io.ByteReader interface. */ - clientId(): string + readByte(): string + } + interface Reader { /** - * SetClientId sets the provider client's ID. + * UnreadByte complements ReadByte in implementing the io.ByteScanner interface. */ - setClientId(clientId: string): void + unreadByte(): void + } + interface Reader { /** - * ClientSecret returns the provider client's app secret. + * ReadRune implements the io.RuneReader interface. */ - clientSecret(): string + readRune(): [string, number] + } + interface Reader { /** - * SetClientSecret sets the provider client's app secret. + * UnreadRune complements ReadRune in implementing the io.RuneScanner interface. */ - setClientSecret(secret: string): void + unreadRune(): void + } + interface Reader { /** - * RedirectUrl returns the end address to redirect the user - * going through the OAuth flow. + * Seek implements the io.Seeker interface. */ - redirectUrl(): string + seek(offset: number, whence: number): number + } + interface Reader { /** - * SetRedirectUrl sets the provider's RedirectUrl. + * WriteTo implements the io.WriterTo interface. */ - setRedirectUrl(url: string): void + writeTo(w: io.Writer): number + } + interface Reader { /** - * AuthUrl returns the provider's authorization service url. + * Reset resets the Reader to be reading from b. */ - authUrl(): string + reset(b: string): 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. + */ +namespace multipart { + /** + * A FileHeader describes a file part of a multipart request. + */ + interface FileHeader { + filename: string + header: textproto.MIMEHeader + size: number + } + interface FileHeader { /** - * SetAuthUrl sets the provider's AuthUrl. + * Open opens and returns the FileHeader's associated File. */ - setAuthUrl(url: string): void + open(): File + } +} + +/** + * 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 client 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) + * // ... + * ``` + * + * 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. + * + * 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()) + * ``` + * + * 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 environment variables 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 + * ``` + * + * The GODEBUG variables are not covered by Go's API compatibility + * promise. 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 { /** - * TokenUrl returns the provider's token exchange service url. + * Method specifies the HTTP method (GET, POST, PUT, etc.). + * For client requests, an empty string means GET. + * + * Go's HTTP client does not support sending a request with + * the CONNECT method. See the documentation on Transport for + * details. */ - tokenUrl(): string + method: string /** - * SetTokenUrl sets the provider's TokenUrl. + * 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) + * + * 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. */ - setTokenUrl(url: string): void + url?: url.URL /** - * UserApiUrl returns the provider's user info api url. + * 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. */ - userApiUrl(): string + proto: string // "HTTP/1.0" + protoMajor: number // 1 + protoMinor: number // 0 /** - * SetUserApiUrl sets the provider's UserApiUrl. + * 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. + * + * 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. */ - setUserApiUrl(url: string): void + header: Header /** - * Client returns an http client using the provided token. + * 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. */ - client(token: oauth2.Token): (any | undefined) + body: io.ReadCloser /** - * BuildAuthUrl returns a URL to the provider's consent page - * that asks for permissions for the required scopes explicitly. + * 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. + * + * For server requests, it is unused. */ - buildAuthUrl(state: string, ...opts: oauth2.AuthCodeOption[]): string + getBody: () => io.ReadCloser /** - * FetchToken converts an authorization code to token. + * 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. */ - fetchToken(code: string, ...opts: oauth2.AuthCodeOption[]): (oauth2.Token | undefined) + contentLength: number /** - * FetchRawUserData requests and marshalizes into `result` the - * the OAuth user api response. + * 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. */ - fetchRawUserData(token: oauth2.Token): string + transferEncoding: Array /** - * FetchAuthUser is similar to FetchRawUserData, but normalizes and - * marshalizes the user api response into a standardized AuthUser struct. + * 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. */ - fetchAuthUser(token: oauth2.Token): (AuthUser | undefined) - } -} - -/** - * 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 { + close: boolean /** - * Isolation is the transaction isolation level. - * If zero, the driver or database's default level is used. + * 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. */ - 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 { + host: string /** - * PingContext verifies a connection to the database is still alive, - * establishing a connection if necessary. + * 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. */ - pingContext(ctx: context.Context): void - } - interface DB { + form: url.Values /** - * Ping verifies a connection to the database is still alive, - * establishing a connection if necessary. + * PostForm contains the parsed form data from PATCH, POST + * or PUT body parameters. * - * Ping uses context.Background internally; to specify the context, use - * PingContext. + * This field is only available after ParseForm is called. + * The HTTP client ignores PostForm and uses Body instead. */ - ping(): void - } - interface DB { + postForm: url.Values /** - * 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. + * 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. */ - close(): void - } - interface DB { + multipartForm?: multipart.Form /** - * SetMaxIdleConns sets the maximum number of connections in the idle - * connection pool. + * Trailer specifies additional headers that are sent after the request + * body. * - * If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, - * then the new MaxIdleConns will be reduced to match the MaxOpenConns limit. + * 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. * - * If n <= 0, no idle connections are retained. + * 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. * - * The default max idle connections is currently 2. This may change in - * a future release. + * Few HTTP clients, servers, or proxies support HTTP trailers. */ - setMaxIdleConns(n: number): void - } - interface DB { + trailer: Header /** - * SetMaxOpenConns sets the maximum number of open connections to the database. - * - * 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 n <= 0, then there is no limit on the number of open connections. - * The default is 0 (unlimited). + * 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. */ - setMaxOpenConns(n: number): void - } - interface DB { + remoteAddr: string /** - * SetConnMaxLifetime sets the maximum amount of time a connection may be reused. - * - * Expired connections may be closed lazily before reuse. - * - * If d <= 0, connections are not closed due to a connection's age. + * 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. */ - setConnMaxLifetime(d: time.Duration): void - } - interface DB { + requestURI: string /** - * SetConnMaxIdleTime sets the maximum amount of time a connection may be idle. + * 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. * - * Expired connections may be closed lazily before reuse. + * For server requests, this field is not applicable. * - * If d <= 0, connections are not closed due to a connection's idle time. + * 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. */ - setConnMaxIdleTime(d: time.Duration): void - } - interface DB { + cancel: undefined /** - * Stats returns database statistics. + * Response is the redirect response which caused this request + * to be created. This field is only populated during client + * redirects. */ - stats(): DBStats + response?: Response } - interface DB { + interface Request { /** - * 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. + * Context returns the request's context. To change the context, use + * WithContext. * - * The provided context is used for the preparation of the statement, not for the - * execution of the statement. - */ - prepareContext(ctx: context.Context, query: string): (Stmt | undefined) - } - interface DB { - /** - * 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. + * The returned context is always non-nil; it defaults to the + * background context. * - * Prepare uses context.Background internally; to specify the context, use - * PrepareContext. + * For outgoing client requests, the context controls cancellation. + * + * 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. */ - prepare(query: string): (Stmt | undefined) + context(): context.Context } - interface DB { + interface Request { /** - * ExecContext executes a query without returning any rows. - * The args are for any placeholder parameters in the query. + * 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 change the context of a request, such as an incoming request you + * want to modify before sending back out, use Request.Clone. Between + * those two uses, it's rare to need WithContext. */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result + withContext(ctx: context.Context): (Request | undefined) } - interface DB { + interface Request { /** - * Exec executes a query without returning any rows. - * The args are for any placeholder parameters in the query. + * Clone returns a deep copy of r with its context changed to ctx. + * The provided ctx must be non-nil. * - * Exec uses context.Background internally; to specify the context, use - * ExecContext. + * 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. */ - exec(query: string, ...args: any[]): Result + clone(ctx: context.Context): (Request | undefined) } - interface DB { + interface Request { /** - * QueryContext executes a query that returns rows, typically a SELECT. - * The args are for any placeholder parameters in the query. + * ProtoAtLeast reports whether the HTTP protocol used + * in the request is at least major.minor. */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) + protoAtLeast(major: number): boolean } - interface DB { + interface Request { /** - * 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. + * UserAgent returns the client's User-Agent, if sent in the request. */ - query(query: string, ...args: any[]): (Rows | undefined) + userAgent(): string } - interface DB { + interface Request { /** - * 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. + * Cookies parses and returns the HTTP cookies sent with the request. */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) + cookies(): Array<(Cookie | undefined)> } - interface DB { + interface 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'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. + * 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. */ - queryRow(query: string, ...args: any[]): (Row | undefined) + cookie(name: string): (Cookie | undefined) } - interface DB { + interface Request { /** - * 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. + * 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. */ - beginTx(ctx: context.Context, opts: TxOptions): (Tx | undefined) + addCookie(c: Cookie): void } - interface DB { + interface Request { /** - * Begin starts a transaction. The default isolation level is dependent on - * the driver. + * Referer returns the referring URL, if sent in the request. * - * Begin uses context.Background internally; to specify the context, use - * BeginTx. + * 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"]. */ - begin(): (Tx | undefined) + referer(): string } - interface DB { + interface Request { /** - * Driver returns the database's underlying driver. + * 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. */ - driver(): any + multipartReader(): (multipart.Reader | undefined) } - interface DB { + interface Request { /** - * 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. + * 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: + * ``` + * Host + * URL + * Method (defaults to "GET") + * Header + * ContentLength + * TransferEncoding + * Body + * ``` * - * Every Conn must be returned to the database pool after use by - * calling Conn.Close. + * 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. */ - conn(ctx: context.Context): (Conn | undefined) - } - /** - * 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. - */ - interface Tx { + write(w: io.Writer): void } - interface Tx { + interface Request { /** - * Commit commits the transaction. + * 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. */ - commit(): void + writeProxy(w: io.Writer): void } - interface Tx { + interface Request { /** - * Rollback aborts the transaction. + * 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. */ - rollback(): void + basicAuth(): [string, boolean] } - interface Tx { + interface Request { /** - * 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. + * SetBasicAuth sets the request's Authorization header to use HTTP + * Basic Authentication with the provided username and password. * - * To use an existing prepared statement on this transaction, see Tx.Stmt. + * With HTTP Basic Authentication the provided username and password + * are not encrypted. * - * 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. + * 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. */ - prepareContext(ctx: context.Context, query: string): (Stmt | undefined) + setBasicAuth(username: string): void } - interface Tx { + interface Request { /** - * 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. + * ParseForm populates r.Form and r.PostForm. * - * To use an existing prepared statement on this transaction, see Tx.Stmt. + * For all requests, ParseForm parses the raw query from the URL and updates + * r.Form. * - * Prepare uses context.Background internally; to specify the context, use - * PrepareContext. - */ - prepare(query: string): (Stmt | undefined) - } - interface Tx { - /** - * StmtContext returns a transaction-specific prepared statement from - * an existing statement. + * 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. * - * 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) + * If the request Body's size has not already been limited by MaxBytesReader, + * the size is capped at 10MB. * - * The provided context is used for the preparation of the statement, not for the - * execution of the statement. + * 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. * - * The returned statement operates within the transaction and will be closed - * when the transaction has been committed or rolled back. + * ParseMultipartForm calls ParseForm automatically. + * ParseForm is idempotent. */ - stmtContext(ctx: context.Context, stmt: Stmt): (Stmt | undefined) + parseForm(): void } - interface Tx { + interface Request { /** - * 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. + * 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. */ - stmt(stmt: Stmt): (Stmt | undefined) + parseMultipartForm(maxMemory: number): void } - interface Tx { + interface Request { /** - * ExecContext executes a query that doesn't return rows. - * For example: an INSERT and UPDATE. + * 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. */ - execContext(ctx: context.Context, query: string, ...args: any[]): Result + formValue(key: string): string } - interface Tx { + interface Request { /** - * Exec executes a query that doesn't return rows. - * For example: an INSERT and UPDATE. - * - * Exec uses context.Background internally; to specify the context, use - * ExecContext. + * 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. */ - exec(query: string, ...args: any[]): Result + postFormValue(key: string): string } - interface Tx { + interface Request { /** - * QueryContext executes a query that returns rows, typically a SELECT. + * FormFile returns the first file for the provided form key. + * FormFile calls ParseMultipartForm and ParseForm if necessary. */ - queryContext(ctx: context.Context, query: string, ...args: any[]): (Rows | undefined) + formFile(key: string): [multipart.File, (multipart.FileHeader | undefined)] } - interface Tx { + /** + * 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 { /** - * Query executes a query that returns rows, typically a SELECT. + * 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. * - * Query uses context.Background internally; to specify the context, use - * QueryContext. + * Changing the header map after a call to WriteHeader (or + * Write) has no effect unless the modified headers are + * trailers. + * + * 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. + * + * To suppress automatic response headers (such as "Date"), set + * their value to nil. */ - query(query: string, ...args: any[]): (Rows | undefined) - } - interface Tx { + header(): Header /** - * 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. + * Write writes the data to the connection as part of an HTTP reply. + * + * 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. + * + * 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. */ - queryRowContext(ctx: context.Context, query: string, ...args: any[]): (Row | undefined) - } - interface Tx { + write(_arg0: string): number /** - * 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. + * WriteHeader sends an HTTP response header with the provided + * status code. + * + * 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. * - * QueryRow uses context.Background internally; to specify the context, use - * QueryRowContext. + * The provided code must be a valid HTTP 1xx-5xx status code. + * Only one header may be written. Go does not currently + * support sending user-defined 1xx informational headers, + * with the exception of 100-continue response header that the + * Server sends automatically when the Request.Body is read. */ - queryRow(query: string, ...args: any[]): (Row | undefined) + writeHeader(statusCode: number): void } /** - * 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 Server defines parameters for running an HTTP server. + * The zero value for Server is a valid configuration. */ - interface Stmt { - } - interface Stmt { + interface Server { /** - * ExecContext executes a prepared statement with the given arguments and - * returns a Result summarizing the effect of the statement. + * 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. */ - execContext(ctx: context.Context, ...args: any[]): Result - } - interface Stmt { + addr: string + handler: Handler // handler to invoke, http.DefaultServeMux if nil /** - * 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. + * 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. */ - exec(...args: any[]): Result - } - interface Stmt { + tlsConfig?: any /** - * QueryContext executes a prepared query statement with the given arguments - * and returns the query results as a *Rows. + * ReadTimeout is the maximum duration for reading the entire + * request, including the body. A zero or negative value means + * there will be no timeout. + * + * 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. */ - queryContext(ctx: context.Context, ...args: any[]): (Rows | undefined) - } - interface Stmt { + readTimeout: time.Duration /** - * Query executes a prepared query statement with the given arguments - * and returns the query results as a *Rows. - * - * Query uses context.Background internally; to specify the context, use - * QueryContext. + * 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. */ - query(...args: any[]): (Rows | undefined) - } - interface Stmt { + readHeaderTimeout: time.Duration /** - * 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. + * 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. */ - queryRowContext(ctx: context.Context, ...args: any[]): (Row | undefined) - } - interface Stmt { + writeTimeout: time.Duration /** - * 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. - * - * Example usage: - * - * var name string - * err := nameByUseridStmt.QueryRow(id).Scan(&name) - * - * QueryRow uses context.Background internally; to specify the context, use - * QueryRowContext. + * 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. */ - queryRow(...args: any[]): (Row | undefined) - } - interface Stmt { + idleTimeout: time.Duration /** - * Close closes the statement. + * 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. */ - 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 { + maxHeaderBytes: number /** - * 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. - * - * Every call to Scan, even the first one, must be preceded by a call to Next. + * 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. */ - next(): boolean - } - interface Rows { + tlsNextProto: _TygojaDict /** - * 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. - * - * 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. + * ConnState specifies an optional callback function that is + * called when a client connection changes state. See the + * ConnState type and associated constants for details. */ - nextResultSet(): boolean - } - interface Rows { + connState: (_arg0: net.Conn, _arg1: ConnState) => void /** - * Err returns the error, if any, that was encountered during iteration. - * Err may be called after an explicit or implicit Close. + * 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. */ - err(): void - } - interface Rows { + errorLog?: any /** - * Columns returns the column names. - * Columns returns an error if the rows are closed. + * 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. */ - columns(): Array - } - interface Rows { + baseContext: (_arg0: net.Listener) => context.Context /** - * ColumnTypes returns column information such as column type, length, - * and nullable. Some information may not be available from some drivers. + * 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. */ - columnTypes(): Array<(ColumnType | undefined)> + connContext: (ctx: context.Context, c: net.Conn) => context.Context } - interface Rows { + interface Server { /** - * 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. - * - * Scan converts columns read from the database into the following - * common Go types and special types provided by the sql package: - * - * ``` - * *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) - * ``` - * - * 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. + * Close immediately closes all active net.Listeners and any + * connections in state StateNew, StateActive, or StateIdle. For a + * graceful shutdown, use Shutdown. * - * 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. + * Close does not attempt to close (and does not even know about) + * any hijacked connections, such as WebSockets. * - * 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. + * Close returns any error returned from closing the Server's + * underlying Listener(s). + */ + close(): void + } + interface Server { + /** + * 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). * - * 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. + * 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. * - * 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. + * 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. * - * Source values of type bool may be scanned into types *bool, - * *interface{}, *string, *[]byte, or *RawBytes. + * Once Shutdown has been called on a server, it may not be reused; + * future calls to methods such as Serve will return ErrServerClosed. + */ + shutdown(ctx: context.Context): void + } + interface Server { + /** + * 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. + */ + registerOnShutdown(f: () => void): void + } + interface Server { + /** + * 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. * - * For scanning into *bool, the source may be true, false, 1, 0, or - * string inputs parseable by strconv.ParseBool. + * If srv.Addr is blank, ":http" is used. * - * 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. + * ListenAndServe always returns a non-nil error. After Shutdown or Close, + * the returned error is ErrServerClosed. + */ + listenAndServe(): void + } + interface Server { + /** + * 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. * - * If any of the first arguments implementing Scanner returns an error, - * that error will be wrapped in the returned 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. + * + * Serve always returns a non-nil error and closes l. + * After Shutdown or Close, the returned error is ErrServerClosed. */ - scan(...dest: any[]): void + serve(l: net.Listener): void } - interface Rows { + interface Server { /** - * 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. + * 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. + * + * ServeTLS always returns a non-nil error. After Shutdown or Close, the + * returned error is ErrServerClosed. */ - close(): void + serveTLS(l: net.Listener, certFile: string): void } - /** - * A Result summarizes an executed SQL command. - */ - interface Result { + interface Server { /** - * 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. + * 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. */ - lastInsertId(): number + setKeepAlivesEnabled(v: boolean): void + } + interface Server { /** - * RowsAffected returns the number of rows affected by an - * update, insert, or delete. Not every database or database - * driver may support this. + * 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. */ - rowsAffected(): number + listenAndServeTLS(certFile: string): void } } /** - * 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. + * Package echo implements high performance, minimalist Go web framework. * - * 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. + * Example: * - * 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. + * ``` + * 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 exec { +namespace echo { /** - * Cmd represents an external command being prepared or run. - * - * A Cmd cannot be reused after calling its Run, Output or CombinedOutput - * methods. + * Context represents the context of the current HTTP request. It holds request and + * response objects, path, path parameters, data and registered handler. */ - interface Cmd { + interface Context { /** - * Path is the path of the command to run. - * - * This is the only field that must be set to a non-zero - * value. If Path is relative, it is evaluated relative - * to Dir. + * Request returns `*http.Request`. */ - path: string + request(): (http.Request | undefined) /** - * Args holds command line arguments, including the command as Args[0]. - * If the Args field is empty or nil, Run uses {Path}. + * SetRequest sets `*http.Request`. + */ + setRequest(r: http.Request): void + /** + * SetResponse sets `*Response`. + */ + setResponse(r: Response): void + /** + * Response returns `*Response`. + */ + response(): (Response | undefined) + /** + * IsTLS returns true if HTTP connection is TLS otherwise false. + */ + isTLS(): boolean + /** + * IsWebSocket returns true if HTTP connection is WebSocket otherwise false. + */ + isWebSocket(): boolean + /** + * Scheme returns the HTTP protocol scheme, `http` or `https`. + */ + scheme(): string + /** + * 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`. + */ + realIP(): string + /** + * 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. + */ + routeInfo(): RouteInfo + /** + * Path returns the registered path for the handler. + */ + path(): string + /** + * PathParam returns path parameter by name. + */ + pathParam(name: string): string + /** + * PathParamDefault returns the path parameter or default value for the provided name. * - * In typical use, both Path and Args are set by calling Command. + * 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.` */ - args: Array + pathParamDefault(name: string, defaultValue: string): string /** - * 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. + * PathParams returns path parameter values. */ - env: Array + pathParams(): PathParams /** - * 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. + * SetPathParams sets path parameters for current request. */ - dir: string + setPathParams(params: PathParams): void /** - * Stdin specifies the process's standard input. - * - * 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. - * - * 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. + * QueryParam returns the query param for the provided name. */ - stdin: io.Reader + queryParam(name: string): string /** - * Stdout and Stderr specify the process's standard output and error. - * - * If either is nil, Run connects the corresponding file descriptor - * to the null device (os.DevNull). - * - * 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. - * - * 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. + * QueryParamDefault returns the query param or default value for the provided name. */ - stdout: io.Writer - stderr: io.Writer + queryParamDefault(name: string): string /** - * 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. - * - * ExtraFiles is not supported on Windows. + * QueryParams returns the query parameters as `url.Values`. */ - extraFiles: Array<(os.File | undefined)> + queryParams(): url.Values /** - * SysProcAttr holds optional, operating system-specific attributes. - * Run passes it to os.StartProcess as the os.ProcAttr's Sys field. + * QueryString returns the URL query string. */ - sysProcAttr?: syscall.SysProcAttr + queryString(): string /** - * Process is the underlying process, once started. + * FormValue returns the form field value for the provided name. */ - process?: os.Process + formValue(name: string): string /** - * ProcessState contains information about an exited process, - * available after a call to Wait or Run. + * FormValueDefault returns the form field value or default value for the provided name. */ - processState?: os.ProcessState - } - interface Cmd { + formValueDefault(name: string): string /** - * 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. + * FormValues returns the form field values as `url.Values`. */ - string(): string - } - interface Cmd { + formValues(): url.Values /** - * Run starts the specified command and waits for it to complete. - * - * 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 the command starts but does not complete successfully, the error is of - * type *ExitError. Other error types may be returned for other situations. - * - * 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. + * FormFile returns the multipart form file for the provided name. */ - run(): void - } - interface Cmd { + formFile(name: string): (multipart.FileHeader | undefined) /** - * Start starts the specified command but does not wait for it to complete. - * - * If Start returns successfully, the c.Process field will be set. - * - * The Wait method will return the exit code and release associated resources - * once the command exits. + * MultipartForm returns the multipart form. */ - start(): void - } - interface Cmd { + multipartForm(): (multipart.Form | undefined) /** - * 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. - * - * 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 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. + * Cookie returns the named cookie provided in the request. */ - wait(): void - } - interface Cmd { + cookie(name: string): (http.Cookie | undefined) /** - * 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. + * SetCookie adds a `Set-Cookie` header in HTTP response. */ - output(): string - } - interface Cmd { + setCookie(cookie: http.Cookie): void /** - * CombinedOutput runs the command and returns its combined standard - * output and standard error. + * Cookies returns the HTTP cookies sent with the request. */ - combinedOutput(): string - } - interface Cmd { + cookies(): Array<(http.Cookie | undefined)> /** - * 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. + * Get retrieves data from the context. */ - stdinPipe(): io.WriteCloser + get(key: string): { } - interface Cmd { /** - * 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. + * Set saves data in the context. */ - stdoutPipe(): io.ReadCloser - } - interface Cmd { + set(key: string, val: { + }): void /** - * 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. + * Bind binds path params, query params and the request body into provided type `i`. The default binder + * binds body based on Content-Type header. */ - stderrPipe(): io.ReadCloser - } -} - -/** - * 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 { + bind(i: { + }): void + /** + * Validate validates provided `i`. It is usually called after `Context#Bind()`. + * Validator must be registered using `Echo#Validator`. + */ + validate(i: { + }): void + /** + * Render renders a template with data and sends a text/html response with status + * code. Renderer must be registered using `Echo.Renderer`. + */ + render(code: number, name: string, data: { + }): void /** - * Read implements io.Reader (https://golang.org/pkg/io/#Reader). + * HTML sends an HTTP response with status code. */ - read(p: string): number - } - interface Reader { + html(code: number, html: string): void /** - * Seek implements io.Seeker (https://golang.org/pkg/io/#Seeker). + * HTMLBlob sends an HTTP blob response with status code. */ - seek(offset: number, whence: number): number - } - interface Reader { + htmlBlob(code: number, b: string): void /** - * Close implements io.Closer (https://golang.org/pkg/io/#Closer). + * String sends a string response with status code. */ - close(): void - } - interface Reader { + string(code: number, s: string): void /** - * ContentType returns the MIME type of the blob. + * JSON sends a JSON response with status code. */ - contentType(): string - } - interface Reader { + json(code: number, i: { + }): void /** - * ModTime returns the time the blob was last modified. + * JSONPretty sends a pretty-print JSON with status code. */ - modTime(): time.Time - } - interface Reader { + jsonPretty(code: number, i: { + }, indent: string): void /** - * Size returns the size of the blob content in bytes. + * JSONBlob sends a JSON blob response with status code. */ - size(): number - } - interface Reader { + jsonBlob(code: number, b: string): void /** - * 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. + * JSONP sends a JSONP response with status code. It uses `callback` to construct + * the JSONP payload. */ - as(i: { - }): boolean - } - interface Reader { + jsonp(code: number, callback: string, i: { + }): void /** - * 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. - * - * It implements the io.WriterTo interface. + * JSONPBlob sends a JSONP blob response with status code. It uses `callback` + * to construct the JSONP payload. */ - writeTo(w: io.Writer): number - } - /** - * Attributes contains attributes about a blob. - */ - interface Attributes { + jsonpBlob(code: number, callback: string, b: string): void /** - * CacheControl specifies caching attributes that services may use - * when serving the blob. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control + * XML sends an XML response with status code. */ - cacheControl: string + xml(code: number, i: { + }): void /** - * 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 + * XMLPretty sends a pretty-print XML with status code. */ - contentDisposition: string + xmlPretty(code: number, i: { + }, indent: string): void /** - * ContentEncoding specifies the encoding used for the blob's content, if any. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + * XMLBlob sends an XML blob response with status code. */ - contentEncoding: string + xmlBlob(code: number, b: string): void /** - * ContentLanguage specifies the language used in the blob's content, if any. - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language + * Blob sends a blob response with status code and content type. */ - contentLanguage: string + blob(code: number, contentType: string, b: string): 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 + * Stream sends a streaming response with status code and content type. */ - contentType: string + stream(code: number, contentType: string, r: io.Reader): 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. + * File sends a response with the content of the file. */ - metadata: _TygojaDict + file(file: string): void /** - * CreateTime is the time the blob was created, if available. If not available, - * CreateTime will be the zero time. + * FileFS sends a response with the content of the file from given filesystem. */ - createTime: time.Time + fileFS(file: string, filesystem: fs.FS): void /** - * ModTime is the time the blob was last modified. + * Attachment sends a response as attachment, prompting client to save the + * file. */ - modTime: time.Time + attachment(file: string, name: string): void /** - * Size is the size of the blob's content in bytes. + * Inline sends a response as inline, opening the file in the browser. */ - size: number + inline(file: string, name: string): void /** - * MD5 is an MD5 hash of the blob contents or nil if not available. + * NoContent sends a response with no body and a status code. */ - md5: string + noContent(code: number): void /** - * ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag. + * Redirect redirects the request to a provided URL with status code. */ - eTag: string + redirect(code: number, url: string): void + /** + * 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. + */ + error(err: Error): void + /** + * 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. + */ + echo(): (Echo | undefined) } - interface Attributes { + // @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 { /** - * 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. + * NewContextFunc allows using custom context implementations, instead of default *echo.context */ - as(i: { - }): boolean + 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 + /** + * 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. + */ + onAddRoute: (host: string, route: Routable) => void } /** - * ListObject represents a single blob returned from List. + * HandlerFunc defines a function to serve HTTP requests. */ - interface ListObject { + interface HandlerFunc {(c: Context): void } + /** + * MiddlewareFunc defines a function to process middleware. + */ + interface MiddlewareFunc {(next: HandlerFunc): HandlerFunc } + interface Echo { /** - * Key is the key for this blob. + * 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. */ - key: string + newContext(r: http.Request, w: http.ResponseWriter): Context + } + interface Echo { /** - * ModTime is the time the blob was last modified. + * Router returns the default router. */ - modTime: time.Time + router(): Router + } + interface Echo { /** - * Size is the size of the blob's content in bytes. + * Routers returns the new map of host => router. */ - size: number + routers(): _TygojaDict + } + interface Echo { /** - * MD5 is an MD5 hash of the blob contents or nil if not available. + * RouterFor returns Router for given host. When host is left empty the default router is returned. */ - md5: string + routerFor(host: string): [Router, boolean] + } + interface Echo { + /** + * 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. + */ + resetRouterCreator(creator: (e: Echo) => Router): void + } + interface Echo { + /** + * 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. + */ + pre(...middleware: MiddlewareFunc[]): void + } + interface Echo { + /** + * Use adds middleware to the chain which is run after router has found matching route and before route/request handler method is executed. + */ + use(...middleware: MiddlewareFunc[]): void + } + interface Echo { + /** + * CONNECT registers a new CONNECT route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. + */ + connect(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + } + interface Echo { + /** + * DELETE registers a new DELETE route for a path with matching handler in the router + * with optional route-level middleware. Panics on error. + */ + delete(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + } + interface Echo { + /** + * GET registers a new GET route for a path with matching handler in the router + * with optional route-level middleware. Panics on error. + */ + get(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + } + interface Echo { /** - * 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. + * HEAD registers a new HEAD route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - isDir: boolean + head(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface ListObject { + interface Echo { /** - * 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. + * OPTIONS registers a new OPTIONS route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - as(i: { - }): boolean + options(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } -} - -/** - * 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 { + interface Echo { /** - * MarshalJSON implements the [json.Marshaler] interface. + * PATCH registers a new PATCH route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - marshalJSON(): string + patch(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface JsonArray { + interface Echo { /** - * Value implements the [driver.Valuer] interface. + * POST registers a new POST route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - value(): any + post(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface JsonArray { + interface Echo { /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JsonArray[T] instance. + * PUT registers a new PUT route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - scan(value: any): void + put(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - /** - * JsonMap defines a map that is safe for json and db read/write. - */ - interface JsonMap extends _TygojaDict{} - interface JsonMap { + interface Echo { /** - * MarshalJSON implements the [json.Marshaler] interface. + * TRACE registers a new TRACE route for a path with matching handler in the + * router with optional route-level middleware. Panics on error. */ - marshalJSON(): string + trace(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface JsonMap { + interface Echo { /** - * Get retrieves a single value from the current JsonMap. + * 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). * - * 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). + * Example: `e.RouteNotFound("/*", func(c echo.Context) error { return c.NoContent(http.StatusNotFound) })` */ - get(key: string): any + routeNotFound(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo } - interface JsonMap { + interface Echo { /** - * Set sets a single value in the current JsonMap. + * 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. * - * 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). + * 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. */ - set(key: string, value: any): void + any(path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes } - interface JsonMap { + interface Echo { /** - * Value implements the [driver.Valuer] interface. + * 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. */ - value(): any + match(methods: Array, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes } - interface JsonMap { + interface Echo { /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current `JsonMap` instance. + * Static registers a new route with path prefix to serve static files from the provided root directory. */ - scan(value: any): void + static(pathPrefix: string): RouteInfo } -} - -/** - * 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 Echo { + /** + * 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. + */ + staticFS(pathPrefix: string, filesystem: fs.FS): RouteInfo } - interface Schema { + interface Echo { /** - * Fields returns the registered schema fields. + * FileFS registers a new route with path to serve file from the provided file system. */ - fields(): Array<(SchemaField | undefined)> + fileFS(path: string, filesystem: fs.FS, ...m: MiddlewareFunc[]): RouteInfo } - interface Schema { + interface Echo { /** - * InitFieldsOptions calls `InitOptions()` for all schema fields. + * File registers a new route with path to serve a static file with optional route-level middleware. Panics on error. */ - initFieldsOptions(): void + file(path: string, ...middleware: MiddlewareFunc[]): RouteInfo } - interface Schema { + interface Echo { /** - * Clone creates a deep clone of the current schema. + * AddRoute registers a new Route with default host Router */ - clone(): (Schema | undefined) + addRoute(route: Routable): RouteInfo } - interface Schema { + interface Echo { /** - * AsMap returns a map with all registered schema field. - * The returned map is indexed with each field name. + * Add registers a new route for an HTTP method and path with matching handler + * in the router with optional route-level middleware. */ - asMap(): _TygojaDict + add(method: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): RouteInfo } - interface Schema { + interface Echo { /** - * GetFieldById returns a single field by its id. + * Host creates a new router group for the provided host and optional host-level middleware. */ - getFieldById(id: string): (SchemaField | undefined) + host(name: string, ...m: MiddlewareFunc[]): (Group | undefined) } - interface Schema { + interface Echo { /** - * GetFieldByName returns a single field by its name. + * Group creates a new router group with prefix and optional group-level middleware. */ - getFieldByName(name: string): (SchemaField | undefined) + group(prefix: string, ...m: MiddlewareFunc[]): (Group | undefined) } - interface Schema { + interface Echo { /** - * RemoveField removes a single schema field by its id. - * - * This method does nothing if field with `id` doesn't exist. + * AcquireContext returns an empty `Context` instance from the pool. + * You must return the context by calling `ReleaseContext()`. */ - removeField(id: string): void + acquireContext(): Context } - interface Schema { + interface Echo { /** - * 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. + * ReleaseContext returns the `Context` instance back to the pool. + * You must call it after `AcquireContext()`. */ - addField(newField: SchemaField): void + releaseContext(c: Context): void } - interface Schema { + interface Echo { /** - * 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. + * ServeHTTP implements `http.Handler` interface, which serves HTTP requests. */ - validate(): void + serveHTTP(w: http.ResponseWriter, r: http.Request): void } - interface Schema { + interface Echo { /** - * MarshalJSON implements the [json.Marshaler] interface. + * 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) + * } + * ``` */ - marshalJSON(): string + start(address: string): void } - interface Schema { +} + +/** + * 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. + */ +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 { + /** + * Path is the path of the command to run. + * + * This is the only field that must be set to a non-zero + * value. If Path is relative, it is evaluated relative + * to Dir. + */ + path: string /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. + * Args holds command line arguments, including the command as Args[0]. + * If the Args field is empty or nil, Run uses {Path}. * - * On success, all schema field options are auto initialized. + * In typical use, both Path and Args are set by calling Command. */ - unmarshalJSON(data: string): void - } - interface Schema { + args: Array /** - * Value implements the [driver.Valuer] interface. + * 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. */ - value(): any - } - interface Schema { + env: Array /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current Schema instance. + * 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. */ - scan(value: any): void - } -} - -/** - * Package models implements all PocketBase DB models and DTOs. - */ -namespace models { - type _subABBPt = BaseModel - interface Admin extends _subABBPt { - avatar: number - email: string - tokenKey: string - passwordHash: string - lastResetSentAt: types.DateTime - } - interface Admin { + dir: string /** - * TableName returns the Admin model SQL table name. + * Stdin specifies the process's standard input. + * + * 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. + * + * 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. */ - tableName(): string - } - interface Admin { + stdin: io.Reader /** - * ValidatePassword validates a plain password against the model's password. + * Stdout and Stderr specify the process's standard output and error. + * + * If either is nil, Run connects the corresponding file descriptor + * to the null device (os.DevNull). + * + * 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. + * + * 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. */ - validatePassword(password: string): boolean - } - interface Admin { + stdout: io.Writer + stderr: io.Writer /** - * SetPassword sets cryptographically secure string to `model.Password`. + * 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. * - * Additionally this method also resets the LastResetSentAt and the TokenKey fields. + * ExtraFiles is not supported on Windows. */ - setPassword(password: string): void - } - interface Admin { + extraFiles: Array<(os.File | undefined)> /** - * RefreshTokenKey generates and sets new random token key. + * SysProcAttr holds optional, operating system-specific attributes. + * Run passes it to os.StartProcess as the os.ProcAttr's Sys field. */ - refreshTokenKey(): void - } - // @ts-ignore - import validation = ozzo_validation - type _subohowk = BaseModel - interface Collection extends _subohowk { - name: string - type: string - system: boolean - schema: schema.Schema - indexes: types.JsonArray + sysProcAttr?: syscall.SysProcAttr /** - * rules + * Process is the underlying process, once started. */ - listRule?: string - viewRule?: string - createRule?: string - updateRule?: string - deleteRule?: string - options: types.JsonMap - } - interface Collection { + process?: os.Process /** - * TableName returns the Collection model SQL table name. + * ProcessState contains information about an exited process, + * available after a call to Wait or Run. */ - tableName(): string + processState?: os.ProcessState } - interface Collection { + interface Cmd { /** - * BaseFilesPath returns the storage dir path used by the collection. + * 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. */ - baseFilesPath(): string + string(): string } - interface Collection { + interface Cmd { /** - * IsBase checks if the current collection has "base" type. + * Run starts the specified command and waits for it to complete. + * + * 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 the command starts but does not complete successfully, the error is of + * type *ExitError. Other error types may be returned for other situations. + * + * 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. */ - isBase(): boolean + run(): void } - interface Collection { + interface Cmd { /** - * IsAuth checks if the current collection has "auth" type. + * Start starts the specified command but does not wait for it to complete. + * + * If Start returns successfully, the c.Process field will be set. + * + * The Wait method will return the exit code and release associated resources + * once the command exits. */ - isAuth(): boolean + start(): void } - interface Collection { + interface Cmd { /** - * IsView checks if the current collection has "view" type. + * 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. + * + * 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 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. */ - isView(): boolean + wait(): void } - interface Collection { + interface Cmd { /** - * MarshalJSON implements the [json.Marshaler] interface. + * 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. */ - marshalJSON(): string + output(): string } - interface Collection { + interface Cmd { /** - * BaseOptions decodes the current collection options and returns them - * as new [CollectionBaseOptions] instance. + * CombinedOutput runs the command and returns its combined standard + * output and standard error. */ - baseOptions(): CollectionBaseOptions + combinedOutput(): string } - interface Collection { + interface Cmd { /** - * AuthOptions decodes the current collection options and returns them - * as new [CollectionAuthOptions] instance. + * 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. */ - authOptions(): CollectionAuthOptions + stdinPipe(): io.WriteCloser } - interface Collection { + interface Cmd { /** - * ViewOptions decodes the current collection options and returns them - * as new [CollectionViewOptions] instance. + * 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. */ - viewOptions(): CollectionViewOptions + stdoutPipe(): io.ReadCloser } - interface Collection { + interface Cmd { /** - * NormalizeOptions updates the current collection options with a - * new normalized state based on the collection type. + * 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. */ - normalizeOptions(): void + stderrPipe(): io.ReadCloser } - interface Collection { - /** - * DecodeOptions decodes the current collection options into the - * provided "result" (must be a pointer). +} + +/** + * 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 */ - decodeOptions(result: any): void + verifyAudience(cmp: string, req: boolean): boolean } - interface Collection { + interface MapClaims { /** - * SetOptions normalizes and unmarshals the specified options into m.Options. + * VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). + * If req is false, it will return true, if exp is unset. */ - setOptions(typedOptions: any): void - } - type _subkpDNS = BaseModel - interface ExternalAuth extends _subkpDNS { - collectionId: string - recordId: string - provider: string - providerId: string - } - interface ExternalAuth { - tableName(): string - } - type _subyoPxp = BaseModel - interface Record extends _subyoPxp { + verifyExpiresAt(cmp: number, req: boolean): boolean } - interface Record { + interface MapClaims { /** - * TableName returns the table name associated to the current Record model. + * VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). + * If req is false, it will return true, if iat is unset. */ - tableName(): string + verifyIssuedAt(cmp: number, req: boolean): boolean } - interface Record { + interface MapClaims { /** - * Collection returns the Collection model associated to the current Record model. + * VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). + * If req is false, it will return true, if nbf is unset. */ - collection(): (Collection | undefined) + verifyNotBefore(cmp: number, req: boolean): boolean } - interface Record { + interface MapClaims { /** - * 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. + * VerifyIssuer compares the iss claim against cmp. + * If required is false, this method will return true if the value matches or is unset */ - originalCopy(): (Record | undefined) + verifyIssuer(cmp: string, req: boolean): boolean } - interface Record { + interface MapClaims { /** - * CleanCopy returns a copy of the current record model populated only - * with its LATEST data state and everything else reset to the defaults. + * 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. */ - cleanCopy(): (Record | undefined) + valid(): void } - interface Record { +} + +/** + * 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 { /** - * Expand returns a shallow copy of the current Record model expand data. + * Read implements io.Reader (https://golang.org/pkg/io/#Reader). */ - expand(): _TygojaDict + read(p: string): number } - interface Record { + interface Reader { /** - * SetExpand shallow copies the provided data to the current Record model's expand. + * Seek implements io.Seeker (https://golang.org/pkg/io/#Seeker). */ - setExpand(expand: _TygojaDict): void + seek(offset: number, whence: number): number } - interface Record { + interface Reader { /** - * 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). + * Close implements io.Closer (https://golang.org/pkg/io/#Closer). */ - mergeExpand(expand: _TygojaDict): void + close(): void } - interface Record { + interface Reader { /** - * SchemaData returns a shallow copy ONLY of the defined record schema fields data. + * ContentType returns the MIME type of the blob. */ - schemaData(): _TygojaDict + contentType(): string } - interface Record { + interface Reader { /** - * 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. + * ModTime returns the time the blob was last modified. */ - unknownData(): _TygojaDict + modTime(): time.Time } - interface Record { + interface Reader { /** - * IgnoreEmailVisibility toggles the flag to ignore the auth record email visibility check. + * Size returns the size of the blob content in bytes. */ - ignoreEmailVisibility(state: boolean): void + size(): number } - interface Record { + interface Reader { /** - * WithUnknownData toggles the export/serialization of unknown data fields - * (false by default). + * 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. */ - withUnknownData(state: boolean): void + as(i: { + }): boolean } - interface Record { + interface Reader { /** - * Set sets the provided key-value data pair for the current Record model. + * 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. * - * If the record collection has field with name matching the provided "key", - * the value will be further normalized according to the field rules. + * It implements the io.WriterTo interface. */ - set(key: string, value: any): void + writeTo(w: io.Writer): number } - interface Record { + /** + * Attributes contains attributes about a blob. + */ + interface Attributes { /** - * Get returns a normalized single record model data value for "key". + * CacheControl specifies caching attributes that services may use + * when serving the blob. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control */ - get(key: string): any - } - interface Record { + cacheControl: string /** - * GetBool returns the data value for "key" as a bool. + * 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 */ - getBool(key: string): boolean - } - interface Record { + contentDisposition: string /** - * GetString returns the data value for "key" as a string. + * ContentEncoding specifies the encoding used for the blob's content, if any. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding */ - getString(key: string): string - } - interface Record { + contentEncoding: string /** - * GetInt returns the data value for "key" as an int. + * ContentLanguage specifies the language used in the blob's content, if any. + * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Language */ - getInt(key: string): number - } - interface Record { + contentLanguage: string /** - * GetFloat returns the data value for "key" as a float64. + * 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 */ - getFloat(key: string): number - } - interface Record { + contentType: string /** - * GetTime returns the data value for "key" as a [time.Time] instance. + * 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. */ - getTime(key: string): time.Time - } - interface Record { + metadata: _TygojaDict /** - * GetDateTime returns the data value for "key" as a DateTime instance. + * CreateTime is the time the blob was created, if available. If not available, + * CreateTime will be the zero time. */ - getDateTime(key: string): types.DateTime - } - interface Record { + createTime: time.Time /** - * GetStringSlice returns the data value for "key" as a slice of unique strings. + * ModTime is the time the blob was last modified. */ - getStringSlice(key: string): Array - } - interface Record { + modTime: time.Time + /** + * Size is the size of the blob's content in bytes. + */ + size: number + /** + * MD5 is an MD5 hash of the blob contents or nil if not available. + */ + md5: string /** - * 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. + * ETag for the blob; see https://en.wikipedia.org/wiki/HTTP_ETag. */ - expandedOne(relField: string): (Record | undefined) + eTag: string } - interface Record { + interface Attributes { /** - * 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. + * 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. */ - expandedAll(relField: string): Array<(Record | undefined)> + as(i: { + }): boolean } - interface Record { + /** + * ListObject represents a single blob returned from List. + */ + interface ListObject { /** - * 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) - * ``` + * Key is the key for this blob. */ - unmarshalJSONField(key: string, result: any): void - } - interface Record { + key: string /** - * BaseFilesPath returns the storage dir path used by the record. + * ModTime is the time the blob was last modified. */ - baseFilesPath(): string - } - interface Record { + modTime: time.Time /** - * FindFileFieldByFile returns the first file type field for which - * any of the record's data contains the provided filename. + * Size is the size of the blob's content in bytes. */ - findFileFieldByFile(filename: string): (schema.SchemaField | undefined) - } - interface Record { + size: number /** - * Load bulk loads the provided data into the current Record model. + * MD5 is an MD5 hash of the blob contents or nil if not available. */ - load(data: _TygojaDict): void - } - interface Record { + md5: string /** - * ColumnValueMap implements [ColumnValueMapper] interface. + * 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. */ - columnValueMap(): _TygojaDict + isDir: boolean } - interface Record { + interface ListObject { /** - * 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)`. + * 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. */ - publicExport(): _TygojaDict + as(i: { + }): boolean } - interface Record { +} + +/** + * 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 { /** * MarshalJSON implements the [json.Marshaler] interface. - * - * Only the data exported by `PublicExport()` will be serialized. */ marshalJSON(): string } - interface Record { + interface JsonArray { /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. + * Value implements the [driver.Valuer] interface. */ - unmarshalJSON(data: string): void + value(): any } - interface Record { + interface JsonArray { /** - * 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} - * ``` + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JsonArray[T] instance. */ - replaceModifers(data: _TygojaDict): _TygojaDict + scan(value: any): void } - interface Record { + /** + * JsonMap defines a map that is safe for json and db read/write. + */ + interface JsonMap extends _TygojaDict{} + interface JsonMap { /** - * Username returns the "username" auth record data value. + * MarshalJSON implements the [json.Marshaler] interface. */ - username(): string + marshalJSON(): string } - interface Record { + interface JsonMap { /** - * SetUsername sets the "username" auth record data value. - * - * This method doesn't check whether the provided value is a valid username. + * Get retrieves a single value from the current JsonMap. * - * Returns an error if the record is not from an auth collection. - */ - setUsername(username: string): void - } - interface Record { - /** - * Email returns the "email" auth record data value. + * 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). */ - email(): string + get(key: string): any } - interface Record { + interface JsonMap { /** - * SetEmail sets the "email" auth record data value. - * - * This method doesn't check whether the provided value is a valid email. + * Set sets a single value in the current JsonMap. * - * Returns an error if the record is not from an auth collection. + * 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). */ - setEmail(email: string): void + set(key: string, value: any): void } - interface Record { + interface JsonMap { /** - * Verified returns the "emailVisibility" auth record data value. + * Value implements the [driver.Valuer] interface. */ - emailVisibility(): boolean + value(): any } - interface Record { + interface JsonMap { /** - * SetEmailVisibility sets the "emailVisibility" auth record data value. - * - * Returns an error if the record is not from an auth collection. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current `JsonMap` instance. */ - setEmailVisibility(visible: boolean): void + scan(value: any): void } - interface Record { +} + +/** + * 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 { /** - * Verified returns the "verified" auth record data value. + * Fields returns the registered schema fields. */ - verified(): boolean + fields(): Array<(SchemaField | undefined)> } - interface Record { + interface Schema { /** - * SetVerified sets the "verified" auth record data value. - * - * Returns an error if the record is not from an auth collection. + * InitFieldsOptions calls `InitOptions()` for all schema fields. */ - setVerified(verified: boolean): void + initFieldsOptions(): void } - interface Record { + interface Schema { /** - * TokenKey returns the "tokenKey" auth record data value. + * Clone creates a deep clone of the current schema. */ - tokenKey(): string + clone(): (Schema | undefined) } - interface Record { + interface Schema { /** - * SetTokenKey sets the "tokenKey" auth record data value. - * - * Returns an error if the record is not from an auth collection. + * AsMap returns a map with all registered schema field. + * The returned map is indexed with each field name. */ - setTokenKey(key: string): void + asMap(): _TygojaDict } - interface Record { + interface Schema { /** - * RefreshTokenKey generates and sets new random auth record "tokenKey". - * - * Returns an error if the record is not from an auth collection. + * GetFieldById returns a single field by its id. */ - refreshTokenKey(): void + getFieldById(id: string): (SchemaField | undefined) } - interface Record { + interface Schema { /** - * LastResetSentAt returns the "lastResentSentAt" auth record data value. + * GetFieldByName returns a single field by its name. */ - lastResetSentAt(): types.DateTime + getFieldByName(name: string): (SchemaField | undefined) } - interface Record { + interface Schema { /** - * SetLastResetSentAt sets the "lastResentSentAt" auth record data value. + * RemoveField removes a single schema field by its id. * - * Returns an error if the record is not from an auth collection. + * This method does nothing if field with `id` doesn't exist. */ - setLastResetSentAt(dateTime: types.DateTime): void + removeField(id: string): void } - interface Record { + interface Schema { /** - * LastVerificationSentAt returns the "lastVerificationSentAt" auth record data value. + * 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. */ - lastVerificationSentAt(): types.DateTime + addField(newField: SchemaField): void } - interface Record { + interface Schema { /** - * SetLastVerificationSentAt sets an "lastVerificationSentAt" auth record data value. + * Validate makes Schema validatable by implementing [validation.Validatable] interface. * - * Returns an error if the record is not from an auth collection. + * Internally calls each individual field's validator and additionally + * checks for invalid renamed fields and field name duplications. */ - setLastVerificationSentAt(dateTime: types.DateTime): void + validate(): void } - interface Record { + interface Schema { /** - * PasswordHash returns the "passwordHash" auth record data value. + * MarshalJSON implements the [json.Marshaler] interface. */ - passwordHash(): string + marshalJSON(): string } - interface Record { + interface Schema { /** - * ValidatePassword validates a plain password against the auth record password. + * UnmarshalJSON implements the [json.Unmarshaler] interface. * - * Returns false if the password is incorrect or record is not from an auth collection. + * On success, all schema field options are auto initialized. */ - validatePassword(password: string): boolean + unmarshalJSON(data: string): void } - interface Record { + interface Schema { /** - * 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. + * Value implements the [driver.Valuer] interface. */ - setPassword(password: string): void - } - /** - * RequestInfo defines a HTTP request data struct, usually used - * as part of the `@request.*` filter resolver. - */ - interface RequestInfo { - method: string - query: _TygojaDict - data: _TygojaDict - headers: _TygojaDict - authRecord?: Record - admin?: Admin + value(): any } - interface RequestInfo { + interface Schema { /** - * HasModifierDataKeys loosely checks if the current struct has any modifier Data keys. + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current Schema instance. */ - hasModifierDataKeys(): boolean + 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 { +namespace models { + type _subgkivd = BaseModel + interface Admin extends _subgkivd { + 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 | undefined) + 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 | undefined) + refreshTokenKey(): void + } + // @ts-ignore + import validation = ozzo_validation + type _subNuoec = BaseModel + interface Collection extends _subNuoec { + 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 + } + 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): 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 _subdhfvX = BaseModel + interface ExternalAuth extends _subdhfvX { + collectionId: string + recordId: string + provider: string + providerId: string + } + interface ExternalAuth { + tableName(): string + } + type _subjpkVR = BaseModel + interface Record extends _subjpkVR { + } + 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 { + /** + * Collection returns the Collection model associated to the current Record model. + */ + collection(): (Collection | undefined) + } + interface Record { /** - * FormValue returns the form field 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. */ - formValue(name: string): string + originalCopy(): (Record | undefined) + } + interface Record { /** - * FormValueDefault returns the form field value or default value for the provided name. + * CleanCopy returns a copy of the current record model populated only + * with its LATEST data state and everything else reset to the defaults. */ - formValueDefault(name: string): string + cleanCopy(): (Record | undefined) + } + interface Record { /** - * FormValues returns the form field values as `url.Values`. + * Expand returns a shallow copy of the current Record model expand data. */ - formValues(): url.Values + expand(): _TygojaDict + } + interface Record { /** - * FormFile returns the multipart form file for the provided name. + * SetExpand shallow copies the provided data to the current Record model's expand. */ - formFile(name: string): (multipart.FileHeader | undefined) + setExpand(expand: _TygojaDict): void + } + interface Record { /** - * MultipartForm returns the multipart form. + * 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). */ - multipartForm(): (multipart.Form | undefined) + mergeExpand(expand: _TygojaDict): void + } + interface Record { /** - * Cookie returns the named cookie provided in the request. + * SchemaData returns a shallow copy ONLY of the defined record schema fields data. */ - cookie(name: string): (http.Cookie | undefined) + schemaData(): _TygojaDict + } + interface Record { /** - * SetCookie adds a `Set-Cookie` header in HTTP response. + * 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. */ - setCookie(cookie: http.Cookie): void + unknownData(): _TygojaDict + } + interface Record { /** - * Cookies returns the HTTP cookies sent with the request. + * IgnoreEmailVisibility toggles the flag to ignore the auth record email visibility check. */ - cookies(): Array<(http.Cookie | undefined)> + ignoreEmailVisibility(state: boolean): void + } + interface Record { /** - * Get retrieves data from the context. + * WithUnknownData toggles the export/serialization of unknown data fields + * (false by default). */ - get(key: string): { + withUnknownData(state: boolean): void } + interface Record { /** - * Set saves data in the context. + * 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. */ - set(key: string, val: { - }): void + set(key: string, value: any): 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. + * Get returns a normalized single record model data value for "key". */ - bind(i: { - }): void + get(key: string): any + } + interface Record { /** - * Validate validates provided `i`. It is usually called after `Context#Bind()`. - * Validator must be registered using `Echo#Validator`. + * GetBool returns the data value for "key" as a bool. */ - validate(i: { - }): void + getBool(key: string): boolean + } + interface Record { /** - * Render renders a template with data and sends a text/html response with status - * code. Renderer must be registered using `Echo.Renderer`. + * GetString returns the data value for "key" as a string. */ - render(code: number, name: string, data: { - }): void + getString(key: string): string + } + interface Record { /** - * HTML sends an HTTP response with status code. + * GetInt returns the data value for "key" as an int. */ - html(code: number, html: string): void + getInt(key: string): number + } + interface Record { /** - * HTMLBlob sends an HTTP blob response with status code. + * GetFloat returns the data value for "key" as a float64. */ - htmlBlob(code: number, b: string): void + getFloat(key: string): number + } + interface Record { /** - * String sends a string response with status code. + * GetTime returns the data value for "key" as a [time.Time] instance. */ - string(code: number, s: string): void + getTime(key: string): time.Time + } + interface Record { /** - * JSON sends a JSON response with status code. + * GetDateTime returns the data value for "key" as a DateTime instance. */ - json(code: number, i: { - }): void + getDateTime(key: string): types.DateTime + } + interface Record { /** - * JSONPretty sends a pretty-print JSON with status code. + * GetStringSlice returns the data value for "key" as a slice of unique strings. */ - jsonPretty(code: number, i: { - }, indent: string): void + getStringSlice(key: string): Array + } + interface Record { /** - * JSONBlob sends a JSON blob response with status code. + * 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. */ - jsonBlob(code: number, b: string): void + expandedOne(relField: string): (Record | undefined) + } + interface Record { /** - * JSONP sends a JSONP response with status code. It uses `callback` to construct - * the JSONP payload. + * 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. */ - jsonp(code: number, callback: string, i: { - }): void + expandedAll(relField: string): Array<(Record | undefined)> + } + interface Record { /** - * JSONPBlob sends a JSONP blob response with status code. It uses `callback` - * to construct the JSONP payload. + * 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) + * ``` */ - jsonpBlob(code: number, callback: string, b: string): void + unmarshalJSONField(key: string, result: any): void + } + interface Record { /** - * XML sends an XML response with status code. + * BaseFilesPath returns the storage dir path used by the record. */ - xml(code: number, i: { - }): void + baseFilesPath(): string + } + interface Record { /** - * XMLPretty sends a pretty-print XML with status code. + * FindFileFieldByFile returns the first file type field for which + * any of the record's data contains the provided filename. */ - xmlPretty(code: number, i: { - }, indent: string): void + findFileFieldByFile(filename: string): (schema.SchemaField | undefined) + } + interface Record { /** - * XMLBlob sends an XML blob response with status code. + * Load bulk loads the provided data into the current Record model. */ - xmlBlob(code: number, b: string): void + load(data: _TygojaDict): void + } + interface Record { /** - * Blob sends a blob response with status code and content type. + * ColumnValueMap implements [ColumnValueMapper] interface. */ - blob(code: number, contentType: string, b: string): void + columnValueMap(): _TygojaDict + } + interface Record { /** - * Stream sends a streaming response with status code and content type. + * 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)`. */ - stream(code: number, contentType: string, r: io.Reader): void + publicExport(): _TygojaDict + } + interface Record { /** - * File sends a response with the content of the file. + * MarshalJSON implements the [json.Marshaler] interface. + * + * Only the data exported by `PublicExport()` will be serialized. */ - file(file: string): void + marshalJSON(): string + } + interface Record { /** - * FileFS sends a response with the content of the file from given filesystem. + * UnmarshalJSON implements the [json.Unmarshaler] interface. */ - fileFS(file: string, filesystem: fs.FS): void + unmarshalJSON(data: string): void + } + interface Record { /** - * Attachment sends a response as attachment, prompting client to save the - * file. + * 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} + * ``` */ - attachment(file: string, name: string): void + replaceModifers(data: _TygojaDict): _TygojaDict + } + interface Record { /** - * Inline sends a response as inline, opening the file in the browser. + * Username returns the "username" auth record data value. */ - inline(file: string, name: string): void + username(): string + } + interface Record { /** - * NoContent sends a response with no body and a status code. + * 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. */ - noContent(code: number): void + setUsername(username: string): void + } + interface Record { /** - * Redirect redirects the request to a provided URL with status code. + * Email returns the "email" auth record data value. */ - redirect(code: number, url: string): void + email(): 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. + * SetEmail sets the "email" 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. - */ - error(err: Error): void - /** - * Echo returns the `Echo` instance. + * This method doesn't check whether the provided value is a valid email. * - * 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. + * Returns an error if the record is not from an auth collection. */ - echo(): (Echo | undefined) + setEmail(email: string): void } - // @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 + * Verified returns the "emailVisibility" auth record data value. */ - newContextFunc: (e: Echo, pathParamAllocSize: number) => ServableContext - debug: boolean - httpErrorHandler: HTTPErrorHandler - binder: Binder - jsonSerializer: JSONSerializer - validator: Validator - renderer: Renderer - logger: Logger - ipExtractor: IPExtractor + emailVisibility(): boolean + } + interface Record { /** - * Filesystem is file system used by Static and File handlers to access files. - * Defaults to os.DirFS(".") + * SetEmailVisibility sets the "emailVisibility" auth record data value. * - * 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. + * Returns an error if the record is not from an auth collection. */ - filesystem: fs.FS + setEmailVisibility(visible: boolean): 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 "verified" auth record data value. */ - onAddRoute: (host: string, route: Routable) => void + verified(): 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. + * SetVerified sets the "verified" 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 + setVerified(verified: boolean): void } - interface Echo { + interface Record { /** - * Router returns the default router. + * TokenKey returns the "tokenKey" auth record data value. */ - router(): Router + tokenKey(): string } - interface Echo { + interface Record { /** - * Routers returns the new map of host => router. + * SetTokenKey sets the "tokenKey" auth record data value. + * + * Returns an error if the record is not from an auth collection. */ - routers(): _TygojaDict + setTokenKey(key: string): void } - interface Echo { + interface Record { /** - * RouterFor returns Router for given host. When host is left empty the default router is returned. + * RefreshTokenKey generates and sets new random auth record "tokenKey". + * + * Returns an error if the record is not from an auth collection. */ - routerFor(host: string): [Router, boolean] + refreshTokenKey(): void } - 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. + * LastResetSentAt returns the "lastResentSentAt" auth record data value. */ - resetRouterCreator(creator: (e: Echo) => Router): void + lastResetSentAt(): types.DateTime } - 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. + * SetLastResetSentAt sets the "lastResentSentAt" auth record data value. + * + * Returns an error if the record is not from an auth collection. */ - pre(...middleware: MiddlewareFunc[]): void + setLastResetSentAt(dateTime: types.DateTime): 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. + * LastVerificationSentAt returns the "lastVerificationSentAt" auth record data value. */ - use(...middleware: MiddlewareFunc[]): void + lastVerificationSentAt(): 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. + * SetLastVerificationSentAt sets an "lastVerificationSentAt" auth record data value. + * + * Returns an error if the record is not from an auth collection. */ - connect(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + setLastVerificationSentAt(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. + * PasswordHash returns the "passwordHash" auth record data value. */ - delete(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + passwordHash(): string } - 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. + * 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. */ - get(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + validatePassword(password: string): boolean } - 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. + * 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. */ - head(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo + setPassword(password: string): void } - interface Echo { + /** + * RequestInfo defines a HTTP request data struct, usually used + * as part of the `@request.*` filter resolver. + */ + interface RequestInfo { + method: string + query: _TygojaDict + data: _TygojaDict + headers: _TygojaDict + authRecord?: Record + admin?: Admin + } + interface RequestInfo { /** - * OPTIONS registers a new OPTIONS 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. */ - options(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 + rawUser: _TygojaDict + accessToken: string + refreshToken: string + } + /** + * Provider defines a common interface for an OAuth2 client. + */ + interface Provider { /** - * PATCH registers a new PATCH route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * Scopes returns the context associated with the provider (if any). */ - patch(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { + context(): context.Context /** - * POST registers a new POST route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * SetContext assigns the specified context to the current provider. */ - post(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { + setContext(ctx: context.Context): void /** - * PUT registers a new PUT route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * Scopes returns the provider access permissions that will be requested. */ - put(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { + scopes(): Array /** - * TRACE registers a new TRACE route for a path with matching handler in the - * router with optional route-level middleware. Panics on error. + * SetScopes sets the provider access permissions that will be requested later. */ - trace(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { + setScopes(scopes: Array): void /** - * 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) })` + * ClientId returns the provider client's app ID. */ - routeNotFound(path: string, h: HandlerFunc, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { + clientId(): string /** - * 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. + * SetClientId sets the provider client's ID. + */ + setClientId(clientId: string): void + /** + * ClientSecret returns the provider client's app secret. */ - any(path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes - } - interface Echo { + clientSecret(): string /** - * 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. + * SetClientSecret sets the provider client's app secret. */ - match(methods: Array, path: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): Routes - } - interface Echo { + setClientSecret(secret: string): void /** - * Static registers a new route with path prefix to serve static files from the provided root directory. + * RedirectUrl returns the end address to redirect the user + * going through the OAuth flow. */ - static(pathPrefix: string): RouteInfo - } - interface Echo { + redirectUrl(): 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. + * SetRedirectUrl sets the provider's RedirectUrl. */ - staticFS(pathPrefix: string, filesystem: fs.FS): RouteInfo - } - interface Echo { + setRedirectUrl(url: string): void /** - * FileFS registers a new route with path to serve file from the provided file system. + * AuthUrl returns the provider's authorization service url. */ - fileFS(path: string, filesystem: fs.FS, ...m: MiddlewareFunc[]): RouteInfo - } - interface Echo { + authUrl(): string /** - * File registers a new route with path to serve a static file with optional route-level middleware. Panics on error. + * SetAuthUrl sets the provider's AuthUrl. */ - file(path: string, ...middleware: MiddlewareFunc[]): RouteInfo - } - interface Echo { + setAuthUrl(url: string): void /** - * AddRoute registers a new Route with default host Router + * TokenUrl returns the provider's token exchange service url. */ - addRoute(route: Routable): RouteInfo - } - interface Echo { + tokenUrl(): string /** - * Add registers a new route for an HTTP method and path with matching handler - * in the router with optional route-level middleware. + * SetTokenUrl sets the provider's TokenUrl. */ - add(method: string, handler: HandlerFunc, ...middleware: MiddlewareFunc[]): RouteInfo - } - interface Echo { + setTokenUrl(url: string): void /** - * Host creates a new router group for the provided host and optional host-level middleware. + * UserApiUrl returns the provider's user info api url. */ - host(name: string, ...m: MiddlewareFunc[]): (Group | undefined) - } - interface Echo { + userApiUrl(): string /** - * Group creates a new router group with prefix and optional group-level middleware. + * SetUserApiUrl sets the provider's UserApiUrl. */ - group(prefix: string, ...m: MiddlewareFunc[]): (Group | undefined) - } - interface Echo { + setUserApiUrl(url: string): void /** - * AcquireContext returns an empty `Context` instance from the pool. - * You must return the context by calling `ReleaseContext()`. + * Client returns an http client using the provided token. */ - acquireContext(): Context - } - interface Echo { + client(token: oauth2.Token): (any | undefined) /** - * ReleaseContext returns the `Context` instance back to the pool. - * You must call it after `AcquireContext()`. + * BuildAuthUrl returns a URL to the provider's consent page + * that asks for permissions for the required scopes explicitly. */ - releaseContext(c: Context): void - } - interface Echo { + buildAuthUrl(state: string, ...opts: oauth2.AuthCodeOption[]): string /** - * ServeHTTP implements `http.Handler` interface, which serves HTTP requests. + * FetchToken converts an authorization code to token. */ - serveHTTP(w: http.ResponseWriter, r: http.Request): void - } - interface Echo { + fetchToken(code: string, ...opts: oauth2.AuthCodeOption[]): (oauth2.Token | undefined) /** - * 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) - * } - * ``` + * FetchRawUserData requests and marshalizes into `result` the + * the OAuth user api response. */ - start(address: string): void + fetchRawUserData(token: oauth2.Token): string + /** + * FetchAuthUser is similar to FetchRawUserData, but normalizes and + * marshalizes the user api response into a standardized AuthUser struct. + */ + fetchAuthUser(token: oauth2.Token): (AuthUser | undefined) } } @@ -11736,36 +11769,6 @@ namespace daos { } } -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 | undefined) - } - 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 core is the backbone of PocketBase. * @@ -13675,6 +13678,36 @@ namespace cobra { } } +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 | undefined) + } + 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 io provides basic interfaces to I/O primitives. * Its primary job is to wrap existing implementations of such primitives, @@ -13868,6 +13901,14 @@ 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. + */ +namespace fs { +} + /** * Package context defines the Context type, which carries deadlines, * cancellation signals, and other request-scoped values across API boundaries @@ -13918,14 +13959,6 @@ namespace time { namespace context { } -/** - * 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. @@ -14062,39 +14095,110 @@ namespace net { */ setDeadline(t: time.Time): void /** - * SetReadDeadline sets the deadline for future Read calls - * and any currently-blocked Read call. - * A zero value for t means Read will not time out. + * SetReadDeadline sets the deadline for future Read calls + * and any currently-blocked Read call. + * A zero value for t means Read will not time out. + */ + setReadDeadline(t: time.Time): void + /** + * SetWriteDeadline sets the deadline for future Write calls + * and any currently-blocked Write call. + * Even if write times out, it may return n > 0, indicating that + * some of the data was successfully written. + * A zero value for t means Write will not time out. + */ + setWriteDeadline(t: time.Time): void + } + /** + * A Listener is a generic network listener for stream-oriented protocols. + * + * Multiple goroutines may invoke methods on a Listener simultaneously. + */ + interface Listener { + /** + * Accept waits for and returns the next connection to the listener. + */ + accept(): Conn + /** + * Close closes the listener. + * Any blocked Accept operations will be unblocked and return errors. + */ + close(): void + /** + * Addr returns the listener's network address. + */ + addr(): Addr + } +} + +/** + * 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 + * a server. + * + * Pipeline, to manage pipelined requests and responses + * in a client. + * + * 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. + * + * Conn, a convenient packaging of Reader, Writer, and Pipeline for use + * with a single network connection. + */ +namespace textproto { + /** + * A MIMEHeader represents a MIME-style header mapping + * keys to sets of values. + */ + interface MIMEHeader extends _TygojaDict{} + interface MIMEHeader { + /** + * Add adds the key, value pair to the header. + * It appends to any existing values associated with key. */ - setReadDeadline(t: time.Time): void + add(key: string): void + } + interface MIMEHeader { /** - * SetWriteDeadline sets the deadline for future Write calls - * and any currently-blocked Write call. - * Even if write times out, it may return n > 0, indicating that - * some of the data was successfully written. - * A zero value for t means Write will not time out. + * Set sets the header entries associated with key to + * the single element value. It replaces any existing + * values associated with key. */ - setWriteDeadline(t: time.Time): void + set(key: string): void } - /** - * A Listener is a generic network listener for stream-oriented protocols. - * - * Multiple goroutines may invoke methods on a Listener simultaneously. - */ - interface Listener { + interface MIMEHeader { /** - * Accept waits for and returns the next connection to the listener. + * Get gets the first value associated with the given key. + * 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. */ - accept(): Conn + get(key: string): string + } + interface MIMEHeader { /** - * Close closes the listener. - * Any blocked Accept operations will be unblocked and return errors. + * Values returns all values associated with the given key. + * 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. */ - close(): void + values(key: string): Array + } + interface MIMEHeader { /** - * Addr returns the listener's network address. + * Del deletes the values associated with key. */ - addr(): Addr + del(key: string): void } } @@ -14296,215 +14400,24 @@ namespace url { /** * Hostname returns u.Host, stripping any valid port number if present. * - * If the result is enclosed in square brackets, as literal IPv6 addresses are, - * the square brackets are removed from the result. - */ - hostname(): string - } - interface URL { - /** - * Port returns the port part of u.Host, without the leading colon. - * - * If u.Host doesn't contain a valid numeric port, Port returns an empty string. - */ - port(): string - } - interface URL { - marshalBinary(): string - } - interface URL { - unmarshalBinary(text: 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. - */ -namespace cobra { - interface PositionalArgs {(cmd: Command, args: Array): void } - // @ts-ignore - import flag = pflag - /** - * FParseErrWhitelist configures Flag parse errors to be ignored - */ - 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 { - /** - * DisableDefaultCmd prevents Cobra from creating a default 'completion' command - */ - disableDefaultCmd: boolean - /** - * DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag - * for shells that support completion descriptions - */ - disableNoDescFlag: boolean - /** - * DisableDescriptions turns off all completion descriptions for shells - * that support them - */ - disableDescriptions: boolean - /** - * HiddenDefaultCmd makes the default 'completion' command hidden - */ - hiddenDefaultCmd: boolean - } -} - -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 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 - * a server. - * - * Pipeline, to manage pipelined requests and responses - * in a client. - * - * 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. - * - * Conn, a convenient packaging of Reader, Writer, and Pipeline for use - * with a single network connection. - */ -namespace textproto { - /** - * A MIMEHeader represents a MIME-style header mapping - * keys to sets of values. - */ - interface MIMEHeader extends _TygojaDict{} - interface MIMEHeader { - /** - * Add adds the key, value pair to the header. - * It appends to any existing values associated with key. - */ - add(key: string): void - } - interface MIMEHeader { - /** - * Set sets the header entries associated with key to - * the single element value. It replaces any existing - * values associated with key. - */ - set(key: string): void - } - interface MIMEHeader { - /** - * Get gets the first value associated with the given key. - * 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. - */ - get(key: string): string - } - interface MIMEHeader { - /** - * Values returns all values associated with the given key. - * 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. + * If the result is enclosed in square brackets, as literal IPv6 addresses are, + * the square brackets are removed from the result. */ - values(key: string): Array + hostname(): string } - interface MIMEHeader { + interface URL { /** - * Del deletes the values associated with key. + * Port returns the port part of u.Host, without the leading colon. + * + * If u.Host doesn't contain a valid numeric port, Port returns an empty string. */ - del(key: string): void + port(): string + } + interface URL { + marshalBinary(): string + } + interface URL { + unmarshalBinary(text: string): void } } @@ -15091,40 +15004,155 @@ namespace oauth2 { } } -namespace subscriptions { +namespace store { /** - * Broker defines a struct for managing subscriptions clients. + * Store defines a concurrent safe in memory key-value data store. */ - interface Broker { + interface Store { } - interface Broker { + interface Store { /** - * Clients returns a shallow copy of all registered clients indexed - * with their connection id. + * Reset clears the store and replaces the store data with a + * shallow copy of the provided newData. */ - clients(): _TygojaDict + reset(newData: _TygojaDict): void } - interface Broker { + interface Store { /** - * ClientById finds a registered client by its id. + * 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. * - * Returns non-nil error when client with clientId is not registered. + * Remove does nothing if key doesn't exist in the store. */ - clientById(clientId: string): Client + remove(key: string): void } - interface Broker { + interface Store { /** - * Register adds a new client to the broker instance. + * Has checks if element with the specified key exist or not. */ - register(client: Client): void + has(key: string): boolean } - interface Broker { + interface Store { /** - * Unregister removes a single client by its id. + * Get returns a single element value from the store. * - * If client with clientId doesn't exist, this method does nothing. + * If key is not set, the zero T value is returned. */ - unregister(clientId: string): void + 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 + } +} + +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 _subfjzzW = mainHook + interface TaggedHook extends _subfjzzW { + } + 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 } } @@ -15344,14 +15372,6 @@ namespace sql { } } -namespace migrate { - interface Migration { - file: string - up: (db: dbx.Builder) => void - down: (db: dbx.Builder) => void - } -} - /** * Package echo implements high performance, minimalist Go web framework. * @@ -15788,95 +15808,14 @@ namespace echo { }[]): string } /** - * PathParams is collections of PathParam instances with various helper methods - */ - interface PathParams extends Array{} - interface PathParams { - /** - * Get returns path parameter value for given name or default value. - */ - get(name: string, defaultValue: string): string - } -} - -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 _subAEegs = mainHook - interface TaggedHook extends _subAEegs { - } - 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 { + * PathParams is collections of PathParam instances with various helper methods + */ + interface PathParams extends Array{} + interface PathParams { /** - * 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. + * Get returns path parameter value for given name or default value. */ - add(fn: Handler): string + get(name: string, defaultValue: string): string } } @@ -16172,16 +16111,16 @@ namespace models { */ validate(): void } - type _subYlPiq = BaseModel - interface Param extends _subYlPiq { + type _subRvBYL = BaseModel + interface Param extends _subRvBYL { key: string value: types.JsonRaw } interface Param { tableName(): string } - type _subKZirt = BaseModel - interface Request extends _subKZirt { + type _subxzbep = BaseModel + interface Request extends _subxzbep { url: string method: string status: number @@ -16385,6 +16324,43 @@ namespace daos { } } +namespace subscriptions { + /** + * Broker defines a struct for managing subscriptions clients. + */ + interface Broker { + } + interface Broker { + /** + * Clients returns a shallow copy of all registered clients indexed + * with their connection id. + */ + clients(): _TygojaDict + } + interface Broker { + /** + * ClientById finds a registered client by its id. + * + * Returns non-nil error when client with clientId is not registered. + */ + clientById(clientId: string): Client + } + interface Broker { + /** + * Register adds a new client to the broker instance. + */ + register(client: Client): void + } + interface Broker { + /** + * Unregister removes a single client by its id. + * + * If client with clientId doesn't exist, this method does nothing. + */ + unregister(clientId: string): void + } +} + /** * Package core is the backbone of PocketBase. * @@ -16407,12 +16383,12 @@ namespace core { httpContext: echo.Context error: Error } - type _subPbadV = BaseModelEvent - interface ModelEvent extends _subPbadV { + type _subxZZeQ = BaseModelEvent + interface ModelEvent extends _subxZZeQ { dao?: daos.Dao } - type _subBpFtS = BaseCollectionEvent - interface MailerRecordEvent extends _subBpFtS { + type _suboqHkC = BaseCollectionEvent + interface MailerRecordEvent extends _suboqHkC { mailClient: mailer.Mailer message?: mailer.Message record?: models.Record @@ -16452,50 +16428,50 @@ namespace core { oldSettings?: settings.Settings newSettings?: settings.Settings } - type _subDZsRE = BaseCollectionEvent - interface RecordsListEvent extends _subDZsRE { + type _subcrnuP = BaseCollectionEvent + interface RecordsListEvent extends _subcrnuP { httpContext: echo.Context records: Array<(models.Record | undefined)> result?: search.Result } - type _subGYMwg = BaseCollectionEvent - interface RecordViewEvent extends _subGYMwg { + type _subsaZzJ = BaseCollectionEvent + interface RecordViewEvent extends _subsaZzJ { httpContext: echo.Context record?: models.Record } - type _subURCnL = BaseCollectionEvent - interface RecordCreateEvent extends _subURCnL { + type _subCfZxC = BaseCollectionEvent + interface RecordCreateEvent extends _subCfZxC { httpContext: echo.Context record?: models.Record uploadedFiles: _TygojaDict } - type _subBHjdn = BaseCollectionEvent - interface RecordUpdateEvent extends _subBHjdn { + type _subPzMXI = BaseCollectionEvent + interface RecordUpdateEvent extends _subPzMXI { httpContext: echo.Context record?: models.Record uploadedFiles: _TygojaDict } - type _subGYYQQ = BaseCollectionEvent - interface RecordDeleteEvent extends _subGYYQQ { + type _subiqJfn = BaseCollectionEvent + interface RecordDeleteEvent extends _subiqJfn { httpContext: echo.Context record?: models.Record } - type _subnjblF = BaseCollectionEvent - interface RecordAuthEvent extends _subnjblF { + type _subTFRFu = BaseCollectionEvent + interface RecordAuthEvent extends _subTFRFu { httpContext: echo.Context record?: models.Record token: string meta: any } - type _subouBQJ = BaseCollectionEvent - interface RecordAuthWithPasswordEvent extends _subouBQJ { + type _subPCWzZ = BaseCollectionEvent + interface RecordAuthWithPasswordEvent extends _subPCWzZ { httpContext: echo.Context record?: models.Record identity: string password: string } - type _sublupxu = BaseCollectionEvent - interface RecordAuthWithOAuth2Event extends _sublupxu { + type _subQoqzZ = BaseCollectionEvent + interface RecordAuthWithOAuth2Event extends _subQoqzZ { httpContext: echo.Context providerName: string providerClient: auth.Provider @@ -16503,49 +16479,49 @@ namespace core { oAuth2User?: auth.AuthUser isNewRecord: boolean } - type _subjXjYS = BaseCollectionEvent - interface RecordAuthRefreshEvent extends _subjXjYS { + type _subHuWhN = BaseCollectionEvent + interface RecordAuthRefreshEvent extends _subHuWhN { httpContext: echo.Context record?: models.Record } - type _subLSMPA = BaseCollectionEvent - interface RecordRequestPasswordResetEvent extends _subLSMPA { + type _subaZZDw = BaseCollectionEvent + interface RecordRequestPasswordResetEvent extends _subaZZDw { httpContext: echo.Context record?: models.Record } - type _subdtUkj = BaseCollectionEvent - interface RecordConfirmPasswordResetEvent extends _subdtUkj { + type _subqVUNG = BaseCollectionEvent + interface RecordConfirmPasswordResetEvent extends _subqVUNG { httpContext: echo.Context record?: models.Record } - type _subYlQQd = BaseCollectionEvent - interface RecordRequestVerificationEvent extends _subYlQQd { + type _subGtJoD = BaseCollectionEvent + interface RecordRequestVerificationEvent extends _subGtJoD { httpContext: echo.Context record?: models.Record } - type _subfgrld = BaseCollectionEvent - interface RecordConfirmVerificationEvent extends _subfgrld { + type _subFzouK = BaseCollectionEvent + interface RecordConfirmVerificationEvent extends _subFzouK { httpContext: echo.Context record?: models.Record } - type _subtYyEq = BaseCollectionEvent - interface RecordRequestEmailChangeEvent extends _subtYyEq { + type _subPBSQf = BaseCollectionEvent + interface RecordRequestEmailChangeEvent extends _subPBSQf { httpContext: echo.Context record?: models.Record } - type _subaCcBa = BaseCollectionEvent - interface RecordConfirmEmailChangeEvent extends _subaCcBa { + type _subBKMqz = BaseCollectionEvent + interface RecordConfirmEmailChangeEvent extends _subBKMqz { httpContext: echo.Context record?: models.Record } - type _subkxbuI = BaseCollectionEvent - interface RecordListExternalAuthsEvent extends _subkxbuI { + type _subJqkxk = BaseCollectionEvent + interface RecordListExternalAuthsEvent extends _subJqkxk { httpContext: echo.Context record?: models.Record externalAuths: Array<(models.ExternalAuth | undefined)> } - type _subsjxpT = BaseCollectionEvent - interface RecordUnlinkExternalAuthEvent extends _subsjxpT { + type _subbBvLx = BaseCollectionEvent + interface RecordUnlinkExternalAuthEvent extends _subbBvLx { httpContext: echo.Context record?: models.Record externalAuth?: models.ExternalAuth @@ -16599,33 +16575,33 @@ namespace core { collections: Array<(models.Collection | undefined)> result?: search.Result } - type _subWBzXz = BaseCollectionEvent - interface CollectionViewEvent extends _subWBzXz { + type _subBKXLB = BaseCollectionEvent + interface CollectionViewEvent extends _subBKXLB { httpContext: echo.Context } - type _subrqXjQ = BaseCollectionEvent - interface CollectionCreateEvent extends _subrqXjQ { + type _suboDvuL = BaseCollectionEvent + interface CollectionCreateEvent extends _suboDvuL { httpContext: echo.Context } - type _subjUmth = BaseCollectionEvent - interface CollectionUpdateEvent extends _subjUmth { + type _subAhKcU = BaseCollectionEvent + interface CollectionUpdateEvent extends _subAhKcU { httpContext: echo.Context } - type _subetDWV = BaseCollectionEvent - interface CollectionDeleteEvent extends _subetDWV { + type _subQvQLT = BaseCollectionEvent + interface CollectionDeleteEvent extends _subQvQLT { httpContext: echo.Context } interface CollectionsImportEvent { httpContext: echo.Context collections: Array<(models.Collection | undefined)> } - type _subvyXDY = BaseModelEvent - interface FileTokenEvent extends _subvyXDY { + type _subJMcIe = BaseModelEvent + interface FileTokenEvent extends _subJMcIe { httpContext: echo.Context token: string } - type _subWrlSL = BaseCollectionEvent - interface FileDownloadEvent extends _subWrlSL { + type _subrUNlU = BaseCollectionEvent + interface FileDownloadEvent extends _subrUNlU { httpContext: echo.Context record?: models.Record fileField?: schema.SchemaField @@ -16635,82 +16611,60 @@ namespace core { } /** - * Package url parses URLs and implements query escaping. + * 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 url { +namespace cobra { + interface PositionalArgs {(cmd: Command, args: Array): void } + // @ts-ignore + import flag = pflag /** - * 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. + * FParseErrWhitelist configures Flag parse errors to be ignored */ - 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 types implements some commonly used db serializable types - * like datetime, json, etc. - */ -namespace types { + interface FParseErrWhitelist extends _TygojaAny{} /** - * JsonRaw defines a json value type that is safe for db read/write. + * Group Structure to manage groups for commands */ - interface JsonRaw extends String{} - interface JsonRaw { - /** - * String returns the current JsonRaw instance as a json encoded string. - */ - string(): string + interface Group { + id: string + title: string } - interface JsonRaw { + /** + * 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 { /** - * MarshalJSON implements the [json.Marshaler] interface. + * DisableDefaultCmd prevents Cobra from creating a default 'completion' command */ - marshalJSON(): string - } - interface JsonRaw { + disableDefaultCmd: boolean /** - * UnmarshalJSON implements the [json.Unmarshaler] interface. + * DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag + * for shells that support completion descriptions */ - unmarshalJSON(b: string): void - } - interface JsonRaw { + disableNoDescFlag: boolean /** - * Value implements the [driver.Valuer] interface. + * DisableDescriptions turns off all completion descriptions for shells + * that support them */ - value(): any - } - interface JsonRaw { + disableDescriptions: boolean /** - * Scan implements [sql.Scanner] interface to scan the provided value - * into the current JsonRaw instance. + * HiddenDefaultCmd makes the default 'completion' command hidden */ - scan(value: { - }): void + hiddenDefaultCmd: boolean } } -namespace store { +namespace migrate { + interface Migration { + file: string + up: (db: dbx.Builder) => void + down: (db: dbx.Builder) => void + } } /** @@ -16723,8 +16677,8 @@ namespace bufio { * ReadWriter stores pointers to a Reader and a Writer. * It implements io.ReadWriter. */ - type _subupaCP = Reader&Writer - interface ReadWriter extends _subupaCP { + type _subDfYEM = Reader&Writer + interface ReadWriter extends _subDfYEM { } } @@ -16780,137 +16734,77 @@ namespace bufio { * 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 cgo resolver - * ``` - * - * 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 Plan 9, the resolver always accesses /net/cs and /net/dns. - * - * On Windows, the resolver always uses 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 { - 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") - } -} - -namespace subscriptions { - /** - * Message defines a client's channel data. - */ - interface Message { - name: string - data: string - } - /** - * Client is an interface for a generic subscription client. - */ - interface Client { - /** - * Id Returns the unique id of the client. - */ - id(): string - /** - * Channel returns the client's communication channel. - */ - channel(): undefined - /** - * Subscriptions returns all subscriptions to which the client has subscribed to. - */ - subscriptions(): _TygojaDict - /** - * Subscribe subscribes the client to the provided subscriptions list. - */ - subscribe(...subs: string[]): void - /** - * Unsubscribe unsubscribes the client from the provided subscriptions list. - */ - unsubscribe(...subs: string[]): void - /** - * HasSubscription checks if the client is subscribed to `sub`. - */ - hasSubscription(sub: string): boolean - /** - * Set stores any value to the client's context. - */ - set(key: string, value: any): void - /** - * Unset removes a single value from the client's context. - */ - unset(key: string): void - /** - * Get retrieves the key value from the client's context. - */ - get(key: string): any - /** - * Discard marks the client as "discarded", meaning that it - * shouldn't be used anymore for sending new messages. - * - * It is safe to call Discard() multiple times. - */ - discard(): void - /** - * IsDiscarded indicates whether the client has been "discarded" - * and should no longer be used. - */ - isDiscarded(): boolean - /** - * Send sends the specified message to the client's channel (if not discarded). - */ - send(m: Message): void - } -} - -namespace hook { - /** - * Handler defines a hook handler function. - */ - interface Handler {(e: T): void } + * 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 cgo resolver + * ``` + * + * 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 Plan 9, the resolver always accesses /net/cs and /net/dns. + * + * On Windows, the resolver always uses C library functions, such as GetAddrInfo and DnsQuery. + */ +namespace net { /** - * wrapped local Hook embedded struct to limit the public API surface. + * 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. */ - type _subuvwCh = Hook - interface mainHook extends _subuvwCh { + interface Addr { + 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") } } -namespace search { +/** + * Package url parses URLs and implements query escaping. + */ +namespace url { /** - * Result defines the returned search result structure. + * 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 Result { - page: number - perPage: number - totalItems: number - totalPages: number - items: any + 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 } } @@ -17091,23 +16985,6 @@ namespace http { import urlpkg = url } -namespace mailer { - /** - * Message defines a generic email message struct. - */ - interface Message { - from: mail.Address - to: Array - bcc: Array - cc: Array - subject: string - html: string - text: string - headers: _TygojaDict - attachments: _TygojaDict - } -} - /** * Package echo implements high performance, minimalist Go web framework. * @@ -17222,6 +17099,95 @@ namespace echo { } } +/** + * Package types implements some commonly used db serializable types + * like datetime, json, etc. + */ +namespace types { + /** + * JsonRaw defines a json value type that is safe for db read/write. + */ + interface JsonRaw extends String{} + interface JsonRaw { + /** + * String returns the current JsonRaw instance as a json encoded string. + */ + string(): string + } + interface JsonRaw { + /** + * MarshalJSON implements the [json.Marshaler] interface. + */ + marshalJSON(): string + } + interface JsonRaw { + /** + * UnmarshalJSON implements the [json.Unmarshaler] interface. + */ + unmarshalJSON(b: string): void + } + interface JsonRaw { + /** + * Value implements the [driver.Valuer] interface. + */ + value(): any + } + interface JsonRaw { + /** + * Scan implements [sql.Scanner] interface to scan the provided value + * into the current JsonRaw instance. + */ + scan(value: { + }): void + } +} + +namespace store { +} + +namespace hook { + /** + * Handler defines a hook handler function. + */ + interface Handler {(e: T): void } + /** + * wrapped local Hook embedded struct to limit the public API surface. + */ + type _subtgUaQ = Hook + interface mainHook extends _subtgUaQ { + } +} + +namespace mailer { + /** + * Message defines a generic email message struct. + */ + interface Message { + from: mail.Address + to: Array + bcc: Array + cc: Array + subject: string + html: string + text: string + headers: _TygojaDict + attachments: _TygojaDict + } +} + +namespace search { + /** + * Result defines the returned search result structure. + */ + interface Result { + page: number + perPage: number + totalItems: number + totalPages: number + items: any + } +} + namespace settings { // @ts-ignore import validation = ozzo_validation @@ -17245,6 +17211,73 @@ namespace settings { } } +namespace subscriptions { + /** + * Message defines a client's channel data. + */ + interface Message { + name: string + data: string + } + /** + * Client is an interface for a generic subscription client. + */ + interface Client { + /** + * Id Returns the unique id of the client. + */ + id(): string + /** + * Channel returns the client's communication channel. + */ + channel(): undefined + /** + * Subscriptions returns all subscriptions to which the client has subscribed to. + */ + subscriptions(): _TygojaDict + /** + * Subscribe subscribes the client to the provided subscriptions list. + */ + subscribe(...subs: string[]): void + /** + * Unsubscribe unsubscribes the client from the provided subscriptions list. + */ + unsubscribe(...subs: string[]): void + /** + * HasSubscription checks if the client is subscribed to `sub`. + */ + hasSubscription(sub: string): boolean + /** + * Set stores any value to the client's context. + */ + set(key: string, value: any): void + /** + * Unset removes a single value from the client's context. + */ + unset(key: string): void + /** + * Get retrieves the key value from the client's context. + */ + get(key: string): any + /** + * Discard marks the client as "discarded", meaning that it + * shouldn't be used anymore for sending new messages. + * + * It is safe to call Discard() multiple times. + */ + discard(): void + /** + * IsDiscarded indicates whether the client has been "discarded" + * and should no longer be used. + */ + isDiscarded(): boolean + /** + * Send sends the specified message to the client's channel (if not discarded). + */ + send(m: Message): void + } +} + /** * Package core is the backbone of PocketBase. * @@ -17527,12 +17560,6 @@ namespace bufio { } } -namespace subscriptions { -} - -namespace search { -} - /** * Package mail implements parsing of mail messages. * @@ -17567,3 +17594,9 @@ namespace mail { string(): string } } + +namespace search { +} + +namespace subscriptions { +} diff --git a/ui/src/components/records/fields/JsonField.svelte b/ui/src/components/records/fields/JsonField.svelte index 88acfb9b0..9dbf4c09a 100644 --- a/ui/src/components/records/fields/JsonField.svelte +++ b/ui/src/components/records/fields/JsonField.svelte @@ -64,7 +64,7 @@ value={serialized} on:change={(e) => { serialized = e.detail; - value = serialized.trim(); // trim the submitted value + value = serialized.trim(); }} /> {:else}